Skip to content

refactor(data-layout): converge state.json onto getDataHome + partition primitive (#374 P1-2A) - #402

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

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

Conversation

@jeff-r2026

Copy link
Copy Markdown
Collaborator

Context

Third step of P1 (per-project data partition, issue #374), after P1-1 (#397,
merged). P1 moves teamai's machine-local data out of the business repo into
~/.teamai/projects/<slug>/ (zero workspace residue). The original P1-2 proved
large/risky on inspection (config + state + managed relocation + partition flip +
lock + status, ~20 call sites, 4 helper signature changes), so it's split into:

  • P1-2A (this PR) — partition primitive + converge state.json. ZERO behavior change.
  • P1-2B — attach dataHome in detection/init (partition-first + double-read),
    relocate config.yaml + team-repo + resources, .sync-lock, status print.
  • P1-3 — auto-migration.

What this PR does (no data moves yet)

1. Partition identity primitive — new src/utils/partition.ts:

  • projectSlug(anchor) = <safe-basename>-<sha256(normalized anchor)[:8]>. The
    hash (not a separator escape) guarantees uniqueness, so escape-ambiguous paths
    (/x/my-proj vs /x/my/proj) never collide, and the home-dir structure isn't
    leaked into the name.
  • isCaseInsensitiveFs() — runtime probe (mixed-case sentinel under ~/.teamai,
    stat the lowercase spelling; cached). realpath does not fold case on
    macOS, so normalization must be explicit. On a case-insensitive FS the whole
    slug lowercases (any spelling → one partition); Linux ext4 stays case-sensitive.
  • projectDataHome(anchor) = ~/.teamai/projects/<slug>, keyed on the shared
    projectAnchor
    so all worktrees of a repo resolve to one partition.

Not wired into any path resolution yet — unit-tested in isolation.

2. Converge state.json onto the machine-data home:

  • LocalConfig gains a runtime-only dataHome? field (attached in P1-2B by
    detection/init; never persisted — serializeLocalConfig strips it, since
    the config file lives inside dataHome and the value is anchor-derived).
  • getDataHome(localConfig) → localConfig.dataHome ?? <legacy>. With no
    attacher yet, this is still exactly the legacy path.
  • getStatePath / loadStateForScope / saveStateForScope move from
    (scope, projectRoot) to (localConfig) and derive from getDataHome, so
    state.json follows the data home in one place when P1-2B flips it. ~20 call
    sites updated mechanically.
  • getConfigPath and the managed-* manifests are deliberately deferred to P1-2B:
    config.yaml is the detection bootstrap file, and managed-hooks.json has
    special HOME-routing for non-self project scope — both need dedicated care.

Test plan (all executed green)

  • npx tsc --noEmit — clean
  • npx vitest run — 188 files / 2621 tests pass (incl. 7 new partition
    tests; state-signature assertions in scope/exclude/roles/pull updated)
  • Real CLI e2e (project scope): init fixture → pull → state.json and
    search-index.json still land in <proj>/.teamai (unchanged);
    config.yaml has no dataHome key (strip-on-save verified);
    HOME/.teamai carries no project data.

Refs #374.

…tition primitive (#374 P1-2A)

Second step of P1 (per-project data partition), split from the larger P1-2 for
independent review. Pure convergence + net-new primitive — ZERO behavior change
(no data moves yet; the partition redirect flips on in P1-2B).

Two pieces:

1. **Partition identity primitive** (new `src/utils/partition.ts`):
   - `projectSlug(anchor)` = `<safe-basename>-<sha256(normalized anchor)[:8]>` —
     the hash (not a path escape) guarantees uniqueness, so escape-ambiguous
     paths (`/x/my-proj` vs `/x/my/proj`) never collide and the home-directory
     structure isn't leaked into the dir name.
   - `isCaseInsensitiveFs()` — runtime probe (write a mixed-case sentinel under
     ~/.teamai, stat the lowercase spelling; cached). realpath does NOT fold case
     on macOS, so this must be explicit. On a case-insensitive FS the whole slug
     is lowercased so any spelling of one dir maps to ONE partition; case-
     sensitive FS (Linux ext4) keeps distinct spellings distinct.
   - `projectDataHome(anchor)` = `~/.teamai/projects/<slug>` — keyed on the
     SHARED projectAnchor so all worktrees of a repo resolve to one partition.
   Not wired into any path resolution yet; unit-tested in isolation.

2. **Converge state.json onto the machine-data home**:
   - `LocalConfig` gains a runtime-only `dataHome?` field (attached in P1-2B by
     detection/init; NEVER persisted — serializeLocalConfig strips it, since the
     config file lives inside dataHome and the value is anchor-derived).
   - `getDataHome(localConfig)` now returns `localConfig.dataHome ?? <legacy>`;
     with no attacher yet this is still exactly the legacy path.
   - `getStatePath`, `loadStateForScope`, `saveStateForScope` change from
     `(scope, projectRoot)` to `(localConfig)` and derive from getDataHome, so
     state.json follows the data home in one place when P1-2B flips it. ~20 call
     sites updated mechanically (push/pull/status/exclude/remove/roles/init/
     bootstrap). getConfigPath and the managed-* manifests are deliberately left
     for P1-2B (config.yaml is the detection bootstrap file; managed-hooks has
     special HOME-routing for non-self project scope — both need dedicated care).

Test plan (all green):
- npx tsc --noEmit — clean
- npx vitest run — 188 files / 2621 tests pass (incl. 7 new partition tests;
  updated the state-signature assertions in scope/exclude/roles/pull tests)
- real CLI e2e (project scope): init fixture → pull → state.json and
  search-index.json still land in <proj>/.teamai (unchanged); config.yaml has NO
  dataHome key (strip-on-save verified); HOME/.teamai carries no project data.

Refs #374. P1-2A of the 4-PR P1 split (P1-1 done; next: P1-2B partition flip +
.sync-lock + status; then P1-3 auto-migration).

@jeff-r2026 jeff-r2026 left a comment

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.

发现 3 个建议合入前处理的严重问题:

  1. 磁盘配置可以注入任意 dataHome,并触发目录递归删除。 LocalConfigSchema 新增 dataHome 后,config.yaml 中持久化的同名字段会被 parse 保留,并由 getDataHome() 直接信任,与注释所说的 “persisted value is ignored on load” 不符。复现:在一份合法配置中加入 dataHome: /tmp/keep,执行 teamai uninstall --yes,buildRemovalPlan() 会将该目录作为 teamaiHome,最终 remove(plan.teamaiHome) 递归删除它。此前该未知字段会被 Zod 丢弃。建议拆分 persisted schema/runtime type,或在所有加载边界明确剥离该字段。

  2. 8 位 SHA-256 后缀不能保证分区唯一。 当前只有 32 bit,碰撞可快速构造。我本地约 0.2 秒找到:

    • /tmp/teamai-collision/64889/repo
    • /tmp/teamai-collision/79057/repo

    两者 SHA-256 前 8 位均为 1436f734,basename 也同为 repo,所以最终 slug 完全相同。分区启用后会混用 config、state 和明文环境数据。建议显著增加摘要长度,不能把 8 hex 当作唯一标识。

  3. 大小写敏感性探测的是 ~/.teamai 所在卷,而不是 anchor 所在卷。 例如 HOME 位于默认大小写不敏感 APFS、项目位于大小写敏感卷时,真实且不同的 /Volumes/Case/work/Foo 与 /Volumes/Case/work/foo 都会被 lower-case,映射到同一分区并互相覆盖。大小写规范化应依据 anchor 所在文件系统。

现有 CI 全绿,但未覆盖上述路径。

…ollisions, case-probe volume

Three confirmed issues from jeff-r2026, all fixed:

1. [SECURITY — arbitrary directory deletion] Adding `dataHome` to
   LocalConfigSchema made it a KNOWN key, so Zod parse PRESERVED a persisted
   `dataHome` from disk (only unknown keys are stripped). getDataHome trusted it,
   and `uninstall` would `remove()` that directory — a hand-edited config.yaml
   with `dataHome: /any/path` becomes an arbitrary recursive delete. Fix: remove
   `dataHome` from the schema entirely; make LocalConfig a runtime-only extension
   `z.infer<Schema> & { dataHome?: string }`. Now parse strips it from disk
   (restoring the pre-existing safe behavior) while the in-memory attach path
   (P1-2B) still works; serializeLocalConfig keeps stripping on save (belt-and-braces).
   Verified via real CLI: config.yaml with injected `dataHome: <victim>` →
   `uninstall --force` removes only the legitimate <projectRoot>/.teamai, victim
   dir intact.

2. [collision] An 8-hex (32-bit) slug suffix is cheaply collidable — reviewer
   constructed two anchors with identical slug in ~0.2s. With the partition live
   that silently merges two projects' config/state/plaintext-env. Fix: widen to
   16 hex (64-bit). Changed now, before P1-2B enables partitions, so there is no
   migration cost.

3. [case-probe] The case-sensitivity probe wrote under `~/.teamai`, i.e. it
   measured HOME's volume, not the anchor's. With HOME on case-insensitive APFS
   and the project on a case-sensitive volume, genuinely distinct anchors
   (/Volumes/Case/work/Foo vs .../foo) would both be lowercased into one
   partition. Fix: probe the anchor's own volume (its parent dir) and cache the
   result per probe directory.

Tests: +4 (disk-injected dataHome dropped by parse and ignored by getDataHome;
runtime-attached dataHome honored; 16-hex suffix). npx tsc clean; npx vitest run
= 188 files / 2625 tests pass. Real CLI security repro confirms the arbitrary-
delete path is closed.

Refs #374 (P1-2A).
@jeff-r2026

Copy link
Copy Markdown
Collaborator Author

@jeff-r2026 三条全部确认成立并已修复,见 8614f76:

1. dataHome 注入 → 任意目录删除(安全):根因是把 dataHome 加进了 LocalConfigSchema,使它成为已知键,Zod parse 会保留磁盘上的持久值(只有未知键才被 strip),与注释矛盾。已把 dataHome 从 schema 移除,改为运行时交叉类型 z.infer<Schema> & { dataHome?: string }:parse 时磁盘值被丢弃(恢复原有安全行为),内存挂载路径(P1-2B)仍可用,serializeLocalConfig 继续在 save 侧剥离(双保险)。真实 CLI 复现验证:注入 dataHome: <victim> 后 uninstall --force 只删合法的 <projectRoot>/.teamai,victim 目录完好。新增 3 个单测锁定。

2. 8 hex(32-bit)碰撞:确认可秒级构造。已加宽到 16 hex(64-bit)。趁 P1-2B 尚未启用分区、此刻改动无迁移成本。

3. 大小写探针探错卷:确认原探针写在 ~/.teamai(HOME 卷),而非 anchor 卷。已改为探测 anchor 自身所在卷(其父目录),并按探测目录缓存;修复了 HOME 在大小写不敏感卷、项目在敏感卷时把 /Volumes/Case/work/Foo 与 foo 误折叠到同一分区的问题。

tsc 干净;vitest run = 188 文件 / 2625 测试全绿(+4)。感谢揪出这三处,尤其是安全那条。

@jeff-r2026
jeff-r2026 merged commit b9f630d into main Sep 3, 2026
7 checks passed
@jeff-r2026
jeff-r2026 deleted the worktree-issue-374-p1-2-partition branch September 3, 2026 14:38
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
… slug collisions, case-probe volume

Three confirmed issues from jeff-r2026, all fixed:

1. [SECURITY — arbitrary directory deletion] Adding `dataHome` to
   LocalConfigSchema made it a KNOWN key, so Zod parse PRESERVED a persisted
   `dataHome` from disk (only unknown keys are stripped). getDataHome trusted it,
   and `uninstall` would `remove()` that directory — a hand-edited config.yaml
   with `dataHome: /any/path` becomes an arbitrary recursive delete. Fix: remove
   `dataHome` from the schema entirely; make LocalConfig a runtime-only extension
   `z.infer<Schema> & { dataHome?: string }`. Now parse strips it from disk
   (restoring the pre-existing safe behavior) while the in-memory attach path
   (P1-2B) still works; serializeLocalConfig keeps stripping on save (belt-and-braces).
   Verified via real CLI: config.yaml with injected `dataHome: <victim>` →
   `uninstall --force` removes only the legitimate <projectRoot>/.teamai, victim
   dir intact.

2. [collision] An 8-hex (32-bit) slug suffix is cheaply collidable — reviewer
   constructed two anchors with identical slug in ~0.2s. With the partition live
   that silently merges two projects' config/state/plaintext-env. Fix: widen to
   16 hex (64-bit). Changed now, before P1-2B enables partitions, so there is no
   migration cost.

3. [case-probe] The case-sensitivity probe wrote under `~/.teamai`, i.e. it
   measured HOME's volume, not the anchor's. With HOME on case-insensitive APFS
   and the project on a case-sensitive volume, genuinely distinct anchors
   (/Volumes/Case/work/Foo vs .../foo) would both be lowercased into one
   partition. Fix: probe the anchor's own volume (its parent dir) and cache the
   result per probe directory.

Tests: +4 (disk-injected dataHome dropped by parse and ignored by getDataHome;
runtime-attached dataHome honored; 16-hex suffix). npx tsc clean; npx vitest run
= 188 files / 2625 tests pass. Real CLI security repro confirms the arbitrary-
delete path is closed.

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

refactor(data-layout): converge state.json onto getDataHome + partition primitive (Tencent#374 P1-2A)
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