@webpieces/agent-workflow-rules 0.4.976 → 0.4.977

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/agent-workflow-rules",
3
- "version": "0.4.976",
3
+ "version": "0.4.977",
4
4
  "description": "Independent workflow guards, guard hook, installation and shim management for AI coding agents.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -24,20 +24,20 @@
24
24
  "directory": "packages/tooling/agent-workflow-rules"
25
25
  },
26
26
  "dependencies": {
27
- "@webpieces/hook-runtime": "0.4.976",
28
- "@webpieces/rules-config": "0.4.976",
27
+ "@webpieces/hook-runtime": "0.4.977",
28
+ "@webpieces/rules-config": "0.4.977",
29
29
  "inversify": "7.10.4",
30
30
  "reflect-metadata": "0.2.2",
31
- "@webpieces/tooling-common": "0.4.976",
32
- "@webpieces/repo-workflow-core": "0.4.976",
31
+ "@webpieces/tooling-common": "0.4.977",
32
+ "@webpieces/repo-workflow-core": "0.4.977",
33
33
  "tslib": "2.8.1",
34
- "@webpieces/rules-sdk": "0.4.976"
34
+ "@webpieces/rules-sdk": "0.4.977"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"
38
38
  },
39
39
  "devDependencies": {
40
- "@webpieces/tooling-testkit": "0.4.976"
40
+ "@webpieces/tooling-testkit": "0.4.977"
41
41
  },
42
42
  "types": "./src/index.d.ts",
43
43
  "bin": {
@@ -27,7 +27,7 @@ import { StreamIdentity } from './log-stream';
27
27
  * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv
28
28
  * (a hand-run of this file) leaves the default, which still prefixes.
29
29
  */
30
- export declare function main(): void;
30
+ export declare function main(): Promise<void>;
31
31
  /**
32
32
  * The `started` of the lock claim the spawner took for this run — argv position 3, which is
33
33
  * `refresherArgv`'s 2 (see the offset note there). NaN when absent or malformed, which matches no
@@ -47,4 +47,4 @@ export declare function spawnerIdentity(argv: string[]): StreamIdentity;
47
47
  * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a
48
48
  * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.
49
49
  */
50
- export declare function refreshMainSync(repoRoot: string, claimStarted: number, argvDetail?: string): void;
50
+ export declare function refreshMainSync(repoRoot: string, claimStarted: number, argvDetail?: string): Promise<void>;
@@ -41,9 +41,9 @@ const locks = new repo_workflow_core_1.MainSyncLockService(undefined, undefined,
41
41
  * (a hand-run of this file) leaves the default, which still prefixes.
42
42
  */
43
43
  // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
44
- function main() {
44
+ async function main() {
45
45
  log_stream_1.logStream.identify(spawnerIdentity(process.argv));
46
- refreshMainSync(process.argv[2] ?? process.cwd(), claimStartedFromArgv(process.argv), process.argv.slice(2).join(' '));
46
+ await refreshMainSync(process.argv[2] ?? process.cwd(), claimStartedFromArgv(process.argv), process.argv.slice(2).join(' '));
47
47
  }
48
48
  /**
49
49
  * The `started` of the lock claim the spawner took for this run — argv position 3, which is
@@ -72,7 +72,7 @@ function spawnerIdentity(argv) {
72
72
  * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.
73
73
  */
74
74
  // webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape
75
- function refreshMainSync(repoRoot, claimStarted, argvDetail = '') {
75
+ async function refreshMainSync(repoRoot, claimStarted, argvDetail = '') {
76
76
  const startedMs = Date.now();
77
77
  // First action: prove the detached child actually started. If the async-refresh stream has no START line
78
78
  // for a spawn, the child never launched (or died before this point).
@@ -93,7 +93,7 @@ function refreshMainSync(repoRoot, claimStarted, argvDetail = '') {
93
93
  // to describe only the branch of whichever tree won this lock, so every other worktree's
94
94
  // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all
95
95
  // of them; the map is rebuilt from the live worktree set, so dead branches drop out.
96
- file = status.computeAllMainSyncStatuses(repoRoot);
96
+ file = await status.computeAllMainSyncStatuses(repoRoot);
97
97
  // Second slow signal, same lock, same detached run: which local branches are dead. One bulk
98
98
  // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its
99
99
  // cap without ever touching the network itself. Deliberately allowed to go stale.
@@ -101,13 +101,13 @@ function refreshMainSync(repoRoot, claimStarted, argvDetail = '') {
101
101
  // `false`: the background refresher NEVER ignores a standing agent lock. That flag is
102
102
  // wp-cleanup's, and it means "a human asked for this run" — nothing an unattended
103
103
  // refresher can claim on somebody's behalf.
104
- const cache = mergedBranches.computeMergedBranches(repoRoot, false);
104
+ const cache = await mergedBranches.computeMergedBranches(repoRoot, false);
105
105
  mergedBranches.writeMergedBranches(repoRoot, cache);
106
106
  // Third step, same detached run: actually DELETE the dead branches. Reporting them was
107
107
  // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an
108
108
  // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has
109
109
  // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).
110
- const reaped = autoReap(repoRoot, cache);
110
+ const reaped = await autoReap(repoRoot, cache);
111
111
  // FINISH after a successful run — START-without-FINISH means we were killed mid-run.
112
112
  outcome = repo_workflow_core_1.RefreshOutcome.OK;
113
113
  const names = Object.keys(file.branches);
@@ -177,7 +177,7 @@ function summarize(file) {
177
177
  * background deletion is exactly what nobody should have to trust.
178
178
  */
179
179
  // webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape
180
- function autoReap(repoRoot, cache) {
180
+ async function autoReap(repoRoot, cache) {
181
181
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
182
182
  try {
183
183
  const config = (0, rules_config_1.loadAndValidate)(repoRoot).rulesConfig['branch-creation-guard'];
@@ -187,7 +187,7 @@ function autoReap(repoRoot, cache) {
187
187
  // that basis would be deleting on a preference nobody expressed.
188
188
  if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true)
189
189
  return 0;
190
- const result = new repo_workflow_core_1.BranchReaper().reap(repoRoot, 'auto-reap', cache);
190
+ const result = await new repo_workflow_core_1.BranchReaper().reap(repoRoot, 'auto-reap', cache);
191
191
  for (const failure of result.failed) {
192
192
  (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));
193
193
  }
@@ -199,7 +199,6 @@ function autoReap(repoRoot, cache) {
199
199
  return 0;
200
200
  }
201
201
  }
202
- if (require.main === module) {
203
- main();
204
- }
202
+ if (require.main === module)
203
+ (0, rules_config_1.runMain)(main);
205
204
  //# sourceMappingURL=sync-main.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/sync-main.ts"],"names":[],"mappings":";;AAyCA,oBAOC;AAQD,oDAGC;AAWD,0CAEC;AAOD,0CAkEC;AAhJD,sEAAqM;AACrM,0DAA0D;AAE1D,iEAA6D;AAC7D,mDAA6D;AAC7D,6CAAyD;AAEzD,0GAA0G;AAC1G,MAAM,MAAM,GAAG,IAAI,0CAAqB,EAAE,CAAC;AAC3C,MAAM,KAAK,GAAG,IAAI,wCAAmB,CAAC,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AAEpE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,mKAAmK;AACnK,SAAgB,IAAI;IAChB,sBAAS,CAAC,QAAQ,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IAClD,eAAe,CACX,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,EAChC,oBAAoB,CAAC,OAAO,CAAC,IAAI,CAAC,EAClC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAClC,CAAC;AACN,CAAC;AAED;;;;GAIG;AACH,yHAAyH;AACzH,SAAgB,oBAAoB,CAAC,IAAc;IAC/C,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G,OAAO,CAAC,CAAC;IACb,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { BranchCreationGuardConfig } from '../configs/rule-configs';\nimport { BranchReaper, MainSyncLockService, MainSyncStatusFile, MainSyncStatusService, MergedBranchesCache, MergedBranchesService, ReapResult, RefreshOutcome } from '@webpieces/repo-workflow-core';\nimport { loadAndValidate } from '@webpieces/rules-config';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logSyncEvent, SyncLogEvent } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n// The services this detached process writes its results through, and adopts and deletes its lock through.\nconst status = new MainSyncStatusService();\nconst locks = new MainSyncLockService(undefined, undefined, status);\n\n/**\n * The detached, fire-and-forget refresher spawned (by file path, not a bin) from\n * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +\n * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it\n * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.\n *\n * Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only\n * the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →\n * claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start (at once for a\n * branch the status file has never seen, #1377), and passes\n * its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates\n * one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this\n * child booted) means another refresher owns the run, and we exit.\n *\n * Ordering at the end is the point: the status file, carrying `lastRefreshStartedMs` and the outcome,\n * is written FIRST and the lock deleted LAST, so no process can win the next lock race and still read\n * the previous stamp.\n *\n * argv: [, , repoRoot, claimStarted, sessionId, agentId, hook]\n *\n * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason\n * they are passed. This process has its own fresh module-level `logStream`; left unidentified it\n * named every line `unknown-coordinator-hook.log` — one shared file that every\n * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),\n * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file\n * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv\n * (a hand-run of this file) leaves the default, which still prefixes.\n */\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function main(): void {\n logStream.identify(spawnerIdentity(process.argv));\n refreshMainSync(\n process.argv[2] ?? process.cwd(),\n claimStartedFromArgv(process.argv),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * The `started` of the lock claim the spawner took for this run — argv position 3, which is\n * `refresherArgv`'s 2 (see the offset note there). NaN when absent or malformed, which matches no\n * lock, so a hand-run of this file without a claim adopts nothing and exits as SKIP_INPROGRESS.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function claimStartedFromArgv(argv: string[]): number {\n const raw = argv[3];\n return raw === undefined || raw.trim() === '' ? Number.NaN : Number(raw);\n}\n\n/**\n * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is\n * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).\n *\n * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a\n * disagreement between two files about argv positions, and a test that only checks the reader would\n * have stayed green through it.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function spawnerIdentity(argv: string[]): StreamIdentity {\n return new StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');\n}\n\n/**\n * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a\n * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape\nexport function refreshMainSync(repoRoot: string, claimStarted: number, argvDetail: string = ''): void {\n const startedMs = Date.now();\n\n // First action: prove the detached child actually started. If the async-refresh stream has no START line\n // for a spawn, the child never launched (or died before this point).\n logSyncEvent(repoRoot, new SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // ADOPT the spawner's lock, never create one: the spawner already won it atomically.\n const lock = locks.adoptMainSyncLock(repoRoot, claimStarted);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', `the spawner's lock ${String(claimStarted)} is no longer on disk; another refresh owns this run`));\n return;\n }\n let file: MainSyncStatusFile | null = null;\n let outcome = RefreshOutcome.ERROR;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used\n // to describe only the branch of whichever tree won this lock, so every other worktree's\n // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all\n // of them; the map is rebuilt from the live worktree set, so dead branches drop out.\n file = status.computeAllMainSyncStatuses(repoRoot);\n\n // Second slow signal, same lock, same detached run: which local branches are dead. One bulk\n // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its\n // cap without ever touching the network itself. Deliberately allowed to go stale.\n const mergedBranches = new MergedBranchesService();\n // `false`: the background refresher NEVER ignores a standing agent lock. That flag is\n // wp-cleanup's, and it means \"a human asked for this run\" — nothing an unattended\n // refresher can claim on somebody's behalf.\n const cache = mergedBranches.computeMergedBranches(repoRoot, false);\n mergedBranches.writeMergedBranches(repoRoot, cache);\n\n // Third step, same detached run: actually DELETE the dead branches. Reporting them was\n // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an\n // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has\n // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).\n const reaped = autoReap(repoRoot, cache);\n\n // FINISH after a successful run — START-without-FINISH means we were killed mid-run.\n outcome = RefreshOutcome.OK;\n const names = Object.keys(file.branches);\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'FINISH', process.pid, names.join(','),\n `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`,\n ));\n } finally {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Stamp FIRST: a failed run (offline, gh auth) still counts as a run, so it is retried\n // after MIN_REFRESH_INTERVAL_MINUTES rather than hammered on every tool call.\n recordRun(repoRoot, file, lock.startedMs, outcome);\n } finally {\n // Lock LAST, and only if still ours: a run that hung past its window was reclaimed,\n // and deleting the newer holder's lock would let a third refresher start beside it.\n locks.releaseMainSyncLock(repoRoot, lock);\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call\n // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));\n }\n}\n\n/**\n * Write this run's results and its stamp to main-sync-status.json (atomically). With fresh branch data\n * the whole document is replaced; without it (the compute threw) only the stamp and outcome are\n * updated, keeping the previous branch data the guards are still reading.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction recordRun(repoRoot: string, file: MainSyncStatusFile | null, startedMs: number, outcome: RefreshOutcome): void {\n if (file === null) {\n status.recordRefreshOutcome(repoRoot, startedMs, outcome);\n return;\n }\n file.lastRefreshStartedMs = startedMs;\n file.lastRefreshOutcome = outcome;\n status.writeMainSyncStatusFile(repoRoot, file);\n}\n\n/**\n * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log\n * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to\n * name every branch written, not just the tree the refresher happened to run in.\n */\n// webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape\nfunction summarize(file: MainSyncStatusFile): (branch: string) => string {\n return (branch: string): string => {\n const status = file.branches[branch];\n if (status === undefined) return `${branch}(?)`;\n return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;\n };\n}\n\n/**\n * Delete the branches the verdicts just declared dead. Returns how many actually went.\n *\n * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup\n * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded\n * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that\n * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on\n * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.\n *\n * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the\n * main-sync status this process exists to produce — but every failure is logged, because a silent\n * background deletion is exactly what nobody should have to trust.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction autoReap(repoRoot: string, cache: MergedBranchesCache): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const config = loadAndValidate(repoRoot).rulesConfig['branch-creation-guard'] as BranchCreationGuardConfig | undefined;\n // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,\n // so every validated config states an answer — which means \"absent\" here is not a consumer\n // who wants the default, it is a config that never passed validation. Deleting branches on\n // that basis would be deleting on a preference nobody expressed.\n if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true) return 0;\n\n const result: ReapResult = new BranchReaper().reap(repoRoot, 'auto-reap', cache);\n for (const failure of result.failed) {\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));\n }\n return result.reaped.length;\n } catch (err: unknown) {\n const error = toError(err);\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));\n return 0;\n }\n}\n\nif (require.main === module) {\n main();\n}\n"]}
1
+ {"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/sync-main.ts"],"names":[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2FAA2F;QAC3F,2FAA2F;QAC3F,iEAAiE;QACjE,IAAI,MAAM,EAAE,IAAI,KAAK,KAAK,IAAI,MAAM,EAAE,sBAAsB,KAAK,IAAI;YAAE,OAAO,CAAC,CAAC;QAEhF,MAAM,MAAM,GAAe,MAAM,IAAI,iCAAY,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC;QACvF,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAClC,IAAA,4BAAY,EAAC,QAAQ,EAAE,IAAI,4BAAY,CACnC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,gBAAgB,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAChF,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IAChC,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,IAAA,4BAAY,EAAC,QAAQ,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,aAAa,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAClG,OAAO,CAAC,CAAC;IACb,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;IAAE,IAAA,sBAAO,EAAC,IAAI,CAAC,CAAC","sourcesContent":["import { BranchCreationGuardConfig } from '../configs/rule-configs';\nimport { BranchReaper, MainSyncLockService, MainSyncStatusFile, MainSyncStatusService, MergedBranchesCache, MergedBranchesService, ReapResult, RefreshOutcome } from '@webpieces/repo-workflow-core';\nimport { loadAndValidate, runMain } from '@webpieces/rules-config';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logSyncEvent, SyncLogEvent } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n// The services this detached process writes its results through, and adopts and deletes its lock through.\nconst status = new MainSyncStatusService();\nconst locks = new MainSyncLockService(undefined, undefined, status);\n\n/**\n * The detached, fire-and-forget refresher spawned (by file path, not a bin) from\n * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +\n * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it\n * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.\n *\n * Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only\n * the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →\n * claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start (at once for a\n * branch the status file has never seen, #1377), and passes\n * its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates\n * one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this\n * child booted) means another refresher owns the run, and we exit.\n *\n * Ordering at the end is the point: the status file, carrying `lastRefreshStartedMs` and the outcome,\n * is written FIRST and the lock deleted LAST, so no process can win the next lock race and still read\n * the previous stamp.\n *\n * argv: [, , repoRoot, claimStarted, sessionId, agentId, hook]\n *\n * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason\n * they are passed. This process has its own fresh module-level `logStream`; left unidentified it\n * named every line `unknown-coordinator-hook.log` — one shared file that every\n * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),\n * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file\n * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv\n * (a hand-run of this file) leaves the default, which still prefixes.\n */\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport async function main(): Promise<void> {\n logStream.identify(spawnerIdentity(process.argv));\n await refreshMainSync(\n process.argv[2] ?? process.cwd(),\n claimStartedFromArgv(process.argv),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * The `started` of the lock claim the spawner took for this run — argv position 3, which is\n * `refresherArgv`'s 2 (see the offset note there). NaN when absent or malformed, which matches no\n * lock, so a hand-run of this file without a claim adopts nothing and exits as SKIP_INPROGRESS.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function claimStartedFromArgv(argv: string[]): number {\n const raw = argv[3];\n return raw === undefined || raw.trim() === '' ? Number.NaN : Number(raw);\n}\n\n/**\n * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is\n * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).\n *\n * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a\n * disagreement between two files about argv positions, and a test that only checks the reader would\n * have stayed green through it.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function spawnerIdentity(argv: string[]): StreamIdentity {\n return new StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');\n}\n\n/**\n * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a\n * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape\nexport async function refreshMainSync(repoRoot: string, claimStarted: number, argvDetail: string = ''): Promise<void> {\n const startedMs = Date.now();\n\n // First action: prove the detached child actually started. If the async-refresh stream has no START line\n // for a spawn, the child never launched (or died before this point).\n logSyncEvent(repoRoot, new SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // ADOPT the spawner's lock, never create one: the spawner already won it atomically.\n const lock = locks.adoptMainSyncLock(repoRoot, claimStarted);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', `the spawner's lock ${String(claimStarted)} is no longer on disk; another refresh owns this run`));\n return;\n }\n let file: MainSyncStatusFile | null = null;\n let outcome = RefreshOutcome.ERROR;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used\n // to describe only the branch of whichever tree won this lock, so every other worktree's\n // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all\n // of them; the map is rebuilt from the live worktree set, so dead branches drop out.\n file = await status.computeAllMainSyncStatuses(repoRoot);\n\n // Second slow signal, same lock, same detached run: which local branches are dead. One bulk\n // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its\n // cap without ever touching the network itself. Deliberately allowed to go stale.\n const mergedBranches = new MergedBranchesService();\n // `false`: the background refresher NEVER ignores a standing agent lock. That flag is\n // wp-cleanup's, and it means \"a human asked for this run\" — nothing an unattended\n // refresher can claim on somebody's behalf.\n const cache = await mergedBranches.computeMergedBranches(repoRoot, false);\n mergedBranches.writeMergedBranches(repoRoot, cache);\n\n // Third step, same detached run: actually DELETE the dead branches. Reporting them was\n // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an\n // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has\n // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).\n const reaped = await autoReap(repoRoot, cache);\n\n // FINISH after a successful run — START-without-FINISH means we were killed mid-run.\n outcome = RefreshOutcome.OK;\n const names = Object.keys(file.branches);\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'FINISH', process.pid, names.join(','),\n `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`,\n ));\n } finally {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Stamp FIRST: a failed run (offline, gh auth) still counts as a run, so it is retried\n // after MIN_REFRESH_INTERVAL_MINUTES rather than hammered on every tool call.\n recordRun(repoRoot, file, lock.startedMs, outcome);\n } finally {\n // Lock LAST, and only if still ours: a run that hung past its window was reclaimed,\n // and deleting the newer holder's lock would let a third refresher start beside it.\n locks.releaseMainSyncLock(repoRoot, lock);\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call\n // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));\n }\n}\n\n/**\n * Write this run's results and its stamp to main-sync-status.json (atomically). With fresh branch data\n * the whole document is replaced; without it (the compute threw) only the stamp and outcome are\n * updated, keeping the previous branch data the guards are still reading.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction recordRun(repoRoot: string, file: MainSyncStatusFile | null, startedMs: number, outcome: RefreshOutcome): void {\n if (file === null) {\n status.recordRefreshOutcome(repoRoot, startedMs, outcome);\n return;\n }\n file.lastRefreshStartedMs = startedMs;\n file.lastRefreshOutcome = outcome;\n status.writeMainSyncStatusFile(repoRoot, file);\n}\n\n/**\n * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log\n * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to\n * name every branch written, not just the tree the refresher happened to run in.\n */\n// webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape\nfunction summarize(file: MainSyncStatusFile): (branch: string) => string {\n return (branch: string): string => {\n const status = file.branches[branch];\n if (status === undefined) return `${branch}(?)`;\n return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;\n };\n}\n\n/**\n * Delete the branches the verdicts just declared dead. Returns how many actually went.\n *\n * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup\n * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded\n * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that\n * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on\n * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.\n *\n * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the\n * main-sync status this process exists to produce — but every failure is logged, because a silent\n * background deletion is exactly what nobody should have to trust.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nasync function autoReap(repoRoot: string, cache: MergedBranchesCache): Promise<number> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const config = loadAndValidate(repoRoot).rulesConfig['branch-creation-guard'] as BranchCreationGuardConfig | undefined;\n // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,\n // so every validated config states an answer — which means \"absent\" here is not a consumer\n // who wants the default, it is a config that never passed validation. Deleting branches on\n // that basis would be deleting on a preference nobody expressed.\n if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true) return 0;\n\n const result: ReapResult = await new BranchReaper().reap(repoRoot, 'auto-reap', cache);\n for (const failure of result.failed) {\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));\n }\n return result.reaped.length;\n } catch (err: unknown) {\n const error = toError(err);\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));\n return 0;\n }\n}\n\nif (require.main === module) runMain(main);\n"]}