@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
|
@@ -14,7 +14,7 @@ export declare const DEFAULT_MAX_COMMITS_BEHIND = 5;
|
|
|
14
14
|
* Bash | stale-main-bash-guard | merged-branch-bash-guard
|
|
15
15
|
*
|
|
16
16
|
* Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so
|
|
17
|
-
* `grep rule=stale-main-bash-guard` over `.webpieces
|
|
17
|
+
* `grep rule=stale-main-bash-guard` over `.webpieces/logs/L2-decisions` keeps working. What merged is
|
|
18
18
|
* the SWITCH: all four read this one config entry (`AbstractRule.configKey`).
|
|
19
19
|
*
|
|
20
20
|
* ## Why one key and not four
|
|
@@ -17,7 +17,7 @@ exports.DEFAULT_MAX_COMMITS_BEHIND = 5;
|
|
|
17
17
|
* Bash | stale-main-bash-guard | merged-branch-bash-guard
|
|
18
18
|
*
|
|
19
19
|
* Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so
|
|
20
|
-
* `grep rule=stale-main-bash-guard` over `.webpieces
|
|
20
|
+
* `grep rule=stale-main-bash-guard` over `.webpieces/logs/L2-decisions` keeps working. What merged is
|
|
21
21
|
* the SWITCH: all four read this one config entry (`AbstractRule.configKey`).
|
|
22
22
|
*
|
|
23
23
|
* ## Why one key and not four
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main-sync-guard-configs.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/configs/main-sync-guard-configs.ts"],"names":[],"mappings":";;;AAAA,oDAA+F;AAC/F,oDAA+D;AAClD,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,sBAAuB,SAAQ,0BAAc;IAEtD,oGAAoG;IACpG,uEAAuE;IACvE,sBAAsB,CAAU;IAChC,oGAAoG;IACpG,wEAAwE;IACxE,kBAAkB,CAAU;IAC5B,6FAA6F;IAC7F,oFAAoF;IACpF,gBAAgB,CAAU;IAE1B,MAAM,CAAU,MAAM,GAAwC;QAC1D,IAAI,EAAE,IAAI,oBAAQ,CAAC,QAAQ,EAAE,wBAAY,CAAC;QAC1C,sBAAsB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACnD,kBAAkB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC/C,gBAAgB,EAAE,IAAI,oBAAQ,CAAC,QAAQ,CAAC;QACxC,GAAG,4BAAgB;KACtB,CAAC;;AAlBN,wDAmBC","sourcesContent":["import { FieldDef, SchemaShape, BaseRuleConfig, BASE_RULE_SCHEMA } from \"@webpieces/rules-sdk\";\nimport { OnOffMode, ON_OFF_MODES } from \"@webpieces/rules-sdk\";\nexport const DEFAULT_MAX_COMMITS_BEHIND = 5;\n\n/**\n * `branch-state-guard` — ONE key, ONE policy: *may I work here, and is what I read current?*\n *\n * Four CLASSES implement it, because the tool wiring genuinely differs (a Read names one file, a Bash\n * command is opaque, and the two Bash halves are not De Morgan duals of each other — see\n * guards/L2-branch-state.md, \"Deliberate divergence\"):\n *\n * | on stale `main` (state A) | on an already-merged branch (state B)\n * Write/Edit | feature-branch-guard | feature-branch-guard\n * Read | read-stale-guard | read-stale-guard\n * Bash | stale-main-bash-guard | merged-branch-bash-guard\n *\n * Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so\n * `grep rule=stale-main-bash-guard` over `.webpieces
|
|
1
|
+
{"version":3,"file":"main-sync-guard-configs.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/configs/main-sync-guard-configs.ts"],"names":[],"mappings":";;;AAAA,oDAA+F;AAC/F,oDAA+D;AAClD,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,sBAAuB,SAAQ,0BAAc;IAEtD,oGAAoG;IACpG,uEAAuE;IACvE,sBAAsB,CAAU;IAChC,oGAAoG;IACpG,wEAAwE;IACxE,kBAAkB,CAAU;IAC5B,6FAA6F;IAC7F,oFAAoF;IACpF,gBAAgB,CAAU;IAE1B,MAAM,CAAU,MAAM,GAAwC;QAC1D,IAAI,EAAE,IAAI,oBAAQ,CAAC,QAAQ,EAAE,wBAAY,CAAC;QAC1C,sBAAsB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACnD,kBAAkB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC/C,gBAAgB,EAAE,IAAI,oBAAQ,CAAC,QAAQ,CAAC;QACxC,GAAG,4BAAgB;KACtB,CAAC;;AAlBN,wDAmBC","sourcesContent":["import { FieldDef, SchemaShape, BaseRuleConfig, BASE_RULE_SCHEMA } from \"@webpieces/rules-sdk\";\nimport { OnOffMode, ON_OFF_MODES } from \"@webpieces/rules-sdk\";\nexport const DEFAULT_MAX_COMMITS_BEHIND = 5;\n\n/**\n * `branch-state-guard` — ONE key, ONE policy: *may I work here, and is what I read current?*\n *\n * Four CLASSES implement it, because the tool wiring genuinely differs (a Read names one file, a Bash\n * command is opaque, and the two Bash halves are not De Morgan duals of each other — see\n * guards/L2-branch-state.md, \"Deliberate divergence\"):\n *\n * | on stale `main` (state A) | on an already-merged branch (state B)\n * Write/Edit | feature-branch-guard | feature-branch-guard\n * Read | read-stale-guard | read-stale-guard\n * Bash | stale-main-bash-guard | merged-branch-bash-guard\n *\n * Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so\n * `grep rule=stale-main-bash-guard` over `.webpieces/logs/L2-decisions` keeps working. What merged is\n * the SWITCH: all four read this one config entry (`AbstractRule.configKey`).\n *\n * ## Why one key and not four\n *\n * Four keys made **half a policy representable**: `read-stale-guard: OFF` beside\n * `merged-branch-bash-guard: ON` is \"read the file, yes; `cat` the same file, no\" — the same\n * information, opposite verdicts. Nobody chose that; it was reachable because the config had a knob\n * per class instead of a knob per decision. One key makes it unconstructible.\n *\n * And `hangTimeoutMinutes` was declared four times, read four times, and fed ONE shared refresher for\n * ONE shared cache — with a per-process latch (main-sync-refresh.ts) plus config-blind callers ahead of\n * the guards, so at most one of the four values could ever reach a spawn. Four knobs, one honoured; now\n * one knob, honoured everywhere (runner + hook-core route through this entry too).\n */\nexport class BranchStateGuardConfig extends BaseRuleConfig {\n declare mode?: OnOffMode;\n // Surfaced verbatim in the on-main block's message, so a project's own convention is what the agent\n // is told to follow. Consumed by FeatureBranchGuardRule.onMainMessage.\n branchNamingConvention?: string;\n // Tunes the DETACHED refresher's stale-lock reclaim window (main-sync.lock.json). One value for one\n // refresher writing one cache — which is what it always physically was.\n hangTimeoutMinutes?: number;\n // Maximum cached commit distance tolerated on local main. Required so every repo consciously\n // carries the policy; 5 means 0..5 are allowed and stale-main blocks starting at 6.\n maxCommitsBehind!: number;\n\n static readonly SCHEMA: SchemaShape<BranchStateGuardConfig> = {\n mode: new FieldDef('string', ON_OFF_MODES),\n branchNamingConvention: FieldDef.optional('string'),\n hangTimeoutMinutes: FieldDef.optional('number'),\n maxCommitsBehind: new FieldDef('number'),\n ...BASE_RULE_SCHEMA,\n };\n}\n"]}
|
|
@@ -109,18 +109,18 @@ export declare class GuardDecision {
|
|
|
109
109
|
constructor(rule: string, tool: string, target: string, branch: string, verdict: Verdict, reason: string, cache: string | undefined, fault: string, matrix: MatrixRef);
|
|
110
110
|
}
|
|
111
111
|
/**
|
|
112
|
-
* Append one tab-separated line per L2 decision to `.webpieces
|
|
112
|
+
* Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where
|
|
113
113
|
* <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never
|
|
114
114
|
* identified renders as `unknown-coordinator-hook` — there is no un-keyed name).
|
|
115
115
|
* `root` is
|
|
116
|
-
* the repo/workspace root that holds `.webpieces
|
|
116
|
+
* the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a
|
|
117
117
|
* RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass
|
|
118
|
-
* logged from a subdir never scatters a stray `.webpieces
|
|
118
|
+
* logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never
|
|
119
119
|
* block or fail a hook.
|
|
120
120
|
*/
|
|
121
121
|
export declare function logGuardDecision(root: string, decision: GuardDecision): void;
|
|
122
122
|
/**
|
|
123
|
-
* The L1 stream — `.webpieces
|
|
123
|
+
* The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.
|
|
124
124
|
*
|
|
125
125
|
* L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name
|
|
126
126
|
* (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —
|
|
@@ -149,7 +149,7 @@ export declare class GuardInvocation {
|
|
|
149
149
|
constructor(root: string, timestamp: string, tool: string, target: string, branch: string, sync: string, projectDir: string);
|
|
150
150
|
}
|
|
151
151
|
/**
|
|
152
|
-
* The per-INVOCATION stream — `.webpieces
|
|
152
|
+
* The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer
|
|
153
153
|
* key), one line for EVERY guards-hook
|
|
154
154
|
* call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a
|
|
155
155
|
* rule actually judged. It captures the tool, the command/file, the live git branch, the async-written
|
|
@@ -171,7 +171,7 @@ export declare class InvocationLog {
|
|
|
171
171
|
private pending;
|
|
172
172
|
/**
|
|
173
173
|
* Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns
|
|
174
|
-
* `.webpieces
|
|
174
|
+
* `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.
|
|
175
175
|
*/
|
|
176
176
|
begin(cwd: string, tool: string, target: string): void;
|
|
177
177
|
/**
|
package/src/core/decision-log.js
CHANGED
|
@@ -24,7 +24,7 @@ const matrix_cures_1 = require("./matrix-cures");
|
|
|
24
24
|
// the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This
|
|
25
25
|
// one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES
|
|
26
26
|
// the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is
|
|
27
|
-
// traceable to a stale or missing async write. Writes to `.webpieces
|
|
27
|
+
// traceable to a stale or missing async write. Writes to `.webpieces/logs/L2-decisions/<writer>.log` —
|
|
28
28
|
// the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).
|
|
29
29
|
const MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)
|
|
30
30
|
/**
|
|
@@ -136,13 +136,13 @@ class GuardDecision {
|
|
|
136
136
|
}
|
|
137
137
|
exports.GuardDecision = GuardDecision;
|
|
138
138
|
/**
|
|
139
|
-
* Append one tab-separated line per L2 decision to `.webpieces
|
|
139
|
+
* Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where
|
|
140
140
|
* <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never
|
|
141
141
|
* identified renders as `unknown-coordinator-hook` — there is no un-keyed name).
|
|
142
142
|
* `root` is
|
|
143
|
-
* the repo/workspace root that holds `.webpieces
|
|
143
|
+
* the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a
|
|
144
144
|
* RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass
|
|
145
|
-
* logged from a subdir never scatters a stray `.webpieces
|
|
145
|
+
* logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never
|
|
146
146
|
* block or fail a hook.
|
|
147
147
|
*/
|
|
148
148
|
// webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container
|
|
@@ -150,7 +150,7 @@ function logGuardDecision(root, decision) {
|
|
|
150
150
|
appendDecision(root, log_streams_1.L2_DECISIONS_STREAM, decision);
|
|
151
151
|
}
|
|
152
152
|
/**
|
|
153
|
-
* The L1 stream — `.webpieces
|
|
153
|
+
* The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.
|
|
154
154
|
*
|
|
155
155
|
* L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name
|
|
156
156
|
* (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —
|
|
@@ -250,7 +250,7 @@ class GuardInvocation {
|
|
|
250
250
|
}
|
|
251
251
|
exports.GuardInvocation = GuardInvocation;
|
|
252
252
|
/**
|
|
253
|
-
* The per-INVOCATION stream — `.webpieces
|
|
253
|
+
* The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer
|
|
254
254
|
* key), one line for EVERY guards-hook
|
|
255
255
|
* call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a
|
|
256
256
|
* rule actually judged. It captures the tool, the command/file, the live git branch, the async-written
|
|
@@ -272,7 +272,7 @@ class InvocationLog {
|
|
|
272
272
|
pending = null;
|
|
273
273
|
/**
|
|
274
274
|
* Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns
|
|
275
|
-
* `.webpieces
|
|
275
|
+
* `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.
|
|
276
276
|
*/
|
|
277
277
|
begin(cwd, tool, target) {
|
|
278
278
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decision-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/decision-log.ts"],"names":[],"mappings":";;;AAqGA,kCAGC;AAkED,4CAEC;AAiBD,sCAEC;AAsMD,oCAaC;;AAlZD,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAE7B,8DAAyD;AACzD,sEAAmF;AACnF,0DAAoE;AACpE,+CAAsF;AAEtF,0DAA4F;AAC5F,iEAA6D;AAC7D,6CAAyC;AACzC,6CAAyC;AACzC,uDAAkD;AAClD,uCAA2C;AAC3C,iDAA+C;AAE/C,qGAAqG;AACrG,2GAA2G;AAC3G,sGAAsG;AACtG,sGAAsG;AACtG,4GAA4G;AAC5G,yFAAyF;AACzF,MAAM,aAAa,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,oEAAoE;AA6BtG;;;;;;;GAOG;AACH,MAAa,SAAS;IACG;IAAwB;IAA7C,YAAqB,KAAa,EAAW,GAAW;QAAnC,UAAK,GAAL,KAAK,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;IAAG,CAAC;CAC/D;AAFD,8BAEC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACU,QAAA,eAAe,GAAG,IAAI,SAAS,CAAC,IAAI,EAAE,iCAAkB,CAAC,CAAC;AAC1D,QAAA,eAAe,GAAG,IAAI,SAAS,CAAC,IAAI,EAAE,6BAAc,CAAC,CA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AAC;QAC3B,KAAK,KAAK,CAAC;QACX,OAAO,SAAS,CAAC;IACrB,CAAC;AACL,CAAC;AAED,oGAAoG;AACpG,oGAAoG;AACpG,kGAAkG;AAClG,UAAU;AACV,iHAAiH;AACjH,SAAS,OAAO,CAAC,KAAa;IAC1B,OAAO,sBAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC;AAED,mKAAmK;AACnK,SAAS,aAAa,CAAC,OAAe,EAAE,QAAgB;IACpD,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAClC,IAAI,IAAI,CAAC,IAAI,GAAG,aAAa,EAAE,CAAC;YAC5B,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YACrD,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;IACf,CAAC;AACL,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\nimport { RepoRootFinder, claudeEnv } from '@webpieces/rules-config';\nimport { L1_LOCATION_STREAM, L2_DECISIONS_STREAM, CALLS_STREAM } from './log-streams';\n\nimport { L0_FAULT_NONE, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\nimport { logTarget } from './log-target';\nimport { aiTypeContext } from './ai-type-context';\nimport { l2RowForReason } from './l2-rows';\nimport { cureForMatrix } from './matrix-cures';\n\n// The SYNC decision log — what the synchronous hook DID on each invocation and WHY. Its companion is\n// the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This\n// one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES\n// the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is\n// traceable to a stale or missing async write. Writes to `.webpieces-logs/logs/L2-decisions/<writer>.log` —\n// the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)\n\n/**\n * THE ACTION CODEBOOK, as a type. These are the five actions GUARD_MATRIX.md numbers 1-5, and they\n * are the vocabulary EVERY layer reports in — so one grep spans L-1, L0, L1 and L2.\n *\n * The three distinctions this exists to make, none of which `'ALLOW' | 'BLOCK'` could:\n *\n * ALLOW no objection — the call was HANDED DOWN to the next layer. A layer saying ALLOW\n * is NOT saying the call ran: the layer below it, or the OTHER parallel hook, may\n * still deny. This is L1's `ACT_DOWN`.\n * ALLOW_EXEMPT out of scope by construction — allowed, and evaluation STOPS here. L1's\n * `ACT_EXEMPT`.\n * ALLOW_FAIL_OPEN state could not be established, so nothing was judged. Keeping this distinct\n * from ALLOW is the entire point of the type: a fail-open allow and a real allow\n * that look identical make it impossible to tell whether the guards are protecting\n * anything or quietly abstaining. It used to be a `' (fail-open)'` SUBSTRING on the\n * reason field, which is exactly why the abstentions were never countable.\n * BLOCK_AI_CURE blocked, and the printed cure is a command the AI can run itself.\n * BLOCK_HUMAN blocked, and it needs a human decision — or a delegation (spawn a subagent) that\n * the blocked agent cannot perform for itself.\n *\n * Hard cut, per `.claude/rules/no-backwards-compat.md`: `'BLOCK'` is GONE rather than aliased, so every\n * construction site fails to\n * compile and has to say which kind of block it is. Before, that question had exactly one wrong\n * answer available — silence.\n */\nexport type Verdict = 'ALLOW' | 'ALLOW_EXEMPT' | 'ALLOW_FAIL_OPEN' | 'BLOCK_AI_CURE' | 'BLOCK_HUMAN';\n\n/**\n * WHICH ROW of WHICH layer's decision table produced this line. Data-only → a class, per CLAUDE.md.\n *\n * `row` is the row NUMBER from the layer's row array (`L1_ROWS[i].num`, `L2_ROWS[i].num`) — the\n * same number the generated doc prints, because the doc is rendered from that same array. So a log\n * line joins to its matrix row BY NUMBER, and checking observed behaviour against the documented use\n * cases becomes a lookup rather than an investigation.\n */\nexport class MatrixRef {\n constructor(readonly layer: string, readonly row: string) {}\n}\n\n/**\n * The layer tokens. EVERY layer now cites a row: L0 through its two decision-matrix rows, L1 through\n * L1_ROWS, and L2 through L2_ROWS (see `matrixL2Row`). This used to say `'-'` was for \"a layer with no\n * row array YET (L2 is the un-converted one)\" — L2 is converted, and a comment describing a state the\n * code left behind is exactly the kind of doc a reader trusts and should not.\n *\n * `'-'` survives for ONE case, and it is a real one: an L2 reason that no row claims. See matrixL2Row.\n *\n * These are REQUIRED at the constructor, not defaulted: a defaulted `MatrixRef` would make the\n * uncited case reachable by doing nothing and impossible to grep — the same defect this file's own\n * docblock argues against for `'BLOCK'`, where silence was the one wrong answer available.\n *\n * L0 NOW CITES ITS ROW TOO. It used to be `'-'` on the grounds that \"L0's faults are a table of letters\n * rather than numbered rows\" — but L0 has BOTH: the letter says WHICH fault, and the numbered decision\n * matrix (`renderGuardMatrixDoc`) says which of its three rows was taken. There is one ALLOW row and one\n * BLOCK row, so the pair `row=` + `fault=` pins the decision exactly, and the deny an agent reads now\n * carries the identical pair. That is the join: one grep spans the deny, the log line and the doc.\n * Two constants, not one `MATRIX_L0`, because the two call sites are a cure-bypass ALLOW and an L0\n * BLOCK — one token covering both is what made the row unciteable in the first place.\n */\nexport const MATRIX_L0_ALLOW = new MatrixRef('L0', L0_ROW_ALLOWLISTED);\nexport const MATRIX_L0_BLOCK = new MatrixRef('L0', L0_ROW_BLOCKED);\n\n/**\n * The L2 reference for one decision, with the row DERIVED FROM THE REASON.\n *\n * There is no `MATRIX_L2` constant any more, and its absence is the point: a single shared instance\n * meant every L2 line in the repo carried `row=-`, which reads as \"L2 has no rows\" rather than \"this\n * decision was not classified\". Deleting it makes every construction site name a reason, and the reason\n * is the only thing a call site has that identifies which row it is an instance of.\n *\n * `l2RowForReason` returns null for a reason no row claims, and that renders as `'-'` — visible in the\n * log, not silently absorbed into a default row. l2-matrix.spec.ts reads the four guard sources and\n * fails the build if any reason literal in them is unmapped, so `-` should never appear in practice;\n * when it does, it is a genuine hole in the table and the log says so.\n */\n// webpieces-disable no-function-outside-class -- a named constructor for MatrixRef beside it, in this module of module-scope writers\nexport function matrixL2Row(reason: string): MatrixRef {\n const row = l2RowForReason(reason);\n return new MatrixRef('L2', row === null ? '-' : String(row));\n}\n\n/**\n * The L2 stream, with NO row — for the two kinds of line that genuinely are not an instance of a row.\n *\n * 1. The runner's AGGREGATE bash lines (\"no bash-guard block\" / \"bash-guard block\"). They summarise\n * the whole guard set's answer for one command, not one row's verdict; the per-guard lines that\n * DO cite rows are written alongside them by the guards themselves.\n * 2. `whole-repo-build-guard`, which is not a branch-state policy at all — it is the experimental\n * home-config guard, has no webpieces.config.json entry, and shares this stream only because the\n * stream is \"bash decisions\", not \"L2 rows\".\n *\n * A NAMED constant rather than an inline `new MatrixRef('L2', '-')`, so `grep MATRIX_L2_UNROWED` lists\n * every uncited line and the list stays short and arguable. It is deliberately NOT called `MATRIX_L2`:\n * the old name was used by everything and made \"L2 has no rows\" indistinguishable from \"this line is\n * not a row\".\n */\nexport const MATRIX_L2_UNROWED = new MatrixRef('L2', '-');\n\n// Data-only record of one guard decision (per CLAUDE.md: classes for data, not object literals).\n// `cache` summarizes the async-written main-sync-status.json that drove a feature-branch-guard\n// decision (branch/merged/conflict/fork + the cache timestamp), or '-' when no cache was consulted\n// (bash guards, on-main, config-bypass).\nexport class GuardDecision {\n rule: string;\n tool: string;\n target: string; // file path (file guards) or the bash command (bash guards)\n branch: string;\n verdict: Verdict;\n reason: string;\n cache: string;\n /**\n * The L0 fault this decision IS, in the codebook's letter (core/l0-fault-codes.ts), or `-` for an\n * ordinary rule decision. The `sh` shim has always stamped `fault=` on its own stream; the three\n * JS-side faults (S/C/Y) reached this one with no label at all, so `grep fault=S` found nothing\n * even while an S storm was blocking every call.\n */\n fault: string;\n /** Which layer + row decided this. See MatrixRef — it is what joins a log line to the doc. */\n matrix: MatrixRef;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(rule: string, tool: string, target: string, branch: string, verdict: Verdict, reason: string, cache: string = '-', fault: string, matrix: MatrixRef) {\n this.rule = rule;\n this.tool = tool;\n this.target = target;\n this.branch = branch;\n this.verdict = verdict;\n this.reason = reason;\n this.cache = cache;\n this.fault = fault;\n this.matrix = matrix;\n }\n}\n\n/**\n * Append one tab-separated line per L2 decision to `.webpieces-logs/logs/L2-decisions/<writer>.log`, where\n * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never\n * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).\n * `root` is\n * the repo/workspace root that holds `.webpieces-logs` (callers pass workspaceRoot, or a\n * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass\n * logged from a subdir never scatters a stray `.webpieces-logs`). Swallows all errors — logging must never\n * block or fail a hook.\n */\n// webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container\nexport function logGuardDecision(root: string, decision: GuardDecision): void {\n appendDecision(root, L2_DECISIONS_STREAM, decision);\n}\n\n/**\n * The L1 stream — `.webpieces-logs/logs/L1-location/<writer>.log`.\n *\n * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name\n * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —\n * the exempt row and the three hand-down rows — wrote nothing at all. So \"L1 had no objection\" was\n * unobservable, and \"show me every L1 decision\" had no answer: L1 existed in the trail only as the\n * `root=` / `projectDir=` / `tree=` columns stapled onto somebody else's line.\n *\n * A SIBLING rather than a `base` parameter on logGuardDecision, deliberately: that signature is what\n * the process-wide `logStream` singleton exists to keep unchanged (see LogStream's docblock), and\n * `INVOCATION_LOG_FILE` already establishes the pattern of a second stream owning its own name in\n * this same module.\n */\n// webpieces-disable no-function-outside-class -- sibling of logGuardDecision, same module-scope writer shape and same reason\nexport function logL1Decision(root: string, decision: GuardDecision): void {\n appendDecision(root, L1_LOCATION_STREAM, decision);\n}\n\n// The one appender both streams share. `streamDir` is the LAYER; the writer key inside it is\n// logStream's session/agent/hook, which is what keeps one writer per file.\n// webpieces-disable no-function-outside-class -- the shared body of the two module-scope writers above\nfunction appendDecision(root: string, streamDir: string, decision: GuardDecision): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: a guard decision belongs to the tree it judged. WHO made the call is answered\n // by the filename, which logStream names with session/agent/hook.\n const logsDir = dotWebpieces.logsFile(root, streamDir);\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 decision.verdict,\n decision.tool,\n oneLine(decision.target),\n decision.branch,\n decision.rule,\n oneLine(decision.reason),\n oneLine(decision.cache),\n // WHICH ROW of WHICH table decided this. The directory already carries the layer, but a\n // line quoted out of its file must still say what judged it — and `row=` is the join key\n // to the generated doc, which is the point of the whole exercise.\n `layer=${decision.matrix.layer}`,\n `row=${decision.matrix.row}`,\n // The tree this decision was actually made against, and what Claude Code told the hook the\n // project was. Appended (never reordered) for the same reason as on the invocation line —\n // see ClaudeEnv: when these two disagree, that disagreement is the bug.\n `root=${root}`,\n `projectDir=${claudeEnv.projectDirForLog()}`,\n // git's name for that tree — `primary`, else the worktree name. Same literal and same\n // derivation as the L0 shim log's `tree=` (shim-audit-log.ts), so one grep spans both\n // streams: L0 carries tree without projectDir, L1 now carries both.\n `tree=${dotWebpieces.worktreeName(root) || 'primary'}`,\n // APPEND-ONLY, same spelling as the invocation line and the L0 shim log: which L0 fault\n // this was, or `-`.\n `fault=${decision.fault}`,\n // WHAT THE AGENT WAS TOLD TO DO — looked up from the row above, never passed in, so it is\n // by construction the same literal the generated matrix prints for that row (see\n // matrix-cures.ts). `row=` says which row judged the call; this says what that row\n // prescribed, which is what makes the trail auditable against the doc without opening it.\n // APPEND-ONLY, like every field before it.\n `cure=${oneLine(cureForMatrix(decision.matrix.layer, decision.matrix.row))}`,\n // WHICH HARNESS made the call, spelled exactly as the L0 sh shim spells it on its own\n // stream — so ONE grep (`ai=codex`) spans all five streams and \"is Codex actually being\n // guarded?\" is a question the trail can answer. APPEND-ONLY, like every field before it; a\n // row from a release that predates this carries no `ai=` and reads as `unknown`.\n `ai=${aiTypeContext.forLog()}`,\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/**\n * What the guard SAW on one invocation, captured up front and held until the outcome is known.\n * Data-only (per CLAUDE.md: classes for data, explicit construction).\n */\nexport class GuardInvocation {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n public readonly root: string,\n public readonly timestamp: string,\n public readonly tool: string,\n public readonly target: string,\n public readonly branch: string,\n public readonly sync: string,\n public readonly projectDir: string,\n ) {}\n}\n\n/**\n * The per-INVOCATION stream — `.webpieces-logs/logs/calls/<writer>.log` (see LogStream for the writer\n * key), one line for EVERY guards-hook\n * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a\n * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written\n * main-sync-status.json snapshot (branch / merged / fork-point / conflict), and — since this class\n * replaced a bare log-and-forget function — HOW THE CALL ENDED.\n *\n * WHY IT IS TWO CALLS. The line used to be written the moment the hook started, so it could not carry\n * a verdict: the decision had not been made yet. Answering \"what happened to this call?\" therefore\n * meant joining this file against the L2 decision stream BY TIMESTAMP, which is exactly the kind of\n * reconstruction a log exists to make unnecessary. So {@link begin} now only CAPTURES (including the\n * git/cache reads, which must still happen while the hook is running), and {@link finish} — called\n * from the hook's single terminal boundary, emitAllow/emitDeny — writes the whole line once the\n * outcome is known. The two streams stay distinct in purpose: this one is \"every call and how it\n * ended\", the decision log remains \"every judgement and why\".\n *\n * Every error is swallowed: logging must never block or fail a hook.\n */\nexport class InvocationLog {\n private pending: GuardInvocation | null = null;\n\n /**\n * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns\n * `.webpieces-logs` is resolved from it. Writes NOTHING — {@link finish} does that.\n */\n begin(cwd: string, tool: string, target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const branch = branchForLog(root);\n // The cache is branch-keyed, so the entry to log is the one for the branch we are standing\n // on. 'unknown' (branchForLog's failure value) simply misses and logs 'sync=none'.\n const sync = summarizeSyncStatus(readMainSyncStatus(root, branch));\n this.pending = new GuardInvocation(root, new Date().toISOString(), tool, oneLine(target), branch, sync, claudeEnv.projectDirForLog());\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Write the captured line, now stamped with the outcome. A no-op when nothing was captured (the\n * 'rules' hook, or a terminal boundary reached before begin()), and it clears the pending entry so\n * a second emit cannot double-log.\n *\n * `rule` is the rule that blocked, or '-' when there is none; `fault` is the L0 fault code when this\n * call ended on one (S/C/Y — the JS-side faults), else '-'. FIELD ORDER IS APPEND-ONLY: the five\n * original fields keep their positions (cleanup automation mines this file), and `guards=` /\n * `rule=` / … / `fault=` are added at the end.\n */\n finish(verdict: Verdict, rule: string, fault: string = L0_FAULT_NONE): void {\n const invocation = this.pending;\n this.pending = null;\n if (invocation === null) return;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const logsDir = dotWebpieces.logsFile(invocation.root, CALLS_STREAM);\n fs.mkdirSync(logsDir, { recursive: true });\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${invocation.timestamp}]`,\n invocation.tool,\n invocation.target,\n `branch=${invocation.branch}`,\n invocation.sync,\n // `guards=`, NOT `verdict=`. This hook can only report on ITSELF. Claude Code runs all\n // its PreToolUse hooks IN PARALLEL, so another hook process may deny a call this one\n // had no objection to, and neither can see the other's answer. Measured under the\n // RETIRED three-hook form: `cd <repo>/packages && ls` was DENIED by L-1 and recorded\n // here three times as `verdict=ALLOW`. The old field name promised an outcome it\n // structurally cannot know, so the name stayed even though L-1 is gone: the two\n // surviving hooks still run in parallel and still cannot see each other.\n `guards=${verdict}`,\n `rule=${oneLine(rule) || '-'}`,\n // The tree the guard ACTED in, next to what Claude Code said the project was. Both, on\n // every line, because the diagnostic value is entirely in comparing them — see\n // ClaudeEnv for the open question this field exists to settle empirically.\n `root=${invocation.root}`,\n `projectDir=${invocation.projectDir}`,\n // See logGuardDecision: the short tree label, so `tree=primary` with a matching\n // projectDir reads as healthy at a glance and `tree=<worktree>` beside a projectDir\n // pointing at the primary is the straddle, without diffing two absolute paths.\n `tree=${dotWebpieces.worktreeName(invocation.root) || 'primary'}`,\n // WHICH L0 fault ended this call, in the same letters and the same field name the L0 sh\n // shim uses (the `L0-shim/` stream) — so ONE grep spans the whole trail.\n `fault=${fault}`,\n // WHICH HARNESS made the call — same field name and same vocabulary as the L0 sh shim's\n // `ai=` and the decision stream's, so one grep spans the whole trail. APPEND-ONLY.\n `ai=${aiTypeContext.forLog()}`,\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\n// Process-wide instance: one hook process handles exactly one tool call, so a single pending entry is\n// the whole state there is. Module-scope (rather than DI) because the terminal boundary that flushes\n// it — emitAllow/emitDeny — is itself module-scope protocol code with no container in reach.\nexport const invocationLog = new InvocationLog();\n\n// One-field summary of main-sync-status.json for the invocation log: the branch the cache is FOR,\n// whether it is already merged (and its PR), fork-point presence, and conflict state — the signals a\n// cleanup step keys off. 'sync=none' when the cache has not been written yet (first call of a session).\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction summarizeSyncStatus(status: MainSyncStatus | null): string {\n if (status === null) return 'sync=none';\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `sync=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n}\n\n// Best-effort current branch for the log line. Returns 'unknown' on any failure (e.g. not a git\n// repo) — this is for display only, never for a control decision.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function branchForLog(root: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: root,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim() || 'unknown';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return 'unknown';\n }\n}\n\n// Collapse newlines/tabs and cap length so one decision is always one log line. The collapse itself\n// lives in LogTarget, because SessionCallHistory READS this format back and the two must agree byte\n// for byte — a second private copy of the cap is a silent way for a long command to stop matching\n// itself.\n// webpieces-disable no-function-outside-class -- the module's own leaf helper, beside branchForLog/rotateLogFile\nfunction oneLine(value: string): string {\n return logTarget.oneLine(value);\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction rotateLogFile(logPath: string, prevPath: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const stat = fs.statSync(logPath);\n if (stat.size > MAX_LOG_BYTES) {\n if (fs.existsSync(prevPath)) fs.unlinkSync(prevPath);\n fs.renameSync(logPath, prevPath);\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decision-log.js","sourceRoot":"","sources":["../../../../../../pack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AAI,IAAI,CAAC,IAAI,GAAG,aAAa,EAAE,CAAC;YAC5B,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YACrD,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;IACf,CAAC;AACL,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\nimport { RepoRootFinder, claudeEnv } from '@webpieces/rules-config';\nimport { L1_LOCATION_STREAM, L2_DECISIONS_STREAM, CALLS_STREAM } from './log-streams';\n\nimport { L0_FAULT_NONE, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\nimport { logTarget } from './log-target';\nimport { aiTypeContext } from './ai-type-context';\nimport { l2RowForReason } from './l2-rows';\nimport { cureForMatrix } from './matrix-cures';\n\n// The SYNC decision log — what the synchronous hook DID on each invocation and WHY. Its companion is\n// the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This\n// one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES\n// the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is\n// traceable to a stale or missing async write. Writes to `.webpieces/logs/L2-decisions/<writer>.log` —\n// the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)\n\n/**\n * THE ACTION CODEBOOK, as a type. These are the five actions GUARD_MATRIX.md numbers 1-5, and they\n * are the vocabulary EVERY layer reports in — so one grep spans L-1, L0, L1 and L2.\n *\n * The three distinctions this exists to make, none of which `'ALLOW' | 'BLOCK'` could:\n *\n * ALLOW no objection — the call was HANDED DOWN to the next layer. A layer saying ALLOW\n * is NOT saying the call ran: the layer below it, or the OTHER parallel hook, may\n * still deny. This is L1's `ACT_DOWN`.\n * ALLOW_EXEMPT out of scope by construction — allowed, and evaluation STOPS here. L1's\n * `ACT_EXEMPT`.\n * ALLOW_FAIL_OPEN state could not be established, so nothing was judged. Keeping this distinct\n * from ALLOW is the entire point of the type: a fail-open allow and a real allow\n * that look identical make it impossible to tell whether the guards are protecting\n * anything or quietly abstaining. It used to be a `' (fail-open)'` SUBSTRING on the\n * reason field, which is exactly why the abstentions were never countable.\n * BLOCK_AI_CURE blocked, and the printed cure is a command the AI can run itself.\n * BLOCK_HUMAN blocked, and it needs a human decision — or a delegation (spawn a subagent) that\n * the blocked agent cannot perform for itself.\n *\n * Hard cut, per `.claude/rules/no-backwards-compat.md`: `'BLOCK'` is GONE rather than aliased, so every\n * construction site fails to\n * compile and has to say which kind of block it is. Before, that question had exactly one wrong\n * answer available — silence.\n */\nexport type Verdict = 'ALLOW' | 'ALLOW_EXEMPT' | 'ALLOW_FAIL_OPEN' | 'BLOCK_AI_CURE' | 'BLOCK_HUMAN';\n\n/**\n * WHICH ROW of WHICH layer's decision table produced this line. Data-only → a class, per CLAUDE.md.\n *\n * `row` is the row NUMBER from the layer's row array (`L1_ROWS[i].num`, `L2_ROWS[i].num`) — the\n * same number the generated doc prints, because the doc is rendered from that same array. So a log\n * line joins to its matrix row BY NUMBER, and checking observed behaviour against the documented use\n * cases becomes a lookup rather than an investigation.\n */\nexport class MatrixRef {\n constructor(readonly layer: string, readonly row: string) {}\n}\n\n/**\n * The layer tokens. EVERY layer now cites a row: L0 through its two decision-matrix rows, L1 through\n * L1_ROWS, and L2 through L2_ROWS (see `matrixL2Row`). This used to say `'-'` was for \"a layer with no\n * row array YET (L2 is the un-converted one)\" — L2 is converted, and a comment describing a state the\n * code left behind is exactly the kind of doc a reader trusts and should not.\n *\n * `'-'` survives for ONE case, and it is a real one: an L2 reason that no row claims. See matrixL2Row.\n *\n * These are REQUIRED at the constructor, not defaulted: a defaulted `MatrixRef` would make the\n * uncited case reachable by doing nothing and impossible to grep — the same defect this file's own\n * docblock argues against for `'BLOCK'`, where silence was the one wrong answer available.\n *\n * L0 NOW CITES ITS ROW TOO. It used to be `'-'` on the grounds that \"L0's faults are a table of letters\n * rather than numbered rows\" — but L0 has BOTH: the letter says WHICH fault, and the numbered decision\n * matrix (`renderGuardMatrixDoc`) says which of its three rows was taken. There is one ALLOW row and one\n * BLOCK row, so the pair `row=` + `fault=` pins the decision exactly, and the deny an agent reads now\n * carries the identical pair. That is the join: one grep spans the deny, the log line and the doc.\n * Two constants, not one `MATRIX_L0`, because the two call sites are a cure-bypass ALLOW and an L0\n * BLOCK — one token covering both is what made the row unciteable in the first place.\n */\nexport const MATRIX_L0_ALLOW = new MatrixRef('L0', L0_ROW_ALLOWLISTED);\nexport const MATRIX_L0_BLOCK = new MatrixRef('L0', L0_ROW_BLOCKED);\n\n/**\n * The L2 reference for one decision, with the row DERIVED FROM THE REASON.\n *\n * There is no `MATRIX_L2` constant any more, and its absence is the point: a single shared instance\n * meant every L2 line in the repo carried `row=-`, which reads as \"L2 has no rows\" rather than \"this\n * decision was not classified\". Deleting it makes every construction site name a reason, and the reason\n * is the only thing a call site has that identifies which row it is an instance of.\n *\n * `l2RowForReason` returns null for a reason no row claims, and that renders as `'-'` — visible in the\n * log, not silently absorbed into a default row. l2-matrix.spec.ts reads the four guard sources and\n * fails the build if any reason literal in them is unmapped, so `-` should never appear in practice;\n * when it does, it is a genuine hole in the table and the log says so.\n */\n// webpieces-disable no-function-outside-class -- a named constructor for MatrixRef beside it, in this module of module-scope writers\nexport function matrixL2Row(reason: string): MatrixRef {\n const row = l2RowForReason(reason);\n return new MatrixRef('L2', row === null ? '-' : String(row));\n}\n\n/**\n * The L2 stream, with NO row — for the two kinds of line that genuinely are not an instance of a row.\n *\n * 1. The runner's AGGREGATE bash lines (\"no bash-guard block\" / \"bash-guard block\"). They summarise\n * the whole guard set's answer for one command, not one row's verdict; the per-guard lines that\n * DO cite rows are written alongside them by the guards themselves.\n * 2. `whole-repo-build-guard`, which is not a branch-state policy at all — it is the experimental\n * home-config guard, has no webpieces.config.json entry, and shares this stream only because the\n * stream is \"bash decisions\", not \"L2 rows\".\n *\n * A NAMED constant rather than an inline `new MatrixRef('L2', '-')`, so `grep MATRIX_L2_UNROWED` lists\n * every uncited line and the list stays short and arguable. It is deliberately NOT called `MATRIX_L2`:\n * the old name was used by everything and made \"L2 has no rows\" indistinguishable from \"this line is\n * not a row\".\n */\nexport const MATRIX_L2_UNROWED = new MatrixRef('L2', '-');\n\n// Data-only record of one guard decision (per CLAUDE.md: classes for data, not object literals).\n// `cache` summarizes the async-written main-sync-status.json that drove a feature-branch-guard\n// decision (branch/merged/conflict/fork + the cache timestamp), or '-' when no cache was consulted\n// (bash guards, on-main, config-bypass).\nexport class GuardDecision {\n rule: string;\n tool: string;\n target: string; // file path (file guards) or the bash command (bash guards)\n branch: string;\n verdict: Verdict;\n reason: string;\n cache: string;\n /**\n * The L0 fault this decision IS, in the codebook's letter (core/l0-fault-codes.ts), or `-` for an\n * ordinary rule decision. The `sh` shim has always stamped `fault=` on its own stream; the three\n * JS-side faults (S/C/Y) reached this one with no label at all, so `grep fault=S` found nothing\n * even while an S storm was blocking every call.\n */\n fault: string;\n /** Which layer + row decided this. See MatrixRef — it is what joins a log line to the doc. */\n matrix: MatrixRef;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(rule: string, tool: string, target: string, branch: string, verdict: Verdict, reason: string, cache: string = '-', fault: string, matrix: MatrixRef) {\n this.rule = rule;\n this.tool = tool;\n this.target = target;\n this.branch = branch;\n this.verdict = verdict;\n this.reason = reason;\n this.cache = cache;\n this.fault = fault;\n this.matrix = matrix;\n }\n}\n\n/**\n * Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where\n * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never\n * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).\n * `root` is\n * the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a\n * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass\n * logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never\n * block or fail a hook.\n */\n// webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container\nexport function logGuardDecision(root: string, decision: GuardDecision): void {\n appendDecision(root, L2_DECISIONS_STREAM, decision);\n}\n\n/**\n * The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.\n *\n * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name\n * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —\n * the exempt row and the three hand-down rows — wrote nothing at all. So \"L1 had no objection\" was\n * unobservable, and \"show me every L1 decision\" had no answer: L1 existed in the trail only as the\n * `root=` / `projectDir=` / `tree=` columns stapled onto somebody else's line.\n *\n * A SIBLING rather than a `base` parameter on logGuardDecision, deliberately: that signature is what\n * the process-wide `logStream` singleton exists to keep unchanged (see LogStream's docblock), and\n * `INVOCATION_LOG_FILE` already establishes the pattern of a second stream owning its own name in\n * this same module.\n */\n// webpieces-disable no-function-outside-class -- sibling of logGuardDecision, same module-scope writer shape and same reason\nexport function logL1Decision(root: string, decision: GuardDecision): void {\n appendDecision(root, L1_LOCATION_STREAM, decision);\n}\n\n// The one appender both streams share. `streamDir` is the LAYER; the writer key inside it is\n// logStream's session/agent/hook, which is what keeps one writer per file.\n// webpieces-disable no-function-outside-class -- the shared body of the two module-scope writers above\nfunction appendDecision(root: string, streamDir: string, decision: GuardDecision): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: a guard decision belongs to the tree it judged. WHO made the call is answered\n // by the filename, which logStream names with session/agent/hook.\n const logsDir = dotWebpieces.logsFile(root, streamDir);\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 decision.verdict,\n decision.tool,\n oneLine(decision.target),\n decision.branch,\n decision.rule,\n oneLine(decision.reason),\n oneLine(decision.cache),\n // WHICH ROW of WHICH table decided this. The directory already carries the layer, but a\n // line quoted out of its file must still say what judged it — and `row=` is the join key\n // to the generated doc, which is the point of the whole exercise.\n `layer=${decision.matrix.layer}`,\n `row=${decision.matrix.row}`,\n // The tree this decision was actually made against, and what Claude Code told the hook the\n // project was. Appended (never reordered) for the same reason as on the invocation line —\n // see ClaudeEnv: when these two disagree, that disagreement is the bug.\n `root=${root}`,\n `projectDir=${claudeEnv.projectDirForLog()}`,\n // git's name for that tree — `primary`, else the worktree name. Same literal and same\n // derivation as the L0 shim log's `tree=` (shim-audit-log.ts), so one grep spans both\n // streams: L0 carries tree without projectDir, L1 now carries both.\n `tree=${dotWebpieces.worktreeName(root) || 'primary'}`,\n // APPEND-ONLY, same spelling as the invocation line and the L0 shim log: which L0 fault\n // this was, or `-`.\n `fault=${decision.fault}`,\n // WHAT THE AGENT WAS TOLD TO DO — looked up from the row above, never passed in, so it is\n // by construction the same literal the generated matrix prints for that row (see\n // matrix-cures.ts). `row=` says which row judged the call; this says what that row\n // prescribed, which is what makes the trail auditable against the doc without opening it.\n // APPEND-ONLY, like every field before it.\n `cure=${oneLine(cureForMatrix(decision.matrix.layer, decision.matrix.row))}`,\n // WHICH HARNESS made the call, spelled exactly as the L0 sh shim spells it on its own\n // stream — so ONE grep (`ai=codex`) spans all five streams and \"is Codex actually being\n // guarded?\" is a question the trail can answer. APPEND-ONLY, like every field before it; a\n // row from a release that predates this carries no `ai=` and reads as `unknown`.\n `ai=${aiTypeContext.forLog()}`,\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/**\n * What the guard SAW on one invocation, captured up front and held until the outcome is known.\n * Data-only (per CLAUDE.md: classes for data, explicit construction).\n */\nexport class GuardInvocation {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n public readonly root: string,\n public readonly timestamp: string,\n public readonly tool: string,\n public readonly target: string,\n public readonly branch: string,\n public readonly sync: string,\n public readonly projectDir: string,\n ) {}\n}\n\n/**\n * The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer\n * key), one line for EVERY guards-hook\n * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a\n * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written\n * main-sync-status.json snapshot (branch / merged / fork-point / conflict), and — since this class\n * replaced a bare log-and-forget function — HOW THE CALL ENDED.\n *\n * WHY IT IS TWO CALLS. The line used to be written the moment the hook started, so it could not carry\n * a verdict: the decision had not been made yet. Answering \"what happened to this call?\" therefore\n * meant joining this file against the L2 decision stream BY TIMESTAMP, which is exactly the kind of\n * reconstruction a log exists to make unnecessary. So {@link begin} now only CAPTURES (including the\n * git/cache reads, which must still happen while the hook is running), and {@link finish} — called\n * from the hook's single terminal boundary, emitAllow/emitDeny — writes the whole line once the\n * outcome is known. The two streams stay distinct in purpose: this one is \"every call and how it\n * ended\", the decision log remains \"every judgement and why\".\n *\n * Every error is swallowed: logging must never block or fail a hook.\n */\nexport class InvocationLog {\n private pending: GuardInvocation | null = null;\n\n /**\n * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns\n * `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.\n */\n begin(cwd: string, tool: string, target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const branch = branchForLog(root);\n // The cache is branch-keyed, so the entry to log is the one for the branch we are standing\n // on. 'unknown' (branchForLog's failure value) simply misses and logs 'sync=none'.\n const sync = summarizeSyncStatus(readMainSyncStatus(root, branch));\n this.pending = new GuardInvocation(root, new Date().toISOString(), tool, oneLine(target), branch, sync, claudeEnv.projectDirForLog());\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Write the captured line, now stamped with the outcome. A no-op when nothing was captured (the\n * 'rules' hook, or a terminal boundary reached before begin()), and it clears the pending entry so\n * a second emit cannot double-log.\n *\n * `rule` is the rule that blocked, or '-' when there is none; `fault` is the L0 fault code when this\n * call ended on one (S/C/Y — the JS-side faults), else '-'. FIELD ORDER IS APPEND-ONLY: the five\n * original fields keep their positions (cleanup automation mines this file), and `guards=` /\n * `rule=` / … / `fault=` are added at the end.\n */\n finish(verdict: Verdict, rule: string, fault: string = L0_FAULT_NONE): void {\n const invocation = this.pending;\n this.pending = null;\n if (invocation === null) return;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const logsDir = dotWebpieces.logsFile(invocation.root, CALLS_STREAM);\n fs.mkdirSync(logsDir, { recursive: true });\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${invocation.timestamp}]`,\n invocation.tool,\n invocation.target,\n `branch=${invocation.branch}`,\n invocation.sync,\n // `guards=`, NOT `verdict=`. This hook can only report on ITSELF. Claude Code runs all\n // its PreToolUse hooks IN PARALLEL, so another hook process may deny a call this one\n // had no objection to, and neither can see the other's answer. Measured under the\n // RETIRED three-hook form: `cd <repo>/packages && ls` was DENIED by L-1 and recorded\n // here three times as `verdict=ALLOW`. The old field name promised an outcome it\n // structurally cannot know, so the name stayed even though L-1 is gone: the two\n // surviving hooks still run in parallel and still cannot see each other.\n `guards=${verdict}`,\n `rule=${oneLine(rule) || '-'}`,\n // The tree the guard ACTED in, next to what Claude Code said the project was. Both, on\n // every line, because the diagnostic value is entirely in comparing them — see\n // ClaudeEnv for the open question this field exists to settle empirically.\n `root=${invocation.root}`,\n `projectDir=${invocation.projectDir}`,\n // See logGuardDecision: the short tree label, so `tree=primary` with a matching\n // projectDir reads as healthy at a glance and `tree=<worktree>` beside a projectDir\n // pointing at the primary is the straddle, without diffing two absolute paths.\n `tree=${dotWebpieces.worktreeName(invocation.root) || 'primary'}`,\n // WHICH L0 fault ended this call, in the same letters and the same field name the L0 sh\n // shim uses (the `L0-shim/` stream) — so ONE grep spans the whole trail.\n `fault=${fault}`,\n // WHICH HARNESS made the call — same field name and same vocabulary as the L0 sh shim's\n // `ai=` and the decision stream's, so one grep spans the whole trail. APPEND-ONLY.\n `ai=${aiTypeContext.forLog()}`,\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\n// Process-wide instance: one hook process handles exactly one tool call, so a single pending entry is\n// the whole state there is. Module-scope (rather than DI) because the terminal boundary that flushes\n// it — emitAllow/emitDeny — is itself module-scope protocol code with no container in reach.\nexport const invocationLog = new InvocationLog();\n\n// One-field summary of main-sync-status.json for the invocation log: the branch the cache is FOR,\n// whether it is already merged (and its PR), fork-point presence, and conflict state — the signals a\n// cleanup step keys off. 'sync=none' when the cache has not been written yet (first call of a session).\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction summarizeSyncStatus(status: MainSyncStatus | null): string {\n if (status === null) return 'sync=none';\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `sync=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n}\n\n// Best-effort current branch for the log line. Returns 'unknown' on any failure (e.g. not a git\n// repo) — this is for display only, never for a control decision.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function branchForLog(root: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: root,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim() || 'unknown';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return 'unknown';\n }\n}\n\n// Collapse newlines/tabs and cap length so one decision is always one log line. The collapse itself\n// lives in LogTarget, because SessionCallHistory READS this format back and the two must agree byte\n// for byte — a second private copy of the cap is a silent way for a long command to stop matching\n// itself.\n// webpieces-disable no-function-outside-class -- the module's own leaf helper, beside branchForLog/rotateLogFile\nfunction oneLine(value: string): string {\n return logTarget.oneLine(value);\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"]}
|
|
@@ -25,7 +25,7 @@ export declare class ExcludedPathReference {
|
|
|
25
25
|
* Finds the paths a BASH command names that the top-level `excludePaths` already exempts.
|
|
26
26
|
*
|
|
27
27
|
* WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so
|
|
28
|
-
* `cat .webpieces
|
|
28
|
+
* `cat .webpieces/tasks.md` at the repo root is DENIED even though that exact file is exempt from
|
|
29
29
|
* every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed
|
|
30
30
|
* was a git state change — strictly more destructive than the one it omitted. This class supplies the
|
|
31
31
|
* missing sentence; it changes no verdict.
|
|
@@ -42,7 +42,7 @@ export declare class ExcludedPathEscapeScan {
|
|
|
42
42
|
* `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the
|
|
43
43
|
* same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved
|
|
44
44
|
* there and ABSOLUTE ones normalised straight to workspace-relative, which is how
|
|
45
|
-
* `cat /abs/path/to/repo/.webpieces
|
|
45
|
+
* `cat /abs/path/to/repo/.webpieces/tasks.md` reaches the same verdict as `cat .webpieces/tasks.md`.
|
|
46
46
|
*/
|
|
47
47
|
constructor(scanner: CommandScanner, workspaceRoot: string, effectiveCwd: string);
|
|
48
48
|
/**
|
|
@@ -58,8 +58,8 @@ export declare class ExcludedPathEscapeScan {
|
|
|
58
58
|
* A directory the agent may `cd` into and have the guards actually stand down, or null.
|
|
59
59
|
*
|
|
60
60
|
* THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles
|
|
61
|
-
* `.webpieces
|
|
62
|
-
* directory `.webpieces
|
|
61
|
+
* `.webpieces/**` to the anchored `/^\.webpieces\/.*$/` — the `/` is a LITERAL, so the bare
|
|
62
|
+
* directory `.webpieces` does NOT match its own glob. `cd .webpieces && cat tasks.md` is still
|
|
63
63
|
* denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a
|
|
64
64
|
* turn to disprove. So the directory is only offered when it passes the very same matcher the
|
|
65
65
|
* runner will use, and the renderer says so plainly when nothing does.
|
|
@@ -36,7 +36,7 @@ exports.ExcludedPathReference = ExcludedPathReference;
|
|
|
36
36
|
* Finds the paths a BASH command names that the top-level `excludePaths` already exempts.
|
|
37
37
|
*
|
|
38
38
|
* WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so
|
|
39
|
-
* `cat .webpieces
|
|
39
|
+
* `cat .webpieces/tasks.md` at the repo root is DENIED even though that exact file is exempt from
|
|
40
40
|
* every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed
|
|
41
41
|
* was a git state change — strictly more destructive than the one it omitted. This class supplies the
|
|
42
42
|
* missing sentence; it changes no verdict.
|
|
@@ -53,7 +53,7 @@ class ExcludedPathEscapeScan {
|
|
|
53
53
|
* `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the
|
|
54
54
|
* same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved
|
|
55
55
|
* there and ABSOLUTE ones normalised straight to workspace-relative, which is how
|
|
56
|
-
* `cat /abs/path/to/repo/.webpieces
|
|
56
|
+
* `cat /abs/path/to/repo/.webpieces/tasks.md` reaches the same verdict as `cat .webpieces/tasks.md`.
|
|
57
57
|
*/
|
|
58
58
|
constructor(scanner, workspaceRoot, effectiveCwd) {
|
|
59
59
|
this.scanner = scanner;
|
|
@@ -93,8 +93,8 @@ class ExcludedPathEscapeScan {
|
|
|
93
93
|
* A directory the agent may `cd` into and have the guards actually stand down, or null.
|
|
94
94
|
*
|
|
95
95
|
* THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles
|
|
96
|
-
* `.webpieces
|
|
97
|
-
* directory `.webpieces
|
|
96
|
+
* `.webpieces/**` to the anchored `/^\.webpieces\/.*$/` — the `/` is a LITERAL, so the bare
|
|
97
|
+
* directory `.webpieces` does NOT match its own glob. `cd .webpieces && cat tasks.md` is still
|
|
98
98
|
* denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a
|
|
99
99
|
* turn to disprove. So the directory is only offered when it passes the very same matcher the
|
|
100
100
|
* runner will use, and the renderer says so plainly when nothing does.
|
|
@@ -180,7 +180,7 @@ class ExcludedPathEscapeHint {
|
|
|
180
180
|
lines.push(` ${glob}`);
|
|
181
181
|
lines.push(` Your command referenced: ${references.map((r) => r.referencedPath).join(', ')}`);
|
|
182
182
|
// Scoped to the FILE, deliberately. The stanza fires on any rule block whose command names an
|
|
183
|
-
// exempt path, and `git push … && cat .webpieces
|
|
183
|
+
// exempt path, and `git push … && cat .webpieces/tasks.md` is blocked for the push — for which
|
|
184
184
|
// Read/Write substitutes for nothing. Claiming the remedies below were optional would be false.
|
|
185
185
|
lines.push(' Read/Write/Edit reaches that file RIGHT NOW, with no git operation at all.');
|
|
186
186
|
lines.push(' Anything ELSE this command does — a git/gh operation, a build — still needs the');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"excluded-path-escape.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/excluded-path-escape.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAI7B,0DAAyD;AACzD,0DAAwD;AAExD;;;;;;;;;GASG;AACH,MAAa,qBAAqB;IAC9B,kEAAkE;IACzD,cAAc,CAAS;IAChC,gGAAgG;IACvF,WAAW,CAAS;IAC7B,kGAAkG;IACzF,WAAW,CAAgB;IACpC,kGAAkG;IACzF,mBAAmB,CAAS;IAErC,YACI,cAAsB,EACtB,WAAmB,EACnB,WAA0B,EAC1B,mBAA2B;QAE3B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IACnD,CAAC;CACJ;AArBD,sDAqBC;AAED;;;;;;;;;;;;GAYG;AACH,MAAa,sBAAsB;IACd,OAAO,CAAiB;IACxB,aAAa,CAAS;IACtB,YAAY,CAAS;IAEtC;;;;;OAKG;IACH,YAAY,OAAuB,EAAE,aAAqB,EAAE,YAAoB;QAC5E,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;IAED;;;;;;OAMG;IACH,UAAU,CAAC,OAAe,EAAE,EAAgB;QACxC,IAAI,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QAErC,MAAM,KAAK,GAA4B,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;QAC/B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE,CAAC;YAChD,MAAM,QAA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YAC3E,uDAAuD;SAC1D,CAAC;IACN,CAAC;IAED,+FAA+F;IAC/F,+FAA+F;IAC/F,wBAAwB;IAChB,SAAS,CAAC,KAA4B;QAC1C,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;QAC/C,OAAO;YACH,wDAAwD;YACxD,QAAQ,GAAG,6DAA6D,KAAK,CAAC,WAAW,gBAAgB;YACzG,2FAA2F;YAC3F,gGAAgG;YAChG,wFAAwF;YACxF,oEAAoE,GAAG,OAAO,KAAK,CAAC,WAAW,IAAI;SACtG,CAAC;IACN,CAAC;CACJ;AAxED,wDAwEC","sourcesContent":["import * as path from 'path';\n\nimport { ExcludePaths } from '@webpieces/rules-config';\n\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { globMatches } from '@webpieces/hook-runtime';\n\n/**\n * One path the denied command NAMED that `excludePaths` already exempts, plus how to reach it.\n *\n * Data-only, so a class (per CLAUDE.md).\n *\n * `cdDirectory` is the whole point of the class rather than a bare string: it is a directory that\n * ITSELF satisfies `globMatches` against one of the configured globs, or null when no such directory\n * exists for this reference. Callers must never invent one — see ExcludedPathEscapeScan for why a\n * naive `dirname` is wrong exactly when it looks most obviously right.\n */\nexport class ExcludedPathReference {\n /** The referenced path, workspace-relative, as it was matched. */\n readonly referencedPath: string;\n /** The `excludePaths` glob that matched it — quoted back so the agent need not re-derive it. */\n readonly matchedGlob: string;\n /** A directory a `cd` may legally land in (matches a glob on its own), or null when none does. */\n readonly cdDirectory: string | null;\n /** `referencedPath` re-expressed relative to `cdDirectory`; '' when there is no `cdDirectory`. */\n readonly pathFromCdDirectory: string;\n\n constructor(\n referencedPath: string,\n matchedGlob: string,\n cdDirectory: string | null,\n pathFromCdDirectory: string,\n ) {\n this.referencedPath = referencedPath;\n this.matchedGlob = matchedGlob;\n this.cdDirectory = cdDirectory;\n this.pathFromCdDirectory = pathFromCdDirectory;\n }\n}\n\n/**\n * Finds the paths a BASH command names that the top-level `excludePaths` already exempts.\n *\n * WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so\n * `cat .webpieces-logs/tasks.md` at the repo root is DENIED even though that exact file is exempt from\n * every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed\n * was a git state change — strictly more destructive than the one it omitted. This class supplies the\n * missing sentence; it changes no verdict.\n *\n * A token is treated as a candidate path with no filesystem check: whether it exists says nothing\n * about whether it is exempt, and a stat per token on the blocking hook path is exactly the cost these\n * guards avoid. Non-path tokens (a `grep` pattern, a `sed` script) simply match no glob.\n */\nexport class ExcludedPathEscapeScan {\n private readonly scanner: CommandScanner;\n private readonly workspaceRoot: string;\n private readonly effectiveCwd: string;\n\n /**\n * `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the\n * same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved\n * there and ABSOLUTE ones normalised straight to workspace-relative, which is how\n * `cat /abs/path/to/repo/.webpieces-logs/tasks.md` reaches the same verdict as `cat .webpieces-logs/tasks.md`.\n */\n constructor(scanner: CommandScanner, workspaceRoot: string, effectiveCwd: string) {\n this.scanner = scanner;\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd;\n }\n\n /**\n * Every excluded path this command references, in command order, de-duplicated.\n *\n * Scans EVERY segment, not just a leading `cd`: `cat x`, `grep -n foo x`, `sed -n '1,5p' x` and a\n * path inside an `&&` compound all count, because the agent's next move depends on the file it\n * wanted, wherever in the line it named it.\n */\n references(command: string, ex: ExcludePaths): readonly ExcludedPathReference[] {\n if (ex.paths.length === 0) return [];\n\n const found: ExcludedPathReference[] = [];\n const seen = new Set<string>();\n for (const token of this.candidateTokens(command)) {\n const relative = this.workspaceRelative(token);\n if (relative === null || seen.has(relative)) continue;\n seen.add(relative);\n const glob = this.matchingGlob(relative, ex);\n if (glob === null) continue;\n found.push(this.reference(relative, glob, ex));\n }\n return found;\n }\n\n // Build the reference, including the `cd` target — the ONE subtle part, see cdDirectory below.\n private reference(relative: string, glob: string, ex: ExcludePaths): ExcludedPathReference {\n const dir = this.cdDirectory(relative, ex);\n return new ExcludedPathReference(\n relative, glob, dir, dir === null ? '' : path.relative(dir, relative),\n );\n }\n\n /**\n * A directory the agent may `cd` into and have the guards actually stand down, or null.\n *\n * THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles\n * `.webpieces-logs/**` to the anchored `/^\\.webpieces-logs\\/.*$/` — the `/` is a LITERAL, so the bare\n * directory `.webpieces-logs` does NOT match its own glob. `cd .webpieces-logs && cat tasks.md` is still\n * denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a\n * turn to disprove. So the directory is only offered when it passes the very same matcher the\n * runner will use, and the renderer says so plainly when nothing does.\n */\n private cdDirectory(relative: string, ex: ExcludePaths): string | null {\n const dir = path.dirname(relative);\n if (dir === '.' || dir === '' || dir === relative) return null;\n return this.matchingGlob(dir, ex) === null ? null : dir;\n }\n\n // The first configured glob this workspace-relative path satisfies, under the runner's OWN matcher\n // (globMatches, load-rules.ts) — never a looser one, or the stanza would promise an exemption the\n // guards do not grant.\n private matchingGlob(relative: string, ex: ExcludePaths): string | null {\n for (const pattern of ex.paths) {\n if (globMatches(pattern, relative)) return pattern;\n }\n return null;\n }\n\n /**\n * Workspace-relative form of a token, or null when it is not a path inside this workspace.\n *\n * `~`-rooted and out-of-tree paths are nothing to do with this repo's exclusions, and the\n * workspace root itself ('') matches no glob by construction.\n */\n private workspaceRelative(token: string): string | null {\n const cleaned = token.replace(REDIRECT_PREFIX, '');\n if (cleaned === '' || cleaned.startsWith('~')) return null;\n const absolute = path.isAbsolute(cleaned) ? cleaned : path.resolve(this.effectiveCwd, cleaned);\n const relative = path.relative(this.workspaceRoot, absolute);\n if (relative === '' || relative.startsWith('..')) return null;\n return relative;\n }\n\n /**\n * Every token that could name a file: each segment's words minus the command word itself and\n * minus flags. Deliberately generous — a token that is not a path matches no glob, while a token\n * dropped by a cleverer filter is a file the agent is never told it can read.\n */\n private candidateTokens(command: string): readonly string[] {\n const tokens: string[] = [];\n for (const segment of this.scanner.commandSegments(command)) {\n const words = this.scanner.words(segment);\n for (let i = 1; i < words.length; i++) {\n if (words[i].startsWith('-')) continue;\n tokens.push(words[i]);\n }\n }\n return tokens;\n }\n}\n\n// A redirection glued to its target (`>out.log`, `2>>err.log`, `<in.txt`) — strip the operator so the\n// target is scanned as the path it is.\nconst REDIRECT_PREFIX = /^\\d*(?:>>?|<)/;\n\n/**\n * Renders the leading stanza of a bash deny body: the Read/Write escape the agent already has, and —\n * when one genuinely exists — the `cd` that makes bash itself work.\n *\n * It goes at the TOP of the report, above the git remedies, because the agent acts on the first\n * actionable thing it reads. The live incident this fixes had the agent create a branch in a human's\n * working tree to record a row in a gitignored scratch file; the cheap, side-effect-free path was one\n * sentence away and never printed. Returns '' when the command names no excluded path, so a repo\n * without exemptions — and every command that names nothing exempt — sees no extra noise.\n */\nexport class ExcludedPathEscapeHint {\n private readonly scan: ExcludedPathEscapeScan;\n\n /** `effectiveCwd` is the directory the command really runs in — see ExcludedPathEscapeScan. */\n constructor(workspaceRoot: string, effectiveCwd: string) {\n this.scan = new ExcludedPathEscapeScan(new CommandScanner(), workspaceRoot, effectiveCwd);\n }\n\n render(command: string, ex: ExcludePaths): string {\n const references = this.scan.references(command, ex);\n if (references.length === 0) return '';\n\n const lines: string[] = [];\n lines.push('✅ YOU CAN USE THE READ/WRITE TOOLS RIGHT NOW — no git operation needed.');\n lines.push(' These paths are in excludePaths and are exempt from every guard:');\n for (const glob of ex.paths) lines.push(` ${glob}`);\n lines.push(` Your command referenced: ${references.map((r: ExcludedPathReference): string => r.referencedPath).join(', ')}`);\n // Scoped to the FILE, deliberately. The stanza fires on any rule block whose command names an\n // exempt path, and `git push … && cat .webpieces-logs/tasks.md` is blocked for the push — for which\n // Read/Write substitutes for nothing. Claiming the remedies below were optional would be false.\n lines.push(' Read/Write/Edit reaches that file RIGHT NOW, with no git operation at all.');\n lines.push(' Anything ELSE this command does — a git/gh operation, a build — still needs the');\n lines.push(' remedies below.');\n const bash = this.bashLines(references);\n if (bash.length > 0) {\n lines.push('');\n for (const line of bash) lines.push(line);\n }\n lines.push('');\n return lines.join('\\n');\n }\n\n // The bash half: the `cd` when one matches, the honest refusal to invent one when none does, and\n // silence when there is not even a directory worth naming.\n private bashLines(references: readonly ExcludedPathReference[]): readonly string[] {\n const withCd = references.find((r: ExcludedPathReference): boolean => r.cdDirectory !== null);\n if (withCd !== undefined) return this.cdLines(withCd);\n // A workspace-ROOT-level file — matched by a file-shaped glob like `*.md` — has no directory to\n // name: `dirname` is `.`, which no excludePaths glob can usefully exempt (the relative cwd at\n // the root is '', so `.` would never match) and which reads as \"exempt the whole repo\". Say\n // nothing about bash rather than something false.\n const nested = references.find(\n (r: ExcludedPathReference): boolean => path.dirname(r.referencedPath) !== '.',\n );\n return nested === undefined ? [] : this.noCdLines(nested);\n }\n\n // A `cd` the guards will actually honour: its directory passed globMatches in the scan.\n private cdLines(withCd: ExcludedPathReference): readonly string[] {\n return [\n '✅ OR KEEP USING BASH — put a `cd` into the excluded tree FIRST:',\n ` cd ${String(withCd.cdDirectory)} && <your command, writing \\`${withCd.referencedPath}\\` as \\`${withCd.pathFromCdDirectory}\\`>`,\n ' The guard resolves a LEADING `cd` and judges that directory, so this runs.',\n ' It must be the first thing in the command: no leading VAR= assignment,',\n ' no subshell wrapper — those defeat the resolution.',\n ];\n }\n\n // No directory on the way to the file matches a glob on its own, so there is no `cd` to offer.\n // Say WHY and give the one-line config edit that would create one, rather than printing a `cd`\n // that would be denied.\n private noCdLines(first: ExcludedPathReference): readonly string[] {\n const dir = path.dirname(first.referencedPath);\n return [\n '⚠️ A `cd` CANNOT rescue bash here, so do not try one.',\n ` \\`${dir}\\` (the directory itself) matches no excludePaths glob: \\`${first.matchedGlob}\\` compiles to`,\n ' an anchored regex whose `/` is literal, so the bare directory fails it and a `cd` into',\n ' it is STILL denied. That form is deliberately not printed here — it looks right and is not.',\n ' Use Read/Write/Edit above — or, to make bash work here too, list the bare directory',\n ` alongside the glob in webpieces.config.json → excludePaths: [\"${dir}\", \"${first.matchedGlob}\"]`,\n ];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"excluded-path-escape.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/excluded-path-escape.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAI7B,0DAAyD;AACzD,0DAAwD;AAExD;;;;;;;;;GASG;AACH,MAAa,qBAAqB;IAC9B,kEAAkE;IACzD,cAAc,CAAS;IAChC,gGAAgG;IACvF,WAAW,CAAS;IAC7B,kGAAkG;IACzF,WAAW,CAAgB;IACpC,kGAAkG;IACzF,mBAAmB,CAAS;IAErC,YACI,cAAsB,EACtB,WAAmB,EACnB,WAA0B,EAC1B,mBAA2B;QAE3B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IACnD,CAAC;CACJ;AArBD,sDAqBC;AAED;;;;;;;;;;;;GAYG;AACH,MAAa,sBAAsB;IACd,OAAO,CAAiB;IACxB,aAAa,CAAS;IACtB,YAAY,CAAS;IAEtC;;;;;OAKG;IACH,YAAY,OAAuB,EAAE,aAAqB,EAAE,YAAoB;QAC5E,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;IAED;;;;;;OAMG;IACH,UAAU,CAAC,OAAe,EAAE,EAAgB;QACxC,IAAI,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QAErC,MAAM,KAAK,GAA4B,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;QAC/B,KAAK,MAAM,KAAK,IAAI,I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,WAAW,MAAM,CAAC,mBAAmB,KAAK;YACpI,+EAA+E;YAC/E,2EAA2E;YAC3E,uDAAuD;SAC1D,CAAC;IACN,CAAC;IAED,+FAA+F;IAC/F,+FAA+F;IAC/F,wBAAwB;IAChB,SAAS,CAAC,KAA4B;QAC1C,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;QAC/C,OAAO;YACH,wDAAwD;YACxD,QAAQ,GAAG,6DAA6D,KAAK,CAAC,WAAW,gBAAgB;YACzG,2FAA2F;YAC3F,gGAAgG;YAChG,wFAAwF;YACxF,oEAAoE,GAAG,OAAO,KAAK,CAAC,WAAW,IAAI;SACtG,CAAC;IACN,CAAC;CACJ;AAxED,wDAwEC","sourcesContent":["import * as path from 'path';\n\nimport { ExcludePaths } from '@webpieces/rules-config';\n\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { globMatches } from '@webpieces/hook-runtime';\n\n/**\n * One path the denied command NAMED that `excludePaths` already exempts, plus how to reach it.\n *\n * Data-only, so a class (per CLAUDE.md).\n *\n * `cdDirectory` is the whole point of the class rather than a bare string: it is a directory that\n * ITSELF satisfies `globMatches` against one of the configured globs, or null when no such directory\n * exists for this reference. Callers must never invent one — see ExcludedPathEscapeScan for why a\n * naive `dirname` is wrong exactly when it looks most obviously right.\n */\nexport class ExcludedPathReference {\n /** The referenced path, workspace-relative, as it was matched. */\n readonly referencedPath: string;\n /** The `excludePaths` glob that matched it — quoted back so the agent need not re-derive it. */\n readonly matchedGlob: string;\n /** A directory a `cd` may legally land in (matches a glob on its own), or null when none does. */\n readonly cdDirectory: string | null;\n /** `referencedPath` re-expressed relative to `cdDirectory`; '' when there is no `cdDirectory`. */\n readonly pathFromCdDirectory: string;\n\n constructor(\n referencedPath: string,\n matchedGlob: string,\n cdDirectory: string | null,\n pathFromCdDirectory: string,\n ) {\n this.referencedPath = referencedPath;\n this.matchedGlob = matchedGlob;\n this.cdDirectory = cdDirectory;\n this.pathFromCdDirectory = pathFromCdDirectory;\n }\n}\n\n/**\n * Finds the paths a BASH command names that the top-level `excludePaths` already exempts.\n *\n * WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so\n * `cat .webpieces/tasks.md` at the repo root is DENIED even though that exact file is exempt from\n * every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed\n * was a git state change — strictly more destructive than the one it omitted. This class supplies the\n * missing sentence; it changes no verdict.\n *\n * A token is treated as a candidate path with no filesystem check: whether it exists says nothing\n * about whether it is exempt, and a stat per token on the blocking hook path is exactly the cost these\n * guards avoid. Non-path tokens (a `grep` pattern, a `sed` script) simply match no glob.\n */\nexport class ExcludedPathEscapeScan {\n private readonly scanner: CommandScanner;\n private readonly workspaceRoot: string;\n private readonly effectiveCwd: string;\n\n /**\n * `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the\n * same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved\n * there and ABSOLUTE ones normalised straight to workspace-relative, which is how\n * `cat /abs/path/to/repo/.webpieces/tasks.md` reaches the same verdict as `cat .webpieces/tasks.md`.\n */\n constructor(scanner: CommandScanner, workspaceRoot: string, effectiveCwd: string) {\n this.scanner = scanner;\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd;\n }\n\n /**\n * Every excluded path this command references, in command order, de-duplicated.\n *\n * Scans EVERY segment, not just a leading `cd`: `cat x`, `grep -n foo x`, `sed -n '1,5p' x` and a\n * path inside an `&&` compound all count, because the agent's next move depends on the file it\n * wanted, wherever in the line it named it.\n */\n references(command: string, ex: ExcludePaths): readonly ExcludedPathReference[] {\n if (ex.paths.length === 0) return [];\n\n const found: ExcludedPathReference[] = [];\n const seen = new Set<string>();\n for (const token of this.candidateTokens(command)) {\n const relative = this.workspaceRelative(token);\n if (relative === null || seen.has(relative)) continue;\n seen.add(relative);\n const glob = this.matchingGlob(relative, ex);\n if (glob === null) continue;\n found.push(this.reference(relative, glob, ex));\n }\n return found;\n }\n\n // Build the reference, including the `cd` target — the ONE subtle part, see cdDirectory below.\n private reference(relative: string, glob: string, ex: ExcludePaths): ExcludedPathReference {\n const dir = this.cdDirectory(relative, ex);\n return new ExcludedPathReference(\n relative, glob, dir, dir === null ? '' : path.relative(dir, relative),\n );\n }\n\n /**\n * A directory the agent may `cd` into and have the guards actually stand down, or null.\n *\n * THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles\n * `.webpieces/**` to the anchored `/^\\.webpieces\\/.*$/` — the `/` is a LITERAL, so the bare\n * directory `.webpieces` does NOT match its own glob. `cd .webpieces && cat tasks.md` is still\n * denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a\n * turn to disprove. So the directory is only offered when it passes the very same matcher the\n * runner will use, and the renderer says so plainly when nothing does.\n */\n private cdDirectory(relative: string, ex: ExcludePaths): string | null {\n const dir = path.dirname(relative);\n if (dir === '.' || dir === '' || dir === relative) return null;\n return this.matchingGlob(dir, ex) === null ? null : dir;\n }\n\n // The first configured glob this workspace-relative path satisfies, under the runner's OWN matcher\n // (globMatches, load-rules.ts) — never a looser one, or the stanza would promise an exemption the\n // guards do not grant.\n private matchingGlob(relative: string, ex: ExcludePaths): string | null {\n for (const pattern of ex.paths) {\n if (globMatches(pattern, relative)) return pattern;\n }\n return null;\n }\n\n /**\n * Workspace-relative form of a token, or null when it is not a path inside this workspace.\n *\n * `~`-rooted and out-of-tree paths are nothing to do with this repo's exclusions, and the\n * workspace root itself ('') matches no glob by construction.\n */\n private workspaceRelative(token: string): string | null {\n const cleaned = token.replace(REDIRECT_PREFIX, '');\n if (cleaned === '' || cleaned.startsWith('~')) return null;\n const absolute = path.isAbsolute(cleaned) ? cleaned : path.resolve(this.effectiveCwd, cleaned);\n const relative = path.relative(this.workspaceRoot, absolute);\n if (relative === '' || relative.startsWith('..')) return null;\n return relative;\n }\n\n /**\n * Every token that could name a file: each segment's words minus the command word itself and\n * minus flags. Deliberately generous — a token that is not a path matches no glob, while a token\n * dropped by a cleverer filter is a file the agent is never told it can read.\n */\n private candidateTokens(command: string): readonly string[] {\n const tokens: string[] = [];\n for (const segment of this.scanner.commandSegments(command)) {\n const words = this.scanner.words(segment);\n for (let i = 1; i < words.length; i++) {\n if (words[i].startsWith('-')) continue;\n tokens.push(words[i]);\n }\n }\n return tokens;\n }\n}\n\n// A redirection glued to its target (`>out.log`, `2>>err.log`, `<in.txt`) — strip the operator so the\n// target is scanned as the path it is.\nconst REDIRECT_PREFIX = /^\\d*(?:>>?|<)/;\n\n/**\n * Renders the leading stanza of a bash deny body: the Read/Write escape the agent already has, and —\n * when one genuinely exists — the `cd` that makes bash itself work.\n *\n * It goes at the TOP of the report, above the git remedies, because the agent acts on the first\n * actionable thing it reads. The live incident this fixes had the agent create a branch in a human's\n * working tree to record a row in a gitignored scratch file; the cheap, side-effect-free path was one\n * sentence away and never printed. Returns '' when the command names no excluded path, so a repo\n * without exemptions — and every command that names nothing exempt — sees no extra noise.\n */\nexport class ExcludedPathEscapeHint {\n private readonly scan: ExcludedPathEscapeScan;\n\n /** `effectiveCwd` is the directory the command really runs in — see ExcludedPathEscapeScan. */\n constructor(workspaceRoot: string, effectiveCwd: string) {\n this.scan = new ExcludedPathEscapeScan(new CommandScanner(), workspaceRoot, effectiveCwd);\n }\n\n render(command: string, ex: ExcludePaths): string {\n const references = this.scan.references(command, ex);\n if (references.length === 0) return '';\n\n const lines: string[] = [];\n lines.push('✅ YOU CAN USE THE READ/WRITE TOOLS RIGHT NOW — no git operation needed.');\n lines.push(' These paths are in excludePaths and are exempt from every guard:');\n for (const glob of ex.paths) lines.push(` ${glob}`);\n lines.push(` Your command referenced: ${references.map((r: ExcludedPathReference): string => r.referencedPath).join(', ')}`);\n // Scoped to the FILE, deliberately. The stanza fires on any rule block whose command names an\n // exempt path, and `git push … && cat .webpieces/tasks.md` is blocked for the push — for which\n // Read/Write substitutes for nothing. Claiming the remedies below were optional would be false.\n lines.push(' Read/Write/Edit reaches that file RIGHT NOW, with no git operation at all.');\n lines.push(' Anything ELSE this command does — a git/gh operation, a build — still needs the');\n lines.push(' remedies below.');\n const bash = this.bashLines(references);\n if (bash.length > 0) {\n lines.push('');\n for (const line of bash) lines.push(line);\n }\n lines.push('');\n return lines.join('\\n');\n }\n\n // The bash half: the `cd` when one matches, the honest refusal to invent one when none does, and\n // silence when there is not even a directory worth naming.\n private bashLines(references: readonly ExcludedPathReference[]): readonly string[] {\n const withCd = references.find((r: ExcludedPathReference): boolean => r.cdDirectory !== null);\n if (withCd !== undefined) return this.cdLines(withCd);\n // A workspace-ROOT-level file — matched by a file-shaped glob like `*.md` — has no directory to\n // name: `dirname` is `.`, which no excludePaths glob can usefully exempt (the relative cwd at\n // the root is '', so `.` would never match) and which reads as \"exempt the whole repo\". Say\n // nothing about bash rather than something false.\n const nested = references.find(\n (r: ExcludedPathReference): boolean => path.dirname(r.referencedPath) !== '.',\n );\n return nested === undefined ? [] : this.noCdLines(nested);\n }\n\n // A `cd` the guards will actually honour: its directory passed globMatches in the scan.\n private cdLines(withCd: ExcludedPathReference): readonly string[] {\n return [\n '✅ OR KEEP USING BASH — put a `cd` into the excluded tree FIRST:',\n ` cd ${String(withCd.cdDirectory)} && <your command, writing \\`${withCd.referencedPath}\\` as \\`${withCd.pathFromCdDirectory}\\`>`,\n ' The guard resolves a LEADING `cd` and judges that directory, so this runs.',\n ' It must be the first thing in the command: no leading VAR= assignment,',\n ' no subshell wrapper — those defeat the resolution.',\n ];\n }\n\n // No directory on the way to the file matches a glob on its own, so there is no `cd` to offer.\n // Say WHY and give the one-line config edit that would create one, rather than printing a `cd`\n // that would be denied.\n private noCdLines(first: ExcludedPathReference): readonly string[] {\n const dir = path.dirname(first.referencedPath);\n return [\n '⚠️ A `cd` CANNOT rescue bash here, so do not try one.',\n ` \\`${dir}\\` (the directory itself) matches no excludePaths glob: \\`${first.matchedGlob}\\` compiles to`,\n ' an anchored regex whose `/` is literal, so the bare directory fails it and a `cd` into',\n ' it is STILL denied. That form is deliberately not printed here — it looks right and is not.',\n ' Use Read/Write/Edit above — or, to make bash work here too, list the bare directory',\n ` alongside the glob in webpieces.config.json → excludePaths: [\"${dir}\", \"${first.matchedGlob}\"]`,\n ];\n }\n}\n"]}
|
package/src/core/l0-matrix.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { L0Call } from '../bin/shim';
|
|
|
2
2
|
import { L0FaultCode } from '@webpieces/rules-config';
|
|
3
3
|
/**
|
|
4
4
|
* The doc L0's deny messages point at. Lives in @webpieces/rules-config/templates alongside the others,
|
|
5
|
-
* and is written to <root>/.webpieces
|
|
5
|
+
* and is written to <root>/.webpieces/instruct-ai/ lazily, only on an L0 BLOCK.
|
|
6
6
|
*
|
|
7
7
|
* That generated doc is the AUTHORITY for the fault table and the allowlist (same arrays, cannot
|
|
8
8
|
* drift). guards/L0-tooling.md is the hand-written companion: it adds L0's evaluation
|
package/src/core/l0-matrix.js
CHANGED
|
@@ -24,7 +24,7 @@ const rules_config_4 = require("@webpieces/rules-config");
|
|
|
24
24
|
// ---------------------------------------------------------------------------
|
|
25
25
|
/**
|
|
26
26
|
* The doc L0's deny messages point at. Lives in @webpieces/rules-config/templates alongside the others,
|
|
27
|
-
* and is written to <root>/.webpieces
|
|
27
|
+
* and is written to <root>/.webpieces/instruct-ai/ lazily, only on an L0 BLOCK.
|
|
28
28
|
*
|
|
29
29
|
* That generated doc is the AUTHORITY for the fault table and the allowlist (same arrays, cannot
|
|
30
30
|
* drift). guards/L0-tooling.md is the hand-written companion: it adds L0's evaluation
|