Skip to content

feat(data-layout): route new project installs to ~/.teamai/projects/<slug>/ + .sync-lock + status (#374 P1-2B) - #406

Merged
jeff-r2026 merged 4 commits into
mainfrom
worktree-issue-374-p1-2b-partition-flip
Sep 4, 2026
Merged

jeff-r2026 merged 4 commits into
mainfrom
worktree-issue-374-p1-2b-partition-flip

Conversation

@jeff-r2026

Copy link
Copy Markdown
Collaborator

Context

Fourth step of P1 (per-project data partition, issue #374), after P1-1 (#397)
and P1-2A (#402). This is the flip: a NEW non-self (git/http) project install now
keeps all its machine data out of the business workspace, under the per-project
partition ~/.teamai/projects/<slug>/ (keyed on the shared projectAnchor, so every
worktree of a repo shares one partition). Old installs keep working unchanged via a
double-read fallback; self mode stays legacy (its slimming is P2).

What this PR does

Detection (config.ts) — detectProjectConfig resolves the partition from the
git anchor and does a partition-first double-read (partition → legacy
<workspaceRoot>/.teamai), attaching a runtime dataHome = the directory the
config was actually found in (the same "anchor to where it lives" rule P0 applies
to projectRoot). A single shared readConfigFrom helper backs both the fast path
and the anchor path, and loadLocalConfigForScope('project') delegates to it so
config location never drifts between "detect the active project" and "load a named
project's config". New resolveProjectDataHome(projectRoot) (partition in a git
repo, else legacy) used by init.

init (init.ts) — non-self git/http project scope resolves teamaiHome to the
partition, attaches dataHome to the saved config, and both the re-init existence
check and the team-repo clone target follow it. A fresh install writes config.yaml,
state.json, env, search-index and the team-repo clone into the partition — zero
teamai files in the workspace
.

.sync-lock (pull.ts / push.ts) — the shared team clone is now reachable
from every worktree, so concurrent git pull/git push could corrupt it. Guard
the shared-clone mutation with the P0 atomic lock at <dataHome>/.sync-lock: pull
skips the fetch on contention (idempotent), push errors out with exit 1 (never
silently drops changes).

status (status.ts) — prints the resolved data home (data: line).

Deferred to P1-2C: managed-mcp.json and local-agent/resources. Both are
resolved inside the local-agent subsystem from (scope, projectRoot) with no
LocalConfig; converging only the reconcile side would desync the partition vs
legacy path between readers, so they need a shared dataHome resolver done as a unit.

Test plan (all executed green)

  • npx tsc --noEmit — clean
  • npx vitest run — 189 files / 2627 tests pass (init.test config mock
    updated; the legacy-layout scope-isolation / scope-inheritance /
    source-project-scope e2e suites still green ⇒ old-install double-read
    compat is regression-verified)
  • Real CLI e2e (github provider): teamai init resolves the clone path to
    ~/.teamai/projects/<slug>/team-repo and leaves <proj>/.teamai absent
    (zero residue); 16-hex slug.
  • Real CLI e2e (local no-auth fixture, partitioned install): status shows
    the partition; pull writes search-index.json + state.json into the
    partition and deploys the skill to <proj>/.claude/skills; a worktree and
    a subdirectory both resolve to the SAME partition; <proj>/.teamai stays
    absent.
  • Concurrent pull (main + worktree): one fetches, the other skips with
    "sync in progress elsewhere"; both exit 0; git fsck --connectivity-only on
    the shared clone passes (no corruption).

Refs #374.

…slug>/ + .sync-lock + status (#374 P1-2B)

Flip the partition on: a NEW non-self (git/http) project install now keeps ALL
its machine data out of the business workspace, under the per-project partition
`~/.teamai/projects/<slug>/` (keyed on the shared projectAnchor). Old installs
keep working unchanged via a double-read fallback; self mode stays legacy (its
slimming is P2).

Detection (config.ts):
- `detectProjectConfig` resolves the partition from the git anchor and does a
  partition-first double-read (partition → legacy `<workspaceRoot>/.teamai`),
  attaching a runtime `dataHome` = the directory the config was actually found in
  (same "anchor to where it lives" rule P0 applies to projectRoot). One shared
  `readConfigFrom` helper backs both the fast path and the anchor path, and
  `loadLocalConfigForScope('project')` delegates to it so config location never
  drifts between "detect active project" and "load named project".
- New `resolveProjectDataHome(projectRoot)` (partition when in a git repo, else
  legacy) used by init.

init (init.ts): non-self git/http project scope resolves `teamaiHome` to the
partition, attaches `dataHome` to the saved config, and the re-init existence
check + team-repo clone target follow it. So a fresh install writes config.yaml,
state.json, env, search-index and the team-repo clone into the partition, leaving
zero teamai files in the workspace. saveLocalConfigForScope writes to
`getDataHome(config)/config.yaml`.

.sync-lock (pull.ts / push.ts): the shared team clone is now reachable from every
worktree of a repo, so concurrent `git pull`/`git push` could corrupt it. Guard
the shared-clone mutation with the P0 atomic lock at `<dataHome>/.sync-lock`:
pull skips the fetch on contention (idempotent), push errors out with exit 1
(never silently drop changes).

status.ts: prints the resolved data home (`data:` line) so users can see where a
project's machine data lives.

Deferred to P1-2C: managed-mcp.json and local-agent/resources. Both are resolved
inside the local-agent subsystem from (scope, projectRoot) with no LocalConfig;
converging only the reconcile side would desync the partition vs legacy path
between readers, so they need a shared dataHome resolver done as a unit.

Test plan (all green):
- npx tsc --noEmit — clean
- npx vitest run — 189 files / 2627 tests pass (init.test config mock updated;
  legacy-layout scope-isolation/inheritance e2e suites still green = old-install
  double-read compat regression-verified)
- real CLI e2e (github provider): `teamai init` resolves the clone path to
  `~/.teamai/projects/<slug>/team-repo` and leaves <proj>/.teamai absent
  (zero residue); 16-hex slug.
- real CLI e2e (local no-auth fixture, partitioned install): status shows the
  partition; pull writes search-index.json + state.json into the partition and
  deploys the skill to <proj>/.claude/skills; worktree AND a subdirectory both
  resolve to the SAME partition; <proj>/.teamai stays absent.
- concurrent pull (main + worktree): one fetches, the other skips with
  "sync in progress elsewhere"; both exit 0; `git fsck --connectivity-only` on
  the shared clone passes (no corruption).

Refs #374.
Comment thread src/config.ts Outdated

// 1. Fast path: legacy layout at <dir>/.teamai (also runs the self-heal
// bootstrap for a freshly-cloned single-repo project).
const direct = await readConfigFrom(path.join(dir, '.teamai'), dir, dir);

@jeff-r2026 jeff-r2026 Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[P1] 这里会让同一项目因 cwd 不同而加载两套配置。仓库根目录存在旧 .teamai/config.yaml 时,这个 fast path 会在解析 partition 之前直接返回旧配置;但从 src/ 等子目录运行时 direct miss,随后会命中新 partition。与此同时 init 的 re-init 检查和写入只针对 partition,所以旧安装重新执行 init 后会同时留下两套配置,导致根目录和子目录的 pull/push 操作不同的 team repo、state 和 env。

本地可稳定复现:同时写入 legacy 和 partition 配置后,detectProjectConfig(repoRoot) 返回 legacy,而 detectProjectConfig(repoRoot/src) 返回 partition。建议先 resolve anchors;非 self 模式严格 partition-first,再 fallback workspace legacy,并让 re-init 显式处理已有 legacy 配置。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

确认成立,已修复(e55a58f)。根因是 fast-path 先读 <dir>/.teamai 再 resolve anchors,导致根目录命中 legacy、子目录命中 partition。改为先 resolve anchors,再按 cwd 无关的严格顺序:partition(新装/已迁移)→ workspace-root legacy(未迁移,带 self-heal);<dir>/.teamai 仅作非-git 目录的兜底。同时 init 现复用已有装的 dataHome(existingLocalConfig?.dataHome ?? resolveProjectDataHome(...)),老装重跑 init 继续写 legacy、不再另造一份 partition 配置(真正迁移留 P1-3)。真实 CLI 复现:legacy + partition 同时存在时,从根目录和子目录跑 status 现在都返回同一分区。

Comment thread src/pull.ts
// clone's current state (the winner's pull already advanced it).
const syncLock = path.join(getDataHome(localConfig), SYNC_LOCK_FILENAME);
let result: string;
const locked = await acquireLock(syncLock);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[P1] 这个锁没有真正串行化共享 clone。acquireLock 返回 false 时这里只跳过 fetch,随后仍无条件执行 flushPendingLearnings;该函数会向同一个 clone 写文件并执行 git add/commit/push。即使成功拿锁,也在 flush 以及后续读取 clone 前就释放了锁,因此另一个 push 可以同时 reset/checkout 这棵工作树。

本地可稳定复现:先持有 <dataHome>/.sync-lock,再执行带 pending learning 的 pull。CLI 输出 sync in progress elsewhere — skipped fetch,但 pending 文件仍被删除,并生成、推送了 Contribute session knowledge commit。建议竞争失败时跳过整个依赖共享 clone 的 scope(或等待锁),并把 flush 及需要一致快照的 clone 操作全部放在同一锁周期内。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

确认成立,已修复(e55a58f)。之前锁只包住 pullRepo,flushPendingLearnings(写文件 + git add/commit/push 同一 clone)在锁外,且竞争跳过时仍执行 —— 正如你复现的:pending 文件被删、还推了 "Contribute session knowledge" commit。改为整段共享-clone 变更(fetch + flush + rev 读取)都在同一锁周期内;竞争拿不到锁时跳过整段并返回 clone 当前 HEAD,让 deploy 从现状继续。真实 CLI 复现:持有 <dataHome>/.sync-lock(活 PID)后带 pending learning 跑 pull → 输出 "sync in progress elsewhere — skipped",pending 文件保留、clone HEAD 未变(无越权 commit/push)。

…+ full-section sync lock

Two confirmed [P1] issues from jeff-r2026:

1. [split config by cwd] detectProjectConfig used a cwd-first fast path: it read
   `<dir>/.teamai` before resolving anchors, so a repo carrying BOTH a legacy
   `.teamai/config.yaml` and a partition config resolved to legacy from the root
   but to the partition from a subdirectory — root and subdir pull/push would then
   act on different team repos/state/env. Fix: resolve git anchors FIRST, then a
   strict, cwd-independent order (partition → workspace-root legacy); the bare
   `<dir>/.teamai` path is only the non-git fallback. And init now reuses an
   existing install's dataHome (`existingLocalConfig?.dataHome ?? resolveProjectDataHome`)
   so re-running init on a legacy install keeps writing legacy instead of forking a
   second partition config (real migration is P1-3).

2. [lock too narrow] The pull sync-lock only wrapped `pullRepo`; the lock was
   released before `flushPendingLearnings`, which writes + `git add/commit/push`es
   the same shared clone — and on contention the code skipped only the fetch but
   still ran the flush. So a pull that lost the lock could still delete pending
   files and push a "Contribute session knowledge" commit while another push was
   resetting the tree. Fix: hold the lock across the ENTIRE clone-mutating section
   (fetch + flush + rev read); on contention skip the whole section and return the
   clone's current HEAD.

Test plan (all green):
- npx tsc --noEmit — clean
- npx vitest run — 189 files / 2627 tests pass
- real CLI repro #1: with BOTH legacy and partition config present,
  `status` from the repo root AND from a subdirectory now both report the SAME
  partition data home.
- real CLI repro #2: hold `<dataHome>/.sync-lock` (live PID), then `pull` with a
  pending learning present → "sync in progress elsewhere — skipped"; the pending
  file is NOT deleted and the clone HEAD is unchanged (no rogue commit/push).

Refs #374 (P1-2B).
Comment thread src/pull.ts Outdated
} catch {
heldVersion = null;
}
return { label: 'sync in progress elsewhere — skipped', version: heldVersion, reportingOnly: false };

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[P1] 锁竞争路径仍会读取并部署正在被修改的共享 clone。这里返回持锁期间的当前 HEAD 后,pullForScope 会继续 reload team config、扫描资源并执行部署;而持锁的 push 此时可能正停在 generated push branch,或正在 reset/checkout 工作树。这样虽然不再执行 pending-learning 写入,仍会把未合并、未评审的临时分支内容同步到用户项目。

本地可稳定复现:让共享 clone checkout 到 teamai/push-in-progress,提交一个仅存在于该分支的 unmerged skill,然后持有 .sync-lock 并运行 pull --force。CLI 先输出 sync in progress elsewhere — skipped,随后仍输出 Synced 1 skills ... new: unmerged,该 skill 确实出现在业务仓库。建议 contention 时让 pullForScope 跳过整个依赖共享 clone 的 scope(或等待锁),而不是返回一个可能处于临时分支的 HEAD 后继续部署。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

确认成立,这是我上一轮修复的漏网点,已修复(e80ea7e)。竞争时我返回了当前 HEAD,但 pullForScope 随后仍 reload/扫描/部署共享 clone —— 而持锁的 push 可能正 checkout 在 teamai/push-in-progress 分支或 reset 工作树,导致未合并、未评审的临时分支内容被同步进业务仓库。采纳你的建议:refreshTeamRepo 竞争时返回 skipped: true,pullForScope 跳过整个依赖共享 clone 的 scope(不扫描、不部署);幂等 —— 锁释放后下次 pull 正常同步。真实 CLI 复现:共享 clone checkout 到 teamai/push-in-progress、带一个仅在该分支的 unmerged skill,持锁跑 pull --force → 输出 "sync in progress elsewhere — skipped",该 skill 未出现在业务仓库。

Comment thread src/config.ts
projectDataHome(anchors.projectAnchor),
anchors.workspaceRoot,
);
if (fromPartition) return fromPartition;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[P1] 无条件 partition-first 会让 init --self 的结果不可达。已有普通 project partition 的仓库执行 self init 时,initSelfRepo 把新的 repo.kind: self 配置写到 <workspaceRoot>/.teamai/config.yaml,但后续每次检测都会在这里先返回旧 partition 的 git 配置,永远不会读到刚写入的 self 配置。命令会显示 self init 成功,实际 pull/push 仍操作旧的外部 team repo。

本地可稳定复现:先创建 partition git config,再按 initSelfRepo 的保存路径写入 legacy self config;随后从仓库根目录和子目录调用 detectProjectConfig,两处返回的 repo.kind 都仍是 git。建议在 workspace 已提交的 .teamai/teamai.yaml 明确声明 mode: self 时优先走 self config/self-heal,或在确认模式切换时显式退役旧 partition,同时保持根目录和子目录结果一致。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

确认成立,已修复(e80ea7e)。无条件 partition-first 会让已有普通 partition 的仓库无法切到 self 模式:init --self 把 self 配置写到 <workspaceRoot>/.teamai/config.yaml,但检测总先返回旧 partition 的 git 配置。采纳你的建议:单仓模式具有权威性 —— 当 workspace 已提交的 .teamai/teamai.yaml 声明 mode: self 时,检测先读 self 配置(带 self-heal),再考虑 partition。新增 declaresSelfMode() marker 读取(与 bootstrap 的 readSelfModeMarker 一致)。真实 CLI 复现:陈旧 partition git 配置 + 已提交 mode: self 标记 + self 配置并存时,从根目录和子目录跑 status,local: 都指向 <proj>/.teamai 的 self clone(不再是旧 partition)。

…ce + skip deploy on lock contention

Two follow-up [P1] issues from jeff-r2026 (both surfaced by the round-1 fixes):

1. [self init unreachable] Unconditional partition-first meant a repo that already
   had a project partition (from an earlier git-mode install) could never switch to
   single-repo mode: `init --self` writes the self config to
   `<workspaceRoot>/.teamai/config.yaml`, but detection kept returning the stale
   partition git config, so pull/push still hit the old external repo. Fix:
   single-repo mode is authoritative — when the workspace's COMMITTED
   `.teamai/teamai.yaml` declares `mode: self`, detection reads the self config
   (with self-heal) BEFORE the partition. New `declaresSelfMode()` marker read.

2. [deploy of a transient tree on contention] On lock contention the pull returned
   the clone's current HEAD and pullForScope went on to reload/scan/DEPLOY the
   shared clone — but the lock holder (a `push`) may have it checked out on a
   generated `teamai/push-in-progress` branch or be mid reset/checkout, so the tree
   can hold unmerged, unreviewed content. Fix: refreshTeamRepo now returns
   `skipped: true` on contention and pullForScope skips the scope's scan/deploy
   entirely (idempotent — the next pull once the lock frees syncs normally).

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 189 files / 2627 tests pass
- real CLI repro #1: stale partition git config + committed `mode: self` marker +
  self config → status from root AND subdir both resolve to the self clone
  (<proj>/.teamai), not the partition.
- real CLI repro #2: shared clone checked out on `teamai/push-in-progress` with an
  `unmerged` skill only on that branch; hold `.sync-lock` and `pull --force` →
  "sync in progress elsewhere — skipped"; the unmerged skill is NOT deployed to
  the workspace.

Refs #374 (P1-2B).
Comment thread src/pull.ts
// deploy from a clone we could not safely snapshot. Idempotent: the next
// pull (once the lock frees) syncs normally.
pullSpin.succeed(`[${scopeLabel}] Team repo: ${label}`);
return;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[P1] 这里的 return 只退出 pullForScope,并没有跳过外层 pull() 后续的共享-clone 操作。外层随后仍执行 hooks/MCP/co-author reconcile,并调用 reportUsageToTeam; 后者即使没有 usage event,也会先对同一个 clone 执行 resetToCleanMaster + pullRepo。因此拿不到 .sync-lock 的进程仍会 checkout/reset 持锁进程正在使用的工作树。

本地可稳定复现:让共享 clone 停在 teamai/push-in-progress,持有 .sync-lock 后运行 pull --force。日志显示 sync in progress elsewhere — skipped,但命令结束后 clone 分支仍从 teamai/push-in-progress 被 auto-report 切回了 main。这会干扰正在进行的 push,并可能丢弃其尚未提交的变更。建议把 skipped 状态传播到外层,至少排除该 scope 的 reconcile/report/source 阶段;更稳妥的是让所有共享-clone 读写统一受同一把锁保护。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

确认成立,这是我 skipped 只退出 pullForScope 留下的漏洞,已修复(9883cdc)。外层 pull() 随后仍调 reportUsageToTeam,其 git 模式段即使无 usage event 也对同一共享 clone 做 resetToCleanMaster + pullRepo —— 拿不到锁的进程仍会把持锁 push 正用的工作树从 teamai/push-in-progress reset/checkout 回 main。采纳你的建议「所有共享-clone 读写统一受同一把锁」:reportUsageToTeam 现在在**整个 git 模式段(reset/pull/commit/push)**外持有 <dataHome>/.sync-lock,竞争拿不到就跳过整个 report(self 模式走 reports orphan-branch worktree,由自己的 reports-lock 协调,不受影响)。无重入:reportUsageToTeam 只在 pull() 外层、pullForScope 释放锁之后调用,pushCore 不调它。真实 CLI 复现:共享 clone 停在 teamai/push-in-progress,持锁跑 pull --force → 输出 "skipped",clone 仍停在该分支(auto-report 未 reset 回 main)。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

补充:这条的完整修复在 #414(#406 已先合并,故拆成独立 PR)。上一轮我只锁了 reportUsageToTeam,但外层 pull() 的 hooks/MCP/co-author reconcile 阶段仍会 loadTeamConfig(clone) 并从可能停在 teamai/push-in-progress 的共享 clone 注入 —— 正是你最初指出的「排除该 scope 的 reconcile/report」还没做全。#414 把竞争状态经 Set<LocalConfig> 累加器传播到外层:pullForScope 竞争时记入该 scope,pull() 随后把它从所有读/写共享 clone 的阶段(hooks/MCP/co-author reconcile + usage report)整体排除。真实 CLI 复现:clone 停在 teamai/push-in-progress(带仅在该分支的 unmerged skill)、持锁跑 pull --force → skipped,unmerged skill 未部署、clone 分支保留、reconcile 阶段对该 scope 无输出。

Comment thread src/config.ts Outdated
* partial/older file still triggers. Mirrors bootstrap's readSelfModeMarker.
*/
async function declaresSelfMode(dataHomeDir: string): Promise<boolean> {
const content = await readFileSafe(path.join(dataHomeDir, 'teamai.yaml'));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[P1] 这里声称读取的是 COMMITTED self marker,但实际只是读取工作树文件,没有检查它是否被 Git 跟踪、是否存在于可信基线,甚至不要求现有 legacy config 的 repo.kind 为 self。因此未跟踪/未提交的 .teamai/teamai.yaml 只要写入 mode: self,就能压过一个完全有效的 partition config,并触发 bootstrapSelfRepo 写入新的机器配置、注入 hooks,后续命令也会切换到 self scope。

本地可稳定复现:在已有有效 partition git config 的仓库中创建未跟踪的 .teamai/teamai.yaml(git status 为 ??,内容含 mode: self),调用 detectProjectConfig 后返回 repo.kind === self,并实际生成 <repo>/.teamai/config.yaml;原 partition 用户被忽略。建议有效 partition 继续优先,只有不存在 partition 时才允许 marker 自举;显式 init --self 应负责退役旧 partition。若必须基于 marker 抢占,也至少应从受信任 Git ref 读取并验证返回 config 确为 self,而不是信任任意工作树 YAML。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

确认成立,已修复(9883cdc)。上一轮我读的是工作树 .teamai/teamai.yaml,没校验是否 tracked/committed,导致未跟踪文件写个 mode: self 就能压过有效 partition 并触发 bootstrap。采纳你更稳妥的方案:有效 partition 始终权威优先 —— 检测无条件先返回它,工作树 marker 绝不能覆盖;把工作树 marker 读取从检测里彻底移除。切换到单仓模式是 init --self 的职责:它现在退役旧 partition(删除 <partition>/config.yaml),检测随后自然落到新写入的 self 配置。真实 CLI 复现:有效 partition + 未跟踪的 mode: self YAML(git status 为 ??)并存时,根/子目录 status 的 local: 都仍指向 partition clone,且不会自动生成 self 配置。

…ative, lock the auto-report clone writes

Two more [P1] issues from jeff-r2026 (regressions from the round-2 fixes):

1. [untracked YAML hijacks a valid partition] The round-2 self-mode precedence
   read the WORKING-TREE `.teamai/teamai.yaml` without checking it was tracked/
   committed, so an untracked file with `mode: self` could shadow a perfectly
   valid partition config and trigger bootstrapSelfRepo (writing machine config +
   injecting hooks). Fix: an existing partition config is now AUTHORITATIVE —
   detection returns it first, unconditionally; a working-tree marker can never
   override it. Switching a partitioned project to single-repo mode is
   `init --self`'s job: it now retires the stale partition config (removes
   `<partition>/config.yaml`) so detection falls through to the freshly written
   self config. Removed the working-tree marker read from detection entirely.

2. [auto-report resets the shared clone on contention] The pull `skipped` return
   only exited pullForScope; the outer pull() still ran `reportUsageToTeam`, whose
   git-mode branch does `resetToCleanMaster` + `pullRepo` on the SAME shared clone
   even with no usage events — so a process that lost `.sync-lock` still reset/
   checked out the clone the lock holder (a push) was mid-operation on, e.g.
   switching it off `teamai/push-in-progress` back to main and risking its
   uncommitted work. Fix: reportUsageToTeam now holds the partition `.sync-lock`
   around its entire git-mode clone section (reset/pull/commit/push) and skips the
   whole report on contention. self mode is unaffected (reports orphan-branch
   worktree, its own reports-lock). No re-entrancy: reportUsageToTeam is only
   called from pull()'s outer stage, after pullForScope released the lock, and
   never from pushCore.

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 189 files / 2627 tests pass
- real CLI repro #1: valid partition git config + an UNTRACKED
  `.teamai/teamai.yaml` (`git status` = `??`) with `mode: self` → status from root
  AND subdir both resolve to the partition clone; no self config is auto-created.
- real CLI repro #2: shared clone checked out on `teamai/push-in-progress`; hold
  `.sync-lock` and `pull --force` → "sync in progress elsewhere — skipped" and the
  clone stays on `teamai/push-in-progress` (auto-report did NOT reset it to main).

Refs #374 (P1-2B).
@jeff-r2026
jeff-r2026 merged commit 599c45e into main Sep 4, 2026
7 checks passed
pull Bot pushed a commit to CrazyForks/teamai-cli that referenced this pull request Sep 4, 2026
…t just the fetch (Tencent#374)

Follow-up to Tencent#406. The sync-lock contention path skipped only pullForScope's
fetch/deploy and locked the usage report, but the outer pull() STILL ran the
hooks / MCP / co-author reconcile stages for that scope. Each of those calls
`loadTeamConfig(localConfig.repo.localPath)` and injects from the SHARED team
clone — the same clone the lock holder (a concurrent push) may have checked out
on a generated `teamai/push-in-progress` branch. So a losing pull could still
read unmerged, unreviewed content off a transient branch and deploy it into the
user's tool dirs (hooks/MCP), even though the fetch was skipped.

Fix: propagate contention to the outer stages. pullForScope now records a
contended scope in a shared `Set<LocalConfig>` accumulator; pull() then drops
those scopes from EVERY later stage that reads or mutates the shared clone —
hooks/MCP/co-author reconcile and the usage report. Skipping is safe and
idempotent: the next uncontended pull reconciles and reports normally.

This completes the reviewer's original ask on Tencent#406 ("propagate skipped to the
outer pull(); at minimum exclude that scope's reconcile/report") — the earlier
fix had only locked the report, not the reconcile stages.

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 191 files / 2639 tests pass
- real CLI repro: shared clone checked out on `teamai/push-in-progress` carrying
  an `unmerged` skill that exists only on that branch; hold `<dataHome>/.sync-lock`
  and run `pull --force` → "sync in progress elsewhere — skipped"; the unmerged
  skill is NOT deployed to the workspace and the clone stays on its branch. The
  reconcile stages emit nothing for the contended scope.

Refs Tencent#374 (follow-up to P1-2B / Tencent#406).
@jeff-r2026
jeff-r2026 deleted the worktree-issue-374-p1-2b-partition-flip branch September 8, 2026 03:40
pull Bot pushed a commit to Walternater/teamai-cli that referenced this pull request Sep 8, 2026
… the partition (Tencent#374 P1-2C)

Completes the P1-2 partition routing deferred from Tencent#406: the two remaining A1
items that still landed in the business workspace for a project install now
follow the machine-data home.

- `managed-mcp.json` (per-project MCP injection manifest) and the project-scope
  `local-agent/resources` cache (the 4MB the issue calls out) move to
  `~/.teamai/projects/<slug>/` for a partitioned install, keeping the workspace
  clean. (local-agent's own config/manifest are A2 — already global under
  ~/.teamai — and are untouched.)

The trap these were deferred for: both are resolved from two sides — callers that
hold a full LocalConfig (mcp-reconcile / mcp-cmd / uninstall) and the local-agent
subsystem, which only carries (scope, projectRoot) and has no LocalConfig. If only
one side moved, a partitioned install's writer and reader would disagree
(partition vs legacy) and desync. Fix: one shared resolver.

- `managedMcpManifestPath(dataHome)` now takes a resolved data home. LocalConfig
  holders pass `getDataHome(localConfig)`.
- New `resolveDataHomeForScope(scope, projectRoot)` in config.ts reproduces
  detection's double-read (user → ~/.teamai; project → getDataHome of
  detectProjectConfig's result, i.e. partition for a new/migrated install, else
  legacy). The local-agent managed-mcp + resource paths route through it, so both
  sides always land on the identical directory.
- `getResourceRepoPath` (local-agent) is now async and uses the shared resolver
  for its project branch; user scope is unchanged (~/.teamai/local-agent/resources).
- `ensureProjectGitignore` now runs only when the cache actually lands inside the
  workspace (a legacy install) — a partitioned cache lives under ~/.teamai, so
  there is nothing in the workspace to ignore.

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 191 files / 2644 tests pass
- new real git+fs integration tests (detect-subdir.test.ts) prove the desync
  guard: `resolveDataHomeForScope` == `getDataHome(detectProjectConfig(...))` for
  legacy, subdirectory, user, non-git, AND partitioned installs (config in
  ~/.teamai/projects/<slug>/ resolves to the partition from both sides).

Note: the full http-backend local-agent install flow (install_skill/install_mcp
end-to-end) is covered by the 65 existing local-agent unit tests; a live-backend
e2e remains a manual TODO, as with the http provider.

Refs Tencent#374 (P1-2C).
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…ection + full-section sync lock

Two confirmed [P1] issues from jeff-r2026:

1. [split config by cwd] detectProjectConfig used a cwd-first fast path: it read
   `<dir>/.teamai` before resolving anchors, so a repo carrying BOTH a legacy
   `.teamai/config.yaml` and a partition config resolved to legacy from the root
   but to the partition from a subdirectory — root and subdir pull/push would then
   act on different team repos/state/env. Fix: resolve git anchors FIRST, then a
   strict, cwd-independent order (partition → workspace-root legacy); the bare
   `<dir>/.teamai` path is only the non-git fallback. And init now reuses an
   existing install's dataHome (`existingLocalConfig?.dataHome ?? resolveProjectDataHome`)
   so re-running init on a legacy install keeps writing legacy instead of forking a
   second partition config (real migration is P1-3).

2. [lock too narrow] The pull sync-lock only wrapped `pullRepo`; the lock was
   released before `flushPendingLearnings`, which writes + `git add/commit/push`es
   the same shared clone — and on contention the code skipped only the fetch but
   still ran the flush. So a pull that lost the lock could still delete pending
   files and push a "Contribute session knowledge" commit while another push was
   resetting the tree. Fix: hold the lock across the ENTIRE clone-mutating section
   (fetch + flush + rev read); on contention skip the whole section and return the
   clone's current HEAD.

Test plan (all green):
- npx tsc --noEmit — clean
- npx vitest run — 189 files / 2627 tests pass
- real CLI repro #1: with BOTH legacy and partition config present,
  `status` from the repo root AND from a subdirectory now both report the SAME
  partition data home.
- real CLI repro #2: hold `<dataHome>/.sync-lock` (live PID), then `pull` with a
  pending learning present → "sync in progress elsewhere — skipped"; the pending
  file is NOT deleted and the clone HEAD is unchanged (no rogue commit/push).

Refs Tencent#374 (P1-2B).
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…recedence + skip deploy on lock contention

Two follow-up [P1] issues from jeff-r2026 (both surfaced by the round-1 fixes):

1. [self init unreachable] Unconditional partition-first meant a repo that already
   had a project partition (from an earlier git-mode install) could never switch to
   single-repo mode: `init --self` writes the self config to
   `<workspaceRoot>/.teamai/config.yaml`, but detection kept returning the stale
   partition git config, so pull/push still hit the old external repo. Fix:
   single-repo mode is authoritative — when the workspace's COMMITTED
   `.teamai/teamai.yaml` declares `mode: self`, detection reads the self config
   (with self-heal) BEFORE the partition. New `declaresSelfMode()` marker read.

2. [deploy of a transient tree on contention] On lock contention the pull returned
   the clone's current HEAD and pullForScope went on to reload/scan/DEPLOY the
   shared clone — but the lock holder (a `push`) may have it checked out on a
   generated `teamai/push-in-progress` branch or be mid reset/checkout, so the tree
   can hold unmerged, unreviewed content. Fix: refreshTeamRepo now returns
   `skipped: true` on contention and pullForScope skips the scope's scan/deploy
   entirely (idempotent — the next pull once the lock frees syncs normally).

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 189 files / 2627 tests pass
- real CLI repro #1: stale partition git config + committed `mode: self` marker +
  self config → status from root AND subdir both resolve to the self clone
  (<proj>/.teamai), not the partition.
- real CLI repro #2: shared clone checked out on `teamai/push-in-progress` with an
  `unmerged` skill only on that branch; hold `.sync-lock` and `pull --force` →
  "sync in progress elsewhere — skipped"; the unmerged skill is NOT deployed to
  the workspace.

Refs Tencent#374 (P1-2B).
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…uthoritative, lock the auto-report clone writes

Two more [P1] issues from jeff-r2026 (regressions from the round-2 fixes):

1. [untracked YAML hijacks a valid partition] The round-2 self-mode precedence
   read the WORKING-TREE `.teamai/teamai.yaml` without checking it was tracked/
   committed, so an untracked file with `mode: self` could shadow a perfectly
   valid partition config and trigger bootstrapSelfRepo (writing machine config +
   injecting hooks). Fix: an existing partition config is now AUTHORITATIVE —
   detection returns it first, unconditionally; a working-tree marker can never
   override it. Switching a partitioned project to single-repo mode is
   `init --self`'s job: it now retires the stale partition config (removes
   `<partition>/config.yaml`) so detection falls through to the freshly written
   self config. Removed the working-tree marker read from detection entirely.

2. [auto-report resets the shared clone on contention] The pull `skipped` return
   only exited pullForScope; the outer pull() still ran `reportUsageToTeam`, whose
   git-mode branch does `resetToCleanMaster` + `pullRepo` on the SAME shared clone
   even with no usage events — so a process that lost `.sync-lock` still reset/
   checked out the clone the lock holder (a push) was mid-operation on, e.g.
   switching it off `teamai/push-in-progress` back to main and risking its
   uncommitted work. Fix: reportUsageToTeam now holds the partition `.sync-lock`
   around its entire git-mode clone section (reset/pull/commit/push) and skips the
   whole report on contention. self mode is unaffected (reports orphan-branch
   worktree, its own reports-lock). No re-entrancy: reportUsageToTeam is only
   called from pull()'s outer stage, after pullForScope released the lock, and
   never from pushCore.

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 189 files / 2627 tests pass
- real CLI repro #1: valid partition git config + an UNTRACKED
  `.teamai/teamai.yaml` (`git status` = `??`) with `mode: self` → status from root
  AND subdir both resolve to the partition clone; no self config is auto-created.
- real CLI repro #2: shared clone checked out on `teamai/push-in-progress`; hold
  `.sync-lock` and `pull --force` → "sync in progress elsewhere — skipped" and the
  clone stays on `teamai/push-in-progress` (auto-report did NOT reset it to main).

Refs Tencent#374 (P1-2B).
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…partition-flip

feat(data-layout): route new project installs to ~/.teamai/projects/<slug>/ + .sync-lock + status (Tencent#374 P1-2B)
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…t just the fetch (Tencent#374)

Follow-up to Tencent#406. The sync-lock contention path skipped only pullForScope's
fetch/deploy and locked the usage report, but the outer pull() STILL ran the
hooks / MCP / co-author reconcile stages for that scope. Each of those calls
`loadTeamConfig(localConfig.repo.localPath)` and injects from the SHARED team
clone — the same clone the lock holder (a concurrent push) may have checked out
on a generated `teamai/push-in-progress` branch. So a losing pull could still
read unmerged, unreviewed content off a transient branch and deploy it into the
user's tool dirs (hooks/MCP), even though the fetch was skipped.

Fix: propagate contention to the outer stages. pullForScope now records a
contended scope in a shared `Set<LocalConfig>` accumulator; pull() then drops
those scopes from EVERY later stage that reads or mutates the shared clone —
hooks/MCP/co-author reconcile and the usage report. Skipping is safe and
idempotent: the next uncontended pull reconciles and reports normally.

This completes the reviewer's original ask on Tencent#406 ("propagate skipped to the
outer pull(); at minimum exclude that scope's reconcile/report") — the earlier
fix had only locked the report, not the reconcile stages.

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 191 files / 2639 tests pass
- real CLI repro: shared clone checked out on `teamai/push-in-progress` carrying
  an `unmerged` skill that exists only on that branch; hold `<dataHome>/.sync-lock`
  and run `pull --force` → "sync in progress elsewhere — skipped"; the unmerged
  skill is NOT deployed to the workspace and the clone stays on its branch. The
  reconcile stages emit nothing for the contended scope.

Refs Tencent#374 (follow-up to P1-2B / Tencent#406).
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
… the partition (Tencent#374 P1-2C)

Completes the P1-2 partition routing deferred from Tencent#406: the two remaining A1
items that still landed in the business workspace for a project install now
follow the machine-data home.

- `managed-mcp.json` (per-project MCP injection manifest) and the project-scope
  `local-agent/resources` cache (the 4MB the issue calls out) move to
  `~/.teamai/projects/<slug>/` for a partitioned install, keeping the workspace
  clean. (local-agent's own config/manifest are A2 — already global under
  ~/.teamai — and are untouched.)

The trap these were deferred for: both are resolved from two sides — callers that
hold a full LocalConfig (mcp-reconcile / mcp-cmd / uninstall) and the local-agent
subsystem, which only carries (scope, projectRoot) and has no LocalConfig. If only
one side moved, a partitioned install's writer and reader would disagree
(partition vs legacy) and desync. Fix: one shared resolver.

- `managedMcpManifestPath(dataHome)` now takes a resolved data home. LocalConfig
  holders pass `getDataHome(localConfig)`.
- New `resolveDataHomeForScope(scope, projectRoot)` in config.ts reproduces
  detection's double-read (user → ~/.teamai; project → getDataHome of
  detectProjectConfig's result, i.e. partition for a new/migrated install, else
  legacy). The local-agent managed-mcp + resource paths route through it, so both
  sides always land on the identical directory.
- `getResourceRepoPath` (local-agent) is now async and uses the shared resolver
  for its project branch; user scope is unchanged (~/.teamai/local-agent/resources).
- `ensureProjectGitignore` now runs only when the cache actually lands inside the
  workspace (a legacy install) — a partitioned cache lives under ~/.teamai, so
  there is nothing in the workspace to ignore.

Test plan (all green):
- npx tsc --noEmit — clean; npx vitest run — 191 files / 2644 tests pass
- new real git+fs integration tests (detect-subdir.test.ts) prove the desync
  guard: `resolveDataHomeForScope` == `getDataHome(detectProjectConfig(...))` for
  legacy, subdirectory, user, non-git, AND partitioned installs (config in
  ~/.teamai/projects/<slug>/ resolves to the partition from both sides).

Note: the full http-backend local-agent install flow (install_skill/install_mcp
end-to-end) is covered by the 65 existing local-agent unit tests; a live-backend
e2e remains a manual TODO, as with the http provider.

Refs Tencent#374 (P1-2C).
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.

1 participant