@webpieces/agent-workflow-rules 0.4.916 → 0.4.918
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 +7 -7
- package/src/adapters/codex-subagent-guard.d.ts +2 -2
- package/src/adapters/codex-subagent-guard.js +2 -2
- package/src/adapters/codex-subagent-guard.js.map +1 -1
- package/src/adapters/hook-app-fixtures.d.ts +1 -1
- package/src/adapters/hook-app-fixtures.js +1 -1
- package/src/adapters/hook-app-fixtures.js.map +1 -1
- package/src/adapters/hook-core.js +3 -3
- package/src/adapters/hook-core.js.map +1 -1
- package/src/bin/dev-hook-install.js +1 -1
- package/src/bin/dev-hook-install.js.map +1 -1
- package/src/bin/dev-hook-uninstall.js +1 -1
- package/src/bin/dev-hook-uninstall.js.map +1 -1
- package/src/bin/l0-allowlist.js +1 -1
- package/src/bin/l0-allowlist.js.map +1 -1
- package/src/bin/setup.js +3 -3
- package/src/bin/setup.js.map +1 -1
- package/src/bin/shim-audit-log.d.ts +2 -2
- package/src/bin/shim-audit-log.js +3 -3
- package/src/bin/shim-audit-log.js.map +1 -1
- package/src/bin/shim.js +1 -1
- package/src/bin/shim.js.map +1 -1
- package/src/bin/upgrade-shim.js +1 -1
- package/src/bin/upgrade-shim.js.map +1 -1
- package/src/configs/main-sync-guard-configs.d.ts +1 -1
- package/src/configs/main-sync-guard-configs.js +1 -1
- package/src/configs/main-sync-guard-configs.js.map +1 -1
- package/src/core/decision-log.d.ts +6 -6
- package/src/core/decision-log.js +7 -7
- package/src/core/decision-log.js.map +1 -1
- package/src/core/excluded-path-escape.d.ts +4 -4
- package/src/core/excluded-path-escape.js +5 -5
- package/src/core/excluded-path-escape.js.map +1 -1
- package/src/core/l0-matrix.d.ts +1 -1
- package/src/core/l0-matrix.js +1 -1
- package/src/core/l0-matrix.js.map +1 -1
- package/src/core/l1-doc.js +8 -8
- package/src/core/l1-doc.js.map +1 -1
- package/src/core/l1-matrix-doc.js +1 -1
- package/src/core/l1-matrix-doc.js.map +1 -1
- package/src/core/l1-rows.js +2 -2
- package/src/core/l1-rows.js.map +1 -1
- package/src/core/l2-doc.js +2 -2
- package/src/core/l2-doc.js.map +1 -1
- package/src/core/l2-matrix-doc.js +1 -1
- package/src/core/l2-matrix-doc.js.map +1 -1
- package/src/core/l2-rows.js +1 -1
- package/src/core/l2-rows.js.map +1 -1
- package/src/core/main-sync-log.d.ts +2 -2
- package/src/core/main-sync-log.js +3 -3
- package/src/core/main-sync-log.js.map +1 -1
- package/src/core/main-sync-refresh.d.ts +1 -1
- package/src/core/main-sync-refresh.js +2 -2
- package/src/core/main-sync-refresh.js.map +1 -1
- package/src/core/main-sync-timeout.js +1 -1
- package/src/core/main-sync-timeout.js.map +1 -1
- package/src/core/rejection-log.js +2 -2
- package/src/core/rejection-log.js.map +1 -1
- package/src/core/rules/content-read-scan.js +2 -2
- package/src/core/rules/content-read-scan.js.map +1 -1
- package/src/core/rules/feature-branch-guard.d.ts +1 -1
- package/src/core/rules/feature-branch-guard.js +1 -1
- package/src/core/rules/feature-branch-guard.js.map +1 -1
- package/src/core/runner.js +1 -1
- package/src/core/runner.js.map +1 -1
- package/src/core/sync-main.d.ts +2 -2
- package/src/core/sync-main.js +2 -2
- package/src/core/sync-main.js.map +1 -1
- package/templates/ai-hook.sh +3 -3
package/src/core/l2-rows.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"l2-rows.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/l2-rows.ts"],"names":[],"mappings":";AAAA,8EAA8E;AAC9E,wCAAwC;AACxC,EAAE;AACF,qGAAqG;AACrG,iFAAiF;AACjF,EAAE;AACF,uGAAuG;AACvG,uGAAuG;AACvG,sGAAsG;AACtG,0FAA0F;AAC1F,EAAE;AACF,iFAAiF;AACjF,EAAE;AACF,sGAAsG;AACtG,uGAAuG;AACvG,oGAAoG;AACpG,sGAAsG;AACtG,oGAAoG;AACpG,mGA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AI,CAAC;AAChB,CAAC;AAED,0EAA0E;AAC1E,yFAAyF;AACzF,SAAgB,eAAe;IAC3B,OAAO,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,CAAC;AACnF,CAAC;AAED,yFAAyF;AACzF,MAAa,SAAS;IACG;IAAsB;IAAsB;IAAjE,YAAqB,GAAW,EAAW,GAAW,EAAW,GAAW;QAAvD,QAAG,GAAH,GAAG,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;IAAG,CAAC;CACnF;AAFD,8BAEC;AAED;;;;;;;;GAQG;AACU,QAAA,QAAQ,GAAyB;AAC1C,iGAAiG;AACjG,EAAE;AACF,oGAAoG;AACpG,qGAAqG;AACrG,kGAAkG;AAClG,yFAAyF;AACzF,4CAA4C;AAC5C,oGAAoG;AACpG,oGAAoG;AACpG,qGAAqG;AACrG,wFAAwF;AACxF,EAAE;AACF,kGAAkG;AAClG,8FAA8F;CACjG,CAAC","sourcesContent":["// ---------------------------------------------------------------------------\n// L2 — the BRANCH-STATE layer, as data.\n//\n// L2 answers one question: *may I work here, and is what I read current?* Drawn as a decision matrix\n// that is TWELVE ordered rows plus one terminal fail-open row, first match wins.\n//\n// This module holds those rows, l2-doc.ts renders them into guards/L2-branch-state.md, and a unit test\n// (l2-matrix.spec.ts) locks that file byte-identical to the renderer — the same mechanism that already\n// makes L0's fault table and L1's location table undriftable. Before this existed the L2 doc was 100%\n// hand-written and said so: *\"Until that lands this text is hand-written and can drift.\"*\n//\n// ## HOW L2 JOINS TO THE ROWS TODAY — read this before assuming it works like L1\n//\n// L1 DISPATCHES from its array: `runner.l1LocationBlock` takes the first matching row and switches on\n// its `blockId`, so deleting a row deletes a block. L2 does NOT, and pretending otherwise would be the\n// drift this table exists to remove. The four L2 guard classes each own their own ladder, and those\n// ladders diverge on purpose (guards/L2-branch-state.md, \"Deliberate divergence\": the two Bash guards\n// differ in polarity, quantifier and empty-command handling all at once, so no single parameterised\n// function serves both). Unifying them is where a wrong edit turns an allow into a session-wedging\n// block, so it is deliberately not attempted here.\n//\n// What L2 does instead is a REASON→ROW join. Every exit of every L2 guard already carries a stable\n// reason string into the decision log; `L2_ROW_FOR_REASON` maps each of those to the row it is an\n// instance of, the guards stamp that number as `row=`, and l2-matrix.spec.ts asserts the map is\n// EXHAUSTIVE against the guard sources — a new reason with no row fails the build. So `row=8` in\n// `.webpieces-logs/logs/L2-decisions` opens guards/L2-branch-state.md at row 8 and reads the state, the cure\n// and the tools that row covers, exactly as `row=5` already does for L1.\n//\n// The rows the guards cannot yet honour are named in the doc's \"Not done\" section rather than quietly\n// rendered as if they were live. That section is generated from NOT_DONE below, so it cannot rot.\n//\n// This module is deliberately import-free at runtime, so `pnpm guards:generate` can load it without the\n// package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\nimport { L2_ALLOW, L2_BLOCK, L2_EXEMPT, L2_FAIL_OPEN, L2_FAIL_OPEN_ROW, L2Row, L2UseCase, NO_ROW_EXIT } from './l2-row';\n\nexport {\n L2Action, L2ActionKind, L2Tool,\n L2_ALLOW, L2_BLOCK, L2_EXEMPT, L2_FAIL_OPEN, L2_FAIL_OPEN_ROW, L2Row, L2UseCase, NO_ROW_EXIT,\n} from './l2-row';\n\n/**\n * THE THIRTEEN L2 ROWS, in first-match-wins order.\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 marker-file\n * scan, row 5 is one `git rev-parse`. Row 11 is the cache divider. Rows 6-10 all read the cache.\n *\n * THE ORDER OF ROW 5 IS THE MOST LOAD-BEARING THING IN THIS TABLE. Put \"on main\" BELOW the divider and\n * WRITES on `main` are permitted for the whole first call of every session — and permanently in a\n * multi-worktree repo, where another tree may hold the cache lock indefinitely.\n *\n * `B` AND `E` PART COMPANY ON `main`, and rows 5/6/7 are where. A WRITE on `main` is wrong at any\n * freshness — the work lands somewhere unreviewable and unrevertable — so row 5 is `E` only, judged on\n * the branch alone, above the divider. A READ or a BUILD on a CURRENT `main` is harmless, and blocking\n * it strands the agent right after `pnpm wp-sync-main` put it there; so `B` joins `R` on the\n * FRESHNESS-gated pair below the divider (row 6 behind → block, row 7 current → allow), where \"cannot\n * tell\" fails open at row 11 by construction. `B` and `R` still differ in SHAPE inside row 6: a Read\n * names one file and is judged precisely, a Bash command is opaque and gets default-deny plus row 4.\n */\nexport const L2_ROWS: readonly L2Row[] = [\n new L2Row(1, ['B', 'R', 'E'], 'on the **global allowlist** (inert command, or a universal cure such as reading/editing `webpieces.config.json`)', L2_ALLOW, '—', [\n new L2UseCase(1,\n 'You are blocked by some other L2 row, and need to turn the policy off to get anything done',\n 'any state — this row is ahead of every block',\n 'ALLOW: reading and editing `webpieces.config.json` is never blocked, so the mode-OFF cure is always reachable',\n 'Edit `webpieces.config.json` → `hookGuards` → `branch-state-guard` → `\"mode\": \"OFF\"`',\n 'webpieces-config-read (escape hatch)'),\n new L2UseCase(2,\n 'A Write to `webpieces.config.json` while on `main`, which row 5 would otherwise block',\n 'on `main`, editing the one file that can disable the guard',\n 'ALLOW: the hook adapter bypasses feature-branch-guard for this path before any guard runs',\n 'None needed — the edit proceeds',\n 'config-bypass (feature-branch-guard skipped)'),\n ]),\n new L2Row(2, ['B'], 'bare `git checkout main`, with no `git pull` chained into the same command', L2_BLOCK, '`pnpm wp-sync-main`', [\n new L2UseCase(3,\n '`git checkout main` after a merge, to start the next piece of work',\n 'about to land on whatever local `main` you last had — 157 commits behind, in the incident',\n 'BLOCK: decided from command TEXT alone, before the checkout, because the only `main` this could measure is the one it is about to leave',\n '`pnpm wp-sync-main` — checkout, pull, reap dead branches/worktrees, sweep orphan directories, in one command (hand-rolled, the pull must be in the SAME command as the checkout)',\n 'bare checkout of main ('),\n new L2UseCase(4,\n 'The same command inside a linked worktree, where `git checkout main` fatals anyway',\n 'linked worktree — `main` is already checked out in the primary clone',\n 'BLOCK, and the message prints the worktree form rather than a cure git would refuse',\n '`git fetch origin main`, then work off `origin/main`',\n 'bare checkout of main ('),\n ]),\n new L2Row(3, ['B', 'R', 'E'], '**merge in progress** — L4 owns this state', L2_EXEMPT, 'finish the merge: `pnpm wp-finish-upsert-pr`', [\n new L2UseCase(5,\n 'Reading and editing conflicted files during a 3-point merge, on a branch row 9 would block',\n 'merge markers on disk — `pnpm wp-start-update` has run and not finished',\n 'EXEMPT: everything is permitted, which is exactly what lets row 9 be strict',\n 'Resolve the conflicts, then `pnpm wp-finish-upsert-pr`',\n NO_ROW_EXIT),\n ]),\n new L2Row(4, ['B'], 'on the **skip list** — it gets you OUT, or tells you where you are', L2_ALLOW, '—', [\n new L2UseCase(6,\n '`git status` / `gh pr view` while blocked, to work out where you are',\n 'any state — orientation is never \"working here\"',\n 'ALLOW: metadata tells you where you are without putting stale file CONTENT in context',\n 'None needed',\n 'not-a-content-read (cure/build/metadata)'),\n new L2UseCase(7,\n '`git stash` when `git checkout -b <new> origin/main` refuses because `origin/main` touched the same files you edited',\n 'on a stale `main` or a merged branch, dirty tree, with an overlapping upstream change',\n 'ALLOW: the cure for the row that blocked you must itself never be blocked — and this is the residual step that makes rows 6 and 8 safe to block on a dirty tree',\n 'None needed — then re-run the checkout and `git stash pop`',\n 'not-a-content-read (cure/build/metadata)'),\n new L2UseCase(28,\n '`gh pr close 123`, `gh pr comment`, `gh api …` or a `curl` while parked on a stale `main` or a merged branch',\n 'blocked state, running something that touches GitHub or a URL and nothing in this tree',\n 'ALLOW: the skip list asks one question — does this read or write repo CONTENT? `gh` talks to GitHub and `curl`/`wget` talk to a network, so the branch state has nothing to say about them. The forms that write a local file (`gh repo clone`, `gh pr checkout`, `curl -o`, any `> file`) are excluded, and `gh pr create`/`merge` remain governed by their own guards',\n 'None needed',\n 'not-a-content-read (cure/build/metadata)'),\n new L2UseCase(8,\n '`pnpm wp-start-upsert-pr` on a branch whose fork point is broken',\n 'row 9 state, running the tool row 9 prescribes',\n 'ALLOW: every `wp-*` bin is on the skip list, so no row can block its own remedy',\n 'None needed',\n 'merged-branch recovery/inspection (allowlisted)'),\n ]),\n new L2Row(5, ['E'], 'on `main`', L2_BLOCK, '`git checkout -b <new> origin/main`', [\n new L2UseCase(9,\n 'An Edit or Write to any tracked file while `git rev-parse --abbrev-ref HEAD` says `main`',\n 'on `main`, any freshness',\n 'BLOCK: decided by one `git rev-parse`, with NO cache read, so it fires on the first tool call of the session',\n '`git checkout -b <new> origin/main` — uncommitted work comes with you',\n 'on-main'),\n new L2UseCase(25,\n 'The FIRST edit of a session, on `main`, before any cache exists',\n 'on `main`, cache absent — row 11 would fail open',\n 'BLOCK anyway: row 5 is ABOVE the cache divider and reads only `git rev-parse`, so it is armed on call #1. This is why the row is `E` only and must never be gated on the cache',\n '`git checkout -b <new> origin/main`',\n 'on-main'),\n ]),\n new L2Row(L2_FAIL_OPEN_ROW, ['B', 'R', 'E'], '**the state could not be established** — branch undeterminable, no cache yet, the cache holds another branch, `origin/main` unknown, or the forge unreachable', L2_FAIL_OPEN, '— (nothing to fix; the refresher populates the cache for the next call)', [\n new L2UseCase(11,\n 'The very first tool call of a session is allowed even on a badly stale `main`',\n 'no cache — the refresher is fire-and-forget and populates it for the NEXT call',\n 'ALLOW (fail-open), logged as `ALLOW_FAIL_OPEN` so abstentions stay countable',\n 'None — the second call is judged normally',\n 'no-sync-cache'),\n new L2UseCase(12,\n 'Guards quietly stand down on a plane, or when `gh` is unauthenticated or rate-limited',\n 'the forge could not be asked whether the PR is merged',\n 'ALLOW (fail-open) logged as `no-forge` — distinct from \"asked, and it is not merged\", which used to look identical in the trail',\n 'None — restore network/`gh auth` to re-arm the merged-branch policy',\n 'no-forge'),\n new L2UseCase(27,\n 'A build, a `cat` or a `curl` on `main`, on the first Bash call of a session',\n 'on `main`, cache absent — so whether `main` is behind is UNKNOWN',\n 'ALLOW (fail-open), logged `ALLOW_FAIL_OPEN`. `B` on `main` is judged by rows 6/7 and therefore lands here when the cache cannot answer; the WRITE half is not, which is why row 5 sits above this divider',\n 'None — the second call is judged normally',\n 'no-sync-cache'),\n new L2UseCase(14,\n 'Mid-rebase, every guard abstains',\n 'detached HEAD — there is no branch name to judge',\n 'ALLOW (fail-open), logged LOUDLY when the branch is unresolvable rather than merely detached',\n 'None — finish or abort the rebase',\n 'branch-undeterminable'),\n ]),\n // ROWS 12/13 sit ABOVE row 6 because they are judged inside its state: local `main` is established\n // BEHIND, and the only remaining question is whether the command already carries its own cure. They\n // are numbered 12/13 rather than slotted in as 6a/6b for the reason row 11 is numbered 11 — row\n // numbers are logged as `row=` and cited here, so renumbering re-points every existing reference.\n new L2Row(12, ['B'], 'on `main`, behind `origin/main`, and the command STARTS with a refresh-main cure joined to the work by `&&`', L2_ALLOW, '—', [\n new L2UseCase(29,\n '`git fetch --prune origin main -q && git pull --ff-only origin main 2>&1 | tail -1 && sed -n \\'30,75p\\' src/app.ts` — the agent cures and reads in one call',\n 'on `main`, behind `origin/main`, cure first, `&&` between',\n 'ALLOW: `&&` short-circuits, so the `sed` never runs if the pull fails — the guard was refusing a safety property the shell already enforces. Measured fleet-wide as `cure_bundled_and`, and filed as a TOOLING defect, not an agent one',\n 'None needed',\n 'cure-prefixed, && short-circuits the work'),\n ]),\n new L2Row(13, ['B'], 'on `main`, behind `origin/main`, and the cure is joined to the work by `;` (or `||`, `&`, a newline) — the work runs even if the cure fails', L2_BLOCK, '`pnpm wp-sync-main && <your command>`', [\n new L2UseCase(30,\n '`pnpm wp-sync-main >/dev/null 2>&1; git log --oneline -1; sed -n \\'598,612p\\' eslint.config.mjs` — and the agent then quotes an eslint rule out of a file 15 commits stale',\n 'on `main`, behind `origin/main`, cure first, `;` between',\n 'BLOCK: `;` discards the cure\\'s exit code, so a conflict, a dirty tree or no network leaves the `sed` reading still-stale content — and 7 of the 9 observed cases also silenced the cure with `>/dev/null 2>&1`, so the failure was invisible too. The two-step is safer because the NEXT tool call re-computes `localMain` against `originMain`, so a failed pull re-blocks; an allowed `;` compound never gets that second look',\n 'Swap the `;` for `&&` — `pnpm wp-sync-main && <your command>` — or run the cure alone and re-issue the command in the next call',\n 'cure-prefixed, work runs anyway'),\n ]),\n new L2Row(6, ['B', 'R'], 'on `main`, farther behind `origin/main` than `maxCommitsBehind`', L2_BLOCK, '`pnpm wp-sync-main`, or `git checkout -b <new> origin/main`', [\n new L2UseCase(13,\n 'The Read tool refuses a file on a stale `main` while you have UNCOMMITTED edits',\n 'on `main`, beyond `maxCommitsBehind`, dirty tree',\n 'BLOCK. This used to fail open, on the argument that the prescribed `git pull` is not a clean fast-forward when the tree is dirty. That was true of the MESSAGE, not the row: the cure cell always offered a second form, and it works dirty',\n '`git checkout -b <new> origin/main` — uncommitted changes come with you onto the new branch. If git refuses because `origin/main` touched the same files, `git stash` first (never blocked), then retry, then `git stash pop`',\n 'on-stale-main'),\n new L2UseCase(15,\n 'The Read tool refuses a file that exists, on a `main` 18 commits behind',\n 'on `main`, beyond `maxCommitsBehind`, clean tree',\n 'BLOCK: judged by live ancestry (`git merge-base --is-ancestor`), not hash equality, so a pull takes effect instantly',\n '`pnpm wp-sync-main`, or `git checkout -b <new> origin/main`',\n 'on-stale-main'),\n new L2UseCase(16,\n 'Read is blocked, so the session reaches for `cat`, `grep` and `ls` instead — and describes a CI workflow set missing a whole workflow that existed upstream',\n 'the SIDE DOOR: same tree, same staleness, different tool',\n 'BLOCK: `B` is judged here beside `R`, so closing the Read tool no longer opens a shell-shaped hole. The log used to read \"read-stale-guard handled\", which is worse than no guard — it looks covered',\n '`git checkout -b <new> origin/main`',\n 'on-stale-main'),\n new L2UseCase(10,\n 'A Bash command that WRITES tracked files as a side effect — `npx expo install`, a formatter, codegen, `sed -i`, a `>` redirect',\n 'on a `main` known to be beyond `maxCommitsBehind`, and the write is incidental to a command whose stated purpose is something else',\n 'BLOCK: inside this row `B` is default-DENY plus row 4\\'s skip list, never a blocklist of readers — a command nobody thought to enumerate is caught by not being on the list, which is the only shape that could have caught this one',\n '`git checkout -b <new> origin/main` BEFORE running anything that may write',\n 'on-stale-main'),\n ]),\n new L2Row(7, ['B', 'R'], 'on `main`, current or within `maxCommitsBehind`', L2_ALLOW, '—', [\n new L2UseCase(17,\n 'Reading files on a `main` you just pulled',\n 'on `main`, and `origin/main` is an ancestor of HEAD',\n 'ALLOW: ancestry, not hash equality, so the allow arrives the instant the pull lands rather than when the detached refresher next runs',\n 'None needed',\n 'local-main-contains-origin (up to date)'),\n new L2UseCase(24,\n '`curl`, `gh pr close` or a test run, immediately after `pnpm wp-sync-main` landed you on a perfectly current `main`',\n 'on `main`, current — no staleness anywhere',\n 'ALLOW. This used to BLOCK, from the branch alone: the tool the repo prescribes put the agent here, and the guard whose name says STALE then refused everything off a narrow allowlist for a reason that had nothing to do with staleness. WRITES here are still blocked, by row 5 — that hazard is real at any freshness',\n 'None needed',\n 'local-main-contains-origin (up to date)'),\n new L2UseCase(31,\n 'Reading or running Bash while local `main` is five commits behind and the configured maximum is five',\n 'on `main`, cached `commitsBehind` is at or below `maxCommitsBehind`',\n 'ALLOW: the detached refresher computed the distance; the guard hot path only reads the cache',\n 'None needed',\n 'within-max-commits-behind'),\n ]),\n new L2Row(8, ['B', 'R', 'E'], 'on a branch whose PR is **already merged**', L2_BLOCK, '`git fetch origin main && git checkout -b <new> origin/main`', [\n new L2UseCase(18,\n 'You keep working on the branch after its PR merged, and the next PR reopens code review already landed',\n 'branch whose PR is merged — `merged` is monotonic, so the cached flag is trusted with no TTL',\n 'BLOCK across all three tools',\n '`git fetch origin main && git checkout -b <new> origin/main`',\n 'already-merged PR#'),\n new L2UseCase(26,\n 'You have uncommitted edits on a branch whose PR just merged',\n 'merged branch, dirty tree',\n 'BLOCK. This used to fail open too, and that valve never had an argument behind it — row 8\\'s cure carries uncommitted work onto the fresh branch, so nothing was ever trapped. It was drift from the documented design, which `read-stale-guard`\\'s own class comment still described correctly',\n '`git fetch origin main && git checkout -b <new> origin/main` — your edits come with you',\n 'already-merged PR#'),\n new L2UseCase(19,\n 'A shell-only session sails through on a merged branch',\n 'merged branch, Bash only — both FILE guards are file-scoped, so Bash reached neither',\n 'BLOCK: `merged-branch-bash-guard` exists because `branchAlreadyMerged` was being computed and logged on that very path, then thrown away',\n '`git fetch origin main && git checkout -b <new> origin/main`',\n 'already-merged PR#'),\n ]),\n new L2Row(9, ['B', 'R', 'E'], 'no fork point with `origin/main`, or `origin/main` moved and collided with your files', L2_BLOCK, '`pnpm wp-start-update`, or `pnpm wp-start-upsert-pr` when a PR is open', [\n new L2UseCase(20,\n 'Your branch and `origin/main` share no merge base — usually a branch cut from a squashed-away tip',\n 'no fork point',\n 'BLOCK: nothing built on this branch can be reasoned about relative to main',\n '`pnpm wp-start-update`, or `pnpm wp-start-upsert-pr` when a PR is open',\n 'no-fork-point'),\n new L2UseCase(21,\n '`origin/main` moved and changed the same files you edited',\n 'main-moved collision',\n 'BLOCK — and row 3 then exempts everything once the merge starts, which is what makes this safe',\n '`pnpm wp-start-update`, resolve, `pnpm wp-finish-upsert-pr`',\n 'main-moved-conflict'),\n ]),\n new L2Row(10, ['B', 'R', 'E'], 'healthy feature branch', L2_ALLOW, '—', [\n new L2UseCase(22,\n 'Ordinary work on a branch cut from a current `origin/main`',\n 'healthy feature branch',\n 'ALLOW — the state every other row exists to push you back into',\n 'None needed',\n 'clean-feature-branch'),\n new L2UseCase(23,\n '`stale-main-bash-guard` sees a feature branch and hands off',\n 'not on `main` — state B belongs to `merged-branch-bash-guard`',\n 'ALLOW: the same verdict about the same tree, logged by the guard that is not responsible for it',\n 'None needed',\n 'not-on-main (state B is another guard)'),\n ]),\n];\n\n/**\n * Every use case on every row, in row order, for the doc and for the exhaustiveness specs.\n *\n * Numbering is GLOBAL and is identity, exactly as the row numbers are: a use case is cited by number in\n * review and in the doc, so add new ones at the END of the highest number rather than renumbering to\n * keep a row's block contiguous.\n */\n// webpieces-disable no-function-outside-class -- pure accessor over L2_ROWS above, in this data module\nexport function allL2UseCases(): readonly L2UseCase[] {\n return L2_ROWS.flatMap((row: L2Row): readonly L2UseCase[] => row.useCases);\n}\n\n/**\n * REASON → ROW. The join between what a guard actually logged and the row it is an instance of.\n *\n * Keys are the exact `reason` strings the four L2 guards pass to their decision log. Two of them are\n * PREFIXES because the guard interpolates a PR number or a matched segment into the reason\n * (`already-merged PR#123`); those are matched by `l2RowForReason` on prefix, which is why they end in\n * a space or a `(`.\n *\n * l2-matrix.spec.ts reads the four guard sources and asserts every reason literal in them resolves\n * here, so a new exit with no row fails the build rather than logging `row=-` forever.\n */\nconst EXACT_REASON_ROWS: Record<string, number> = {\n // Row 1 — the universal cure that must stay reachable from inside any block.\n 'webpieces-config-read (escape hatch)': 1,\n // Row 2 — the preventive half, decided from command TEXT before any cache is read.\n // (prefix, see PREFIX_REASON_ROWS)\n // Row 4 — the skip list, in its two live spellings.\n 'merged-branch recovery/inspection (allowlisted)': 4,\n 'not-a-content-read (cure/build/metadata)': 4,\n // Row 5 — never WRITE on main, at any freshness. `E` only; the Bash half is rows 6/7.\n 'on-main': 5,\n // Row 6/7 — freshness, for `B` and `R` alike. Both guards log these two literals: read-stale-guard\n // for the Read tool, stale-main-bash-guard for Bash. Same cache, same ancestry test, one verdict.\n 'on-stale-main': 6,\n 'local-main-contains-origin (up to date)': 7,\n 'within-max-commits-behind': 7,\n // Rows 12/13 — composition, judged INSIDE row 6's state: the tree is established behind, and the\n // only remaining question is whether the command carries its own cure and with which operator.\n 'cure-prefixed, && short-circuits the work': 12,\n 'cure-prefixed, work runs anyway': 13,\n // Row 9 — the two unhealthy-fork states.\n 'no-fork-point': 9,\n 'main-moved-conflict': 9,\n // Row 10 — healthy, and the state-B guard's \"this is not my state\" hand-off, which is the same\n // verdict about the same tree.\n 'clean-feature-branch': 10,\n 'not-on-main (state B is another guard)': 10,\n // Row 11 — every \"could not establish\", including the two dirty-tree valves the code still opens\n // (see NOT_DONE) and the unreachable forge.\n 'branch-undeterminable': L2_FAIL_OPEN_ROW,\n 'commit-distance-unknown': L2_FAIL_OPEN_ROW,\n // The target tree HAS no branch name (mid-rebase / mid-bisect), so there is no key into the\n // branch-keyed cache — use case 14, which the row already describes. It used to arrive here as the\n // literal branch `HEAD`, miss in the cache and log `no-sync-cache`: the right verdict recorded under\n // a reason that names a different cause, and therefore uncountable.\n 'detached-head': L2_FAIL_OPEN_ROW,\n // The file being judged lives in a NESTED CLONE (`repositories/**`) — another repo's branch is not\n // this policy's to judge. The bash path calls the same state ALLOW_EXEMPT at L1; on the file path it\n // is an abstention, because nothing about the target tree's state was established.\n 'target-tree-foreign': L2_FAIL_OPEN_ROW,\n 'no-sync-cache': L2_FAIL_OPEN_ROW,\n 'stale-cross-branch-cache': L2_FAIL_OPEN_ROW,\n 'origin-main-unknown': L2_FAIL_OPEN_ROW,\n // `dirty-tree-on-main` and `dirty-merged-branch` used to live here. Both valves are deleted: rows\n // 6 and 8 now block on a dirty tree, because each row's cure carries uncommitted work with you.\n 'no-forge': L2_FAIL_OPEN_ROW,\n // The config-edit bypass logged by the hook adapter before any guard runs — row 1, same universal\n // cure as the config READ above.\n 'config-bypass (feature-branch-guard skipped)': 1,\n};\n\n/** Reasons the guards interpolate a value into. Matched by prefix, longest first. */\nconst PREFIX_REASON_ROWS: Record<string, number> = {\n 'already-merged PR#': 8,\n 'bare checkout of main (': 2,\n // `stale-main content read (` used to live here, mapping the Bash side of row 6. It is gone with\n // the guard exit that emitted it: on `main`, row 5 now blocks before any content-read scan runs,\n // so row 6 is what the table always said it was — the ROW-ONLY row.\n};\n\n/**\n * The row a logged reason belongs to, or null when nothing claims it.\n *\n * Null rather than a default row: a reason with no row is a HOLE in the table, and defaulting it to\n * \"fail-open\" would hide exactly the drift the exhaustiveness spec exists to catch. The guards render\n * null as `row=-`, so an unmapped reason is visible in the log too, not only in CI.\n */\n// webpieces-disable no-function-outside-class -- the matcher over the two tables above, beside them in this data module\nexport function l2RowForReason(reason: string): number | null {\n const exact = EXACT_REASON_ROWS[reason];\n if (exact !== undefined) return exact;\n for (const prefix of Object.keys(PREFIX_REASON_ROWS)) {\n if (reason.startsWith(prefix)) return PREFIX_REASON_ROWS[prefix];\n }\n return null;\n}\n\n/** Every reason string this table claims, for the exhaustiveness spec. */\n// webpieces-disable no-function-outside-class -- pure accessor over the two tables above\nexport function l2MappedReasons(): readonly string[] {\n return [...Object.keys(EXACT_REASON_ROWS), ...Object.keys(PREFIX_REASON_ROWS)];\n}\n\n/** One documented gap between a row and what the guards actually do today. Data-only. */\nexport class L2NotDone {\n constructor(readonly row: number, readonly gap: string, readonly why: string) {}\n}\n\n/**\n * WHERE THE TABLE AND THE CODE DISAGREE, stated rather than papered over.\n *\n * The L1 precedent is `## Not done — \\`o\\` is not exempt yet`: a row the runner cannot reach, named in\n * the generated doc with the reason it has not shipped. The same treatment applies here, and it is what\n * makes it safe to publish a table the guards do not yet dispatch from — a reader is told exactly which\n * rows describe intent rather than behaviour, and the log's `row=` stamps land on row 11 for every one\n * of these, so the trail never claims the strict row fired.\n */\nexport const NOT_DONE: readonly L2NotDone[] = [\n // EMPTY, and that is the goal state: every row in the table is a row the guards actually honour.\n //\n // It held three entries. Row 5's `B` half shipped and then MOVED: on `main`, a write is judged from\n // the branch alone (row 5, above the divider) while Bash is judged on freshness beside the Read tool\n // (rows 6/7), because a build on a CURRENT `main` harms nothing and denying it stranded agents on\n // the very `main` `pnpm wp-sync-main` had just handed them. Rows 6 and 8 held DIRTY-TREE\n // valves, and both are now closed — each of\n // those rows cures with `git checkout -b <new> origin/main`, which carries uncommitted changes onto\n // the new branch, so a dirty tree never trapped anybody. The row 6 entry claimed the dirty argument\n // \"has teeth\" there because its cure is `git pull`; that was a fact about the MESSAGE, which printed\n // only the pull, and the fix was to print both cures rather than to suppress the block.\n //\n // Keep this array. An empty \"Not done\" is a claim worth making explicitly — the doc says so in as\n // many words — and the next divergence between a row and its code belongs here, not in prose.\n];\n"]}
|
|
1
|
+
{"version":3,"file":"l2-rows.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/l2-rows.ts"],"names":[],"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AC,CAAC;IACxC,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IACtC,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAAE,CAAC;QACnD,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC;YAAE,OAAO,kBAAkB,CAAC,MAAM,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,IAAI,CAAC;AAChB,CAAC;AAED,0EAA0E;AAC1E,yFAAyF;AACzF,SAAgB,eAAe;IAC3B,OAAO,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,CAAC;AACnF,CAAC;AAED,yFAAyF;AACzF,MAAa,SAAS;IACG;IAAsB;IAAsB;IAAjE,YAAqB,GAAW,EAAW,GAAW,EAAW,GAAW;QAAvD,QAAG,GAAH,GAAG,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;IAAG,CAAC;CACnF;AAFD,8BAEC;AAED;;;;;;;;GAQG;AACU,QAAA,QAAQ,GAAyB;AAC1C,iGAAiG;AACjG,EAAE;AACF,oGAAoG;AACpG,qGAAqG;AACrG,kGAAkG;AAClG,yFAAyF;AACzF,4CAA4C;AAC5C,oGAAoG;AACpG,oGAAoG;AACpG,qGAAqG;AACrG,wFAAwF;AACxF,EAAE;AACF,kGAAkG;AAClG,8FAA8F;CACjG,CAAC","sourcesContent":["// ---------------------------------------------------------------------------\n// L2 — the BRANCH-STATE layer, as data.\n//\n// L2 answers one question: *may I work here, and is what I read current?* Drawn as a decision matrix\n// that is TWELVE ordered rows plus one terminal fail-open row, first match wins.\n//\n// This module holds those rows, l2-doc.ts renders them into guards/L2-branch-state.md, and a unit test\n// (l2-matrix.spec.ts) locks that file byte-identical to the renderer — the same mechanism that already\n// makes L0's fault table and L1's location table undriftable. Before this existed the L2 doc was 100%\n// hand-written and said so: *\"Until that lands this text is hand-written and can drift.\"*\n//\n// ## HOW L2 JOINS TO THE ROWS TODAY — read this before assuming it works like L1\n//\n// L1 DISPATCHES from its array: `runner.l1LocationBlock` takes the first matching row and switches on\n// its `blockId`, so deleting a row deletes a block. L2 does NOT, and pretending otherwise would be the\n// drift this table exists to remove. The four L2 guard classes each own their own ladder, and those\n// ladders diverge on purpose (guards/L2-branch-state.md, \"Deliberate divergence\": the two Bash guards\n// differ in polarity, quantifier and empty-command handling all at once, so no single parameterised\n// function serves both). Unifying them is where a wrong edit turns an allow into a session-wedging\n// block, so it is deliberately not attempted here.\n//\n// What L2 does instead is a REASON→ROW join. Every exit of every L2 guard already carries a stable\n// reason string into the decision log; `L2_ROW_FOR_REASON` maps each of those to the row it is an\n// instance of, the guards stamp that number as `row=`, and l2-matrix.spec.ts asserts the map is\n// EXHAUSTIVE against the guard sources — a new reason with no row fails the build. So `row=8` in\n// `.webpieces/logs/L2-decisions` opens guards/L2-branch-state.md at row 8 and reads the state, the cure\n// and the tools that row covers, exactly as `row=5` already does for L1.\n//\n// The rows the guards cannot yet honour are named in the doc's \"Not done\" section rather than quietly\n// rendered as if they were live. That section is generated from NOT_DONE below, so it cannot rot.\n//\n// This module is deliberately import-free at runtime, so `pnpm guards:generate` can load it without the\n// package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\nimport { L2_ALLOW, L2_BLOCK, L2_EXEMPT, L2_FAIL_OPEN, L2_FAIL_OPEN_ROW, L2Row, L2UseCase, NO_ROW_EXIT } from './l2-row';\n\nexport {\n L2Action, L2ActionKind, L2Tool,\n L2_ALLOW, L2_BLOCK, L2_EXEMPT, L2_FAIL_OPEN, L2_FAIL_OPEN_ROW, L2Row, L2UseCase, NO_ROW_EXIT,\n} from './l2-row';\n\n/**\n * THE THIRTEEN L2 ROWS, in first-match-wins order.\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 marker-file\n * scan, row 5 is one `git rev-parse`. Row 11 is the cache divider. Rows 6-10 all read the cache.\n *\n * THE ORDER OF ROW 5 IS THE MOST LOAD-BEARING THING IN THIS TABLE. Put \"on main\" BELOW the divider and\n * WRITES on `main` are permitted for the whole first call of every session — and permanently in a\n * multi-worktree repo, where another tree may hold the cache lock indefinitely.\n *\n * `B` AND `E` PART COMPANY ON `main`, and rows 5/6/7 are where. A WRITE on `main` is wrong at any\n * freshness — the work lands somewhere unreviewable and unrevertable — so row 5 is `E` only, judged on\n * the branch alone, above the divider. A READ or a BUILD on a CURRENT `main` is harmless, and blocking\n * it strands the agent right after `pnpm wp-sync-main` put it there; so `B` joins `R` on the\n * FRESHNESS-gated pair below the divider (row 6 behind → block, row 7 current → allow), where \"cannot\n * tell\" fails open at row 11 by construction. `B` and `R` still differ in SHAPE inside row 6: a Read\n * names one file and is judged precisely, a Bash command is opaque and gets default-deny plus row 4.\n */\nexport const L2_ROWS: readonly L2Row[] = [\n new L2Row(1, ['B', 'R', 'E'], 'on the **global allowlist** (inert command, or a universal cure such as reading/editing `webpieces.config.json`)', L2_ALLOW, '—', [\n new L2UseCase(1,\n 'You are blocked by some other L2 row, and need to turn the policy off to get anything done',\n 'any state — this row is ahead of every block',\n 'ALLOW: reading and editing `webpieces.config.json` is never blocked, so the mode-OFF cure is always reachable',\n 'Edit `webpieces.config.json` → `hookGuards` → `branch-state-guard` → `\"mode\": \"OFF\"`',\n 'webpieces-config-read (escape hatch)'),\n new L2UseCase(2,\n 'A Write to `webpieces.config.json` while on `main`, which row 5 would otherwise block',\n 'on `main`, editing the one file that can disable the guard',\n 'ALLOW: the hook adapter bypasses feature-branch-guard for this path before any guard runs',\n 'None needed — the edit proceeds',\n 'config-bypass (feature-branch-guard skipped)'),\n ]),\n new L2Row(2, ['B'], 'bare `git checkout main`, with no `git pull` chained into the same command', L2_BLOCK, '`pnpm wp-sync-main`', [\n new L2UseCase(3,\n '`git checkout main` after a merge, to start the next piece of work',\n 'about to land on whatever local `main` you last had — 157 commits behind, in the incident',\n 'BLOCK: decided from command TEXT alone, before the checkout, because the only `main` this could measure is the one it is about to leave',\n '`pnpm wp-sync-main` — checkout, pull, reap dead branches/worktrees, sweep orphan directories, in one command (hand-rolled, the pull must be in the SAME command as the checkout)',\n 'bare checkout of main ('),\n new L2UseCase(4,\n 'The same command inside a linked worktree, where `git checkout main` fatals anyway',\n 'linked worktree — `main` is already checked out in the primary clone',\n 'BLOCK, and the message prints the worktree form rather than a cure git would refuse',\n '`git fetch origin main`, then work off `origin/main`',\n 'bare checkout of main ('),\n ]),\n new L2Row(3, ['B', 'R', 'E'], '**merge in progress** — L4 owns this state', L2_EXEMPT, 'finish the merge: `pnpm wp-finish-upsert-pr`', [\n new L2UseCase(5,\n 'Reading and editing conflicted files during a 3-point merge, on a branch row 9 would block',\n 'merge markers on disk — `pnpm wp-start-update` has run and not finished',\n 'EXEMPT: everything is permitted, which is exactly what lets row 9 be strict',\n 'Resolve the conflicts, then `pnpm wp-finish-upsert-pr`',\n NO_ROW_EXIT),\n ]),\n new L2Row(4, ['B'], 'on the **skip list** — it gets you OUT, or tells you where you are', L2_ALLOW, '—', [\n new L2UseCase(6,\n '`git status` / `gh pr view` while blocked, to work out where you are',\n 'any state — orientation is never \"working here\"',\n 'ALLOW: metadata tells you where you are without putting stale file CONTENT in context',\n 'None needed',\n 'not-a-content-read (cure/build/metadata)'),\n new L2UseCase(7,\n '`git stash` when `git checkout -b <new> origin/main` refuses because `origin/main` touched the same files you edited',\n 'on a stale `main` or a merged branch, dirty tree, with an overlapping upstream change',\n 'ALLOW: the cure for the row that blocked you must itself never be blocked — and this is the residual step that makes rows 6 and 8 safe to block on a dirty tree',\n 'None needed — then re-run the checkout and `git stash pop`',\n 'not-a-content-read (cure/build/metadata)'),\n new L2UseCase(28,\n '`gh pr close 123`, `gh pr comment`, `gh api …` or a `curl` while parked on a stale `main` or a merged branch',\n 'blocked state, running something that touches GitHub or a URL and nothing in this tree',\n 'ALLOW: the skip list asks one question — does this read or write repo CONTENT? `gh` talks to GitHub and `curl`/`wget` talk to a network, so the branch state has nothing to say about them. The forms that write a local file (`gh repo clone`, `gh pr checkout`, `curl -o`, any `> file`) are excluded, and `gh pr create`/`merge` remain governed by their own guards',\n 'None needed',\n 'not-a-content-read (cure/build/metadata)'),\n new L2UseCase(8,\n '`pnpm wp-start-upsert-pr` on a branch whose fork point is broken',\n 'row 9 state, running the tool row 9 prescribes',\n 'ALLOW: every `wp-*` bin is on the skip list, so no row can block its own remedy',\n 'None needed',\n 'merged-branch recovery/inspection (allowlisted)'),\n ]),\n new L2Row(5, ['E'], 'on `main`', L2_BLOCK, '`git checkout -b <new> origin/main`', [\n new L2UseCase(9,\n 'An Edit or Write to any tracked file while `git rev-parse --abbrev-ref HEAD` says `main`',\n 'on `main`, any freshness',\n 'BLOCK: decided by one `git rev-parse`, with NO cache read, so it fires on the first tool call of the session',\n '`git checkout -b <new> origin/main` — uncommitted work comes with you',\n 'on-main'),\n new L2UseCase(25,\n 'The FIRST edit of a session, on `main`, before any cache exists',\n 'on `main`, cache absent — row 11 would fail open',\n 'BLOCK anyway: row 5 is ABOVE the cache divider and reads only `git rev-parse`, so it is armed on call #1. This is why the row is `E` only and must never be gated on the cache',\n '`git checkout -b <new> origin/main`',\n 'on-main'),\n ]),\n new L2Row(L2_FAIL_OPEN_ROW, ['B', 'R', 'E'], '**the state could not be established** — branch undeterminable, no cache yet, the cache holds another branch, `origin/main` unknown, or the forge unreachable', L2_FAIL_OPEN, '— (nothing to fix; the refresher populates the cache for the next call)', [\n new L2UseCase(11,\n 'The very first tool call of a session is allowed even on a badly stale `main`',\n 'no cache — the refresher is fire-and-forget and populates it for the NEXT call',\n 'ALLOW (fail-open), logged as `ALLOW_FAIL_OPEN` so abstentions stay countable',\n 'None — the second call is judged normally',\n 'no-sync-cache'),\n new L2UseCase(12,\n 'Guards quietly stand down on a plane, or when `gh` is unauthenticated or rate-limited',\n 'the forge could not be asked whether the PR is merged',\n 'ALLOW (fail-open) logged as `no-forge` — distinct from \"asked, and it is not merged\", which used to look identical in the trail',\n 'None — restore network/`gh auth` to re-arm the merged-branch policy',\n 'no-forge'),\n new L2UseCase(27,\n 'A build, a `cat` or a `curl` on `main`, on the first Bash call of a session',\n 'on `main`, cache absent — so whether `main` is behind is UNKNOWN',\n 'ALLOW (fail-open), logged `ALLOW_FAIL_OPEN`. `B` on `main` is judged by rows 6/7 and therefore lands here when the cache cannot answer; the WRITE half is not, which is why row 5 sits above this divider',\n 'None — the second call is judged normally',\n 'no-sync-cache'),\n new L2UseCase(14,\n 'Mid-rebase, every guard abstains',\n 'detached HEAD — there is no branch name to judge',\n 'ALLOW (fail-open), logged LOUDLY when the branch is unresolvable rather than merely detached',\n 'None — finish or abort the rebase',\n 'branch-undeterminable'),\n ]),\n // ROWS 12/13 sit ABOVE row 6 because they are judged inside its state: local `main` is established\n // BEHIND, and the only remaining question is whether the command already carries its own cure. They\n // are numbered 12/13 rather than slotted in as 6a/6b for the reason row 11 is numbered 11 — row\n // numbers are logged as `row=` and cited here, so renumbering re-points every existing reference.\n new L2Row(12, ['B'], 'on `main`, behind `origin/main`, and the command STARTS with a refresh-main cure joined to the work by `&&`', L2_ALLOW, '—', [\n new L2UseCase(29,\n '`git fetch --prune origin main -q && git pull --ff-only origin main 2>&1 | tail -1 && sed -n \\'30,75p\\' src/app.ts` — the agent cures and reads in one call',\n 'on `main`, behind `origin/main`, cure first, `&&` between',\n 'ALLOW: `&&` short-circuits, so the `sed` never runs if the pull fails — the guard was refusing a safety property the shell already enforces. Measured fleet-wide as `cure_bundled_and`, and filed as a TOOLING defect, not an agent one',\n 'None needed',\n 'cure-prefixed, && short-circuits the work'),\n ]),\n new L2Row(13, ['B'], 'on `main`, behind `origin/main`, and the cure is joined to the work by `;` (or `||`, `&`, a newline) — the work runs even if the cure fails', L2_BLOCK, '`pnpm wp-sync-main && <your command>`', [\n new L2UseCase(30,\n '`pnpm wp-sync-main >/dev/null 2>&1; git log --oneline -1; sed -n \\'598,612p\\' eslint.config.mjs` — and the agent then quotes an eslint rule out of a file 15 commits stale',\n 'on `main`, behind `origin/main`, cure first, `;` between',\n 'BLOCK: `;` discards the cure\\'s exit code, so a conflict, a dirty tree or no network leaves the `sed` reading still-stale content — and 7 of the 9 observed cases also silenced the cure with `>/dev/null 2>&1`, so the failure was invisible too. The two-step is safer because the NEXT tool call re-computes `localMain` against `originMain`, so a failed pull re-blocks; an allowed `;` compound never gets that second look',\n 'Swap the `;` for `&&` — `pnpm wp-sync-main && <your command>` — or run the cure alone and re-issue the command in the next call',\n 'cure-prefixed, work runs anyway'),\n ]),\n new L2Row(6, ['B', 'R'], 'on `main`, farther behind `origin/main` than `maxCommitsBehind`', L2_BLOCK, '`pnpm wp-sync-main`, or `git checkout -b <new> origin/main`', [\n new L2UseCase(13,\n 'The Read tool refuses a file on a stale `main` while you have UNCOMMITTED edits',\n 'on `main`, beyond `maxCommitsBehind`, dirty tree',\n 'BLOCK. This used to fail open, on the argument that the prescribed `git pull` is not a clean fast-forward when the tree is dirty. That was true of the MESSAGE, not the row: the cure cell always offered a second form, and it works dirty',\n '`git checkout -b <new> origin/main` — uncommitted changes come with you onto the new branch. If git refuses because `origin/main` touched the same files, `git stash` first (never blocked), then retry, then `git stash pop`',\n 'on-stale-main'),\n new L2UseCase(15,\n 'The Read tool refuses a file that exists, on a `main` 18 commits behind',\n 'on `main`, beyond `maxCommitsBehind`, clean tree',\n 'BLOCK: judged by live ancestry (`git merge-base --is-ancestor`), not hash equality, so a pull takes effect instantly',\n '`pnpm wp-sync-main`, or `git checkout -b <new> origin/main`',\n 'on-stale-main'),\n new L2UseCase(16,\n 'Read is blocked, so the session reaches for `cat`, `grep` and `ls` instead — and describes a CI workflow set missing a whole workflow that existed upstream',\n 'the SIDE DOOR: same tree, same staleness, different tool',\n 'BLOCK: `B` is judged here beside `R`, so closing the Read tool no longer opens a shell-shaped hole. The log used to read \"read-stale-guard handled\", which is worse than no guard — it looks covered',\n '`git checkout -b <new> origin/main`',\n 'on-stale-main'),\n new L2UseCase(10,\n 'A Bash command that WRITES tracked files as a side effect — `npx expo install`, a formatter, codegen, `sed -i`, a `>` redirect',\n 'on a `main` known to be beyond `maxCommitsBehind`, and the write is incidental to a command whose stated purpose is something else',\n 'BLOCK: inside this row `B` is default-DENY plus row 4\\'s skip list, never a blocklist of readers — a command nobody thought to enumerate is caught by not being on the list, which is the only shape that could have caught this one',\n '`git checkout -b <new> origin/main` BEFORE running anything that may write',\n 'on-stale-main'),\n ]),\n new L2Row(7, ['B', 'R'], 'on `main`, current or within `maxCommitsBehind`', L2_ALLOW, '—', [\n new L2UseCase(17,\n 'Reading files on a `main` you just pulled',\n 'on `main`, and `origin/main` is an ancestor of HEAD',\n 'ALLOW: ancestry, not hash equality, so the allow arrives the instant the pull lands rather than when the detached refresher next runs',\n 'None needed',\n 'local-main-contains-origin (up to date)'),\n new L2UseCase(24,\n '`curl`, `gh pr close` or a test run, immediately after `pnpm wp-sync-main` landed you on a perfectly current `main`',\n 'on `main`, current — no staleness anywhere',\n 'ALLOW. This used to BLOCK, from the branch alone: the tool the repo prescribes put the agent here, and the guard whose name says STALE then refused everything off a narrow allowlist for a reason that had nothing to do with staleness. WRITES here are still blocked, by row 5 — that hazard is real at any freshness',\n 'None needed',\n 'local-main-contains-origin (up to date)'),\n new L2UseCase(31,\n 'Reading or running Bash while local `main` is five commits behind and the configured maximum is five',\n 'on `main`, cached `commitsBehind` is at or below `maxCommitsBehind`',\n 'ALLOW: the detached refresher computed the distance; the guard hot path only reads the cache',\n 'None needed',\n 'within-max-commits-behind'),\n ]),\n new L2Row(8, ['B', 'R', 'E'], 'on a branch whose PR is **already merged**', L2_BLOCK, '`git fetch origin main && git checkout -b <new> origin/main`', [\n new L2UseCase(18,\n 'You keep working on the branch after its PR merged, and the next PR reopens code review already landed',\n 'branch whose PR is merged — `merged` is monotonic, so the cached flag is trusted with no TTL',\n 'BLOCK across all three tools',\n '`git fetch origin main && git checkout -b <new> origin/main`',\n 'already-merged PR#'),\n new L2UseCase(26,\n 'You have uncommitted edits on a branch whose PR just merged',\n 'merged branch, dirty tree',\n 'BLOCK. This used to fail open too, and that valve never had an argument behind it — row 8\\'s cure carries uncommitted work onto the fresh branch, so nothing was ever trapped. It was drift from the documented design, which `read-stale-guard`\\'s own class comment still described correctly',\n '`git fetch origin main && git checkout -b <new> origin/main` — your edits come with you',\n 'already-merged PR#'),\n new L2UseCase(19,\n 'A shell-only session sails through on a merged branch',\n 'merged branch, Bash only — both FILE guards are file-scoped, so Bash reached neither',\n 'BLOCK: `merged-branch-bash-guard` exists because `branchAlreadyMerged` was being computed and logged on that very path, then thrown away',\n '`git fetch origin main && git checkout -b <new> origin/main`',\n 'already-merged PR#'),\n ]),\n new L2Row(9, ['B', 'R', 'E'], 'no fork point with `origin/main`, or `origin/main` moved and collided with your files', L2_BLOCK, '`pnpm wp-start-update`, or `pnpm wp-start-upsert-pr` when a PR is open', [\n new L2UseCase(20,\n 'Your branch and `origin/main` share no merge base — usually a branch cut from a squashed-away tip',\n 'no fork point',\n 'BLOCK: nothing built on this branch can be reasoned about relative to main',\n '`pnpm wp-start-update`, or `pnpm wp-start-upsert-pr` when a PR is open',\n 'no-fork-point'),\n new L2UseCase(21,\n '`origin/main` moved and changed the same files you edited',\n 'main-moved collision',\n 'BLOCK — and row 3 then exempts everything once the merge starts, which is what makes this safe',\n '`pnpm wp-start-update`, resolve, `pnpm wp-finish-upsert-pr`',\n 'main-moved-conflict'),\n ]),\n new L2Row(10, ['B', 'R', 'E'], 'healthy feature branch', L2_ALLOW, '—', [\n new L2UseCase(22,\n 'Ordinary work on a branch cut from a current `origin/main`',\n 'healthy feature branch',\n 'ALLOW — the state every other row exists to push you back into',\n 'None needed',\n 'clean-feature-branch'),\n new L2UseCase(23,\n '`stale-main-bash-guard` sees a feature branch and hands off',\n 'not on `main` — state B belongs to `merged-branch-bash-guard`',\n 'ALLOW: the same verdict about the same tree, logged by the guard that is not responsible for it',\n 'None needed',\n 'not-on-main (state B is another guard)'),\n ]),\n];\n\n/**\n * Every use case on every row, in row order, for the doc and for the exhaustiveness specs.\n *\n * Numbering is GLOBAL and is identity, exactly as the row numbers are: a use case is cited by number in\n * review and in the doc, so add new ones at the END of the highest number rather than renumbering to\n * keep a row's block contiguous.\n */\n// webpieces-disable no-function-outside-class -- pure accessor over L2_ROWS above, in this data module\nexport function allL2UseCases(): readonly L2UseCase[] {\n return L2_ROWS.flatMap((row: L2Row): readonly L2UseCase[] => row.useCases);\n}\n\n/**\n * REASON → ROW. The join between what a guard actually logged and the row it is an instance of.\n *\n * Keys are the exact `reason` strings the four L2 guards pass to their decision log. Two of them are\n * PREFIXES because the guard interpolates a PR number or a matched segment into the reason\n * (`already-merged PR#123`); those are matched by `l2RowForReason` on prefix, which is why they end in\n * a space or a `(`.\n *\n * l2-matrix.spec.ts reads the four guard sources and asserts every reason literal in them resolves\n * here, so a new exit with no row fails the build rather than logging `row=-` forever.\n */\nconst EXACT_REASON_ROWS: Record<string, number> = {\n // Row 1 — the universal cure that must stay reachable from inside any block.\n 'webpieces-config-read (escape hatch)': 1,\n // Row 2 — the preventive half, decided from command TEXT before any cache is read.\n // (prefix, see PREFIX_REASON_ROWS)\n // Row 4 — the skip list, in its two live spellings.\n 'merged-branch recovery/inspection (allowlisted)': 4,\n 'not-a-content-read (cure/build/metadata)': 4,\n // Row 5 — never WRITE on main, at any freshness. `E` only; the Bash half is rows 6/7.\n 'on-main': 5,\n // Row 6/7 — freshness, for `B` and `R` alike. Both guards log these two literals: read-stale-guard\n // for the Read tool, stale-main-bash-guard for Bash. Same cache, same ancestry test, one verdict.\n 'on-stale-main': 6,\n 'local-main-contains-origin (up to date)': 7,\n 'within-max-commits-behind': 7,\n // Rows 12/13 — composition, judged INSIDE row 6's state: the tree is established behind, and the\n // only remaining question is whether the command carries its own cure and with which operator.\n 'cure-prefixed, && short-circuits the work': 12,\n 'cure-prefixed, work runs anyway': 13,\n // Row 9 — the two unhealthy-fork states.\n 'no-fork-point': 9,\n 'main-moved-conflict': 9,\n // Row 10 — healthy, and the state-B guard's \"this is not my state\" hand-off, which is the same\n // verdict about the same tree.\n 'clean-feature-branch': 10,\n 'not-on-main (state B is another guard)': 10,\n // Row 11 — every \"could not establish\", including the two dirty-tree valves the code still opens\n // (see NOT_DONE) and the unreachable forge.\n 'branch-undeterminable': L2_FAIL_OPEN_ROW,\n 'commit-distance-unknown': L2_FAIL_OPEN_ROW,\n // The target tree HAS no branch name (mid-rebase / mid-bisect), so there is no key into the\n // branch-keyed cache — use case 14, which the row already describes. It used to arrive here as the\n // literal branch `HEAD`, miss in the cache and log `no-sync-cache`: the right verdict recorded under\n // a reason that names a different cause, and therefore uncountable.\n 'detached-head': L2_FAIL_OPEN_ROW,\n // The file being judged lives in a NESTED CLONE (`repositories/**`) — another repo's branch is not\n // this policy's to judge. The bash path calls the same state ALLOW_EXEMPT at L1; on the file path it\n // is an abstention, because nothing about the target tree's state was established.\n 'target-tree-foreign': L2_FAIL_OPEN_ROW,\n 'no-sync-cache': L2_FAIL_OPEN_ROW,\n 'stale-cross-branch-cache': L2_FAIL_OPEN_ROW,\n 'origin-main-unknown': L2_FAIL_OPEN_ROW,\n // `dirty-tree-on-main` and `dirty-merged-branch` used to live here. Both valves are deleted: rows\n // 6 and 8 now block on a dirty tree, because each row's cure carries uncommitted work with you.\n 'no-forge': L2_FAIL_OPEN_ROW,\n // The config-edit bypass logged by the hook adapter before any guard runs — row 1, same universal\n // cure as the config READ above.\n 'config-bypass (feature-branch-guard skipped)': 1,\n};\n\n/** Reasons the guards interpolate a value into. Matched by prefix, longest first. */\nconst PREFIX_REASON_ROWS: Record<string, number> = {\n 'already-merged PR#': 8,\n 'bare checkout of main (': 2,\n // `stale-main content read (` used to live here, mapping the Bash side of row 6. It is gone with\n // the guard exit that emitted it: on `main`, row 5 now blocks before any content-read scan runs,\n // so row 6 is what the table always said it was — the ROW-ONLY row.\n};\n\n/**\n * The row a logged reason belongs to, or null when nothing claims it.\n *\n * Null rather than a default row: a reason with no row is a HOLE in the table, and defaulting it to\n * \"fail-open\" would hide exactly the drift the exhaustiveness spec exists to catch. The guards render\n * null as `row=-`, so an unmapped reason is visible in the log too, not only in CI.\n */\n// webpieces-disable no-function-outside-class -- the matcher over the two tables above, beside them in this data module\nexport function l2RowForReason(reason: string): number | null {\n const exact = EXACT_REASON_ROWS[reason];\n if (exact !== undefined) return exact;\n for (const prefix of Object.keys(PREFIX_REASON_ROWS)) {\n if (reason.startsWith(prefix)) return PREFIX_REASON_ROWS[prefix];\n }\n return null;\n}\n\n/** Every reason string this table claims, for the exhaustiveness spec. */\n// webpieces-disable no-function-outside-class -- pure accessor over the two tables above\nexport function l2MappedReasons(): readonly string[] {\n return [...Object.keys(EXACT_REASON_ROWS), ...Object.keys(PREFIX_REASON_ROWS)];\n}\n\n/** One documented gap between a row and what the guards actually do today. Data-only. */\nexport class L2NotDone {\n constructor(readonly row: number, readonly gap: string, readonly why: string) {}\n}\n\n/**\n * WHERE THE TABLE AND THE CODE DISAGREE, stated rather than papered over.\n *\n * The L1 precedent is `## Not done — \\`o\\` is not exempt yet`: a row the runner cannot reach, named in\n * the generated doc with the reason it has not shipped. The same treatment applies here, and it is what\n * makes it safe to publish a table the guards do not yet dispatch from — a reader is told exactly which\n * rows describe intent rather than behaviour, and the log's `row=` stamps land on row 11 for every one\n * of these, so the trail never claims the strict row fired.\n */\nexport const NOT_DONE: readonly L2NotDone[] = [\n // EMPTY, and that is the goal state: every row in the table is a row the guards actually honour.\n //\n // It held three entries. Row 5's `B` half shipped and then MOVED: on `main`, a write is judged from\n // the branch alone (row 5, above the divider) while Bash is judged on freshness beside the Read tool\n // (rows 6/7), because a build on a CURRENT `main` harms nothing and denying it stranded agents on\n // the very `main` `pnpm wp-sync-main` had just handed them. Rows 6 and 8 held DIRTY-TREE\n // valves, and both are now closed — each of\n // those rows cures with `git checkout -b <new> origin/main`, which carries uncommitted changes onto\n // the new branch, so a dirty tree never trapped anybody. The row 6 entry claimed the dirty argument\n // \"has teeth\" there because its cure is `git pull`; that was a fact about the MESSAGE, which printed\n // only the pull, and the fix was to print both cures rather than to suppress the block.\n //\n // Keep this array. An empty \"Not done\" is a claim worth making explicitly — the doc says so in as\n // many words — and the next divergence between a row and its code belongs here, not in prose.\n];\n"]}
|
|
@@ -8,8 +8,8 @@ export declare class SyncLogEvent {
|
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
10
|
* Append one tab-separated line per refresher event to
|
|
11
|
-
* `.webpieces
|
|
12
|
-
* the workspace root holding `.webpieces
|
|
11
|
+
* `.webpieces/logs/async-refresh/<writer>.log` (see LogStream for the writer key). `root` is
|
|
12
|
+
* the workspace root holding `.webpieces`. Swallows all errors — logging must never block or fail
|
|
13
13
|
* the refresher (or the hook that spawns it).
|
|
14
14
|
*/
|
|
15
15
|
export declare function logSyncEvent(root: string, event: SyncLogEvent): void;
|
|
@@ -17,7 +17,7 @@ const log_stream_1 = require("./log-stream");
|
|
|
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
19
|
// mid-run (START with no FINISH), or threw. Writes to
|
|
20
|
-
// `.webpieces
|
|
20
|
+
// `.webpieces/logs/async-refresh/<writer>.log`, where <writer> is LogStream's
|
|
21
21
|
// `<sessionId>-<agentId|coordinator>-<hook>` key (see LOGS_STATE_DIR and ASYNC_REFRESH_STREAM).
|
|
22
22
|
//
|
|
23
23
|
// THE CHILD'S RAW STDIO GOES TO THIS SAME FILE. It used to have a `.stderr.log` sibling, which was
|
|
@@ -43,8 +43,8 @@ class SyncLogEvent {
|
|
|
43
43
|
exports.SyncLogEvent = SyncLogEvent;
|
|
44
44
|
/**
|
|
45
45
|
* Append one tab-separated line per refresher event to
|
|
46
|
-
* `.webpieces
|
|
47
|
-
* the workspace root holding `.webpieces
|
|
46
|
+
* `.webpieces/logs/async-refresh/<writer>.log` (see LogStream for the writer key). `root` is
|
|
47
|
+
* the workspace root holding `.webpieces`. Swallows all errors — logging must never block or fail
|
|
48
48
|
* the refresher (or the hook that spawns it).
|
|
49
49
|
*/
|
|
50
50
|
// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
|
|
@@ -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,
|
|
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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';\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"]}
|
|
@@ -15,7 +15,7 @@ export declare function refresherArgv(refresher: string, workspaceRoot: string,
|
|
|
15
15
|
* the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.
|
|
16
16
|
*
|
|
17
17
|
* Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to
|
|
18
|
-
* `.webpieces
|
|
18
|
+
* `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's
|
|
19
19
|
* stdout/stderr are redirected to a sibling file (not
|
|
20
20
|
* /dev/null) so a crash before the child's own logging is still captured. If the async-refresh stream shows
|
|
21
21
|
* SPAWN_ATTEMPT but never START, the detached child was killed before it ran.
|
|
@@ -35,7 +35,7 @@ function refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, identity) {
|
|
|
35
35
|
* the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.
|
|
36
36
|
*
|
|
37
37
|
* Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to
|
|
38
|
-
* `.webpieces
|
|
38
|
+
* `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's
|
|
39
39
|
* stdout/stderr are redirected to a sibling file (not
|
|
40
40
|
* /dev/null) so a crash before the child's own logging is still captured. If the async-refresh stream shows
|
|
41
41
|
* SPAWN_ATTEMPT but never START, the detached child was killed before it ran.
|
|
@@ -69,7 +69,7 @@ function triggerMainSyncRefresh(workspaceRoot, hangTimeoutMinutes) {
|
|
|
69
69
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
70
70
|
try {
|
|
71
71
|
const refresher = path.join(__dirname, 'sync-main.js');
|
|
72
|
-
// SPAWN_ATTEMPT first — this also creates .webpieces
|
|
72
|
+
// SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.
|
|
73
73
|
(0, main_sync_log_1.logSyncEvent)(workspaceRoot, new main_sync_log_1.SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher}`));
|
|
74
74
|
// Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash
|
|
75
75
|
// before the child's own logging — e.g. a module-load failure — is still captured.
|
|
@@ -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,
|
|
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"]}
|
|
@@ -13,7 +13,7 @@ const main_sync_refresh_1 = require("./main-sync-refresh");
|
|
|
13
13
|
// ---------------------------------------------------------------------------
|
|
14
14
|
// THE ONE `hangTimeoutMinutes`, and every caller that has to read it.
|
|
15
15
|
//
|
|
16
|
-
// There is ONE detached refresher writing ONE cache (.webpieces
|
|
16
|
+
// There is ONE detached refresher writing ONE cache (.webpieces/main-sync-status.json), so there is one
|
|
17
17
|
// knob: `hookGuards.branch-state-guard.hangTimeoutMinutes`, which tunes the stale-lock reclaim window.
|
|
18
18
|
//
|
|
19
19
|
// It used to be declared FOUR times — once per branch-state guard class — and read four times, and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main-sync-timeout.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-timeout.ts"],"names":[],"mappings":";;AAoCA,sCAGC;AAID,wDAGC;AAaD,8DAYC;AAID,oEAEC;AAYD,oDAKC;AA9FD,0DAAgF;AAChF,gDAAwD;AAExD,sEAA6E;AAE7E,iEAA6D;AAC7D,2DAA6D;AAG7D,8EAA8E;AAC9E,sEAAsE;AACtE,EAAE;AACF,
|
|
1
|
+
{"version":3,"file":"main-sync-timeout.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-timeout.ts"],"names":[],"mappings":";;AAoCA,sCAGC;AAID,wDAGC;AAaD,8DAYC;AAID,oEAEC;AAYD,oDAKC;AA9FD,0DAAgF;AAChF,gDAAwD;AAExD,sEAA6E;AAE7E,iEAA6D;AAC7D,2DAA6D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1B,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,oDAAoD;AACpD,kGAAkG;AAClG,SAAgB,4BAA4B;IACxC,iBAAiB,GAAG,IAAI,CAAC;AAC7B,CAAC;AAED;;;;;;;;GAQG;AACH,8IAA8I;AAC9I,SAAgB,oBAAoB,CAAC,KAAsB,EAAE,aAAqB,EAAE,kBAA0B;IAC1G,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAO,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,sBAAsB,CAAC,CAAC;IAClF,IAAI,KAAK,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QAC7B,IAAA,0CAAsB,EAAC,aAAa,EAAE,kBAAkB,CAAC,CAAC;IAC9D,CAAC;AACL,CAAC","sourcesContent":["import { loadAndValidate, WebpiecesRulesConfig } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../policy-keys';\nimport { BranchStateGuardConfig } from \"../configs/main-sync-guard-configs\";\nimport { DEFAULT_HANG_TIMEOUT_MINUTES } from '@webpieces/repo-workflow-core';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { triggerMainSyncRefresh } from './main-sync-refresh';\nimport type { Rule } from '@webpieces/hook-runtime';\n\n// ---------------------------------------------------------------------------\n// THE ONE `hangTimeoutMinutes`, and every caller that has to read it.\n//\n// There is ONE detached refresher writing ONE cache (.webpieces/main-sync-status.json), so there is one\n// knob: `hookGuards.branch-state-guard.hangTimeoutMinutes`, which tunes the stale-lock reclaim window.\n//\n// It used to be declared FOUR times — once per branch-state guard class — and read four times, and\n// three of those four values were structurally unable to take effect. Two things conspired:\n// `triggerMainSyncRefresh` latches at most one spawn per hook process, and two callers ran BEFORE any\n// guard's own call while passing the hardcoded default. So on the Bash path and the Read path (the two\n// hottest) the default always won the latch and the configured value never reached a spawn.\n//\n// Collapsing four declarations into one only fixes that if EVERY caller reads the one. This module is\n// where they do, which is also why it is a module rather than three helpers in runner.ts: the callers\n// live in two files (the runner and the hook adapter) and a knob honoured in one of them is the bug\n// again, one release later.\n// ---------------------------------------------------------------------------\n\n/**\n * The value on a branch-state ENTRY, or the default — for the four guard classes, which are handed\n * their own typed config and never see the whole file.\n *\n * The four used to spell this inline as `this.config.hangTimeoutMinutes ?? DEFAULT_HANG_TIMEOUT_MINUTES`,\n * which is a fourth copy of the resolution and exactly the shape that let the four DECLARATIONS drift\n * apart in the first place. One reader, one fallback.\n */\n// webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from\nexport function hangTimeoutOf(config: BranchStateGuardConfig): number {\n const configured = config.hangTimeoutMinutes;\n return typeof configured === 'number' ? configured : DEFAULT_HANG_TIMEOUT_MINUTES;\n}\n\n/** The configured value for a caller that has ALREADY loaded the whole config. */\n// webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from\nexport function branchStateHangTimeout(config: WebpiecesRulesConfig): number {\n const entry = config[BRANCH_STATE_GUARD_KEY] as BranchStateGuardConfig | undefined;\n return entry === undefined ? DEFAULT_HANG_TIMEOUT_MINUTES : hangTimeoutOf(entry);\n}\n\n// Memoized per PROCESS, and a hook process handles exactly one tool call — so the adapter's two call\n// sites cost at most one extra config parse between them, never one each.\nlet cachedHangTimeout: number | null = null;\n\n/**\n * The configured value for a caller that has NOT loaded the config — the hook adapter's two pre-rule\n * refresh triggers (the webpieces.config.json edit bypass, and the Read fast path).\n *\n * Fails back to the default on an unloadable config: warming a cache must never throw on the tool path.\n */\n// webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from\nexport function branchStateHangTimeoutFor(cwd: string): number {\n if (cachedHangTimeout !== null) return cachedHangTimeout;\n let value = DEFAULT_HANG_TIMEOUT_MINUTES;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a cache-warming knob must never throw on the tool path\n try {\n value = branchStateHangTimeout(loadAndValidate(cwd).rulesConfig);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n cachedHangTimeout = value;\n return value;\n}\n\n/** Test-only: clears the per-process memo above. */\n// webpieces-disable no-function-outside-class -- module-scope test hook beside the memo it clears\nexport function resetHangTimeoutCacheForTest(): void {\n cachedHangTimeout = null;\n}\n\n/**\n * Fire-and-forget the detached refresher when the branch-state policy is loaded and active, so the\n * cache stays fresh as the AI works. The guard rules themselves also trigger it; this covers the Bash\n * path so the cache is warm on every command.\n *\n * Keyed on `feature-branch-guard` — the rule NAME, not the config key. Any of the four branch-state\n * classes would do (they share one entry, so they are on or off together); this one is asked because it\n * is the class whose cache freshness matters on the very next Write.\n */\n// webpieces-disable no-function-outside-class -- module-scope refresh trigger, matching the shape of the runner helpers it was extracted from\nexport function maybeRefreshMainSync(rules: readonly Rule[], workspaceRoot: string, hangTimeoutMinutes: number): void {\n const guard = rules.find((r: Rule): boolean => r.name === 'feature-branch-guard');\n if (guard && guard.shouldRun()) {\n triggerMainSyncRefresh(workspaceRoot, hangTimeoutMinutes);\n }\n}\n"]}
|
|
@@ -43,8 +43,8 @@ const RULE_NAME_RE = /^\[([^\]]+)\] \(/gm;
|
|
|
43
43
|
function logRejection(toolKind, input, result, cwd) {
|
|
44
44
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
45
45
|
try {
|
|
46
|
-
// `.webpieces
|
|
47
|
-
// the AI is in a subdirectory never scatters a stray `<subdir>/.webpieces
|
|
46
|
+
// `.webpieces/` lives at the repo root, NOT the AI's cwd — resolve it so a hook fired while
|
|
47
|
+
// the AI is in a subdirectory never scatters a stray `<subdir>/.webpieces` tree.
|
|
48
48
|
const root = new rules_config_1.RepoRootFinder().resolveRepoRoot(cwd);
|
|
49
49
|
const now = new Date();
|
|
50
50
|
const timestamp = now.toISOString();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rejection-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/rejection-log.ts"],"names":[],"mappings":";;AA2CA,oCAoDC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AC;QAC/B,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;IAEO,WAAW,CAAC,MAAc;QAC9B,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IAED,kGAAkG;IAClG,oCAAoC;IAC5B,UAAU,CAAC,MAAc;QAC7B,8DAA8D;QAC9D,IAAI,CAAC;YACD,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;QACf,CAAC;IACL,CAAC;IAED,yFAAyF;IACjF,cAAc,CAAC,MAAc;QACjC,8DAA8D;QAC9D,IAAI,CAAC;YACD,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QACzB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;QACf,CAAC;IACL,CAAC;CACJ;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { RepoRootFinder } from '@webpieces/rules-config';\nimport { REJECTIONS_STREAM } from './log-streams';\n\nimport type { ToolKind, NormalizedToolInput, BlockedResult } from '@webpieces/hook-runtime';\nimport { logStream } from './log-stream';\nimport { aiTypeContext } from './ai-type-context';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * The rejection index and its detail files, BOTH inside the `rejections/` stream directory, both\n * named by the same writer key:\n *\n * logs/rejections/<sid>-<agent>-<hook>.log ← the index (one line per block)\n * logs/rejections/<sid>-<agent>-<hook>/ ← its detail dir, SAME key\n * writeInfo-<epochMs>.md\n *\n * The detail files used to be `hooks/<YYYY-MM-DD>/writeInfo-<epochMs>.md` — a directory keyed only by\n * the DATE, shared by every writer in the tree, written with a raw `writeFileSync`. Two agents blocked\n * in the same millisecond produced the same path and one silently overwrote the other's evidence. The\n * comment that licensed it claimed a per-worktree log has exactly one writer; LogStream's class\n * comment is the measurement that disproves it (parallel PreToolUse hooks, non-isolated subagents and\n * multiple Claude Code windows all share a tree). Naming the directory after the LOG THAT POINTS AT IT\n * gives it the same one-owner-by-construction property the log itself has, and makes the pointer\n * readable: the index line, the directory and the file are one name.\n *\n * RETENTION is therefore filename-based, not directory-date-based: there is no date level left, so\n * `DetailPruner` parses `<epochMs>` out of each `writeInfo-*.md` (no `stat` call) and removes any\n * stream directory left empty. Every delete is `force: true` and failures are swallowed, so concurrent\n * agents racing the same week-old files is harmless.\n */\nconst DETAIL_PREFIX = 'writeInfo-';\nconst DETAIL_SUFFIX = '.md';\nconst DETAIL_RE = /^writeInfo-(\\d+)\\.md$/;\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded\nconst MAX_AGE_DAYS = 7;\n\nconst RULE_NAME_RE = /^\\[([^\\]]+)\\] \\(/gm;\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 logRejection(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n result: BlockedResult,\n cwd: string,\n): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // `.webpieces-logs/` lives at the repo root, NOT the AI's cwd — resolve it so a hook fired while\n // the AI is in a subdirectory never scatters a stray `<subdir>/.webpieces-logs` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const now = new Date();\n const timestamp = now.toISOString();\n const epochMs = String(now.getTime());\n\n // LOCAL scope — a rejection is this worktree's event. WHICH writer's event is answered by the\n // stream prefix, on the index AND on its detail directory, so neither can collide.\n const logsDir = dotWebpieces.logsFile(root, REJECTIONS_STREAM);\n // The detail directory is the writer key with NO extension, sitting beside the `.log` that\n // indexes it — so index and details share one owner, one level down inside the stream dir.\n const detailDirName = logStream.writerFile('');\n const detailDir = path.join(logsDir, detailDirName);\n fs.mkdirSync(detailDir, { recursive: true });\n\n const relativePath = computeRelativePath(input.filePath, root);\n const ruleNames = extractRuleNames(result.report);\n const detailFileName = `${DETAIL_PREFIX}${epochMs}${DETAIL_SUFFIX}`;\n // Relative to `rejections/` — the index's own directory — so the pointer resolves from where\n // the reader found the line, and reads as the log's own name plus a file.\n const detailRelPath = `${detailDirName}/${detailFileName}`;\n\n const detail = buildDetailContent(timestamp, toolKind, relativePath, ruleNames, result.report, input);\n fs.writeFileSync(path.join(detailDir, detailFileName), detail);\n\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n // APPEND-ONLY, and `fault=` is spelled exactly as the L0 sh log spells it. A fault-S storm\n // previously landed here as a couple of lines attributed to whatever rule the report happened\n // to cite, with nothing anywhere identifying L0 as the cause. (WHO made the call is answered by\n // the filename, which logStream prefixes with session/agent/hook — not by a column here.)\n // `ai=` joins the same append-only tail as `fault=`, in the same vocabulary the L0 sh shim and\n // both decision streams use — so `grep ai=codex` spans all five streams. A row from a release\n // that predates the field carries no `ai=` and reads as `unknown`.\n const logLine = `[${timestamp}]\\t${toolKind}\\t${relativePath}\\t[${ruleNames.join(',')}]\\t${detailRelPath}\\tfault=${result.fault}\\tai=${aiTypeContext.forLog()}\\n`;\n fs.appendFileSync(logPath, logLine);\n\n detailPruner.prune(logsDir, MAX_AGE_DAYS);\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\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 computeRelativePath(filePath: string, cwd: string): string {\n if (filePath.startsWith(cwd)) {\n const rel = filePath.slice(cwd.length);\n if (rel.startsWith('/')) return rel.slice(1);\n return rel;\n }\n return filePath;\n}\n\n/**\n * The rule names a block report cites — every `[<rule-name>] (` header it opens with. Exported because\n * two audit streams need the same answer from the same regex: this file's rejection index, and the\n * `rule=` field the `calls/` stream now carries (see InvocationLog.finish). Two scrapers would be\n * two answers to one question.\n */\n// webpieces-disable no-function-outside-class -- pure regex scraper beside this module's other module-scope helpers; exported so the invocation log and the rejection index scrape rule names with the SAME code.\nexport function extractRuleNames(report: string): string[] {\n const names: string[] = [];\n let match = RULE_NAME_RE.exec(report);\n while (match !== null) {\n names.push(match[1]);\n match = RULE_NAME_RE.exec(report);\n }\n RULE_NAME_RE.lastIndex = 0;\n return names;\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 buildDetailContent(\n timestamp: string,\n toolKind: ToolKind,\n relativePath: string,\n ruleNames: string[],\n report: string,\n input: NormalizedToolInput,\n): string {\n const lines: string[] = [];\n lines.push('# Hook Rejection Detail');\n lines.push('');\n lines.push(`- **Timestamp:** ${timestamp}`);\n lines.push(`- **Tool:** ${toolKind}`);\n lines.push(`- **File:** ${relativePath}`);\n lines.push(`- **Rules violated:** ${ruleNames.join(', ')}`);\n lines.push('');\n lines.push('## Report');\n lines.push('');\n lines.push('```');\n lines.push(report.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('## Content Being Written');\n lines.push('');\n\n if (toolKind === 'Write') {\n const content = input.edits.length > 0 ? input.edits[0].newString : '';\n lines.push('```typescript');\n lines.push(content.trimEnd());\n lines.push('```');\n } else {\n for (let i = 0; i < input.edits.length; i += 1) {\n const edit = input.edits[i];\n lines.push(`### Edit ${String(i + 1)} of ${String(input.edits.length)}`);\n lines.push('');\n lines.push('**old_string:**');\n lines.push('```typescript');\n lines.push(edit.oldString.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('**new_string:**');\n lines.push('```typescript');\n lines.push(edit.newString.trimEnd());\n lines.push('```');\n lines.push('');\n }\n }\n\n return lines.join('\\n') + '\\n';\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 err;\n }\n}\n\n/**\n * The 7-day sweep over rejection DETAIL files.\n *\n * A class rather than four module-scope helpers because the four belong together: `prune` is the\n * policy and the other three are the swallow-everything filesystem calls it is built from, none of\n * which means anything on its own.\n *\n * The age comes out of the FILENAME, not out of `stat` — the epoch millis are already in the name, so\n * a sweep costs one `readdir` per stream directory and no syscall per file. (The old scheme could\n * delete a whole `hooks/<YYYY-MM-DD>/` in one recursive `rm` because the date WAS the directory; the\n * directory is now the WRITER, which never expires, so expiry moved down one level.)\n *\n * IDEMPOTENT AND RACE-TOLERANT ON PURPOSE. Several agents sweep the same directory concurrently, so\n * two processes will regularly try to unlink the same week-old file and to rmdir the same emptied\n * directory. `force: true` makes an already-gone target a no-op, an rmdir of a still-populated (or\n * already-removed) directory fails harmlessly, and every error is swallowed: the loser of the race\n * does nothing and reports nothing, which is the correct outcome — the file is gone either way.\n */\nclass DetailPruner {\n prune(logsDir: string, maxAgeDays: number): void {\n const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;\n for (const dirName of this.readdirOrEmpty(logsDir)) {\n const dir = path.join(logsDir, dirName);\n if (!this.isDirectory(dir)) continue;\n const names = this.readdirOrEmpty(dir);\n let removed = 0;\n for (const name of names) {\n const match = DETAIL_RE.exec(name);\n if (match === null) continue;\n if (Number(match[1]) >= cutoff) continue;\n this.removeFile(path.join(dir, name));\n removed += 1;\n }\n // Only a directory we just emptied is a candidate, and the removal is a NON-recursive rmdir\n // on purpose: it fails harmlessly if a concurrent writer dropped a fresh detail in between,\n // so the sweep can never take a file it did not decide was expired.\n if (removed > 0 && removed === names.length) this.removeEmptyDir(dir);\n }\n }\n\n private readdirOrEmpty(dir: string): string[] {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n private isDirectory(target: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.statSync(target).isDirectory();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n // `force: true` is what makes the concurrent sweep harmless: a file another agent already deleted\n // is a no-op rather than an ENOENT.\n private removeFile(target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(target, { force: true });\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // NON-recursive by design — see prune(). This must refuse a directory that is not empty.\n private removeEmptyDir(target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmdirSync(target);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n}\n\nconst detailPruner = new DetailPruner();\n"]}
|
|
1
|
+
{"version":3,"file":"rejection-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/rejection-log.ts"],"names":[],"mappings":";;AA2CA,oCAoDC;AAmBD,4CASC;;AA3HD,+CAAyB;AACzB,mDAA6B;AAE7B,8DAAyD;AACzD,0DAAyD;AACzD,+CAAkD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C,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;IAEO,WAAW,CAAC,MAAc;QAC9B,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IAED,kGAAkG;IAClG,oCAAoC;IAC5B,UAAU,CAAC,MAAc;QAC7B,8DAA8D;QAC9D,IAAI,CAAC;YACD,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;QACf,CAAC;IACL,CAAC;IAED,yFAAyF;IACjF,cAAc,CAAC,MAAc;QACjC,8DAA8D;QAC9D,IAAI,CAAC;YACD,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QACzB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;QACf,CAAC;IACL,CAAC;CACJ;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { RepoRootFinder } from '@webpieces/rules-config';\nimport { REJECTIONS_STREAM } from './log-streams';\n\nimport type { ToolKind, NormalizedToolInput, BlockedResult } from '@webpieces/hook-runtime';\nimport { logStream } from './log-stream';\nimport { aiTypeContext } from './ai-type-context';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * The rejection index and its detail files, BOTH inside the `rejections/` stream directory, both\n * named by the same writer key:\n *\n * logs/rejections/<sid>-<agent>-<hook>.log ← the index (one line per block)\n * logs/rejections/<sid>-<agent>-<hook>/ ← its detail dir, SAME key\n * writeInfo-<epochMs>.md\n *\n * The detail files used to be `hooks/<YYYY-MM-DD>/writeInfo-<epochMs>.md` — a directory keyed only by\n * the DATE, shared by every writer in the tree, written with a raw `writeFileSync`. Two agents blocked\n * in the same millisecond produced the same path and one silently overwrote the other's evidence. The\n * comment that licensed it claimed a per-worktree log has exactly one writer; LogStream's class\n * comment is the measurement that disproves it (parallel PreToolUse hooks, non-isolated subagents and\n * multiple Claude Code windows all share a tree). Naming the directory after the LOG THAT POINTS AT IT\n * gives it the same one-owner-by-construction property the log itself has, and makes the pointer\n * readable: the index line, the directory and the file are one name.\n *\n * RETENTION is therefore filename-based, not directory-date-based: there is no date level left, so\n * `DetailPruner` parses `<epochMs>` out of each `writeInfo-*.md` (no `stat` call) and removes any\n * stream directory left empty. Every delete is `force: true` and failures are swallowed, so concurrent\n * agents racing the same week-old files is harmless.\n */\nconst DETAIL_PREFIX = 'writeInfo-';\nconst DETAIL_SUFFIX = '.md';\nconst DETAIL_RE = /^writeInfo-(\\d+)\\.md$/;\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded\nconst MAX_AGE_DAYS = 7;\n\nconst RULE_NAME_RE = /^\\[([^\\]]+)\\] \\(/gm;\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 logRejection(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n result: BlockedResult,\n cwd: string,\n): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // `.webpieces/` lives at the repo root, NOT the AI's cwd — resolve it so a hook fired while\n // the AI is in a subdirectory never scatters a stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const now = new Date();\n const timestamp = now.toISOString();\n const epochMs = String(now.getTime());\n\n // LOCAL scope — a rejection is this worktree's event. WHICH writer's event is answered by the\n // stream prefix, on the index AND on its detail directory, so neither can collide.\n const logsDir = dotWebpieces.logsFile(root, REJECTIONS_STREAM);\n // The detail directory is the writer key with NO extension, sitting beside the `.log` that\n // indexes it — so index and details share one owner, one level down inside the stream dir.\n const detailDirName = logStream.writerFile('');\n const detailDir = path.join(logsDir, detailDirName);\n fs.mkdirSync(detailDir, { recursive: true });\n\n const relativePath = computeRelativePath(input.filePath, root);\n const ruleNames = extractRuleNames(result.report);\n const detailFileName = `${DETAIL_PREFIX}${epochMs}${DETAIL_SUFFIX}`;\n // Relative to `rejections/` — the index's own directory — so the pointer resolves from where\n // the reader found the line, and reads as the log's own name plus a file.\n const detailRelPath = `${detailDirName}/${detailFileName}`;\n\n const detail = buildDetailContent(timestamp, toolKind, relativePath, ruleNames, result.report, input);\n fs.writeFileSync(path.join(detailDir, detailFileName), detail);\n\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n // APPEND-ONLY, and `fault=` is spelled exactly as the L0 sh log spells it. A fault-S storm\n // previously landed here as a couple of lines attributed to whatever rule the report happened\n // to cite, with nothing anywhere identifying L0 as the cause. (WHO made the call is answered by\n // the filename, which logStream prefixes with session/agent/hook — not by a column here.)\n // `ai=` joins the same append-only tail as `fault=`, in the same vocabulary the L0 sh shim and\n // both decision streams use — so `grep ai=codex` spans all five streams. A row from a release\n // that predates the field carries no `ai=` and reads as `unknown`.\n const logLine = `[${timestamp}]\\t${toolKind}\\t${relativePath}\\t[${ruleNames.join(',')}]\\t${detailRelPath}\\tfault=${result.fault}\\tai=${aiTypeContext.forLog()}\\n`;\n fs.appendFileSync(logPath, logLine);\n\n detailPruner.prune(logsDir, MAX_AGE_DAYS);\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\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 computeRelativePath(filePath: string, cwd: string): string {\n if (filePath.startsWith(cwd)) {\n const rel = filePath.slice(cwd.length);\n if (rel.startsWith('/')) return rel.slice(1);\n return rel;\n }\n return filePath;\n}\n\n/**\n * The rule names a block report cites — every `[<rule-name>] (` header it opens with. Exported because\n * two audit streams need the same answer from the same regex: this file's rejection index, and the\n * `rule=` field the `calls/` stream now carries (see InvocationLog.finish). Two scrapers would be\n * two answers to one question.\n */\n// webpieces-disable no-function-outside-class -- pure regex scraper beside this module's other module-scope helpers; exported so the invocation log and the rejection index scrape rule names with the SAME code.\nexport function extractRuleNames(report: string): string[] {\n const names: string[] = [];\n let match = RULE_NAME_RE.exec(report);\n while (match !== null) {\n names.push(match[1]);\n match = RULE_NAME_RE.exec(report);\n }\n RULE_NAME_RE.lastIndex = 0;\n return names;\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 buildDetailContent(\n timestamp: string,\n toolKind: ToolKind,\n relativePath: string,\n ruleNames: string[],\n report: string,\n input: NormalizedToolInput,\n): string {\n const lines: string[] = [];\n lines.push('# Hook Rejection Detail');\n lines.push('');\n lines.push(`- **Timestamp:** ${timestamp}`);\n lines.push(`- **Tool:** ${toolKind}`);\n lines.push(`- **File:** ${relativePath}`);\n lines.push(`- **Rules violated:** ${ruleNames.join(', ')}`);\n lines.push('');\n lines.push('## Report');\n lines.push('');\n lines.push('```');\n lines.push(report.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('## Content Being Written');\n lines.push('');\n\n if (toolKind === 'Write') {\n const content = input.edits.length > 0 ? input.edits[0].newString : '';\n lines.push('```typescript');\n lines.push(content.trimEnd());\n lines.push('```');\n } else {\n for (let i = 0; i < input.edits.length; i += 1) {\n const edit = input.edits[i];\n lines.push(`### Edit ${String(i + 1)} of ${String(input.edits.length)}`);\n lines.push('');\n lines.push('**old_string:**');\n lines.push('```typescript');\n lines.push(edit.oldString.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('**new_string:**');\n lines.push('```typescript');\n lines.push(edit.newString.trimEnd());\n lines.push('```');\n lines.push('');\n }\n }\n\n return lines.join('\\n') + '\\n';\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 err;\n }\n}\n\n/**\n * The 7-day sweep over rejection DETAIL files.\n *\n * A class rather than four module-scope helpers because the four belong together: `prune` is the\n * policy and the other three are the swallow-everything filesystem calls it is built from, none of\n * which means anything on its own.\n *\n * The age comes out of the FILENAME, not out of `stat` — the epoch millis are already in the name, so\n * a sweep costs one `readdir` per stream directory and no syscall per file. (The old scheme could\n * delete a whole `hooks/<YYYY-MM-DD>/` in one recursive `rm` because the date WAS the directory; the\n * directory is now the WRITER, which never expires, so expiry moved down one level.)\n *\n * IDEMPOTENT AND RACE-TOLERANT ON PURPOSE. Several agents sweep the same directory concurrently, so\n * two processes will regularly try to unlink the same week-old file and to rmdir the same emptied\n * directory. `force: true` makes an already-gone target a no-op, an rmdir of a still-populated (or\n * already-removed) directory fails harmlessly, and every error is swallowed: the loser of the race\n * does nothing and reports nothing, which is the correct outcome — the file is gone either way.\n */\nclass DetailPruner {\n prune(logsDir: string, maxAgeDays: number): void {\n const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;\n for (const dirName of this.readdirOrEmpty(logsDir)) {\n const dir = path.join(logsDir, dirName);\n if (!this.isDirectory(dir)) continue;\n const names = this.readdirOrEmpty(dir);\n let removed = 0;\n for (const name of names) {\n const match = DETAIL_RE.exec(name);\n if (match === null) continue;\n if (Number(match[1]) >= cutoff) continue;\n this.removeFile(path.join(dir, name));\n removed += 1;\n }\n // Only a directory we just emptied is a candidate, and the removal is a NON-recursive rmdir\n // on purpose: it fails harmlessly if a concurrent writer dropped a fresh detail in between,\n // so the sweep can never take a file it did not decide was expired.\n if (removed > 0 && removed === names.length) this.removeEmptyDir(dir);\n }\n }\n\n private readdirOrEmpty(dir: string): string[] {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n private isDirectory(target: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.statSync(target).isDirectory();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n // `force: true` is what makes the concurrent sweep harmless: a file another agent already deleted\n // is a no-op rather than an ENOENT.\n private removeFile(target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(target, { force: true });\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // NON-recursive by design — see prune(). This must refuse a directory that is not empty.\n private removeEmptyDir(target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmdirSync(target);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n}\n\nconst detailPruner = new DetailPruner();\n"]}
|
|
@@ -149,11 +149,11 @@ class ContentReadScan {
|
|
|
149
149
|
return !relative.startsWith('..');
|
|
150
150
|
}
|
|
151
151
|
// Always-readable paths: webpieces.config.json is the mode-OFF escape hatch (never block the
|
|
152
|
-
// file that turns the guard off), and `.webpieces
|
|
152
|
+
// file that turns the guard off), and `.webpieces/` is the guards' own logs/caches — orientation
|
|
153
153
|
// data this guard writes itself, not source that upstream has moved past.
|
|
154
154
|
isEscapeHatchPath(relative) {
|
|
155
155
|
const normalized = relative.replace(/^\.\//, '');
|
|
156
|
-
return normalized === 'webpieces.config.json' || normalized.startsWith('.webpieces
|
|
156
|
+
return normalized === 'webpieces.config.json' || normalized.startsWith('.webpieces/');
|
|
157
157
|
}
|
|
158
158
|
// `/usr/bin/cat` and `./scripts/cat` both invoke a program named cat; match on the base name.
|
|
159
159
|
baseName(word) {
|