@agent-corpus/policy-manager 0.3.0 → 0.5.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/README.md +56 -5
- package/dist/adapters.d.ts +11 -1
- package/dist/adapters.js +69 -4
- package/dist/cli.js +19 -2
- package/dist/config.js +4 -2
- package/dist/flow.d.ts +9 -0
- package/dist/flow.js +698 -0
- package/dist/permissive.d.ts +15 -6
- package/dist/permissive.js +225 -79
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +60 -1
- package/dist/redact.d.ts +3 -0
- package/dist/redact.js +140 -0
- package/dist/replay.d.ts +2 -0
- package/dist/replay.js +9 -1
- package/dist/review.d.ts +55 -0
- package/dist/review.js +231 -0
- package/dist/script.d.ts +101 -0
- package/dist/script.js +912 -0
- package/dist/service.d.ts +1 -0
- package/dist/service.js +1 -1
- package/dist/session.d.ts +13 -1
- package/dist/session.js +114 -7
- package/dist/setup.js +3 -1
- package/dist/shell.d.ts +6 -3
- package/dist/shell.js +75 -353
- package/dist/types.d.ts +14 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -46,6 +46,18 @@ Setup merges only the managed hook definitions. Existing custom hooks, permissio
|
|
|
46
46
|
|
|
47
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
48
|
|
|
49
|
+
### Codex hook trust
|
|
50
|
+
|
|
51
|
+
Codex runs a non-managed hook only after you review and trust its exact definition, and setup never grants that trust. After `setup-hook-codex`, start Codex and open `/hooks`, review the five policy-manager hooks, and trust them. Until then Codex skips them and prints a warning at startup, so no policy decision is made.
|
|
52
|
+
|
|
53
|
+
Trust is recorded per hook in `config.toml` under `[hooks.state."<hooks.json path>:<event>:0:0"]` as `trusted_hash = "sha256:<hex>"`. The hash covers the event, the matcher, and the hook's command and timeout, so:
|
|
54
|
+
|
|
55
|
+
- Trust is tied to the command text only: Codex hashes the command line, not the script behind it. An upgrade that keeps the same CLI path (for example an in-place `npm install -g` upgrade) keeps trust while the code behind the hooks changes, so review a new version before upgrading in place. An upgrade that changes the command, such as installing into a per-version directory or a Node upgrade that changes `process.execPath` (it is part of the command), makes Codex mark all five hooks as changed and skip them until you trust them again. Re-running `setup-hook-codex` for the same installed version changes nothing and keeps trust.
|
|
56
|
+
- Codex hashes the effective timeout, which it limits to 1 to 3 seconds for `SessionEnd`. The generated `SessionEnd` timeout is 3 seconds, the same effective value as the earlier 8, so changing it did not by itself invalidate trust.
|
|
57
|
+
- `--dangerously-bypass-hook-trust` runs enabled hooks without persisted trust for one invocation. Use it only for automation that already vets the hook source.
|
|
58
|
+
|
|
59
|
+
Codex hook trust was checked against Codex CLI 0.167.1; see the [Codex hooks reference](https://developers.openai.com/codex/hooks) for the release behavior.
|
|
60
|
+
|
|
49
61
|
## Request protocol
|
|
50
62
|
|
|
51
63
|
Pass one JSON object on standard input:
|
|
@@ -70,6 +82,35 @@ The session's policy-manager agent returns the following object for an ambiguous
|
|
|
70
82
|
|
|
71
83
|
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
84
|
|
|
85
|
+
## AI classification of ambiguous requests (experiment)
|
|
86
|
+
|
|
87
|
+
Under a `permissive` profile, a person is asked only for what code says must stay with a person. Every other escalation is _ambiguous_: the deterministic engine cannot decide it, so the session's AI decides it instead of the person. Strict mode, and calls made outside the hooks (`policy-manager review`), are unchanged.
|
|
88
|
+
|
|
89
|
+
How a hook call flows (Claude Code, Codex and Copilot `PreToolUse`):
|
|
90
|
+
|
|
91
|
+
1. **First call.** The command is _not run_ and the person is not asked. The hook blocks it with a reason that tells the model to ask the session's policy-manager agent whether the exact command is recoverable and non-sensitive, to record the answer with `policy-manager classify`, and to retry the same command.
|
|
92
|
+
2. **Classified.** `classify` takes `{requestHash, category, confidence, recoverable, rationale}`. The request is approved only when `recoverable` is `true`, `confidence` is at least 0.95, and the category is not `sensitive`, `destructive` or `unknown`. Anything else is a **deny with a reason** the model sees and works around. No person is involved either way. The outcome is remembered for five minutes for that exact request, and a verdict is final in that time: a deny cannot be reclassified into an approve.
|
|
93
|
+
3. **Fallback.** If the classifier is unavailable or its answer is invalid, the retry reaches a person through the normal prompt (under Codex, which cannot ask, it is a deny that tells the model to have the user run the command themselves or change the profile). This happens at most once per request, so there is never a loop and never a lost prompt. After 50 AI approvals in a session, further ambiguous requests go to a person.
|
|
94
|
+
|
|
95
|
+
**What always stays with a person, in code, and is never AI-relaxable** (these are the owner's calls; they list exactly what this experiment does not change):
|
|
96
|
+
|
|
97
|
+
- Credential and secret retrieval, protected paths and configuration such as the policy profile and hook settings (category `sensitive`).
|
|
98
|
+
- Destructive operations: unrecoverable deletion, unmerged-work loss, cloud deletion (category `destructive`).
|
|
99
|
+
- Commands matching the profile's `humanPatterns`.
|
|
100
|
+
- Writes outside a linked feature worktree (main clones and protected branches).
|
|
101
|
+
- Cloud operations outside the read catalog. The profile's `cloudWrites: "allow"` is the way to automate these.
|
|
102
|
+
- Requests the engine cannot trust: incomplete or invalid requests, a different execution directory, unrecognized patches, and environment or loader overrides such as `LD_PRELOAD`.
|
|
103
|
+
|
|
104
|
+
**Known weakness.** The classifier is the working model's own policy-manager agent, and the working model records its answer, so a model that wanted to approve itself could. Confidence is self-reported. This is why the experiment records everything and is reviewed after two days of use rather than trusted.
|
|
105
|
+
|
|
106
|
+
**Recording.** The audit log gets `classification-requested` (with the command, redacted: secret-looking values, URL credentials and long tokens are replaced and the text is capped), `classification` (category, confidence, recoverable, redacted rationale), `decision` (with the stage `requested`, `approved`, `denied` or `fallback`), and `classification-fallback` (with the reason `unavailable`, `invalid-result` or `limit`). Review them across sessions:
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
policy-manager review-classifications [--since 2026-11-12T00:00:00Z] [--json]
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The report shows how many ambiguous requests were approved, denied, fell back to a person (and why), and never resolved; a confidence histogram; every AI-approved command with its outcome; approved commands that then failed; and commands a person later denied. It reads the session logs under the temporary directory, which the operating system clears after a few days, so run it within two days of starting. `replay` prints how many escalations in recorded transcripts would go to the classifier instead of a person.
|
|
113
|
+
|
|
73
114
|
## Policy
|
|
74
115
|
|
|
75
116
|
- Ordinary file reads must resolve inside a Git repository.
|
|
@@ -103,7 +144,17 @@ policy-manager profile install policy.json # writes ~/.config/agent-corpus/pol
|
|
|
103
144
|
|
|
104
145
|
The service reads the profile only from that user directory (`$XDG_CONFIG_HOME` honored). It must be a regular, non-symlink file owned by the user, not group/world writable, and outside every Git checkout, so an agent cannot rewrite its own rules from a worktree. On Windows, POSIX owner and mode bits do not exist, so only the regular-file, non-symlink and outside-Git checks apply and the user-profile ACL is the trust boundary. `cd <literal>` is tracked, and each later command is judged in every directory it could run in. Git long-option abbreviations are treated as the full option. An invalid or untrusted profile logs `profile ... invalid-using-strict` and the session stays strict. Each session records the profile mode and SHA-256 digest in `audit.jsonl`.
|
|
105
146
|
|
|
106
|
-
`permissive` approves compound commands (`;`, `&&`, `||`, `|`, quotes, redirects, `VAR=x` prefixes) when every simple command is acceptable, and approves unknown executables and interpreters with inline code. It still sends these to a human: deletion (`rm`, `find -delete`, `xargs rm`), `sudo`, `git reset --hard`, `git clean`, forced or mirror pushes, discarding checkouts and restores, stash and reflog destruction, `gh` deletions and security endpoints, cloud deletion and credential retrieval, infrastructure destroy, `npm publish`, destructive HTTP verbs, piping into a shell,
|
|
147
|
+
`permissive` approves compound commands (`;`, `&&`, `||`, `|`, quotes, redirects, `VAR=x` prefixes) when every simple command is acceptable, and approves unknown executables and interpreters with inline code. It still sends these to a human: deletion (`rm`, `find -delete`, `xargs rm`), `sudo`, `git reset --hard`, `git clean`, forced or mirror pushes, discarding checkouts and restores, stash and reflog destruction, `gh` deletions and security endpoints, cloud deletion and credential retrieval, infrastructure destroy, `npm publish`, destructive HTTP verbs, piping into a shell, ssh and database clients, builtins that run a string later (`eval`, `source`, `trap`, `alias`), printing the environment, writes outside linked feature worktrees and `scratchRoots`, and protected or credential paths. `humanPatterns` adds organization-specific expressions.
|
|
148
|
+
|
|
149
|
+
#### Shell syntax in permissive mode
|
|
150
|
+
|
|
151
|
+
Every command that could run is judged, not only the first. Understood: `;`, newlines, `&&`, `||`, `|`, `&`, comments, quoting and escapes, line continuation, redirections (including `&>`, `|&`, here-strings and quoted-delimiter heredocs), `( ... )`, `{ ...; }`, `for`, `while`, `until`, `if`, `case`, `$(...)`, backticks and `<(...)`.
|
|
152
|
+
|
|
153
|
+
- **Variables.** `NAME=value`, `export NAME=value` and `for NAME in a b c` give a variable a known value; the command is then judged with the value substituted, in every directory and for every value it could take. A variable assigned in only some branches, in a loop, or from a command, glob or `read` has an unknown value, as does any environment variable the script did not assign. An unknown value is accepted only as an argument to `echo`, `printf` with string conversions, `test`/`[` without numeric tests, `true`, `false`, `basename` and `dirname`, and as the value of a commit or PR message option (`git commit -m "$(...)"`, `gh pr create --body "$(...)"`). It is never a program, option, path, `cd` target or redirection target. Environment variables other than a short list (`PWD`, `USER`, `TMPDIR`, ...) need a human, because they can hold credentials.
|
|
154
|
+
- **Command substitution** and process substitution run first: the inner command is judged with the same rules.
|
|
155
|
+
- **Heredocs.** A quoted delimiter (`<<'EOF'`) is literal text. An unquoted delimiter is accepted only when the body has no `$`, backtick or backslash. A shell fed by a heredoc (`bash <<'EOF'`) has its body judged as a script. An interpreter fed by a heredoc or `-c` is treated like inline code: the code is scanned for file deletion, process creation, string evaluation and protected paths, and anything flagged goes to a human; code piped in from elsewhere always does.
|
|
156
|
+
- **Compound commands.** Branches are judged on copies of the state and merged; a loop's assigned variables are unknown inside it and afterwards, and a `cd` inside a loop or pipeline needs a human.
|
|
157
|
+
- **Still sent to a human:** brace expansion, arithmetic (`$((`, `$[`, `(( ))`), `${X:-y}` and other parameter forms, `$'...'`, function definitions, unquoted heredocs whose body expands, and scripts that expand to more than a few hundred commands. `cloudWrites: "allow"` also approves non-destructive cloud changes.
|
|
107
158
|
|
|
108
159
|
Measure a profile against real usage with `policy-manager replay ~/.claude/projects --profile policy.json`: it replays the Bash commands recorded in Claude Code transcripts through the evaluator (nothing is executed) and prints the approval rate with and without the profile, plus the most common reasons that still need a human. Reports include short command excerpts, so keep them local.
|
|
109
160
|
|
|
@@ -119,7 +170,7 @@ The cache belongs to the service process and is scoped to harness plus session I
|
|
|
119
170
|
|
|
120
171
|
`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.
|
|
121
172
|
|
|
122
|
-
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
|
|
173
|
+
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`: it parses the value, marks the hook failed and runs the tool anyway. A decision that needs a human is therefore returned to Codex as a `deny` whose reason says the command was not run and that approving it in chat does not unblock it (the decision is deterministic, so a retry is denied again); there is no in-Codex button to approve it. The user runs the command themselves or changes the policy profile. An ambiguous cloud request is the one exception: its reason points to the session policy-manager agent, and a classification of approved is accepted for the session, so a retry passes. Codex's own approval prompt (`PermissionRequest`) is left to Codex for the requests it would ask about, and an approval is returned as `allow`.
|
|
123
174
|
|
|
124
175
|
## Audit API and reported outcomes
|
|
125
176
|
|
|
@@ -149,9 +200,9 @@ Or an execution report:
|
|
|
149
200
|
}
|
|
150
201
|
```
|
|
151
202
|
|
|
152
|
-
Human responses are `approved` or `denied`. Execution statuses are `completed`, `succeeded`, `failed`, or `
|
|
203
|
+
Human responses are `approved` or `denied`. Execution statuses are `completed`, `succeeded`, `failed`, `cancelled`, or `unknown`. `unknown` is recorded for Codex when the hook payload exposes no exit status, which is the usual case for a Bash result. 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.
|
|
153
204
|
|
|
154
|
-
Generated post-tool hooks record execution reports for the supported tool matcher. Claude and Copilot also get failure hooks. Codex uses `PostToolUse`, which
|
|
205
|
+
Generated post-tool hooks record execution reports for the supported tool matcher. Claude and Copilot also get failure hooks. Codex uses `PostToolUse`, which also runs after commands that exit non-zero. Codex sends a Bash result as the command's output text only, with no exit code and no duration, so the adapter records `unknown` for Codex rather than `completed` or `succeeded`; a structured `exit_code` is used when one is present. Claude and Copilot record `completed` when an exit code is absent. 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.
|
|
155
206
|
|
|
156
207
|
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.
|
|
157
208
|
|
|
@@ -162,7 +213,7 @@ Tests exercise real service processes and native-shaped hook payloads for all th
|
|
|
162
213
|
Verified documentation, November 5, 2026:
|
|
163
214
|
|
|
164
215
|
- [Claude Code hooks](https://code.claude.com/docs/en/hooks)
|
|
165
|
-
- [Codex hooks](https://
|
|
216
|
+
- [Codex hooks](https://developers.openai.com/codex/hooks)
|
|
166
217
|
- [Copilot hooks](https://docs.github.com/en/copilot/reference/hooks-reference)
|
|
167
218
|
|
|
168
219
|
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.
|
package/dist/adapters.d.ts
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import type { Decision, OutcomeReport, Request } from "./types.js";
|
|
2
2
|
export declare function normalize(harness: Request["harness"], payload: Record<string, unknown>): Request;
|
|
3
|
-
export
|
|
3
|
+
export interface HookContext {
|
|
4
|
+
cliPath: string;
|
|
5
|
+
sessionId: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The exact command the model is told to run to record a classification. A here-string, not a
|
|
9
|
+
* pipe: `printf ... | node ...` is "piping into an interpreter" and is itself escalated, so the
|
|
10
|
+
* round trip could never finish. A test evaluates this exact string and requires `approve`.
|
|
11
|
+
*/
|
|
12
|
+
export declare function classifyCommand(harness: Request["harness"], context?: HookContext, json?: string): string;
|
|
13
|
+
export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
|
|
4
14
|
export declare function executionReport(request: Request, phase: string, payload: Record<string, unknown>): OutcomeReport;
|
|
5
15
|
//# sourceMappingURL=adapters.d.ts.map
|
package/dist/adapters.js
CHANGED
|
@@ -15,7 +15,55 @@ export function normalize(harness, payload) {
|
|
|
15
15
|
input: args,
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
|
-
|
|
18
|
+
/**
|
|
19
|
+
* The exact command the model is told to run to record a classification. A here-string, not a
|
|
20
|
+
* pipe: `printf ... | node ...` is "piping into an interpreter" and is itself escalated, so the
|
|
21
|
+
* round trip could never finish. A test evaluates this exact string and requires `approve`.
|
|
22
|
+
*/
|
|
23
|
+
export function classifyCommand(harness, context, json = "<json>") {
|
|
24
|
+
// A Windows path (`D:\\a\\cli.js`) is written with forward slashes: Node accepts them, and a
|
|
25
|
+
// backslash inside double quotes is a shell escape the policy cannot judge, which would
|
|
26
|
+
// escalate the command that finishes the round trip.
|
|
27
|
+
const cliPath = context && /^[A-Za-z]:\\/.test(context.cliPath)
|
|
28
|
+
? context.cliPath.replace(/\\/g, "/")
|
|
29
|
+
: context?.cliPath;
|
|
30
|
+
const safe = context &&
|
|
31
|
+
cliPath &&
|
|
32
|
+
/^[^"$`\\\n']+$/.test(cliPath) &&
|
|
33
|
+
/^[A-Za-z0-9_.-]+$/.test(context.sessionId);
|
|
34
|
+
return safe
|
|
35
|
+
? `node "${cliPath}" classify ${harness} ${context.sessionId} <<< '${json}'`
|
|
36
|
+
: `policy-manager classify ${harness} <session-id> <<< '${json}'`;
|
|
37
|
+
}
|
|
38
|
+
/** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
|
|
39
|
+
function classifyInstruction(harness, decision, context) {
|
|
40
|
+
const command = classifyCommand(harness, context);
|
|
41
|
+
return `Not run yet: this request needs classification before it can run (request ${decision.requestHash}; ${decision.reason}). Ask the session's policy-manager agent whether the exact command is recoverable and non-sensitive. It answers with {"requestHash":"${decision.requestHash}","category":"code-read|worktree-write|cloud-read|git-read|impactful-write|destructive|sensitive|unknown","confidence":0.0-1.0,"recoverable":true|false,"rationale":"one short sentence without quotes"}. Record that answer with this command, replacing <json> with the answer and using no single quotes in it: ${command} Then retry the same command unchanged. If you cannot get a classification, retry once and the user will be asked.`;
|
|
42
|
+
}
|
|
43
|
+
export function hookResponse(harness, phase, decision, context) {
|
|
44
|
+
if (decision.decision === "deny") {
|
|
45
|
+
const reason = decision.classification === "requested"
|
|
46
|
+
? classifyInstruction(harness, decision, context)
|
|
47
|
+
: decision.reason;
|
|
48
|
+
if (phase === "PermissionRequest")
|
|
49
|
+
return harness === "copilot"
|
|
50
|
+
? {}
|
|
51
|
+
: {
|
|
52
|
+
hookSpecificOutput: {
|
|
53
|
+
hookEventName: phase,
|
|
54
|
+
decision: { behavior: "deny", message: reason },
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
return harness === "copilot"
|
|
58
|
+
? { permissionDecision: "deny", permissionDecisionReason: reason }
|
|
59
|
+
: {
|
|
60
|
+
hookSpecificOutput: {
|
|
61
|
+
hookEventName: phase,
|
|
62
|
+
permissionDecision: "deny",
|
|
63
|
+
permissionDecisionReason: reason,
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
19
67
|
if (harness === "copilot") {
|
|
20
68
|
if (phase === "PermissionRequest")
|
|
21
69
|
return decision.decision === "approve" ? { behavior: "allow" } : {};
|
|
@@ -29,13 +77,24 @@ export function hookResponse(harness, phase, decision) {
|
|
|
29
77
|
: {};
|
|
30
78
|
if (decision.decision === "approve")
|
|
31
79
|
return { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
|
|
32
|
-
|
|
80
|
+
// Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
|
|
81
|
+
// runs the tool anyway (https://developers.openai.com/codex/hooks). Only "deny" stops a command,
|
|
82
|
+
// so a decision that needs a human is a deny. Approving it in chat does not change the decision,
|
|
83
|
+
// so the reason says so; the one in-session way through is classifying an ambiguous cloud
|
|
84
|
+
// request (needsClassification), which a retry then sees as approved. Codex's own approval prompt
|
|
85
|
+
// (PermissionRequest, above) still handles the requests it would ask about.
|
|
86
|
+
if (harness === "codex") {
|
|
87
|
+
const next = decision.needsClassification === true && decision.classification !== "fallback"
|
|
88
|
+
? "Classify it with the session policy-manager agent and retry. If it is not classified as approved, ask the user to run it themselves or to change the policy profile."
|
|
89
|
+
: "Approving it in this session does not unblock it: ask the user to run it themselves or to change the policy profile.";
|
|
33
90
|
return {
|
|
34
91
|
hookSpecificOutput: {
|
|
35
92
|
hookEventName: phase,
|
|
36
|
-
|
|
93
|
+
permissionDecision: "deny",
|
|
94
|
+
permissionDecisionReason: `Policy manager: ${decision.reason}. This needs a human decision and was not run. ${next} Request ${decision.requestHash}.`,
|
|
37
95
|
},
|
|
38
96
|
};
|
|
97
|
+
}
|
|
39
98
|
return {
|
|
40
99
|
hookSpecificOutput: {
|
|
41
100
|
hookEventName: phase,
|
|
@@ -51,6 +110,10 @@ export function executionReport(request, phase, payload) {
|
|
|
51
110
|
const exitCode = typeof code === "number" && Number.isSafeInteger(code) && Math.abs(code) <= 2147483647
|
|
52
111
|
? code
|
|
53
112
|
: undefined;
|
|
113
|
+
// Codex sends a Bash result as the output text alone: no exit code and no duration, even for a
|
|
114
|
+
// command that exited non-zero. That is not "completed"; the outcome is unknown. Claude and
|
|
115
|
+
// Copilot keep their existing behaviour.
|
|
116
|
+
const unknown = exitCode === undefined && request.harness === "codex";
|
|
54
117
|
const duration = payload.duration_ms ?? payload.durationMs;
|
|
55
118
|
return {
|
|
56
119
|
requestHash: hash(request),
|
|
@@ -60,7 +123,9 @@ export function executionReport(request, phase, payload) {
|
|
|
60
123
|
? "cancelled"
|
|
61
124
|
: "failed"
|
|
62
125
|
: exitCode === undefined
|
|
63
|
-
?
|
|
126
|
+
? unknown
|
|
127
|
+
? "unknown"
|
|
128
|
+
: "completed"
|
|
64
129
|
: exitCode === 0
|
|
65
130
|
? "succeeded"
|
|
66
131
|
: "failed",
|
package/dist/cli.js
CHANGED
|
@@ -7,6 +7,7 @@ import { executionReport, hookResponse, normalize } from "./adapters.js";
|
|
|
7
7
|
import { hookConfig } from "./config.js";
|
|
8
8
|
import { defaultProfilePath, loadProfile, parseProfile } from "./profile.js";
|
|
9
9
|
import { replayTranscripts } from "./replay.js";
|
|
10
|
+
import { formatReview, reviewClassifications, sessionDirectories } from "./review.js";
|
|
10
11
|
import { send, serve, start, stop } from "./service.js";
|
|
11
12
|
import { SetupError, setupHook } from "./setup.js";
|
|
12
13
|
const usage = `policy-manager usage [--json]
|
|
@@ -20,6 +21,7 @@ policy-manager config <claude|codex|copilot> <absolute-installed-cli-path>
|
|
|
20
21
|
policy-manager profile validate <file> # check a policy profile without installing it
|
|
21
22
|
policy-manager profile install <file> # install it to the user config directory outside Git
|
|
22
23
|
policy-manager replay <transcript-dir-or-file...> [--profile <file>] [--files <n>] # approval rate over recorded Bash commands; nothing is executed
|
|
24
|
+
policy-manager review-classifications [--since <iso-time>] [--dir <session-dir>...] [--json] # risk review of AI-classified ambiguous requests
|
|
23
25
|
policy-manager stop <claude|codex|copilot> <session-id>
|
|
24
26
|
A per-session background service checks policy and writes private temporary audit.jsonl logs.
|
|
25
27
|
AI classification comes from the session's policy-manager agent, never an external API.
|
|
@@ -90,12 +92,26 @@ try {
|
|
|
90
92
|
const report = replayTranscripts(positionals, profile, Number(values.files ?? 50));
|
|
91
93
|
const pct = (n) => `${((100 * n) / Math.max(report.commands, 1)).toFixed(1)}%`;
|
|
92
94
|
console.log(`${report.commands} unique commands; approved ${pct(report.approved)} (strict ${pct(report.strictApproved)})`);
|
|
95
|
+
const humans = report.commands - report.approved;
|
|
96
|
+
console.log(`${report.classified} of ${humans} escalations go to AI classification instead of a person; ${humans - report.classified} stay with a human by rule`);
|
|
93
97
|
for (const row of report.reasons.slice(0, 15)) {
|
|
94
98
|
console.log(`${row.count}\t${row.reason}`);
|
|
95
99
|
for (const example of row.examples)
|
|
96
100
|
console.log(`\t ${example}`);
|
|
97
101
|
}
|
|
98
102
|
}
|
|
103
|
+
else if (action === "review-classifications") {
|
|
104
|
+
const { values } = parseArgs({
|
|
105
|
+
args: args.slice(1),
|
|
106
|
+
options: {
|
|
107
|
+
since: { type: "string" },
|
|
108
|
+
dir: { type: "string", multiple: true },
|
|
109
|
+
json: { type: "boolean" },
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
const review = await reviewClassifications(sessionDirectories(values.dir ?? []), values.since);
|
|
113
|
+
console.log(values.json ? JSON.stringify(review, null, 2) : formatReview(review));
|
|
114
|
+
}
|
|
99
115
|
else if (action === "serve")
|
|
100
116
|
await serve(harness, phase ?? "");
|
|
101
117
|
else if (action === "stop")
|
|
@@ -120,7 +136,7 @@ try {
|
|
|
120
136
|
else {
|
|
121
137
|
const directory = await start(harness, request.sessionId, cliPath);
|
|
122
138
|
if (phase === "SessionStart") {
|
|
123
|
-
const context = `Policy service started. Audit log: ${join(directory, "audit.jsonl")}. Native hooks route tool and permission requests directly to the deterministic service.
|
|
139
|
+
const context = `Policy service started. Audit log: ${join(directory, "audit.jsonl")}. Native hooks route tool and permission requests directly to the deterministic service. An ambiguous request is blocked once with instructions to have the policy-manager agent classify it and then retry; the person is asked only if classification fails. 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.`;
|
|
124
140
|
console.log(JSON.stringify(harness === "copilot"
|
|
125
141
|
? { additionalContext: context }
|
|
126
142
|
: { hookSpecificOutput: { hookEventName: phase, additionalContext: context } }));
|
|
@@ -136,8 +152,9 @@ try {
|
|
|
136
152
|
const decision = (await send(harness, request.sessionId, {
|
|
137
153
|
action: "review",
|
|
138
154
|
request,
|
|
155
|
+
phase,
|
|
139
156
|
}));
|
|
140
|
-
console.log(JSON.stringify(hookResponse(harness, phase, decision)));
|
|
157
|
+
console.log(JSON.stringify(hookResponse(harness, phase, decision, { cliPath, sessionId: request.sessionId })));
|
|
141
158
|
}
|
|
142
159
|
else
|
|
143
160
|
throw new Error("Unsupported hook event");
|
package/dist/config.js
CHANGED
|
@@ -16,6 +16,8 @@ export function hookConfig(harness, cliPath) {
|
|
|
16
16
|
"SessionEnd",
|
|
17
17
|
];
|
|
18
18
|
for (const phase of phases) {
|
|
19
|
+
// Codex limits SessionEnd to 1 to 3 seconds and warns about anything longer.
|
|
20
|
+
const timeout = harness === "codex" && phase === "SessionEnd" ? 3 : 8;
|
|
19
21
|
if (harness === "copilot") {
|
|
20
22
|
const event = phase[0]?.toLowerCase() + phase.slice(1);
|
|
21
23
|
hooks[event] = [
|
|
@@ -24,7 +26,7 @@ export function hookConfig(harness, cliPath) {
|
|
|
24
26
|
...(phase === "PreToolUse" || phase.startsWith("PostToolUse") ? { matcher } : {}),
|
|
25
27
|
exec: process.execPath,
|
|
26
28
|
args: [cliPath, "hook", harness, phase, managedHookFlag],
|
|
27
|
-
timeoutSec:
|
|
29
|
+
timeoutSec: timeout,
|
|
28
30
|
},
|
|
29
31
|
];
|
|
30
32
|
}
|
|
@@ -36,7 +38,7 @@ export function hookConfig(harness, cliPath) {
|
|
|
36
38
|
{
|
|
37
39
|
type: "command",
|
|
38
40
|
command: `"${process.execPath}" "${cliPath}" hook ${harness} ${phase} ${managedHookFlag}`,
|
|
39
|
-
timeout
|
|
41
|
+
timeout,
|
|
40
42
|
},
|
|
41
43
|
],
|
|
42
44
|
},
|
package/dist/flow.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Profile } from "./profile.js";
|
|
2
|
+
import type { Decision, Request } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Evaluates a compound command. `cd <literal>` is tracked: every later command is judged in each
|
|
5
|
+
* directory it could run in (before and after the `cd`, since `cd x || ...` may fail), so a command
|
|
6
|
+
* that only looks safe relative to the starting directory cannot hide behind a `cd`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function commandDecision(request: Request, command: string, profile: Profile, depth?: number, start?: string[]): Decision;
|
|
9
|
+
//# sourceMappingURL=flow.d.ts.map
|