@webpieces/agent-workflow-rules 0.4.927 → 0.4.928
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/hook-app-fixtures.js +3 -2
- package/src/adapters/hook-app-fixtures.js.map +1 -1
- package/src/configs/main-sync-guard-configs.js +0 -1
- package/src/configs/main-sync-guard-configs.js.map +1 -1
- package/src/configs/rule-configs.js +0 -2
- package/src/configs/rule-configs.js.map +1 -1
- package/src/core/excluded-path-escape.js +2 -2
- package/src/core/excluded-path-escape.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/agent-workflow-rules",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.928",
|
|
4
4
|
"description": "Independent workflow guards, guard hook, installation and shim management for AI coding agents.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -24,20 +24,20 @@
|
|
|
24
24
|
"directory": "packages/tooling/agent-workflow-rules"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@webpieces/hook-runtime": "0.4.
|
|
28
|
-
"@webpieces/rules-config": "0.4.
|
|
27
|
+
"@webpieces/hook-runtime": "0.4.928",
|
|
28
|
+
"@webpieces/rules-config": "0.4.928",
|
|
29
29
|
"inversify": "7.10.4",
|
|
30
30
|
"reflect-metadata": "0.2.2",
|
|
31
|
-
"@webpieces/tooling-common": "0.4.
|
|
32
|
-
"@webpieces/repo-workflow-core": "0.4.
|
|
31
|
+
"@webpieces/tooling-common": "0.4.928",
|
|
32
|
+
"@webpieces/repo-workflow-core": "0.4.928",
|
|
33
33
|
"tslib": "2.8.1",
|
|
34
|
-
"@webpieces/rules-sdk": "0.4.
|
|
34
|
+
"@webpieces/rules-sdk": "0.4.928"
|
|
35
35
|
},
|
|
36
36
|
"publishConfig": {
|
|
37
37
|
"access": "public"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@webpieces/tooling-testkit": "0.4.
|
|
40
|
+
"@webpieces/tooling-testkit": "0.4.928"
|
|
41
41
|
},
|
|
42
42
|
"types": "./src/index.d.ts",
|
|
43
43
|
"bin": {
|
|
@@ -159,7 +159,8 @@ class GoldenRepoBuilder {
|
|
|
159
159
|
.manifests()
|
|
160
160
|
.map((pack) => pack.packageName === rule_pack_1.rulePackManifest.packageName ? rule_pack_1.rulePackManifest : pack);
|
|
161
161
|
if (fixture.crashingRuntime) {
|
|
162
|
-
|
|
162
|
+
// Every rule carries the framework-owned hatches (#1253), so the client seed states them.
|
|
163
|
+
const seed = Object.assign(new rules_sdk_1.ConfigObject(), { mode: 'ON', turnOffRuleUntilEpoch: 0, turnOffRuleWhileOnBranch: null });
|
|
163
164
|
const definition = new rules_sdk_1.OwnedRuleDefinition('client-crash', { mode: new rules_sdk_1.FieldDef('string', ['ON', 'OFF']) }, 1, {}, seed, 'rules', new rules_sdk_1.RuleHelp('Client failure fixture', 'Repair {configFile}.'));
|
|
164
165
|
manifests.push(new rules_sdk_1.RulePackManifest('@client/crash', '1.0.0-fixture', 3, [definition], [
|
|
165
166
|
new rules_sdk_1.RuleContribution('client-crash', '@client/crash', 'source-hook', './crash-runtime.cjs'),
|
|
@@ -185,7 +186,7 @@ class GoldenRepoBuilder {
|
|
|
185
186
|
return this.configJson;
|
|
186
187
|
// webpieces-disable no-any-unknown -- the frozen fixture config is data on disk; re-parsing it into a named type here would be a second declaration of a file whose whole point is being literal
|
|
187
188
|
const parsed = JSON.parse(this.configJson);
|
|
188
|
-
parsed['rules']['client-crash'] = Object.assign(new rules_sdk_1.ConfigObject(), { mode: 'ON' });
|
|
189
|
+
parsed['rules']['client-crash'] = Object.assign(new rules_sdk_1.ConfigObject(), { mode: 'ON', turnOffRuleUntilEpoch: 0, turnOffRuleWhileOnBranch: null });
|
|
189
190
|
return JSON.stringify(parsed, null, 4);
|
|
190
191
|
}
|
|
191
192
|
git(repo, args) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-app-fixtures.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-app-fixtures.ts"],"names":[],"mappings":";;;;AAAA,oDAO8B;AAC9B,4CAAgD;AAChD,gEAA2D;AAC3D,gEAA0D;AAC1D,iDAAyC;AACzC,+CAAyB;AAEzB,mDAA6B;AAI7B;;;;;;;;;;;GAWG;AAEH,yFAAyF;AACzF,MAAa,aAAa;IACtB,2DAA2D;IAClD,IAAI,CAAS;IACtB,sDAAsD;IAC7C,IAAI,CAAW;IACxB;;;OAGG;IACM,KAAK,CAAS;IACvB,4FAA4F;IACnF,eAAe,CAAU;IAElC,YAAY,IAAY,EAAE,IAAc,EAAE,KAAa,EAAE,kBAA2B,KAAK;QACrF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IAC3C,CAAC;CACJ;AAnBD,sCAmBC;AAED,gGAAgG;AAChG,MAAa,eAAe;IACf,IAAI,CAAS;IACb,IAAI,CAAS;IACb,KAAK,CAAS;IAEvB,YAAY,IAAY,EAAE,IAAY,EAAE,KAAa;QACjD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAVD,0CAUC;AAED;;;;;;GAMG;AACU,QAAA,UAAU,GAAG,QAAQ,CAAC;AAEnC,MAAM,eAAe,GAAG;IACpB,eAAe,EAAE,YAAY;IAC7B,UAAU,EAAE,aAAa;IACzB,eAAe,EAAE,WAAW;IAC5B,GAAG,EAAE,kBAAU;CAClB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,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E,IAAY;QAClC,IAAA,wBAAQ,EAAC,OAAO,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;IAC7D,CAAC;CACJ;AApFD,8CAoFC","sourcesContent":["import {\n ConfigObject,\n FieldDef,\n OwnedRuleDefinition,\n RuleContribution,\n RuleHelp,\n RulePackManifest,\n} from '@webpieces/rules-sdk';\nimport { rulePackManifest } from '../rule-pack';\nimport { policyFixture } from '@webpieces/tooling-testkit';\nimport { specTempDirs } from '@webpieces/tooling-testkit';\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\nimport { HookMode } from '@webpieces/hook-runtime';\n\n/**\n * THE WIRE BYTES the golden tests drive, and the throwaway repo they are judged against.\n *\n * Everything here exists so a reader can see EXACTLY what a harness sends: the payloads are built from\n * the measured envelope key sets (see the fixture docs on GoldenFixture below), not from anything the\n * hook itself produces, and the repo is a real `git init` with a frozen webpieces.config.json rather\n * than whatever tree the suite happens to be running in. A golden computed against the live repo would\n * change verdict with the branch you are standing on.\n *\n * This is NOT a spec file, deliberately: `tsconfig.lib.json` excludes `*.spec.ts`, so a payload builder\n * living in one would never be type-checked by the build.\n */\n\n/** How one PreToolUse call is presented to the hook. Data class per CLAUDE.md rule 1. */\nexport class GoldenFixture {\n /** Stable key into `__goldens__/hook-app-goldens.json`. */\n readonly name: string;\n /** Which hook binary's mode — `guards` or `rules`. */\n readonly mode: HookMode;\n /**\n * The raw stdin bytes. A STRING, never an object, because malformed stdin is one of the fixtures\n * and a shape that cannot express \"not JSON\" would quietly drop the case that matters most.\n */\n readonly stdin: string;\n /** True ⇒ the fixture repo also gets a `rulesDir` whose one module throws when required. */\n readonly crashingRuntime: boolean;\n\n constructor(name: string, mode: HookMode, stdin: string, crashingRuntime: boolean = false) {\n this.name = name;\n this.mode = mode;\n this.stdin = stdin;\n this.crashingRuntime = crashingRuntime;\n }\n}\n\n/** A built fixture repo: where it lives, and the stdin bytes with `<REPO>` resolved into it. */\nexport class PreparedFixture {\n readonly repo: string;\n readonly root: string;\n readonly stdin: string;\n\n constructor(repo: string, root: string, stdin: string) {\n this.repo = repo;\n this.root = root;\n this.stdin = stdin;\n }\n}\n\n/**\n * The placeholder that stands for the fixture repo's absolute path, in BOTH directions: payloads are\n * written with it and it is substituted in before the run; golden bytes are compared with the real\n * path substituted back out. Guard reports legitimately name absolute paths (the git-workflow doc\n * pointer, the blocked file), and a golden that hard-coded one machine's `/var/folders/...` would be\n * a golden nobody else could run.\n */\nexport const REPO_TOKEN = '<REPO>';\n\nconst CLAUDE_ENVELOPE = {\n hook_event_name: 'PreToolUse',\n session_id: 'sess-golden',\n transcript_path: '/dev/null',\n cwd: REPO_TOKEN,\n};\n\n/**\n * The Codex additions, MEASURED from codex-cli 0.151.0: it uses Claude's key names and merely ADDS\n * `model`, `turn_id`, `tool_use_id` and `permission_mode`. `turn_id` is the one discriminator (see\n * detect-ai.ts). `agent_id` empty ⇒ the coordinator, populated ⇒ a subagent — identical semantics in\n * both harnesses.\n */\nconst CODEX_ENVELOPE = {\n ...CLAUDE_ENVELOPE,\n model: 'gpt-5-codex',\n turn_id: 'turn-golden',\n tool_use_id: 'call_1',\n permission_mode: 'default',\n agent_type: 'default',\n agent_id: '',\n};\n\n// Codex's edit tool. MEASURED: the tool is named `apply_patch`, it carries `tool_input.command` (not\n// file_path), hunk headers are a bare `@@`, and ONE patch may carry many files with mixed operations.\nconst PATCH_ADD_JS = '*** Begin Patch\\n*** Add File: src/foo.js\\n+var x = 1;\\n*** End Patch\\n';\nconst PATCH_ADD_TS =\n '*** Begin Patch\\n*** Add File: scripts/added.ts\\n+export const b = 2;\\n*** End Patch\\n';\n\n/**\n * Serializes ONE PreToolUse envelope to the bytes a harness would put on stdin. A class rather than a\n * module-scope function because that is the repo rule, and the one instance below is built at module\n * load so the fixture table can stay a plain literal list.\n */\nclass WirePayload {\n // webpieces-disable no-any-unknown -- these objects ARE the wire envelope; JSON.stringify of a plain object is the payload under test, and naming a type for it would assert a shape the fixtures exist to state literally\n write(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n envelope: Record<string, unknown>,\n toolName: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n toolInput: Record<string, unknown>,\n ): string {\n return JSON.stringify({ ...envelope, tool_name: toolName, tool_input: toolInput });\n }\n}\n\nconst WIRE = new WirePayload();\n\n/**\n * ONE fixture per row of the coverage the composed pipeline had none of before: for BOTH harnesses a\n * Bash deny (the ANSI-red systemMessage), a file-tool deny (NO systemMessage), an allow, a read-only\n * tool, malformed stdin, and a fail-closed crash.\n */\nexport const GOLDEN_FIXTURES: readonly GoldenFixture[] = [\n // ── Claude Code ────────────────────────────────────────────────────────────────────────────────\n // A Bash deny. `git merge` is blocked on every branch, so this verdict does not depend on repo\n // state — and a Bash deny is the ONE case that carries the red `systemMessage`.\n new GoldenFixture(\n 'claude/bash-deny',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'claude/bash-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // The read-only tool: log-and-allow, and the only guard that can deny it is a stale `main`.\n new GoldenFixture(\n 'claude/read-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Read', { file_path: `${REPO_TOKEN}/f.txt` }),\n ),\n // Write / Edit / MultiEdit denies — all three must emit NO systemMessage.\n new GoldenFixture('claude/malformed', 'guards', 'not json at all'),\n\n // ── Codex ──────────────────────────────────────────────────────────────────────────────────────\n new GoldenFixture(\n 'codex/bash-deny',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'codex/bash-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // Codex has no Read tool: a read arrives as `Bash` running a pager, which read parity turns into a\n // read-scoped verdict ON TOP of the bash guards.\n new GoldenFixture(\n 'codex/read-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: `sed -n '1,240p' ${REPO_TOKEN}/f.txt` }),\n ),\n new GoldenFixture('codex/malformed', 'guards', '{\"turn_id\": broken'),\n];\n\n// A rules module that blows up the moment it is required — the shortest honest way to reach the hook's\n// fail-closed boundary from OUTSIDE the hook, i.e. without stubbing anything the pipeline owns.\nconst CRASHING_RULE_MODULE = \"throw new Error('boom from a custom rule module');\\n\";\n\n/**\n * Builds ONE throwaway git repo per fixture and returns it with the payload's `<REPO>` resolved.\n *\n * A FRESH repo per fixture, not one shared: the hook writes `.webpieces/` state (the decision log, the\n * main-sync cache) as it runs, so a shared tree would let fixture N's leftovers decide fixture N+1's\n * verdict — an order-dependent suite, which is the one kind of golden test worse than none.\n *\n * `realpathSync` matters on macOS: `os.tmpdir()` hands back `/var/folders/...` which resolves to\n * `/private/var/...`, and the L1 location guard compares the payload's cwd against the resolved repo\n * root. Without it every fixture denies with \"run git from the repo root\" instead of the verdict under\n * test.\n */\nexport class GoldenRepoBuilder {\n private readonly configJson: string;\n\n constructor() {\n this.configJson = fs.readFileSync(\n path.join(__dirname, '__goldens__', 'fixture-webpieces.config.json'),\n 'utf8',\n );\n }\n\n build(fixture: GoldenFixture): PreparedFixture {\n const root = specTempDirs.makeReal('wp-hook-golden-');\n const repo = path.join(root, 'repo');\n fs.mkdirSync(repo);\n this.git(repo, 'init -q -b main');\n // The developer's own commit hooks would otherwise fire inside this throwaway repo.\n this.git(repo, 'config core.hooksPath /dev/null');\n this.git(repo, 'config user.email t@t.co');\n this.git(repo, 'config user.name tester');\n const manifests = policyFixture\n .manifests()\n .map((pack: RulePackManifest) =>\n pack.packageName === rulePackManifest.packageName ? rulePackManifest : pack,\n );\n if (fixture.crashingRuntime) {\n const seed = Object.assign(new ConfigObject(), { mode: 'ON' });\n const definition = new OwnedRuleDefinition(\n 'client-crash',\n { mode: new FieldDef('string', ['ON', 'OFF']) },\n 1,\n {},\n seed,\n 'rules',\n new RuleHelp('Client failure fixture', 'Repair {configFile}.'),\n );\n manifests.push(\n new RulePackManifest(\n '@client/crash',\n '1.0.0-fixture',\n 3,\n [definition],\n [\n new RuleContribution(\n 'client-crash',\n '@client/crash',\n 'source-hook',\n './crash-runtime.cjs',\n ),\n ],\n [],\n [],\n ),\n );\n }\n policyFixture.writeOwnerConfig(repo, JSON.parse(this.repoConfig(fixture)), manifests);\n fs.writeFileSync(path.join(repo, 'f.txt'), 'hello\\n');\n fs.mkdirSync(path.join(repo, 'scripts'));\n fs.writeFileSync(path.join(repo, 'scripts', 'ok.ts'), 'const a = 1;\\n');\n if (fixture.crashingRuntime) {\n fs.writeFileSync(path.join(repo, 'crash-runtime.cjs'), CRASHING_RULE_MODULE);\n }\n this.git(repo, 'add -A');\n this.git(repo, 'commit -qm init');\n // A local origin/main, so `origin/main..<branch>` resolves exactly as it does in a real clone.\n this.git(repo, 'update-ref refs/remotes/origin/main HEAD');\n // A feature branch, because that is where an agent actually works.\n this.git(repo, 'checkout -q -b dean/fixture');\n return new PreparedFixture(repo, root, fixture.stdin.split(REPO_TOKEN).join(repo));\n }\n\n private repoConfig(fixture: GoldenFixture): string {\n if (!fixture.crashingRuntime) return this.configJson;\n // webpieces-disable no-any-unknown -- the frozen fixture config is data on disk; re-parsing it into a named type here would be a second declaration of a file whose whole point is being literal\n const parsed = JSON.parse(this.configJson) as Record<string, unknown>;\n (parsed['rules'] as Record<string, ConfigObject>)['client-crash'] = Object.assign(\n new ConfigObject(),\n { mode: 'ON' },\n );\n return JSON.stringify(parsed, null, 4);\n }\n\n private git(repo: string, args: string): void {\n execSync(`git ${args}`, { cwd: repo, encoding: 'utf8' });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hook-app-fixtures.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-app-fixtures.ts"],"names":[],"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IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;IAC7D,CAAC;CACJ;AArFD,8CAqFC","sourcesContent":["import {\n ConfigObject,\n FieldDef,\n OwnedRuleDefinition,\n RuleContribution,\n RuleHelp,\n RulePackManifest,\n} from '@webpieces/rules-sdk';\nimport { rulePackManifest } from '../rule-pack';\nimport { policyFixture } from '@webpieces/tooling-testkit';\nimport { specTempDirs } from '@webpieces/tooling-testkit';\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\nimport { HookMode } from '@webpieces/hook-runtime';\n\n/**\n * THE WIRE BYTES the golden tests drive, and the throwaway repo they are judged against.\n *\n * Everything here exists so a reader can see EXACTLY what a harness sends: the payloads are built from\n * the measured envelope key sets (see the fixture docs on GoldenFixture below), not from anything the\n * hook itself produces, and the repo is a real `git init` with a frozen webpieces.config.json rather\n * than whatever tree the suite happens to be running in. A golden computed against the live repo would\n * change verdict with the branch you are standing on.\n *\n * This is NOT a spec file, deliberately: `tsconfig.lib.json` excludes `*.spec.ts`, so a payload builder\n * living in one would never be type-checked by the build.\n */\n\n/** How one PreToolUse call is presented to the hook. Data class per CLAUDE.md rule 1. */\nexport class GoldenFixture {\n /** Stable key into `__goldens__/hook-app-goldens.json`. */\n readonly name: string;\n /** Which hook binary's mode — `guards` or `rules`. */\n readonly mode: HookMode;\n /**\n * The raw stdin bytes. A STRING, never an object, because malformed stdin is one of the fixtures\n * and a shape that cannot express \"not JSON\" would quietly drop the case that matters most.\n */\n readonly stdin: string;\n /** True ⇒ the fixture repo also gets a `rulesDir` whose one module throws when required. */\n readonly crashingRuntime: boolean;\n\n constructor(name: string, mode: HookMode, stdin: string, crashingRuntime: boolean = false) {\n this.name = name;\n this.mode = mode;\n this.stdin = stdin;\n this.crashingRuntime = crashingRuntime;\n }\n}\n\n/** A built fixture repo: where it lives, and the stdin bytes with `<REPO>` resolved into it. */\nexport class PreparedFixture {\n readonly repo: string;\n readonly root: string;\n readonly stdin: string;\n\n constructor(repo: string, root: string, stdin: string) {\n this.repo = repo;\n this.root = root;\n this.stdin = stdin;\n }\n}\n\n/**\n * The placeholder that stands for the fixture repo's absolute path, in BOTH directions: payloads are\n * written with it and it is substituted in before the run; golden bytes are compared with the real\n * path substituted back out. Guard reports legitimately name absolute paths (the git-workflow doc\n * pointer, the blocked file), and a golden that hard-coded one machine's `/var/folders/...` would be\n * a golden nobody else could run.\n */\nexport const REPO_TOKEN = '<REPO>';\n\nconst CLAUDE_ENVELOPE = {\n hook_event_name: 'PreToolUse',\n session_id: 'sess-golden',\n transcript_path: '/dev/null',\n cwd: REPO_TOKEN,\n};\n\n/**\n * The Codex additions, MEASURED from codex-cli 0.151.0: it uses Claude's key names and merely ADDS\n * `model`, `turn_id`, `tool_use_id` and `permission_mode`. `turn_id` is the one discriminator (see\n * detect-ai.ts). `agent_id` empty ⇒ the coordinator, populated ⇒ a subagent — identical semantics in\n * both harnesses.\n */\nconst CODEX_ENVELOPE = {\n ...CLAUDE_ENVELOPE,\n model: 'gpt-5-codex',\n turn_id: 'turn-golden',\n tool_use_id: 'call_1',\n permission_mode: 'default',\n agent_type: 'default',\n agent_id: '',\n};\n\n// Codex's edit tool. MEASURED: the tool is named `apply_patch`, it carries `tool_input.command` (not\n// file_path), hunk headers are a bare `@@`, and ONE patch may carry many files with mixed operations.\nconst PATCH_ADD_JS = '*** Begin Patch\\n*** Add File: src/foo.js\\n+var x = 1;\\n*** End Patch\\n';\nconst PATCH_ADD_TS =\n '*** Begin Patch\\n*** Add File: scripts/added.ts\\n+export const b = 2;\\n*** End Patch\\n';\n\n/**\n * Serializes ONE PreToolUse envelope to the bytes a harness would put on stdin. A class rather than a\n * module-scope function because that is the repo rule, and the one instance below is built at module\n * load so the fixture table can stay a plain literal list.\n */\nclass WirePayload {\n // webpieces-disable no-any-unknown -- these objects ARE the wire envelope; JSON.stringify of a plain object is the payload under test, and naming a type for it would assert a shape the fixtures exist to state literally\n write(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n envelope: Record<string, unknown>,\n toolName: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n toolInput: Record<string, unknown>,\n ): string {\n return JSON.stringify({ ...envelope, tool_name: toolName, tool_input: toolInput });\n }\n}\n\nconst WIRE = new WirePayload();\n\n/**\n * ONE fixture per row of the coverage the composed pipeline had none of before: for BOTH harnesses a\n * Bash deny (the ANSI-red systemMessage), a file-tool deny (NO systemMessage), an allow, a read-only\n * tool, malformed stdin, and a fail-closed crash.\n */\nexport const GOLDEN_FIXTURES: readonly GoldenFixture[] = [\n // ── Claude Code ────────────────────────────────────────────────────────────────────────────────\n // A Bash deny. `git merge` is blocked on every branch, so this verdict does not depend on repo\n // state — and a Bash deny is the ONE case that carries the red `systemMessage`.\n new GoldenFixture(\n 'claude/bash-deny',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'claude/bash-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // The read-only tool: log-and-allow, and the only guard that can deny it is a stale `main`.\n new GoldenFixture(\n 'claude/read-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Read', { file_path: `${REPO_TOKEN}/f.txt` }),\n ),\n // Write / Edit / MultiEdit denies — all three must emit NO systemMessage.\n new GoldenFixture('claude/malformed', 'guards', 'not json at all'),\n\n // ── Codex ──────────────────────────────────────────────────────────────────────────────────────\n new GoldenFixture(\n 'codex/bash-deny',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'codex/bash-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // Codex has no Read tool: a read arrives as `Bash` running a pager, which read parity turns into a\n // read-scoped verdict ON TOP of the bash guards.\n new GoldenFixture(\n 'codex/read-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: `sed -n '1,240p' ${REPO_TOKEN}/f.txt` }),\n ),\n new GoldenFixture('codex/malformed', 'guards', '{\"turn_id\": broken'),\n];\n\n// A rules module that blows up the moment it is required — the shortest honest way to reach the hook's\n// fail-closed boundary from OUTSIDE the hook, i.e. without stubbing anything the pipeline owns.\nconst CRASHING_RULE_MODULE = \"throw new Error('boom from a custom rule module');\\n\";\n\n/**\n * Builds ONE throwaway git repo per fixture and returns it with the payload's `<REPO>` resolved.\n *\n * A FRESH repo per fixture, not one shared: the hook writes `.webpieces/` state (the decision log, the\n * main-sync cache) as it runs, so a shared tree would let fixture N's leftovers decide fixture N+1's\n * verdict — an order-dependent suite, which is the one kind of golden test worse than none.\n *\n * `realpathSync` matters on macOS: `os.tmpdir()` hands back `/var/folders/...` which resolves to\n * `/private/var/...`, and the L1 location guard compares the payload's cwd against the resolved repo\n * root. Without it every fixture denies with \"run git from the repo root\" instead of the verdict under\n * test.\n */\nexport class GoldenRepoBuilder {\n private readonly configJson: string;\n\n constructor() {\n this.configJson = fs.readFileSync(\n path.join(__dirname, '__goldens__', 'fixture-webpieces.config.json'),\n 'utf8',\n );\n }\n\n build(fixture: GoldenFixture): PreparedFixture {\n const root = specTempDirs.makeReal('wp-hook-golden-');\n const repo = path.join(root, 'repo');\n fs.mkdirSync(repo);\n this.git(repo, 'init -q -b main');\n // The developer's own commit hooks would otherwise fire inside this throwaway repo.\n this.git(repo, 'config core.hooksPath /dev/null');\n this.git(repo, 'config user.email t@t.co');\n this.git(repo, 'config user.name tester');\n const manifests = policyFixture\n .manifests()\n .map((pack: RulePackManifest) =>\n pack.packageName === rulePackManifest.packageName ? rulePackManifest : pack,\n );\n if (fixture.crashingRuntime) {\n // Every rule carries the framework-owned hatches (#1253), so the client seed states them.\n const seed = Object.assign(new ConfigObject(), { mode: 'ON', turnOffRuleUntilEpoch: 0, turnOffRuleWhileOnBranch: null });\n const definition = new OwnedRuleDefinition(\n 'client-crash',\n { mode: new FieldDef('string', ['ON', 'OFF']) },\n 1,\n {},\n seed,\n 'rules',\n new RuleHelp('Client failure fixture', 'Repair {configFile}.'),\n );\n manifests.push(\n new RulePackManifest(\n '@client/crash',\n '1.0.0-fixture',\n 3,\n [definition],\n [\n new RuleContribution(\n 'client-crash',\n '@client/crash',\n 'source-hook',\n './crash-runtime.cjs',\n ),\n ],\n [],\n [],\n ),\n );\n }\n policyFixture.writeOwnerConfig(repo, JSON.parse(this.repoConfig(fixture)), manifests);\n fs.writeFileSync(path.join(repo, 'f.txt'), 'hello\\n');\n fs.mkdirSync(path.join(repo, 'scripts'));\n fs.writeFileSync(path.join(repo, 'scripts', 'ok.ts'), 'const a = 1;\\n');\n if (fixture.crashingRuntime) {\n fs.writeFileSync(path.join(repo, 'crash-runtime.cjs'), CRASHING_RULE_MODULE);\n }\n this.git(repo, 'add -A');\n this.git(repo, 'commit -qm init');\n // A local origin/main, so `origin/main..<branch>` resolves exactly as it does in a real clone.\n this.git(repo, 'update-ref refs/remotes/origin/main HEAD');\n // A feature branch, because that is where an agent actually works.\n this.git(repo, 'checkout -q -b dean/fixture');\n return new PreparedFixture(repo, root, fixture.stdin.split(REPO_TOKEN).join(repo));\n }\n\n private repoConfig(fixture: GoldenFixture): string {\n if (!fixture.crashingRuntime) return this.configJson;\n // webpieces-disable no-any-unknown -- the frozen fixture config is data on disk; re-parsing it into a named type here would be a second declaration of a file whose whole point is being literal\n const parsed = JSON.parse(this.configJson) as Record<string, unknown>;\n (parsed['rules'] as Record<string, ConfigObject>)['client-crash'] = Object.assign(\n new ConfigObject(),\n { mode: 'ON', turnOffRuleUntilEpoch: 0, turnOffRuleWhileOnBranch: null },\n );\n return JSON.stringify(parsed, null, 4);\n }\n\n private git(repo: string, args: string): void {\n execSync(`git ${args}`, { cwd: repo, encoding: 'utf8' });\n }\n}\n"]}
|
|
@@ -47,7 +47,6 @@ class BranchStateGuardConfig extends rules_sdk_1.BaseRuleConfig {
|
|
|
47
47
|
branchNamingConvention: rules_sdk_1.FieldDef.optional('string'),
|
|
48
48
|
hangTimeoutMinutes: rules_sdk_1.FieldDef.optional('number'),
|
|
49
49
|
maxCommitsBehind: new rules_sdk_1.FieldDef('number'),
|
|
50
|
-
...rules_sdk_1.BASE_RULE_SCHEMA,
|
|
51
50
|
};
|
|
52
51
|
}
|
|
53
52
|
exports.BranchStateGuardConfig = BranchStateGuardConfig;
|
|
@@ -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,
|
|
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,oDAA6E;AAC7E,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;KAC3C,CAAC;;AAjBN,wDAkBC","sourcesContent":["import { FieldDef, SchemaShape, BaseRuleConfig } 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 };\n}\n"]}
|
|
@@ -53,7 +53,6 @@ class BranchCreationGuardConfig extends rules_sdk_2.BaseRuleConfig {
|
|
|
53
53
|
maxLocalBranches: rules_sdk_3.FieldDef.optional('number'),
|
|
54
54
|
maxWorktrees: rules_sdk_3.FieldDef.optional('number'),
|
|
55
55
|
autoReapMergedBranches: new rules_sdk_3.FieldDef('boolean'),
|
|
56
|
-
...rules_sdk_2.BASE_RULE_SCHEMA,
|
|
57
56
|
};
|
|
58
57
|
}
|
|
59
58
|
exports.BranchCreationGuardConfig = BranchCreationGuardConfig;
|
|
@@ -89,7 +88,6 @@ exports.BranchCreationGuardConfig = BranchCreationGuardConfig;
|
|
|
89
88
|
class PrLifecycleGuardConfig extends rules_sdk_2.BaseRuleConfig {
|
|
90
89
|
static SCHEMA = {
|
|
91
90
|
mode: new rules_sdk_3.FieldDef('string', rules_sdk_1.ON_OFF_MODES),
|
|
92
|
-
...rules_sdk_2.BASE_RULE_SCHEMA,
|
|
93
91
|
};
|
|
94
92
|
}
|
|
95
93
|
exports.PrLifecycleGuardConfig = PrLifecycleGuardConfig;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rule-configs.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/configs/rule-configs.ts"],"names":[],"mappings":";;;AAAA,oDAA+D;AAC/D,
|
|
1
|
+
{"version":3,"file":"rule-configs.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/configs/rule-configs.ts"],"names":[],"mappings":";;;AAAA,oDAA+D;AAC/D,oDAAsD;AACtD,oDAA6D;AAC7D,uFAAuF;AACvF,2FAA2F;AAC3F,+FAA+F;AAC/F,wDAAwD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AC,QAAQ,EAAE,wBAAY,CAAC;KAC7C,CAAC;;AALN,wDAMC","sourcesContent":["import { OnOffMode, ON_OFF_MODES } from \"@webpieces/rules-sdk\";\nimport { BaseRuleConfig } from \"@webpieces/rules-sdk\";\nimport { FieldDef, SchemaShape } from \"@webpieces/rules-sdk\";\n// branch-creation-guard modes. ON_NO_SUBBRANCHES is the strict variant: it hard-blocks\n// creating a branch off any non-main branch (no sub-branch affordance), pointing the agent\n// back to `git checkout main && git pull && git checkout -b <branch>`. Temporarily overridable\n// via the universal turnOffRuleUntilEpoch escape hatch.\nexport const BRANCH_GUARD_MODES = ['ON', 'OFF', 'ON_NO_SUBBRANCHES'] as const;\n\nexport type BranchGuardMode = typeof BRANCH_GUARD_MODES[number];\n\nexport class BranchCreationGuardConfig extends BaseRuleConfig {\n declare mode?: BranchGuardMode;\n // Naming pattern for stacked SUB-branches only (branches created off another feature branch,\n // which require human approval). Never applied to branches created off main.\n //\n // Schema-REQUIRED (#1017), like `mode` and `autoReapMergedBranches`, and for the same reason: it\n // is BEHAVIOUR, not a knob. This string decides which branch names the guard BLOCKS, and the\n // refusal quotes it back at the agent as the convention to follow — so a repo running webpieces'\n // shipped value is a repo whose branch-naming convention was chosen by a framework author who\n // never saw it. TS-optional but schema-required, the split `mode` uses: absent at RUNTIME means\n // the config never passed validation.\n subBranchNaming!: string;\n // Human-sentence instruction telling the AI how to name a NEW branch off main. Surfaced back\n // to the agent in the guard's fix hints. May mirror no-edit-on-main.branchNamingConvention.\n branchFormat?: string;\n // Hard cap on local feature branches (excluding main). Creating one past the cap is BLOCKED until\n // already-merged branches are reaped, which is what keeps the branch list from growing without\n // bound. Branch creation is the gate because it is the only moment cleanup is both cheap and\n // obviously worth it. See merged-branches.ts for how \"already merged\" is determined.\n maxLocalBranches?: number;\n // Hard cap on LINKED worktrees (the primary clone is never counted). A separate budget from\n // maxLocalBranches: every worktree holds a branch, so if worktree-held branches also spent the\n // branch budget, five worktrees would leave room for zero branches. Held branches count here;\n // parked branches count against maxLocalBranches. Enforced at `git worktree add`.\n maxWorktrees?: number;\n // Let the detached background refresher DELETE dead branches on its own, instead of only\n // reporting them. Every candidate is provably dead (a MERGED PR — its own, or the PR of the branch\n // it snapshots; nothing else qualifies) and\n // recoverable by the SHA logged to branch-mutations.log — but it is still UNATTENDED deletion,\n // so this is schema-REQUIRED like `mode` and `turnOffRuleUntilEpoch`. \"Every built-in rule\n // must be explicitly configured — no silent defaults\" (validate-config.ts) applies with extra\n // force here: branches disappearing on a preference nobody ever stated is precisely the kind of\n // default that must not exist. Validation makes each consumer answer the question once.\n //\n // TS-optional but schema-required — the same split `mode` uses. Absent at RUNTIME therefore means\n // the config never passed validation, and the only safe reading of \"nobody has answered\" is: do\n // not delete anything.\n autoReapMergedBranches?: boolean;\n\n static readonly SCHEMA: SchemaShape<BranchCreationGuardConfig> = {\n mode: new FieldDef('string', BRANCH_GUARD_MODES),\n subBranchNaming: new FieldDef('string'),\n branchFormat: FieldDef.optional('string'),\n maxLocalBranches: FieldDef.optional('number'),\n maxWorktrees: FieldDef.optional('number'),\n autoReapMergedBranches: new FieldDef('boolean'),\n };\n}\n\n/**\n * `pr-lifecycle-guard` — ONE key, ONE policy: *PRs and merges go through the gated flow.*\n *\n * Four CLASSES implement it, and their names are unchanged (they are the operator identity every\n * decision-log line and every deny report carries):\n *\n * pr-creation-or-push-guard a manual `git push` / `gh pr create|edit` / a raw pulls API call\n * merge-in-progress-guard a PR command while a 3-point merge is half-finished\n * pr-merge-guard a bare `gh pr merge`\n * redirect-how-to-merge-main \"how do I get main into my branch?\" → the documented flow\n *\n * ## Say this out loud: `\"mode\": \"OFF\"` releases the unvalidated-merge gate too\n *\n * Three of the four are pure COMMAND-SHAPE blocks and can never fire spuriously. The fourth,\n * merge-in-progress-guard, is STATE-conditional — it fires only while a 3-point merge is actually in\n * progress, and it is the one state L2 explicitly stands down for. So turning this key OFF to unblock\n * `gh pr merge` ALSO drops the \"you have an unfinished merge\" gate. That is the honest cost of one key\n * per policy, and it is stated here, in guards/L4-pr-lifecycle.md, and in the error path, rather than\n * being papered over with a granular sub-mode (which would be four knobs wearing one key's name).\n *\n * ## The command strings are NOT here\n *\n * `upsertPrCommand` and `mergeCompleteCommand` used to sit on the two guards, and — being read at the\n * point of use — they BEAT `commands.guardHints`, so `guardHintsWhy`'s claim that renaming a gated\n * command there makes \"every guard message follow\" was simply false. They are DELETED, not deprecated.\n * `commands.guardHints.prCreationOrPush` / `.mergeInProgress` is the one place those strings live, and\n * the loader hands the resolved values to the two rules directly. A consumer that still sets the old\n * per-guard field gets a RETIRED_FIELD_HINTS error naming the destination.\n */\nexport class PrLifecycleGuardConfig extends BaseRuleConfig {\n declare mode?: OnOffMode;\n\n static readonly SCHEMA: SchemaShape<PrLifecycleGuardConfig> = {\n mode: new FieldDef('string', ON_OFF_MODES),\n };\n}\n"]}
|
|
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.ExcludedPathEscapeHint = exports.ExcludedPathEscapeScan = exports.ExcludedPathReference = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const path = tslib_1.__importStar(require("path"));
|
|
6
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
6
7
|
const hook_runtime_1 = require("@webpieces/hook-runtime");
|
|
7
|
-
const hook_runtime_2 = require("@webpieces/hook-runtime");
|
|
8
8
|
/**
|
|
9
9
|
* One path the denied command NAMED that `excludePaths` already exempts, plus how to reach it.
|
|
10
10
|
*
|
|
@@ -110,7 +110,7 @@ class ExcludedPathEscapeScan {
|
|
|
110
110
|
// guards do not grant.
|
|
111
111
|
matchingGlob(relative, ex) {
|
|
112
112
|
for (const pattern of ex.paths) {
|
|
113
|
-
if ((0,
|
|
113
|
+
if ((0, rules_config_1.globMatches)(pattern, relative))
|
|
114
114
|
return pattern;
|
|
115
115
|
}
|
|
116
116
|
return null;
|
|
@@ -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,QAAQ,GAAG,IAAI,CAAC,iBAAiB,CAAC,KAAK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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"]}
|
|
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;AAE7B,0DAAoE;AAEpE,0DAAyD;AAEzD;;;;;;;;;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,QAAQ,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C3E,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, globMatches } from '@webpieces/rules-config';\n\nimport { CommandScanner } 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"]}
|