@webpieces/agent-workflow-rules 0.4.958 → 0.4.959

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.958",
3
+ "version": "0.4.959",
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.958",
28
- "@webpieces/rules-config": "0.4.958",
27
+ "@webpieces/hook-runtime": "0.4.959",
28
+ "@webpieces/rules-config": "0.4.959",
29
29
  "inversify": "7.10.4",
30
30
  "reflect-metadata": "0.2.2",
31
- "@webpieces/tooling-common": "0.4.958",
32
- "@webpieces/repo-workflow-core": "0.4.958",
31
+ "@webpieces/tooling-common": "0.4.959",
32
+ "@webpieces/repo-workflow-core": "0.4.959",
33
33
  "tslib": "2.8.1",
34
- "@webpieces/rules-sdk": "0.4.958"
34
+ "@webpieces/rules-sdk": "0.4.959"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"
38
38
  },
39
39
  "devDependencies": {
40
- "@webpieces/tooling-testkit": "0.4.958"
40
+ "@webpieces/tooling-testkit": "0.4.959"
41
41
  },
42
42
  "types": "./src/index.d.ts",
43
43
  "bin": {
@@ -74,6 +74,7 @@ function useCaseRow(useCase) {
74
74
  function renderL2Doc() {
75
75
  return [
76
76
  ...renderHead(),
77
+ ...renderRefreshCadence(),
77
78
  ...renderTable(),
78
79
  ...renderTableNotes(),
79
80
  ...renderUseCases(),
@@ -152,6 +153,25 @@ function renderHead() {
152
153
  '',
153
154
  ];
154
155
  }
156
+ // The refresh cadence (#1342) — its own section of the head, split out to keep renderHead inside the
157
+ // method-line budget. The join order in renderL2Doc places it right after the cache prose.
158
+ // webpieces-disable no-function-outside-class -- a section of renderL2Doc's string, beside it in this module
159
+ function renderRefreshCadence() {
160
+ return [
161
+ '**The refresher STARTS at most once every 10 minutes per repo** (`MIN_REFRESH_INTERVAL_MINUTES`).',
162
+ 'The guard decides before it launches anything: one read of `lastRefreshStartedMs` in the status',
163
+ 'file. Inside the interval nothing is spawned and no git runs; past it, the guard creates',
164
+ '`main-sync.lock.json` exclusively (so of several hook processes firing at once exactly one',
165
+ 'launches), and the detached child adopts that lock rather than creating its own. The lock is only a',
166
+ 'mutex (`pid`, `startedMs`): the child writes the status file and its stamp FIRST and deletes the',
167
+ 'lock LAST. A failed run still records its start, so it is retried after the interval rather than on',
168
+ 'every call; a hung or crashed one leaves its lock, which is reclaimed once past `hangTimeoutMinutes`,',
169
+ 'its holder killed. Every command the refresher runs is bounded by a timeout. Commands that act on',
170
+ '`main` (`pnpm wp-sync-main`, the `wp-*` PR flow) fetch for themselves, so the interval never makes',
171
+ 'a gate decision stale.',
172
+ '',
173
+ ];
174
+ }
155
175
  // The legend and the table itself — this is the ROW DATA.
156
176
  // webpieces-disable no-function-outside-class -- second section of renderL2Doc's string, beside it in this module
157
177
  function renderTable() {
@@ -1 +1 @@
1
- {"version":3,"file":"l2-doc.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/l2-doc.ts"],"names":[],"mappings":";;AA4EA,kCASC;AArFD,uCAA4G;AAE5G,8EAA8E;AAC9E,oDAAoD;AACpD,EAAE;AACF,uGAAuG;AACvG,uGAAuG;AACvG,mCAAmC;AACnC,EAAE;AACF,uGAAuG;AACvG,qGAAqG;AACrG,4FAA4F;AAC5F,2FAA2F;AAC3F,uDAAuD;AACvD,EAAE;AACF,sGAAsG;AACtG,iDAAiD;AACjD,8EAA8E;AAE9E,iHAAiH;AACjH,SAAS,QAAQ,CAAC,GAAU;IACxB,OAAO,KAAK,GAAG,CAAC,GAAG,QAAQ,GAAG,CAAC,QAAQ,EAAE,QAAQ,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EAAiE;AACjE,gHAAgH;AAChH,SAAS,UAAU;IACf,OAAO;QACH,iDAAiD;QACjD,EAAE;QACF,GAAG,iBAAiB,EAAE;QACtB,EAAE;QACF,sGAAsG;QACtG,sFAAsF;QACtF,EAAE;QACF,4CAA4C;QAC5C,EAAE;QACF,mGAAmG;QACnG,oGAAoG;QACpG,kGAAkG;QAClG,kGAAkG;QAClG,qGAAqG;QACrG,iGAAiG;QACjG,qGAAqG;QACrG,mGAAmG;QACnG,8FAA8F;QAC9F,mGAAmG;QACnG,iGAAiG;QACjG,mBAAmB;QACnB,qGAAqG;QACrG,iGAAiG;QACjG,0CAA0C;QAC1C,EAAE;QACF,KAAK;QACL,EAAE;QACF,EAAE;QACF,iBAAiB;QACjB,EAAE;QACF,6BAA6B;QAC7B,eAAe;QACf,2HAA2H;QAC3H,4FAA4F;QAC5F,qHAAqH;QACrH,+HAA+H;QAC/H,kIAAkI;QAClI,2IAA2I;QAC3I,4IAA4I;QAC5I,sFAAsF;QACtF,8IAA8I;QAC9I,2JAA2J;QAC3J,EAAE;KACL,CAAC;AACN,CAAC","sourcesContent":["import { L2Row, L2NotDone, L2UseCase, L2_ROWS, L2_FAIL_OPEN_ROW, NOT_DONE, allL2UseCases } from './l2-rows';\n\n// ---------------------------------------------------------------------------\n// guards/L2-branch-state.md, rendered from L2_ROWS.\n//\n// Same arrangement as l1-doc.renderL1Doc(): one join('\\n') of literal markdown lines with the ROW DATA\n// interpolated from the array. Everything that is not row data is a literal line here, because that is\n// the half a generator cannot own.\n//\n// A unit test (l2-matrix.spec.ts) locks guards/L2-branch-state.md byte-identical to renderL2Doc(), and\n// `pnpm guards:generate` rewrites the file. The doc that stood here before was 100% hand-written and\n// carried its own warning that it could drift; it did, in three places at once (it proposed\n// `branch-state-guard` as a future key while GUARD_MATRIX.md proposed a different name and\n// docs/plans/guard-layer-toggles.md proposed a third).\n//\n// This module, like l2-rows.ts, has no runtime imports outside this pair so the generator can load it\n// without the package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL2Doc below, in this render module\nfunction tableRow(row: L2Row): string {\n return `| ${row.num} | \\`${row.toolCell()}\\` | ${row.state} | ${row.action.label} | ${row.cure} |`;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL2Doc below, in this render module\nfunction notDoneRow(entry: L2NotDone): string {\n return `| ${entry.row} | ${entry.gap} | ${entry.why} |`;\n}\n\n/**\n * The \"Not done\" body — a table when there are gaps, a SENTENCE when there are none.\n *\n * An empty table renders as a bare header with nothing under it, which reads like a rendering bug\n * rather than like an achievement. \"Every row is honoured\" is a claim worth making in words, and it is\n * the state this section exists to drive the layer towards.\n */\n// webpieces-disable no-function-outside-class -- section builder for renderL2Doc below, in this render module\nfunction renderNotDoneBody(): string[] {\n if (NOT_DONE.length === 0) {\n return [\n '**Nothing. Every row in the table above is a row the guards actually honour today.**',\n '',\n 'That has not always been true, and the section stays here for when it stops being true again:',\n 'a row the code cannot yet honour is listed here rather than rendered as if it were live, the',\n 'same way L1 lists its unreachable `o` row. The three entries this section used to carry were',\n 'row 5\\'s Bash half (shipped, then moved: Bash on `main` is judged on FRESHNESS at rows 6/7, while',\n 'row 5 keeps the unconditional WRITE block) and the DIRTY-TREE',\n 'valves on rows 6 and 8 — both closed, because each of those rows cures with',\n '`git checkout -b <new> origin/main`, which carries uncommitted changes onto the new branch. A',\n 'dirty tree never trapped anyone; the row 6 message just printed the one cure that could not run',\n 'dirty, and the fix was to print both.',\n ];\n }\n return [\n 'Each row below describes INTENT the code has not caught up with. They are listed rather than',\n 'silently rendered as if they were live, the same way L1 lists its unreachable `o` row. Every one of',\n `them currently exits at row ${L2_FAIL_OPEN_ROW} instead, so the log never claims the strict row fired.`,\n '',\n '| row | the gap | why it has not shipped |',\n '|---|---|---|',\n ...NOT_DONE.map(notDoneRow),\n ];\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL2Doc below, in this render module\nfunction useCaseRow(useCase: L2UseCase): string {\n return `| ${useCase.num} | ${useCase.symptom} | ${useCase.state} | ${useCase.verdict} | ${useCase.fix} |`;\n}\n\n/**\n * Render guards/L2-branch-state.md.\n *\n * Split into sections purely to stay inside the method-line budget — the join order is what makes them\n * one file, so keep them adjacent and keep the byte-lock test as the arbiter.\n */\n// webpieces-disable no-function-outside-class -- pure string builder over L2_ROWS, beside the array it reads\nexport function renderL2Doc(): string {\n return [\n ...renderHead(),\n ...renderTable(),\n ...renderTableNotes(),\n ...renderUseCases(),\n ...renderNotes(),\n ...renderTail(),\n ].join('\\n');\n}\n\n// webpieces-disable no-function-outside-class -- first section of renderL2Doc's string, beside it in this module\nfunction renderHead(): string[] {\n return [\n '# L2 — branch state',\n '',\n '**Goal: may I work here, and is what I read current?**',\n '',\n '**Config key: `branch-state-guard`.** ONE key for the whole policy. It used to be FOUR —',\n '`feature-branch-guard`, `read-stale-guard`, `stale-main-bash-guard`, `merged-branch-bash-guard` —',\n 'and three of them carried nothing but `mode` plus the two escape hatches. Four keys made HALF a',\n 'policy representable: `read-stale-guard: OFF` beside `merged-branch-bash-guard: ON` is \"read the',\n 'file, yes; `cat` the same file, no\" — the same information, opposite verdicts, chosen by nobody.',\n 'One key makes that unconstructible. The four class NAMES are unchanged and still appear as `rule=`',\n 'on every decision-log line, so `grep rule=stale-main-bash-guard` keeps working; only the switch',\n 'merged. The four old keys are rejected by name with this destination — see `retired-config-keys.ts`.',\n '',\n '**Code:** `agent-workflow-rules/src/core/rules/{feature-branch,read-stale,stale-main-bash,merged-branch-bash}-guard.ts` ·',\n 'the rows in `agent-workflow-rules/src/core/l2-rows.ts` · the shared cache in',\n '`rules-config/src/main-sync-status.ts` + `main-sync-file.ts` · the refresher in',\n '`agent-workflow-rules/src/core/sync-main.ts`.',\n '',\n '## The four classes, and why there are four',\n '',\n '| | Write/Edit | Read | Bash |',\n '|---|---|---|---|',\n '| **state A** — stale `main` | `feature-branch-guard` | `read-stale-guard` | `stale-main-bash-guard` |',\n '| **state B** — merged branch | `feature-branch-guard` | `read-stale-guard` | `merged-branch-bash-guard` |',\n '',\n 'The split is TOOL WIRING, not policy. A Read names exactly one file; a Bash command is opaque; a',\n 'Write is neither.',\n '',\n '**The two Bash guards used to differ in polarity, and no longer do.** merged-branch was',\n 'default-DENY + allowlist; stale-main was default-ALLOW + blocklist of content readers, so',\n '`pnpm build` was denied by one and allowed by the other for the same reason — \"you should not be',\n 'working in this tree\". A blocklist of readers structurally cannot catch an installer, a formatter',\n 'or a codegen step, so both states now use default-DENY plus one shared `RecoveryAllowlist` (the',\n 'row 4 skip list). Two skip lists drift, and the half that drifts is the half that wedges a session',\n 'on its own cure.',\n '',\n '**What is gated is WHEN that polarity applies, not the polarity.** stale-main asks the cache',\n 'whether cached `commitsBehind` exceeds `branch-state-guard.maxCommitsBehind` (rows 6/7) and',\n 'default-denies only then; a current or tolerated `main` — which is',\n 'exactly where `pnpm wp-sync-main` leaves you — is not this guard\\'s business at all.',\n '',\n 'They remain separate CLASSES because the states they detect are different — one reads the branch',\n 'name, the other the cached merged flag — and because each carries its own message.',\n '',\n '## The cache',\n '',\n 'the main-sync status file in the primary clone\\'s state directory, written by a **detached single-flight',\n 'refresher**. It is fire-and-forget: it populates the cache for the NEXT call, never the current',\n 'one — so the first tool call of every session sees no cache and takes row ' + String(L2_FAIL_OPEN_ROW) + '. That is intended,',\n 'and it is why the on-main write block (row 5) must not depend on the cache.',\n 'That refresh also computes `commitsBehind`; guards never count on the hot path, and missing counts fail open.',\n '',\n 'The file holds a **map of branch → status**, so every worktree\\'s guards stay armed. Before that it',\n 'held one branch\\'s snapshot, so with N worktrees at most one tree was armed at any instant and the',\n 'rest abstained, thrashing as the lock changed hands.',\n '',\n '**There is no TTL.** `timestamp` is logged and never enforced; an hours-old cache whose branch',\n 'matches is trusted to block. State A is mitigated by a live ancestry check (`git merge-base',\n '--is-ancestor`, not hash equality, so a pull takes effect instantly); state B trusts the cached',\n 'merged flag, which is safe only because \"merged\" is monotonic.',\n '',\n '**`hangTimeoutMinutes` is ONE knob** — `branch-state-guard.hangTimeoutMinutes` — because there is',\n 'one refresher writing one cache. It used to be declared four times and read four times, which,',\n 'with the refresher\\'s at-most-once-per-process latch and two config-blind callers ahead of the',\n 'guards, meant at most one of the four values could ever reach a spawn.',\n '',\n ];\n}\n\n// The legend and the table itself — this is the ROW DATA.\n// webpieces-disable no-function-outside-class -- second section of renderL2Doc's string, beside it in this module\nfunction renderTable(): string[] {\n return [\n '## Table — one table, ordered, first match wins',\n '',\n '**Tools:** `B` Bash · `R` Read · `E` Write/Edit',\n '',\n '| # | tools | state | act | cure |',\n '|---|---|---|---|---|',\n ...L2_ROWS.map(tableRow),\n '',\n `Rows 1-5 need **no cache** and fire on call #1: rows 1, 2 and 4 are text matches, row 3 is a`,\n `marker-file scan, and row 5 is one \\`git rev-parse\\`. Row ${L2_FAIL_OPEN_ROW} is the divider: everything below it`,\n `reads the main-sync cache, so if the branch is undeterminable, the cache is absent, it holds`,\n `another branch, or the forge could not be reached, evaluation STOPS at row ${L2_FAIL_OPEN_ROW} and ALLOWS.`,\n '',\n `Row ${L2_FAIL_OPEN_ROW} is numbered after row 10 and PRINTED between 5 and 6, and that is not a mistake. Row`,\n 'numbers are identity — they are logged as `row=` and cited here — so renumbering 6-10 to slot it in',\n 'would silently re-point every reference. L1 does the same with its row 8.',\n '',\n ];\n}\n\n// The prose that explains the table's shape — split out of renderTable purely to stay inside the\n// method-line budget. The join order is what makes them one section; keep them adjacent.\n// webpieces-disable no-function-outside-class -- continuation of renderTable above, beside it in this module\nfunction renderTableNotes(): string[] {\n return [\n '### The one rule that explains the tool column',\n '',\n '**`B` tracks `E` everywhere except on `main`, where `B` tracks `R` instead — rows 5, 6 and 7.**',\n '',\n 'The hazards differ. A WRITE on `main` lands work somewhere unreviewable and unrevertable at ANY',\n 'freshness, so row 5 is `E` only and is judged from the branch alone, above the cache divider. A',\n 'READ or a BUILD on a CURRENT `main` harms nothing, and blocking it strands the agent immediately',\n 'after `pnpm wp-sync-main` — the command this repo prescribes — put it there. So `B` joins',\n '`R` on the freshness-gated pair: row 6 (behind) blocks, row 7 (current) allows, and \"cannot tell\"',\n 'fails open at row ' + String(L2_FAIL_OPEN_ROW) + ' by construction.',\n '',\n 'Inside row 6 they still differ in SHAPE: a Read names exactly one file and is evaluated precisely;',\n 'a Bash command is opaque and gets the conservative answer, default-deny plus the row 4 skip list.',\n '',\n '### Why the order of row 5 is the most load-bearing thing here',\n '',\n 'L2 is armed **from the second tool call onward**, because the refresher populates the cache for the',\n 'NEXT call. That is deliberate — it keeps the blocking path free of network git — and it is fine in',\n 'practice, because the agent discovers the problem within a command or two.',\n '',\n `Row 5 is the exception that must not be relaxed. Put \"on \\`main\\`\" BELOW row ${L2_FAIL_OPEN_ROW} and WRITES on \\`main\\``,\n 'are permitted for the whole first call of every session — and permanently in a multi-worktree repo,',\n 'where another tree can hold the refresh lock indefinitely. That is why row 5 is `E` only: the Bash',\n 'half asks a question the cache CAN answer late without harm (\"is `main` behind?\"), so it belongs',\n 'below the divider, where not knowing means allowing.',\n '',\n '### Why row 9 can block reads without trapping you',\n '',\n 'Blocking reads on a broken fork point looks like it traps the agent away from the files it must',\n 'read to resolve the conflict. It does not, because **row 3 comes first**:',\n '',\n 'blocked → `pnpm wp-start-update` (row 4, skip list) → now merge-in-progress → **row 3 exempts',\n 'everything** → read and write freely to resolve → finish. The exemption row is what lets row 9 be',\n 'strict.',\n '',\n '### Why row 8 can block reads on a dirty tree',\n '',\n '`git checkout -b <new> origin/main` **carries uncommitted changes onto the new branch**. The work',\n 'comes with you, so nothing needs reading first and nothing is trapped. Residual: if `origin/main`',\n 'changed the same files you edited, git refuses the switch — `git stash` is on the skip list and',\n 'clears it.',\n '',\n 'Row 6 looked like the one place the dirty argument had teeth, because its FIRST cure pulls, and a',\n 'pull genuinely is not a clean fast-forward on a dirty tree. But row 6 has always carried a SECOND',\n 'cure — `git checkout -b <new> origin/main` — and that one works dirty for exactly the reason above.',\n 'The teeth were in the MESSAGE, which printed only the pull; it now prints both, labelled, so the',\n 'cure an agent reads is always one it can run. **So there is no dirty row anywhere, and no dirty',\n 'valve in the code either** — both were closed, and \"Not done\" is empty as a result.',\n '',\n '### Rows 12 and 13 — the cure may be COMPOSED with the work, but only with `&&`',\n '',\n '`pnpm wp-sync-main && cat src/app.ts` is ALLOWED. `pnpm wp-sync-main ; cat',\n 'src/app.ts` is REFUSED, and the refusal names the operator you typed.',\n '',\n 'The difference belongs to the shell, not to this guard. `&&` short-circuits: the work cannot run',\n 'when the cure exits non-zero, which is exactly the property the row 6 block exists to guarantee.',\n 'Refusing that bought nothing and cost a round trip. `;` discards the cure\\'s exit code and runs the',\n 'work regardless — measured with `>/dev/null 2>&1` on the cure in 7 of 9 observed cases, so the',\n 'failure was invisible as well as ignored. The two-step is genuinely safer there, because the NEXT',\n 'tool call is a fresh evaluation that recomputes `localMain` against `originMain`: a failed pull',\n 're-blocks. An allowed `;` compound never gets that second look.',\n '',\n '`git fetch` may LEAD the prefix (`git fetch --prune origin main && git pull --ff-only origin main`',\n 'is the shape agents type) but never satisfies it alone: a fetch moves the remote-tracking ref and',\n 'leaves local `main` exactly as far behind, so there is nothing for the `&&` to protect.',\n '',\n ];\n}\n\n// The use-case table (ROW DATA, in the doc's own global numbering) and the note that explains it.\n// webpieces-disable no-function-outside-class -- third section of renderL2Doc's string, beside it in this module\nfunction renderUseCases(): string[] {\n return [\n '## L2 use cases',\n '',\n 'Same row shape as L0 and L1: the **Fix** is literal or it is not a fix. Each case is attached IN',\n 'CODE to the row that judges it (`useCases` on `L2Row`), so this table cannot describe a row that no',\n 'longer exists and a row cannot quietly acquire behaviour nothing documents.',\n '',\n '**This table is how the layer LEARNS.** When a new situation comes up in a session, the change is',\n 'one more `new L2UseCase(...)` on the row that judged it — not a paragraph added here, which the',\n 'byte-lock spec would reject anyway. Every case also carries the exact `reason` string the guard',\n 'logs, and a spec pushes that back through `l2RowForReason` to assert it lands on the row it is filed',\n 'under. So a case whose row is wrong fails the build rather than misinforming a reader.',\n '',\n '| # | what you SEE (exact symptom) | state | verdict | Fix |',\n '|---|---|---|---|---|',\n ...allL2UseCases().map(useCaseRow),\n '',\n 'The incidental-write case under row 6 is the one to read first: `npx expo install` on `main`, in',\n 'another repo on this toolchain, modified two tracked files and no guard fired. It is filed under row',\n '6 rather than row 5 because that is the row that judges Bash on `main` today — a command\\'s stated',\n 'purpose never says whether it also writes, which is why the shape there is default-deny plus the row',\n '4 skip list rather than a blocklist of readers anybody could have enumerated.',\n '',\n ];\n}\n\n// How the log joins to this table, and the skip list. Prose plus the reason→row contract.\n// webpieces-disable no-function-outside-class -- fourth section of renderL2Doc's string, beside it in this module\nfunction renderNotes(): string[] {\n return [\n '## How a log line joins to a row',\n '',\n 'Every L2 decision is written to the L2-decisions log (one file per writer) with `layer=L2` and',\n '`row=<n>`, where `<n>` is a row number from the table above. So `row=8` means \"this call was judged',\n 'by row 8\" and you read the state, the verdict and the cure straight off this page.',\n '',\n '**The join is by REASON, not by dispatch, and the difference is worth knowing.** L1 takes the first',\n 'matching row and switches on it, so deleting an L1 row deletes a block. L2\\'s four classes each own',\n 'their own ladder (see \"The four classes\" above for why they cannot be one function), and',\n '`L2_ROW_FOR_REASON` in `l2-rows.ts` maps each ladder exit to the row it is an instance of. A unit',\n 'test reads the four guard sources and asserts every reason literal resolves to a row, so a new exit',\n 'with no row fails the build rather than logging `row=-` forever.',\n '',\n '## The skip list (row 4)',\n '',\n 'Principle: **these get you OUT or tell you where you are.** They are not \"working here\".',\n '',\n '| group | commands |',\n '|---|---|',\n '| get out | `git checkout -b <new> origin/main` · `git switch -c <new> origin/main` · `git switch <other>` · `git worktree add … -b <new> origin/main` |',\n '| make `main` current | `pnpm wp-sync-main` *(the prescribed form — also reaps dead branches/worktrees and sweeps orphan directories)* · `git pull` · `git fetch` · `git checkout main && git pull origin main` *(paired only; still allowed, and still the L0 recovery cure, where no `pnpm` bin can be trusted)* |',\n '| orient | `git status\\\\|log\\\\|diff\\\\|branch` · `gh` generally (`pr view`, `pr close`, `pr comment`, `api`, `run watch` — it talks to GitHub, not to this tree) |',\n '| talk to the network | `curl` · `wget` — a URL is not this repo. NOT the forms that write a local file: `curl -o`, `wget -O`, `gh repo clone`, `gh pr checkout`, `gh run download`, or any `> file` redirect |',\n '| park work | `git stash` |',\n '| repair / tooling | `pnpm wp-start-update` · `pnpm wp-start-upsert-pr` · the `wp-*` bins |',\n '',\n '**NOT on it:** `git commit` `add` `push` `merge` `rebase` `reset` `restore` `clean` `cherry-pick` ·',\n '`git grep` `show <rev>:<path>` `cat-file` `ls-files` (those read tracked content). **`pnpm build` /',\n '`pnpm test` are not on it either** — there is no point running them on `main` or on a dead branch.',\n '',\n '## Cannot tell — everything that lands on row ' + String(L2_FAIL_OPEN_ROW),\n '',\n '| state | expected? | treatment |',\n '|---|---|---|',\n '| cache absent | **yes** — the refresher populates for the NEXT call, so this fires on the first tool call of every session | fail open, log |',\n '| detached HEAD | **yes** — mid-rebase, `git checkout <sha>` | fail open, log |',\n '| forge unreachable | **yes** — `gh` missing, unauthenticated, rate-limited or offline | fail open, log as `no-forge` |',\n '| branch unresolvable | **no** — not a repo, git broken | fail open, log LOUDLY |',\n '| cache for another branch | **no** — unreachable since the cache became branch-keyed | fail open, log LOUDLY |',\n '',\n '**Do NOT block to capture these cases.** `cache-absent` fires on every session\\'s first call;',\n 'blocking there deadlocks every session behind a network fetch. And if a guard cannot establish',\n 'state, blocking means a *broken* guard wedges the session — the exact failure this family exists to',\n 'avoid.',\n '',\n '`ALLOW_FAIL_OPEN` is a TYPED VERDICT, not a string suffix on the reason, so abstentions are',\n 'countable. `no-forge` is the newest member: `branchAlreadyMerged: false` used to be produced both by',\n '\"this branch has no merged PR\" and by \"we could not ask\", and both logged a plain ALLOW — so from',\n 'the trail you could not tell whether the merged-branch policy was protecting anything or quietly',\n 'standing down.',\n '',\n ];\n}\n\n// The gaps between the table and the code, and the code anchors.\n// webpieces-disable no-function-outside-class -- last section of renderL2Doc's string, beside it in this module\nfunction renderTail(): string[] {\n return [\n '## Not done — rows the guards do not yet honour',\n '',\n ...renderNotDoneBody(),\n '',\n 'This section is generated from `NOT_DONE` in `l2-rows.ts`, so closing a gap means deleting its entry',\n 'and the doc follows — it cannot rot into a list of things that were fixed years ago.',\n '',\n '## Incidents these guards exist because of',\n '',\n '- **The 157-commit checkout.** An agent ran `git checkout main` in a clone whose local `main` was',\n ' 157 commits behind. That checkout reverted the `@webpieces` pin, reverted the guard shim — **the',\n ' drift guard itself** — to a copy whose message stated the drift backwards, and so reverted the',\n ' agent\\'s judgment: it ran the `pnpm install` that message named and downgraded `node_modules`.',\n ' Lesson, quoted from the code: *a guard a stale checkout can revert cannot be relied on to catch a',\n ' stale checkout.* Hence row 2, which is preventive, matches on command TEXT only, and asks git',\n ' nothing — deliberately, because the only `main` it could measure is the one it is about to leave.',\n '- **The side door.** An agent on a `main` 18 commits behind (108 files, +8069/−3692 upstream) had',\n ' its Read tool blocked exactly as designed, then spent the session `ls`-ing, `grep`-ing and',\n ' `cat`-ing the same stale tree, and described a CI workflow set missing a 186-line workflow that',\n ' existed upstream. *The logs read \"read-stale-guard handled\", which is worse than no guard: it',\n ' looks covered.*',\n '- **Computed and thrown away.** Both file guards are file-scoped, so Bash reached neither. An agent',\n ' that only ran shell sailed through on a merged branch **even though `branchAlreadyMerged` was',\n ' loaded and logged on that very path.**',\n '',\n '---',\n '',\n '',\n '## Code anchors',\n '',\n '| section | file | symbol |',\n '|---|---|---|',\n '| the rows + the reason→row join | `agent-workflow-rules/src/core/l2-rows.ts` | `L2_ROWS`, `l2RowForReason`, `NOT_DONE` |',\n '| write policy | `agent-workflow-rules/src/core/rules/feature-branch-guard.ts` | `check` |',\n '| read policy | `agent-workflow-rules/src/core/rules/read-stale-guard.ts` | `checkStaleMain`, `checkMergedBranch` |',\n '| stale-main Bash | `agent-workflow-rules/src/core/rules/stale-main-bash-guard.ts` | `checkFreshness`, `bareCheckoutOfMain` |',\n '| the shared freshness predicate | `agent-workflow-rules/src/core/rules/main-freshness.ts` | `containsOriginMain`, `summarize` |',\n '| merged-branch Bash | `agent-workflow-rules/src/core/rules/merged-branch-bash-guard.ts` | `isFullyRecovery`, `ALLOWED_GIT_SUBCOMMANDS` |',\n '| the cache | `rules-config/src/main-sync-status.ts`, `main-sync-file.ts` | `readMainSyncStatus`, `MainSyncStatusFile`, `forgeReachable` |',\n '| the refresher | `agent-workflow-rules/src/core/sync-main.ts` | `refreshMainSync` |',\n '| command scanning | `agent-workflow-rules/src/core/rules/content-read-scan.ts`, `shell-segment-scan.ts` | `readsStaleContent`, `classify` |',\n '| the config key | `agent-workflow-rules/src/configs/main-sync-guard-configs.ts`, `policy-keys.ts` | `BranchStateGuardConfig`, `BRANCH_STATE_GUARD_KEY` |',\n '',\n ];\n}\n"]}
1
+ {"version":3,"file":"l2-doc.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/l2-doc.ts"],"names":[],"mappings":";;AA4EA,kCAUC;AAtFD,uCAA4G;AAE5G,8EAA8E;AAC9E,oDAAoD;AACpD,EAAE;AACF,uGAAuG;AACvG,uGAAuG;AACvG,mCAAmC;AACnC,EAAE;AACF,uGAAuG;AACvG,qGAAqG;AACrG,4FAA4F;AAC5F,2FAA2F;AAC3F,uDAAuD;AACvD,EAAE;AACF,sGAAsG;AACtG,iDAAiD;AACjD,8EAA8E;AAE9E,iHAAiH;AACjH,SAAS,QAAQ,CAAC,GAAU;IACxB,OAAO,KAAK,GAAG,CAAC,GAAG,QAAQ,GAAG,CAAC,QAAQ,EAAE,QAAQ,GAAG,CAAC,KAAK,MAAM,GAAG,CAAC,MAAM,CAAC,KAAK,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC;AACvG,CAAC;AAED,iHAAiH;AACjH,SAAS,UAAU,CAAC,KAAgB;IAChC,OAAO,KAAK,KAAK,CAAC,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC;AAC5D,CAAC;A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QAChB,EAAE;KACL,CAAC;AACN,CAAC;AAED,iEAAiE;AACjE,gHAAgH;AAChH,SAAS,UAAU;IACf,OAAO;QACH,iDAAiD;QACjD,EAAE;QACF,GAAG,iBAAiB,EAAE;QACtB,EAAE;QACF,sGAAsG;QACtG,sFAAsF;QACtF,EAAE;QACF,4CAA4C;QAC5C,EAAE;QACF,mGAAmG;QACnG,oGAAoG;QACpG,kGAAkG;QAClG,kGAAkG;QAClG,qGAAqG;QACrG,iGAAiG;QACjG,qGAAqG;QACrG,mGAAmG;QACnG,8FAA8F;QAC9F,mGAAmG;QACnG,iGAAiG;QACjG,mBAAmB;QACnB,qGAAqG;QACrG,iGAAiG;QACjG,0CAA0C;QAC1C,EAAE;QACF,KAAK;QACL,EAAE;QACF,EAAE;QACF,iBAAiB;QACjB,EAAE;QACF,6BAA6B;QAC7B,eAAe;QACf,2HAA2H;QAC3H,4FAA4F;QAC5F,qHAAqH;QACrH,+HAA+H;QAC/H,kIAAkI;QAClI,2IAA2I;QAC3I,4IAA4I;QAC5I,sFAAsF;QACtF,8IAA8I;QAC9I,2JAA2J;QAC3J,EAAE;KACL,CAAC;AACN,CAAC","sourcesContent":["import { L2Row, L2NotDone, L2UseCase, L2_ROWS, L2_FAIL_OPEN_ROW, NOT_DONE, allL2UseCases } from './l2-rows';\n\n// ---------------------------------------------------------------------------\n// guards/L2-branch-state.md, rendered from L2_ROWS.\n//\n// Same arrangement as l1-doc.renderL1Doc(): one join('\\n') of literal markdown lines with the ROW DATA\n// interpolated from the array. Everything that is not row data is a literal line here, because that is\n// the half a generator cannot own.\n//\n// A unit test (l2-matrix.spec.ts) locks guards/L2-branch-state.md byte-identical to renderL2Doc(), and\n// `pnpm guards:generate` rewrites the file. The doc that stood here before was 100% hand-written and\n// carried its own warning that it could drift; it did, in three places at once (it proposed\n// `branch-state-guard` as a future key while GUARD_MATRIX.md proposed a different name and\n// docs/plans/guard-layer-toggles.md proposed a third).\n//\n// This module, like l2-rows.ts, has no runtime imports outside this pair so the generator can load it\n// without the package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL2Doc below, in this render module\nfunction tableRow(row: L2Row): string {\n return `| ${row.num} | \\`${row.toolCell()}\\` | ${row.state} | ${row.action.label} | ${row.cure} |`;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL2Doc below, in this render module\nfunction notDoneRow(entry: L2NotDone): string {\n return `| ${entry.row} | ${entry.gap} | ${entry.why} |`;\n}\n\n/**\n * The \"Not done\" body — a table when there are gaps, a SENTENCE when there are none.\n *\n * An empty table renders as a bare header with nothing under it, which reads like a rendering bug\n * rather than like an achievement. \"Every row is honoured\" is a claim worth making in words, and it is\n * the state this section exists to drive the layer towards.\n */\n// webpieces-disable no-function-outside-class -- section builder for renderL2Doc below, in this render module\nfunction renderNotDoneBody(): string[] {\n if (NOT_DONE.length === 0) {\n return [\n '**Nothing. Every row in the table above is a row the guards actually honour today.**',\n '',\n 'That has not always been true, and the section stays here for when it stops being true again:',\n 'a row the code cannot yet honour is listed here rather than rendered as if it were live, the',\n 'same way L1 lists its unreachable `o` row. The three entries this section used to carry were',\n 'row 5\\'s Bash half (shipped, then moved: Bash on `main` is judged on FRESHNESS at rows 6/7, while',\n 'row 5 keeps the unconditional WRITE block) and the DIRTY-TREE',\n 'valves on rows 6 and 8 — both closed, because each of those rows cures with',\n '`git checkout -b <new> origin/main`, which carries uncommitted changes onto the new branch. A',\n 'dirty tree never trapped anyone; the row 6 message just printed the one cure that could not run',\n 'dirty, and the fix was to print both.',\n ];\n }\n return [\n 'Each row below describes INTENT the code has not caught up with. They are listed rather than',\n 'silently rendered as if they were live, the same way L1 lists its unreachable `o` row. Every one of',\n `them currently exits at row ${L2_FAIL_OPEN_ROW} instead, so the log never claims the strict row fired.`,\n '',\n '| row | the gap | why it has not shipped |',\n '|---|---|---|',\n ...NOT_DONE.map(notDoneRow),\n ];\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL2Doc below, in this render module\nfunction useCaseRow(useCase: L2UseCase): string {\n return `| ${useCase.num} | ${useCase.symptom} | ${useCase.state} | ${useCase.verdict} | ${useCase.fix} |`;\n}\n\n/**\n * Render guards/L2-branch-state.md.\n *\n * Split into sections purely to stay inside the method-line budget — the join order is what makes them\n * one file, so keep them adjacent and keep the byte-lock test as the arbiter.\n */\n// webpieces-disable no-function-outside-class -- pure string builder over L2_ROWS, beside the array it reads\nexport function renderL2Doc(): string {\n return [\n ...renderHead(),\n ...renderRefreshCadence(),\n ...renderTable(),\n ...renderTableNotes(),\n ...renderUseCases(),\n ...renderNotes(),\n ...renderTail(),\n ].join('\\n');\n}\n\n// webpieces-disable no-function-outside-class -- first section of renderL2Doc's string, beside it in this module\nfunction renderHead(): string[] {\n return [\n '# L2 — branch state',\n '',\n '**Goal: may I work here, and is what I read current?**',\n '',\n '**Config key: `branch-state-guard`.** ONE key for the whole policy. It used to be FOUR —',\n '`feature-branch-guard`, `read-stale-guard`, `stale-main-bash-guard`, `merged-branch-bash-guard` —',\n 'and three of them carried nothing but `mode` plus the two escape hatches. Four keys made HALF a',\n 'policy representable: `read-stale-guard: OFF` beside `merged-branch-bash-guard: ON` is \"read the',\n 'file, yes; `cat` the same file, no\" — the same information, opposite verdicts, chosen by nobody.',\n 'One key makes that unconstructible. The four class NAMES are unchanged and still appear as `rule=`',\n 'on every decision-log line, so `grep rule=stale-main-bash-guard` keeps working; only the switch',\n 'merged. The four old keys are rejected by name with this destination — see `retired-config-keys.ts`.',\n '',\n '**Code:** `agent-workflow-rules/src/core/rules/{feature-branch,read-stale,stale-main-bash,merged-branch-bash}-guard.ts` ·',\n 'the rows in `agent-workflow-rules/src/core/l2-rows.ts` · the shared cache in',\n '`rules-config/src/main-sync-status.ts` + `main-sync-file.ts` · the refresher in',\n '`agent-workflow-rules/src/core/sync-main.ts`.',\n '',\n '## The four classes, and why there are four',\n '',\n '| | Write/Edit | Read | Bash |',\n '|---|---|---|---|',\n '| **state A** — stale `main` | `feature-branch-guard` | `read-stale-guard` | `stale-main-bash-guard` |',\n '| **state B** — merged branch | `feature-branch-guard` | `read-stale-guard` | `merged-branch-bash-guard` |',\n '',\n 'The split is TOOL WIRING, not policy. A Read names exactly one file; a Bash command is opaque; a',\n 'Write is neither.',\n '',\n '**The two Bash guards used to differ in polarity, and no longer do.** merged-branch was',\n 'default-DENY + allowlist; stale-main was default-ALLOW + blocklist of content readers, so',\n '`pnpm build` was denied by one and allowed by the other for the same reason — \"you should not be',\n 'working in this tree\". A blocklist of readers structurally cannot catch an installer, a formatter',\n 'or a codegen step, so both states now use default-DENY plus one shared `RecoveryAllowlist` (the',\n 'row 4 skip list). Two skip lists drift, and the half that drifts is the half that wedges a session',\n 'on its own cure.',\n '',\n '**What is gated is WHEN that polarity applies, not the polarity.** stale-main asks the cache',\n 'whether cached `commitsBehind` exceeds `branch-state-guard.maxCommitsBehind` (rows 6/7) and',\n 'default-denies only then; a current or tolerated `main` — which is',\n 'exactly where `pnpm wp-sync-main` leaves you — is not this guard\\'s business at all.',\n '',\n 'They remain separate CLASSES because the states they detect are different — one reads the branch',\n 'name, the other the cached merged flag — and because each carries its own message.',\n '',\n '## The cache',\n '',\n 'the main-sync status file in the primary clone\\'s state directory, written by a **detached single-flight',\n 'refresher**. It is fire-and-forget: it populates the cache for the NEXT call, never the current',\n 'one — so the first tool call of every session sees no cache and takes row ' + String(L2_FAIL_OPEN_ROW) + '. That is intended,',\n 'and it is why the on-main write block (row 5) must not depend on the cache.',\n 'That refresh also computes `commitsBehind`; guards never count on the hot path, and missing counts fail open.',\n '',\n 'The file holds a **map of branch → status**, so every worktree\\'s guards stay armed. Before that it',\n 'held one branch\\'s snapshot, so with N worktrees at most one tree was armed at any instant and the',\n 'rest abstained, thrashing as the lock changed hands.',\n '',\n '**There is no TTL.** `timestamp` is logged and never enforced; an hours-old cache whose branch',\n 'matches is trusted to block. State A is mitigated by a live ancestry check (`git merge-base',\n '--is-ancestor`, not hash equality, so a pull takes effect instantly); state B trusts the cached',\n 'merged flag, which is safe only because \"merged\" is monotonic.',\n '',\n '**`hangTimeoutMinutes` is ONE knob** — `branch-state-guard.hangTimeoutMinutes` — because there is',\n 'one refresher writing one cache. It used to be declared four times and read four times, which,',\n 'with the refresher\\'s at-most-once-per-process latch and two config-blind callers ahead of the',\n 'guards, meant at most one of the four values could ever reach a spawn.',\n '',\n ];\n}\n\n// The refresh cadence (#1342) — its own section of the head, split out to keep renderHead inside the\n// method-line budget. The join order in renderL2Doc places it right after the cache prose.\n// webpieces-disable no-function-outside-class -- a section of renderL2Doc's string, beside it in this module\nfunction renderRefreshCadence(): string[] {\n return [\n '**The refresher STARTS at most once every 10 minutes per repo** (`MIN_REFRESH_INTERVAL_MINUTES`).',\n 'The guard decides before it launches anything: one read of `lastRefreshStartedMs` in the status',\n 'file. Inside the interval nothing is spawned and no git runs; past it, the guard creates',\n '`main-sync.lock.json` exclusively (so of several hook processes firing at once exactly one',\n 'launches), and the detached child adopts that lock rather than creating its own. The lock is only a',\n 'mutex (`pid`, `startedMs`): the child writes the status file and its stamp FIRST and deletes the',\n 'lock LAST. A failed run still records its start, so it is retried after the interval rather than on',\n 'every call; a hung or crashed one leaves its lock, which is reclaimed once past `hangTimeoutMinutes`,',\n 'its holder killed. Every command the refresher runs is bounded by a timeout. Commands that act on',\n '`main` (`pnpm wp-sync-main`, the `wp-*` PR flow) fetch for themselves, so the interval never makes',\n 'a gate decision stale.',\n '',\n ];\n}\n\n// The legend and the table itself — this is the ROW DATA.\n// webpieces-disable no-function-outside-class -- second section of renderL2Doc's string, beside it in this module\nfunction renderTable(): string[] {\n return [\n '## Table — one table, ordered, first match wins',\n '',\n '**Tools:** `B` Bash · `R` Read · `E` Write/Edit',\n '',\n '| # | tools | state | act | cure |',\n '|---|---|---|---|---|',\n ...L2_ROWS.map(tableRow),\n '',\n `Rows 1-5 need **no cache** and fire on call #1: rows 1, 2 and 4 are text matches, row 3 is a`,\n `marker-file scan, and row 5 is one \\`git rev-parse\\`. Row ${L2_FAIL_OPEN_ROW} is the divider: everything below it`,\n `reads the main-sync cache, so if the branch is undeterminable, the cache is absent, it holds`,\n `another branch, or the forge could not be reached, evaluation STOPS at row ${L2_FAIL_OPEN_ROW} and ALLOWS.`,\n '',\n `Row ${L2_FAIL_OPEN_ROW} is numbered after row 10 and PRINTED between 5 and 6, and that is not a mistake. Row`,\n 'numbers are identity — they are logged as `row=` and cited here — so renumbering 6-10 to slot it in',\n 'would silently re-point every reference. L1 does the same with its row 8.',\n '',\n ];\n}\n\n// The prose that explains the table's shape — split out of renderTable purely to stay inside the\n// method-line budget. The join order is what makes them one section; keep them adjacent.\n// webpieces-disable no-function-outside-class -- continuation of renderTable above, beside it in this module\nfunction renderTableNotes(): string[] {\n return [\n '### The one rule that explains the tool column',\n '',\n '**`B` tracks `E` everywhere except on `main`, where `B` tracks `R` instead — rows 5, 6 and 7.**',\n '',\n 'The hazards differ. A WRITE on `main` lands work somewhere unreviewable and unrevertable at ANY',\n 'freshness, so row 5 is `E` only and is judged from the branch alone, above the cache divider. A',\n 'READ or a BUILD on a CURRENT `main` harms nothing, and blocking it strands the agent immediately',\n 'after `pnpm wp-sync-main` — the command this repo prescribes — put it there. So `B` joins',\n '`R` on the freshness-gated pair: row 6 (behind) blocks, row 7 (current) allows, and \"cannot tell\"',\n 'fails open at row ' + String(L2_FAIL_OPEN_ROW) + ' by construction.',\n '',\n 'Inside row 6 they still differ in SHAPE: a Read names exactly one file and is evaluated precisely;',\n 'a Bash command is opaque and gets the conservative answer, default-deny plus the row 4 skip list.',\n '',\n '### Why the order of row 5 is the most load-bearing thing here',\n '',\n 'L2 is armed **from the second tool call onward**, because the refresher populates the cache for the',\n 'NEXT call. That is deliberate — it keeps the blocking path free of network git — and it is fine in',\n 'practice, because the agent discovers the problem within a command or two.',\n '',\n `Row 5 is the exception that must not be relaxed. Put \"on \\`main\\`\" BELOW row ${L2_FAIL_OPEN_ROW} and WRITES on \\`main\\``,\n 'are permitted for the whole first call of every session — and permanently in a multi-worktree repo,',\n 'where another tree can hold the refresh lock indefinitely. That is why row 5 is `E` only: the Bash',\n 'half asks a question the cache CAN answer late without harm (\"is `main` behind?\"), so it belongs',\n 'below the divider, where not knowing means allowing.',\n '',\n '### Why row 9 can block reads without trapping you',\n '',\n 'Blocking reads on a broken fork point looks like it traps the agent away from the files it must',\n 'read to resolve the conflict. It does not, because **row 3 comes first**:',\n '',\n 'blocked → `pnpm wp-start-update` (row 4, skip list) → now merge-in-progress → **row 3 exempts',\n 'everything** → read and write freely to resolve → finish. The exemption row is what lets row 9 be',\n 'strict.',\n '',\n '### Why row 8 can block reads on a dirty tree',\n '',\n '`git checkout -b <new> origin/main` **carries uncommitted changes onto the new branch**. The work',\n 'comes with you, so nothing needs reading first and nothing is trapped. Residual: if `origin/main`',\n 'changed the same files you edited, git refuses the switch — `git stash` is on the skip list and',\n 'clears it.',\n '',\n 'Row 6 looked like the one place the dirty argument had teeth, because its FIRST cure pulls, and a',\n 'pull genuinely is not a clean fast-forward on a dirty tree. But row 6 has always carried a SECOND',\n 'cure — `git checkout -b <new> origin/main` — and that one works dirty for exactly the reason above.',\n 'The teeth were in the MESSAGE, which printed only the pull; it now prints both, labelled, so the',\n 'cure an agent reads is always one it can run. **So there is no dirty row anywhere, and no dirty',\n 'valve in the code either** — both were closed, and \"Not done\" is empty as a result.',\n '',\n '### Rows 12 and 13 — the cure may be COMPOSED with the work, but only with `&&`',\n '',\n '`pnpm wp-sync-main && cat src/app.ts` is ALLOWED. `pnpm wp-sync-main ; cat',\n 'src/app.ts` is REFUSED, and the refusal names the operator you typed.',\n '',\n 'The difference belongs to the shell, not to this guard. `&&` short-circuits: the work cannot run',\n 'when the cure exits non-zero, which is exactly the property the row 6 block exists to guarantee.',\n 'Refusing that bought nothing and cost a round trip. `;` discards the cure\\'s exit code and runs the',\n 'work regardless — measured with `>/dev/null 2>&1` on the cure in 7 of 9 observed cases, so the',\n 'failure was invisible as well as ignored. The two-step is genuinely safer there, because the NEXT',\n 'tool call is a fresh evaluation that recomputes `localMain` against `originMain`: a failed pull',\n 're-blocks. An allowed `;` compound never gets that second look.',\n '',\n '`git fetch` may LEAD the prefix (`git fetch --prune origin main && git pull --ff-only origin main`',\n 'is the shape agents type) but never satisfies it alone: a fetch moves the remote-tracking ref and',\n 'leaves local `main` exactly as far behind, so there is nothing for the `&&` to protect.',\n '',\n ];\n}\n\n// The use-case table (ROW DATA, in the doc's own global numbering) and the note that explains it.\n// webpieces-disable no-function-outside-class -- third section of renderL2Doc's string, beside it in this module\nfunction renderUseCases(): string[] {\n return [\n '## L2 use cases',\n '',\n 'Same row shape as L0 and L1: the **Fix** is literal or it is not a fix. Each case is attached IN',\n 'CODE to the row that judges it (`useCases` on `L2Row`), so this table cannot describe a row that no',\n 'longer exists and a row cannot quietly acquire behaviour nothing documents.',\n '',\n '**This table is how the layer LEARNS.** When a new situation comes up in a session, the change is',\n 'one more `new L2UseCase(...)` on the row that judged it — not a paragraph added here, which the',\n 'byte-lock spec would reject anyway. Every case also carries the exact `reason` string the guard',\n 'logs, and a spec pushes that back through `l2RowForReason` to assert it lands on the row it is filed',\n 'under. So a case whose row is wrong fails the build rather than misinforming a reader.',\n '',\n '| # | what you SEE (exact symptom) | state | verdict | Fix |',\n '|---|---|---|---|---|',\n ...allL2UseCases().map(useCaseRow),\n '',\n 'The incidental-write case under row 6 is the one to read first: `npx expo install` on `main`, in',\n 'another repo on this toolchain, modified two tracked files and no guard fired. It is filed under row',\n '6 rather than row 5 because that is the row that judges Bash on `main` today — a command\\'s stated',\n 'purpose never says whether it also writes, which is why the shape there is default-deny plus the row',\n '4 skip list rather than a blocklist of readers anybody could have enumerated.',\n '',\n ];\n}\n\n// How the log joins to this table, and the skip list. Prose plus the reason→row contract.\n// webpieces-disable no-function-outside-class -- fourth section of renderL2Doc's string, beside it in this module\nfunction renderNotes(): string[] {\n return [\n '## How a log line joins to a row',\n '',\n 'Every L2 decision is written to the L2-decisions log (one file per writer) with `layer=L2` and',\n '`row=<n>`, where `<n>` is a row number from the table above. So `row=8` means \"this call was judged',\n 'by row 8\" and you read the state, the verdict and the cure straight off this page.',\n '',\n '**The join is by REASON, not by dispatch, and the difference is worth knowing.** L1 takes the first',\n 'matching row and switches on it, so deleting an L1 row deletes a block. L2\\'s four classes each own',\n 'their own ladder (see \"The four classes\" above for why they cannot be one function), and',\n '`L2_ROW_FOR_REASON` in `l2-rows.ts` maps each ladder exit to the row it is an instance of. A unit',\n 'test reads the four guard sources and asserts every reason literal resolves to a row, so a new exit',\n 'with no row fails the build rather than logging `row=-` forever.',\n '',\n '## The skip list (row 4)',\n '',\n 'Principle: **these get you OUT or tell you where you are.** They are not \"working here\".',\n '',\n '| group | commands |',\n '|---|---|',\n '| get out | `git checkout -b <new> origin/main` · `git switch -c <new> origin/main` · `git switch <other>` · `git worktree add … -b <new> origin/main` |',\n '| make `main` current | `pnpm wp-sync-main` *(the prescribed form — also reaps dead branches/worktrees and sweeps orphan directories)* · `git pull` · `git fetch` · `git checkout main && git pull origin main` *(paired only; still allowed, and still the L0 recovery cure, where no `pnpm` bin can be trusted)* |',\n '| orient | `git status\\\\|log\\\\|diff\\\\|branch` · `gh` generally (`pr view`, `pr close`, `pr comment`, `api`, `run watch` — it talks to GitHub, not to this tree) |',\n '| talk to the network | `curl` · `wget` — a URL is not this repo. NOT the forms that write a local file: `curl -o`, `wget -O`, `gh repo clone`, `gh pr checkout`, `gh run download`, or any `> file` redirect |',\n '| park work | `git stash` |',\n '| repair / tooling | `pnpm wp-start-update` · `pnpm wp-start-upsert-pr` · the `wp-*` bins |',\n '',\n '**NOT on it:** `git commit` `add` `push` `merge` `rebase` `reset` `restore` `clean` `cherry-pick` ·',\n '`git grep` `show <rev>:<path>` `cat-file` `ls-files` (those read tracked content). **`pnpm build` /',\n '`pnpm test` are not on it either** — there is no point running them on `main` or on a dead branch.',\n '',\n '## Cannot tell — everything that lands on row ' + String(L2_FAIL_OPEN_ROW),\n '',\n '| state | expected? | treatment |',\n '|---|---|---|',\n '| cache absent | **yes** — the refresher populates for the NEXT call, so this fires on the first tool call of every session | fail open, log |',\n '| detached HEAD | **yes** — mid-rebase, `git checkout <sha>` | fail open, log |',\n '| forge unreachable | **yes** — `gh` missing, unauthenticated, rate-limited or offline | fail open, log as `no-forge` |',\n '| branch unresolvable | **no** — not a repo, git broken | fail open, log LOUDLY |',\n '| cache for another branch | **no** — unreachable since the cache became branch-keyed | fail open, log LOUDLY |',\n '',\n '**Do NOT block to capture these cases.** `cache-absent` fires on every session\\'s first call;',\n 'blocking there deadlocks every session behind a network fetch. And if a guard cannot establish',\n 'state, blocking means a *broken* guard wedges the session — the exact failure this family exists to',\n 'avoid.',\n '',\n '`ALLOW_FAIL_OPEN` is a TYPED VERDICT, not a string suffix on the reason, so abstentions are',\n 'countable. `no-forge` is the newest member: `branchAlreadyMerged: false` used to be produced both by',\n '\"this branch has no merged PR\" and by \"we could not ask\", and both logged a plain ALLOW — so from',\n 'the trail you could not tell whether the merged-branch policy was protecting anything or quietly',\n 'standing down.',\n '',\n ];\n}\n\n// The gaps between the table and the code, and the code anchors.\n// webpieces-disable no-function-outside-class -- last section of renderL2Doc's string, beside it in this module\nfunction renderTail(): string[] {\n return [\n '## Not done — rows the guards do not yet honour',\n '',\n ...renderNotDoneBody(),\n '',\n 'This section is generated from `NOT_DONE` in `l2-rows.ts`, so closing a gap means deleting its entry',\n 'and the doc follows — it cannot rot into a list of things that were fixed years ago.',\n '',\n '## Incidents these guards exist because of',\n '',\n '- **The 157-commit checkout.** An agent ran `git checkout main` in a clone whose local `main` was',\n ' 157 commits behind. That checkout reverted the `@webpieces` pin, reverted the guard shim — **the',\n ' drift guard itself** — to a copy whose message stated the drift backwards, and so reverted the',\n ' agent\\'s judgment: it ran the `pnpm install` that message named and downgraded `node_modules`.',\n ' Lesson, quoted from the code: *a guard a stale checkout can revert cannot be relied on to catch a',\n ' stale checkout.* Hence row 2, which is preventive, matches on command TEXT only, and asks git',\n ' nothing — deliberately, because the only `main` it could measure is the one it is about to leave.',\n '- **The side door.** An agent on a `main` 18 commits behind (108 files, +8069/−3692 upstream) had',\n ' its Read tool blocked exactly as designed, then spent the session `ls`-ing, `grep`-ing and',\n ' `cat`-ing the same stale tree, and described a CI workflow set missing a 186-line workflow that',\n ' existed upstream. *The logs read \"read-stale-guard handled\", which is worse than no guard: it',\n ' looks covered.*',\n '- **Computed and thrown away.** Both file guards are file-scoped, so Bash reached neither. An agent',\n ' that only ran shell sailed through on a merged branch **even though `branchAlreadyMerged` was',\n ' loaded and logged on that very path.**',\n '',\n '---',\n '',\n '',\n '## Code anchors',\n '',\n '| section | file | symbol |',\n '|---|---|---|',\n '| the rows + the reason→row join | `agent-workflow-rules/src/core/l2-rows.ts` | `L2_ROWS`, `l2RowForReason`, `NOT_DONE` |',\n '| write policy | `agent-workflow-rules/src/core/rules/feature-branch-guard.ts` | `check` |',\n '| read policy | `agent-workflow-rules/src/core/rules/read-stale-guard.ts` | `checkStaleMain`, `checkMergedBranch` |',\n '| stale-main Bash | `agent-workflow-rules/src/core/rules/stale-main-bash-guard.ts` | `checkFreshness`, `bareCheckoutOfMain` |',\n '| the shared freshness predicate | `agent-workflow-rules/src/core/rules/main-freshness.ts` | `containsOriginMain`, `summarize` |',\n '| merged-branch Bash | `agent-workflow-rules/src/core/rules/merged-branch-bash-guard.ts` | `isFullyRecovery`, `ALLOWED_GIT_SUBCOMMANDS` |',\n '| the cache | `rules-config/src/main-sync-status.ts`, `main-sync-file.ts` | `readMainSyncStatus`, `MainSyncStatusFile`, `forgeReachable` |',\n '| the refresher | `agent-workflow-rules/src/core/sync-main.ts` | `refreshMainSync` |',\n '| command scanning | `agent-workflow-rules/src/core/rules/content-read-scan.ts`, `shell-segment-scan.ts` | `readsStaleContent`, `classify` |',\n '| the config key | `agent-workflow-rules/src/configs/main-sync-guard-configs.ts`, `policy-keys.ts` | `BranchStateGuardConfig`, `BRANCH_STATE_GUARD_KEY` |',\n '',\n ];\n}\n"]}
@@ -16,7 +16,9 @@ const log_stream_1 = require("./log-stream");
16
16
  // exited, with stdio discarded, so when it fails to update the cache there is normally no trace.
17
17
  // This log captures its lifecycle — SPAWN_ATTEMPT (parent side), then START / SKIP_INPROGRESS /
18
18
  // FINISH / ERROR (child side) — so we can tell whether the detached child never launched, was killed
19
- // mid-run (START with no FINISH), or threw. Writes to
19
+ // mid-run (START with no FINISH), or threw. A spawn happens at most once per MIN_REFRESH_INTERVAL_MINUTES
20
+ // per repo, and a throttled call logs nothing (#1342), so one cycle per interval is the healthy shape.
21
+ // Writes to
20
22
  // `.webpieces/logs/async-refresh/<writer>.log`, where <writer> is LogStream's
21
23
  // `<sessionId>-<agentId|coordinator>-<hook>` key (see LOGS_STATE_DIR and ASYNC_REFRESH_STREAM).
22
24
  //
@@ -1 +1 @@
1
- {"version":3,"file":"main-sync-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-log.ts"],"names":[],"mappings":";;;AAmDA,oCAwBC;AAUD,0DAEC;;AAvFD,+CAAyB;AACzB,mDAA6B;AAE7B,8DAAyD;AACzD,+CAAqD;AAErD,iEAA6D;AAC7D,6CAAyC;AAEzC,iGAAiG;AACjG,mGAAmG;AACnG,iGAAiG;AACjG,iGAAiG;AACjG,gGAAgG;AAChG,qGAAqG;AACrG,sDAAsD;AACtD,8EAA8E;AAC9E,gGAAgG;AAChG,EAAE;AACF,mGAAmG;AACnG,mGAAmG;AACnG,mGAAmG;AACnG,mGAAmG;AACnG,gEAAgE;AAChE,MAAM,aAAa,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,uDAAuD;AACzF,MAAM,cAAc,GAAG,GAAG,CAAC;AAI3B,uFAAuF;AACvF,MAAa,YAAY;IACrB,KAAK,CAAY;IACjB,GAAG,CAAS;IACZ,SAAS,CAAS;IAClB,MAAM,CAAS;IAEf,YAAY,KAAgB,EAAE,GAAW,EAAE,SAAiB,EAAE,MAAc;QACxE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;Q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AACnG,8FAA8F;AAC9F,6FAA6F;AAC7F,+DAA+D;AAC/D,EAAE;AACF,mGAAmG;AACnG,mCAAmC;AACnC,2KAA2K;AAC3K,SAAgB,uBAAuB,CAAC,IAAY;IAChD,OAAO,6BAAY,CAAC,QAAQ,CAAC,IAAI,EAAE,kCAAoB,EAAE,sBAAS,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;AAC3F,CAAC;AAED,6EAA6E;AAC7E,mKAAmK;AACnK,SAAS,OAAO,CAAC,KAAa;IAC1B,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IACrD,OAAO,IAAI,CAAC,MAAM,IAAI,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,cAAc,CAAC,GAAG,GAAG,CAAC;AACtF,CAAC;AAED,mKAAmK;AACnK,SAAS,aAAa,CAAC,OAAe,EAAE,QAAgB;IACpD,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAClC,IAAI,IAAI,CAAC,IAAI,GAAG,aAAa,EAAE,CAAC;YAC5B,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YACrD,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;IACf,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { ASYNC_REFRESH_STREAM } from './log-streams';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\n\n// The ASYNC log — observability for the detached background refresher (sync-main.ts) that writes\n// main-sync-status.json. Its companion is the SYNC log (sync-decisions.log, decision-log.ts) which\n// records what the hook DECIDED using that cache. The refresher runs AFTER the spawning hook has\n// exited, with stdio discarded, so when it fails to update the cache there is normally no trace.\n// This log captures its lifecycle — SPAWN_ATTEMPT (parent side), then START / SKIP_INPROGRESS /\n// FINISH / ERROR (child side) — so we can tell whether the detached child never launched, was killed\n// mid-run (START with no FINISH), or threw. Writes to\n// `.webpieces/logs/async-refresh/<writer>.log`, where <writer> is LogStream's\n// `<sessionId>-<agentId|coordinator>-<hook>` key (see LOGS_STATE_DIR and ASYNC_REFRESH_STREAM).\n//\n// THE CHILD'S RAW STDIO GOES TO THIS SAME FILE. It used to have a `.stderr.log` sibling, which was\n// 0 bytes on every measured run — it is written to ONLY when the child dies before its own logging\n// (a module-load failure, say), and that is precisely the moment you want the crash output sitting\n// directly beneath the SPAWN_ATTEMPT that preceded it, in time order, rather than in a second file\n// you have to think to open. Same cycle, same writer, one file.\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors decision-log)\nconst MAX_DETAIL_LEN = 300;\n\nexport type SyncPhase = 'SPAWN_ATTEMPT' | 'START' | 'SKIP_INPROGRESS' | 'FINISH' | 'ERROR';\n\n// Data-only record of one refresher lifecycle event (per CLAUDE.md: classes for data).\nexport class SyncLogEvent {\n phase: SyncPhase;\n pid: number;\n branchArg: string;\n detail: string;\n\n constructor(phase: SyncPhase, pid: number, branchArg: string, detail: string) {\n this.phase = phase;\n this.pid = pid;\n this.branchArg = branchArg;\n this.detail = detail;\n }\n}\n\n/**\n * Append one tab-separated line per refresher event to\n * `.webpieces/logs/async-refresh/<writer>.log` (see LogStream for the writer key). `root` is\n * the workspace root holding `.webpieces`. Swallows all errors — logging must never block or fail\n * the refresher (or the hook that spawns it).\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 logSyncEvent(root: string, event: SyncLogEvent): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: this is the refresher's own lifecycle trace for THIS worktree. One writer per\n // log, so its appends cannot interleave with another agent's.\n const logsDir = dotWebpieces.logsFile(root, ASYNC_REFRESH_STREAM);\n fs.mkdirSync(logsDir, { recursive: true });\n\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${timestamp}]`,\n event.phase,\n `pid=${String(event.pid)}`,\n event.branchArg,\n oneLine(event.detail),\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n\n// The path the detached child's stdout/stderr are redirected to (opened with fs.openSync(p,'a') by\n// the spawner), so even a crash BEFORE our own logging runs — e.g. a module-load failure — is\n// captured instead of vanishing into /dev/null. Callers must ensure the log dir exists first\n// (logSyncEvent's mkdir, called for SPAWN_ATTEMPT, does that).\n//\n// This is THE SAME FILE logSyncEvent appends to — see the header. It is not a second stream and it\n// no longer has a name of its own.\n// webpieces-disable no-function-outside-class -- sibling of logSyncEvent in this module-scope writer; it must stay callable from a tree too broken to build a DI container\nexport function refresherChildStdioPath(root: string): string {\n return dotWebpieces.logsFile(root, ASYNC_REFRESH_STREAM, logStream.writerFile('.log'));\n}\n\n// Collapse newlines/tabs and cap length so one event is always one log line.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction oneLine(value: string): string {\n const flat = value.replace(/[\\t\\r\\n]+/g, ' ').trim();\n return flat.length <= MAX_DETAIL_LEN ? flat : flat.slice(0, MAX_DETAIL_LEN) + '…';\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction rotateLogFile(logPath: string, prevPath: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const stat = fs.statSync(logPath);\n if (stat.size > MAX_LOG_BYTES) {\n if (fs.existsSync(prevPath)) fs.unlinkSync(prevPath);\n fs.renameSync(logPath, prevPath);\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n"]}
1
+ {"version":3,"file":"main-sync-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-log.ts"],"names":[],"mappings":";;;AAqDA,oCAwBC;AAUD,0DAEC;;AAzFD,+CAAyB;AACzB,mDAA6B;AAE7B,8DAAyD;AACzD,+CAAqD;AAErD,iEAA6D;AAC7D,6CAAyC;AAEzC,iGAAiG;AACjG,mGAAmG;AACnG,iGAAiG;AACjG,iGAAiG;AACjG,gGAAgG;AAChG,qGAAqG;AACrG,0GAA0G;AAC1G,uGAAuG;AACvG,YAAY;AACZ,8EAA8E;AAC9E,gGAAgG;AAChG,EAAE;AACF,mGAAmG;AACnG,mGAAmG;AACnG,mGAAmG;AACnG,mGAAmG;AACnG,gEAAgE;AAChE,MAAM,aAAa,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,uDAAuD;AACzF,MAAM,cAAc,GAAG,GAAG,CAAC;AAI3B,uFAAuF;AACvF,MAAa,YAAY;IACrB,KAAK,CAAY;IACjB,GAAG,CAAS;IACZ,SAAS,CAAS;IAClB,MAAM,CAAS;IAEf,YAAY,KAAgB,EAAE,GAAW,EAAE,SAAiB,EAAE,MAAc;QACxE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAZD,oCAYC;AAED;;;;;GAKG;AACH,mKAAmK;AACnK,SAAgB,YAAY,CAAC,IAAY,EAAE,KAAmB;IAC1D,8DAA8D;IAC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;AAC3F,CAAC;AAED,6EAA6E;AAC7E,mKAAmK;AACnK,SAAS,OAAO,CAAC,KAAa;IAC1B,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IACrD,OAAO,IAAI,CAAC,MAAM,IAAI,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,cAAc,CAAC,GAAG,GAAG,CAAC;AACtF,CAAC;AAED,mKAAmK;AACnK,SAAS,aAAa,CAAC,OAAe,EAAE,QAAgB;IACpD,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAClC,IAAI,IAAI,CAAC,IAAI,GAAG,aAAa,EAAE,CAAC;YAC5B,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YACrD,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;IACf,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { ASYNC_REFRESH_STREAM } from './log-streams';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\n\n// The ASYNC log — observability for the detached background refresher (sync-main.ts) that writes\n// main-sync-status.json. Its companion is the SYNC log (sync-decisions.log, decision-log.ts) which\n// records what the hook DECIDED using that cache. The refresher runs AFTER the spawning hook has\n// exited, with stdio discarded, so when it fails to update the cache there is normally no trace.\n// This log captures its lifecycle — SPAWN_ATTEMPT (parent side), then START / SKIP_INPROGRESS /\n// FINISH / ERROR (child side) — so we can tell whether the detached child never launched, was killed\n// mid-run (START with no FINISH), or threw. A spawn happens at most once per MIN_REFRESH_INTERVAL_MINUTES\n// per repo, and a throttled call logs nothing (#1342), so one cycle per interval is the healthy shape.\n// Writes to\n// `.webpieces/logs/async-refresh/<writer>.log`, where <writer> is LogStream's\n// `<sessionId>-<agentId|coordinator>-<hook>` key (see LOGS_STATE_DIR and ASYNC_REFRESH_STREAM).\n//\n// THE CHILD'S RAW STDIO GOES TO THIS SAME FILE. It used to have a `.stderr.log` sibling, which was\n// 0 bytes on every measured run — it is written to ONLY when the child dies before its own logging\n// (a module-load failure, say), and that is precisely the moment you want the crash output sitting\n// directly beneath the SPAWN_ATTEMPT that preceded it, in time order, rather than in a second file\n// you have to think to open. Same cycle, same writer, one file.\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors decision-log)\nconst MAX_DETAIL_LEN = 300;\n\nexport type SyncPhase = 'SPAWN_ATTEMPT' | 'START' | 'SKIP_INPROGRESS' | 'FINISH' | 'ERROR';\n\n// Data-only record of one refresher lifecycle event (per CLAUDE.md: classes for data).\nexport class SyncLogEvent {\n phase: SyncPhase;\n pid: number;\n branchArg: string;\n detail: string;\n\n constructor(phase: SyncPhase, pid: number, branchArg: string, detail: string) {\n this.phase = phase;\n this.pid = pid;\n this.branchArg = branchArg;\n this.detail = detail;\n }\n}\n\n/**\n * Append one tab-separated line per refresher event to\n * `.webpieces/logs/async-refresh/<writer>.log` (see LogStream for the writer key). `root` is\n * the workspace root holding `.webpieces`. Swallows all errors — logging must never block or fail\n * the refresher (or the hook that spawns it).\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 logSyncEvent(root: string, event: SyncLogEvent): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: this is the refresher's own lifecycle trace for THIS worktree. One writer per\n // log, so its appends cannot interleave with another agent's.\n const logsDir = dotWebpieces.logsFile(root, ASYNC_REFRESH_STREAM);\n fs.mkdirSync(logsDir, { recursive: true });\n\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${timestamp}]`,\n event.phase,\n `pid=${String(event.pid)}`,\n event.branchArg,\n oneLine(event.detail),\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n\n// The path the detached child's stdout/stderr are redirected to (opened with fs.openSync(p,'a') by\n// the spawner), so even a crash BEFORE our own logging runs — e.g. a module-load failure — is\n// captured instead of vanishing into /dev/null. Callers must ensure the log dir exists first\n// (logSyncEvent's mkdir, called for SPAWN_ATTEMPT, does that).\n//\n// This is THE SAME FILE logSyncEvent appends to — see the header. It is not a second stream and it\n// no longer has a name of its own.\n// webpieces-disable no-function-outside-class -- sibling of logSyncEvent in this module-scope writer; it must stay callable from a tree too broken to build a DI container\nexport function refresherChildStdioPath(root: string): string {\n return dotWebpieces.logsFile(root, ASYNC_REFRESH_STREAM, logStream.writerFile('.log'));\n}\n\n// Collapse newlines/tabs and cap length so one event is always one log line.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction oneLine(value: string): string {\n const flat = value.replace(/[\\t\\r\\n]+/g, ' ').trim();\n return flat.length <= MAX_DETAIL_LEN ? flat : flat.slice(0, MAX_DETAIL_LEN) + '…';\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction rotateLogFile(logPath: string, prevPath: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const stat = fs.statSync(logPath);\n if (stat.size > MAX_LOG_BYTES) {\n if (fs.existsSync(prevPath)) fs.unlinkSync(prevPath);\n fs.renameSync(logPath, prevPath);\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n"]}
@@ -3,17 +3,27 @@ export declare function resetMainSyncRefreshLatchForTest(): void;
3
3
  /**
4
4
  * The detached child's argv, spawner side. Positions here are offset by two from the child's
5
5
  * `process.argv` (node + script path), so this array's 3/4/5 are the child's 4/5/6 — which is what
6
- * `sync-main.ts:spawnerIdentity` reads. The two are pinned against each other by ONE test, because a
6
+ * `sync-main.ts:spawnerIdentity` reads — and its 2 (the lock's `startedMs`) is the child's 3, which
7
+ * `sync-main.ts:claimStartedFromArgv` reads. The hang timeout no longer travels: the child adopts a
8
+ * lock the spawner already took, so it has nothing to time out. The two are pinned against each other
9
+ * by ONE test, because a
7
10
  * silent disagreement about these positions IS the bug being fixed: the child previously received no
8
11
  * identity at all and wrote every line to the shared `unknown-coordinator-hook-` stream.
9
12
  */
10
- export declare function refresherArgv(refresher: string, workspaceRoot: string, hangTimeoutMinutes: number, identity: StreamIdentity): string[];
13
+ export declare function refresherArgv(refresher: string, workspaceRoot: string, claimStarted: number, identity: StreamIdentity): string[];
11
14
  /**
12
15
  * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,
13
16
  * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow
14
17
  * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on
15
18
  * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.
16
19
  *
20
+ * THROTTLED AND SINGLE-FLIGHT IN THE SPAWNER (#1342): at most one refresher START per
21
+ * MIN_REFRESH_INTERVAL_MINUTES per repo, decided here by one read of `lastRefreshStartedMs` in
22
+ * `main-sync-status.json` before any process is launched. Past the interval the spawner creates
23
+ * `main-sync.lock.json` exclusively, so of several hook processes firing at once exactly one launches.
24
+ * The child ADOPTS that lock (it never creates one itself), stamps the status file, and deletes the
25
+ * lock last.
26
+ *
17
27
  * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to
18
28
  * `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's
19
29
  * stdout/stderr are redirected to a sibling file (not
@@ -8,11 +8,16 @@ const child_process_1 = require("child_process");
8
8
  const fs = tslib_1.__importStar(require("fs"));
9
9
  const path = tslib_1.__importStar(require("path"));
10
10
  const to_error_1 = require("@webpieces/tooling-common/to-error");
11
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
11
12
  const main_sync_log_1 = require("./main-sync-log");
12
13
  const log_stream_1 = require("./log-stream");
13
14
  // Per-process latch for the spawn below. A hook process handles exactly one tool call, so this makes
14
15
  // the refresher at-most-once per tool call. Exported reset is test-only.
15
16
  let alreadyTriggered = false;
17
+ // The services the spawner throttles and claims through. Module scope, like the latch: this path must
18
+ // stay callable from a tree too broken to build a DI container.
19
+ const mainSyncStatus = new repo_workflow_core_1.MainSyncStatusService();
20
+ const mainSyncLocks = new repo_workflow_core_1.MainSyncLockService(undefined, undefined, mainSyncStatus);
16
21
  // webpieces-disable no-function-outside-class -- test-only latch reset, matching this module's function shape
17
22
  function resetMainSyncRefreshLatchForTest() {
18
23
  alreadyTriggered = false;
@@ -20,13 +25,16 @@ function resetMainSyncRefreshLatchForTest() {
20
25
  /**
21
26
  * The detached child's argv, spawner side. Positions here are offset by two from the child's
22
27
  * `process.argv` (node + script path), so this array's 3/4/5 are the child's 4/5/6 — which is what
23
- * `sync-main.ts:spawnerIdentity` reads. The two are pinned against each other by ONE test, because a
28
+ * `sync-main.ts:spawnerIdentity` reads — and its 2 (the lock's `startedMs`) is the child's 3, which
29
+ * `sync-main.ts:claimStartedFromArgv` reads. The hang timeout no longer travels: the child adopts a
30
+ * lock the spawner already took, so it has nothing to time out. The two are pinned against each other
31
+ * by ONE test, because a
24
32
  * silent disagreement about these positions IS the bug being fixed: the child previously received no
25
33
  * identity at all and wrote every line to the shared `unknown-coordinator-hook-` stream.
26
34
  */
27
35
  // webpieces-disable no-function-outside-class -- argv builder for this module's spawn, matching its function shape
28
- function refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, identity) {
29
- return [refresher, workspaceRoot, String(hangTimeoutMinutes), identity.sessionId, identity.agentId, identity.hook];
36
+ function refresherArgv(refresher, workspaceRoot, claimStarted, identity) {
37
+ return [refresher, workspaceRoot, String(claimStarted), identity.sessionId, identity.agentId, identity.hook];
30
38
  }
31
39
  /**
32
40
  * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,
@@ -34,6 +42,13 @@ function refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, identity) {
34
42
  * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on
35
43
  * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.
36
44
  *
45
+ * THROTTLED AND SINGLE-FLIGHT IN THE SPAWNER (#1342): at most one refresher START per
46
+ * MIN_REFRESH_INTERVAL_MINUTES per repo, decided here by one read of `lastRefreshStartedMs` in
47
+ * `main-sync-status.json` before any process is launched. Past the interval the spawner creates
48
+ * `main-sync.lock.json` exclusively, so of several hook processes firing at once exactly one launches.
49
+ * The child ADOPTS that lock (it never creates one itself), stamps the status file, and deletes the
50
+ * lock last.
51
+ *
37
52
  * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to
38
53
  * `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's
39
54
  * stdout/stderr are redirected to a sibling file (not
@@ -62,19 +77,50 @@ function triggerMainSyncRefresh(workspaceRoot, hangTimeoutMinutes) {
62
77
  // fast path in hook-core AND read-stale-guard's own check(), for one — which is why the log showed
63
78
  // two SPAWN_ATTEMPTs ~20ms apart from the same pid on every cycle. The loser only ever reached the
64
79
  // lock and exited, so the second child was pure waste (and one more `git fetch` racing the
65
- // agent's). The child's lock still guards against refreshers from OTHER hook processes.
80
+ // agent's). The claim below guards against refreshers from OTHER hook processes.
66
81
  if (alreadyTriggered)
67
82
  return;
68
83
  alreadyTriggered = true;
69
84
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
70
85
  try {
71
- const refresher = path.join(__dirname, 'sync-main.js');
72
- // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.
73
- (0, main_sync_log_1.logSyncEvent)(workspaceRoot, new main_sync_log_1.SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher}`));
86
+ // THE THROTTLE LIVES HERE, IN THE SPAWNER (#1342) — not in the child, which only learned it had
87
+ // nothing to do after node had already booted (measured: 6500 SPAWN_ATTEMPTs, 2677 of them
88
+ // ending in SKIP_INPROGRESS). One read of the status file's stamp decides; a throttled call
89
+ // launches nothing. The lock is created exclusively, so of N hook processes firing at once
90
+ // exactly one spawns. See MainSyncLockService.claimRefresh for the stamp semantics.
91
+ //
92
+ // A skip writes NO log line. It is the outcome of nearly every tool call, so logging it would
93
+ // trade the SPAWN_ATTEMPT flood for a SKIP flood. The throttle is visible instead as
94
+ // SPAWN_ATTEMPTs at least MIN_REFRESH_INTERVAL_MINUTES apart, each naming the run it follows.
95
+ const claim = mainSyncLocks.claimRefresh(workspaceRoot, hangTimeoutMinutes);
96
+ if (claim.outcome !== repo_workflow_core_1.RefreshClaimOutcome.CLAIMED || claim.lock === null)
97
+ return;
98
+ spawnRefresher(workspaceRoot, claim.lock, claim.lastRefreshStartedMs);
99
+ }
100
+ catch (err) { // webpieces-disable catch-must-propagate -- warming a background cache must never block or fail the agent's tool call; there is no caller to propagate to, so the failure is recorded in the async-refresh log instead
101
+ const error = (0, to_error_1.toError)(err);
102
+ // A persistent claim failure (EACCES/EPERM on the lock) would otherwise stop every refresh
103
+ // without a trace. Only failures are logged; a throttled skip still writes nothing.
104
+ (0, main_sync_log_1.logSyncEvent)(workspaceRoot, new main_sync_log_1.SyncLogEvent('ERROR', process.pid, '-', `spawner claim/spawn failed: ${error.message}`));
105
+ }
106
+ }
107
+ /**
108
+ * Launch the detached refresher for a lock this process WON. If the launch fails synchronously the run
109
+ * is recorded as an ERROR (stamp first) and the lock deleted (last), so the next attempt waits out the
110
+ * interval like any failed run, rather than an unadopted lock sitting until the hang window expires.
111
+ */
112
+ // webpieces-disable no-function-outside-class -- the spawn half of triggerMainSyncRefresh, beside it in this module-scope spawner
113
+ function spawnRefresher(workspaceRoot, claim, lastRefreshStartedMs) {
114
+ const refresher = path.join(__dirname, 'sync-main.js');
115
+ const after = lastRefreshStartedMs === null ? 'none' : new Date(lastRefreshStartedMs).toISOString();
116
+ // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.
117
+ (0, main_sync_log_1.logSyncEvent)(workspaceRoot, new main_sync_log_1.SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher} lockStartedMs=${String(claim.startedMs)} previousStart=${after}`));
118
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
119
+ try {
74
120
  // Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash
75
121
  // before the child's own logging — e.g. a module-load failure — is still captured.
76
122
  const errFd = fs.openSync((0, main_sync_log_1.refresherChildStdioPath)(workspaceRoot), 'a');
77
- const child = (0, child_process_1.spawn)(process.execPath, refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, log_stream_1.logStream.identity()), {
123
+ const child = (0, child_process_1.spawn)(process.execPath, refresherArgv(refresher, workspaceRoot, claim.startedMs, log_stream_1.logStream.identity()), {
78
124
  detached: true,
79
125
  stdio: ['ignore', errFd, errFd],
80
126
  });
@@ -89,8 +135,9 @@ function triggerMainSyncRefresh(workspaceRoot, hangTimeoutMinutes) {
89
135
  }
90
136
  catch (err) {
91
137
  const error = (0, to_error_1.toError)(err);
92
- void error;
93
- // Spawning the background refresh must never block or fail the tool call.
138
+ mainSyncStatus.recordRefreshOutcome(workspaceRoot, claim.startedMs, repo_workflow_core_1.RefreshOutcome.ERROR);
139
+ mainSyncLocks.releaseMainSyncLock(workspaceRoot, claim);
140
+ throw error;
94
141
  }
95
142
  }
96
143
  //# sourceMappingURL=main-sync-refresh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"main-sync-refresh.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-refresh.ts"],"names":[],"mappings":";;AAaA,4EAEC;AAUD,sCAEC;AA+BD,wDAmCC;;AA7FD,iDAAsC;AACtC,+CAAyB;AACzB,mDAA6B;AAE7B,iEAA6D;AAC7D,mDAAsF;AACtF,6CAAyD;AAEzD,qGAAqG;AACrG,yEAAyE;AACzE,IAAI,gBAAgB,GAAG,KAAK,CAAC;AAE7B,8GAA8G;AAC9G,SAAgB,gCAAgC;IAC5C,gBAAgB,GAAG,KAAK,CAAC;AAC7B,CAAC;AAED;;;;;;GAMG;AACH,mHAAmH;AACnH,SAAgB,aAAa,CAAC,SAAiB,EAAE,aAAqB,EAAE,kBAA0B,EAAE,QAAwB;IACxH,OAAO,CAAC,SAAS,EAAE,aAAa,EAAE,MAAM,CAAC,kBAAkB,CAAC,EAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;AACvH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,mOAAmO;AACnO,SAAgB,sBAAsB,CAAC,aAAqB,EAAE,kBAA0B;IACpF,gGAAgG;IAChG,mGAAmG;IACnG,mGAAmG;IACnG,2FAA2F;IAC3F,wFAAwF;IACxF,IAAI,gBAAgB;QAAE,OAAO;IAC7B,gBAAgB,GAAG,IAAI,CAAC;IAExB,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QACvD,2FAA2F;QAC3F,IAAA,4BAAY,EAAC,aAAa,EAAE,IAAI,4BAAY,CAAC,eAAe,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,aAAa,SAAS,EAAE,CAAC,CAAC,CAAC;QAE3G,6FAA6F;QAC7F,mFAAmF;QACnF,MAAM,KAAK,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAA,uCAAuB,EAAC,aAAa,CAAC,EAAE,GAAG,CAAC,CAAC;QACvE,MAAM,KAAK,GAAG,IAAA,qBAAK,EAAC,OAAO,CAAC,QAAQ,EAAE,aAAa,CAAC,SAAS,EAAE,aAAa,EAAE,kBAAkB,EAAE,sBAAS,CAAC,QAAQ,EAAE,CAAC,EAAE;YACrH,QAAQ,EAAE,IAAI;YACd,KAAK,EAAE,CAAC,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC;SAClC,CAAC,CAAC;QACH,8FAA8F;QAC9F,wFAAwF;QACxF,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,GAAU,EAAQ,EAAE;YACrC,IAAA,4BAAY,EAAC,aAAa,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,iBAAiB,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QACjH,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,mFAAmF;QACnF,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;QACX,0EAA0E;IAC9E,CAAC;AACL,CAAC","sourcesContent":["import { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logSyncEvent, SyncLogEvent, refresherChildStdioPath } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n// Per-process latch for the spawn below. A hook process handles exactly one tool call, so this makes\n// the refresher at-most-once per tool call. Exported reset is test-only.\nlet alreadyTriggered = false;\n\n// webpieces-disable no-function-outside-class -- test-only latch reset, matching this module's function shape\nexport function resetMainSyncRefreshLatchForTest(): void {\n alreadyTriggered = false;\n}\n\n/**\n * The detached child's argv, spawner side. Positions here are offset by two from the child's\n * `process.argv` (node + script path), so this array's 3/4/5 are the child's 4/5/6 — which is what\n * `sync-main.ts:spawnerIdentity` reads. The two are pinned against each other by ONE test, because a\n * silent disagreement about these positions IS the bug being fixed: the child previously received no\n * identity at all and wrote every line to the shared `unknown-coordinator-hook-` stream.\n */\n// webpieces-disable no-function-outside-class -- argv builder for this module's spawn, matching its function shape\nexport function refresherArgv(refresher: string, workspaceRoot: string, hangTimeoutMinutes: number, identity: StreamIdentity): string[] {\n return [refresher, workspaceRoot, String(hangTimeoutMinutes), identity.sessionId, identity.agentId, identity.hook];\n}\n\n/**\n * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,\n * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow\n * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on\n * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.\n *\n * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to\n * `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's\n * stdout/stderr are redirected to a sibling file (not\n * /dev/null) so a crash before the child's own logging is still captured. If the async-refresh stream shows\n * SPAWN_ATTEMPT but never START, the detached child was killed before it ran.\n *\n * `hangTimeoutMinutes` IS REQUIRED, deliberately. It used to default to DEFAULT_HANG_TIMEOUT_MINUTES,\n * and that default is the mechanism by which three of the four configured values could never reach a\n * spawn: two callers ran before any guard and simply omitted the argument, and the at-most-once latch\n * below then meant the guard's own call — the one carrying the configured value — was a no-op. An\n * omitted argument that silently means \"the default\" is unreadable at the call site and impossible to\n * grep. Required makes every caller say which value it is passing, and makes forgetting a compile error.\n *\n * THE IDENTITY GOES ON ARGV, and that is what makes the sentence above true. The child is a separate\n * node process whose `logStream` starts unidentified, so it used to write every line to the shared\n * `unknown-coordinator-hook.log` while this parent wrote SPAWN_ATTEMPT to its own\n * prefixed stream. One cycle, two files — the SPAWN_ATTEMPT-without-START check then read as a\n * failure on every cycle even when the child ran perfectly — and every agent's child appending to\n * that one shared path is exactly the multi-writer tearing LogStream exists to remove. Passing\n * session/agent/hook through (positional argv, alongside the root and timeout the child already\n * takes) puts the whole cycle back in ONE file.\n */\n// webpieces-disable no-function-outside-class -- the module's one entry point, beside refresherArgv; a detached fire-and-forget spawn has no state to inject and must stay callable from a tree too broken to build a DI container\nexport function triggerMainSyncRefresh(workspaceRoot: string, hangTimeoutMinutes: number): void {\n // ONE refresher per hook process. Several call sites fire this on a single tool call — the Read\n // fast path in hook-core AND read-stale-guard's own check(), for one — which is why the log showed\n // two SPAWN_ATTEMPTs ~20ms apart from the same pid on every cycle. The loser only ever reached the\n // lock and exited, so the second child was pure waste (and one more `git fetch` racing the\n // agent's). The child's lock still guards against refreshers from OTHER hook processes.\n if (alreadyTriggered) return;\n alreadyTriggered = true;\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const refresher = path.join(__dirname, 'sync-main.js');\n // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.\n logSyncEvent(workspaceRoot, new SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher}`));\n\n // Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash\n // before the child's own logging — e.g. a module-load failure — is still captured.\n const errFd = fs.openSync(refresherChildStdioPath(workspaceRoot), 'a');\n const child = spawn(process.execPath, refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, logStream.identity()), {\n detached: true,\n stdio: ['ignore', errFd, errFd],\n });\n // spawn errors (e.g. ENOENT) arrive asynchronously; record one if it fires. The hook may exit\n // before this handler runs, but on POSIX a successful exec has already happened by now.\n child.once('error', (err: Error): void => {\n logSyncEvent(workspaceRoot, new SyncLogEvent('ERROR', child.pid ?? -1, '-', `spawn failed: ${err.message}`));\n });\n child.unref();\n // The child has its own dup'd copy of the fd after spawn; close the parent's copy.\n fs.closeSync(errFd);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n // Spawning the background refresh must never block or fail the tool call.\n }\n}\n"]}
1
+ {"version":3,"file":"main-sync-refresh.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-refresh.ts"],"names":[],"mappings":";;AAmBA,4EAEC;AAaD,sCAEC;AAsCD,wDA6BC;;AAvGD,iDAAsC;AACtC,+CAAyB;AACzB,mDAA6B;AAE7B,iEAA6D;AAC7D,sEAA8I;AAC9I,mDAAsF;AACtF,6CAAyD;AAEzD,qGAAqG;AACrG,yEAAyE;AACzE,IAAI,gBAAgB,GAAG,KAAK,CAAC;AAE7B,sGAAsG;AACtG,gEAAgE;AAChE,MAAM,cAAc,GAAG,IAAI,0CAAqB,EAAE,CAAC;AACnD,MAAM,aAAa,GAAG,IAAI,wCAAmB,CAAC,SAAS,EAAE,SAAS,EAAE,cAAc,CAAC,CAAC;AAEpF,8GAA8G;AAC9G,SAAgB,gCAAgC;IAC5C,gBAAgB,GAAG,KAAK,CAAC;AAC7B,CAAC;AAED;;;;;;;;;GASG;AACH,mHAAmH;AACnH,SAAgB,aAAa,CAAC,SAAiB,EAAE,aAAqB,EAAE,YAAoB,EAAE,QAAwB;IAClH,OAAO,CAAC,SAAS,EAAE,aAAa,EAAE,MAAM,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,mOAAmO;AACnO,SAAgB,sBAAsB,CAAC,aAAqB,EAAE,kBAA0B;IACpF,gGAAgG;IAChG,mGAAmG;IACnG,mGAAmG;IACnG,2FAA2F;IAC3F,iFAAiF;IACjF,IAAI,gBAAgB;QAAE,OAAO;IAC7B,gBAAgB,GAAG,IAAI,CAAC;IAExB,8DAA8D;IAC9D,IAAI,CAAC;QACD,gGAAgG;QAChG,2FAA2F;QAC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K,8DAA8D;IAC9D,IAAI,CAAC;QACD,6FAA6F;QAC7F,mFAAmF;QACnF,MAAM,KAAK,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAA,uCAAuB,EAAC,aAAa,CAAC,EAAE,GAAG,CAAC,CAAC;QACvE,MAAM,KAAK,GAAG,IAAA,qBAAK,EAAC,OAAO,CAAC,QAAQ,EAAE,aAAa,CAAC,SAAS,EAAE,aAAa,EAAE,KAAK,CAAC,SAAS,EAAE,sBAAS,CAAC,QAAQ,EAAE,CAAC,EAAE;YAClH,QAAQ,EAAE,IAAI;YACd,KAAK,EAAE,CAAC,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC;SAClC,CAAC,CAAC;QACH,8FAA8F;QAC9F,wFAAwF;QACxF,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,GAAU,EAAQ,EAAE;YACrC,IAAA,4BAAY,EAAC,aAAa,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,iBAAiB,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QACjH,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,mFAAmF;QACnF,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,cAAc,CAAC,oBAAoB,CAAC,aAAa,EAAE,KAAK,CAAC,SAAS,EAAE,mCAAc,CAAC,KAAK,CAAC,CAAC;QAC1F,aAAa,CAAC,mBAAmB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QACxD,MAAM,KAAK,CAAC;IAChB,CAAC;AACL,CAAC","sourcesContent":["import { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { MainSyncLock, MainSyncLockService, MainSyncStatusService, RefreshClaimOutcome, RefreshOutcome } from '@webpieces/repo-workflow-core';\nimport { logSyncEvent, SyncLogEvent, refresherChildStdioPath } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n// Per-process latch for the spawn below. A hook process handles exactly one tool call, so this makes\n// the refresher at-most-once per tool call. Exported reset is test-only.\nlet alreadyTriggered = false;\n\n// The services the spawner throttles and claims through. Module scope, like the latch: this path must\n// stay callable from a tree too broken to build a DI container.\nconst mainSyncStatus = new MainSyncStatusService();\nconst mainSyncLocks = new MainSyncLockService(undefined, undefined, mainSyncStatus);\n\n// webpieces-disable no-function-outside-class -- test-only latch reset, matching this module's function shape\nexport function resetMainSyncRefreshLatchForTest(): void {\n alreadyTriggered = false;\n}\n\n/**\n * The detached child's argv, spawner side. Positions here are offset by two from the child's\n * `process.argv` (node + script path), so this array's 3/4/5 are the child's 4/5/6 — which is what\n * `sync-main.ts:spawnerIdentity` reads — and its 2 (the lock's `startedMs`) is the child's 3, which\n * `sync-main.ts:claimStartedFromArgv` reads. The hang timeout no longer travels: the child adopts a\n * lock the spawner already took, so it has nothing to time out. The two are pinned against each other\n * by ONE test, because a\n * silent disagreement about these positions IS the bug being fixed: the child previously received no\n * identity at all and wrote every line to the shared `unknown-coordinator-hook-` stream.\n */\n// webpieces-disable no-function-outside-class -- argv builder for this module's spawn, matching its function shape\nexport function refresherArgv(refresher: string, workspaceRoot: string, claimStarted: number, identity: StreamIdentity): string[] {\n return [refresher, workspaceRoot, String(claimStarted), identity.sessionId, identity.agentId, identity.hook];\n}\n\n/**\n * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,\n * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow\n * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on\n * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.\n *\n * THROTTLED AND SINGLE-FLIGHT IN THE SPAWNER (#1342): at most one refresher START per\n * MIN_REFRESH_INTERVAL_MINUTES per repo, decided here by one read of `lastRefreshStartedMs` in\n * `main-sync-status.json` before any process is launched. Past the interval the spawner creates\n * `main-sync.lock.json` exclusively, so of several hook processes firing at once exactly one launches.\n * The child ADOPTS that lock (it never creates one itself), stamps the status file, and deletes the\n * lock last.\n *\n * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to\n * `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's\n * stdout/stderr are redirected to a sibling file (not\n * /dev/null) so a crash before the child's own logging is still captured. If the async-refresh stream shows\n * SPAWN_ATTEMPT but never START, the detached child was killed before it ran.\n *\n * `hangTimeoutMinutes` IS REQUIRED, deliberately. It used to default to DEFAULT_HANG_TIMEOUT_MINUTES,\n * and that default is the mechanism by which three of the four configured values could never reach a\n * spawn: two callers ran before any guard and simply omitted the argument, and the at-most-once latch\n * below then meant the guard's own call — the one carrying the configured value — was a no-op. An\n * omitted argument that silently means \"the default\" is unreadable at the call site and impossible to\n * grep. Required makes every caller say which value it is passing, and makes forgetting a compile error.\n *\n * THE IDENTITY GOES ON ARGV, and that is what makes the sentence above true. The child is a separate\n * node process whose `logStream` starts unidentified, so it used to write every line to the shared\n * `unknown-coordinator-hook.log` while this parent wrote SPAWN_ATTEMPT to its own\n * prefixed stream. One cycle, two files — the SPAWN_ATTEMPT-without-START check then read as a\n * failure on every cycle even when the child ran perfectly — and every agent's child appending to\n * that one shared path is exactly the multi-writer tearing LogStream exists to remove. Passing\n * session/agent/hook through (positional argv, alongside the root and timeout the child already\n * takes) puts the whole cycle back in ONE file.\n */\n// webpieces-disable no-function-outside-class -- the module's one entry point, beside refresherArgv; a detached fire-and-forget spawn has no state to inject and must stay callable from a tree too broken to build a DI container\nexport function triggerMainSyncRefresh(workspaceRoot: string, hangTimeoutMinutes: number): void {\n // ONE refresher per hook process. Several call sites fire this on a single tool call — the Read\n // fast path in hook-core AND read-stale-guard's own check(), for one — which is why the log showed\n // two SPAWN_ATTEMPTs ~20ms apart from the same pid on every cycle. The loser only ever reached the\n // lock and exited, so the second child was pure waste (and one more `git fetch` racing the\n // agent's). The claim below guards against refreshers from OTHER hook processes.\n if (alreadyTriggered) return;\n alreadyTriggered = true;\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // THE THROTTLE LIVES HERE, IN THE SPAWNER (#1342) — not in the child, which only learned it had\n // nothing to do after node had already booted (measured: 6500 SPAWN_ATTEMPTs, 2677 of them\n // ending in SKIP_INPROGRESS). One read of the status file's stamp decides; a throttled call\n // launches nothing. The lock is created exclusively, so of N hook processes firing at once\n // exactly one spawns. See MainSyncLockService.claimRefresh for the stamp semantics.\n //\n // A skip writes NO log line. It is the outcome of nearly every tool call, so logging it would\n // trade the SPAWN_ATTEMPT flood for a SKIP flood. The throttle is visible instead as\n // SPAWN_ATTEMPTs at least MIN_REFRESH_INTERVAL_MINUTES apart, each naming the run it follows.\n const claim = mainSyncLocks.claimRefresh(workspaceRoot, hangTimeoutMinutes);\n if (claim.outcome !== RefreshClaimOutcome.CLAIMED || claim.lock === null) return;\n spawnRefresher(workspaceRoot, claim.lock, claim.lastRefreshStartedMs);\n } catch (err: unknown) { // webpieces-disable catch-must-propagate -- warming a background cache must never block or fail the agent's tool call; there is no caller to propagate to, so the failure is recorded in the async-refresh log instead\n const error = toError(err);\n // A persistent claim failure (EACCES/EPERM on the lock) would otherwise stop every refresh\n // without a trace. Only failures are logged; a throttled skip still writes nothing.\n logSyncEvent(workspaceRoot, new SyncLogEvent('ERROR', process.pid, '-', `spawner claim/spawn failed: ${error.message}`));\n }\n}\n\n/**\n * Launch the detached refresher for a lock this process WON. If the launch fails synchronously the run\n * is recorded as an ERROR (stamp first) and the lock deleted (last), so the next attempt waits out the\n * interval like any failed run, rather than an unadopted lock sitting until the hang window expires.\n */\n// webpieces-disable no-function-outside-class -- the spawn half of triggerMainSyncRefresh, beside it in this module-scope spawner\nfunction spawnRefresher(workspaceRoot: string, claim: MainSyncLock, lastRefreshStartedMs: number | null): void {\n const refresher = path.join(__dirname, 'sync-main.js');\n const after = lastRefreshStartedMs === null ? 'none' : new Date(lastRefreshStartedMs).toISOString();\n // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.\n logSyncEvent(workspaceRoot, new SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher} lockStartedMs=${String(claim.startedMs)} previousStart=${after}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash\n // before the child's own logging — e.g. a module-load failure — is still captured.\n const errFd = fs.openSync(refresherChildStdioPath(workspaceRoot), 'a');\n const child = spawn(process.execPath, refresherArgv(refresher, workspaceRoot, claim.startedMs, logStream.identity()), {\n detached: true,\n stdio: ['ignore', errFd, errFd],\n });\n // spawn errors (e.g. ENOENT) arrive asynchronously; record one if it fires. The hook may exit\n // before this handler runs, but on POSIX a successful exec has already happened by now.\n child.once('error', (err: Error): void => {\n logSyncEvent(workspaceRoot, new SyncLogEvent('ERROR', child.pid ?? -1, '-', `spawn failed: ${err.message}`));\n });\n child.unref();\n // The child has its own dup'd copy of the fd after spawn; close the parent's copy.\n fs.closeSync(errFd);\n } catch (err: unknown) {\n const error = toError(err);\n mainSyncStatus.recordRefreshOutcome(workspaceRoot, claim.startedMs, RefreshOutcome.ERROR);\n mainSyncLocks.releaseMainSyncLock(workspaceRoot, claim);\n throw error;\n }\n}\n"]}
@@ -5,12 +5,18 @@ import { StreamIdentity } from './log-stream';
5
5
  * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it
6
6
  * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.
7
7
  *
8
- * Concurrency: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start
9
- * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds
10
- * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,
11
- * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.
8
+ * Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only
9
+ * the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →
10
+ * claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start, and passes
11
+ * its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates
12
+ * one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this
13
+ * child booted) means another refresher owns the run, and we exit.
12
14
  *
13
- * argv: [, , repoRoot, hangTimeoutMinutes, sessionId, agentId, hook]
15
+ * Ordering at the end is the point: the status file, carrying `lastRefreshStartedMs` and the outcome,
16
+ * is written FIRST and the lock deleted LAST, so no process can win the next lock race and still read
17
+ * the previous stamp.
18
+ *
19
+ * argv: [, , repoRoot, claimStarted, sessionId, agentId, hook]
14
20
  *
15
21
  * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason
16
22
  * they are passed. This process has its own fresh module-level `logStream`; left unidentified it
@@ -22,14 +28,11 @@ import { StreamIdentity } from './log-stream';
22
28
  */
23
29
  export declare function main(): void;
24
30
  /**
25
- * Parse the hang timeout off argv, WITHOUT `||`.
26
- *
27
- * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — "never treat a lock as stale" — into
28
- * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state
29
- * policy entry), so a value that survives the config only to be discarded at the process boundary is
30
- * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.
31
+ * The `started` of the lock claim the spawner took for this run — argv position 3, which is
32
+ * `refresherArgv`'s 2 (see the offset note there). NaN when absent or malformed, which matches no
33
+ * lock, so a hand-run of this file without a claim adopts nothing and exits as SKIP_INPROGRESS.
31
34
  */
32
- export declare function hangTimeoutFromArgv(raw: string | undefined): number;
35
+ export declare function claimStartedFromArgv(argv: string[]): number;
33
36
  /**
34
37
  * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is
35
38
  * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).
@@ -43,4 +46,4 @@ export declare function spawnerIdentity(argv: string[]): StreamIdentity;
43
46
  * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a
44
47
  * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.
45
48
  */
46
- export declare function refreshMainSync(repoRoot: string, hangTimeoutMinutes: number, argvDetail?: string): void;
49
+ export declare function refreshMainSync(repoRoot: string, claimStarted: number, argvDetail?: string): void;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.main = main;
4
- exports.hangTimeoutFromArgv = hangTimeoutFromArgv;
4
+ exports.claimStartedFromArgv = claimStartedFromArgv;
5
5
  exports.spawnerIdentity = spawnerIdentity;
6
6
  exports.refreshMainSync = refreshMainSync;
7
7
  const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
@@ -9,18 +9,27 @@ const rules_config_1 = require("@webpieces/rules-config");
9
9
  const to_error_1 = require("@webpieces/tooling-common/to-error");
10
10
  const main_sync_log_1 = require("./main-sync-log");
11
11
  const log_stream_1 = require("./log-stream");
12
+ // The services this detached process writes its results through, and adopts and deletes its lock through.
13
+ const status = new repo_workflow_core_1.MainSyncStatusService();
14
+ const locks = new repo_workflow_core_1.MainSyncLockService(undefined, undefined, status);
12
15
  /**
13
16
  * The detached, fire-and-forget refresher spawned (by file path, not a bin) from
14
17
  * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +
15
18
  * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it
16
19
  * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.
17
20
  *
18
- * Concurrency: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start
19
- * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds
20
- * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,
21
- * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.
21
+ * Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only
22
+ * the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →
23
+ * claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start, and passes
24
+ * its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates
25
+ * one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this
26
+ * child booted) means another refresher owns the run, and we exit.
22
27
  *
23
- * argv: [, , repoRoot, hangTimeoutMinutes, sessionId, agentId, hook]
28
+ * Ordering at the end is the point: the status file, carrying `lastRefreshStartedMs` and the outcome,
29
+ * is written FIRST and the lock deleted LAST, so no process can win the next lock race and still read
30
+ * the previous stamp.
31
+ *
32
+ * argv: [, , repoRoot, claimStarted, sessionId, agentId, hook]
24
33
  *
25
34
  * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason
26
35
  * they are passed. This process has its own fresh module-level `logStream`; left unidentified it
@@ -33,22 +42,17 @@ const log_stream_1 = require("./log-stream");
33
42
  // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
34
43
  function main() {
35
44
  log_stream_1.logStream.identify(spawnerIdentity(process.argv));
36
- refreshMainSync(process.argv[2] ?? process.cwd(), hangTimeoutFromArgv(process.argv[3]), process.argv.slice(2).join(' '));
45
+ refreshMainSync(process.argv[2] ?? process.cwd(), claimStartedFromArgv(process.argv), process.argv.slice(2).join(' '));
37
46
  }
38
47
  /**
39
- * Parse the hang timeout off argv, WITHOUT `||`.
40
- *
41
- * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — "never treat a lock as stale" — into
42
- * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state
43
- * policy entry), so a value that survives the config only to be discarded at the process boundary is
44
- * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.
48
+ * The `started` of the lock claim the spawner took for this run — argv position 3, which is
49
+ * `refresherArgv`'s 2 (see the offset note there). NaN when absent or malformed, which matches no
50
+ * lock, so a hand-run of this file without a claim adopts nothing and exits as SKIP_INPROGRESS.
45
51
  */
46
52
  // webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape
47
- function hangTimeoutFromArgv(raw) {
48
- if (raw === undefined || raw.trim() === '')
49
- return repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
50
- const parsed = Number(raw);
51
- return Number.isFinite(parsed) ? parsed : repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
53
+ function claimStartedFromArgv(argv) {
54
+ const raw = argv[3];
55
+ return raw === undefined || raw.trim() === '' ? Number.NaN : Number(raw);
52
56
  }
53
57
  /**
54
58
  * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is
@@ -67,28 +71,28 @@ function spawnerIdentity(argv) {
67
71
  * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.
68
72
  */
69
73
  // webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape
70
- function refreshMainSync(repoRoot, hangTimeoutMinutes, argvDetail = '') {
74
+ function refreshMainSync(repoRoot, claimStarted, argvDetail = '') {
71
75
  const startedMs = Date.now();
72
76
  // First action: prove the detached child actually started. If the async-refresh stream has no START line
73
77
  // for a spawn, the child never launched (or died before this point).
74
78
  (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));
75
79
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
76
80
  try {
77
- // ONE atomic acquire — not a check followed by a write. The old check-then-write pair had a
78
- // gap in which two detached children could both pass the check and then both run `git fetch`.
79
- const lock = (0, repo_workflow_core_1.tryAcquireMainSyncLock)(repoRoot, hangTimeoutMinutes);
81
+ // ADOPT the spawner's lock, never create one: the spawner already won it atomically.
82
+ const lock = locks.adoptMainSyncLock(repoRoot, claimStarted);
80
83
  if (!lock) {
81
- (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', 'another refresh is in progress'));
84
+ (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', `the spawner's lock ${String(claimStarted)} is no longer on disk; another refresh owns this run`));
82
85
  return;
83
86
  }
87
+ let file = null;
88
+ let outcome = repo_workflow_core_1.RefreshOutcome.ERROR;
84
89
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
85
90
  try {
86
91
  // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used
87
92
  // to describe only the branch of whichever tree won this lock, so every other worktree's
88
93
  // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all
89
94
  // of them; the map is rebuilt from the live worktree set, so dead branches drop out.
90
- const file = (0, repo_workflow_core_1.computeAllMainSyncStatuses)(repoRoot);
91
- (0, repo_workflow_core_1.writeMainSyncStatusFile)(repoRoot, file);
95
+ file = status.computeAllMainSyncStatuses(repoRoot);
92
96
  // Second slow signal, same lock, same detached run: which local branches are dead. One bulk
93
97
  // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its
94
98
  // cap without ever touching the network itself. Deliberately allowed to go stale.
@@ -103,14 +107,23 @@ function refreshMainSync(repoRoot, hangTimeoutMinutes, argvDetail = '') {
103
107
  // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has
104
108
  // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).
105
109
  const reaped = autoReap(repoRoot, cache);
106
- // FINISH after a successful write — START-without-FINISH means we were killed mid-run.
110
+ // FINISH after a successful run — START-without-FINISH means we were killed mid-run.
111
+ outcome = repo_workflow_core_1.RefreshOutcome.OK;
107
112
  const names = Object.keys(file.branches);
108
113
  (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('FINISH', process.pid, names.join(','), `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`));
109
114
  }
110
115
  finally {
111
- // Always flip the lock off so a compute failure can't wedge the guard until the
112
- // staleness reclaim kicks in.
113
- (0, repo_workflow_core_1.writeMainSyncLock)(repoRoot, (0, repo_workflow_core_1.finishedLock)(lock.started));
116
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
117
+ try {
118
+ // Stamp FIRST: a failed run (offline, gh auth) still counts as a run, so it is retried
119
+ // after MIN_REFRESH_INTERVAL_MINUTES rather than hammered on every tool call.
120
+ recordRun(repoRoot, file, lock.startedMs, outcome);
121
+ }
122
+ finally {
123
+ // Lock LAST, and only if still ours: a run that hung past its window was reclaimed,
124
+ // and deleting the newer holder's lock would let a third refresher start beside it.
125
+ locks.releaseMainSyncLock(repoRoot, lock);
126
+ }
114
127
  }
115
128
  }
116
129
  catch (err) {
@@ -120,6 +133,21 @@ function refreshMainSync(repoRoot, hangTimeoutMinutes, argvDetail = '') {
120
133
  (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));
121
134
  }
122
135
  }
136
+ /**
137
+ * Write this run's results and its stamp to main-sync-status.json (atomically). With fresh branch data
138
+ * the whole document is replaced; without it (the compute threw) only the stamp and outcome are
139
+ * updated, keeping the previous branch data the guards are still reading.
140
+ */
141
+ // webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape
142
+ function recordRun(repoRoot, file, startedMs, outcome) {
143
+ if (file === null) {
144
+ status.recordRefreshOutcome(repoRoot, startedMs, outcome);
145
+ return;
146
+ }
147
+ file.lastRefreshStartedMs = startedMs;
148
+ file.lastRefreshOutcome = outcome;
149
+ status.writeMainSyncStatusFile(repoRoot, file);
150
+ }
123
151
  /**
124
152
  * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log
125
153
  * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to
@@ -1 +1 @@
1
- {"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/sync-main.ts"],"names":[],"mappings":";;AA8BA,oBAOC;AAWD,kDAIC;AAWD,0CAEC;AAOD,0CA0DC;AAjID,sEAAqR;AACrR,0DAA0D;AAE1D,iEAA6D;AAC7D,mDAA6D;AAC7D,6CAAyD;AAEzD;;;;;;;;;;;;;;;;;;;;GAoBG;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,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EACpC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAClC,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,yHAAyH;AACzH,SAAgB,mBAAmB,CAAC,GAAuB;IACvD,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,iDAA4B,CAAC;IAChF,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IAC3B,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,iDAA4B,CAAC;AAC3E,CAAC;AAED;;;;;;;GAOG;AACH,yHAAyH;AACzH,SAAgB,eAAe,CAAC,IAAc;IAC1C,OAAO,IAAI,2BAAc,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,C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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,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { BranchCreationGuardConfig } from '../configs/rule-configs';\nimport { BranchReaper, DEFAULT_HANG_TIMEOUT_MINUTES, MainSyncStatusFile, MergedBranchesCache, MergedBranchesService, ReapResult, computeAllMainSyncStatuses, writeMainSyncStatusFile, writeMainSyncLock, tryAcquireMainSyncLock, finishedLock } 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/**\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: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start\n * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds\n * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,\n * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.\n *\n * argv: [, , repoRoot, hangTimeoutMinutes, 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 hangTimeoutFromArgv(process.argv[3]),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * Parse the hang timeout off argv, WITHOUT `||`.\n *\n * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — \"never treat a lock as stale\" — into\n * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state\n * policy entry), so a value that survives the config only to be discarded at the process boundary is\n * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function hangTimeoutFromArgv(raw: string | undefined): number {\n if (raw === undefined || raw.trim() === '') return DEFAULT_HANG_TIMEOUT_MINUTES;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : DEFAULT_HANG_TIMEOUT_MINUTES;\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, hangTimeoutMinutes: 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 // ONE atomic acquire — not a check followed by a write. The old check-then-write pair had a\n // gap in which two detached children could both pass the check and then both run `git fetch`.\n const lock = tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', 'another refresh is in progress'));\n return;\n }\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 const file = computeAllMainSyncStatuses(repoRoot);\n writeMainSyncStatusFile(repoRoot, file);\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 write — START-without-FINISH means we were killed mid-run.\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 // Always flip the lock off so a compute failure can't wedge the guard until the\n // staleness reclaim kicks in.\n writeMainSyncLock(repoRoot, finishedLock(lock.started));\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 * 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":[],"mappings":";;AAwCA,oBAOC;AAQD,oDAGC;AAWD,0CAEC;AAOD,0CAkEC;AA/ID,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;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;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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,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,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, 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"]}