@webpieces/rules-config 0.4.518 → 0.4.520

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.
@@ -8,33 +8,60 @@ const tslib_1 = require("tslib");
8
8
  const fs = tslib_1.__importStar(require("fs"));
9
9
  const path = tslib_1.__importStar(require("path"));
10
10
  const inversify_1 = require("inversify");
11
+ const atomic_file_1 = require("./atomic-file");
12
+ const repo_root_1 = require("./repo-root");
13
+ const state_dir_1 = require("./state-dir");
11
14
  const TEMPLATES_DIR = path.join(__dirname, '..', 'templates');
12
- const DEFAULT_INSTRUCT_DIR = '.webpieces/instruct-ai';
15
+ // Sentinel for "use the resolved LOCAL instruct-ai dir". Kept as the parameter default so the handful
16
+ // of callers that pass an explicit relative dir (they join it onto workspaceRoot themselves) are
17
+ // unaffected; anything passing the default gets DotWebpieces.local() resolution.
18
+ const DEFAULT_INSTRUCT_DIR = '';
13
19
  /**
14
20
  * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.
15
21
  * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.
16
22
  */
17
23
  let TemplateWriter = class TemplateWriter {
24
+ dotDir;
25
+ atomicFile;
26
+ constructor(dotDir = state_dir_1.dotWebpieces, atomicFile = new atomic_file_1.AtomicFile()) {
27
+ this.dotDir = dotDir;
28
+ this.atomicFile = atomicFile;
29
+ }
18
30
  loadTemplate(name) {
19
31
  return fs.readFileSync(path.join(TEMPLATES_DIR, name), 'utf-8');
20
32
  }
21
33
  writeTemplateIfMissing(workspaceRoot, name, instructDir = DEFAULT_INSTRUCT_DIR) {
22
- const dest = path.join(workspaceRoot, instructDir, name);
34
+ const dest = this.destination(workspaceRoot, name, instructDir);
23
35
  if (fs.existsSync(dest))
24
36
  return;
25
- fs.mkdirSync(path.dirname(dest), { recursive: true });
26
- fs.writeFileSync(dest, this.loadTemplate(name), 'utf-8');
37
+ this.atomicFile.writeAtomic(dest, this.loadTemplate(name));
27
38
  }
39
+ /**
40
+ * Rewrite the doc, ATOMICALLY and only when its bytes actually changed.
41
+ *
42
+ * Every `wp-*` command regenerates these, and the AI is routinely told to open one by absolute
43
+ * path. A plain truncating write means a reader can catch it empty; skip-if-unchanged means the
44
+ * overwhelmingly common case (same package version ⇒ identical content) does not write at all.
45
+ */
28
46
  writeTemplate(workspaceRoot, name, instructDir = DEFAULT_INSTRUCT_DIR) {
29
- const dest = path.join(workspaceRoot, instructDir, name);
30
- fs.mkdirSync(path.dirname(dest), { recursive: true });
31
- fs.writeFileSync(dest, this.loadTemplate(name), 'utf-8');
47
+ const dest = this.destination(workspaceRoot, name, instructDir);
48
+ this.atomicFile.writeIfChanged(dest, this.loadTemplate(name));
32
49
  return dest;
33
50
  }
51
+ // LOCAL `.webpieces/instruct-ai/<name>` by default; an explicitly-passed relative dir is still
52
+ // joined onto workspaceRoot exactly as before.
53
+ destination(workspaceRoot, name, instructDir) {
54
+ if (instructDir === DEFAULT_INSTRUCT_DIR) {
55
+ return this.dotDir.localFile(workspaceRoot, repo_root_1.INSTRUCT_AI_LEAF, name);
56
+ }
57
+ return path.join(workspaceRoot, instructDir, name);
58
+ }
34
59
  };
35
60
  exports.TemplateWriter = TemplateWriter;
36
61
  exports.TemplateWriter = TemplateWriter = tslib_1.__decorate([
37
- (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
62
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
63
+ tslib_1.__metadata("design:paramtypes", [state_dir_1.DotWebpieces,
64
+ atomic_file_1.AtomicFile])
38
65
  ], TemplateWriter);
39
66
  // Temporary migration delegators — consumers migrate to injecting TemplateWriter over follow-up PRs.
40
67
  const templateWriterSvc = new TemplateWriter();
@@ -1 +1 @@
1
- {"version":3,"file":"load-template.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-template.ts"],"names":[],"mappings":";;;AAmCA,oCAEC;AAED,wDAMC;AAED,sCAMC;;AArDD,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Ac;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,cAAc,CAkB1B;AAED,qGAAqG;AACrG,MAAM,iBAAiB,GAAG,IAAI,cAAc,EAAE,CAAC;AAE/C,SAAgB,YAAY,CAAC,IAAY;IACrC,OAAO,iBAAiB,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC;AAED,SAAgB,sBAAsB,CAClC,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,iBAAiB,CAAC,sBAAsB,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC/E,CAAC;AAED,SAAgB,aAAa,CACzB,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,OAAO,iBAAiB,CAAC,aAAa,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst TEMPLATES_DIR = path.join(__dirname, '..', 'templates');\nconst DEFAULT_INSTRUCT_DIR = '.webpieces/instruct-ai';\n\n/**\n * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.\n * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class TemplateWriter {\n loadTemplate(name: string): string {\n return fs.readFileSync(path.join(TEMPLATES_DIR, name), 'utf-8');\n }\n\n writeTemplateIfMissing(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): void {\n const dest = path.join(workspaceRoot, instructDir, name);\n if (fs.existsSync(dest)) return;\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, this.loadTemplate(name), 'utf-8');\n }\n\n writeTemplate(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): string {\n const dest = path.join(workspaceRoot, instructDir, name);\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, this.loadTemplate(name), 'utf-8');\n return dest;\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting TemplateWriter over follow-up PRs.\nconst templateWriterSvc = new TemplateWriter();\n\nexport function loadTemplate(name: string): string {\n return templateWriterSvc.loadTemplate(name);\n}\n\nexport function writeTemplateIfMissing(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): void {\n templateWriterSvc.writeTemplateIfMissing(workspaceRoot, name, instructDir);\n}\n\nexport function writeTemplate(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): string {\n return templateWriterSvc.writeTemplate(workspaceRoot, name, instructDir);\n}\n"]}
1
+ {"version":3,"file":"load-template.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-template.ts"],"names":[],"mappings":";;;AA6DA,oCAEC;AAED,wDAMC;AAED,sCAMC;;AA/ED,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,+CAA2C;AAC3C,2CAA+C;AAC/C,2CAAyD;AAEzD,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC9D,sGAAsG;AACtG,iGAAiG;AACjG,iFAAiF;AACjF,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC;;;GAGG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAEF;IACA;IAFrB,YACqB,SAAuB,wBAAY,EACnC,aAAyB,IAAI,wBAAU,EAAE;QADzC,WAAM,GAAN,MAAM,CAA6B;QACnC,eAAU,GAAV,UAAU,CAA+B;IAC3D,CAAC;IAEJ,YAAY,CAAC,IAAY;QACrB,OAAO,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;IACpE,CA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CAAC,CAAC;AAChD,CAAC;AAED,SAAgB,sBAAsB,CAClC,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,iBAAiB,CAAC,sBAAsB,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC/E,CAAC;AAED,SAAgB,aAAa,CACzB,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,OAAO,iBAAiB,CAAC,aAAa,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from './atomic-file';\nimport { INSTRUCT_AI_LEAF } from './repo-root';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\n\nconst TEMPLATES_DIR = path.join(__dirname, '..', 'templates');\n// Sentinel for \"use the resolved LOCAL instruct-ai dir\". Kept as the parameter default so the handful\n// of callers that pass an explicit relative dir (they join it onto workspaceRoot themselves) are\n// unaffected; anything passing the default gets DotWebpieces.local() resolution.\nconst DEFAULT_INSTRUCT_DIR = '';\n\n/**\n * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.\n * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class TemplateWriter {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n ) {}\n\n loadTemplate(name: string): string {\n return fs.readFileSync(path.join(TEMPLATES_DIR, name), 'utf-8');\n }\n\n writeTemplateIfMissing(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): void {\n const dest = this.destination(workspaceRoot, name, instructDir);\n if (fs.existsSync(dest)) return;\n this.atomicFile.writeAtomic(dest, this.loadTemplate(name));\n }\n\n /**\n * Rewrite the doc, ATOMICALLY and only when its bytes actually changed.\n *\n * Every `wp-*` command regenerates these, and the AI is routinely told to open one by absolute\n * path. A plain truncating write means a reader can catch it empty; skip-if-unchanged means the\n * overwhelmingly common case (same package version ⇒ identical content) does not write at all.\n */\n writeTemplate(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): string {\n const dest = this.destination(workspaceRoot, name, instructDir);\n this.atomicFile.writeIfChanged(dest, this.loadTemplate(name));\n return dest;\n }\n\n // LOCAL `.webpieces/instruct-ai/<name>` by default; an explicitly-passed relative dir is still\n // joined onto workspaceRoot exactly as before.\n private destination(workspaceRoot: string, name: string, instructDir: string): string {\n if (instructDir === DEFAULT_INSTRUCT_DIR) {\n return this.dotDir.localFile(workspaceRoot, INSTRUCT_AI_LEAF, name);\n }\n return path.join(workspaceRoot, instructDir, name);\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting TemplateWriter over follow-up PRs.\nconst templateWriterSvc = new TemplateWriter();\n\nexport function loadTemplate(name: string): string {\n return templateWriterSvc.loadTemplate(name);\n}\n\nexport function writeTemplateIfMissing(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): void {\n templateWriterSvc.writeTemplateIfMissing(workspaceRoot, name, instructDir);\n}\n\nexport function writeTemplate(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): string {\n return templateWriterSvc.writeTemplate(workspaceRoot, name, instructDir);\n}\n"]}
@@ -1,3 +1,5 @@
1
+ import { AtomicFile } from './atomic-file';
2
+ import { DotWebpieces } from './state-dir';
1
3
  export declare const DEFAULT_HANG_TIMEOUT_MINUTES = 5;
2
4
  export declare class MainSyncStatus {
3
5
  branch: string;
@@ -25,9 +27,48 @@ export declare class MainSyncLock {
25
27
  * status. `@injectable(bindingScopeValues.Singleton)` so it's injectable and drawn in the rules-config DI design.
26
28
  */
27
29
  export declare class MainSyncStatusService {
30
+ private readonly dotDir;
31
+ private readonly atomicFile;
32
+ constructor(dotDir?: DotWebpieces, atomicFile?: AtomicFile);
33
+ /**
34
+ * SHARED scope: `<primary>/.webpieces/main-sync-status.json`, one per repo.
35
+ *
36
+ * It is the OUTPUT of the single-flight refresher below, so it has to live where the lock lives —
37
+ * one `.git`, one `origin/main`, one fetch, one answer. A per-worktree copy under single-flight
38
+ * would only ever be written for whichever worktree won the lock anyway.
39
+ *
40
+ * KNOWN CONSEQUENCE, stated plainly rather than discovered later: the file's CONTENT is keyed to
41
+ * one branch (`branch`, `featureHead`, `conflict`, `conflictFiles`), and every reader fails OPEN
42
+ * when the cached branch is not the branch being judged (`merged-branch-bash-guard` and
43
+ * `stale-main-bash-guard` both log `stale-cross-branch-cache (fail-open)`). With several worktrees
44
+ * on several branches, the losers of the lock therefore see a cross-branch cache and their guards
45
+ * allow rather than block. That is the fail-SAFE direction and it is inherent to single-flight, not
46
+ * to the shared path — but making the entries branch-keyed (a map of branch → status, written
47
+ * atomically) is the obvious follow-up.
48
+ */
28
49
  mainSyncStatusPath(repoRoot: string): string;
50
+ /**
51
+ * SHARED scope — the single-flight lock for the whole repo.
52
+ *
53
+ * This is the fix for the filed bug "the detached main-sync refresher's `git fetch` races the
54
+ * agent's foreground `git fetch`/`git pull` and corrupts `.git/FETCH_HEAD`". The lock was already
55
+ * atomic (O_CREAT|O_EXCL) and already serialised refreshers against each other — but only WITHIN
56
+ * one worktree, so N worktrees meant N locks and up to N concurrent `git fetch`es against the ONE
57
+ * shared `.git`, which is exactly how a duplicate `for-merge` line lands in FETCH_HEAD. There is
58
+ * one `.git`, so there is now one lock: at most one refresher in flight across all worktrees.
59
+ *
60
+ * Stale-lock handling is unchanged and still required (a lock nobody can clear is worse than the
61
+ * race): the holder records pid + start epoch, and `tryAcquireMainSyncLock` reclaims it once
62
+ * `isRefreshInProgress` proves the holder is finished, hung past hangTimeoutMinutes, or dead.
63
+ */
29
64
  mainSyncLockPath(repoRoot: string): string;
30
65
  readMainSyncStatus(repoRoot: string): MainSyncStatus | null;
66
+ /**
67
+ * ATOMIC write (temp file + `rename()` in the same directory). The refresher writes this file while
68
+ * guards on the blocking path read it; a plain `writeFileSync` truncates first, so a reader landing
69
+ * in that window gets a torn document. Now that the file is repo-wide the reader may be in another
70
+ * worktree entirely, which widens the window rather than creating it. See AtomicFile.
71
+ */
31
72
  writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void;
32
73
  readMainSyncLock(repoRoot: string): MainSyncLock | null;
33
74
  writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void;
@@ -20,7 +20,8 @@ const child_process_1 = require("child_process");
20
20
  const fs = tslib_1.__importStar(require("fs"));
21
21
  const path = tslib_1.__importStar(require("path"));
22
22
  const inversify_1 = require("inversify");
23
- const constants_1 = require("./constants");
23
+ const atomic_file_1 = require("./atomic-file");
24
+ const state_dir_1 = require("./state-dir");
24
25
  const to_error_1 = require("./to-error");
25
26
  // Shared "is my feature branch healthy relative to origin/main?" state. The SLOW signals (git fetch +
26
27
  // merge-base + same-file-overlap + a merged-PR lookup) are computed by the ai-hook-rules refresher in a
@@ -83,11 +84,47 @@ exports.MainSyncLock = MainSyncLock;
83
84
  * status. `@injectable(bindingScopeValues.Singleton)` so it's injectable and drawn in the rules-config DI design.
84
85
  */
85
86
  let MainSyncStatusService = class MainSyncStatusService {
87
+ dotDir;
88
+ atomicFile;
89
+ constructor(dotDir = state_dir_1.dotWebpieces, atomicFile = new atomic_file_1.AtomicFile()) {
90
+ this.dotDir = dotDir;
91
+ this.atomicFile = atomicFile;
92
+ }
93
+ /**
94
+ * SHARED scope: `<primary>/.webpieces/main-sync-status.json`, one per repo.
95
+ *
96
+ * It is the OUTPUT of the single-flight refresher below, so it has to live where the lock lives —
97
+ * one `.git`, one `origin/main`, one fetch, one answer. A per-worktree copy under single-flight
98
+ * would only ever be written for whichever worktree won the lock anyway.
99
+ *
100
+ * KNOWN CONSEQUENCE, stated plainly rather than discovered later: the file's CONTENT is keyed to
101
+ * one branch (`branch`, `featureHead`, `conflict`, `conflictFiles`), and every reader fails OPEN
102
+ * when the cached branch is not the branch being judged (`merged-branch-bash-guard` and
103
+ * `stale-main-bash-guard` both log `stale-cross-branch-cache (fail-open)`). With several worktrees
104
+ * on several branches, the losers of the lock therefore see a cross-branch cache and their guards
105
+ * allow rather than block. That is the fail-SAFE direction and it is inherent to single-flight, not
106
+ * to the shared path — but making the entries branch-keyed (a map of branch → status, written
107
+ * atomically) is the obvious follow-up.
108
+ */
86
109
  mainSyncStatusPath(repoRoot) {
87
- return path.join(repoRoot, constants_1.WEBPIECES_TMP_DIR, MAIN_SYNC_STATUS_FILE);
110
+ return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_STATUS_FILE);
88
111
  }
112
+ /**
113
+ * SHARED scope — the single-flight lock for the whole repo.
114
+ *
115
+ * This is the fix for the filed bug "the detached main-sync refresher's `git fetch` races the
116
+ * agent's foreground `git fetch`/`git pull` and corrupts `.git/FETCH_HEAD`". The lock was already
117
+ * atomic (O_CREAT|O_EXCL) and already serialised refreshers against each other — but only WITHIN
118
+ * one worktree, so N worktrees meant N locks and up to N concurrent `git fetch`es against the ONE
119
+ * shared `.git`, which is exactly how a duplicate `for-merge` line lands in FETCH_HEAD. There is
120
+ * one `.git`, so there is now one lock: at most one refresher in flight across all worktrees.
121
+ *
122
+ * Stale-lock handling is unchanged and still required (a lock nobody can clear is worse than the
123
+ * race): the holder records pid + start epoch, and `tryAcquireMainSyncLock` reclaims it once
124
+ * `isRefreshInProgress` proves the holder is finished, hung past hangTimeoutMinutes, or dead.
125
+ */
89
126
  mainSyncLockPath(repoRoot) {
90
- return path.join(repoRoot, constants_1.WEBPIECES_TMP_DIR, MAIN_SYNC_LOCK_FILE);
127
+ return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_LOCK_FILE);
91
128
  }
92
129
  // Pure read — any error (missing file, malformed JSON) returns null so the guard fails OPEN.
93
130
  readMainSyncStatus(repoRoot) {
@@ -108,10 +145,14 @@ let MainSyncStatusService = class MainSyncStatusService {
108
145
  return null;
109
146
  }
110
147
  }
148
+ /**
149
+ * ATOMIC write (temp file + `rename()` in the same directory). The refresher writes this file while
150
+ * guards on the blocking path read it; a plain `writeFileSync` truncates first, so a reader landing
151
+ * in that window gets a torn document. Now that the file is repo-wide the reader may be in another
152
+ * worktree entirely, which widens the window rather than creating it. See AtomicFile.
153
+ */
111
154
  writeMainSyncStatus(repoRoot, status) {
112
- const statusPath = this.mainSyncStatusPath(repoRoot);
113
- this.ensureDir(statusPath);
114
- fs.writeFileSync(statusPath, JSON.stringify(status, null, 2) + '\n');
155
+ this.atomicFile.writeJsonAtomic(this.mainSyncStatusPath(repoRoot), status);
115
156
  }
116
157
  readMainSyncLock(repoRoot) {
117
158
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
@@ -391,7 +432,9 @@ let MainSyncStatusService = class MainSyncStatusService {
391
432
  };
392
433
  exports.MainSyncStatusService = MainSyncStatusService;
393
434
  exports.MainSyncStatusService = MainSyncStatusService = tslib_1.__decorate([
394
- (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
435
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
436
+ tslib_1.__metadata("design:paramtypes", [state_dir_1.DotWebpieces,
437
+ atomic_file_1.AtomicFile])
395
438
  ], MainSyncStatusService);
396
439
  // Temporary migration delegators to MainSyncStatusService — removed once consumers inject it.
397
440
  const mainSyncSvc = new MainSyncStatusService();
@@ -1 +1 @@
1
- {"version":3,"file":"main-sync-status.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/main-sync-status.ts"],"names":[],"mappings":";;;AAidA,gDAAiH;AAEjH,4CAA6G;AAE7G,gDAAgI;AAEhI,kDAA0I;AAE1I,4CAA0H;AAE1H,8CAAgI;AAEhI,kCAAiL;AAEjL,kDAAmM;AAEnM,wDAAqP;AAErP,sCAAgJ;AAEhJ,oCAAyG;AAEzG,sDAA+H;AAE/H,kDAA+H;AAE/H,4DAAoH;;AA3epH,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC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P,4IAA4I;AAC5I,SAAgB,aAAa,CAAC,MAAc,IAAI,CAAC,GAAG,EAAE,EAAE,MAAc,OAAO,CAAC,GAAG,IAAkB,OAAO,WAAW,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAChJ,4IAA4I;AAC5I,SAAgB,YAAY,CAAC,OAAe,IAAkB,OAAO,WAAW,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AACzG,4IAA4I;AAC5I,SAAgB,qBAAqB,CAAC,QAAgB,IAAoB,OAAO,WAAW,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,mBAAmB,CAAC,aAAqB,IAAc,OAAO,WAAW,CAAC,mBAAmB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,wBAAwB,CAAC,QAAgB,IAAU,WAAW,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAC,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 { toError } from './to-error';\n\n// Shared \"is my feature branch healthy relative to origin/main?\" state. The SLOW signals (git fetch +\n// merge-base + same-file-overlap + a merged-PR lookup) are computed by the ai-hook-rules refresher in a\n// DETACHED background process; the feature-branch-guard only READS this cached file. pr-gate's merge\n// flow also writes it synchronously after a merge. Lives here (the shared dep of both).\n\n// How long an `inprocess` refresher lock may sit before a new refresher assumes the prior run hung.\nexport const DEFAULT_HANG_TIMEOUT_MINUTES = 5;\n\nconst MAIN_SYNC_STATUS_FILE = 'main-sync-status.json';\nconst MAIN_SYNC_LOCK_FILE = 'main-sync.lock.json';\n\nconst LOCK_STATE_INPROCESS = 'inprocess';\nconst LOCK_STATE_FINISHED = 'finished';\n\n// Data-only (per CLAUDE.md, classes for data).\nexport class MainSyncStatus {\n branch: string;\n branchAlreadyMerged: boolean;\n mergedPr: string;\n hasForkPoint: boolean;\n forkPoint: string | null;\n originMain: string;\n featureHead: string;\n conflict: boolean;\n conflictFiles: string[];\n timestamp: string;\n // An OPEN (not merged) PR tracking this branch, if any — '' = none or not-yet-known. Advisory.\n // Kept OUT of the positional constructor (a defaulted field) so existing call sites don't churn.\n openPr: string = '';\n // The LOCAL refs/heads/main hash — '' = main does not exist locally (fresh clone / worktree) or\n // could not be read. Paired with `originMain`, this is what tells the read-stale-guard whether a\n // checked-out `main` is behind its remote. Defaulted field for the same reason as `openPr`.\n localMain: string = '';\n\n constructor(\n branch: string,\n branchAlreadyMerged: boolean,\n mergedPr: string,\n hasForkPoint: boolean,\n forkPoint: string | null,\n originMain: string,\n featureHead: string,\n conflict: boolean,\n conflictFiles: string[],\n timestamp: string,\n ) {\n this.branch = branch;\n this.branchAlreadyMerged = branchAlreadyMerged;\n this.mergedPr = mergedPr;\n this.hasForkPoint = hasForkPoint;\n this.forkPoint = forkPoint;\n this.originMain = originMain;\n this.featureHead = featureHead;\n this.conflict = conflict;\n this.conflictFiles = conflictFiles;\n this.timestamp = timestamp;\n }\n}\n\n// Concurrency state machine for the detached refresher. `started` is epoch ms. `pid` is the refresher\n// process's pid (0 = unknown) — used so a KILLED refresher doesn't wedge `inprocess` for the timeout.\nexport class MainSyncLock {\n state: string;\n started: number;\n pid: number;\n\n constructor(state: string, started: number, pid: number = 0) {\n this.state = state;\n this.started = started;\n this.pid = pid;\n }\n}\n\n// Raw JSON shapes for the cast at the parse boundary.\ninterface RawStatus {\n branch?: string;\n branchAlreadyMerged?: boolean;\n mergedPr?: string;\n hasForkPoint?: boolean;\n forkPoint?: string | null;\n originMain?: string;\n featureHead?: string;\n conflict?: boolean;\n conflictFiles?: string[];\n timestamp?: string;\n openPr?: string;\n localMain?: string;\n}\n\ninterface RawLock {\n state?: string;\n started?: number;\n pid?: number;\n}\n\n// Result of a captured git/gh invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n/**\n * Reads/writes the main-sync cache + lock and computes the slow \"is my branch healthy vs origin/main?\"\n * status. `@injectable(bindingScopeValues.Singleton)` so it's injectable and drawn in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class MainSyncStatusService {\n mainSyncStatusPath(repoRoot: string): string {\n return path.join(repoRoot, WEBPIECES_TMP_DIR, MAIN_SYNC_STATUS_FILE);\n }\n\n mainSyncLockPath(repoRoot: string): string {\n return path.join(repoRoot, WEBPIECES_TMP_DIR, MAIN_SYNC_LOCK_FILE);\n }\n\n // Pure read — any error (missing file, malformed JSON) returns null so the guard fails OPEN.\n readMainSyncStatus(repoRoot: string): MainSyncStatus | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const statusPath = this.mainSyncStatusPath(repoRoot);\n if (!fs.existsSync(statusPath)) return null;\n const raw = JSON.parse(fs.readFileSync(statusPath, 'utf8')) as RawStatus;\n const status = new MainSyncStatus(\n raw.branch ?? '',\n raw.branchAlreadyMerged ?? false,\n raw.mergedPr ?? '',\n raw.hasForkPoint ?? true,\n raw.forkPoint ?? null,\n raw.originMain ?? '',\n raw.featureHead ?? '',\n raw.conflict ?? false,\n raw.conflictFiles ?? [],\n raw.timestamp ?? '',\n );\n status.openPr = raw.openPr ?? '';\n status.localMain = raw.localMain ?? '';\n return status;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void {\n const statusPath = this.mainSyncStatusPath(repoRoot);\n this.ensureDir(statusPath);\n fs.writeFileSync(statusPath, JSON.stringify(status, null, 2) + '\\n');\n }\n\n readMainSyncLock(repoRoot: string): MainSyncLock | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const lockPath = this.mainSyncLockPath(repoRoot);\n if (!fs.existsSync(lockPath)) return null;\n const raw = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as RawLock;\n return new MainSyncLock(raw.state ?? LOCK_STATE_FINISHED, raw.started ?? 0, raw.pid ?? 0);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\\n');\n }\n\n // A lock is stale (prior refresher assumed hung) once `inprocess` longer than hangTimeoutMinutes.\n isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n return now - lock.started > hangTimeoutMinutes * 60 * 1000;\n }\n\n // True when another refresher is actively running and we should NOT start a second one.\n isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n const lock = this.readMainSyncLock(repoRoot);\n if (!lock) return false;\n if (lock.state !== LOCK_STATE_INPROCESS) return false;\n if (this.isLockStale(lock, hangTimeoutMinutes, now)) return false;\n return this.isProcessAlive(lock.pid);\n }\n\n /**\n * ATOMICALLY take the refresher lock. Returns the held lock, or null when someone else holds it.\n *\n * Replaces the check-then-write pair (`isRefreshInProgress` then `writeMainSyncLock`), whose gap\n * let two detached refreshers both pass the check and then both run `git fetch` at once — the\n * concurrency this lock exists to prevent. The create uses the `wx` flag (O_CREAT|O_EXCL), so of\n * N racing refreshers exactly one creates the file.\n *\n * A lock file left behind by a FINISHED, hung, or killed refresher is reclaimed: we only unlink\n * and re-take it once `isRefreshInProgress` says the holder is provably not running, and we\n * re-read afterwards to confirm the entry we see is ours before claiming the lock.\n */\n tryAcquireMainSyncLock(\n repoRoot: string,\n hangTimeoutMinutes: number,\n now: number = Date.now(),\n pid: number = process.pid,\n ): MainSyncLock | null {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n const lock = this.inProcessLock(now, pid);\n const payload = JSON.stringify(lock, null, 2) + '\\n';\n\n if (this.createExclusive(lockPath, payload)) return lock;\n\n // The file already exists. Leave it alone while a live refresher owns it.\n if (this.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now)) return null;\n\n // Reclaim it: remove the dead entry, then re-take it exclusively so only one reclaimer wins.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.unlinkSync(lockPath);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // someone else reclaimed it first — the exclusive create below decides\n }\n if (!this.createExclusive(lockPath, payload)) return null;\n\n // Confirm the lock on disk is OURS (a simultaneous reclaimer could have unlinked ours and\n // written its own between the two calls above).\n const held = this.readMainSyncLock(repoRoot);\n if (!held || held.pid !== pid || held.started !== lock.started) return null;\n return lock;\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(lockPath: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(lockPath, payload, { flag: 'wx' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_INPROCESS, now, pid);\n }\n\n finishedLock(started: number): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_FINISHED, started, 0);\n }\n\n /**\n * The SLOW path, run only inside the detached refresher. Computes every cached signal the\n * feature-branch-guard needs. Never run on the hook's blocking path.\n */\n // webpieces-disable max-lines-new-methods -- one cohesive slow-path computation\n computeMainSyncStatus(repoRoot: string): MainSyncStatus {\n const branch = this.gitBranch(repoRoot);\n const mergedPr = this.detectMergedPr(repoRoot, branch);\n const openPr = this.detectOpenPr(repoRoot, branch);\n\n // Best-effort network refresh; offline just means we evaluate against the last-fetched ref.\n this.fetchOriginMain(repoRoot);\n\n const head = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const localMain = this.localMainHash(repoRoot);\n const featureHead = head.ok ? head.out : '';\n if (!head.ok || !originMain.ok) {\n const status = this.benignStatus(branch, featureHead);\n status.branchAlreadyMerged = mergedPr !== '';\n status.mergedPr = mergedPr;\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n const forkPoint = this.capture(repoRoot, 'git', ['merge-base', 'origin/main', 'HEAD']);\n if (!forkPoint.ok || forkPoint.out === '') {\n const noFork = new MainSyncStatus(branch, mergedPr !== '', mergedPr, false, null, originMain.out, featureHead, false, [], new Date().toISOString());\n noFork.openPr = openPr;\n noFork.localMain = localMain;\n return noFork;\n }\n\n const featureFiles = new Set(this.featureChangedFiles(repoRoot, forkPoint.out));\n const mainFiles = this.changedFiles(repoRoot, forkPoint.out, 'origin/main');\n const conflictFiles = mainFiles.filter((file: string): boolean => featureFiles.has(file));\n\n const status = new MainSyncStatus(\n branch,\n mergedPr !== '',\n mergedPr,\n true,\n forkPoint.out,\n originMain.out,\n featureHead,\n conflictFiles.length > 0,\n conflictFiles,\n new Date().toISOString(),\n );\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n // The recovery steps when there is no fork point with origin/main (a bad merge of main into branch).\n squashRecoverySteps(currentBranch: string): string[] {\n return [\n '1. Fetch latest main: git fetch origin main',\n `2. New branch off origin/main: git checkout -b ${currentBranch}-v2 origin/main`,\n `3. Squash-merge old branch: git merge --squash ${currentBranch}`,\n ' ^^ HUMAN-ONLY. `git merge` is blocked for AI (redirect-how-to-merge-main). AI: ask the',\n ' human to run step 3, and warn them it is a raw merge — only correct here because the',\n ' branch is already broken. For a normal update from main they should push back and',\n ' tell you to use the gated 3-point merge instead: `pnpm wp-start-update` (paired with',\n ' `pnpm wp-finish-update`) when no PR is open, or `pnpm wp-start-upsert-pr` (paired with',\n ' `pnpm wp-finish-upsert-pr`) when a PR IS open — a PR MUST use the upsert-pr pair.',\n `4. Commit the squash: git add -A && git commit -m \"Squashed from ${currentBranch}\"`,\n '5. If a PR exists: open a NEW PR for the -v2 branch and close the old one.',\n ];\n }\n\n // Synchronously stamp a clean \"up to date with main\" status — call right after a successful merge.\n stampCleanMainSyncStatus(repoRoot: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const branch = this.gitBranch(repoRoot);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const featureHead = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n if (!originMain.ok || !featureHead.ok) return;\n const status = new MainSyncStatus(\n branch, false, '', true, originMain.out, originMain.out, featureHead.out, false, [], new Date().toISOString(),\n );\n status.localMain = this.localMainHash(repoRoot);\n this.writeMainSyncStatus(repoRoot, status);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Refresh `origin/main` WITHOUT writing `.git/FETCH_HEAD`.\n *\n * WHY the flag is not optional: this runs in a DETACHED background process while the agent is\n * running its own foreground `git fetch` / `git pull` in the very same repo. `.git/FETCH_HEAD` is\n * a single file that git takes no lock on, so two overlapping fetches interleave their writes and\n * can leave the SAME `for-merge` line twice. `git pull` then reads two for-merge entries and dies\n * with `fatal: Cannot fast-forward to multiple branches` — wedging the exact command the\n * read-stale-guard tells the agent to run. `--no-write-fetch-head` (git >= 2.29) still updates the\n * remote-tracking ref, which is all anything downstream reads (`origin/main`, merge-base), so\n * nothing here needs FETCH_HEAD written at all.\n *\n * Older git rejects the flag; only then do we retry the plain form, accepting the old behaviour\n * rather than losing the refresh entirely on a pre-2020 git.\n */\n private fetchOriginMain(repoRoot: string): void {\n const safe = spawnSync('git', ['fetch', '--no-write-fetch-head', 'origin', 'main'], {\n cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'],\n });\n if (safe.status === 0) return;\n if (!this.isUnknownGitOption(safe.stderr)) return; // a real failure (offline, auth) — not our business\n spawnSync('git', ['fetch', 'origin', 'main'], { cwd: repoRoot, stdio: 'ignore' });\n }\n\n // Did git reject the flag itself (too old), as opposed to failing the network refresh?\n private isUnknownGitOption(stderr: string | null): boolean {\n const text = (stderr ?? '').toLowerCase();\n return text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');\n }\n\n private ensureDir(filePath: string): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n }\n\n // Liveness probe: is `pid` still a running process? pid <= 0 (unknown) → assume alive.\n private isProcessAlive(pid: number): boolean {\n if (pid <= 0) return true;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n process.kill(pid, 0);\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n return !error.message.includes('ESRCH');\n }\n }\n\n // Run a command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, cmd: string, args: string[]): CmdCapture {\n const result = spawnSync(cmd, 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 // The actual checked-out branch in repoRoot — cwd-correct so the cache's `branch` label matches.\n private gitBranch(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', '--abbrev-ref', 'HEAD']);\n return result.ok ? result.out : '';\n }\n\n // The LOCAL main hash. `refs/heads/main` (not the bare name) so it can never resolve to a remote\n // ref or a tag. '' when main does not exist locally — which the guard treats as fail-open.\n private localMainHash(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', 'refs/heads/main']);\n return result.ok ? result.out : '';\n }\n\n private changedFiles(repoRoot: string, base: string, head: string): string[] {\n const result = this.capture(repoRoot, 'git', ['diff', '--name-only', base, head]);\n if (!result.ok || result.out === '') return [];\n return result.out.split('\\n').map((line: string): string => line.trim()).filter((line: string): boolean => line.length > 0);\n }\n\n // Every file this feature branch has touched since the fork point — committed AND still in the\n // working tree (staged / unstaged / untracked), so a conflict is visible WHILE editing.\n private featureChangedFiles(repoRoot: string, forkPoint: string): string[] {\n const out = new Set<string>();\n const add = (args: string[]): void => {\n const r = this.capture(repoRoot, 'git', args);\n if (!r.ok || r.out === '') return;\n for (const line of r.out.split('\\n')) {\n const f = line.trim();\n if (f.length > 0) out.add(f);\n }\n };\n add(['diff', '--name-only', forkPoint, 'HEAD']); // committed since the fork point\n add(['diff', '--name-only', 'HEAD']); // unstaged working-tree edits\n add(['diff', '--name-only', '--cached', 'HEAD']); // staged edits\n add(['ls-files', '--others', '--exclude-standard']); // untracked new files (respects .gitignore)\n return [...out];\n }\n\n // Has this feature branch already been merged into main? Reliable signal: a MERGED PR exists.\n private detectMergedPr(repoRoot: string, branch: string): string {\n if (!branch || branch === 'main') return '';\n const result = this.capture(repoRoot, 'gh', ['pr', 'list', '--head', branch, '--state', 'merged', '--json', 'number', '--jq', '.[0].number']);\n return result.ok ? result.out : '';\n }\n\n // An OPEN PR tracking this branch, if any. Best-effort/advisory.\n private detectOpenPr(repoRoot: string, branch: string): string {\n if (!branch || branch === 'main') return '';\n const result = this.capture(repoRoot, 'gh', ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number', '--jq', '.[0].number']);\n return result.ok ? result.out : '';\n }\n\n // A benign status that never blocks — used when origin/main can't be resolved.\n private benignStatus(branch: string, featureHead: string): MainSyncStatus {\n return new MainSyncStatus(branch, false, '', true, null, '', featureHead, false, [], new Date().toISOString());\n }\n}\n\n// Temporary migration delegators to MainSyncStatusService — removed once consumers inject it.\nconst mainSyncSvc = new MainSyncStatusService();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncStatusPath(repoRoot: string): string { return mainSyncSvc.mainSyncStatusPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncLockPath(repoRoot: string): string { return mainSyncSvc.mainSyncLockPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncStatus(repoRoot: string): MainSyncStatus | null { return mainSyncSvc.readMainSyncStatus(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void { mainSyncSvc.writeMainSyncStatus(repoRoot, status); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncLock(repoRoot: string): MainSyncLock | null { return mainSyncSvc.readMainSyncLock(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void { mainSyncSvc.writeMainSyncLock(repoRoot, lock); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isLockStale(lock, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function tryAcquireMainSyncLock(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now(), pid: number = process.pid): MainSyncLock | null { return mainSyncSvc.tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes, now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock { return mainSyncSvc.inProcessLock(now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function finishedLock(started: number): MainSyncLock { return mainSyncSvc.finishedLock(started); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function computeMainSyncStatus(repoRoot: string): MainSyncStatus { return mainSyncSvc.computeMainSyncStatus(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function squashRecoverySteps(currentBranch: string): string[] { return mainSyncSvc.squashRecoverySteps(currentBranch); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function stampCleanMainSyncStatus(repoRoot: string): void { mainSyncSvc.stampCleanMainSyncStatus(repoRoot); }\n"]}
1
+ {"version":3,"file":"main-sync-status.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/main-sync-status.ts"],"names":[],"mappings":";;;AAyfA,gDAAiH;AAEjH,4CAA6G;AAE7G,gDAAgI;AAEhI,kDAA0I;AAE1I,4CAA0H;AAE1H,8CAAgI;AAEhI,kCAAiL;AAEjL,kDAAmM;AAEnM,wDAAqP;AAErP,sCAAgJ;AAEhJ,oCAAyG;AAEzG,sDAA+H;AAE/H,kDAA+H;AAE/H,4DAAoH;;AAnhBpH,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,+CAA2C;AAC3C,2CAAyD;AACzD,yCAAqC;AAErC,sGAAsG;AACtG,wGAAwG;AACxG,qGAAqG;AACrG,wFAAwF;AAExF,oGAAoG;AACvF,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AACtD,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAElD,MAAM,oBAAoB,GAAG,WAAW,CAAC;AACzC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAEvC,+CAA+C;AAC/C,MAAa,cAAc;IACvB,MAAM,CAAS;IACf,mBAAmB,CAAU;IAC7B,QAAQ,CAAS;IACjB,YAAY,CAAU;IACtB,SAAS,CAAgB;IACzB,UAAU,CAAS;IACnB,WAAW,CAAS;IACpB,QAA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AAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,mBAAmB,CAAC,aAAqB,IAAc,OAAO,WAAW,CAAC,mBAAmB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,wBAAwB,CAAC,QAAgB,IAAU,WAAW,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from './atomic-file';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\nimport { toError } from './to-error';\n\n// Shared \"is my feature branch healthy relative to origin/main?\" state. The SLOW signals (git fetch +\n// merge-base + same-file-overlap + a merged-PR lookup) are computed by the ai-hook-rules refresher in a\n// DETACHED background process; the feature-branch-guard only READS this cached file. pr-gate's merge\n// flow also writes it synchronously after a merge. Lives here (the shared dep of both).\n\n// How long an `inprocess` refresher lock may sit before a new refresher assumes the prior run hung.\nexport const DEFAULT_HANG_TIMEOUT_MINUTES = 5;\n\nconst MAIN_SYNC_STATUS_FILE = 'main-sync-status.json';\nconst MAIN_SYNC_LOCK_FILE = 'main-sync.lock.json';\n\nconst LOCK_STATE_INPROCESS = 'inprocess';\nconst LOCK_STATE_FINISHED = 'finished';\n\n// Data-only (per CLAUDE.md, classes for data).\nexport class MainSyncStatus {\n branch: string;\n branchAlreadyMerged: boolean;\n mergedPr: string;\n hasForkPoint: boolean;\n forkPoint: string | null;\n originMain: string;\n featureHead: string;\n conflict: boolean;\n conflictFiles: string[];\n timestamp: string;\n // An OPEN (not merged) PR tracking this branch, if any — '' = none or not-yet-known. Advisory.\n // Kept OUT of the positional constructor (a defaulted field) so existing call sites don't churn.\n openPr: string = '';\n // The LOCAL refs/heads/main hash — '' = main does not exist locally (fresh clone / worktree) or\n // could not be read. Paired with `originMain`, this is what tells the read-stale-guard whether a\n // checked-out `main` is behind its remote. Defaulted field for the same reason as `openPr`.\n localMain: string = '';\n\n constructor(\n branch: string,\n branchAlreadyMerged: boolean,\n mergedPr: string,\n hasForkPoint: boolean,\n forkPoint: string | null,\n originMain: string,\n featureHead: string,\n conflict: boolean,\n conflictFiles: string[],\n timestamp: string,\n ) {\n this.branch = branch;\n this.branchAlreadyMerged = branchAlreadyMerged;\n this.mergedPr = mergedPr;\n this.hasForkPoint = hasForkPoint;\n this.forkPoint = forkPoint;\n this.originMain = originMain;\n this.featureHead = featureHead;\n this.conflict = conflict;\n this.conflictFiles = conflictFiles;\n this.timestamp = timestamp;\n }\n}\n\n// Concurrency state machine for the detached refresher. `started` is epoch ms. `pid` is the refresher\n// process's pid (0 = unknown) — used so a KILLED refresher doesn't wedge `inprocess` for the timeout.\nexport class MainSyncLock {\n state: string;\n started: number;\n pid: number;\n\n constructor(state: string, started: number, pid: number = 0) {\n this.state = state;\n this.started = started;\n this.pid = pid;\n }\n}\n\n// Raw JSON shapes for the cast at the parse boundary.\ninterface RawStatus {\n branch?: string;\n branchAlreadyMerged?: boolean;\n mergedPr?: string;\n hasForkPoint?: boolean;\n forkPoint?: string | null;\n originMain?: string;\n featureHead?: string;\n conflict?: boolean;\n conflictFiles?: string[];\n timestamp?: string;\n openPr?: string;\n localMain?: string;\n}\n\ninterface RawLock {\n state?: string;\n started?: number;\n pid?: number;\n}\n\n// Result of a captured git/gh invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n/**\n * Reads/writes the main-sync cache + lock and computes the slow \"is my branch healthy vs origin/main?\"\n * status. `@injectable(bindingScopeValues.Singleton)` so it's injectable and drawn in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class MainSyncStatusService {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n ) {}\n\n /**\n * SHARED scope: `<primary>/.webpieces/main-sync-status.json`, one per repo.\n *\n * It is the OUTPUT of the single-flight refresher below, so it has to live where the lock lives —\n * one `.git`, one `origin/main`, one fetch, one answer. A per-worktree copy under single-flight\n * would only ever be written for whichever worktree won the lock anyway.\n *\n * KNOWN CONSEQUENCE, stated plainly rather than discovered later: the file's CONTENT is keyed to\n * one branch (`branch`, `featureHead`, `conflict`, `conflictFiles`), and every reader fails OPEN\n * when the cached branch is not the branch being judged (`merged-branch-bash-guard` and\n * `stale-main-bash-guard` both log `stale-cross-branch-cache (fail-open)`). With several worktrees\n * on several branches, the losers of the lock therefore see a cross-branch cache and their guards\n * allow rather than block. That is the fail-SAFE direction and it is inherent to single-flight, not\n * to the shared path — but making the entries branch-keyed (a map of branch → status, written\n * atomically) is the obvious follow-up.\n */\n mainSyncStatusPath(repoRoot: string): string {\n return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_STATUS_FILE);\n }\n\n /**\n * SHARED scope — the single-flight lock for the whole repo.\n *\n * This is the fix for the filed bug \"the detached main-sync refresher's `git fetch` races the\n * agent's foreground `git fetch`/`git pull` and corrupts `.git/FETCH_HEAD`\". The lock was already\n * atomic (O_CREAT|O_EXCL) and already serialised refreshers against each other — but only WITHIN\n * one worktree, so N worktrees meant N locks and up to N concurrent `git fetch`es against the ONE\n * shared `.git`, which is exactly how a duplicate `for-merge` line lands in FETCH_HEAD. There is\n * one `.git`, so there is now one lock: at most one refresher in flight across all worktrees.\n *\n * Stale-lock handling is unchanged and still required (a lock nobody can clear is worse than the\n * race): the holder records pid + start epoch, and `tryAcquireMainSyncLock` reclaims it once\n * `isRefreshInProgress` proves the holder is finished, hung past hangTimeoutMinutes, or dead.\n */\n mainSyncLockPath(repoRoot: string): string {\n return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_LOCK_FILE);\n }\n\n // Pure read — any error (missing file, malformed JSON) returns null so the guard fails OPEN.\n readMainSyncStatus(repoRoot: string): MainSyncStatus | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const statusPath = this.mainSyncStatusPath(repoRoot);\n if (!fs.existsSync(statusPath)) return null;\n const raw = JSON.parse(fs.readFileSync(statusPath, 'utf8')) as RawStatus;\n const status = new MainSyncStatus(\n raw.branch ?? '',\n raw.branchAlreadyMerged ?? false,\n raw.mergedPr ?? '',\n raw.hasForkPoint ?? true,\n raw.forkPoint ?? null,\n raw.originMain ?? '',\n raw.featureHead ?? '',\n raw.conflict ?? false,\n raw.conflictFiles ?? [],\n raw.timestamp ?? '',\n );\n status.openPr = raw.openPr ?? '';\n status.localMain = raw.localMain ?? '';\n return status;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * ATOMIC write (temp file + `rename()` in the same directory). The refresher writes this file while\n * guards on the blocking path read it; a plain `writeFileSync` truncates first, so a reader landing\n * in that window gets a torn document. Now that the file is repo-wide the reader may be in another\n * worktree entirely, which widens the window rather than creating it. See AtomicFile.\n */\n writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void {\n this.atomicFile.writeJsonAtomic(this.mainSyncStatusPath(repoRoot), status);\n }\n\n readMainSyncLock(repoRoot: string): MainSyncLock | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const lockPath = this.mainSyncLockPath(repoRoot);\n if (!fs.existsSync(lockPath)) return null;\n const raw = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as RawLock;\n return new MainSyncLock(raw.state ?? LOCK_STATE_FINISHED, raw.started ?? 0, raw.pid ?? 0);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\\n');\n }\n\n // A lock is stale (prior refresher assumed hung) once `inprocess` longer than hangTimeoutMinutes.\n isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n return now - lock.started > hangTimeoutMinutes * 60 * 1000;\n }\n\n // True when another refresher is actively running and we should NOT start a second one.\n isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n const lock = this.readMainSyncLock(repoRoot);\n if (!lock) return false;\n if (lock.state !== LOCK_STATE_INPROCESS) return false;\n if (this.isLockStale(lock, hangTimeoutMinutes, now)) return false;\n return this.isProcessAlive(lock.pid);\n }\n\n /**\n * ATOMICALLY take the refresher lock. Returns the held lock, or null when someone else holds it.\n *\n * Replaces the check-then-write pair (`isRefreshInProgress` then `writeMainSyncLock`), whose gap\n * let two detached refreshers both pass the check and then both run `git fetch` at once — the\n * concurrency this lock exists to prevent. The create uses the `wx` flag (O_CREAT|O_EXCL), so of\n * N racing refreshers exactly one creates the file.\n *\n * A lock file left behind by a FINISHED, hung, or killed refresher is reclaimed: we only unlink\n * and re-take it once `isRefreshInProgress` says the holder is provably not running, and we\n * re-read afterwards to confirm the entry we see is ours before claiming the lock.\n */\n tryAcquireMainSyncLock(\n repoRoot: string,\n hangTimeoutMinutes: number,\n now: number = Date.now(),\n pid: number = process.pid,\n ): MainSyncLock | null {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n const lock = this.inProcessLock(now, pid);\n const payload = JSON.stringify(lock, null, 2) + '\\n';\n\n if (this.createExclusive(lockPath, payload)) return lock;\n\n // The file already exists. Leave it alone while a live refresher owns it.\n if (this.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now)) return null;\n\n // Reclaim it: remove the dead entry, then re-take it exclusively so only one reclaimer wins.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.unlinkSync(lockPath);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // someone else reclaimed it first — the exclusive create below decides\n }\n if (!this.createExclusive(lockPath, payload)) return null;\n\n // Confirm the lock on disk is OURS (a simultaneous reclaimer could have unlinked ours and\n // written its own between the two calls above).\n const held = this.readMainSyncLock(repoRoot);\n if (!held || held.pid !== pid || held.started !== lock.started) return null;\n return lock;\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(lockPath: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(lockPath, payload, { flag: 'wx' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_INPROCESS, now, pid);\n }\n\n finishedLock(started: number): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_FINISHED, started, 0);\n }\n\n /**\n * The SLOW path, run only inside the detached refresher. Computes every cached signal the\n * feature-branch-guard needs. Never run on the hook's blocking path.\n */\n // webpieces-disable max-lines-new-methods -- one cohesive slow-path computation\n computeMainSyncStatus(repoRoot: string): MainSyncStatus {\n const branch = this.gitBranch(repoRoot);\n const mergedPr = this.detectMergedPr(repoRoot, branch);\n const openPr = this.detectOpenPr(repoRoot, branch);\n\n // Best-effort network refresh; offline just means we evaluate against the last-fetched ref.\n this.fetchOriginMain(repoRoot);\n\n const head = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const localMain = this.localMainHash(repoRoot);\n const featureHead = head.ok ? head.out : '';\n if (!head.ok || !originMain.ok) {\n const status = this.benignStatus(branch, featureHead);\n status.branchAlreadyMerged = mergedPr !== '';\n status.mergedPr = mergedPr;\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n const forkPoint = this.capture(repoRoot, 'git', ['merge-base', 'origin/main', 'HEAD']);\n if (!forkPoint.ok || forkPoint.out === '') {\n const noFork = new MainSyncStatus(branch, mergedPr !== '', mergedPr, false, null, originMain.out, featureHead, false, [], new Date().toISOString());\n noFork.openPr = openPr;\n noFork.localMain = localMain;\n return noFork;\n }\n\n const featureFiles = new Set(this.featureChangedFiles(repoRoot, forkPoint.out));\n const mainFiles = this.changedFiles(repoRoot, forkPoint.out, 'origin/main');\n const conflictFiles = mainFiles.filter((file: string): boolean => featureFiles.has(file));\n\n const status = new MainSyncStatus(\n branch,\n mergedPr !== '',\n mergedPr,\n true,\n forkPoint.out,\n originMain.out,\n featureHead,\n conflictFiles.length > 0,\n conflictFiles,\n new Date().toISOString(),\n );\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n // The recovery steps when there is no fork point with origin/main (a bad merge of main into branch).\n squashRecoverySteps(currentBranch: string): string[] {\n return [\n '1. Fetch latest main: git fetch origin main',\n `2. New branch off origin/main: git checkout -b ${currentBranch}-v2 origin/main`,\n `3. Squash-merge old branch: git merge --squash ${currentBranch}`,\n ' ^^ HUMAN-ONLY. `git merge` is blocked for AI (redirect-how-to-merge-main). AI: ask the',\n ' human to run step 3, and warn them it is a raw merge — only correct here because the',\n ' branch is already broken. For a normal update from main they should push back and',\n ' tell you to use the gated 3-point merge instead: `pnpm wp-start-update` (paired with',\n ' `pnpm wp-finish-update`) when no PR is open, or `pnpm wp-start-upsert-pr` (paired with',\n ' `pnpm wp-finish-upsert-pr`) when a PR IS open — a PR MUST use the upsert-pr pair.',\n `4. Commit the squash: git add -A && git commit -m \"Squashed from ${currentBranch}\"`,\n '5. If a PR exists: open a NEW PR for the -v2 branch and close the old one.',\n ];\n }\n\n // Synchronously stamp a clean \"up to date with main\" status — call right after a successful merge.\n stampCleanMainSyncStatus(repoRoot: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const branch = this.gitBranch(repoRoot);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const featureHead = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n if (!originMain.ok || !featureHead.ok) return;\n const status = new MainSyncStatus(\n branch, false, '', true, originMain.out, originMain.out, featureHead.out, false, [], new Date().toISOString(),\n );\n status.localMain = this.localMainHash(repoRoot);\n this.writeMainSyncStatus(repoRoot, status);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Refresh `origin/main` WITHOUT writing `.git/FETCH_HEAD`.\n *\n * WHY the flag is not optional: this runs in a DETACHED background process while the agent is\n * running its own foreground `git fetch` / `git pull` in the very same repo. `.git/FETCH_HEAD` is\n * a single file that git takes no lock on, so two overlapping fetches interleave their writes and\n * can leave the SAME `for-merge` line twice. `git pull` then reads two for-merge entries and dies\n * with `fatal: Cannot fast-forward to multiple branches` — wedging the exact command the\n * read-stale-guard tells the agent to run. `--no-write-fetch-head` (git >= 2.29) still updates the\n * remote-tracking ref, which is all anything downstream reads (`origin/main`, merge-base), so\n * nothing here needs FETCH_HEAD written at all.\n *\n * Older git rejects the flag; only then do we retry the plain form, accepting the old behaviour\n * rather than losing the refresh entirely on a pre-2020 git.\n */\n private fetchOriginMain(repoRoot: string): void {\n const safe = spawnSync('git', ['fetch', '--no-write-fetch-head', 'origin', 'main'], {\n cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'],\n });\n if (safe.status === 0) return;\n if (!this.isUnknownGitOption(safe.stderr)) return; // a real failure (offline, auth) — not our business\n spawnSync('git', ['fetch', 'origin', 'main'], { cwd: repoRoot, stdio: 'ignore' });\n }\n\n // Did git reject the flag itself (too old), as opposed to failing the network refresh?\n private isUnknownGitOption(stderr: string | null): boolean {\n const text = (stderr ?? '').toLowerCase();\n return text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');\n }\n\n private ensureDir(filePath: string): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n }\n\n // Liveness probe: is `pid` still a running process? pid <= 0 (unknown) → assume alive.\n private isProcessAlive(pid: number): boolean {\n if (pid <= 0) return true;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n process.kill(pid, 0);\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n return !error.message.includes('ESRCH');\n }\n }\n\n // Run a command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, cmd: string, args: string[]): CmdCapture {\n const result = spawnSync(cmd, 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 // The actual checked-out branch in repoRoot — cwd-correct so the cache's `branch` label matches.\n private gitBranch(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', '--abbrev-ref', 'HEAD']);\n return result.ok ? result.out : '';\n }\n\n // The LOCAL main hash. `refs/heads/main` (not the bare name) so it can never resolve to a remote\n // ref or a tag. '' when main does not exist locally — which the guard treats as fail-open.\n private localMainHash(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', 'refs/heads/main']);\n return result.ok ? result.out : '';\n }\n\n private changedFiles(repoRoot: string, base: string, head: string): string[] {\n const result = this.capture(repoRoot, 'git', ['diff', '--name-only', base, head]);\n if (!result.ok || result.out === '') return [];\n return result.out.split('\\n').map((line: string): string => line.trim()).filter((line: string): boolean => line.length > 0);\n }\n\n // Every file this feature branch has touched since the fork point — committed AND still in the\n // working tree (staged / unstaged / untracked), so a conflict is visible WHILE editing.\n private featureChangedFiles(repoRoot: string, forkPoint: string): string[] {\n const out = new Set<string>();\n const add = (args: string[]): void => {\n const r = this.capture(repoRoot, 'git', args);\n if (!r.ok || r.out === '') return;\n for (const line of r.out.split('\\n')) {\n const f = line.trim();\n if (f.length > 0) out.add(f);\n }\n };\n add(['diff', '--name-only', forkPoint, 'HEAD']); // committed since the fork point\n add(['diff', '--name-only', 'HEAD']); // unstaged working-tree edits\n add(['diff', '--name-only', '--cached', 'HEAD']); // staged edits\n add(['ls-files', '--others', '--exclude-standard']); // untracked new files (respects .gitignore)\n return [...out];\n }\n\n // Has this feature branch already been merged into main? Reliable signal: a MERGED PR exists.\n private detectMergedPr(repoRoot: string, branch: string): string {\n if (!branch || branch === 'main') return '';\n const result = this.capture(repoRoot, 'gh', ['pr', 'list', '--head', branch, '--state', 'merged', '--json', 'number', '--jq', '.[0].number']);\n return result.ok ? result.out : '';\n }\n\n // An OPEN PR tracking this branch, if any. Best-effort/advisory.\n private detectOpenPr(repoRoot: string, branch: string): string {\n if (!branch || branch === 'main') return '';\n const result = this.capture(repoRoot, 'gh', ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number', '--jq', '.[0].number']);\n return result.ok ? result.out : '';\n }\n\n // A benign status that never blocks — used when origin/main can't be resolved.\n private benignStatus(branch: string, featureHead: string): MainSyncStatus {\n return new MainSyncStatus(branch, false, '', true, null, '', featureHead, false, [], new Date().toISOString());\n }\n}\n\n// Temporary migration delegators to MainSyncStatusService — removed once consumers inject it.\nconst mainSyncSvc = new MainSyncStatusService();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncStatusPath(repoRoot: string): string { return mainSyncSvc.mainSyncStatusPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncLockPath(repoRoot: string): string { return mainSyncSvc.mainSyncLockPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncStatus(repoRoot: string): MainSyncStatus | null { return mainSyncSvc.readMainSyncStatus(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void { mainSyncSvc.writeMainSyncStatus(repoRoot, status); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncLock(repoRoot: string): MainSyncLock | null { return mainSyncSvc.readMainSyncLock(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void { mainSyncSvc.writeMainSyncLock(repoRoot, lock); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isLockStale(lock, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function tryAcquireMainSyncLock(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now(), pid: number = process.pid): MainSyncLock | null { return mainSyncSvc.tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes, now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock { return mainSyncSvc.inProcessLock(now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function finishedLock(started: number): MainSyncLock { return mainSyncSvc.finishedLock(started); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function computeMainSyncStatus(repoRoot: string): MainSyncStatus { return mainSyncSvc.computeMainSyncStatus(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function squashRecoverySteps(currentBranch: string): string[] { return mainSyncSvc.squashRecoverySteps(currentBranch); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function stampCleanMainSyncStatus(repoRoot: string): void { mainSyncSvc.stampCleanMainSyncStatus(repoRoot); }\n"]}
@@ -1,9 +1,19 @@
1
+ import { AtomicFile } from './atomic-file';
2
+ import { DotWebpieces } from './state-dir';
1
3
  import { WorktreeService } from './worktrees';
2
4
  import { CacheFreshness, MergedBranchesCache } from './merged-branch-verdicts';
3
5
  export { MergedBranch, DeletableBranch, DeletableWorktree, MergedBranchesCache, CacheFreshness, CACHE_STALE_AFTER_MS, CLASSIFICATION_MERGED_PR, CLASSIFICATION_BACKUP_OF_MERGED, CLASSIFICATION_NO_COMMITS, CLASSIFICATION_SUPERSEDED, CLASSIFICATION_CONTENT_IN_MAIN, CLASSIFICATION_NEVER_PROPOSED, CLASSIFICATION_IN_USE, CLASSIFICATION_PRUNABLE, CLASSIFICATION_LOCKED, CLASSIFICATION_CURRENT, CLASSIFICATION_DETACHED, PROMPTABLE_CLASSIFICATIONS, } from './merged-branch-verdicts';
4
6
  export declare class MergedBranchesService {
5
7
  private readonly worktrees;
6
- constructor(worktrees?: WorktreeService);
8
+ private readonly dotDir;
9
+ private readonly atomicFile;
10
+ constructor(worktrees?: WorktreeService, dotDir?: DotWebpieces, atomicFile?: AtomicFile);
11
+ /**
12
+ * SHARED scope — one per repo, in the primary clone, NOT one per worktree. This file's contents
13
+ * describe every branch AND every worktree in the repo, so a per-worktree copy was a repo-wide fact
14
+ * stored N times and therefore N times wrong: branch-creation-guard reported "8 parked local
15
+ * branches" against an actual 1, reading a copy that predated deletions made from another worktree.
16
+ */
7
17
  mergedBranchesPath(repoRoot: string): string;
8
18
  readMergedBranches(repoRoot: string): MergedBranchesCache | null;
9
19
  /**
@@ -25,6 +35,18 @@ export declare class MergedBranchesService {
25
35
  * rather than emptied, since "git failed" must never read as "everything was deleted".
26
36
  */
27
37
  reconcile(repoRoot: string, cache: MergedBranchesCache): MergedBranchesCache;
38
+ /**
39
+ * ATOMIC write. Now that this file is shared by every worktree it has N concurrent writers (one
40
+ * detached refresher per agent), and its readers are the guards' BLOCKING path. A plain
41
+ * `writeFileSync` truncates before it writes, so a reader landing in that window gets a torn
42
+ * document — the reader-side retry added in PR #526 cannot rescue a syntactically valid PREFIX.
43
+ * Fixed where it belongs: temp file + `rename()`, which POSIX makes atomic. See AtomicFile.
44
+ *
45
+ * This buys ATOMIC READS, not lost-update protection: two read-modify-write cycles still end
46
+ * last-writer-wins. That is acceptable and deliberate — this is a DERIVED cache, recomputed from
47
+ * `gh` + git by the refresher, and wp-cleanup recomputes rather than trusting it before deleting
48
+ * anything. Nothing here is transactional and no caller may assume it is.
49
+ */
28
50
  writeMergedBranches(repoRoot: string, cache: MergedBranchesCache): void;
29
51
  /**
30
52
  * Every local branch except `main`. Uses `git for-each-ref`, NOT `git branch` — the latter is a
@@ -4,9 +4,9 @@ exports.MergedBranchesService = exports.PROMPTABLE_CLASSIFICATIONS = exports.CLA
4
4
  const tslib_1 = require("tslib");
5
5
  const child_process_1 = require("child_process");
6
6
  const fs = tslib_1.__importStar(require("fs"));
7
- const path = tslib_1.__importStar(require("path"));
8
7
  const inversify_1 = require("inversify");
9
- const constants_1 = require("./constants");
8
+ const atomic_file_1 = require("./atomic-file");
9
+ const state_dir_1 = require("./state-dir");
10
10
  const to_error_1 = require("./to-error");
11
11
  const worktrees_1 = require("./worktrees");
12
12
  const merged_branch_verdicts_1 = require("./merged-branch-verdicts");
@@ -94,13 +94,23 @@ class Verdict {
94
94
  }
95
95
  let MergedBranchesService = class MergedBranchesService {
96
96
  worktrees;
97
+ dotDir;
98
+ atomicFile;
97
99
  // Defaulted so the non-DI call sites (`new MergedBranchesService()` in the guard and the detached
98
100
  // refresher) keep working, while inversify still injects the singleton when resolved from a container.
99
- constructor(worktrees = new worktrees_1.WorktreeService()) {
101
+ constructor(worktrees = new worktrees_1.WorktreeService(), dotDir = state_dir_1.dotWebpieces, atomicFile = new atomic_file_1.AtomicFile()) {
100
102
  this.worktrees = worktrees;
103
+ this.dotDir = dotDir;
104
+ this.atomicFile = atomicFile;
101
105
  }
106
+ /**
107
+ * SHARED scope — one per repo, in the primary clone, NOT one per worktree. This file's contents
108
+ * describe every branch AND every worktree in the repo, so a per-worktree copy was a repo-wide fact
109
+ * stored N times and therefore N times wrong: branch-creation-guard reported "8 parked local
110
+ * branches" against an actual 1, reading a copy that predated deletions made from another worktree.
111
+ */
102
112
  mergedBranchesPath(repoRoot) {
103
- return path.join(repoRoot, constants_1.WEBPIECES_TMP_DIR, MERGED_BRANCHES_FILE);
113
+ return this.dotDir.sharedFile(repoRoot, MERGED_BRANCHES_FILE);
104
114
  }
105
115
  // Pure read — any error (missing file, malformed JSON) returns null so the guard fails OPEN.
106
116
  readMergedBranches(repoRoot) {
@@ -151,10 +161,20 @@ let MergedBranchesService = class MergedBranchesService {
151
161
  const keepTree = (entry) => trees.length === 0 || livePaths.has(entry.path);
152
162
  return new merged_branch_verdicts_1.MergedBranchesCache(cache.timestamp, cache.deletable.filter(keepBranch), cache.keep.filter(keepBranch), cache.worktrees.filter(keepTree));
153
163
  }
164
+ /**
165
+ * ATOMIC write. Now that this file is shared by every worktree it has N concurrent writers (one
166
+ * detached refresher per agent), and its readers are the guards' BLOCKING path. A plain
167
+ * `writeFileSync` truncates before it writes, so a reader landing in that window gets a torn
168
+ * document — the reader-side retry added in PR #526 cannot rescue a syntactically valid PREFIX.
169
+ * Fixed where it belongs: temp file + `rename()`, which POSIX makes atomic. See AtomicFile.
170
+ *
171
+ * This buys ATOMIC READS, not lost-update protection: two read-modify-write cycles still end
172
+ * last-writer-wins. That is acceptable and deliberate — this is a DERIVED cache, recomputed from
173
+ * `gh` + git by the refresher, and wp-cleanup recomputes rather than trusting it before deleting
174
+ * anything. Nothing here is transactional and no caller may assume it is.
175
+ */
154
176
  writeMergedBranches(repoRoot, cache) {
155
- const cachePath = this.mergedBranchesPath(repoRoot);
156
- fs.mkdirSync(path.dirname(cachePath), { recursive: true });
157
- fs.writeFileSync(cachePath, JSON.stringify(cache, null, 2) + '\n');
177
+ this.atomicFile.writeJsonAtomic(this.mergedBranchesPath(repoRoot), cache);
158
178
  }
159
179
  /**
160
180
  * Every local branch except `main`. Uses `git for-each-ref`, NOT `git branch` — the latter is a
@@ -441,6 +461,8 @@ let MergedBranchesService = class MergedBranchesService {
441
461
  exports.MergedBranchesService = MergedBranchesService;
442
462
  exports.MergedBranchesService = MergedBranchesService = tslib_1.__decorate([
443
463
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
444
- tslib_1.__metadata("design:paramtypes", [worktrees_1.WorktreeService])
464
+ tslib_1.__metadata("design:paramtypes", [worktrees_1.WorktreeService,
465
+ state_dir_1.DotWebpieces,
466
+ atomic_file_1.AtomicFile])
445
467
  ], MergedBranchesService);
446
468
  //# sourceMappingURL=merged-branches.js.map