Skip to content

fix(knowledge): lock the shared worktree against concurrent commands - #2068

Merged
jeff-r2026 merged 2 commits into
Tencent:mainfrom
TINGyu123644:fix/knowledge-worktree-lock
Nov 26, 2026
Merged

jeff-r2026 merged 2 commits into
Tencent:mainfrom
TINGyu123644:fix/knowledge-worktree-lock

Conversation

@TINGyu123644

@TINGyu123644 TINGyu123644 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2067

What changed

withKnowledgeWorktree() now holds an exclusive lock for the entire life of the shared knowledge checkout: stale cleanup, fetch, worktree add, the caller's callback, and the final removal. A contender is refused with CheckoutRefusedError before it makes any git call, so a running command keeps its checkout and its uncommitted work.

Why a dedicated lock

  • The lock lives beside wt, not inside it: worktree remove --force would delete a lock held inside while its owner is still holding it.
  • It uses its own filename, not .sync-lock: push and promotion-publish already hold .sync-lock when they call into this function, so reusing it would deadlock against themselves.
  • remove, manifest-edit and promotion-publish hold no lock today, so they now contend on this one and are serialized with push as well.
  • The new lock file and its reclaim artifacts are skipped and recognized during migration, so a stale lock is never copied into the partition and mistaken for a live one.

This follows the existing pattern in branch-worktree.ts (removeOldCheckouts, #1443), where a checkout is never removed while another command holds its lock.

Tests

$ vitest run src/__tests__/knowledge-worktree-lock.test.ts
✓ refuses before touching the checkout when another command holds the lock
✓ holds the lock across the callback and releases it after cleanup
✓ releases the lock even when the callback throws
3 passed

These run real git worktree operations (about 3s each), not stubs: each case builds a repository, takes the lock through withKnowledgeWorktree, and asserts what happened to the checkout.

tsc --noEmit over the repository reports 0 errors.

On the real-CLI record

I could not produce an end-to-end verify:world run for this one, and it is worth being precise about why rather than implying it was done:

  • withKnowledgeWorktree is reached from remove.ts:60, manifest-edit.ts:51, push.ts:1365 and promotion-publish.ts:79 — all of them self-mode branches. A workspace-scope project never enters this function, so teamai remove there runs a different path and exercises none of this code.
  • The project's verify:world harness refuses to run on Windows: scripts/verify/world.ts throws "A world needs a POSIX shell; Windows is not supported."
  • Building a self-mode world by hand on Windows also fails at init: teamai init . reads the business repo's origin, and git has already applied the url.<file>.insteadOf rewrite that makes a fake remote reachable, so the URL comes back as file://… and init rejects it as an invalid repo URL.

So the honest state is: the lock's behaviour is proven by the three real-git tests above, and the end-to-end CLI run needs a POSIX host. If a reviewer has one, the pair to run is two concurrent teamai remove calls in a self-mode world — one should report the knowledge checkout is busy instead of deleting the other's checkout.

Two earlier assertions in this PR description are superseded and were wrong: the pre-fix harness was extracted-and-stubbed, which cannot see module specifiers (it missed './update.js', since corrected to '../update.js'), and it could not have observed real lock contention either.

Every knowledge-producing command - push, remove, manifest edits and promotion
- calls withKnowledgeWorktree on the SAME fixed path, and each one removes that
worktree with --force both on entry to clear an interrupted run and in `finally`.
Nothing serialized them. If two commands overlapped, the later one's entry
cleanup deleted the checkout the earlier one was still committing in: changes
made by A were pushed in B's PR, or A's own changes silently vanished when B's
`finally` ran. The active tree was never touched, which made the loss look like
a merge failure rather than a race.

Branch worktrees already take a lock beside the checkout for this exact reason
(Tencent#1443). The knowledge checkout had no lock at all.

- Add KNOWLEDGE_LOCK_FILENAME and take an exclusive lock beside `wt` for the
  whole lifecycle: stale cleanup, fetch, worktree add, the callback, and the
  final removal. A contender is refused with CheckoutRefusedError before it can
  mutate anything, matching how a busy checkout is handled elsewhere.
- Put the lock BESIDE the worktree, never inside it: `worktree remove --force`
  would delete a lock held inside while its owner still holds it. Use a
  dedicated name instead of `.sync-lock`, because push and promotion already
  hold `.sync-lock` when they call here and would deadlock against themselves.
- Skip and recognize the new lock (and its reclaim artifacts) during migration,
  so a stale lock is never copied into the partition and mistaken for a live
  one.
- Add knowledge-worktree-lock.test.ts covering refusal without mutation, lock
  ownership across the callback, and release when the callback throws.

Signed-off-by: TINGyu123644 <[email protected]>
@TINGyu123644

Copy link
Copy Markdown
Contributor Author

Quick review orientation (TL;DR):

The key design decision is why this is a new .knowledge-lock and not the existing .sync-lock: push.ts and promotion-publish.ts already hold .sync-lock when they call withKnowledgeWorktree(), so reusing it would deadlock against themselves. remove.ts / manifest-edit.ts held nothing, so all four now serialize on this one lock.

Verification extracted the real function body from both the pre-fix commit and this branch and replayed the same interleaving: pre-fix, B deleted A's in-use checkout; fixed, B is refused and A's checkout is untouched. CI is green.

Happy to split the migration changes into a separate commit if that helps review.

reports-branch.ts lives in src/utils/, so `./update.js` resolved to
src/utils/update.js, which does not exist - acquireLock and releaseLock are
exported from src/update.ts. A type check reports it as

    error TS2307: Cannot find module './update.js'

and at runtime the module would fail to resolve. Use the same `../` level the
file already uses for `../types.js`.

Verified with `tsc --noEmit` against the upstream baseline: this file now
reports no error the pre-change tree does not also report.

Signed-off-by: TINGyu123644 <[email protected]>
@TINGyu123644

Copy link
Copy Markdown
Contributor Author

Follow-up commit 60e0651 fixes a real mistake in the first commit: reports-branch.ts is in src/utils/, so from './update.js' resolved to the non-existent src/utils/update.js. acquireLock/releaseLock live in src/update.ts, so the import is now ../update.js (the same level this file already uses for ../types.js).

Caught by a type check, not by the harness I described earlier — the harness extracts the function body and stubs its dependencies, so it never resolves the module specifier. Worth stating plainly: the string './update.js' would also have failed at runtime with ERR_MODULE_NOT_FOUND the first time a knowledge command loaded this module, which is exactly the kind of thing a stub-based verification cannot see.

How it was checked:

# before (4e8b0da)
src/utils/reports-branch.ts(32,...): error TS2307: Cannot find module './update.js'

# after (60e0651)
(no such error)

Method: ran tsc --noEmit on the working tree, then swapped in the upstream versions of reports-branch.ts / types.ts / migrate.ts, ran it again, and diffed the two error sets per file (line numbers stripped, so the added lines do not mask the comparison). Before the fix this file had one error the baseline did not; after it, zero new errors in all three files.

The environment still has no installed dependencies, so the same run reports ~26k Cannot find module (vitest, simple-git, @teamai/*) and Cannot find name 'node:fs' errors. Those are present unchanged on the upstream baseline. The test file knowledge-worktree-lock.test.ts has only the same error classes the existing import-from-mr.test.ts already has.

@jeff-r2026 jeff-r2026 self-assigned this Nov 25, 2026
@github-actions

Copy link
Copy Markdown
  • [P1 blocking] Missing required real-CLI verification record — src/utils/reports-branch.ts:329 changes runtime behavior, but the PR’s verification uses an extracted function with stubbed dependencies, not the real CLI in a verify world. This violates the Code Review Rules requirement for an “end-to-end / real-CLI verification record, not only unit tests or type checks.” Run one representative real-CLI case in a world and document the command and result in the PR description.

No other confident findings in the current diff. Nothing was run, built, or installed from the PR.

@TINGyu123644

Copy link
Copy Markdown
Contributor Author

On the real-CLI record: I could not produce one for this change, and I would rather say so precisely than dress up a substitute.

withKnowledgeWorktree is reached from remove.ts:60, manifest-edit.ts:51, push.ts:1365 and promotion-publish.ts:79 — all self-mode branches. A workspace-scope project never enters the function, so teamai remove there runs a different path and touches none of this code (I verified that: a remove with the lock held ran to completion, because it never asked for the lock). Building a self-mode world by hand on Windows then fails at teamai init .: it reads the business repo's origin, git has already applied the url.<file>.insteadOf rewrite that makes the fake remote reachable, and the URL comes back as file://…, which init rejects. And verify:world refuses Windows outright (scripts/verify/world.ts: "A world needs a POSIX shell; Windows is not supported").

What I do have is behavioural, not stubbed: src/__tests__/knowledge-worktree-lock.test.ts builds a real repository and runs real git worktree operations (about 3s per case) through withKnowledgeWorktree — refusal before any git call, the lock held across the callback, and release when the callback throws. 3 passed, and tsc --noEmit reports 0 errors.

If you have a POSIX host, the representative case is two concurrent teamai remove calls in a self-mode world: one should report the knowledge checkout is busy and leave the other's checkout intact. I have documented this, and the two limits above, in the PR description under "On the real-CLI record" rather than claiming a world run I did not do.

@TINGyu123644

Copy link
Copy Markdown
Contributor Author

I tried to produce the verify-world record on Linux instead of stopping at "Windows is not supported". Result: the obstacle is not the host platform, and I want to correct what I said earlier.

What I got working:

Where this change still has no world record:

withKnowledgeWorktree is only reached from self-mode branches (remove.ts:60, manifest-edit.ts:51, push.ts:1365, promotion-publish.ts:79). A world's project is a plain workspace project with no origin, so teamai init . --self stops at "Could not read the business repo origin remote".

I added an origin and retried. Then the real reason showed up: the world's ~/.gitconfig maps the team URL to a local bare repo —

[url "file:///tmp/teamai-verify/<run>/team.git"]
	insteadOf = https://teamai.test/team/repo.git

— so any origin a self-mode init can read comes back as file://…, which init rejects as an invalid repo URL. That is the same wall I hit on Windows, and it is a harness/self-mode interaction, not a platform limitation. Building the config by hand (kind: self, businessRepoRoot, a minimal teamai.yaml in the project) did not get status past "Team config (teamai.yaml) not found" either, and I stopped rather than keep patching a world into a shape the harness does not model.

So the honest state of this PR is unchanged from what I wrote before, with a sharper reason:

  • What is proven: three vitest cases that build a real repository and run real git worktree operations through withKnowledgeWorktree — refusal before any git call, the lock held across the callback, release on throw. tsc --noEmit 0 errors.
  • What is not: an end-to-end CLI run, because the only entry point is self mode and neither a world nor a Windows host can construct one.

If the review requires that record, this PR cannot supply it here. I would rather say that plainly than leave a claim I cannot back. The representative case remains available to anyone with a POSIX host and a self-mode repo: two concurrent teamai remove calls, one should report the knowledge checkout is busy.

@jeff-r2026

Copy link
Copy Markdown
Collaborator

The real-CLI record the thread was waiting for — produced on a POSIX host (Linux), with the packed build, in a real self-mode project.

Setup: a team repo (teamai.yaml + .teamai/skills/demo/) cloned as the business repo from ssh://root@localhost/<path>/origin.git — a real git remote whose URL parses as a valid generic-Git repo URL, so teamai init . accepts it (this sidesteps the insteadOf→file:// wall documented above without touching the world harness). Isolated HOME. teamai init . --agent claude succeeds; then two concurrent teamai remove skills demo --force, the second starting 0.7s after the first.

main (af6832fe build, no lock):

r1: ⚠ Not found (skipping): demo / ✖ No matching resources found to remove — exit 1
r2: ✔ Removed 1 skills from 1 location(s) / branch pushed — exit 0

r1's search is wrong: r2 entered the shared knowledge checkout concurrently and its stale-cleanup worktree remove --force took r1's checkout out mid-run, so r1 searched nothing and reported "not found". One command clobbered the other's checkout mid-write, and the user sees a wrong result with no hint of the race.

this PR (main + #2068, same setup):

r1: ✔ Removed 1 skills from 1 location(s) / branch pushed — exit 0
r2: ✖ Remove failed: <repo>/.teamai/knowledge-wt is being used by another teamai command (<repo>/.teamai/.knowledge-lock is held). teamai keeps one shared knowledge checkout, so it left the other command untouched. Run this again when the other command finishes. — exit 1

Also verified on latest main + this PR (stacked with #1954/#2076): typecheck, build, lint, unit 202 passed, e2e 4 passed. The PR is mergeable from my side.

@jeff-r2026 jeff-r2026 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real-CLI record added in the comment above; verified on latest main stacked with #1954/#2076 (typecheck/build/lint/unit/e2e). Squash-merging.

@jeff-r2026
jeff-r2026 merged commit 4aa0cc1 into Tencent:main Nov 26, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Concurrent knowledge commands delete each other’s worktree mid-write

2 participants