@agent-corpus/policy-manager 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 agent-corpus contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,139 @@
1
- # Temporary Holding Version
1
+ # @agent-corpus/policy-manager
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A coding-agent-independent permission evaluator. It starts a private background service for each session, verifies ordinary code operations and cloud inspection commands, and records requests and decisions in a temporary audit log. Uses the shared `@agent-corpus/audit-log` package and makes no model API calls.
4
+
5
+ This is a conservative initial implementation. It grants ordinary operations through deterministic checks. For additional cloud inspection operations, AI can confirm a bounded read-only candidate. A same-session AI classifier can categorize candidates and recommend structured replacements for opaque commands. Confidence alone never authorizes an opaque command.
6
+
7
+ ## Usage
8
+
9
+ Build from an inspected worktree with `npm install` and `npm run build`. Install the reviewed package outside agent-writable worktrees before using it as an approval authority. The initial package is not yet published.
10
+
11
+ ```sh
12
+ policy-manager usage --json
13
+ policy-manager config codex /absolute/reviewed/install/dist/cli.js
14
+ policy-manager config claude /absolute/reviewed/install/dist/cli.js
15
+ policy-manager config copilot /absolute/reviewed/install/dist/cli.js
16
+ ```
17
+
18
+ `config` prints configuration. It does not change permissions or install hooks. Merge its output into the native settings without replacing existing hooks or permission rules:
19
+
20
+ | CLI | Destination | Activation |
21
+ | ----------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------- |
22
+ | Claude Code | `~/.claude/settings.json` or repository `.claude/settings.json` | Review configuration, then start a new session. |
23
+ | Codex | `~/.codex/hooks.json` or repository `.codex/hooks.json` | Review and trust the exact hooks with `/hooks`. |
24
+ | Copilot | `~/.copilot/hooks/policy-manager.json` or `.github/hooks/policy-manager.json` | Start a new session. Sandbox escape still needs human confirmation. |
25
+
26
+ Use the generated absolute installed path. Do not point approval hooks at a mutable worktree or an unpinned `npx` download. Keep native sandboxes and interactive approval modes enabled. Existing host grants and other hooks can authorize actions independently; this service does not revoke them.
27
+
28
+ The `SessionStart` hook starts one deterministic service and injects instructions to create a read-only policy-manager agent. Creation of the AI agent is a model action, not a native hook guarantee. Resident-agent availability varies by harness. This release has not established automatic resident-agent parity across the three CLIs. The fallback can run in the parent session when resident agents are unavailable.
29
+
30
+ ## Install native hooks
31
+
32
+ Install the reviewed package outside Git checkouts, then run one setup command:
33
+
34
+ ```sh
35
+ policy-manager setup-hook-claude --dry-run
36
+ policy-manager setup-hook-claude
37
+ policy-manager setup-hook-codex
38
+ policy-manager setup-hook-copilot
39
+ ```
40
+
41
+ The canonical form is `policy-manager setup-hook <claude|codex|copilot>`. Each alias uses that same implementation. Setup connects native tool, permission, execution-report, startup, and shutdown hooks directly to the deterministic service. The working AI does not need to request policy-manager approval for recognized native hook events.
42
+
43
+ Setup merges only the managed hook definitions. Existing custom hooks, permissions, settings, allow rules, and deny rules remain. Repeated setup is idempotent. Package upgrades replace hooks carrying the managed marker; unmarked manual entries remain. Existing settings receive an owner-only backup, and updates use a temporary file with atomic replacement. Invalid JSON, unsupported schemas, symbolic links, concurrent setup, and detected concurrent edits fail without replacing the existing settings.
44
+
45
+ `--dry-run` prints the target path, proposed managed hooks, and next steps without writing files or printing existing settings. `--config-dir <directory>` selects a harness configuration root for portable profiles or testing. Defaults respect `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, and `COPILOT_HOME`, then use the standard user directories listed above. Setup refuses to activate an entrypoint inside a Git checkout, including an npm link into a checkout. Source builds can preview with `--dry-run`.
46
+
47
+ Start a new session after setup. Codex still requires explicit review and trust through `/hooks`; setup does not grant that trust. Existing sandbox controls and host permission rules continue to apply. Ambiguous requests retain the documented classification or human fallback; setup does not enable automatic AI fallback across unsupported native interfaces.
48
+
49
+ ## Request protocol
50
+
51
+ Pass one JSON object on standard input:
52
+
53
+ ```json
54
+ {
55
+ "sessionId": "session-example",
56
+ "harness": "codex",
57
+ "cwd": "/absolute/worktree",
58
+ "tool": "Bash",
59
+ "input": { "command": "az resource list" }
60
+ }
61
+ ```
62
+
63
+ Run `policy-manager review codex session-example`. The response includes `decision` (`approve` or `human`), `category`, `reason`, `requestHash`, `cache`, and `cached`. The library exports the same evaluator.
64
+
65
+ The session's policy-manager agent returns the following object for an ambiguous request. The working agent submits it through `policy-manager classify codex session-example`:
66
+
67
+ ```json
68
+ { "requestHash": "<exact hash from review>", "category": "unknown", "confidence": 0.4 }
69
+ ```
70
+
71
+ Categories are `code-read`, `worktree-write`, `cloud-read`, `git-read`, `impactful-write`, `destructive`, `sensitive`, and `unknown`. The threshold is 0.99 plus deterministic verification and category agreement. Explicitly listed metadata operations with permitted selectors can qualify through AI classification. Endpoint overrides and cloud writes cannot qualify. Unknown commands stay human decisions. No classifier starts a second harness or calls an external model API.
72
+
73
+ ## Policy
74
+
75
+ - Ordinary file reads must resolve inside a Git repository.
76
+ - Ordinary file writes must resolve inside a linked worktree on a feature branch.
77
+ - Main clones, protected branches, credentials, Git metadata, policy files, and hook settings require human approval.
78
+ - Structured patches check all add, update, and move paths. Deletions require human approval.
79
+ - Cloud reads use exact inspection and metadata operation catalogs with permitted options. Credential-returning settings, connection strings, publishing credentials, and storage keys are sensitive before AI classification. Unknown verbs, endpoint overrides, secret retrieval, and cloud writes require human approval.
80
+ - A small Git inspection subset, `git fetch origin` with a verified network transport, and constrained feature worktree creation under `.worktrees/` are automatic. Branch deletion reports upstream and reachability evidence, but always requires a human. Fetched remote references can be stale.
81
+ - Shell expansions, pipelines, interpreters, package scripts, and unknown effects require human review. A worktree does not establish their safety.
82
+
83
+ These are approval recommendations, not a sandbox. Trusted local executables and their configuration remain part of the host's trust boundary. Hooks cannot observe every hosted tool or prevent arbitrary same-user processes from changing files. Recheck path evidence on every request; filesystem races still require host enforcement.
84
+
85
+ ## Service, cache, and logs
86
+
87
+ The service uses a Unix socket on macOS/Linux and a named pipe on Windows. A random session token authenticates local requests. Files use owner-only modes on Unix. On Windows, the operating system's temporary-directory ACL is the access boundary; Unix modes do not establish Windows ACL isolation. Other processes running as the same user are outside this boundary.
88
+
89
+ The cache belongs to the service process and is scoped to harness plus session ID. It holds at most 512 cloud-inspection decisions, expires entries after one minute, and evaluates policy before lookup. Filesystem and branch evidence is never cached. `SessionEnd` or `policy-manager stop <harness> <session-id>` stops the service. An idle service stops after 30 minutes. Requests restart it when necessary; crash-created stale sockets require inspection rather than unsafe automatic deletion.
90
+
91
+ `SessionStart` reports the private temporary directory containing `audit.jsonl`. Each request and decision is recorded before an approval is returned. The log stores versioned event envelopes, readable action summaries, opaque session identifiers, request hashes, and hashed targets. It excludes paths, argument values, source text, credentials, and model explanations. Compare request hashes against the original request in the harness transcript during an investigation. Logs rotate at 10 MiB per segment and stop accepting writes at 100 MiB total. Earlier segments remain available through `audit-log query` and `audit-log export`; no records are automatically deleted. Logs remain after normal shutdown and can disappear during operating-system cleanup. Copy them before cleanup when needed.
92
+
93
+ Logging failure, malformed requests, service failure, and unknown semantics never produce an automatic approval. Permission hooks fall through to native human handling. Pre-tool failures exit 2. Host timeout behavior differs: Copilot command-hook timeouts fall through to its normal permission flow. Codex does not support `ask` in `PreToolUse`, so human recommendations add context and leave native permission handling unchanged.
94
+
95
+ ## Audit API and reported outcomes
96
+
97
+ Every policy event uses the shared audit-log schema: `schemaVersion`, unique `eventId`, UTC `timestamp` and `observedTimestamp`, `eventName`, `source`, opaque `sessionId`, optional `requestId`, `severityText`, `summary`, and `attributes`. The existing private session directory remains the storage location. `requestId` is the normalized request hash; repeated identical requests share correlation, and distinct `eventId` values identify each observation.
98
+
99
+ ```sh
100
+ audit-log query /private/session-directory --request-id REQUEST_HASH
101
+ audit-log export /private/session-directory > investigation.jsonl
102
+ policy-manager record codex session-example < outcome.json
103
+ ```
104
+
105
+ The record command accepts a host-reported event:
106
+
107
+ ```json
108
+ { "event": "human-response", "requestHash": "<64-character request hash>", "response": "approved" }
109
+ ```
110
+
111
+ Or an execution report:
112
+
113
+ ```json
114
+ {
115
+ "event": "execution-result",
116
+ "requestHash": "<64-character request hash>",
117
+ "status": "succeeded",
118
+ "exitCode": 0,
119
+ "durationMs": 12
120
+ }
121
+ ```
122
+
123
+ Human responses are `approved` or `denied`. Execution statuses are `completed`, `succeeded`, `failed`, or `cancelled`. Reports use the source `policy-manager.adapter-report`. They are observations declared by the caller and never modify permission decisions or caches. The API does not authenticate a human identity. A denial policy remains a human decision even after an approval report is recorded.
124
+
125
+ Generated post-tool hooks record execution reports for the supported tool matcher. Claude and Copilot also get failure hooks. Codex uses `PostToolUse`, which can carry nonzero exit codes. When an exit code is absent, the adapter records `completed` rather than inventing success. Output text and error bodies are discarded. Human responses require an explicit report from the host; the native hooks do not provide a universal human-response signal.
126
+
127
+ The shared logger redacts structured sensitive fields, validates events, locks concurrent access, and flushes each append. Queries cover active and rotated segments. Busy storage, a stale lock, incomplete records, capacity limits, or write failures prevent automatic approval. The initial API is a library plus CLI; an additional resident logging server is deferred until another consumer needs one.
128
+
129
+ ## Validation and support
130
+
131
+ Tests exercise real service processes and native-shaped hook payloads for all three CLIs. These protocol tests are separate from authenticated live model sessions. CLI versions inspected during development: Claude Code 2.1.316, Codex CLI 0.166.0, Copilot CLI 1.0.104. Full live-session approval, resident-agent startup, and desktop validation remain rollout work. Do not describe generated hook configurations as an installed policy.
132
+
133
+ Verified documentation, November 5, 2026:
134
+
135
+ - [Claude Code hooks](https://code.claude.com/docs/en/hooks)
136
+ - [Codex hooks](https://learn.chatgpt.com/docs/hooks)
137
+ - [Copilot hooks](https://docs.github.com/en/copilot/reference/hooks-reference)
138
+
139
+ Exit codes: 0 means a protocol response was returned; inspect `decision` before acting. 1 means invalid input or service failure. Pre-tool hook failures use 2. Diagnostics use stderr and contain no raw request data.
@@ -0,0 +1,5 @@
1
+ import type { Decision, OutcomeReport, Request } from "./types.js";
2
+ export declare function normalize(harness: Request["harness"], payload: Record<string, unknown>): Request;
3
+ export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision): Record<string, unknown>;
4
+ export declare function executionReport(request: Request, phase: string, payload: Record<string, unknown>): OutcomeReport;
5
+ //# sourceMappingURL=adapters.d.ts.map
@@ -0,0 +1,73 @@
1
+ import { hash } from "./policy.js";
2
+ export function normalize(harness, payload) {
3
+ let input = payload.tool_input ?? payload.toolInput ?? payload.toolArgs ?? {};
4
+ if (typeof input === "string")
5
+ input = JSON.parse(input);
6
+ if (!input || typeof input !== "object" || Array.isArray(input))
7
+ throw new Error("Invalid tool input");
8
+ const args = input;
9
+ const cwd = args.workdir ?? args.cwd ?? payload.cwd;
10
+ return {
11
+ sessionId: String(payload.session_id ?? payload.sessionId ?? ""),
12
+ harness,
13
+ cwd: typeof cwd === "string" ? cwd : "",
14
+ tool: String(payload.tool_name ?? payload.toolName ?? ""),
15
+ input: args,
16
+ };
17
+ }
18
+ export function hookResponse(harness, phase, decision) {
19
+ if (harness === "copilot") {
20
+ if (phase === "PermissionRequest")
21
+ return decision.decision === "approve" ? { behavior: "allow" } : {};
22
+ return decision.decision === "approve"
23
+ ? { permissionDecision: "allow" }
24
+ : { permissionDecision: "ask", permissionDecisionReason: decision.reason };
25
+ }
26
+ if (phase === "PermissionRequest")
27
+ return decision.decision === "approve"
28
+ ? { hookSpecificOutput: { hookEventName: phase, decision: { behavior: "allow" } } }
29
+ : {};
30
+ if (decision.decision === "approve")
31
+ return { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
32
+ if (harness === "codex")
33
+ return {
34
+ hookSpecificOutput: {
35
+ hookEventName: phase,
36
+ additionalContext: `${decision.reason}. Request ${decision.requestHash}. The policy manager grants no approval. Classify ambiguous requests with the session policy-manager agent. Preserve the native human approval flow.`,
37
+ },
38
+ };
39
+ return {
40
+ hookSpecificOutput: {
41
+ hookEventName: phase,
42
+ permissionDecision: "ask",
43
+ permissionDecisionReason: decision.reason,
44
+ },
45
+ };
46
+ }
47
+ export function executionReport(request, phase, payload) {
48
+ const response = payload.tool_response ?? payload.toolResponse ?? payload.tool_result ?? payload.toolResult;
49
+ const result = response && typeof response === "object" ? response : {};
50
+ const code = result.exit_code ?? result.exitCode;
51
+ const exitCode = typeof code === "number" && Number.isSafeInteger(code) && Math.abs(code) <= 2147483647
52
+ ? code
53
+ : undefined;
54
+ const duration = payload.duration_ms ?? payload.durationMs;
55
+ return {
56
+ requestHash: hash(request),
57
+ event: "execution-result",
58
+ status: phase === "PostToolUseFailure"
59
+ ? payload.is_interrupt === true
60
+ ? "cancelled"
61
+ : "failed"
62
+ : exitCode === undefined
63
+ ? "completed"
64
+ : exitCode === 0
65
+ ? "succeeded"
66
+ : "failed",
67
+ ...(exitCode === undefined ? {} : { exitCode }),
68
+ ...(typeof duration === "number" && Number.isFinite(duration) && duration >= 0
69
+ ? { durationMs: duration }
70
+ : {}),
71
+ };
72
+ }
73
+ //# sourceMappingURL=adapters.js.map
@@ -0,0 +1,6 @@
1
+ import type { Request } from "./types.js";
2
+ export declare function sessionDirectory(harness: string, sessionId: string): string;
3
+ export declare function sessionToken(directory: string): string;
4
+ export declare function audit(directory: string, event: Record<string, unknown>): void;
5
+ export declare function requestSummary(request: Request): Record<string, unknown>;
6
+ //# sourceMappingURL=audit.d.ts.map
package/dist/audit.js ADDED
@@ -0,0 +1,95 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, join } from "node:path";
5
+ import { AuditLog } from "@agent-corpus/audit-log";
6
+ import { hash, words } from "./policy.js";
7
+ const vocabulary = new Set("git az aws gcloud cat rm terraform resource group network monitor servicebus queue topic storage blob webapp appservice containerapp vm disk ec2 rds s3api cloudformation logs cloudwatch sqs sns ecs eks compute instances projects container run sql pubsub logging monitoring log-analytics workspace boards work-item account list show query create update delete destroy purge status diff log fetch origin branch worktree add describe-instances describe-volumes describe-stacks".split(" "));
8
+ const tools = new Set("Read Write Edit view create edit Bash bash powershell exec_command apply_patch shell read_file write_file".split(" "));
9
+ export function sessionDirectory(harness, sessionId) {
10
+ if (!sessionId || !["claude", "codex", "copilot"].includes(harness))
11
+ throw new Error("A harness and session ID are required");
12
+ const path = join(tmpdir(), `acp-${process.getuid?.() ?? "user"}-${hash([harness, sessionId]).slice(0, 24)}`);
13
+ try {
14
+ mkdirSync(path, { mode: 0o700 });
15
+ }
16
+ catch (error) {
17
+ if (error.code !== "EEXIST")
18
+ throw error;
19
+ }
20
+ const stat = lstatSync(path);
21
+ if (!stat.isDirectory() ||
22
+ stat.isSymbolicLink() ||
23
+ (process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0)))
24
+ throw new Error("Unsafe session directory");
25
+ return path;
26
+ }
27
+ export function sessionToken(directory) {
28
+ const path = join(directory, "token");
29
+ try {
30
+ writeFileSync(path, randomBytes(32).toString("hex"), { flag: "wx", mode: 0o600 });
31
+ }
32
+ catch (error) {
33
+ if (error.code !== "EEXIST")
34
+ throw error;
35
+ }
36
+ if (lstatSync(path).isSymbolicLink())
37
+ throw new Error("Unsafe token file");
38
+ return readFileSync(path, "utf8");
39
+ }
40
+ export function audit(directory, event) {
41
+ const { event: name, summary, requestHash, ...attributes } = event;
42
+ if (typeof name !== "string")
43
+ throw new Error("Invalid policy audit event");
44
+ new AuditLog(directory).append({
45
+ eventName: name,
46
+ source: name === "human-response" || name === "execution-result"
47
+ ? "policy-manager.adapter-report"
48
+ : "policy-manager",
49
+ sessionId: basename(directory),
50
+ ...(typeof requestHash === "string" && /^[a-f0-9]{64}$/.test(requestHash)
51
+ ? { requestId: requestHash }
52
+ : {}),
53
+ severityText: name === "evaluation-failure" ? "ERROR" : "INFO",
54
+ ...(typeof summary === "string" ? { summary } : {}),
55
+ attributes,
56
+ });
57
+ }
58
+ export function requestSummary(request) {
59
+ const command = request.input.command ?? request.input.cmd;
60
+ const argv = typeof command === "string" ? words(command) : undefined;
61
+ const operation = argv?.slice(0, 4).filter((word, index) => index === 0 || !word.startsWith("-"));
62
+ const action = operation?.map((word) => (vocabulary.has(word) ? word : "[REDACTED]")).join(" ");
63
+ const file = request.input.file_path ?? request.input.path;
64
+ const selectors = new Set([
65
+ "--ids",
66
+ "--name",
67
+ "--resource-group",
68
+ "--subscription",
69
+ "--project",
70
+ "--namespace-name",
71
+ "--workspace",
72
+ "--region",
73
+ "--zone",
74
+ ]);
75
+ const targets = argv?.flatMap((word, index) => selectors.has(word) && argv[index + 1] !== undefined
76
+ ? [{ selector: word, valueHash: hash(argv[index + 1]) }]
77
+ : []) ?? [];
78
+ return {
79
+ summary: action ??
80
+ (tools.has(request.tool) ? `${request.tool} tool operation` : "Unrecognized tool operation"),
81
+ action: action ?? "tool operation",
82
+ tool: tools.has(request.tool) ? request.tool : "other",
83
+ ...(typeof file === "string" ? { targetHash: hash([request.cwd, file]) } : {}),
84
+ ...(targets.length ? { targets } : {}),
85
+ requestHash: hash(request),
86
+ harness: request.harness,
87
+ sessionHash: hash(request.sessionId),
88
+ cwdHash: hash(request.cwd),
89
+ toolHash: hash(request.tool),
90
+ inputKeys: Object.keys(request.input).map((key) => hash(key)),
91
+ // Keep action terms and hashed targets; omit raw payloads and argument values.
92
+ executable: argv && /^(?:git|az|aws|gcloud|cat|rm|terraform)$/.test(argv[0] ?? "") ? argv[0] : "other",
93
+ };
94
+ }
95
+ //# sourceMappingURL=audit.js.map
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
package/dist/cli.js ADDED
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { parseArgs } from "node:util";
5
+ import { executionReport, hookResponse, normalize } from "./adapters.js";
6
+ import { hookConfig } from "./config.js";
7
+ import { send, serve, start } from "./service.js";
8
+ import { SetupError, setupHook } from "./setup.js";
9
+ const usage = `policy-manager usage [--json]
10
+ policy-manager hook <claude|codex|copilot> <SessionStart|PreToolUse|PermissionRequest|PostToolUse|PostToolUseFailure|SessionEnd>
11
+ policy-manager review <claude|codex|copilot> <session-id> # normalized request JSON on stdin
12
+ policy-manager classify <claude|codex|copilot> <session-id> # {requestHash,category,confidence} on stdin
13
+ policy-manager record <claude|codex|copilot> <session-id> # host-reported human response or execution result JSON
14
+ policy-manager setup-hook <claude|codex|copilot> [--dry-run] [--config-dir <harness-config-directory>]
15
+ policy-manager setup-hook-claude|setup-hook-codex|setup-hook-copilot [--dry-run] [--config-dir <directory>]
16
+ policy-manager config <claude|codex|copilot> <absolute-installed-cli-path>
17
+ policy-manager stop <claude|codex|copilot> <session-id>
18
+ A per-session background service checks policy and writes private temporary audit.jsonl logs.
19
+ AI classification comes from the session's policy-manager agent, never an external API.
20
+ Unknown effects require human approval. Exit 0: protocol response; exit 1: malformed input or service failure.
21
+ `;
22
+ async function stdin() {
23
+ let text = "";
24
+ for await (const chunk of process.stdin) {
25
+ text += chunk.toString();
26
+ if (text.length > 1024 * 1024)
27
+ throw new Error("Oversized request");
28
+ }
29
+ const value = JSON.parse(text);
30
+ if (!value || typeof value !== "object" || Array.isArray(value))
31
+ throw new Error("Expected a JSON object");
32
+ return value;
33
+ }
34
+ const args = process.argv.slice(2);
35
+ const [action, harnessArg, phase] = args;
36
+ const harness = harnessArg;
37
+ const cliPath = fileURLToPath(import.meta.url);
38
+ try {
39
+ if (action === "usage" || !action)
40
+ console.log(args.includes("--json") ? JSON.stringify({ usage }) : usage);
41
+ else if (action === "setup-hook" || /^setup-hook-(claude|codex|copilot)$/.test(action)) {
42
+ const alias = action.match(/^setup-hook-(claude|codex|copilot)$/)?.[1];
43
+ const selected = (alias ?? harnessArg);
44
+ const { values } = parseArgs({
45
+ args: args.slice(alias ? 1 : 2),
46
+ options: { "dry-run": { type: "boolean" }, "config-dir": { type: "string" } },
47
+ });
48
+ console.log(JSON.stringify(setupHook(selected, cliPath, {
49
+ dryRun: values["dry-run"],
50
+ configDirectory: values["config-dir"],
51
+ }), null, 2));
52
+ }
53
+ else if (action === "config")
54
+ console.log(JSON.stringify(hookConfig(harness, phase ?? ""), null, 2));
55
+ else if (action === "serve")
56
+ await serve(harness, phase ?? "");
57
+ else if (action === "stop")
58
+ console.log(JSON.stringify(await send(harness, phase ?? "", { action: "stop" })));
59
+ else if (action === "review" || action === "classify" || action === "record") {
60
+ const payload = await stdin();
61
+ await start(harness, phase ?? "", cliPath);
62
+ const result = await send(harness, phase ?? "", action === "review"
63
+ ? { action, request: payload }
64
+ : action === "classify"
65
+ ? { action, classification: payload }
66
+ : { action, report: payload });
67
+ console.log(JSON.stringify(result));
68
+ }
69
+ else if (action === "hook") {
70
+ const payload = await stdin();
71
+ const request = normalize(harness, payload);
72
+ if (phase === "SessionEnd") {
73
+ await send(harness, request.sessionId, { action: "stop" });
74
+ console.log("{}");
75
+ }
76
+ else {
77
+ const directory = await start(harness, request.sessionId, cliPath);
78
+ if (phase === "SessionStart") {
79
+ const context = `Policy service started. Audit log: ${join(directory, "audit.jsonl")}. Native hooks route tool and permission requests directly to the deterministic service. For ambiguous requests, use a configured policy-manager agent or retain native human approval. If .agent-config/agents/policy-manager.md exists, read it before creating a read-only policy-manager agent. Never ask an agent to approve its own tools.`;
80
+ console.log(JSON.stringify(harness === "copilot"
81
+ ? { additionalContext: context }
82
+ : { hookSpecificOutput: { hookEventName: phase, additionalContext: context } }));
83
+ }
84
+ else if (phase === "PostToolUse" || phase === "PostToolUseFailure") {
85
+ await send(harness, request.sessionId, {
86
+ action: "record",
87
+ report: executionReport(request, phase, payload),
88
+ });
89
+ console.log("{}");
90
+ }
91
+ else if (phase === "PreToolUse" || phase === "PermissionRequest") {
92
+ const decision = (await send(harness, request.sessionId, {
93
+ action: "review",
94
+ request,
95
+ }));
96
+ console.log(JSON.stringify(hookResponse(harness, phase, decision)));
97
+ }
98
+ else
99
+ throw new Error("Unsupported hook event");
100
+ }
101
+ }
102
+ else
103
+ throw new Error(usage);
104
+ }
105
+ catch (error) {
106
+ if (action?.startsWith("setup-hook")) {
107
+ console.error(error instanceof SetupError
108
+ ? error.message
109
+ : "Hook setup failed. No automatic approval was granted.");
110
+ process.exitCode = 1;
111
+ }
112
+ else if (action === "record" || (action === "hook" && phase?.startsWith("PostToolUse"))) {
113
+ console.error("The audit report could not be recorded. The tool may already have completed.");
114
+ process.exitCode = 1;
115
+ }
116
+ else {
117
+ // Error text can contain paths or secrets. Keep diagnostics fixed.
118
+ console.error("Policy manager failed. Human approval is required. No automatic approval was granted.");
119
+ if (action === "hook" && phase === "PermissionRequest")
120
+ console.log("{}");
121
+ else if (action === "hook" && phase === "PreToolUse") {
122
+ console.error("The policy check could not complete.");
123
+ process.exitCode = 2;
124
+ }
125
+ else
126
+ process.exitCode = 1;
127
+ }
128
+ }
129
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,4 @@
1
+ import type { Request } from "./types.js";
2
+ export declare const managedHookFlag = "--agent-corpus-policy-manager-hook";
3
+ export declare function hookConfig(harness: Request["harness"], cliPath: string): Record<string, unknown>;
4
+ //# sourceMappingURL=config.d.ts.map
package/dist/config.js ADDED
@@ -0,0 +1,47 @@
1
+ import { isAbsolute } from "node:path";
2
+ export const managedHookFlag = "--agent-corpus-policy-manager-hook";
3
+ export function hookConfig(harness, cliPath) {
4
+ if (![cliPath, process.execPath].every((path) => isAbsolute(path) && !/["\r\n$`%]/.test(path)))
5
+ throw new Error("Use a safe absolute path to the reviewed CLI installation");
6
+ if (!["claude", "codex", "copilot"].includes(harness))
7
+ throw new Error("Unknown harness");
8
+ const hooks = {};
9
+ const matcher = "Bash|Read|Edit|Write|apply_patch|bash|powershell|view|read_file|write_file|edit|create|exec_command|shell";
10
+ const phases = [
11
+ "SessionStart",
12
+ "PreToolUse",
13
+ "PermissionRequest",
14
+ "PostToolUse",
15
+ ...(harness === "codex" ? [] : ["PostToolUseFailure"]),
16
+ "SessionEnd",
17
+ ];
18
+ for (const phase of phases) {
19
+ if (harness === "copilot") {
20
+ const event = phase[0]?.toLowerCase() + phase.slice(1);
21
+ hooks[event] = [
22
+ {
23
+ type: "command",
24
+ ...(phase === "PreToolUse" || phase.startsWith("PostToolUse") ? { matcher } : {}),
25
+ exec: process.execPath,
26
+ args: [cliPath, "hook", harness, phase, managedHookFlag],
27
+ timeoutSec: 8,
28
+ },
29
+ ];
30
+ }
31
+ else
32
+ hooks[phase] = [
33
+ {
34
+ ...(phase === "PreToolUse" || phase.startsWith("PostToolUse") ? { matcher } : {}),
35
+ hooks: [
36
+ {
37
+ type: "command",
38
+ command: `"${process.execPath}" "${cliPath}" hook ${harness} ${phase} ${managedHookFlag}`,
39
+ timeout: 8,
40
+ },
41
+ ],
42
+ },
43
+ ];
44
+ }
45
+ return harness === "copilot" ? { version: 1, hooks } : { hooks };
46
+ }
47
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,12 @@
1
+ export declare function git(cwd: string, args: string[]): string;
2
+ export declare function canonical(path: string): string;
3
+ export declare function inside(root: string, path: string): boolean;
4
+ export declare function sensitive(path: string): boolean;
5
+ export declare function protectedPath(path: string): boolean;
6
+ export declare function pathEvidence(cwd: string, input: string, write: boolean): {
7
+ allowed: boolean;
8
+ category: "code-read" | "worktree-write" | "sensitive";
9
+ reason: string;
10
+ };
11
+ export declare function branchEvidence(cwd: string, branch: string): string;
12
+ //# sourceMappingURL=evidence.d.ts.map
@@ -0,0 +1,94 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, realpathSync, statSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
4
+ export function git(cwd, args) {
5
+ return execFileSync("git", ["-c", "core.fsmonitor=false", "-C", cwd, ...args], {
6
+ encoding: "utf8",
7
+ timeout: 3000,
8
+ maxBuffer: 1024 * 1024,
9
+ stdio: ["ignore", "pipe", "ignore"],
10
+ env: Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
11
+ }).trim();
12
+ }
13
+ export function canonical(path) {
14
+ if (existsSync(path))
15
+ return realpathSync(path);
16
+ const parent = dirname(path);
17
+ if (parent === path)
18
+ throw new Error("Cannot resolve path");
19
+ return resolve(canonical(parent), basename(path));
20
+ }
21
+ export function inside(root, path) {
22
+ const rel = relative(root, path);
23
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
24
+ }
25
+ export function sensitive(path) {
26
+ return path
27
+ .split(/[\\/]/)
28
+ .some((part) => /^(?:\.git|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.kube|\.npmrc|\.netrc|credentials?|secrets?|id_rsa|id_ed25519|id_ecdsa|kubeconfig|terraform\.tfstate(?:\..*)?|.*\.(?:pem|key|pfx|p12))$/i.test(part));
29
+ }
30
+ export function protectedPath(path) {
31
+ return path
32
+ .split(/[\\/]/)
33
+ .some((part) => /^(?:\.agent-config|\.local|\.codex|\.claude|\.agents|AGENTS\.md|CLAUDE\.md|\.github)$/i.test(part));
34
+ }
35
+ export function pathEvidence(cwd, input, write) {
36
+ try {
37
+ const lexical = resolve(cwd, input);
38
+ const path = canonical(lexical);
39
+ if (sensitive(path) ||
40
+ sensitive(lexical) ||
41
+ (write && (protectedPath(path) || protectedPath(lexical))))
42
+ return {
43
+ allowed: false,
44
+ category: "sensitive",
45
+ reason: "Protected path requires human approval",
46
+ };
47
+ let parent = existsSync(path) && statSync(path).isDirectory() ? path : dirname(path);
48
+ while (!existsSync(parent))
49
+ parent = dirname(parent);
50
+ const root = canonical(git(parent, ["rev-parse", "--show-toplevel"]));
51
+ if (!inside(root, path))
52
+ throw new Error("Outside repository");
53
+ if (!write)
54
+ return { allowed: true, category: "code-read", reason: "Read within a Git repository" };
55
+ const gitDir = canonical(git(parent, ["rev-parse", "--absolute-git-dir"]));
56
+ const common = canonical(resolve(parent, git(parent, ["rev-parse", "--git-common-dir"])));
57
+ const branch = git(parent, ["branch", "--show-current"]);
58
+ if (gitDir === common || !branch || /^(?:main|master)$/.test(branch))
59
+ return {
60
+ allowed: false,
61
+ category: "worktree-write",
62
+ reason: "Write requires a linked worktree on a feature branch",
63
+ };
64
+ return {
65
+ allowed: true,
66
+ category: "worktree-write",
67
+ reason: "Write within a linked feature worktree",
68
+ };
69
+ }
70
+ catch {
71
+ return {
72
+ allowed: false,
73
+ category: write ? "worktree-write" : "code-read",
74
+ reason: "Cannot verify repository and path evidence",
75
+ };
76
+ }
77
+ }
78
+ export function branchEvidence(cwd, branch) {
79
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9/_-]*$/.test(branch))
80
+ return "Cannot verify branch name";
81
+ try {
82
+ const commit = git(cwd, ["rev-parse", "--verify", `refs/heads/${branch}`]);
83
+ const upstream = git(cwd, ["for-each-ref", "--format=%(upstream)", `refs/heads/${branch}`]);
84
+ const remotes = git(cwd, ["for-each-ref", "--format=%(refname)", "refs/remotes/"])
85
+ .split("\n")
86
+ .filter(Boolean);
87
+ const unique = git(cwd, ["rev-list", "--count", commit, "--not", ...remotes]);
88
+ return `Local branch deletion requires human approval; upstream=${upstream ? "present" : "absent"}; commits absent from fetched remote refs=${unique}; remote state may be stale`;
89
+ }
90
+ catch {
91
+ return "Local branch deletion requires human approval; branch reachability could not be verified";
92
+ }
93
+ }
94
+ //# sourceMappingURL=evidence.js.map