@webpieces/hook-runtime 0.4.942 → 0.4.944
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 +5 -5
- package/src/adapters/agent-payload.d.ts +2 -0
- package/src/adapters/agent-payload.js.map +1 -1
- package/src/adapters/claude-code-adapter.js +3 -3
- package/src/adapters/claude-code-adapter.js.map +1 -1
- package/src/core/apply-patch-parse.js +6 -3
- package/src/core/apply-patch-parse.js.map +1 -1
- package/src/core/build-context.js +2 -1
- package/src/core/build-context.js.map +1 -1
- package/src/core/proposed-file.d.ts +33 -0
- package/src/core/proposed-file.js +118 -0
- package/src/core/proposed-file.js.map +1 -0
- package/src/core/rule-evaluation.js +6 -0
- package/src/core/rule-evaluation.js.map +1 -1
- package/src/core/types.d.ts +3 -1
- package/src/core/types.js +3 -1
- package/src/core/types.js.map +1 -1
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
- package/src/index.js.map +1 -1
- package/src/protocol.d.ts +3 -1
- package/src/protocol.js +8 -2
- package/src/protocol.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/hook-runtime",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.944",
|
|
4
4
|
"description": "Agent hook protocol, normalized events, and fail-closed application boundary.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -22,16 +22,16 @@
|
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"inversify": "7.10.4",
|
|
24
24
|
"reflect-metadata": "0.2.2",
|
|
25
|
-
"@webpieces/rules-config": "0.4.
|
|
26
|
-
"@webpieces/tooling-common": "0.4.
|
|
25
|
+
"@webpieces/rules-config": "0.4.944",
|
|
26
|
+
"@webpieces/tooling-common": "0.4.944",
|
|
27
27
|
"tslib": "2.8.1",
|
|
28
|
-
"@webpieces/rules-sdk": "0.4.
|
|
28
|
+
"@webpieces/rules-sdk": "0.4.944"
|
|
29
29
|
},
|
|
30
30
|
"publishConfig": {
|
|
31
31
|
"access": "public"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
|
-
"@webpieces/tooling-testkit": "0.4.
|
|
34
|
+
"@webpieces/tooling-testkit": "0.4.944"
|
|
35
35
|
},
|
|
36
36
|
"types": "./src/index.d.ts"
|
|
37
37
|
}
|
|
@@ -27,12 +27,14 @@ export interface AgentToolInput {
|
|
|
27
27
|
content?: string;
|
|
28
28
|
old_string?: string;
|
|
29
29
|
new_string?: string;
|
|
30
|
+
replace_all?: boolean;
|
|
30
31
|
edits?: AgentEditEntry[];
|
|
31
32
|
command?: string;
|
|
32
33
|
}
|
|
33
34
|
export interface AgentEditEntry {
|
|
34
35
|
old_string?: string;
|
|
35
36
|
new_string?: string;
|
|
37
|
+
replace_all?: boolean;
|
|
36
38
|
}
|
|
37
39
|
export declare class AgentPayloadParser {
|
|
38
40
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-payload.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/adapters/agent-payload.ts"],"names":[],"mappings":";;;AAAA,8DAA0D;AAC1D,iEAA6D;
|
|
1
|
+
{"version":3,"file":"agent-payload.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/adapters/agent-payload.ts"],"names":[],"mappings":";;;AAAA,8DAA0D;AAC1D,iEAA6D;AA2C7D,MAAa,kBAAkB;IAC3B;;;;;;;;OAQG;IACH,KAAK,CAAC,GAAW;QACb,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE;YAAE,OAAO,IAAI,CAAC;QAC3C,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAiB,CAAC;QAC3C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,MAAM,IAAI,8BAAa,CAAC,gDAAgD,KAAK,CAAC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/G,CAAC;IACL,CAAC;CACJ;AApBD,gDAoBC","sourcesContent":["import { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * The RAW PreToolUse wire envelope, as it arrives on stdin.\n *\n * ONE shape for both harnesses, because that is what was measured: Codex uses the SAME key names as\n * Claude Code (`hook_event_name`, `tool_name`, `tool_input`, `cwd`, `session_id`, `transcript_path`,\n * `agent_id`, `agent_type`) and merely ADDS `model`, `turn_id` and `tool_use_id`. A second payload\n * type for the second harness would be two spellings of one thing.\n *\n * Interfaces, not classes, and deliberately so: nothing in this codebase ever CONSTRUCTS one of these.\n * They describe bytes somebody else wrote, which `JSON.parse` hands back as a plain object — the same\n * reason the shape this replaces was an interface.\n */\nexport interface AgentPayload {\n tool_name: string;\n tool_input: AgentToolInput;\n /** The session's current working directory. Used to scope guards to the tree the agent is in. */\n cwd?: string;\n session_id?: string;\n /** Empty/absent ⇒ the coordinator, populated ⇒ a subagent. MEASURED identical in both harnesses. */\n agent_id?: string;\n agent_type?: string;\n /** Codex-only, and REQUIRED there. The one discriminator — see ./detect-ai.ts. */\n turn_id?: string;\n}\n\nexport interface AgentToolInput {\n file_path?: string;\n content?: string;\n old_string?: string;\n new_string?: string;\n replace_all?: boolean;\n edits?: AgentEditEntry[];\n command?: string;\n}\n\nexport interface AgentEditEntry {\n old_string?: string;\n new_string?: string;\n replace_all?: boolean;\n}\n\nexport class AgentPayloadParser {\n /**\n * Returns null for empty stdin (nothing to judge); throws InformAiError on unparseable bytes.\n *\n * The message still names Claude Code even though this path is shared, and that is DELIBERATE and\n * temporary: the overriding constraint on this change is that no Claude Code behaviour moves, and a\n * user-visible string is behaviour. Renaming it is a one-line follow-up once the Codex path is\n * actually armed (it cannot mislead anyone before then — no Codex session reaches this code until\n * the installer lands).\n */\n parse(raw: string): AgentPayload | null {\n if (!raw || raw.trim() === '') return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(raw) as AgentPayload;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Malformed hook input from Claude Code stdin: ${error.message}`, { cause: error });\n }\n }\n}\n"]}
|
|
@@ -55,13 +55,13 @@ class ClaudeCodeAdapter {
|
|
|
55
55
|
if (!filePath)
|
|
56
56
|
return [];
|
|
57
57
|
if (toolKind === 'Write') {
|
|
58
|
-
return [new protocol_1.FileOperation(toolKind, new protocol_2.NormalizedToolInput(filePath, [new protocol_2.NormalizedEdit('', toolInput.content || '')]))];
|
|
58
|
+
return [new protocol_1.FileOperation(toolKind, new protocol_2.NormalizedToolInput(filePath, [new protocol_2.NormalizedEdit('', toolInput.content || '', false)]))];
|
|
59
59
|
}
|
|
60
60
|
if (toolKind === 'Edit') {
|
|
61
|
-
return [new protocol_1.FileOperation(toolKind, new protocol_2.NormalizedToolInput(filePath, [new protocol_2.NormalizedEdit(toolInput.old_string || '', toolInput.new_string || '')]))];
|
|
61
|
+
return [new protocol_1.FileOperation(toolKind, new protocol_2.NormalizedToolInput(filePath, [new protocol_2.NormalizedEdit(toolInput.old_string || '', toolInput.new_string || '', toolInput.replace_all === true)]))];
|
|
62
62
|
}
|
|
63
63
|
const raw = Array.isArray(toolInput.edits) ? toolInput.edits : [];
|
|
64
|
-
const edits = raw.map((e) => new protocol_2.NormalizedEdit(e.old_string || '', e.new_string || ''));
|
|
64
|
+
const edits = raw.map((e) => new protocol_2.NormalizedEdit(e.old_string || '', e.new_string || '', e.replace_all === true));
|
|
65
65
|
return [new protocol_1.FileOperation(toolKind, new protocol_2.NormalizedToolInput(filePath, edits))];
|
|
66
66
|
}
|
|
67
67
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-code-adapter.js","sourceRoot":"","sources":["../../../../../../packages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D,MAAM,SAAS,GAAmB,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;QAC3F,OAAO,IAAI,yBAAc,CACrB,aAAa,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAC3C,GAAG,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE,EAAE,OAAO,CAAC,QAAQ,IAAI,EAAE,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE,EAC/E,KAAK,EAAE,IAAI,EAAE,KAAK,CACrB,CAAC;IACN,CAAC;IAEO,MAAM,CAAC,QAAgB;QAC3B,IAAI,QAAQ,KAAK,MAAM;YAAE,OAAO,MAAM,CAAC;QACvC,IAAI,QAAQ,KAAK,MAAM;YAAE,OAAO,MAAM,CAAC;QACvC,IAAI,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,OAAO,MAAM,CAAC;QACpD,OAAO,SAAS,CAAC;IACrB,CAAC;IAEO,cAAc,CAAC,QAAkB,EAAE,SAAyB;QAChE,MAAM,QAAQ,GAAG,SAAS,CAAC,SAAS,CAAC;QACrC,IAAI,CAAC,QAAQ;YAAE,OAAO,EAAE,CAAC;QACzB,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;YACvB,OAAO,CAAC,IAAI,wBAAa,CAAC,QAAQ,EAAE,IAAI,8BAAmB,CAAC,QAAQ,EAAE,CAAC,IAAI,yBAAc,CAAC,EAAE,EAAE,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"claude-code-adapter.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/adapters/claude-code-adapter.ts"],"names":[],"mappings":";;;AACA,0CAA4E;AAC5E,0CAAiG;AAEjG;;;GAGG;AACH,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAA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,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAClE,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAiB,EAAkB,EAAE,CAAC,IAAI,yBAAc,CAAC,CAAC,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC;QACjJ,OAAO,CAAC,IAAI,wBAAa,CAAC,QAAQ,EAAE,IAAI,8BAAmB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IACnF,CAAC;CACJ;AAtDD,8CAsDC","sourcesContent":["import { AgentPayload, AgentToolInput, AgentEditEntry } from './agent-payload';\nimport { AgentHookEvent, AgentEventKind, FileOperation } from '../protocol';\nimport { NormalizedBashInput, NormalizedEdit, NormalizedToolInput, ToolKind } from '../protocol';\n\n/**\n * The Claude Code tools that enter the file/edit rule pipeline. `Read` is deliberately NOT here — it\n * has its own fast path and only one guard may see it.\n */\nconst HANDLED_FILE_TOOLS: ReadonlySet<string> = new Set(['Write', 'Edit', 'MultiEdit']);\n\n/**\n * Morphs a Claude Code PreToolUse payload into the one normalized `AgentHookEvent`.\n *\n * This is the SAME `normalizeToolKind` / `normalizeToolInput` logic that used to live inline in\n * hook-core.ts, moved out unchanged so hook-core is written once for every harness. Claude Code is the\n * harness every developer uses today, so nothing about the mapping is allowed to move: `Write` still\n * becomes one edit of `content` against '', `Edit` one edit of `old_string`→`new_string`, `MultiEdit`\n * one per entry, and a file tool with no `file_path` still ends up allowed (kind `Ignored`).\n */\nexport class ClaudeCodeAdapter {\n /**\n * What is known from the ENVELOPE ALONE, touching nothing but `tool_name` and the identity fields.\n *\n * Not a second spelling of `toEvent` — a different question, asked at a moment when the answer to\n * the other one may not exist. `toEvent` reads `tool_input`, and a payload whose `tool_input` is\n * missing makes it throw; the crash then still has to be DENIED, and the deny still has to know\n * whether it is decorating a Bash block (which needs the red `systemMessage`) or a file block\n * (which does not). This is the shape that answers that, and it cannot fail.\n */\n envelope(payload: AgentPayload): AgentHookEvent {\n return new AgentHookEvent(\n 'claude-code', this.kindOf(payload.tool_name), payload.tool_name,\n payload.cwd ?? '', payload.session_id ?? '', payload.agent_id ?? '', payload.agent_type ?? '',\n [], null, [],\n );\n }\n\n toEvent(payload: AgentPayload, cwd: string): AgentHookEvent {\n const kind = this.kindOf(payload.tool_name);\n const toolInput = payload.tool_input;\n const bash = kind === 'Bash' ? new NormalizedBashInput(toolInput.command ?? '') : null;\n const reads = kind === 'Read' ? [toolInput.file_path ?? ''] : [];\n const files = kind === 'File' ? this.fileOperations(payload.tool_name as ToolKind, toolInput) : [];\n // A file tool that named no file has nothing to judge; fall back to Ignored so the hook allows\n // it, exactly as the old `if (!input) emitAllow()` did.\n const effective: AgentEventKind = kind === 'File' && files.length === 0 ? 'Ignored' : kind;\n return new AgentHookEvent(\n 'claude-code', effective, payload.tool_name,\n cwd, payload.session_id ?? '', payload.agent_id ?? '', payload.agent_type ?? '',\n files, bash, reads,\n );\n }\n\n private kindOf(toolName: string): AgentEventKind {\n if (toolName === 'Bash') return 'Bash';\n if (toolName === 'Read') return 'Read';\n if (HANDLED_FILE_TOOLS.has(toolName)) return 'File';\n return 'Ignored';\n }\n\n private fileOperations(toolKind: ToolKind, toolInput: AgentToolInput): readonly FileOperation[] {\n const filePath = toolInput.file_path;\n if (!filePath) return [];\n if (toolKind === 'Write') {\n return [new FileOperation(toolKind, new NormalizedToolInput(filePath, [new NormalizedEdit('', toolInput.content || '', false)]))];\n }\n if (toolKind === 'Edit') {\n return [new FileOperation(toolKind, new NormalizedToolInput(filePath, [new NormalizedEdit(toolInput.old_string || '', toolInput.new_string || '', toolInput.replace_all === true)]))];\n }\n const raw = Array.isArray(toolInput.edits) ? toolInput.edits : [];\n const edits = raw.map((e: AgentEditEntry): NormalizedEdit => new NormalizedEdit(e.old_string || '', e.new_string || '', e.replace_all === true));\n return [new FileOperation(toolKind, new NormalizedToolInput(filePath, edits))];\n }\n}\n"]}
|
|
@@ -85,7 +85,7 @@ class ApplyPatchParser {
|
|
|
85
85
|
content.push(line.slice(1));
|
|
86
86
|
index += 1;
|
|
87
87
|
}
|
|
88
|
-
ops.push(new protocol_1.FileOperation('Write', new protocol_2.NormalizedToolInput(filePath, [new protocol_2.NormalizedEdit('', content.join('\n'))])));
|
|
88
|
+
ops.push(new protocol_1.FileOperation('Write', new protocol_2.NormalizedToolInput(filePath, [new protocol_2.NormalizedEdit('', content.join('\n'), false)])));
|
|
89
89
|
return index;
|
|
90
90
|
}
|
|
91
91
|
/**
|
|
@@ -98,6 +98,7 @@ class ApplyPatchParser {
|
|
|
98
98
|
parseUpdate(body, start, cwd, ops) {
|
|
99
99
|
let index = start + 1;
|
|
100
100
|
let filePath = this.resolve(body[start].slice(UPDATE_FILE.length), cwd);
|
|
101
|
+
const sourcePath = filePath;
|
|
101
102
|
if (index < body.length && body[index].startsWith(MOVE_TO)) {
|
|
102
103
|
filePath = this.resolve(body[index].slice(MOVE_TO.length), cwd);
|
|
103
104
|
index += 1;
|
|
@@ -135,12 +136,14 @@ class ApplyPatchParser {
|
|
|
135
136
|
}
|
|
136
137
|
index += 1;
|
|
137
138
|
}
|
|
138
|
-
edits.push(new protocol_2.NormalizedEdit(oldLines.join('\n'), newLines.join('\n')));
|
|
139
|
+
edits.push(new protocol_2.NormalizedEdit(oldLines.join('\n'), newLines.join('\n'), false));
|
|
139
140
|
}
|
|
140
141
|
if (edits.length === 0) {
|
|
141
142
|
throw new tooling_common_1.InformAiError(`[apply-patch] '${UPDATE_FILE.trim()}' section for ${filePath} carries no '@@' hunk — refusing to allow an edit whose content could not be read.`);
|
|
142
143
|
}
|
|
143
|
-
|
|
144
|
+
const input = new protocol_2.NormalizedToolInput(filePath, edits);
|
|
145
|
+
input.sourcePath = sourcePath;
|
|
146
|
+
ops.push(new protocol_1.FileOperation('Edit', input));
|
|
144
147
|
return index;
|
|
145
148
|
}
|
|
146
149
|
resolve(rawPath, cwd) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply-patch-parse.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/apply-patch-parse.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAE7B,0CAA4C;AAC5C,0CAAkE;AAClE,8DAA0D;AAE1D,MAAM,WAAW,GAAG,iBAAiB,CAAC;AACtC,MAAM,SAAS,GAAG,eAAe,CAAC;AAClC,MAAM,QAAQ,GAAG,gBAAgB,CAAC;AAClC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,OAAO,GAAG,eAAe,CAAC;AAChC,MAAM,WAAW,GAAG,IAAI,CAAC;AAEzB;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,gBAAgB;IACzB,KAAK,CAAC,OAAe,EAAE,GAAW;QAC9B,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,WAAW,CAAC,CAAC;QAChF,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACZ,MAAM,IAAI,8BAAa,CAAC,kCAAkC,WAAW,oEAAoE,CAAC,CAAC;QAC/I,CAAC;QACD,MAAM,GAAG,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,SAAS,CAAC,CAAC;QAC5E,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,KAAK,EAAE,CAAC;YACzB,MAAM,IAAI,8BAAa,CAAC,kCAAkC,SAAS,iBAAiB,WAAW,0CAA0C,CAAC,CAAC;QAC/I,CAAC;QAED,MAAM,IAAI,GAAG,KAA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B,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAC9E,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,OAAO,CAAC,OAAe,EAAE,GAAW;QACxC,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC/B,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,8BAAa,CAAC,qDAAqD,CAAC,CAAC;QACnF,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;CACJ;AAhHD,4CAgHC","sourcesContent":["import * as path from 'path';\n\nimport { FileOperation } from '../protocol';\nimport { NormalizedEdit, NormalizedToolInput } from '../protocol';\nimport { InformAiError } from '@webpieces/tooling-common';\n\nconst BEGIN_PATCH = '*** Begin Patch';\nconst END_PATCH = '*** End Patch';\nconst ADD_FILE = '*** Add File: ';\nconst UPDATE_FILE = '*** Update File: ';\nconst DELETE_FILE = '*** Delete File: ';\nconst MOVE_TO = '*** Move to: ';\nconst HUNK_HEADER = '@@';\n\n/**\n * Parses Codex's `apply_patch` envelope into the same `FileOperation[]` the rest of the hook already\n * understands, so a Codex edit is judged by the identical rules a Claude edit is.\n *\n * The grammar is MEASURED from a live codex-cli 0.151.0 session, not inferred from a diff format it\n * resembles. Two properties of it drive every design choice here:\n *\n * - ONE envelope carries MANY files with MIXED operations, which is why the result is a LIST of\n * `FileOperation` (each with its own kind) rather than one kind for the call.\n * - Hunk headers are a BARE `@@` with NO line numbers. A unified-diff `@@ -1,3 +1,4 @@` is therefore\n * not a stricter spelling of the same thing — it is an envelope we have never seen, and guessing at\n * it is how a guard silently judges the wrong bytes. It is rejected.\n *\n * Paths are sometimes relative and sometimes absolute (measured: subagents used relative, the\n * coordinator absolute), so a relative path is resolved against the payload's `cwd`.\n *\n * FAIL CLOSED. Every malformed envelope THROWS `InformAiError`, which the hook's one top-level handler\n * turns into a deny naming the offending line. A parser that \"did its best\" on an envelope it did not\n * understand would hand the rule engine a subset of the real edit and allow the rest unjudged, which is\n * strictly worse than refusing the call.\n */\nexport class ApplyPatchParser {\n parse(command: string, cwd: string): readonly FileOperation[] {\n const lines = command.split('\\n');\n const begin = lines.findIndex((l: string): boolean => l.trim() === BEGIN_PATCH);\n if (begin < 0) {\n throw new InformAiError(`[apply-patch] envelope has no '${BEGIN_PATCH}' line — refusing to judge a patch this parser does not recognise.`);\n }\n const end = lines.findIndex((l: string): boolean => l.trim() === END_PATCH);\n if (end < 0 || end < begin) {\n throw new InformAiError(`[apply-patch] envelope has no '${END_PATCH}' line after '${BEGIN_PATCH}' — refusing to judge a truncated patch.`);\n }\n\n const body = lines.slice(begin + 1, end);\n const ops: FileOperation[] = [];\n let index = 0;\n while (index < body.length) {\n const line = body[index];\n if (line.startsWith(ADD_FILE)) {\n index = this.parseAdd(body, index, cwd, ops);\n } else if (line.startsWith(DELETE_FILE)) {\n ops.push(new FileOperation('Delete', new NormalizedToolInput(this.resolve(line.slice(DELETE_FILE.length), cwd), [])));\n index += 1;\n } else if (line.startsWith(UPDATE_FILE)) {\n index = this.parseUpdate(body, index, cwd, ops);\n } else if (line.trim() === '') {\n index += 1;\n } else {\n throw new InformAiError(`[apply-patch] unexpected line outside any file section: ${JSON.stringify(line)}`);\n }\n }\n if (ops.length === 0) {\n throw new InformAiError('[apply-patch] envelope names no files — refusing to allow a patch whose targets could not be read.');\n }\n return ops;\n }\n\n /** `*** Add File: <p>` plus a body of `+` lines → a Write of the joined body. */\n private parseAdd(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n const filePath = this.resolve(body[start].slice(ADD_FILE.length), cwd);\n const content: string[] = [];\n let index = start + 1;\n while (index < body.length && !body[index].startsWith('*** ')) {\n const line = body[index];\n if (!line.startsWith('+')) {\n throw new InformAiError(`[apply-patch] '${ADD_FILE.trim()}' body line must begin with '+', got ${JSON.stringify(line)}`);\n }\n content.push(line.slice(1));\n index += 1;\n }\n ops.push(new FileOperation('Write', new NormalizedToolInput(filePath, [new NormalizedEdit('', content.join('\\n'))])));\n return index;\n }\n\n /**\n * `*** Update File: <p>`, an optional `*** Move to: <q>`, then one or more bare-`@@` hunks.\n *\n * A `Move to` makes the DESTINATION the judged path. That is the file whose bytes will exist after\n * the call, so it is the one a path-scoped rule must see; judging the source would let a rename\n * into a guarded directory land unjudged.\n */\n private parseUpdate(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n let index = start + 1;\n let filePath = this.resolve(body[start].slice(UPDATE_FILE.length), cwd);\n if (index < body.length && body[index].startsWith(MOVE_TO)) {\n filePath = this.resolve(body[index].slice(MOVE_TO.length), cwd);\n index += 1;\n }\n const edits: NormalizedEdit[] = [];\n while (index < body.length && !body[index].startsWith('*** ')) {\n const header = body[index];\n if (header.trim() !== HUNK_HEADER) {\n throw new InformAiError(`[apply-patch] malformed hunk header ${JSON.stringify(header)} — a Codex hunk header is a bare '@@' with no line numbers.`);\n }\n index += 1;\n const oldLines: string[] = [];\n const newLines: string[] = [];\n while (index < body.length && !body[index].startsWith('*** ') && body[index].trim() !== HUNK_HEADER) {\n const line = body[index];\n // A bare empty line is a CONTEXT line whose content is empty — the leading space is\n // routinely stripped by whatever carried the patch, so treating it as malformed would\n // deny ordinary edits to files with blank lines.\n if (line === '') {\n oldLines.push('');\n newLines.push('');\n } else if (line.startsWith(' ')) {\n oldLines.push(line.slice(1));\n newLines.push(line.slice(1));\n } else if (line.startsWith('-')) {\n oldLines.push(line.slice(1));\n } else if (line.startsWith('+')) {\n newLines.push(line.slice(1));\n } else {\n throw new InformAiError(`[apply-patch] hunk line must begin with ' ', '-' or '+', got ${JSON.stringify(line)}`);\n }\n index += 1;\n }\n edits.push(new NormalizedEdit(oldLines.join('\\n'), newLines.join('\\n')));\n }\n if (edits.length === 0) {\n throw new InformAiError(`[apply-patch] '${UPDATE_FILE.trim()}' section for ${filePath} carries no '@@' hunk — refusing to allow an edit whose content could not be read.`);\n }\n ops.push(new FileOperation('Edit', new NormalizedToolInput(filePath, edits)));\n return index;\n }\n\n private resolve(rawPath: string, cwd: string): string {\n const trimmed = rawPath.trim();\n if (trimmed === '') {\n throw new InformAiError('[apply-patch] a file directive named an empty path.');\n }\n return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apply-patch-parse.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/apply-patch-parse.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAE7B,0CAA4C;AAC5C,0CAAkE;AAClE,8DAA0D;AAE1D,MAAM,WAAW,GAAG,iBAAiB,CAAC;AACtC,MAAM,SAAS,GAAG,eAAe,CAAC;AAClC,MAAM,QAAQ,GAAG,gBAAgB,CAAC;AAClC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,OAAO,GAAG,eAAe,CAAC;AAChC,MAAM,WAAW,GAAG,IAAI,CAAC;AAEzB;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,gBAAgB;IACzB,KAAK,CAAC,OAAe,EAAE,GAAW;QAC9B,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,WAAW,CAAC,CAAC;QAChF,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACZ,MAAM,IAAI,8BAAa,CAAC,kCAAkC,WAAW,oEAAoE,CAAC,CAAC;QAC/I,CAAC;QACD,MAAM,GAAG,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,SA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AC,CAAC,CAAC;QACpF,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACrB,MAAM,IAAI,8BAAa,CAAC,kBAAkB,WAAW,CAAC,IAAI,EAAE,iBAAiB,QAAQ,oFAAoF,CAAC,CAAC;QAC/K,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,8BAAmB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QACvD,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,IAAI,wBAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;QAC3C,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,OAAO,CAAC,OAAe,EAAE,GAAW;QACxC,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC/B,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,8BAAa,CAAC,qDAAqD,CAAC,CAAC;QACnF,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;CACJ;AAnHD,4CAmHC","sourcesContent":["import * as path from 'path';\n\nimport { FileOperation } from '../protocol';\nimport { NormalizedEdit, NormalizedToolInput } from '../protocol';\nimport { InformAiError } from '@webpieces/tooling-common';\n\nconst BEGIN_PATCH = '*** Begin Patch';\nconst END_PATCH = '*** End Patch';\nconst ADD_FILE = '*** Add File: ';\nconst UPDATE_FILE = '*** Update File: ';\nconst DELETE_FILE = '*** Delete File: ';\nconst MOVE_TO = '*** Move to: ';\nconst HUNK_HEADER = '@@';\n\n/**\n * Parses Codex's `apply_patch` envelope into the same `FileOperation[]` the rest of the hook already\n * understands, so a Codex edit is judged by the identical rules a Claude edit is.\n *\n * The grammar is MEASURED from a live codex-cli 0.151.0 session, not inferred from a diff format it\n * resembles. Two properties of it drive every design choice here:\n *\n * - ONE envelope carries MANY files with MIXED operations, which is why the result is a LIST of\n * `FileOperation` (each with its own kind) rather than one kind for the call.\n * - Hunk headers are a BARE `@@` with NO line numbers. A unified-diff `@@ -1,3 +1,4 @@` is therefore\n * not a stricter spelling of the same thing — it is an envelope we have never seen, and guessing at\n * it is how a guard silently judges the wrong bytes. It is rejected.\n *\n * Paths are sometimes relative and sometimes absolute (measured: subagents used relative, the\n * coordinator absolute), so a relative path is resolved against the payload's `cwd`.\n *\n * FAIL CLOSED. Every malformed envelope THROWS `InformAiError`, which the hook's one top-level handler\n * turns into a deny naming the offending line. A parser that \"did its best\" on an envelope it did not\n * understand would hand the rule engine a subset of the real edit and allow the rest unjudged, which is\n * strictly worse than refusing the call.\n */\nexport class ApplyPatchParser {\n parse(command: string, cwd: string): readonly FileOperation[] {\n const lines = command.split('\\n');\n const begin = lines.findIndex((l: string): boolean => l.trim() === BEGIN_PATCH);\n if (begin < 0) {\n throw new InformAiError(`[apply-patch] envelope has no '${BEGIN_PATCH}' line — refusing to judge a patch this parser does not recognise.`);\n }\n const end = lines.findIndex((l: string): boolean => l.trim() === END_PATCH);\n if (end < 0 || end < begin) {\n throw new InformAiError(`[apply-patch] envelope has no '${END_PATCH}' line after '${BEGIN_PATCH}' — refusing to judge a truncated patch.`);\n }\n\n const body = lines.slice(begin + 1, end);\n const ops: FileOperation[] = [];\n let index = 0;\n while (index < body.length) {\n const line = body[index];\n if (line.startsWith(ADD_FILE)) {\n index = this.parseAdd(body, index, cwd, ops);\n } else if (line.startsWith(DELETE_FILE)) {\n ops.push(new FileOperation('Delete', new NormalizedToolInput(this.resolve(line.slice(DELETE_FILE.length), cwd), [])));\n index += 1;\n } else if (line.startsWith(UPDATE_FILE)) {\n index = this.parseUpdate(body, index, cwd, ops);\n } else if (line.trim() === '') {\n index += 1;\n } else {\n throw new InformAiError(`[apply-patch] unexpected line outside any file section: ${JSON.stringify(line)}`);\n }\n }\n if (ops.length === 0) {\n throw new InformAiError('[apply-patch] envelope names no files — refusing to allow a patch whose targets could not be read.');\n }\n return ops;\n }\n\n /** `*** Add File: <p>` plus a body of `+` lines → a Write of the joined body. */\n private parseAdd(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n const filePath = this.resolve(body[start].slice(ADD_FILE.length), cwd);\n const content: string[] = [];\n let index = start + 1;\n while (index < body.length && !body[index].startsWith('*** ')) {\n const line = body[index];\n if (!line.startsWith('+')) {\n throw new InformAiError(`[apply-patch] '${ADD_FILE.trim()}' body line must begin with '+', got ${JSON.stringify(line)}`);\n }\n content.push(line.slice(1));\n index += 1;\n }\n ops.push(new FileOperation('Write', new NormalizedToolInput(filePath, [new NormalizedEdit('', content.join('\\n'), false)])));\n return index;\n }\n\n /**\n * `*** Update File: <p>`, an optional `*** Move to: <q>`, then one or more bare-`@@` hunks.\n *\n * A `Move to` makes the DESTINATION the judged path. That is the file whose bytes will exist after\n * the call, so it is the one a path-scoped rule must see; judging the source would let a rename\n * into a guarded directory land unjudged.\n */\n private parseUpdate(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n let index = start + 1;\n let filePath = this.resolve(body[start].slice(UPDATE_FILE.length), cwd);\n const sourcePath = filePath;\n if (index < body.length && body[index].startsWith(MOVE_TO)) {\n filePath = this.resolve(body[index].slice(MOVE_TO.length), cwd);\n index += 1;\n }\n const edits: NormalizedEdit[] = [];\n while (index < body.length && !body[index].startsWith('*** ')) {\n const header = body[index];\n if (header.trim() !== HUNK_HEADER) {\n throw new InformAiError(`[apply-patch] malformed hunk header ${JSON.stringify(header)} — a Codex hunk header is a bare '@@' with no line numbers.`);\n }\n index += 1;\n const oldLines: string[] = [];\n const newLines: string[] = [];\n while (index < body.length && !body[index].startsWith('*** ') && body[index].trim() !== HUNK_HEADER) {\n const line = body[index];\n // A bare empty line is a CONTEXT line whose content is empty — the leading space is\n // routinely stripped by whatever carried the patch, so treating it as malformed would\n // deny ordinary edits to files with blank lines.\n if (line === '') {\n oldLines.push('');\n newLines.push('');\n } else if (line.startsWith(' ')) {\n oldLines.push(line.slice(1));\n newLines.push(line.slice(1));\n } else if (line.startsWith('-')) {\n oldLines.push(line.slice(1));\n } else if (line.startsWith('+')) {\n newLines.push(line.slice(1));\n } else {\n throw new InformAiError(`[apply-patch] hunk line must begin with ' ', '-' or '+', got ${JSON.stringify(line)}`);\n }\n index += 1;\n }\n edits.push(new NormalizedEdit(oldLines.join('\\n'), newLines.join('\\n'), false));\n }\n if (edits.length === 0) {\n throw new InformAiError(`[apply-patch] '${UPDATE_FILE.trim()}' section for ${filePath} carries no '@@' hunk — refusing to allow an edit whose content could not be read.`);\n }\n const input = new NormalizedToolInput(filePath, edits);\n input.sourcePath = sourcePath;\n ops.push(new FileOperation('Edit', input));\n return index;\n }\n\n private resolve(rawPath: string, cwd: string): string {\n const trimmed = rawPath.trim();\n if (trimmed === '') {\n throw new InformAiError('[apply-patch] a file directive named an empty path.');\n }\n return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);\n }\n}\n"]}
|
|
@@ -8,6 +8,7 @@ const fs = tslib_1.__importStar(require("fs"));
|
|
|
8
8
|
const strip_ts_noise_1 = require("./strip-ts-noise");
|
|
9
9
|
const disable_directives_1 = require("./disable-directives");
|
|
10
10
|
const types_1 = require("./types");
|
|
11
|
+
const proposed_file_1 = require("./proposed-file");
|
|
11
12
|
class BuiltContexts {
|
|
12
13
|
fileContext;
|
|
13
14
|
editContexts;
|
|
@@ -32,7 +33,7 @@ function buildContexts(toolKind, input, workspaceRoot, governed) {
|
|
|
32
33
|
const projectedFileLines = toolKind === 'Write'
|
|
33
34
|
? countLines(edits.length > 0 ? edits[0].newString : '')
|
|
34
35
|
: currentFileLines + linesAdded - linesRemoved;
|
|
35
|
-
const fileContext = new types_1.FileContext(toolKind, filePath, relativePath, workspaceRoot, currentFileLines, linesAdded, linesRemoved, projectedFileLines, governed.treeRoot, governed.treeRelativePath);
|
|
36
|
+
const fileContext = new types_1.FileContext(toolKind, filePath, relativePath, workspaceRoot, new proposed_file_1.ProposedFile(toolKind, input), currentFileLines, linesAdded, linesRemoved, projectedFileLines, governed.treeRoot, governed.treeRelativePath);
|
|
36
37
|
const editContexts = edits.map((e, idx) => {
|
|
37
38
|
const addedContent = e.newString;
|
|
38
39
|
const stripped = (0, strip_ts_noise_1.stripTsNoise)(addedContent);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-context.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/build-context.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"build-context.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/build-context.ts"],"names":[],"mappings":";;;AAqBA,sCA0DC;AAKD,4CAEC;;AAtFD,+CAAyB;AAIzB,qDAAgD;AAChD,6DAA4D;AAC5D,mCAAgE;AAEhE,mDAA+C;AAE/C,MAAa,aAAa;IACb,WAAW,CAAc;IACzB,YAAY,CAAyB;IAE9C,YAAY,WAAwB,EAAE,YAAoC;QACtE,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AARD,sCAQC;AAED,mKAAmK;AACnK,SAAgB,aAAa,CACzB,QAAkB,EAClB,KAA0B,EAC1B,aAAqB,EACrB,QAAsB;IAEtB,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAChC,MAAM,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;IAC3C,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IAE1B,MAAM,gBAAgB,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IACxD,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;QACpB,UAAU,IAAI,UAAU,CAAC,C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qG;AACrG,oGAAoG;AACpG,kMAAkM;AAClM,SAAgB,gBAAgB,CAAC,OAAe,EAAE,IAAmB;IACjE,OAAO,IAAI,mBAAW,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;AACrF,CAAC;AAED,mKAAmK;AACnK,SAAS,oBAAoB,CAAC,QAAgB;IAC1C,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAClD,OAAO,UAAU,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,8GAA8G;QAC9G,KAAK,GAAG,CAAC;QACT,OAAO,CAAC,CAAC;IACb,CAAC;AACL,CAAC;AAED,mKAAmK;AACnK,SAAS,UAAU,CAAC,CAAS;IACzB,IAAI,CAAC,CAAC;QAAE,OAAO,CAAC,CAAC;IACjB,OAAO,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC;AAChC,CAAC","sourcesContent":["import * as fs from 'fs';\n\nimport { EffectiveTree } from './effective-tree';\nimport { GovernedPath } from './target-tree';\nimport { stripTsNoise } from './strip-ts-noise';\nimport { createIsLineDisabled } from './disable-directives';\nimport { EditContext, FileContext, BashContext } from './types';\nimport { ToolKind, NormalizedToolInput, NormalizedEdit } from '../protocol';\nimport { ProposedFile } from './proposed-file';\n\nexport class BuiltContexts {\n readonly fileContext: FileContext;\n readonly editContexts: readonly EditContext[];\n\n constructor(fileContext: FileContext, editContexts: readonly EditContext[]) {\n this.fileContext = fileContext;\n this.editContexts = editContexts;\n }\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function buildContexts(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n workspaceRoot: string,\n governed: GovernedPath,\n): BuiltContexts {\n const filePath = input.filePath;\n const relativePath = governed.relativePath;\n const edits = input.edits;\n\n const currentFileLines = readCurrentFileLines(filePath);\n let linesAdded = 0;\n let linesRemoved = 0;\n for (const e of edits) {\n linesAdded += countLines(e.newString);\n linesRemoved += countLines(e.oldString);\n }\n\n const projectedFileLines =\n toolKind === 'Write'\n ? countLines(edits.length > 0 ? edits[0].newString : '')\n : currentFileLines + linesAdded - linesRemoved;\n\n const fileContext = new FileContext(\n toolKind,\n filePath,\n relativePath,\n workspaceRoot,\n new ProposedFile(toolKind, input),\n currentFileLines,\n linesAdded,\n linesRemoved,\n projectedFileLines,\n governed.treeRoot,\n governed.treeRelativePath,\n );\n\n const editContexts = edits.map((e, idx) => {\n const addedContent = e.newString;\n const stripped = stripTsNoise(addedContent);\n const isLineDisabled = createIsLineDisabled(addedContent);\n return new EditContext(\n toolKind,\n idx,\n edits.length,\n filePath,\n relativePath,\n workspaceRoot,\n addedContent,\n stripped,\n addedContent.split('\\n'),\n stripped.split('\\n'),\n e.oldString,\n isLineDisabled,\n );\n });\n\n return new BuiltContexts(fileContext, editContexts);\n}\n\n// The bash context is built from the RESOLVED tree, not the shell's cwd: `tree.root` is the worktree\n// the command acts on (what the guards must judge) while `tree.governedRoot` still owns the config.\n// webpieces-disable no-function-outside-class -- sibling of buildContexts() above; this module is a pair of module-scope context factories and a lone class for one of them would break its shape\nexport function buildBashContext(command: string, tree: EffectiveTree): BashContext {\n return new BashContext(command, tree.root, tree.effectiveCwd, tree.governedRoot);\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 readCurrentFileLines(filePath: string): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n return countLines(content);\n } catch (err: unknown) {\n // eslint-disable-next-line @webpieces/catch-error-pattern -- file-not-found is expected for new Write targets\n void err;\n return 0;\n }\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction countLines(s: string): number {\n if (!s) return 0;\n return s.split('\\n').length;\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { InformAiError } from '@webpieces/tooling-common';
|
|
2
|
+
import { NormalizedToolInput, ToolKind } from '../protocol';
|
|
3
|
+
/** Character range in the final proposed file. Empty ranges record deletion sites. */
|
|
4
|
+
export declare class ChangedRange {
|
|
5
|
+
readonly start: number;
|
|
6
|
+
readonly end: number;
|
|
7
|
+
constructor(start: number, end: number);
|
|
8
|
+
}
|
|
9
|
+
export declare class ProposedContent {
|
|
10
|
+
readonly original: string;
|
|
11
|
+
readonly text: string;
|
|
12
|
+
readonly changes: readonly ChangedRange[];
|
|
13
|
+
constructor(original: string, text: string, changes: readonly ChangedRange[]);
|
|
14
|
+
changedLines(): ReadonlySet<number>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The proposed file cannot be projected from this edit: its context is stale, ambiguous or empty, so no
|
|
18
|
+
* rule may judge guessed content. A structured refusal, not a rule bug — `runRuleCheck` renders it as the
|
|
19
|
+
* deny it is (never "Rule … crashed"). Worded for every harness: Claude Code, Codex and openclaw each name
|
|
20
|
+
* the edit's fields differently, so the cure names the INTENT, never a tool's parameter.
|
|
21
|
+
*/
|
|
22
|
+
export declare class ProjectionRefusal extends InformAiError {
|
|
23
|
+
readonly filePath: string;
|
|
24
|
+
constructor(filePath: string, reason: string);
|
|
25
|
+
}
|
|
26
|
+
/** Lazily projects an operation in memory; existing non-syntax rules need not read the file. */
|
|
27
|
+
export declare class ProposedFile {
|
|
28
|
+
private readonly tool;
|
|
29
|
+
private readonly input;
|
|
30
|
+
private content;
|
|
31
|
+
constructor(tool: ToolKind, input: NormalizedToolInput);
|
|
32
|
+
read(): ProposedContent;
|
|
33
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ProposedFile = exports.ProjectionRefusal = exports.ProposedContent = exports.ChangedRange = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const fs = tslib_1.__importStar(require("fs"));
|
|
6
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
7
|
+
/** Character range in the final proposed file. Empty ranges record deletion sites. */
|
|
8
|
+
class ChangedRange {
|
|
9
|
+
start;
|
|
10
|
+
end;
|
|
11
|
+
constructor(start, end) {
|
|
12
|
+
this.start = start;
|
|
13
|
+
this.end = end;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.ChangedRange = ChangedRange;
|
|
17
|
+
class ProposedContent {
|
|
18
|
+
original;
|
|
19
|
+
text;
|
|
20
|
+
changes;
|
|
21
|
+
constructor(original, text, changes) {
|
|
22
|
+
this.original = original;
|
|
23
|
+
this.text = text;
|
|
24
|
+
this.changes = changes;
|
|
25
|
+
}
|
|
26
|
+
changedLines() {
|
|
27
|
+
const lines = new Set();
|
|
28
|
+
for (const range of this.changes) {
|
|
29
|
+
const startLine = this.text.slice(0, range.start).split('\n').length;
|
|
30
|
+
const endLine = this.text.slice(0, Math.max(range.start, range.end - 1)).split('\n').length;
|
|
31
|
+
for (let line = startLine; line <= endLine; line++)
|
|
32
|
+
lines.add(line);
|
|
33
|
+
}
|
|
34
|
+
return lines;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.ProposedContent = ProposedContent;
|
|
38
|
+
/**
|
|
39
|
+
* The proposed file cannot be projected from this edit: its context is stale, ambiguous or empty, so no
|
|
40
|
+
* rule may judge guessed content. A structured refusal, not a rule bug — `runRuleCheck` renders it as the
|
|
41
|
+
* deny it is (never "Rule … crashed"). Worded for every harness: Claude Code, Codex and openclaw each name
|
|
42
|
+
* the edit's fields differently, so the cure names the INTENT, never a tool's parameter.
|
|
43
|
+
*/
|
|
44
|
+
class ProjectionRefusal extends tooling_common_1.InformAiError {
|
|
45
|
+
filePath;
|
|
46
|
+
constructor(filePath, reason) {
|
|
47
|
+
super(`Cannot judge the edit of ${filePath}: ${reason}`);
|
|
48
|
+
this.name = 'ProjectionRefusal';
|
|
49
|
+
this.filePath = filePath;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
exports.ProjectionRefusal = ProjectionRefusal;
|
|
53
|
+
/** Lazily projects an operation in memory; existing non-syntax rules need not read the file. */
|
|
54
|
+
class ProposedFile {
|
|
55
|
+
tool;
|
|
56
|
+
input;
|
|
57
|
+
content = null;
|
|
58
|
+
constructor(tool, input) {
|
|
59
|
+
this.tool = tool;
|
|
60
|
+
this.input = input;
|
|
61
|
+
}
|
|
62
|
+
read() {
|
|
63
|
+
if (this.content)
|
|
64
|
+
return this.content;
|
|
65
|
+
const original = fs.existsSync(this.input.sourcePath) ? fs.readFileSync(this.input.sourcePath, 'utf8') : '';
|
|
66
|
+
if (this.tool === 'Write') {
|
|
67
|
+
const text = this.input.edits[0]?.newString ?? '';
|
|
68
|
+
this.content = new ProposedContent(original, text, [new ChangedRange(0, text.length)]);
|
|
69
|
+
return this.content;
|
|
70
|
+
}
|
|
71
|
+
let text = original;
|
|
72
|
+
let changes = [];
|
|
73
|
+
for (const edit of this.input.edits) {
|
|
74
|
+
if (!edit.oldString)
|
|
75
|
+
throw new ProjectionRefusal(this.input.filePath, 'the edit names no existing text to replace, so there is nothing to locate. Write the complete file in one whole-file write instead, or base the edit on text the file already contains.');
|
|
76
|
+
let offset = 0;
|
|
77
|
+
let count = 0;
|
|
78
|
+
while (true) {
|
|
79
|
+
const start = text.indexOf(edit.oldString, offset);
|
|
80
|
+
if (start < 0)
|
|
81
|
+
break;
|
|
82
|
+
if (!edit.replaceAll && text.indexOf(edit.oldString, start + edit.oldString.length) >= 0)
|
|
83
|
+
throw new ProjectionRefusal(this.input.filePath, 'the text to replace matches multiple locations, so the edit is ambiguous. Include enough surrounding lines that it matches exactly once, or make it an edit that replaces every occurrence.');
|
|
84
|
+
const end = start + edit.oldString.length;
|
|
85
|
+
if (edit.oldString === edit.newString) {
|
|
86
|
+
count++;
|
|
87
|
+
offset = end;
|
|
88
|
+
if (!edit.replaceAll)
|
|
89
|
+
break;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const delta = edit.newString.length - edit.oldString.length;
|
|
93
|
+
changes = changes.map((range) => range.end < start ? range
|
|
94
|
+
: range.start > end ? new ChangedRange(range.start + delta, range.end + delta)
|
|
95
|
+
: new ChangedRange(Math.min(range.start, start), Math.max(start + edit.newString.length, range.end + delta)));
|
|
96
|
+
let prefix = 0;
|
|
97
|
+
while (prefix < edit.oldString.length && prefix < edit.newString.length && edit.oldString[prefix] === edit.newString[prefix])
|
|
98
|
+
prefix++;
|
|
99
|
+
let suffix = 0;
|
|
100
|
+
while (suffix < edit.oldString.length - prefix && suffix < edit.newString.length - prefix
|
|
101
|
+
&& edit.oldString[edit.oldString.length - suffix - 1] === edit.newString[edit.newString.length - suffix - 1])
|
|
102
|
+
suffix++;
|
|
103
|
+
changes.push(new ChangedRange(start + prefix, start + edit.newString.length - suffix));
|
|
104
|
+
text = text.slice(0, start) + edit.newString + text.slice(end);
|
|
105
|
+
count++;
|
|
106
|
+
offset = start + edit.newString.length;
|
|
107
|
+
if (!edit.replaceAll)
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
if (count === 0)
|
|
111
|
+
throw new ProjectionRefusal(this.input.filePath, 'the text to replace does not match the current file. Read the file again and base the edit on its current content.');
|
|
112
|
+
}
|
|
113
|
+
this.content = new ProposedContent(original, text, text === original ? [] : changes);
|
|
114
|
+
return this.content;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
exports.ProposedFile = ProposedFile;
|
|
118
|
+
//# sourceMappingURL=proposed-file.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proposed-file.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/proposed-file.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,8DAA0D;AAG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,KAAK,CAAC,QAAQ,EAAE,oHAAoH,CAAC,CAAC;QAC5L,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QACrF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;CACJ;AAnDD,oCAmDC","sourcesContent":["import * as fs from 'fs';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { NormalizedToolInput, ToolKind } from '../protocol';\n\n/** Character range in the final proposed file. Empty ranges record deletion sites. */\nexport class ChangedRange {\n constructor(readonly start: number, readonly end: number) {}\n}\n\nexport class ProposedContent {\n constructor(readonly original: string, readonly text: string, readonly changes: readonly ChangedRange[]) {}\n\n changedLines(): ReadonlySet<number> {\n const lines = new Set<number>();\n for (const range of this.changes) {\n const startLine = this.text.slice(0, range.start).split('\\n').length;\n const endLine = this.text.slice(0, Math.max(range.start, range.end - 1)).split('\\n').length;\n for (let line = startLine; line <= endLine; line++) lines.add(line);\n }\n return lines;\n }\n}\n\n/**\n * The proposed file cannot be projected from this edit: its context is stale, ambiguous or empty, so no\n * rule may judge guessed content. A structured refusal, not a rule bug — `runRuleCheck` renders it as the\n * deny it is (never \"Rule … crashed\"). Worded for every harness: Claude Code, Codex and openclaw each name\n * the edit's fields differently, so the cure names the INTENT, never a tool's parameter.\n */\nexport class ProjectionRefusal extends InformAiError {\n readonly filePath: string;\n\n constructor(filePath: string, reason: string) {\n super(`Cannot judge the edit of ${filePath}: ${reason}`);\n this.name = 'ProjectionRefusal';\n this.filePath = filePath;\n }\n}\n\n/** Lazily projects an operation in memory; existing non-syntax rules need not read the file. */\nexport class ProposedFile {\n private content: ProposedContent | null = null;\n\n constructor(private readonly tool: ToolKind, private readonly input: NormalizedToolInput) {}\n\n read(): ProposedContent {\n if (this.content) return this.content;\n const original = fs.existsSync(this.input.sourcePath) ? fs.readFileSync(this.input.sourcePath, 'utf8') : '';\n if (this.tool === 'Write') {\n const text = this.input.edits[0]?.newString ?? '';\n this.content = new ProposedContent(original, text, [new ChangedRange(0, text.length)]);\n return this.content;\n }\n let text = original;\n let changes: ChangedRange[] = [];\n for (const edit of this.input.edits) {\n if (!edit.oldString) throw new ProjectionRefusal(this.input.filePath, 'the edit names no existing text to replace, so there is nothing to locate. Write the complete file in one whole-file write instead, or base the edit on text the file already contains.');\n let offset = 0;\n let count = 0;\n while (true) {\n const start = text.indexOf(edit.oldString, offset);\n if (start < 0) break;\n if (!edit.replaceAll && text.indexOf(edit.oldString, start + edit.oldString.length) >= 0)\n throw new ProjectionRefusal(this.input.filePath, 'the text to replace matches multiple locations, so the edit is ambiguous. Include enough surrounding lines that it matches exactly once, or make it an edit that replaces every occurrence.');\n const end = start + edit.oldString.length;\n if (edit.oldString === edit.newString) {\n count++;\n offset = end;\n if (!edit.replaceAll) break;\n continue;\n }\n const delta = edit.newString.length - edit.oldString.length;\n changes = changes.map((range: ChangedRange): ChangedRange => range.end < start ? range\n : range.start > end ? new ChangedRange(range.start + delta, range.end + delta)\n : new ChangedRange(Math.min(range.start, start), Math.max(start + edit.newString.length, range.end + delta)));\n let prefix = 0;\n while (prefix < edit.oldString.length && prefix < edit.newString.length && edit.oldString[prefix] === edit.newString[prefix]) prefix++;\n let suffix = 0;\n while (suffix < edit.oldString.length - prefix && suffix < edit.newString.length - prefix\n && edit.oldString[edit.oldString.length - suffix - 1] === edit.newString[edit.newString.length - suffix - 1]) suffix++;\n changes.push(new ChangedRange(start + prefix, start + edit.newString.length - suffix));\n text = text.slice(0, start) + edit.newString + text.slice(end);\n count++;\n offset = start + edit.newString.length;\n if (!edit.replaceAll) break;\n }\n if (count === 0) throw new ProjectionRefusal(this.input.filePath, 'the text to replace does not match the current file. Read the file again and base the edit on its current content.');\n }\n this.content = new ProposedContent(original, text, text === original ? [] : changes);\n return this.content;\n }\n}\n"]}
|
|
@@ -6,6 +6,7 @@ exports.runEditRules = runEditRules;
|
|
|
6
6
|
exports.runFileRules = runFileRules;
|
|
7
7
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
8
8
|
const to_error_1 = require("@webpieces/tooling-common/to-error");
|
|
9
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
9
10
|
const types_1 = require("./types");
|
|
10
11
|
const rules_config_2 = require("@webpieces/rules-config");
|
|
11
12
|
// Every entry was read from its declared owner file and validated before execution.
|
|
@@ -21,6 +22,11 @@ function runRuleCheck(rule, ctx) {
|
|
|
21
22
|
if (error instanceof rules_config_1.RuleFailError) {
|
|
22
23
|
return [violationFromRuleFail(error)];
|
|
23
24
|
}
|
|
25
|
+
// A structured refusal written for the AI — e.g. ProposedFile refusing stale or ambiguous edit
|
|
26
|
+
// context — is the deny itself, not a bug in the rule, so it is never rendered as "crashed".
|
|
27
|
+
if (error instanceof tooling_common_1.InformAiError) {
|
|
28
|
+
return [new types_1.Violation(0, '', error.message)];
|
|
29
|
+
}
|
|
24
30
|
return [new types_1.Violation(0, '', `Rule '${rule.name}' crashed: ${error.message}`)];
|
|
25
31
|
}
|
|
26
32
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rule-evaluation.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/rule-evaluation.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"rule-evaluation.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/rule-evaluation.ts"],"names":[],"mappings":";;AAiBA,oCAoBC;AAqBD,oCAcC;AAGD,oCAwBC;AAGD,oCAeC;AArHD,0DAA6E;AAC7E,iEAA6D;AAC7D,8DAA0D;AAC1D,mCAQiB;AAEjB,0DAAsD;AAEtD,oFAAoF;AACpF,+HAA+H;AAC/H,SAAgB,YAAY,CACxB,IAAU,EACV,GAA4C;IAE5C,8DAA8D;IAC9D,IAAI,CAAC;QACD,OAAO,IAAI,CAAC,KAAK,CAAC,GA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AAG,CAAC,SAAS,CAAC;gBAC/B,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC7B,CAAC;QACL,CAAC;QACD,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC3B,MAAM,CAAC,IAAI,CAAC,IAAI,iBAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC,CAAC;QACzF,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,+HAA+H;AAC/H,SAAgB,YAAY,CACxB,KAAsB,EACtB,WAAwB;IAExB,MAAM,MAAM,GAAgB,EAAE,CAAC;IAC/B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,IAAI,IAAI,CAAC,KAAK,KAAK,MAAM;YAAE,SAAS;QACpC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YAAE,SAAS;QAChC,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,YAAY,CAAC;YAAE,SAAS;QAC/D,MAAM,EAAE,GAAG,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QAC3C,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAChB,MAAM,CAAC,IAAI,CAAC,IAAI,iBAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;QACnF,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC","sourcesContent":["import { RuleFailError, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport {\n Rule,\n EditContext,\n FileContext,\n BashContext,\n Violation,\n RuleGroup,\n BlockedResult,\n} from './types';\n\nimport { globMatches } from '@webpieces/rules-config';\n\n// Every entry was read from its declared owner file and validated before execution.\n// webpieces-disable no-function-outside-class -- existing stateless evaluator helpers extracted intact for both hook providers\nexport function runRuleCheck(\n rule: Rule,\n ctx: EditContext | FileContext | BashContext,\n): readonly Violation[] {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return rule.check(ctx);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) {\n return [violationFromRuleFail(error)];\n }\n // A structured refusal written for the AI — e.g. ProposedFile refusing stale or ambiguous edit\n // context — is the deny itself, not a bug in the rule, so it is never rendered as \"crashed\".\n if (error instanceof InformAiError) {\n return [new Violation(0, '', error.message)];\n }\n return [new Violation(0, '', `Rule '${rule.name}' crashed: ${error.message}`)];\n }\n}\n\n// A thrown RuleFailError carries its own AI-facing message + optional location and cures. Fold the\n// cures into the message because Violation has no fixHint field (RuleGroup's fixHint comes from the\n// rule definition, not a per-throw value). The \"Fix Option N:\"/\"(preferred)\" labels come from the ONE\n// framework-owned renderer, exactly as report.ts renders a rule's static FixHint — a rule never\n// hand-numbers its own cures.\n// webpieces-disable no-function-outside-class -- existing stateless evaluator helpers extracted intact for both hook providers\nfunction violationFromRuleFail(error: RuleFailError): Violation {\n return new Violation(error.line ?? 0, error.snippet ?? '', renderRuleFailForAi(error));\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless evaluator helpers extracted intact for both hook providers\nfunction ruleMatchesFile(rule: Rule, relativePath: string): boolean {\n for (const pattern of rule.files) {\n if (globMatches(pattern, relativePath)) return true;\n }\n return false;\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless evaluator helpers extracted intact for both hook providers\nexport function runBashRules(\n rules: readonly Rule[],\n bashContext: BashContext,\n): readonly RuleGroup[] {\n const groups: RuleGroup[] = [];\n for (const rule of rules) {\n if (rule.scope !== 'bash') continue;\n if (!rule.shouldRun()) continue;\n const vs = runRuleCheck(rule, bashContext);\n if (vs.length > 0) {\n groups.push(new RuleGroup(rule.name, rule.description, rule.fixHint, [...vs]));\n }\n }\n return groups;\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless evaluator helpers extracted intact for both hook providers\nexport function runEditRules(\n rules: readonly Rule[],\n editContexts: readonly EditContext[],\n): readonly RuleGroup[] {\n const groups: RuleGroup[] = [];\n for (const rule of rules) {\n if (rule.scope !== 'edit') continue;\n if (!rule.shouldRun()) continue;\n const allViolations: Violation[] = [];\n for (const ctx of editContexts) {\n if (!ruleMatchesFile(rule, ctx.relativePath)) continue;\n const vs = runRuleCheck(rule, ctx);\n for (const v of vs) {\n const copy = new Violation(v.line, v.snippet, v.message);\n copy.editIndex = ctx.editIndex;\n copy.editCount = ctx.editCount;\n allViolations.push(copy);\n }\n }\n if (allViolations.length > 0) {\n groups.push(new RuleGroup(rule.name, rule.description, rule.fixHint, allViolations));\n }\n }\n return groups;\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless evaluator helpers extracted intact for both hook providers\nexport function runFileRules(\n rules: readonly Rule[],\n fileContext: FileContext,\n): readonly RuleGroup[] {\n const groups: RuleGroup[] = [];\n for (const rule of rules) {\n if (rule.scope !== 'file') continue;\n if (!rule.shouldRun()) continue;\n if (!ruleMatchesFile(rule, fileContext.relativePath)) continue;\n const vs = runRuleCheck(rule, fileContext);\n if (vs.length > 0) {\n groups.push(new RuleGroup(rule.name, rule.description, rule.fixHint, [...vs]));\n }\n }\n return groups;\n}\n"]}
|
package/src/core/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { RuleOptions } from '@webpieces/rules-config';
|
|
2
2
|
import { ToolKind } from '../protocol';
|
|
3
3
|
import { FixHint } from './fix-hint';
|
|
4
|
+
import { ProposedFile } from './proposed-file';
|
|
4
5
|
export type RuleScope = 'edit' | 'file' | 'bash';
|
|
5
6
|
export type IsLineDisabled = (lineNum: number, ruleName: string) => boolean;
|
|
6
7
|
export declare class Violation {
|
|
@@ -79,6 +80,7 @@ export declare class BashContext {
|
|
|
79
80
|
private stripProse;
|
|
80
81
|
}
|
|
81
82
|
export declare class FileContext {
|
|
83
|
+
readonly proposedFile: ProposedFile | null;
|
|
82
84
|
readonly tool: ToolKind;
|
|
83
85
|
readonly filePath: string;
|
|
84
86
|
readonly relativePath: string;
|
|
@@ -92,7 +94,7 @@ export declare class FileContext {
|
|
|
92
94
|
readonly linesRemoved: number;
|
|
93
95
|
readonly projectedFileLines: number;
|
|
94
96
|
options: RuleOptions;
|
|
95
|
-
constructor(tool: ToolKind, filePath: string, relativePath: string, workspaceRoot: string, currentFileLines: number, linesAdded: number, linesRemoved: number, projectedFileLines: number, targetRoot?: string, targetRelativePath?: string);
|
|
97
|
+
constructor(tool: ToolKind, filePath: string, relativePath: string, workspaceRoot: string, proposedFile: ProposedFile | null, currentFileLines: number, linesAdded: number, linesRemoved: number, projectedFileLines: number, targetRoot?: string, targetRelativePath?: string);
|
|
96
98
|
}
|
|
97
99
|
/**
|
|
98
100
|
* The shape of a client hook policy returned by its declared runtime factory.
|
package/src/core/types.js
CHANGED
|
@@ -128,6 +128,7 @@ class BashContext {
|
|
|
128
128
|
}
|
|
129
129
|
exports.BashContext = BashContext;
|
|
130
130
|
class FileContext {
|
|
131
|
+
proposedFile;
|
|
131
132
|
tool;
|
|
132
133
|
filePath;
|
|
133
134
|
relativePath;
|
|
@@ -141,7 +142,8 @@ class FileContext {
|
|
|
141
142
|
linesRemoved;
|
|
142
143
|
projectedFileLines;
|
|
143
144
|
options;
|
|
144
|
-
constructor(tool, filePath, relativePath, workspaceRoot, currentFileLines, linesAdded, linesRemoved, projectedFileLines, targetRoot = workspaceRoot, targetRelativePath = relativePath) {
|
|
145
|
+
constructor(tool, filePath, relativePath, workspaceRoot, proposedFile, currentFileLines, linesAdded, linesRemoved, projectedFileLines, targetRoot = workspaceRoot, targetRelativePath = relativePath) {
|
|
146
|
+
this.proposedFile = proposedFile;
|
|
145
147
|
this.tool = tool;
|
|
146
148
|
this.filePath = filePath;
|
|
147
149
|
this.relativePath = relativePath;
|
package/src/core/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/types.ts"],"names":[],"mappings":";;;AAWA,0DAAwD;AAmBxD,MAAa,SAAS;IACT,IAAI,CAAS;IACb,OAAO,CAAS;IACzB,yFAAyF;IACzF,yFAAyF;IACzF,iEAAiE;IACxD,OAAO,CAAqB;IACrC,SAAS,CAAqB;IAC9B,SAAS,CAAqB;IAE9B,YAAY,IAAY,EAAE,OAAe,EAAE,OAAgB;QACvD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AAjBD,8BAiBC;AAED,MAAa,WAAW;IACX,IAAI,CAAW;IACf,SAAS,CAAS;IAClB,SAAS,CAAS;IAClB,QAAQ,CAAS;IACjB,YAAY,CAAS;IACrB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,eAAe,CAAS;IACxB,KAAK,CAAoB;IACzB,aAAa,CAAoB;IACjC,cAAc,CAAS;IACvB,cAAc,CAAiB;IACxC,OAAO,CAAc;IAErB,YACI,IAAc,EACd,SAAiB,EACjB,SAAiB,EACjB,QAAgB,EAChB,YAAoB,EACpB,aAAqB,EACrB,YAAoB,EACpB,eAAuB,EACvB,KAAwB,EACxB,aAAgC,EAChC,cAAsB,EACtB,cAA8B;QAE9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAA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AG,gBAAgB,CAAC;QACzC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,kBAAkB,GAAG,kBAAkB,CAAC;QAC7C,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACtB,CAAC;CACJ;AAvCD,kCAuCC;AA0CD,MAAa,SAAS;IACT,QAAQ,CAAS;IACjB,eAAe,CAAS;IACxB,OAAO,CAAU;IACjB,UAAU,CAAuB;IAE1C,YACI,QAAgB,EAChB,eAAuB,EACvB,OAAgB,EAChB,UAAgC;QAEhC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAjBD,8BAiBC;AAED,MAAa,aAAa;IACb,MAAM,CAAS;IACxB;;;;;;;;OAQG;IACM,KAAK,CAAS;IAEvB,YAAY,MAAc,EAAE,QAAgB,4BAAa;QACrD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAjBD,sCAiBC","sourcesContent":["// ResolvedConfig / ResolvedRuleConfig / RuleOptions now live in @webpieces/rules-config\n// so ai-hooks and the Nx validate-code executor share one loader and one config file.\nimport { RuleOptions } from '@webpieces/rules-config';\nimport {\n HookMode,\n NormalizedBashInput,\n NormalizedEdit,\n NormalizedToolInput,\n ToolKind,\n} from '../protocol';\nimport { FixHint } from './fix-hint';\nimport { L0_FAULT_NONE } from '@webpieces/rules-config';\n\n// 'Read' is a first-class member because read-stale-guard is a file-scoped guard that runs on the\n// Read fast path. It is deliberately NOT in HANDLED_FILE_TOOLS (adapters/claude-code-adapter.ts), so\n// ClaudeCodeAdapter.kindOf() maps it to the 'Read' routing kind and Read never enters the edit/file\n// rule pipeline — only the one guard that asks for it. Nothing switches exhaustively on this union;\n// it is carried for logging.\n//\n// 'Delete' arrives ONLY from a Codex `apply_patch` carrying a `*** Delete File:` directive — no Claude\n// Code tool produces it. Every existing rule DEFAULTS TO NOT FIRING on it (see DeleteScopedRules in\n// ./delete-scoped-rules.ts): a rule written to judge the bytes an edit ADDS has nothing to say about a file going\n// away, and inventing a verdict for it would be guessing. Rules for which a delete IS meaningful — a\n// barrel export disappearing, a doc that documents a deleted file — opt in there, deliberately.\nexport type RuleScope = 'edit' | 'file' | 'bash';\n// Which category of built-in rules a hook invocation runs: code-style 'rules', git/PR/branch\n// 'guards' (the hookGuards section), or 'all' (both categories — used by the openclaw plugin adapter,\n// which is a single before_tool_call hook rather than two split PreToolUse hooks).\nexport type IsLineDisabled = (lineNum: number, ruleName: string) => boolean;\n\nexport class Violation {\n readonly line: number;\n readonly snippet: string;\n // Optional per-occurrence override for the `→` line. When omitted, the report falls back\n // to the rule's `FixHint.violation`. Dynamic rules (param name, line count, marker path,\n // branch/PR) pass a specific message here; static rules omit it.\n readonly message: string | undefined;\n editIndex: number | undefined;\n editCount: number | undefined;\n\n constructor(line: number, snippet: string, message?: string) {\n this.line = line;\n this.snippet = snippet;\n this.message = message;\n this.editIndex = undefined;\n this.editCount = undefined;\n }\n}\n\nexport class EditContext {\n readonly tool: ToolKind;\n readonly editIndex: number;\n readonly editCount: number;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n readonly addedContent: string;\n readonly strippedContent: string;\n readonly lines: readonly string[];\n readonly strippedLines: readonly string[];\n readonly removedContent: string;\n readonly isLineDisabled: IsLineDisabled;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n editIndex: number,\n editCount: number,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n addedContent: string,\n strippedContent: string,\n lines: readonly string[],\n strippedLines: readonly string[],\n removedContent: string,\n isLineDisabled: IsLineDisabled,\n ) {\n this.tool = tool;\n this.editIndex = editIndex;\n this.editCount = editCount;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.addedContent = addedContent;\n this.strippedContent = strippedContent;\n this.lines = lines;\n this.strippedLines = strippedLines;\n this.removedContent = removedContent;\n this.isLineDisabled = isLineDisabled;\n this.options = {};\n }\n}\n\n// A heredoc and its body: `<<EOF` / `<<'EOF'` / `<<-EOF` through the terminator line.\nconst HEREDOC_BODY = /<<-?\\s*(['\"]?)(\\w+)\\1[\\s\\S]*?^\\t*\\2\\s*$/gm;\n\n// A single- or double-quoted span.\nconst QUOTED_SPAN = /'([^']*)'|\"([^\"]*)\"/g;\n\n// Shell syntax that a quoted span is explicitly NOT: separators, pipes, subshells, redirection,\n// expansion. Content carrying any of these is data (a jq filter, a regex, a glob), and unquoting it\n// would hand the segment scanner syntax the shell never sees. See stripProse.\nconst SHELL_METACHARACTER = /[|;&()<>$`]/;\n\nexport class BashContext {\n readonly tool: 'Bash';\n readonly command: string;\n /**\n * `command` with heredoc bodies and prose-in-quotes removed — what a guard should MATCH on, while\n * `command` stays raw for the violation message (a human needs to see what they actually typed).\n *\n * A commit message that merely MENTIONS a blocked command is not that command. This repo's whole\n * subject matter is the git workflow, so its commit messages, docs and the guards' own fix-hint\n * text are full of `git push` / `gh pr …` strings; matching raw text blocks writing about the\n * tooling. A guard that cries wolf is a guard someone eventually turns OFF, which costs far more\n * than the theoretical bypass this opens (`sh -c '<blocked command>'` stops matching). That trade\n * is deliberate: these guards exist to catch a FORGETFUL agent, not an adversarial one.\n *\n * ONLY for blocklist-shaped guards (\"if the command matches X, block\"), where stripping can only\n * ever block LESS. Never use it in an allowlist-shaped guard such as merged-branch-bash-guard,\n * where stripping could turn a permitted recovery command into a blocked one and deadlock the\n * session — there, match on the raw `command`.\n */\n readonly commandCode: string;\n /**\n * The tree this command is JUDGED against — the root of the worktree it actually acts on, which\n * is NOT the shell's cwd whenever the command carries a leading `cd <path> &&` (see\n * EffectiveTreeResolver). Guards read git state, the main-sync cache and the decision log from\n * here, so a command aimed at a linked worktree is judged on that worktree's branch, never the\n * primary clone's.\n */\n readonly workspaceRoot: string;\n /** The directory the command really runs in (post-`cd`). Relative paths resolve against THIS. */\n readonly effectiveCwd: string;\n /** The root owning webpieces.config.json. Equals workspaceRoot except in a linked worktree. */\n readonly governedRoot: string;\n options: RuleOptions;\n\n constructor(\n command: string,\n workspaceRoot: string,\n effectiveCwd?: string,\n governedRoot?: string,\n ) {\n this.tool = 'Bash';\n this.command = command;\n this.commandCode = this.stripProse(command);\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd ?? workspaceRoot;\n this.governedRoot = governedRoot ?? workspaceRoot;\n this.options = {};\n }\n\n /**\n * A quoted span WITHOUT whitespace is kept: `git checkout \"main\"` is a real command with a quoted\n * argument, not prose. One containing whitespace is a sentence, and becomes a single space.\n *\n * ONE exception, and it is a false positive that actually fired: a whitespace-free span carrying\n * SHELL METACHARACTERS is dropped too. Keeping the content strips only the quotes, so a jq filter —\n * `--jq '[.[]|select(.title|test(\"x\"))]|length'` — was handed to the guards as bare shell syntax.\n * Every guard then split it on its `|`, `(` and `;` and saw a segment reading exactly `test`, which\n * whole-repo-build-guard classified as the workspace-wide test script and BLOCKED. There was no\n * build anywhere in that command; it polled npm and GitHub.\n *\n * Quoting is precisely how a shell says \"this is DATA, not syntax\", so honouring the quotes is the\n * correct reading. And because commandCode only ever feeds blocklist-shaped guards, dropping more\n * can only ever block LESS — never turn an allowed command into a refused one.\n */\n private stripProse(command: string): string {\n const withoutHeredocs = command.replace(HEREDOC_BODY, ' ');\n return withoutHeredocs.replace(\n QUOTED_SPAN,\n (match: string, single?: string, double?: string): string => {\n const content = single ?? double ?? '';\n if (/\\s/.test(content)) return ' ';\n return SHELL_METACHARACTER.test(content) ? ' ' : content;\n },\n );\n }\n}\n\nexport class FileContext {\n readonly tool: ToolKind;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n /** The git tree that owns filePath. workspaceRoot remains the root that owns policy/config. */\n readonly targetRoot: string;\n /** filePath relative to targetRoot, independent of its governed-root spelling. */\n readonly targetRelativePath: string;\n readonly currentFileLines: number;\n readonly linesAdded: number;\n readonly linesRemoved: number;\n readonly projectedFileLines: number;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n currentFileLines: number,\n linesAdded: number,\n linesRemoved: number,\n projectedFileLines: number,\n targetRoot: string = workspaceRoot,\n targetRelativePath: string = relativePath,\n ) {\n this.tool = tool;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.targetRoot = targetRoot;\n this.targetRelativePath = targetRelativePath;\n this.currentFileLines = currentFileLines;\n this.linesAdded = linesAdded;\n this.linesRemoved = linesRemoved;\n this.projectedFileLines = projectedFileLines;\n this.options = {};\n }\n}\n\n/**\n * The shape of a client hook policy returned by its declared runtime factory.\n * It carries only metadata + a `check` method — no on/off logic of its own.\n */\nexport interface PlainRule {\n readonly name: string;\n readonly description: string;\n readonly scope: RuleScope;\n readonly files: readonly string[];\n readonly defaultOptions: RuleOptions;\n readonly fixHint: FixHint;\n check(ctx: EditContext | FileContext | BashContext): readonly Violation[];\n}\n\n/**\n * The runtime contract the runner iterates. Both the built-in rule classes (which extend\n * EditRuleBase/FileRuleBase/BashRuleBase) and the custom-rule adapter satisfy this: they add\n * `shouldRun()` (mode + escape-hatch decision) on top of the PlainRule metadata.\n */\nexport interface Rule extends PlainRule {\n /**\n * The webpieces.config.json key whose entry configures this rule — NOT necessarily `name`.\n *\n * `name` is the operator identity (what a decision-log line and a deny report carry); `configKey`\n * is the switch. They differ wherever several classes implement one POLICY: all four branch-state\n * guards read `branch-state-guard`, all four PR-lifecycle guards read `pr-lifecycle-guard`. Every\n * consumer that asks \"which section does this live in?\" (filterByMode) or \"does this have an\n * entry?\" (the fault-Y config-sync check) must read THIS field, because asking for `name` there\n * demands entries under keys the validator rejects as retired.\n */\n readonly configKey: string;\n shouldRun(): boolean;\n /**\n * True when this rule's own `excludePaths` matches the workspace-relative path (#1253). The engine\n * asks it before dispatching the rule on a path, exactly as it asks shouldRun() — no rule filters\n * its own paths. AbstractRule supplies it.\n */\n excludesPath(relativePath: string): boolean;\n}\n\nexport class RuleGroup {\n readonly ruleName: string;\n readonly ruleDescription: string;\n readonly fixHint: FixHint;\n readonly violations: readonly Violation[];\n\n constructor(\n ruleName: string,\n ruleDescription: string,\n fixHint: FixHint,\n violations: readonly Violation[],\n ) {\n this.ruleName = ruleName;\n this.ruleDescription = ruleDescription;\n this.fixHint = fixHint;\n this.violations = violations;\n }\n}\n\nexport class BlockedResult {\n readonly report: string;\n /**\n * The L0 fault this block IS, in the codebook's own letter (see core/l0-fault-codes.ts), or `-` for\n * an ordinary rule block.\n *\n * It rides on the result rather than being re-derived from the report text because the block is\n * decided deep in the runner (fault C in configMissingBlock, fault Y during owner-config validation) and\n * STAMPED by the adapter at the terminal boundary, several frames up. Scraping the report for a\n * fault would be a second answer to a question the producer already knows.\n */\n readonly fault: string;\n\n constructor(report: string, fault: string = L0_FAULT_NONE) {\n this.report = report;\n this.fault = fault;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../packages/tooling/hook-runtime/src/core/types.ts"],"names":[],"mappings":";;;AAWA,0DAAwD;AAoBxD,MAAa,SAAS;IACT,IAAI,CAAS;IACb,OAAO,CAAS;IACzB,yFAAyF;IACzF,yFAAyF;IACzF,iEAAiE;IACxD,OAAO,CAAqB;IACrC,SAAS,CAAqB;IAC9B,SAAS,CAAqB;IAE9B,YAAY,IAAY,EAAE,OAAe,EAAE,OAAgB;QACvD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAA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AC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAjBD,8BAiBC;AAED,MAAa,aAAa;IACb,MAAM,CAAS;IACxB;;;;;;;;OAQG;IACM,KAAK,CAAS;IAEvB,YAAY,MAAc,EAAE,QAAgB,4BAAa;QACrD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAjBD,sCAiBC","sourcesContent":["// ResolvedConfig / ResolvedRuleConfig / RuleOptions now live in @webpieces/rules-config\n// so ai-hooks and the Nx validate-code executor share one loader and one config file.\nimport { RuleOptions } from '@webpieces/rules-config';\nimport {\n HookMode,\n NormalizedBashInput,\n NormalizedEdit,\n NormalizedToolInput,\n ToolKind,\n} from '../protocol';\nimport { FixHint } from './fix-hint';\nimport { L0_FAULT_NONE } from '@webpieces/rules-config';\nimport { ProposedFile } from './proposed-file';\n\n// 'Read' is a first-class member because read-stale-guard is a file-scoped guard that runs on the\n// Read fast path. It is deliberately NOT in HANDLED_FILE_TOOLS (adapters/claude-code-adapter.ts), so\n// ClaudeCodeAdapter.kindOf() maps it to the 'Read' routing kind and Read never enters the edit/file\n// rule pipeline — only the one guard that asks for it. Nothing switches exhaustively on this union;\n// it is carried for logging.\n//\n// 'Delete' arrives ONLY from a Codex `apply_patch` carrying a `*** Delete File:` directive — no Claude\n// Code tool produces it. Every existing rule DEFAULTS TO NOT FIRING on it (see DeleteScopedRules in\n// ./delete-scoped-rules.ts): a rule written to judge the bytes an edit ADDS has nothing to say about a file going\n// away, and inventing a verdict for it would be guessing. Rules for which a delete IS meaningful — a\n// barrel export disappearing, a doc that documents a deleted file — opt in there, deliberately.\nexport type RuleScope = 'edit' | 'file' | 'bash';\n// Which category of built-in rules a hook invocation runs: code-style 'rules', git/PR/branch\n// 'guards' (the hookGuards section), or 'all' (both categories — used by the openclaw plugin adapter,\n// which is a single before_tool_call hook rather than two split PreToolUse hooks).\nexport type IsLineDisabled = (lineNum: number, ruleName: string) => boolean;\n\nexport class Violation {\n readonly line: number;\n readonly snippet: string;\n // Optional per-occurrence override for the `→` line. When omitted, the report falls back\n // to the rule's `FixHint.violation`. Dynamic rules (param name, line count, marker path,\n // branch/PR) pass a specific message here; static rules omit it.\n readonly message: string | undefined;\n editIndex: number | undefined;\n editCount: number | undefined;\n\n constructor(line: number, snippet: string, message?: string) {\n this.line = line;\n this.snippet = snippet;\n this.message = message;\n this.editIndex = undefined;\n this.editCount = undefined;\n }\n}\n\nexport class EditContext {\n readonly tool: ToolKind;\n readonly editIndex: number;\n readonly editCount: number;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n readonly addedContent: string;\n readonly strippedContent: string;\n readonly lines: readonly string[];\n readonly strippedLines: readonly string[];\n readonly removedContent: string;\n readonly isLineDisabled: IsLineDisabled;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n editIndex: number,\n editCount: number,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n addedContent: string,\n strippedContent: string,\n lines: readonly string[],\n strippedLines: readonly string[],\n removedContent: string,\n isLineDisabled: IsLineDisabled,\n ) {\n this.tool = tool;\n this.editIndex = editIndex;\n this.editCount = editCount;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.addedContent = addedContent;\n this.strippedContent = strippedContent;\n this.lines = lines;\n this.strippedLines = strippedLines;\n this.removedContent = removedContent;\n this.isLineDisabled = isLineDisabled;\n this.options = {};\n }\n}\n\n// A heredoc and its body: `<<EOF` / `<<'EOF'` / `<<-EOF` through the terminator line.\nconst HEREDOC_BODY = /<<-?\\s*(['\"]?)(\\w+)\\1[\\s\\S]*?^\\t*\\2\\s*$/gm;\n\n// A single- or double-quoted span.\nconst QUOTED_SPAN = /'([^']*)'|\"([^\"]*)\"/g;\n\n// Shell syntax that a quoted span is explicitly NOT: separators, pipes, subshells, redirection,\n// expansion. Content carrying any of these is data (a jq filter, a regex, a glob), and unquoting it\n// would hand the segment scanner syntax the shell never sees. See stripProse.\nconst SHELL_METACHARACTER = /[|;&()<>$`]/;\n\nexport class BashContext {\n readonly tool: 'Bash';\n readonly command: string;\n /**\n * `command` with heredoc bodies and prose-in-quotes removed — what a guard should MATCH on, while\n * `command` stays raw for the violation message (a human needs to see what they actually typed).\n *\n * A commit message that merely MENTIONS a blocked command is not that command. This repo's whole\n * subject matter is the git workflow, so its commit messages, docs and the guards' own fix-hint\n * text are full of `git push` / `gh pr …` strings; matching raw text blocks writing about the\n * tooling. A guard that cries wolf is a guard someone eventually turns OFF, which costs far more\n * than the theoretical bypass this opens (`sh -c '<blocked command>'` stops matching). That trade\n * is deliberate: these guards exist to catch a FORGETFUL agent, not an adversarial one.\n *\n * ONLY for blocklist-shaped guards (\"if the command matches X, block\"), where stripping can only\n * ever block LESS. Never use it in an allowlist-shaped guard such as merged-branch-bash-guard,\n * where stripping could turn a permitted recovery command into a blocked one and deadlock the\n * session — there, match on the raw `command`.\n */\n readonly commandCode: string;\n /**\n * The tree this command is JUDGED against — the root of the worktree it actually acts on, which\n * is NOT the shell's cwd whenever the command carries a leading `cd <path> &&` (see\n * EffectiveTreeResolver). Guards read git state, the main-sync cache and the decision log from\n * here, so a command aimed at a linked worktree is judged on that worktree's branch, never the\n * primary clone's.\n */\n readonly workspaceRoot: string;\n /** The directory the command really runs in (post-`cd`). Relative paths resolve against THIS. */\n readonly effectiveCwd: string;\n /** The root owning webpieces.config.json. Equals workspaceRoot except in a linked worktree. */\n readonly governedRoot: string;\n options: RuleOptions;\n\n constructor(\n command: string,\n workspaceRoot: string,\n effectiveCwd?: string,\n governedRoot?: string,\n ) {\n this.tool = 'Bash';\n this.command = command;\n this.commandCode = this.stripProse(command);\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd ?? workspaceRoot;\n this.governedRoot = governedRoot ?? workspaceRoot;\n this.options = {};\n }\n\n /**\n * A quoted span WITHOUT whitespace is kept: `git checkout \"main\"` is a real command with a quoted\n * argument, not prose. One containing whitespace is a sentence, and becomes a single space.\n *\n * ONE exception, and it is a false positive that actually fired: a whitespace-free span carrying\n * SHELL METACHARACTERS is dropped too. Keeping the content strips only the quotes, so a jq filter —\n * `--jq '[.[]|select(.title|test(\"x\"))]|length'` — was handed to the guards as bare shell syntax.\n * Every guard then split it on its `|`, `(` and `;` and saw a segment reading exactly `test`, which\n * whole-repo-build-guard classified as the workspace-wide test script and BLOCKED. There was no\n * build anywhere in that command; it polled npm and GitHub.\n *\n * Quoting is precisely how a shell says \"this is DATA, not syntax\", so honouring the quotes is the\n * correct reading. And because commandCode only ever feeds blocklist-shaped guards, dropping more\n * can only ever block LESS — never turn an allowed command into a refused one.\n */\n private stripProse(command: string): string {\n const withoutHeredocs = command.replace(HEREDOC_BODY, ' ');\n return withoutHeredocs.replace(\n QUOTED_SPAN,\n (match: string, single?: string, double?: string): string => {\n const content = single ?? double ?? '';\n if (/\\s/.test(content)) return ' ';\n return SHELL_METACHARACTER.test(content) ? ' ' : content;\n },\n );\n }\n}\n\nexport class FileContext {\n readonly tool: ToolKind;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n /** The git tree that owns filePath. workspaceRoot remains the root that owns policy/config. */\n readonly targetRoot: string;\n /** filePath relative to targetRoot, independent of its governed-root spelling. */\n readonly targetRelativePath: string;\n readonly currentFileLines: number;\n readonly linesAdded: number;\n readonly linesRemoved: number;\n readonly projectedFileLines: number;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n readonly proposedFile: ProposedFile | null,\n currentFileLines: number,\n linesAdded: number,\n linesRemoved: number,\n projectedFileLines: number,\n targetRoot: string = workspaceRoot,\n targetRelativePath: string = relativePath,\n ) {\n this.tool = tool;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.targetRoot = targetRoot;\n this.targetRelativePath = targetRelativePath;\n this.currentFileLines = currentFileLines;\n this.linesAdded = linesAdded;\n this.linesRemoved = linesRemoved;\n this.projectedFileLines = projectedFileLines;\n this.options = {};\n }\n}\n\n/**\n * The shape of a client hook policy returned by its declared runtime factory.\n * It carries only metadata + a `check` method — no on/off logic of its own.\n */\nexport interface PlainRule {\n readonly name: string;\n readonly description: string;\n readonly scope: RuleScope;\n readonly files: readonly string[];\n readonly defaultOptions: RuleOptions;\n readonly fixHint: FixHint;\n check(ctx: EditContext | FileContext | BashContext): readonly Violation[];\n}\n\n/**\n * The runtime contract the runner iterates. Both the built-in rule classes (which extend\n * EditRuleBase/FileRuleBase/BashRuleBase) and the custom-rule adapter satisfy this: they add\n * `shouldRun()` (mode + escape-hatch decision) on top of the PlainRule metadata.\n */\nexport interface Rule extends PlainRule {\n /**\n * The webpieces.config.json key whose entry configures this rule — NOT necessarily `name`.\n *\n * `name` is the operator identity (what a decision-log line and a deny report carry); `configKey`\n * is the switch. They differ wherever several classes implement one POLICY: all four branch-state\n * guards read `branch-state-guard`, all four PR-lifecycle guards read `pr-lifecycle-guard`. Every\n * consumer that asks \"which section does this live in?\" (filterByMode) or \"does this have an\n * entry?\" (the fault-Y config-sync check) must read THIS field, because asking for `name` there\n * demands entries under keys the validator rejects as retired.\n */\n readonly configKey: string;\n shouldRun(): boolean;\n /**\n * True when this rule's own `excludePaths` matches the workspace-relative path (#1253). The engine\n * asks it before dispatching the rule on a path, exactly as it asks shouldRun() — no rule filters\n * its own paths. AbstractRule supplies it.\n */\n excludesPath(relativePath: string): boolean;\n}\n\nexport class RuleGroup {\n readonly ruleName: string;\n readonly ruleDescription: string;\n readonly fixHint: FixHint;\n readonly violations: readonly Violation[];\n\n constructor(\n ruleName: string,\n ruleDescription: string,\n fixHint: FixHint,\n violations: readonly Violation[],\n ) {\n this.ruleName = ruleName;\n this.ruleDescription = ruleDescription;\n this.fixHint = fixHint;\n this.violations = violations;\n }\n}\n\nexport class BlockedResult {\n readonly report: string;\n /**\n * The L0 fault this block IS, in the codebook's own letter (see core/l0-fault-codes.ts), or `-` for\n * an ordinary rule block.\n *\n * It rides on the result rather than being re-derived from the report text because the block is\n * decided deep in the runner (fault C in configMissingBlock, fault Y during owner-config validation) and\n * STAMPED by the adapter at the terminal boundary, several frames up. Scraping the report for a\n * fault would be a second answer to a question the producer already knows.\n */\n readonly fault: string;\n\n constructor(report: string, fault: string = L0_FAULT_NONE) {\n this.report = report;\n this.fault = fault;\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export * from './core/custom-rule-adapter';
|
|
|
11
11
|
export * from './core/strip-ts-noise';
|
|
12
12
|
export * from './core/disable-directives';
|
|
13
13
|
export * from './core/build-context';
|
|
14
|
+
export * from './core/proposed-file';
|
|
14
15
|
export * from './core/report';
|
|
15
16
|
export * from './core/effective-tree';
|
|
16
17
|
export * from './core/command-scan';
|
package/src/index.js
CHANGED
|
@@ -38,6 +38,7 @@ tslib_1.__exportStar(require("./core/custom-rule-adapter"), exports);
|
|
|
38
38
|
tslib_1.__exportStar(require("./core/strip-ts-noise"), exports);
|
|
39
39
|
tslib_1.__exportStar(require("./core/disable-directives"), exports);
|
|
40
40
|
tslib_1.__exportStar(require("./core/build-context"), exports);
|
|
41
|
+
tslib_1.__exportStar(require("./core/proposed-file"), exports);
|
|
41
42
|
tslib_1.__exportStar(require("./core/report"), exports);
|
|
42
43
|
tslib_1.__exportStar(require("./core/effective-tree"), exports);
|
|
43
44
|
tslib_1.__exportStar(require("./core/command-scan"), exports);
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/hook-runtime/src/index.ts"],"names":[],"mappings":";;;;AAAA,uCAYoB;AAVhB,oGAAA,QAAQ,OAAA;AACR,2GAAA,eAAe,OAAA;AAIf,0GAAA,cAAc,OAAA;AACd,+GAAA,mBAAmB,OAAA;AACnB,+GAAA,mBAAmB,OAAA;AACnB,yGAAA,aAAa,OAAA;AACb,0GAAA,cAAc,OAAA;AAElB,qCAAkE;AAAzD,sGAAA,WAAW,OAAA;AAAE,mGAAA,QAAQ,OAAA;AAAE,yGAAA,cAAc,OAAA;AAC9C,uCAAsC;AAA7B,oGAAA,QAAQ,OAAA;AACjB,2CAAgF;AAAvE,6GAAA,eAAe,OAAA;AAAE,4GAAA,cAAc,OAAA;AAAE,6GAAA,eAAe,OAAA;AACzD,mDAAiD;AAAxC,+GAAA,aAAa,OAAA;AACtB,uCAAsD;AAA7C,mGAAA,OAAO,OAAA;AAAE,2GAAA,eAAe,OAAA;AAEjC,sCAWsB;AARlB,kGAAA,SAAS,OAAA;AACT,oGAAA,WAAW,OAAA;AACX,oGAAA,WAAW,OAAA;AACX,oGAAA,WAAW,OAAA;AAGX,kGAAA,SAAS,OAAA;AACT,sGAAA,aAAa,OAAA;AAEjB,0DAAgC;AAChC,2DAAiC;AACjC,qEAA2C;AAC3C,gEAAsC;AACtC,oEAA0C;AAC1C,+DAAqC;AACrC,wDAA8B;AAC9B,gEAAsC;AACtC,8DAAoC;AACpC,6DAAmC;AACnC,gEAAsC;AACtC,qEAA2C;AAC3C,mEAAyC;AACzC,mEAAyC;AACzC,mEAAyC;AACzC,+DAAqC;AACrC,oEAA0C;AAC1C,yEAA+C;AAC/C,mEAAyC;AACzC,+DAAqC;AACrC,iEAAuC;AACvC,0EAAgD;AAChD,iEAAuC;AAEvC,mDAA4D;AAAnD,0HAAA,wBAAwB,OAAA;AAEjC,+DAAiE;AAAxD,+HAAA,uBAAuB,OAAA","sourcesContent":["export {\n AiType,\n AI_TYPES,\n AI_TYPE_UNKNOWN,\n HookMode,\n ToolKind,\n AgentEventKind,\n NormalizedEdit,\n NormalizedToolInput,\n NormalizedBashInput,\n FileOperation,\n AgentHookEvent,\n} from './protocol';\nexport { HookOutcome, HookArgs, HookTerminated } from './outcome';\nexport { denyJson } from './response';\nexport { HookStdinSource, HookStdoutSink, HookProcessExit } from './hook-ports';\nexport { HookEvaluator } from './hook-evaluator';\nexport { HookApp, HookBootFailure } from './hook-app';\n\nexport {\n RuleScope,\n IsLineDisabled,\n Violation,\n EditContext,\n FileContext,\n BashContext,\n Rule,\n PlainRule,\n RuleGroup,\n BlockedResult,\n} from './core/types';\nexport * from './core/fix-hint';\nexport * from './core/rule-base';\nexport * from './core/custom-rule-adapter';\nexport * from './core/strip-ts-noise';\nexport * from './core/disable-directives';\nexport * from './core/build-context';\nexport * from './core/report';\nexport * from './core/effective-tree';\nexport * from './core/command-scan';\nexport * from './core/target-tree';\nexport * from './core/excluded-paths';\nexport * from './core/delete-scoped-rules';\nexport * from './core/apply-patch-parse';\nexport * from './core/shell-read-parity';\nexport * from './adapters/agent-payload';\nexport * from './adapters/detect-ai';\nexport * from './adapters/agent-adapters';\nexport * from './adapters/claude-code-adapter';\nexport * from './adapters/codex-adapter';\nexport * from './core/root-manifest';\nexport * from './core/rule-evaluation';\nexport * from './core/rules/shell-segment-scan';\nexport * from './core/file-evaluation';\n\nexport { HookPolicyRuntimeRequest } from './policy-runtime';\nexport type { HookRuleRuntime } from './policy-runtime';\nexport { HookPolicyContributions } from './policy-contributions';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/hook-runtime/src/index.ts"],"names":[],"mappings":";;;;AAAA,uCAYoB;AAVhB,oGAAA,QAAQ,OAAA;AACR,2GAAA,eAAe,OAAA;AAIf,0GAAA,cAAc,OAAA;AACd,+GAAA,mBAAmB,OAAA;AACnB,+GAAA,mBAAmB,OAAA;AACnB,yGAAA,aAAa,OAAA;AACb,0GAAA,cAAc,OAAA;AAElB,qCAAkE;AAAzD,sGAAA,WAAW,OAAA;AAAE,mGAAA,QAAQ,OAAA;AAAE,yGAAA,cAAc,OAAA;AAC9C,uCAAsC;AAA7B,oGAAA,QAAQ,OAAA;AACjB,2CAAgF;AAAvE,6GAAA,eAAe,OAAA;AAAE,4GAAA,cAAc,OAAA;AAAE,6GAAA,eAAe,OAAA;AACzD,mDAAiD;AAAxC,+GAAA,aAAa,OAAA;AACtB,uCAAsD;AAA7C,mGAAA,OAAO,OAAA;AAAE,2GAAA,eAAe,OAAA;AAEjC,sCAWsB;AARlB,kGAAA,SAAS,OAAA;AACT,oGAAA,WAAW,OAAA;AACX,oGAAA,WAAW,OAAA;AACX,oGAAA,WAAW,OAAA;AAGX,kGAAA,SAAS,OAAA;AACT,sGAAA,aAAa,OAAA;AAEjB,0DAAgC;AAChC,2DAAiC;AACjC,qEAA2C;AAC3C,gEAAsC;AACtC,oEAA0C;AAC1C,+DAAqC;AACrC,+DAAqC;AACrC,wDAA8B;AAC9B,gEAAsC;AACtC,8DAAoC;AACpC,6DAAmC;AACnC,gEAAsC;AACtC,qEAA2C;AAC3C,mEAAyC;AACzC,mEAAyC;AACzC,mEAAyC;AACzC,+DAAqC;AACrC,oEAA0C;AAC1C,yEAA+C;AAC/C,mEAAyC;AACzC,+DAAqC;AACrC,iEAAuC;AACvC,0EAAgD;AAChD,iEAAuC;AAEvC,mDAA4D;AAAnD,0HAAA,wBAAwB,OAAA;AAEjC,+DAAiE;AAAxD,+HAAA,uBAAuB,OAAA","sourcesContent":["export {\n AiType,\n AI_TYPES,\n AI_TYPE_UNKNOWN,\n HookMode,\n ToolKind,\n AgentEventKind,\n NormalizedEdit,\n NormalizedToolInput,\n NormalizedBashInput,\n FileOperation,\n AgentHookEvent,\n} from './protocol';\nexport { HookOutcome, HookArgs, HookTerminated } from './outcome';\nexport { denyJson } from './response';\nexport { HookStdinSource, HookStdoutSink, HookProcessExit } from './hook-ports';\nexport { HookEvaluator } from './hook-evaluator';\nexport { HookApp, HookBootFailure } from './hook-app';\n\nexport {\n RuleScope,\n IsLineDisabled,\n Violation,\n EditContext,\n FileContext,\n BashContext,\n Rule,\n PlainRule,\n RuleGroup,\n BlockedResult,\n} from './core/types';\nexport * from './core/fix-hint';\nexport * from './core/rule-base';\nexport * from './core/custom-rule-adapter';\nexport * from './core/strip-ts-noise';\nexport * from './core/disable-directives';\nexport * from './core/build-context';\nexport * from './core/proposed-file';\nexport * from './core/report';\nexport * from './core/effective-tree';\nexport * from './core/command-scan';\nexport * from './core/target-tree';\nexport * from './core/excluded-paths';\nexport * from './core/delete-scoped-rules';\nexport * from './core/apply-patch-parse';\nexport * from './core/shell-read-parity';\nexport * from './adapters/agent-payload';\nexport * from './adapters/detect-ai';\nexport * from './adapters/agent-adapters';\nexport * from './adapters/claude-code-adapter';\nexport * from './adapters/codex-adapter';\nexport * from './core/root-manifest';\nexport * from './core/rule-evaluation';\nexport * from './core/rules/shell-segment-scan';\nexport * from './core/file-evaluation';\n\nexport { HookPolicyRuntimeRequest } from './policy-runtime';\nexport type { HookRuleRuntime } from './policy-runtime';\nexport { HookPolicyContributions } from './policy-contributions';\n"]}
|
package/src/protocol.d.ts
CHANGED
|
@@ -6,11 +6,13 @@ export type HookMode = 'rules' | 'guards' | 'all';
|
|
|
6
6
|
export type ToolKind = 'Write' | 'Edit' | 'MultiEdit' | 'Read' | 'Delete';
|
|
7
7
|
export type AgentEventKind = 'File' | 'Bash' | 'Read' | 'Ignored';
|
|
8
8
|
export declare class NormalizedEdit {
|
|
9
|
+
readonly replaceAll: boolean;
|
|
9
10
|
readonly oldString: string;
|
|
10
11
|
readonly newString: string;
|
|
11
|
-
constructor(oldString: string, newString: string);
|
|
12
|
+
constructor(oldString: string, newString: string, replaceAll: boolean);
|
|
12
13
|
}
|
|
13
14
|
export declare class NormalizedToolInput {
|
|
15
|
+
sourcePath: string;
|
|
14
16
|
readonly filePath: string;
|
|
15
17
|
readonly edits: readonly NormalizedEdit[];
|
|
16
18
|
constructor(filePath: string, edits: readonly NormalizedEdit[]);
|
package/src/protocol.js
CHANGED
|
@@ -4,15 +4,21 @@ exports.AgentHookEvent = exports.FileOperation = exports.NormalizedBashInput = e
|
|
|
4
4
|
exports.AI_TYPES = ['claude-code', 'codex'];
|
|
5
5
|
exports.AI_TYPE_UNKNOWN = 'unknown';
|
|
6
6
|
class NormalizedEdit {
|
|
7
|
+
replaceAll;
|
|
7
8
|
oldString;
|
|
8
9
|
newString;
|
|
9
|
-
constructor(oldString, newString) {
|
|
10
|
+
constructor(oldString, newString, replaceAll) {
|
|
11
|
+
this.replaceAll = replaceAll;
|
|
12
|
+
this.oldString = oldString;
|
|
13
|
+
this.newString = newString;
|
|
14
|
+
}
|
|
10
15
|
}
|
|
11
16
|
exports.NormalizedEdit = NormalizedEdit;
|
|
12
17
|
class NormalizedToolInput {
|
|
18
|
+
sourcePath;
|
|
13
19
|
filePath;
|
|
14
20
|
edits;
|
|
15
|
-
constructor(filePath, edits) { this.filePath = filePath; this.edits = edits; }
|
|
21
|
+
constructor(filePath, edits) { this.filePath = filePath; this.sourcePath = filePath; this.edits = edits; }
|
|
16
22
|
}
|
|
17
23
|
exports.NormalizedToolInput = NormalizedToolInput;
|
|
18
24
|
class NormalizedBashInput {
|
package/src/protocol.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../../../packages/tooling/hook-runtime/src/protocol.ts"],"names":[],"mappings":";;;AAEa,QAAA,QAAQ,GAAsB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AACvD,QAAA,eAAe,GAAG,SAAS,CAAC;AAKzC,MAAa,cAAc;
|
|
1
|
+
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../../../packages/tooling/hook-runtime/src/protocol.ts"],"names":[],"mappings":";;;AAEa,QAAA,QAAQ,GAAsB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AACvD,QAAA,eAAe,GAAG,SAAS,CAAC;AAKzC,MAAa,cAAc;IAGoC;IAFlD,SAAS,CAAS;IAClB,SAAS,CAAS;IAC3B,YAAY,SAAiB,EAAE,SAAiB,EAAW,UAAmB;QAAnB,eAAU,GAAV,UAAU,CAAS;QAAI,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAAC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAAC,CAAC;CAC9I;AAJD,w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SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AA5BD,wCA4BC","sourcesContent":["/** Coding harness that produced an agent-hook call. */\nexport type AiType = 'claude-code' | 'codex';\nexport const AI_TYPES: readonly AiType[] = ['claude-code', 'codex'];\nexport const AI_TYPE_UNKNOWN = 'unknown';\nexport type HookMode = 'rules' | 'guards' | 'all';\nexport type ToolKind = 'Write' | 'Edit' | 'MultiEdit' | 'Read' | 'Delete';\nexport type AgentEventKind = 'File' | 'Bash' | 'Read' | 'Ignored';\n\nexport class NormalizedEdit {\n readonly oldString: string;\n readonly newString: string;\n constructor(oldString: string, newString: string, readonly replaceAll: boolean) { this.oldString = oldString; this.newString = newString; }\n}\n\nexport class NormalizedToolInput {\n sourcePath: string;\n readonly filePath: string;\n readonly edits: readonly NormalizedEdit[];\n constructor(filePath: string, edits: readonly NormalizedEdit[]) { this.filePath = filePath; this.sourcePath = filePath; this.edits = edits; }\n}\n\nexport class NormalizedBashInput {\n readonly command: string;\n constructor(command: string) { this.command = command; }\n}\n\nexport class FileOperation {\n readonly toolKind: ToolKind;\n readonly input: NormalizedToolInput;\n constructor(toolKind: ToolKind, input: NormalizedToolInput) { this.toolKind = toolKind; this.input = input; }\n}\n\n/** One normalized hook event, independent of the source harness and rule product. */\nexport class AgentHookEvent {\n readonly aiType: AiType;\n readonly kind: AgentEventKind;\n readonly rawToolName: string;\n readonly cwd: string;\n readonly sessionId: string;\n readonly agentId: string;\n readonly agentType: string;\n readonly files: readonly FileOperation[];\n readonly bash: NormalizedBashInput | null;\n readonly reads: readonly string[];\n\n constructor(\n aiType: AiType, kind: AgentEventKind, rawToolName: string, cwd: string, sessionId: string,\n agentId: string, agentType: string, files: readonly FileOperation[],\n bash: NormalizedBashInput | null, reads: readonly string[],\n ) {\n this.aiType = aiType;\n this.kind = kind;\n this.rawToolName = rawToolName;\n this.cwd = cwd;\n this.sessionId = sessionId;\n this.agentId = agentId;\n this.agentType = agentType;\n this.files = files;\n this.bash = bash;\n this.reads = reads;\n }\n}\n"]}
|