@webpieces/rules-config 0.4.614 → 0.4.616

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/rules-config",
3
- "version": "0.4.614",
3
+ "version": "0.4.616",
4
4
  "description": "Shared webpieces.config.json loader. Single source of truth for validation rule configuration consumed by @webpieces/ai-hook-rules, @webpieces/code-rules, and @webpieces/nx-webpieces-rules.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -18,9 +18,20 @@ export declare class RepoRootFinder {
18
18
  * The repo root for `startDir`. Resolution order (first hit wins):
19
19
  * 1. Directory holding webpieces.config.json — the webpieces workspace root, and the exact
20
20
  * anchor the hook runner already uses. Walks UP from startDir, so a subdir resolves to root.
21
- * 2. git toplevel (`git rev-parse --show-toplevel`) — the repo root when no config is present
22
- * yet (e.g. the installer runs before webpieces.config.json exists).
21
+ * 2. git toplevel — the repo root when no config is present yet (e.g. the installer runs before
22
+ * webpieces.config.json exists). Asked via `DotWebpieces.treeRoot`, which is the ONE
23
+ * `git rev-parse` tree-root resolver in this repo (memoized, fails closed). This class used to
24
+ * carry its own byte-identical `spawnSync` copy, with a comment claiming to "mirror"
25
+ * runner.ts's — a mirror that had already drifted, since runner.ts had moved the call to
26
+ * effective-tree.ts. There is one implementation now, so a mirror cannot drift.
23
27
  * 3. `startDir` — last resort (git unavailable / not a repo / no config). Best-effort only.
28
+ *
29
+ * Step 1 is deliberately FIRST and deliberately not identity: config walk-up climbs PAST a nested
30
+ * clone's `.git` to the outer webpieces root (repo-root.spec.ts pins that), and in a linked worktree
31
+ * it answers with the WORKTREE, because `webpieces.config.json` is TRACKED IN GIT and therefore part
32
+ * of the BRANCH — a branch may change its own rules. See state-dir.ts for that boundary, and
33
+ * `EffectiveTreeResolver` for the different question ("which tree is this, and is it ours") that
34
+ * must NOT be answered from the config file.
24
35
  */
25
36
  resolveRepoRoot(startDir: string): string;
26
37
  /**
@@ -37,5 +48,4 @@ export declare class RepoRootFinder {
37
48
  instructAiDocPath(repoRoot: string, docName: string): string;
38
49
  /** Absolute instruct-ai doc path resolved directly from `startDir` (resolveRepoRoot + join). */
39
50
  docPathFrom(startDir: string, docName: string): string;
40
- private gitToplevel;
41
51
  }
package/src/repo-root.js CHANGED
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RepoRootFinder = exports.INSTRUCT_AI_LEAF = exports.INSTRUCT_AI_DIR = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const child_process_1 = require("child_process");
6
5
  const path = tslib_1.__importStar(require("path"));
7
6
  const inversify_1 = require("inversify");
8
7
  const config_file_1 = require("./config-file");
@@ -32,15 +31,26 @@ let RepoRootFinder = class RepoRootFinder {
32
31
  * The repo root for `startDir`. Resolution order (first hit wins):
33
32
  * 1. Directory holding webpieces.config.json — the webpieces workspace root, and the exact
34
33
  * anchor the hook runner already uses. Walks UP from startDir, so a subdir resolves to root.
35
- * 2. git toplevel (`git rev-parse --show-toplevel`) — the repo root when no config is present
36
- * yet (e.g. the installer runs before webpieces.config.json exists).
34
+ * 2. git toplevel — the repo root when no config is present yet (e.g. the installer runs before
35
+ * webpieces.config.json exists). Asked via `DotWebpieces.treeRoot`, which is the ONE
36
+ * `git rev-parse` tree-root resolver in this repo (memoized, fails closed). This class used to
37
+ * carry its own byte-identical `spawnSync` copy, with a comment claiming to "mirror"
38
+ * runner.ts's — a mirror that had already drifted, since runner.ts had moved the call to
39
+ * effective-tree.ts. There is one implementation now, so a mirror cannot drift.
37
40
  * 3. `startDir` — last resort (git unavailable / not a repo / no config). Best-effort only.
41
+ *
42
+ * Step 1 is deliberately FIRST and deliberately not identity: config walk-up climbs PAST a nested
43
+ * clone's `.git` to the outer webpieces root (repo-root.spec.ts pins that), and in a linked worktree
44
+ * it answers with the WORKTREE, because `webpieces.config.json` is TRACKED IN GIT and therefore part
45
+ * of the BRANCH — a branch may change its own rules. See state-dir.ts for that boundary, and
46
+ * `EffectiveTreeResolver` for the different question ("which tree is this, and is it ours") that
47
+ * must NOT be answered from the config file.
38
48
  */
39
49
  resolveRepoRoot(startDir) {
40
50
  const configPath = (0, config_file_1.findConfigFile)(startDir);
41
51
  if (configPath !== null)
42
52
  return path.dirname(configPath);
43
- const gitRoot = this.gitToplevel(startDir);
53
+ const gitRoot = this.dotDir.treeRoot(startDir);
44
54
  if (gitRoot !== null)
45
55
  return gitRoot;
46
56
  return startDir;
@@ -63,16 +73,6 @@ let RepoRootFinder = class RepoRootFinder {
63
73
  docPathFrom(startDir, docName) {
64
74
  return this.instructAiDocPath(this.resolveRepoRoot(startDir), docName);
65
75
  }
66
- // git repo root of `cwd`, or null when cwd is not in a git repo. `status !== 0` is the EXPECTED
67
- // "not a repo" value (spawnSync does not throw on non-zero exit), so we never swallow a real
68
- // failure with try/catch — a genuine git crash still surfaces. Mirrors runner.ts:gitToplevel.
69
- gitToplevel(cwd) {
70
- const r = (0, child_process_1.spawnSync)('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });
71
- if (r.status !== 0)
72
- return null;
73
- const root = (r.stdout ?? '').trim();
74
- return root !== '' ? root : null;
75
- }
76
76
  };
77
77
  exports.RepoRootFinder = RepoRootFinder;
78
78
  exports.RepoRootFinder = RepoRootFinder = tslib_1.__decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"repo-root.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/repo-root.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,mDAA6B;AAC7B,yCAA2D;AAE3D,+CAA+C;AAC/C,2CAAgD;AAChD,2CAAyD;AAEzD,oGAAoG;AACpG,0FAA0F;AAC7E,QAAA,eAAe,GAAG,GAAG,6BAAiB,cAAc,CAAC;AAClE,+FAA+F;AAClF,QAAA,gBAAgB,GAAG,aAAa,CAAC;AAE9C;;;;;;;;;GASG;AAEI,IAAM,cAA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AAC,CAAC,IAAI,CAAC;IACrC,CAAC;CACJ,CAAA;AAhDY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,wBAAY;GADxC,cAAc,CAgD1B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { findConfigFile } from './config-file';\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\n\n// The single instruct-ai home under `.webpieces/`. Kept here (not just in load-template) so callers\n// building AI-facing messages can render the ABSOLUTE doc path from a resolved repo root.\nexport const INSTRUCT_AI_DIR = `${WEBPIECES_TMP_DIR}/instruct-ai`;\n// The instruct-ai leaf under a resolved `.webpieces` dir. LOCAL scope — see instructAiDocPath.\nexport const INSTRUCT_AI_LEAF = 'instruct-ai';\n\n/**\n * Resolves the single repo root that owns the `.webpieces/` tree, and renders absolute paths beneath\n * it.\n *\n * `.webpieces/` MUST live at the repo root — never in a CWD-dependent subdirectory. A tool invoked\n * from a subdir (a nested package, a `services/*` app) that naively joined `.webpieces` onto its own\n * cwd would scatter stray `.webpieces` trees across the tree — the exact bug this prevents. Every\n * writer of `.webpieces/...` (logs, instruct-ai docs, sync cache, merge/pr state) MUST anchor its\n * path here rather than at `process.cwd()`.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class RepoRootFinder {\n constructor(private readonly dotDir: DotWebpieces = dotWebpieces) {}\n\n /**\n * The repo root for `startDir`. Resolution order (first hit wins):\n * 1. Directory holding webpieces.config.json — the webpieces workspace root, and the exact\n * anchor the hook runner already uses. Walks UP from startDir, so a subdir resolves to root.\n * 2. git toplevel (`git rev-parse --show-toplevel`) — the repo root when no config is present\n * yet (e.g. the installer runs before webpieces.config.json exists).\n * 3. `startDir` — last resort (git unavailable / not a repo / no config). Best-effort only.\n */\n resolveRepoRoot(startDir: string): string {\n const configPath = findConfigFile(startDir);\n if (configPath !== null) return path.dirname(configPath);\n const gitRoot = this.gitToplevel(startDir);\n if (gitRoot !== null) return gitRoot;\n return startDir;\n }\n\n /**\n * Absolute path to an instruct-ai doc. Hand THIS to the AI in a violation/fix message — never a\n * bare `.webpieces/instruct-ai/...` relative path, which an AI whose cwd is a subdirectory would\n * resolve against the wrong directory and fail to open.\n *\n * LOCAL scope: these docs are regenerated by every `wp-*` command, so under a shared path seven\n * agents would rewrite one file concurrently for no benefit — the content is version-scoped and\n * identical, and a doc the AI is told to open must never be mid-truncation. Per-worktree it has one\n * writer. TemplateWriter additionally writes it atomically and skips the write entirely when the\n * bytes already match.\n */\n instructAiDocPath(repoRoot: string, docName: string): string {\n return this.dotDir.localFile(repoRoot, INSTRUCT_AI_LEAF, docName);\n }\n\n /** Absolute instruct-ai doc path resolved directly from `startDir` (resolveRepoRoot + join). */\n docPathFrom(startDir: string, docName: string): string {\n return this.instructAiDocPath(this.resolveRepoRoot(startDir), docName);\n }\n\n // git repo root of `cwd`, or null when cwd is not in a git repo. `status !== 0` is the EXPECTED\n // \"not a repo\" value (spawnSync does not throw on non-zero exit), so we never swallow a real\n // failure with try/catch — a genuine git crash still surfaces. Mirrors runner.ts:gitToplevel.\n private gitToplevel(cwd: string): string | null {\n const r = spawnSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });\n if (r.status !== 0) return null;\n const root = (r.stdout ?? '').trim();\n return root !== '' ? root : null;\n }\n}\n"]}
1
+ {"version":3,"file":"repo-root.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/repo-root.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,yCAA2D;AAE3D,+CAA+C;AAC/C,2CAAgD;AAChD,2CAAyD;AAEzD,oGAAoG;AACpG,0FAA0F;AAC7E,QAAA,eAAe,GAAG,GAAG,6BAAiB,cAAc,CAAC;AAClE,+FAA+F;AAClF,QAAA,gBAAgB,GAAG,aAAa,CAAC;AAE9C;;;;;;;;;GASG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IACM;IAA7B,YAA6B,SAAuB,wBAAY;QAAnC,WAAM,GAAN,MAAM,CAA6B;IAAG,CAAC;IAEpE;;;;;;;;;;;;;;;;;;OAkBG;IACH,eAAe,CAAC,QAAgB;QAC5B,MAAM,UAAU,GAAG,IAAA,4BAAc,EAAC,QAAQ,CAAC,CAAC;QAC5C,IAAI,UAAU,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QACzD,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAC/C,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,OAAO,CAAC;QACrC,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED;;;;;;;;;;OAUG;IACH,iBAAiB,CAAC,QAAgB,EAAE,OAAe;QAC/C,OAAO,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,QAAQ,EAAE,wBAAgB,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED,gGAAgG;IAChG,WAAW,CAAC,QAAgB,EAAE,OAAe;QACzC,OAAO,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;CAEJ,CAAA;AAlDY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,wBAAY;GADxC,cAAc,CAkD1B","sourcesContent":["import * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { findConfigFile } from './config-file';\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\n\n// The single instruct-ai home under `.webpieces/`. Kept here (not just in load-template) so callers\n// building AI-facing messages can render the ABSOLUTE doc path from a resolved repo root.\nexport const INSTRUCT_AI_DIR = `${WEBPIECES_TMP_DIR}/instruct-ai`;\n// The instruct-ai leaf under a resolved `.webpieces` dir. LOCAL scope — see instructAiDocPath.\nexport const INSTRUCT_AI_LEAF = 'instruct-ai';\n\n/**\n * Resolves the single repo root that owns the `.webpieces/` tree, and renders absolute paths beneath\n * it.\n *\n * `.webpieces/` MUST live at the repo root — never in a CWD-dependent subdirectory. A tool invoked\n * from a subdir (a nested package, a `services/*` app) that naively joined `.webpieces` onto its own\n * cwd would scatter stray `.webpieces` trees across the tree — the exact bug this prevents. Every\n * writer of `.webpieces/...` (logs, instruct-ai docs, sync cache, merge/pr state) MUST anchor its\n * path here rather than at `process.cwd()`.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class RepoRootFinder {\n constructor(private readonly dotDir: DotWebpieces = dotWebpieces) {}\n\n /**\n * The repo root for `startDir`. Resolution order (first hit wins):\n * 1. Directory holding webpieces.config.json — the webpieces workspace root, and the exact\n * anchor the hook runner already uses. Walks UP from startDir, so a subdir resolves to root.\n * 2. git toplevel — the repo root when no config is present yet (e.g. the installer runs before\n * webpieces.config.json exists). Asked via `DotWebpieces.treeRoot`, which is the ONE\n * `git rev-parse` tree-root resolver in this repo (memoized, fails closed). This class used to\n * carry its own byte-identical `spawnSync` copy, with a comment claiming to \"mirror\"\n * runner.ts's — a mirror that had already drifted, since runner.ts had moved the call to\n * effective-tree.ts. There is one implementation now, so a mirror cannot drift.\n * 3. `startDir` — last resort (git unavailable / not a repo / no config). Best-effort only.\n *\n * Step 1 is deliberately FIRST and deliberately not identity: config walk-up climbs PAST a nested\n * clone's `.git` to the outer webpieces root (repo-root.spec.ts pins that), and in a linked worktree\n * it answers with the WORKTREE, because `webpieces.config.json` is TRACKED IN GIT and therefore part\n * of the BRANCH — a branch may change its own rules. See state-dir.ts for that boundary, and\n * `EffectiveTreeResolver` for the different question (\"which tree is this, and is it ours\") that\n * must NOT be answered from the config file.\n */\n resolveRepoRoot(startDir: string): string {\n const configPath = findConfigFile(startDir);\n if (configPath !== null) return path.dirname(configPath);\n const gitRoot = this.dotDir.treeRoot(startDir);\n if (gitRoot !== null) return gitRoot;\n return startDir;\n }\n\n /**\n * Absolute path to an instruct-ai doc. Hand THIS to the AI in a violation/fix message — never a\n * bare `.webpieces/instruct-ai/...` relative path, which an AI whose cwd is a subdirectory would\n * resolve against the wrong directory and fail to open.\n *\n * LOCAL scope: these docs are regenerated by every `wp-*` command, so under a shared path seven\n * agents would rewrite one file concurrently for no benefit — the content is version-scoped and\n * identical, and a doc the AI is told to open must never be mid-truncation. Per-worktree it has one\n * writer. TemplateWriter additionally writes it atomically and skips the write entirely when the\n * bytes already match.\n */\n instructAiDocPath(repoRoot: string, docName: string): string {\n return this.dotDir.localFile(repoRoot, INSTRUCT_AI_LEAF, docName);\n }\n\n /** Absolute instruct-ai doc path resolved directly from `startDir` (resolveRepoRoot + join). */\n docPathFrom(startDir: string, docName: string): string {\n return this.instructAiDocPath(this.resolveRepoRoot(startDir), docName);\n }\n\n}\n"]}
@@ -85,6 +85,7 @@ export declare class GitDirs {
85
85
  export declare class DotWebpieces {
86
86
  private readonly migrator;
87
87
  private readonly gitDirsByRoot;
88
+ private readonly treeRootByDir;
88
89
  private readonly migrated;
89
90
  constructor(migrator?: StateDirMigrator);
90
91
  /**
@@ -122,6 +123,30 @@ export declare class DotWebpieces {
122
123
  logsFile(startDir: string, ...segments: string[]): string;
123
124
  /** True when `startDir` sits in a LINKED worktree rather than the primary clone. */
124
125
  isLinkedWorktree(startDir: string): boolean;
126
+ /**
127
+ * git's two dir answers for `startDir`, memoized — null when it is not a git repo / git is
128
+ * unavailable.
129
+ *
130
+ * PUBLIC because TREE IDENTITY is decided from these two strings and nothing else. `commonDir`
131
+ * is the same for every checkout of ONE repo, so `commonDir(a) === commonDir(b)` is "same repo,
132
+ * different placement" — the test that tells a linked worktree (ours, wherever it sits, including
133
+ * inside the repo at `.claude/worktrees/**`) from a nested clone under `repositories/**` (not
134
+ * ours). `gitDirs.isLinkedWorktree` then separates primary from linked. See
135
+ * `EffectiveTreeResolver.classify`, the caller that runs this on the hook's blocking path, which is
136
+ * why it goes through this cache rather than spawning its own `rev-parse`.
137
+ */
138
+ gitDirs(startDir: string): GitDirs | null;
139
+ /**
140
+ * The WORKING TREE root containing `startDir` (`git rev-parse --show-toplevel`), memoized, or null
141
+ * when `startDir` is not in a git repo. In a linked worktree this is the WORKTREE's own root, which
142
+ * is exactly what a caller judging "which checkout am I standing in" needs.
143
+ *
144
+ * THE ONE tree-root resolver. There used to be three byte-identical `spawnSync … --show-toplevel`
145
+ * copies — this one, `RepoRootFinder`'s and `effective-tree.ts`'s — each commenting that it
146
+ * "mirrors" one of the others, and one of those comments was already stale. Both copies are deleted;
147
+ * everything that needs a tree root calls this. Do not add a fourth.
148
+ */
149
+ treeRoot(startDir: string): string | null;
125
150
  /**
126
151
  * git's own name for this linked worktree — the basename of `<primary>/.git/worktrees/<name>`, and
127
152
  * the namespace key under `worktrees/`. Empty for the primary clone. git's name rather than the
@@ -138,8 +163,6 @@ export declare class DotWebpieces {
138
163
  */
139
164
  legacyDir(treeRoot: string): string;
140
165
  private migrateOnce;
141
- private gitDirs;
142
- private gitToplevel;
143
166
  private revParse;
144
167
  }
145
168
  export declare const dotWebpieces: DotWebpieces;
package/src/state-dir.js CHANGED
@@ -123,6 +123,8 @@ let DotWebpieces = class DotWebpieces {
123
123
  // treeRoot → git's answer. One `git rev-parse` pair per root per process; every later path lookup
124
124
  // in that invocation is a Map hit.
125
125
  gitDirsByRoot = new Map();
126
+ // startDir → `git rev-parse --show-toplevel`, cached on the same terms as gitDirsByRoot.
127
+ treeRootByDir = new Map();
126
128
  // Roots whose legacy per-worktree `.webpieces/` has already been considered for migration.
127
129
  migrated = new Set();
128
130
  constructor(migrator = new state_dir_migration_1.StateDirMigrator()) {
@@ -183,6 +185,48 @@ let DotWebpieces = class DotWebpieces {
183
185
  const dirs = this.gitDirs(startDir);
184
186
  return dirs !== null && dirs.isLinkedWorktree;
185
187
  }
188
+ /**
189
+ * git's two dir answers for `startDir`, memoized — null when it is not a git repo / git is
190
+ * unavailable.
191
+ *
192
+ * PUBLIC because TREE IDENTITY is decided from these two strings and nothing else. `commonDir`
193
+ * is the same for every checkout of ONE repo, so `commonDir(a) === commonDir(b)` is "same repo,
194
+ * different placement" — the test that tells a linked worktree (ours, wherever it sits, including
195
+ * inside the repo at `.claude/worktrees/**`) from a nested clone under `repositories/**` (not
196
+ * ours). `gitDirs.isLinkedWorktree` then separates primary from linked. See
197
+ * `EffectiveTreeResolver.classify`, the caller that runs this on the hook's blocking path, which is
198
+ * why it goes through this cache rather than spawning its own `rev-parse`.
199
+ */
200
+ gitDirs(startDir) {
201
+ const cached = this.gitDirsByRoot.get(startDir);
202
+ if (cached !== undefined)
203
+ return cached;
204
+ const gitDir = this.revParse(startDir, '--git-dir');
205
+ const commonDir = this.revParse(startDir, '--git-common-dir');
206
+ const dirs = gitDir === null || commonDir === null ? null : new GitDirs(gitDir, commonDir);
207
+ this.gitDirsByRoot.set(startDir, dirs);
208
+ return dirs;
209
+ }
210
+ /**
211
+ * The WORKING TREE root containing `startDir` (`git rev-parse --show-toplevel`), memoized, or null
212
+ * when `startDir` is not in a git repo. In a linked worktree this is the WORKTREE's own root, which
213
+ * is exactly what a caller judging "which checkout am I standing in" needs.
214
+ *
215
+ * THE ONE tree-root resolver. There used to be three byte-identical `spawnSync … --show-toplevel`
216
+ * copies — this one, `RepoRootFinder`'s and `effective-tree.ts`'s — each commenting that it
217
+ * "mirrors" one of the others, and one of those comments was already stale. Both copies are deleted;
218
+ * everything that needs a tree root calls this. Do not add a fourth.
219
+ */
220
+ treeRoot(startDir) {
221
+ const cached = this.treeRootByDir.get(startDir);
222
+ if (cached !== undefined)
223
+ return cached;
224
+ // `status !== 0` IS the expected "not a repo" answer (spawnSync does not throw on a non-zero
225
+ // exit), so nothing here swallows a real git crash.
226
+ const root = this.revParse(startDir, '--show-toplevel');
227
+ this.treeRootByDir.set(startDir, root);
228
+ return root;
229
+ }
186
230
  /**
187
231
  * git's own name for this linked worktree — the basename of `<primary>/.git/worktrees/<name>`, and
188
232
  * the namespace key under `worktrees/`. Empty for the primary clone. git's name rather than the
@@ -222,27 +266,11 @@ let DotWebpieces = class DotWebpieces {
222
266
  if (this.migrated.has(startDir))
223
267
  return;
224
268
  this.migrated.add(startDir);
225
- const toplevel = this.gitToplevel(startDir);
269
+ const toplevel = this.treeRoot(startDir);
226
270
  if (toplevel === null)
227
271
  return;
228
272
  this.migrator.migrate(this.legacyDir(toplevel), target);
229
273
  }
230
- // Both git dirs for `startDir`, cached, or null when this is not a git repo / git is unavailable.
231
- // `status !== 0` IS the expected "not a repo" answer (spawnSync does not throw on a non-zero exit),
232
- // so there is no try/catch here swallowing a real git crash. Mirrors RepoRootFinder.gitToplevel.
233
- gitDirs(startDir) {
234
- const cached = this.gitDirsByRoot.get(startDir);
235
- if (cached !== undefined)
236
- return cached;
237
- const gitDir = this.revParse(startDir, '--git-dir');
238
- const commonDir = this.revParse(startDir, '--git-common-dir');
239
- const dirs = gitDir === null || commonDir === null ? null : new GitDirs(gitDir, commonDir);
240
- this.gitDirsByRoot.set(startDir, dirs);
241
- return dirs;
242
- }
243
- gitToplevel(startDir) {
244
- return this.revParse(startDir, '--show-toplevel');
245
- }
246
274
  // One `git rev-parse <flag>`, resolved to an absolute path (git prints a bare `.git`, relative to
247
275
  // the tree, in the primary clone, and an absolute path from a linked worktree).
248
276
  revParse(cwd, flag) {
@@ -1 +1 @@
1
- {"version":3,"file":"state-dir.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/state-dir.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,2CAAgD;AAChD,+DAAyD;AAEzD,uGAAuG;AACvG,2FAA2F;AAC3F,8DAA8D;AACjD,QAAA,kBAAkB,GAAG,WAAW,CAAC;AAE9C,kGAAkG;AAClG,iGAAiG;AACjG,mGAAmG;AACnG,iEAAiE;AACjE,EAAE;AACF,0FAA0F;AA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7C,IAAI,OAAO,KAAK,EAAE;YAAE,OAAO,IAAI,CAAC;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACJ,CAAA;AA7IY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAQE,sCAAgB;GAP9C,YAAY,CA6IxB;AAED,sGAAsG;AACtG,sGAAsG;AACtG,uFAAuF;AAC1E,QAAA,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { StateDirMigrator } from './state-dir-migration';\n\n// The per-worktree namespace inside the primary clone's `.webpieces/`. A LINKED worktree's local state\n// lives at `<primary>/.webpieces/worktrees/<worktreeName>/`; the primary clone keeps using\n// `<primary>/.webpieces/` directly, exactly as it always has.\nexport const WORKTREE_STATE_DIR = 'worktrees';\n\n// The ONE and ONLY directory webpieces writes observability state into — `<state>/logs/`, for the\n// primary clone and for each worktree namespace alike. There is no second state directory and no\n// split: the L1 binary's logs, the L0 sh shim's log, and the rejection DETAIL files (which are not\n// `.log`s but belong to the log that indexes them) are all here.\n//\n// It used to be two directories — `hooks/`, holding the binary's logs mixed in with dated\n// `hooks/<YYYY-MM-DD>/writeInfo-*.md` rejection details, and `logs/`, where the sh shim wrote — so\n// \"where are the logs?\" had two answers and neither was complete. `hooks/` is gone entirely; nothing\n// reads or writes it.\n//\n// Every writer resolves its DIRECTORY through dotWebpieces.logs()/logsFile(), so the layout cannot\n// drift apart again. What sits INSIDE it is ai-hook-rules' business (see its log-streams.ts and\n// LogStream): one directory per LAYER, and inside that one file per WRITER, named\n// <sessionId>-<agentId|coordinator>-<hook>.log — because Claude Code runs all matching PreToolUse\n// hooks IN PARALLEL and subagents/windows share a tree, so writers must never share a file.\nexport const LOGS_STATE_DIR = 'logs';\n\n\n// git prints the shared git dir as `<primary>/.git` for a conventional clone. Anything else (a bare\n// repo, `--separate-git-dir`) is a layout we decline to derive a working tree from.\nconst GIT_DIR_NAME = '.git';\n\n/**\n * Data-only carrier for the two paths git is asked for. Per CLAUDE.md: classes for data.\n *\n * `gitDir` is the PER-WORKTREE git dir (`<primary>/.git/worktrees/<name>` in a linked worktree,\n * `<primary>/.git` in the primary clone). `commonDir` is the SHARED one — always `<primary>/.git`.\n * They differ if and only if this is a linked worktree; that is git's own canonical test.\n */\nexport class GitDirs {\n readonly gitDir: string;\n readonly commonDir: string;\n\n constructor(gitDir: string, commonDir: string) {\n this.gitDir = gitDir;\n this.commonDir = commonDir;\n }\n\n get isLinkedWorktree(): boolean {\n return path.resolve(this.gitDir) !== path.resolve(this.commonDir);\n }\n}\n\n/**\n * WHERE a piece of `.webpieces/` state belongs — the ONE resolver every reader and writer must go\n * through, with TWO named methods because there are exactly two answers and a call site must DECLARE\n * which one it means.\n *\n * dotWebpieces.shared(dir) → <primary>/.webpieces (repo-wide facts)\n * dotWebpieces.local(dir) → <primary>/.webpieces/worktrees/<name> (this worktree only)\n * → <primary>/.webpieces (…in the primary clone)\n *\n * ─── The bug ───────────────────────────────────────────────────────────────────────────────────────\n * `.webpieces/` is gitignored, and it was anchored at the directory holding webpieces.config.json —\n * which in a linked worktree is the WORKTREE. So a repo with seven worktrees had SEVEN independent\n * copies of files that describe the WHOLE REPO. `merged-branches.json` holds verdicts for every branch\n * AND every worktree in the repo; N copies is N divergent truths, and the guards read them as fact.\n * Observed in the field: branch-creation-guard asserted \"8 parked local branches\" while\n * `git branch --list` showed ONE — it was reading a cache written before deletions performed from a\n * DIFFERENT worktree — and it then blocked a legitimate `git worktree add` on that fiction.\n *\n * ─── Why two explicit methods and not a symlink ────────────────────────────────────────────────────\n * A `<worktree>/.webpieces` → `<primary>/…/worktrees/<name>` symlink would have left every call site\n * untouched, which is seductive and wrong. Nothing hooks `git worktree add`, so the link needs LAZY\n * creation that also has to handle \"link already exists\", \"link points somewhere else\", and \"a real\n * directory is already there\" — invisible filesystem magic with a Windows failure mode. Worse, the safe\n * way to write a shared file under concurrency is temp-file-then-`rename()`, and `rename(2)` acts on\n * the PATH, not the link: it REPLACES a symlink with a real file. That silently works for one writer\n * and diverges for everyone else — the exact bug being fixed, but invisible. An explicit call is\n * greppable, testable, and forces each site to say which scope it means.\n *\n * ─── Which scope is which (the scope assignment is deliberate, not incidental) ─────────────────────\n * shared():\n * • merged-branches.json — verdicts for every branch and worktree in the repo. Atomically written.\n * • main-sync-status.json AND main-sync.lock.json — there is one `main` and one `.git`, so there is\n * one refresher. A lock inside a per-worktree directory locks nothing.\n * local():\n * • logs/*.log, INCLUDING branch-mutations.log. A shared append-only log genuinely corrupts:\n * `O_APPEND` writes are indivisible only under PIPE_BUF, which is 512 bytes on macOS, and a\n * `recover=git worktree add -b <branch> <abs-path> <tag>` line with real paths exceeds that. A\n * per-worktree log has exactly ONE writer and cannot tear, and under this layout it already\n * survives the worktree's deletion — recovery is one glob over\n * `<primary>/.webpieces/worktrees/*/logs/branch-mutations.log`.\n * • merge-info/staged|merged/<branch>/ and its index.json, pr-review/<branch>/, instruct-ai/, and\n * every other per-tree scratch file.\n *\n * ─── The boundary that must not be blurred ─────────────────────────────────────────────────────────\n * ONLY the gitignored `.webpieces/` STATE relocates. `webpieces.config.json` is TRACKED IN GIT and is\n * therefore part of the BRANCH: a branch may legitimately change its own rules and that must keep\n * working. Config resolution is untouched — still per-worktree, via findConfigFile /\n * RepoRootFinder.resolveRepoRoot. Nothing in this class reads or moves config.\n *\n * ─── Why `--git-dir` / `--git-common-dir`, and not one of the existing services ────────────────────\n * They are git's own answers, from any subdirectory, in one cheap local call, with no `.git`-file\n * parsing by hand (which gets `--separate-git-dir` and submodules wrong). Two existing mechanisms do\n * distinguish primary from linked, and neither is the right authority here:\n * • `WorktreeService` answers \"what worktrees exist and what do they hold\" — a repo-wide ENUMERATION\n * (`git worktree list --porcelain`) for the caps and the reaper. Using it for a path lookup would\n * run an enumeration on the hook's blocking path for every state access, and it fails SOFT to `[]`,\n * which here would read as \"there is no primary clone\" on exactly the degraded repo where the\n * answer matters most. It also does not expose the worktree's git NAME, which is the namespace key.\n * • `EffectiveTreeResolver` (#524) answers \"which tree does this COMMAND act on\" — it takes a command\n * string and is a policy input to the bash guards, not a filesystem-path resolver.\n * Both remain authoritative for their own questions. This asks the narrowest one — two path strings —\n * and lives in rules-config, UNDER both, which is where a primitive that pr-gate, ai-hook-rules and\n * code-rules all need has to sit.\n *\n * Fails CLOSED to the pre-change behaviour: when git cannot answer, every path here collapses to\n * `<startDir-root>/.webpieces` exactly as before. Degrading to merely-suboptimal beats throwing on a\n * hook's blocking path.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DotWebpieces {\n // treeRoot → git's answer. One `git rev-parse` pair per root per process; every later path lookup\n // in that invocation is a Map hit.\n private readonly gitDirsByRoot = new Map<string, GitDirs | null>();\n // Roots whose legacy per-worktree `.webpieces/` has already been considered for migration.\n private readonly migrated = new Set<string>();\n\n constructor(private readonly migrator: StateDirMigrator = new StateDirMigrator()) {}\n\n /**\n * REPO-WIDE state: `<primary>/.webpieces`. Use ONLY for facts about the repo rather than about one\n * worktree — today that is merged-branches.json and the main-sync status + lock. Identical from\n * every worktree, and never behind an indirection, so an atomic `rename()` into it is safe.\n */\n shared(startDir: string): string {\n return path.join(this.primaryRoot(startDir), WEBPIECES_TMP_DIR);\n }\n\n /** A path beneath the repo-wide state dir. */\n sharedFile(startDir: string, ...segments: string[]): string {\n return path.join(this.shared(startDir), ...segments);\n }\n\n /**\n * THIS WORKTREE's private state: `<primary>/.webpieces/worktrees/<name>` for a linked worktree, and\n * `<primary>/.webpieces` for the primary clone, which keeps its state exactly where it has always\n * been. Fully isolated — two worktrees never write the same path, so nothing here needs a lock.\n *\n * The first call for a linked worktree also MIGRATES a legacy real `<worktree>/.webpieces/`\n * directory into the namespace, so in-flight merge / pr-review state written under the old scheme\n * (or by an older PUBLISHED build during the transition) is picked up rather than orphaned.\n */\n local(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return this.shared(startDir);\n\n const target = path.join(this.shared(startDir), WORKTREE_STATE_DIR, path.basename(dirs.gitDir));\n this.migrateOnce(startDir, target);\n return target;\n }\n\n /** A path beneath this worktree's private state dir. */\n localFile(startDir: string, ...segments: string[]): string {\n return path.join(this.local(startDir), ...segments);\n }\n\n /**\n * THE log directory — `<local()>/logs` — and the only place webpieces writes a `.log` or a log's\n * detail files, in the primary clone and in every worktree namespace alike.\n *\n * There is NO migration here, deliberately. A lazy once-per-process relocation of an older\n * release's `hooks/*.log` used to run on this path, and it was itself the defect it claimed to\n * cure: it only fires in the trees a process happens to re-enter, so it guarantees two answers to\n * \"where are the logs\" indefinitely rather than converging on one. New writes go to `logs/` and\n * nothing else; a stale `hooks/` left by an older release is inert and can be deleted by hand.\n */\n logs(startDir: string): string {\n return path.join(this.local(startDir), LOGS_STATE_DIR);\n }\n\n /** A path beneath the log directory — `dotWebpieces.logsFile(root, CALLS_STREAM, writerFile)`. */\n logsFile(startDir: string, ...segments: string[]): string {\n return path.join(this.logs(startDir), ...segments);\n }\n\n /** True when `startDir` sits in a LINKED worktree rather than the primary clone. */\n isLinkedWorktree(startDir: string): boolean {\n const dirs = this.gitDirs(startDir);\n return dirs !== null && dirs.isLinkedWorktree;\n }\n\n /**\n * git's own name for this linked worktree — the basename of `<primary>/.git/worktrees/<name>`, and\n * the namespace key under `worktrees/`. Empty for the primary clone. git's name rather than the\n * directory's basename, so two worktrees checked out into same-named directories under different\n * parents cannot collide.\n */\n worktreeName(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return '';\n return path.basename(dirs.gitDir);\n }\n\n /** The primary clone's root, from any worktree. Falls back to git's toplevel-less best guess. */\n primaryRoot(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null) return startDir;\n if (path.basename(dirs.commonDir) !== GIT_DIR_NAME) return startDir;\n const primary = path.dirname(dirs.commonDir);\n return fs.existsSync(primary) ? primary : startDir;\n }\n\n /**\n * The PRE-change location, `<treeRoot>/.webpieces` — what every call site used to compute. Public\n * because the migrator and its specs must be able to name the thing being migrated FROM, and\n * because the transition-window fallback readers need it.\n */\n legacyDir(treeRoot: string): string {\n return path.join(treeRoot, WEBPIECES_TMP_DIR);\n }\n\n // Drain a legacy per-worktree `.webpieces/` into this worktree's namespace, at most once per tree\n // per process. Migration is idempotent, but it touches the filesystem on the hook's blocking path.\n private migrateOnce(startDir: string, target: string): void {\n // Guard on the CHEAP key first. `local()` is called many times per invocation, and resolving the\n // worktree toplevel costs a `git rev-parse` — doing that before the once-check would put a\n // process spawn on the hook's blocking path for every single state-path lookup.\n if (this.migrated.has(startDir)) return;\n this.migrated.add(startDir);\n const toplevel = this.gitToplevel(startDir);\n if (toplevel === null) return;\n this.migrator.migrate(this.legacyDir(toplevel), target);\n }\n\n // Both git dirs for `startDir`, cached, or null when this is not a git repo / git is unavailable.\n // `status !== 0` IS the expected \"not a repo\" answer (spawnSync does not throw on a non-zero exit),\n // so there is no try/catch here swallowing a real git crash. Mirrors RepoRootFinder.gitToplevel.\n private gitDirs(startDir: string): GitDirs | null {\n const cached = this.gitDirsByRoot.get(startDir);\n if (cached !== undefined) return cached;\n\n const gitDir = this.revParse(startDir, '--git-dir');\n const commonDir = this.revParse(startDir, '--git-common-dir');\n const dirs = gitDir === null || commonDir === null ? null : new GitDirs(gitDir, commonDir);\n this.gitDirsByRoot.set(startDir, dirs);\n return dirs;\n }\n\n private gitToplevel(startDir: string): string | null {\n return this.revParse(startDir, '--show-toplevel');\n }\n\n // One `git rev-parse <flag>`, resolved to an absolute path (git prints a bare `.git`, relative to\n // the tree, in the primary clone, and an absolute path from a linked worktree).\n private revParse(cwd: string, flag: string): string | null {\n const result = spawnSync('git', ['-C', cwd, 'rev-parse', flag], { encoding: 'utf8' });\n if (result.status !== 0) return null;\n const printed = (result.stdout ?? '').trim();\n if (printed === '') return null;\n return path.resolve(cwd, printed);\n }\n}\n\n// Process-wide instance for the many non-DI call sites (hooks, detached refreshers, wp-* bins, eslint\n// rules). Sharing one instance is what makes the git-resolution cache and the once-per-tree migration\n// worth having; inversify still injects the singleton wherever a container is in play.\nexport const dotWebpieces = new DotWebpieces();\n"]}
1
+ {"version":3,"file":"state-dir.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/state-dir.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,2CAAgD;AAChD,+DAAyD;AAEzD,uGAAuG;AACvG,2FAA2F;AAC3F,8DAA8D;AACjD,QAAA,kBAAkB,GAAG,WAAW,CAAC;AAE9C,kGAAkG;AAClG,iGAAiG;AACjG,mGAAmG;AACnG,iEAAiE;AACjE,EAAE;AACF,0FAA0F;AAC1F,mGAAmG;AACnG,qGAAqG;AACrG,sBAAsB;AACtB,EAAE;AACF,mGAAmG;AACnG,gGAAgG;AAChG,kFAAkF;AAClF,kGAAkG;AAClG,4FAA4F;AAC/E,QAAA,cAAc,GAAG,MAAM,CAAC;AAGrC,oGAAoG;AACpG,oFAAoF;AACpF,MAAM,YAAY,GAAG,MAAM,CAAC;AAE5B;;;;;;GAMG;AACH,MAAa,OAAO;IACP,MAAM,CAAS;IACf,SAAS,CAAS;IAE3B,YAAY,MAAc,EAAE,SAAiB;QACzC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;IAED,IAAI,gBAAgB;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACtE,CAAC;CACJ;AAZD,0BAYC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;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,QAAA,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { StateDirMigrator } from './state-dir-migration';\n\n// The per-worktree namespace inside the primary clone's `.webpieces/`. A LINKED worktree's local state\n// lives at `<primary>/.webpieces/worktrees/<worktreeName>/`; the primary clone keeps using\n// `<primary>/.webpieces/` directly, exactly as it always has.\nexport const WORKTREE_STATE_DIR = 'worktrees';\n\n// The ONE and ONLY directory webpieces writes observability state into — `<state>/logs/`, for the\n// primary clone and for each worktree namespace alike. There is no second state directory and no\n// split: the L1 binary's logs, the L0 sh shim's log, and the rejection DETAIL files (which are not\n// `.log`s but belong to the log that indexes them) are all here.\n//\n// It used to be two directories — `hooks/`, holding the binary's logs mixed in with dated\n// `hooks/<YYYY-MM-DD>/writeInfo-*.md` rejection details, and `logs/`, where the sh shim wrote — so\n// \"where are the logs?\" had two answers and neither was complete. `hooks/` is gone entirely; nothing\n// reads or writes it.\n//\n// Every writer resolves its DIRECTORY through dotWebpieces.logs()/logsFile(), so the layout cannot\n// drift apart again. What sits INSIDE it is ai-hook-rules' business (see its log-streams.ts and\n// LogStream): one directory per LAYER, and inside that one file per WRITER, named\n// <sessionId>-<agentId|coordinator>-<hook>.log — because Claude Code runs all matching PreToolUse\n// hooks IN PARALLEL and subagents/windows share a tree, so writers must never share a file.\nexport const LOGS_STATE_DIR = 'logs';\n\n\n// git prints the shared git dir as `<primary>/.git` for a conventional clone. Anything else (a bare\n// repo, `--separate-git-dir`) is a layout we decline to derive a working tree from.\nconst GIT_DIR_NAME = '.git';\n\n/**\n * Data-only carrier for the two paths git is asked for. Per CLAUDE.md: classes for data.\n *\n * `gitDir` is the PER-WORKTREE git dir (`<primary>/.git/worktrees/<name>` in a linked worktree,\n * `<primary>/.git` in the primary clone). `commonDir` is the SHARED one — always `<primary>/.git`.\n * They differ if and only if this is a linked worktree; that is git's own canonical test.\n */\nexport class GitDirs {\n readonly gitDir: string;\n readonly commonDir: string;\n\n constructor(gitDir: string, commonDir: string) {\n this.gitDir = gitDir;\n this.commonDir = commonDir;\n }\n\n get isLinkedWorktree(): boolean {\n return path.resolve(this.gitDir) !== path.resolve(this.commonDir);\n }\n}\n\n/**\n * WHERE a piece of `.webpieces/` state belongs — the ONE resolver every reader and writer must go\n * through, with TWO named methods because there are exactly two answers and a call site must DECLARE\n * which one it means.\n *\n * dotWebpieces.shared(dir) → <primary>/.webpieces (repo-wide facts)\n * dotWebpieces.local(dir) → <primary>/.webpieces/worktrees/<name> (this worktree only)\n * → <primary>/.webpieces (…in the primary clone)\n *\n * ─── The bug ───────────────────────────────────────────────────────────────────────────────────────\n * `.webpieces/` is gitignored, and it was anchored at the directory holding webpieces.config.json —\n * which in a linked worktree is the WORKTREE. So a repo with seven worktrees had SEVEN independent\n * copies of files that describe the WHOLE REPO. `merged-branches.json` holds verdicts for every branch\n * AND every worktree in the repo; N copies is N divergent truths, and the guards read them as fact.\n * Observed in the field: branch-creation-guard asserted \"8 parked local branches\" while\n * `git branch --list` showed ONE — it was reading a cache written before deletions performed from a\n * DIFFERENT worktree — and it then blocked a legitimate `git worktree add` on that fiction.\n *\n * ─── Why two explicit methods and not a symlink ────────────────────────────────────────────────────\n * A `<worktree>/.webpieces` → `<primary>/…/worktrees/<name>` symlink would have left every call site\n * untouched, which is seductive and wrong. Nothing hooks `git worktree add`, so the link needs LAZY\n * creation that also has to handle \"link already exists\", \"link points somewhere else\", and \"a real\n * directory is already there\" — invisible filesystem magic with a Windows failure mode. Worse, the safe\n * way to write a shared file under concurrency is temp-file-then-`rename()`, and `rename(2)` acts on\n * the PATH, not the link: it REPLACES a symlink with a real file. That silently works for one writer\n * and diverges for everyone else — the exact bug being fixed, but invisible. An explicit call is\n * greppable, testable, and forces each site to say which scope it means.\n *\n * ─── Which scope is which (the scope assignment is deliberate, not incidental) ─────────────────────\n * shared():\n * • merged-branches.json — verdicts for every branch and worktree in the repo. Atomically written.\n * • main-sync-status.json AND main-sync.lock.json — there is one `main` and one `.git`, so there is\n * one refresher. A lock inside a per-worktree directory locks nothing.\n * local():\n * • logs/*.log, INCLUDING branch-mutations.log. A shared append-only log genuinely corrupts:\n * `O_APPEND` writes are indivisible only under PIPE_BUF, which is 512 bytes on macOS, and a\n * `recover=git worktree add -b <branch> <abs-path> <tag>` line with real paths exceeds that. A\n * per-worktree log has exactly ONE writer and cannot tear, and under this layout it already\n * survives the worktree's deletion — recovery is one glob over\n * `<primary>/.webpieces/worktrees/*/logs/branch-mutations.log`.\n * • merge-info/staged|merged/<branch>/ and its index.json, pr-review/<branch>/, instruct-ai/, and\n * every other per-tree scratch file.\n *\n * ─── The boundary that must not be blurred ─────────────────────────────────────────────────────────\n * ONLY the gitignored `.webpieces/` STATE relocates. `webpieces.config.json` is TRACKED IN GIT and is\n * therefore part of the BRANCH: a branch may legitimately change its own rules and that must keep\n * working. Config resolution is untouched — still per-worktree, via findConfigFile /\n * RepoRootFinder.resolveRepoRoot. Nothing in this class reads or moves config.\n *\n * ─── Why `--git-dir` / `--git-common-dir`, and not one of the existing services ────────────────────\n * They are git's own answers, from any subdirectory, in one cheap local call, with no `.git`-file\n * parsing by hand (which gets `--separate-git-dir` and submodules wrong). Two existing mechanisms do\n * distinguish primary from linked, and neither is the right authority here:\n * • `WorktreeService` answers \"what worktrees exist and what do they hold\" — a repo-wide ENUMERATION\n * (`git worktree list --porcelain`) for the caps and the reaper. Using it for a path lookup would\n * run an enumeration on the hook's blocking path for every state access, and it fails SOFT to `[]`,\n * which here would read as \"there is no primary clone\" on exactly the degraded repo where the\n * answer matters most. It also does not expose the worktree's git NAME, which is the namespace key.\n * • `EffectiveTreeResolver` (#524) answers \"which tree does this COMMAND act on\" — it takes a command\n * string and is a policy input to the bash guards, not a filesystem-path resolver.\n * Both remain authoritative for their own questions. This asks the narrowest one — two path strings —\n * and lives in rules-config, UNDER both, which is where a primitive that pr-gate, ai-hook-rules and\n * code-rules all need has to sit.\n *\n * Fails CLOSED to the pre-change behaviour: when git cannot answer, every path here collapses to\n * `<startDir-root>/.webpieces` exactly as before. Degrading to merely-suboptimal beats throwing on a\n * hook's blocking path.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DotWebpieces {\n // treeRoot → git's answer. One `git rev-parse` pair per root per process; every later path lookup\n // in that invocation is a Map hit.\n private readonly gitDirsByRoot = new Map<string, GitDirs | null>();\n // startDir → `git rev-parse --show-toplevel`, cached on the same terms as gitDirsByRoot.\n private readonly treeRootByDir = new Map<string, string | null>();\n // Roots whose legacy per-worktree `.webpieces/` has already been considered for migration.\n private readonly migrated = new Set<string>();\n\n constructor(private readonly migrator: StateDirMigrator = new StateDirMigrator()) {}\n\n /**\n * REPO-WIDE state: `<primary>/.webpieces`. Use ONLY for facts about the repo rather than about one\n * worktree — today that is merged-branches.json and the main-sync status + lock. Identical from\n * every worktree, and never behind an indirection, so an atomic `rename()` into it is safe.\n */\n shared(startDir: string): string {\n return path.join(this.primaryRoot(startDir), WEBPIECES_TMP_DIR);\n }\n\n /** A path beneath the repo-wide state dir. */\n sharedFile(startDir: string, ...segments: string[]): string {\n return path.join(this.shared(startDir), ...segments);\n }\n\n /**\n * THIS WORKTREE's private state: `<primary>/.webpieces/worktrees/<name>` for a linked worktree, and\n * `<primary>/.webpieces` for the primary clone, which keeps its state exactly where it has always\n * been. Fully isolated — two worktrees never write the same path, so nothing here needs a lock.\n *\n * The first call for a linked worktree also MIGRATES a legacy real `<worktree>/.webpieces/`\n * directory into the namespace, so in-flight merge / pr-review state written under the old scheme\n * (or by an older PUBLISHED build during the transition) is picked up rather than orphaned.\n */\n local(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return this.shared(startDir);\n\n const target = path.join(this.shared(startDir), WORKTREE_STATE_DIR, path.basename(dirs.gitDir));\n this.migrateOnce(startDir, target);\n return target;\n }\n\n /** A path beneath this worktree's private state dir. */\n localFile(startDir: string, ...segments: string[]): string {\n return path.join(this.local(startDir), ...segments);\n }\n\n /**\n * THE log directory — `<local()>/logs` — and the only place webpieces writes a `.log` or a log's\n * detail files, in the primary clone and in every worktree namespace alike.\n *\n * There is NO migration here, deliberately. A lazy once-per-process relocation of an older\n * release's `hooks/*.log` used to run on this path, and it was itself the defect it claimed to\n * cure: it only fires in the trees a process happens to re-enter, so it guarantees two answers to\n * \"where are the logs\" indefinitely rather than converging on one. New writes go to `logs/` and\n * nothing else; a stale `hooks/` left by an older release is inert and can be deleted by hand.\n */\n logs(startDir: string): string {\n return path.join(this.local(startDir), LOGS_STATE_DIR);\n }\n\n /** A path beneath the log directory — `dotWebpieces.logsFile(root, CALLS_STREAM, writerFile)`. */\n logsFile(startDir: string, ...segments: string[]): string {\n return path.join(this.logs(startDir), ...segments);\n }\n\n /** True when `startDir` sits in a LINKED worktree rather than the primary clone. */\n isLinkedWorktree(startDir: string): boolean {\n const dirs = this.gitDirs(startDir);\n return dirs !== null && dirs.isLinkedWorktree;\n }\n\n /**\n * git's two dir answers for `startDir`, memoized — null when it is not a git repo / git is\n * unavailable.\n *\n * PUBLIC because TREE IDENTITY is decided from these two strings and nothing else. `commonDir`\n * is the same for every checkout of ONE repo, so `commonDir(a) === commonDir(b)` is \"same repo,\n * different placement\" — the test that tells a linked worktree (ours, wherever it sits, including\n * inside the repo at `.claude/worktrees/**`) from a nested clone under `repositories/**` (not\n * ours). `gitDirs.isLinkedWorktree` then separates primary from linked. See\n * `EffectiveTreeResolver.classify`, the caller that runs this on the hook's blocking path, which is\n * why it goes through this cache rather than spawning its own `rev-parse`.\n */\n gitDirs(startDir: string): GitDirs | null {\n const cached = this.gitDirsByRoot.get(startDir);\n if (cached !== undefined) return cached;\n\n const gitDir = this.revParse(startDir, '--git-dir');\n const commonDir = this.revParse(startDir, '--git-common-dir');\n const dirs = gitDir === null || commonDir === null ? null : new GitDirs(gitDir, commonDir);\n this.gitDirsByRoot.set(startDir, dirs);\n return dirs;\n }\n\n /**\n * The WORKING TREE root containing `startDir` (`git rev-parse --show-toplevel`), memoized, or null\n * when `startDir` is not in a git repo. In a linked worktree this is the WORKTREE's own root, which\n * is exactly what a caller judging \"which checkout am I standing in\" needs.\n *\n * THE ONE tree-root resolver. There used to be three byte-identical `spawnSync … --show-toplevel`\n * copies — this one, `RepoRootFinder`'s and `effective-tree.ts`'s — each commenting that it\n * \"mirrors\" one of the others, and one of those comments was already stale. Both copies are deleted;\n * everything that needs a tree root calls this. Do not add a fourth.\n */\n treeRoot(startDir: string): string | null {\n const cached = this.treeRootByDir.get(startDir);\n if (cached !== undefined) return cached;\n // `status !== 0` IS the expected \"not a repo\" answer (spawnSync does not throw on a non-zero\n // exit), so nothing here swallows a real git crash.\n const root = this.revParse(startDir, '--show-toplevel');\n this.treeRootByDir.set(startDir, root);\n return root;\n }\n\n /**\n * git's own name for this linked worktree — the basename of `<primary>/.git/worktrees/<name>`, and\n * the namespace key under `worktrees/`. Empty for the primary clone. git's name rather than the\n * directory's basename, so two worktrees checked out into same-named directories under different\n * parents cannot collide.\n */\n worktreeName(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return '';\n return path.basename(dirs.gitDir);\n }\n\n /** The primary clone's root, from any worktree. Falls back to git's toplevel-less best guess. */\n primaryRoot(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null) return startDir;\n if (path.basename(dirs.commonDir) !== GIT_DIR_NAME) return startDir;\n const primary = path.dirname(dirs.commonDir);\n return fs.existsSync(primary) ? primary : startDir;\n }\n\n /**\n * The PRE-change location, `<treeRoot>/.webpieces` — what every call site used to compute. Public\n * because the migrator and its specs must be able to name the thing being migrated FROM, and\n * because the transition-window fallback readers need it.\n */\n legacyDir(treeRoot: string): string {\n return path.join(treeRoot, WEBPIECES_TMP_DIR);\n }\n\n // Drain a legacy per-worktree `.webpieces/` into this worktree's namespace, at most once per tree\n // per process. Migration is idempotent, but it touches the filesystem on the hook's blocking path.\n private migrateOnce(startDir: string, target: string): void {\n // Guard on the CHEAP key first. `local()` is called many times per invocation, and resolving the\n // worktree toplevel costs a `git rev-parse` — doing that before the once-check would put a\n // process spawn on the hook's blocking path for every single state-path lookup.\n if (this.migrated.has(startDir)) return;\n this.migrated.add(startDir);\n const toplevel = this.treeRoot(startDir);\n if (toplevel === null) return;\n this.migrator.migrate(this.legacyDir(toplevel), target);\n }\n\n // One `git rev-parse <flag>`, resolved to an absolute path (git prints a bare `.git`, relative to\n // the tree, in the primary clone, and an absolute path from a linked worktree).\n private revParse(cwd: string, flag: string): string | null {\n const result = spawnSync('git', ['-C', cwd, 'rev-parse', flag], { encoding: 'utf8' });\n if (result.status !== 0) return null;\n const printed = (result.stdout ?? '').trim();\n if (printed === '') return null;\n return path.resolve(cwd, printed);\n }\n}\n\n// Process-wide instance for the many non-DI call sites (hooks, detached refreshers, wp-* bins, eslint\n// rules). Sharing one instance is what makes the git-resolution cache and the once-per-tree migration\n// worth having; inversify still injects the singleton wherever a container is in play.\nexport const dotWebpieces = new DotWebpieces();\n"]}
@@ -35,6 +35,14 @@ export declare class WorktreeService {
35
35
  * (a `gitdir:` pointer) where the primary clone has a `.git` DIRECTORY. This runs on the read
36
36
  * path, where reads vastly outnumber every other tool call, so the cost matters.
37
37
  *
38
+ * It is a CHEAP FAST PATH over the authoritative answer, not a second authority. The authority is
39
+ * `DotWebpieces.gitDirs` — `gitDir !== commonDir`, git's own canonical test, which also handles the
40
+ * layouts a `.git` stat cannot see (`--separate-git-dir`, submodules). This is NOT calling it,
41
+ * deliberately: that costs a `rev-parse` spawn per read. `worktree-identity.spec.ts` asserts the two
42
+ * agree for the primary clone, an in-repo `.claude/worktrees/**` worktree and a sibling worktree
43
+ * outside the repo — so if git ever changes the `.git` layout this fails there, not in the field.
44
+ * Anything that needs to be RIGHT rather than cheap (tree identity, state paths) asks `gitDirs`.
45
+ *
38
46
  * Returns FALSE on anything uncertain (no `.git` at all, unreadable, a submodule's `.git` file
39
47
  * in a non-worktree checkout). False is the fail-open direction here: callers then print both
40
48
  * forms rather than confidently printing the wrong one.
package/src/worktrees.js CHANGED
@@ -88,6 +88,14 @@ let WorktreeService = class WorktreeService {
88
88
  * (a `gitdir:` pointer) where the primary clone has a `.git` DIRECTORY. This runs on the read
89
89
  * path, where reads vastly outnumber every other tool call, so the cost matters.
90
90
  *
91
+ * It is a CHEAP FAST PATH over the authoritative answer, not a second authority. The authority is
92
+ * `DotWebpieces.gitDirs` — `gitDir !== commonDir`, git's own canonical test, which also handles the
93
+ * layouts a `.git` stat cannot see (`--separate-git-dir`, submodules). This is NOT calling it,
94
+ * deliberately: that costs a `rev-parse` spawn per read. `worktree-identity.spec.ts` asserts the two
95
+ * agree for the primary clone, an in-repo `.claude/worktrees/**` worktree and a sibling worktree
96
+ * outside the repo — so if git ever changes the `.git` layout this fails there, not in the field.
97
+ * Anything that needs to be RIGHT rather than cheap (tree identity, state paths) asks `gitDirs`.
98
+ *
91
99
  * Returns FALSE on anything uncertain (no `.git` at all, unreadable, a submodule's `.git` file
92
100
  * in a non-worktree checkout). False is the fail-open direction here: callers then print both
93
101
  * forms rather than confidently printing the wrong one.
@@ -1 +1 @@
1
- {"version":3,"file":"worktrees.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/worktrees.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,yCAAqC;AAErC;;;;;;;;;;;GAWG;AAEH,qGAAqG;AACrG,uGAAuG;AACvG,MAAM,YAAY,GAAG,WAAW,CAAC;AACjC,MAAM,UAAU,GAAG,SAAS,CAAC;AAC7B,MAAM,UAAU,GAAG,aAAa,CAAC;AAEjC,+CAA+C;AAC/C,MAAa,QAAQ;IACjB,IAAI,CAAS;IACb,yFAAyF;IACzF,MAAM,CAAS;IACf,8FAA8F;IAC9F,MAAM,CAAU;IAChB,2FAA2F;IAC3F,QAA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,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAC3E,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;YAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC;QAC5F,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;IACnD,CAAC;CACJ,CAAA;AA1HY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,eAAe,CA0H3B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { toError } from './to-error';\n\n/**\n * Reading the git worktree list.\n *\n * WHY this exists separately from merged-branches: a worktree is a SECOND budget. Every worktree holds\n * a branch, so if worktree-held branches also counted against the local-branch cap, five worktrees\n * would consume the entire branch budget and no branch could ever be created again. The two are\n * therefore counted apart — held branches against the worktree cap, parked branches against the branch\n * cap — and this service is what tells the two apart.\n *\n * Unlike the merged-PR lookup, everything here is LOCAL and cheap (one `git worktree list`), so it is\n * safe to call on the guard's blocking path.\n */\n\n// `git worktree list --porcelain` emits blank-line-separated records. The first record is always the\n// main worktree. Keys are space-separated; `detached`, `bare` and `locked` may appear bare (no value).\nconst WORKTREE_KEY = 'worktree ';\nconst BRANCH_KEY = 'branch ';\nconst REFS_HEADS = 'refs/heads/';\n\n// Data-only (per CLAUDE.md, classes for data).\nexport class Worktree {\n path: string;\n // Short branch name (refs/heads/ stripped). Empty when the worktree is detached or bare.\n branch: string;\n // The primary clone — the one that owns .git. Never counted against the cap, never removable.\n isMain: boolean;\n // git already knows this worktree's directory is gone; `git worktree prune` will clear it.\n prunable: boolean;\n // A human ran `git worktree lock`. Explicitly \"do not touch\".\n locked: boolean;\n\n constructor(path: string, branch: string, isMain: boolean, prunable: boolean, locked: boolean) {\n this.path = path;\n this.branch = branch;\n this.isMain = isMain;\n this.prunable = prunable;\n this.locked = locked;\n }\n}\n\n// Result of a captured git invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class WorktreeService {\n /**\n * Every worktree, main one first. Fails SOFT to [] — a repo with no worktree support, or a git\n * that errors, must read as \"no worktrees\" so the cap fails OPEN rather than blocking on data we\n * do not have.\n */\n listWorktrees(repoRoot: string): Worktree[] {\n const result = this.capture(repoRoot, ['worktree', 'list', '--porcelain']);\n if (!result.ok || result.out === '') return [];\n return this.parsePorcelain(result.out);\n }\n\n // The linked worktrees — everything except the primary clone. This is what the cap counts.\n linkedWorktrees(repoRoot: string): Worktree[] {\n return this.listWorktrees(repoRoot).filter((tree: Worktree): boolean => !tree.isMain);\n }\n\n /**\n * Branch names checked out in ANY worktree, including the primary clone's own HEAD.\n *\n * Two callers, one reason: git flatly refuses to delete a branch that is checked out somewhere.\n * A held branch must never be proposed for `git branch -D` (the delete would fail and take the\n * whole reap command down with it), and it must not be counted as a parked branch either.\n */\n heldBranches(repoRoot: string): Set<string> {\n const held = new Set<string>();\n for (const tree of this.listWorktrees(repoRoot)) {\n if (tree.branch !== '') held.add(tree.branch);\n }\n return held;\n }\n\n /**\n * Am I standing in a LINKED worktree (as opposed to the primary clone)?\n *\n * This is the question every recovery message needs, because the two trees take different\n * commands: `git checkout main` fatals inside a linked worktree (\"main is already checked out\n * at <primary>\"), and a dead linked worktree is reaped with `git worktree remove`, not\n * `git branch -d`. A guard that cannot tell them apart must print BOTH forms and let the AI\n * guess — which is exactly how an AI ends up running the fatal one.\n *\n * The test is a single `statSync`, no process spawn: git gives a linked worktree a `.git` FILE\n * (a `gitdir:` pointer) where the primary clone has a `.git` DIRECTORY. This runs on the read\n * path, where reads vastly outnumber every other tool call, so the cost matters.\n *\n * Returns FALSE on anything uncertain (no `.git` at all, unreadable, a submodule's `.git` file\n * in a non-worktree checkout). False is the fail-open direction here: callers then print both\n * forms rather than confidently printing the wrong one.\n */\n isLinkedWorktree(root: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return !fs.statSync(path.join(root, '.git')).isDirectory();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n /**\n * The worktree record for the tree rooted at `root`, or null when it is not one of git's\n * worktrees (or git could not answer). Callers use it to name the exact directory a\n * `git worktree remove` has to take — a reap instruction with the wrong path is worse than none.\n */\n currentWorktree(root: string): Worktree | null {\n const resolved = path.resolve(root);\n for (const tree of this.listWorktrees(root)) {\n if (path.resolve(tree.path) === resolved) return tree;\n }\n return null;\n }\n\n /**\n * Parse the porcelain records. A record starts at a `worktree <path>` line and runs to the blank\n * line; the FIRST record is the main worktree (git guarantees the ordering). A `prunable` worktree\n * still appears in the list, which is exactly why it can be reaped.\n */\n private parsePorcelain(out: string): Worktree[] {\n const trees: Worktree[] = [];\n let path = '';\n let branch = '';\n let prunable = false;\n let locked = false;\n\n const flush = (): void => {\n if (path === '') return;\n trees.push(new Worktree(path, branch, trees.length === 0, prunable, locked));\n path = '';\n branch = '';\n prunable = false;\n locked = false;\n };\n\n for (const raw of out.split('\\n')) {\n const line = raw.trim();\n if (line === '') {\n flush();\n } else if (line.startsWith(WORKTREE_KEY)) {\n // A new record begins — flush the previous one in case the blank line was missing.\n flush();\n path = line.slice(WORKTREE_KEY.length).trim();\n } else if (line.startsWith(BRANCH_KEY)) {\n const ref = line.slice(BRANCH_KEY.length).trim();\n branch = ref.startsWith(REFS_HEADS) ? ref.slice(REFS_HEADS.length) : ref;\n } else if (line === 'prunable' || line.startsWith('prunable ')) {\n prunable = true;\n } else if (line === 'locked' || line.startsWith('locked ')) {\n locked = true;\n }\n }\n flush();\n\n return trees;\n }\n\n // Run a git command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, args: string[]): CmdCapture {\n const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return { ok: false, out: '' };\n return { ok: true, out: result.stdout.trim() };\n }\n}\n"]}
1
+ {"version":3,"file":"worktrees.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/worktrees.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,yCAAqC;AAErC;;;;;;;;;;;GAWG;AAEH,qGAAqG;AACrG,uGAAuG;AACvG,MAAM,YAAY,GAAG,WAAW,CAAC;AACjC,MAAM,UAAU,GAAG,SAAS,CAAC;AAC7B,MAAM,UAAU,GAAG,aAAa,CAAC;AAEjC,+CAA+C;AAC/C,MAAa,QAAQ;IACjB,IAAI,CAAS;IACb,yFAAyF;IACzF,MAAM,CAAS;IACf,8FAA8F;IAC9F,MAAM,CAAU;IAChB,2FAA2F;IAC3F,QAAQ,CAAU;IAClB,8DAA8D;IAC9D,MAAM,CAAU;IAEhB,YAAY,IAAY,EAAE,MAAc,EAAE,MAAe,EAAE,QAAiB,EAAE,MAAe;QACzF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAlBD,4BAkBC;AASM,IAAM,eAAe,GAArB,MAAM,eAAe;IACxB;;;;OAIG;IACH,aAAa,CAAC,QAAgB;QAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC;QAC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'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { toError } from './to-error';\n\n/**\n * Reading the git worktree list.\n *\n * WHY this exists separately from merged-branches: a worktree is a SECOND budget. Every worktree holds\n * a branch, so if worktree-held branches also counted against the local-branch cap, five worktrees\n * would consume the entire branch budget and no branch could ever be created again. The two are\n * therefore counted apart — held branches against the worktree cap, parked branches against the branch\n * cap — and this service is what tells the two apart.\n *\n * Unlike the merged-PR lookup, everything here is LOCAL and cheap (one `git worktree list`), so it is\n * safe to call on the guard's blocking path.\n */\n\n// `git worktree list --porcelain` emits blank-line-separated records. The first record is always the\n// main worktree. Keys are space-separated; `detached`, `bare` and `locked` may appear bare (no value).\nconst WORKTREE_KEY = 'worktree ';\nconst BRANCH_KEY = 'branch ';\nconst REFS_HEADS = 'refs/heads/';\n\n// Data-only (per CLAUDE.md, classes for data).\nexport class Worktree {\n path: string;\n // Short branch name (refs/heads/ stripped). Empty when the worktree is detached or bare.\n branch: string;\n // The primary clone — the one that owns .git. Never counted against the cap, never removable.\n isMain: boolean;\n // git already knows this worktree's directory is gone; `git worktree prune` will clear it.\n prunable: boolean;\n // A human ran `git worktree lock`. Explicitly \"do not touch\".\n locked: boolean;\n\n constructor(path: string, branch: string, isMain: boolean, prunable: boolean, locked: boolean) {\n this.path = path;\n this.branch = branch;\n this.isMain = isMain;\n this.prunable = prunable;\n this.locked = locked;\n }\n}\n\n// Result of a captured git invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class WorktreeService {\n /**\n * Every worktree, main one first. Fails SOFT to [] — a repo with no worktree support, or a git\n * that errors, must read as \"no worktrees\" so the cap fails OPEN rather than blocking on data we\n * do not have.\n */\n listWorktrees(repoRoot: string): Worktree[] {\n const result = this.capture(repoRoot, ['worktree', 'list', '--porcelain']);\n if (!result.ok || result.out === '') return [];\n return this.parsePorcelain(result.out);\n }\n\n // The linked worktrees — everything except the primary clone. This is what the cap counts.\n linkedWorktrees(repoRoot: string): Worktree[] {\n return this.listWorktrees(repoRoot).filter((tree: Worktree): boolean => !tree.isMain);\n }\n\n /**\n * Branch names checked out in ANY worktree, including the primary clone's own HEAD.\n *\n * Two callers, one reason: git flatly refuses to delete a branch that is checked out somewhere.\n * A held branch must never be proposed for `git branch -D` (the delete would fail and take the\n * whole reap command down with it), and it must not be counted as a parked branch either.\n */\n heldBranches(repoRoot: string): Set<string> {\n const held = new Set<string>();\n for (const tree of this.listWorktrees(repoRoot)) {\n if (tree.branch !== '') held.add(tree.branch);\n }\n return held;\n }\n\n /**\n * Am I standing in a LINKED worktree (as opposed to the primary clone)?\n *\n * This is the question every recovery message needs, because the two trees take different\n * commands: `git checkout main` fatals inside a linked worktree (\"main is already checked out\n * at <primary>\"), and a dead linked worktree is reaped with `git worktree remove`, not\n * `git branch -d`. A guard that cannot tell them apart must print BOTH forms and let the AI\n * guess — which is exactly how an AI ends up running the fatal one.\n *\n * The test is a single `statSync`, no process spawn: git gives a linked worktree a `.git` FILE\n * (a `gitdir:` pointer) where the primary clone has a `.git` DIRECTORY. This runs on the read\n * path, where reads vastly outnumber every other tool call, so the cost matters.\n *\n * It is a CHEAP FAST PATH over the authoritative answer, not a second authority. The authority is\n * `DotWebpieces.gitDirs` — `gitDir !== commonDir`, git's own canonical test, which also handles the\n * layouts a `.git` stat cannot see (`--separate-git-dir`, submodules). This is NOT calling it,\n * deliberately: that costs a `rev-parse` spawn per read. `worktree-identity.spec.ts` asserts the two\n * agree for the primary clone, an in-repo `.claude/worktrees/**` worktree and a sibling worktree\n * outside the repo — so if git ever changes the `.git` layout this fails there, not in the field.\n * Anything that needs to be RIGHT rather than cheap (tree identity, state paths) asks `gitDirs`.\n *\n * Returns FALSE on anything uncertain (no `.git` at all, unreadable, a submodule's `.git` file\n * in a non-worktree checkout). False is the fail-open direction here: callers then print both\n * forms rather than confidently printing the wrong one.\n */\n isLinkedWorktree(root: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return !fs.statSync(path.join(root, '.git')).isDirectory();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n /**\n * The worktree record for the tree rooted at `root`, or null when it is not one of git's\n * worktrees (or git could not answer). Callers use it to name the exact directory a\n * `git worktree remove` has to take — a reap instruction with the wrong path is worse than none.\n */\n currentWorktree(root: string): Worktree | null {\n const resolved = path.resolve(root);\n for (const tree of this.listWorktrees(root)) {\n if (path.resolve(tree.path) === resolved) return tree;\n }\n return null;\n }\n\n /**\n * Parse the porcelain records. A record starts at a `worktree <path>` line and runs to the blank\n * line; the FIRST record is the main worktree (git guarantees the ordering). A `prunable` worktree\n * still appears in the list, which is exactly why it can be reaped.\n */\n private parsePorcelain(out: string): Worktree[] {\n const trees: Worktree[] = [];\n let path = '';\n let branch = '';\n let prunable = false;\n let locked = false;\n\n const flush = (): void => {\n if (path === '') return;\n trees.push(new Worktree(path, branch, trees.length === 0, prunable, locked));\n path = '';\n branch = '';\n prunable = false;\n locked = false;\n };\n\n for (const raw of out.split('\\n')) {\n const line = raw.trim();\n if (line === '') {\n flush();\n } else if (line.startsWith(WORKTREE_KEY)) {\n // A new record begins — flush the previous one in case the blank line was missing.\n flush();\n path = line.slice(WORKTREE_KEY.length).trim();\n } else if (line.startsWith(BRANCH_KEY)) {\n const ref = line.slice(BRANCH_KEY.length).trim();\n branch = ref.startsWith(REFS_HEADS) ? ref.slice(REFS_HEADS.length) : ref;\n } else if (line === 'prunable' || line.startsWith('prunable ')) {\n prunable = true;\n } else if (line === 'locked' || line.startsWith('locked ')) {\n locked = true;\n }\n }\n flush();\n\n return trees;\n }\n\n // Run a git command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, args: string[]): CmdCapture {\n const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return { ok: false, out: '' };\n return { ok: true, out: result.stdout.trim() };\n }\n}\n"]}