@agent-corpus/policy-manager 0.5.0 → 0.7.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/dist/script.js CHANGED
@@ -163,6 +163,134 @@ function closingParen(command, start) {
163
163
  }
164
164
  return undefined;
165
165
  }
166
+ /** No leading `=`: zsh's EQUALS option expands `=cmd` to a command path. */
167
+ const PARAM_WORD = /^(?:[A-Za-z0-9_@%+:,./-][A-Za-z0-9_@%+=:,./-]*)?$/;
168
+ const PARAM_PATTERN = /^[A-Za-z0-9_@%+=:,./*?-]+$/;
169
+ /** The name and operation inside `${...}`, or undefined for a form that is not modelled. */
170
+ function parameter(body) {
171
+ const NAME_OR_POSITION = "([A-Za-z_][A-Za-z0-9_]*|[1-9][0-9]*)";
172
+ let m = new RegExp(`^${NAME_OR_POSITION}$`).exec(body);
173
+ if (m)
174
+ return { name: m[1] };
175
+ m = new RegExp(`^#${NAME_OR_POSITION}$`).exec(body);
176
+ if (m)
177
+ return { name: m[1], op: { kind: "length" } };
178
+ m = new RegExp(`^${NAME_OR_POSITION}(:?)([-+])(.*)$`).exec(body);
179
+ if (m && PARAM_WORD.test(m[4]))
180
+ return {
181
+ name: m[1],
182
+ op: { kind: m[3] === "-" ? "default" : "alternate", word: m[4] },
183
+ };
184
+ m = new RegExp(`^${NAME_OR_POSITION}(##?|%%?)(.*)$`).exec(body);
185
+ if (m && PARAM_PATTERN.test(m[3])) {
186
+ const op = m[2];
187
+ return {
188
+ name: m[1],
189
+ op: {
190
+ kind: "strip",
191
+ suffix: op.startsWith("%"),
192
+ longest: op.length === 2,
193
+ pattern: m[3],
194
+ },
195
+ };
196
+ }
197
+ m = new RegExp(`^${NAME_OR_POSITION}:([0-9]+)(?::([0-9]+))?$`).exec(body);
198
+ if (m)
199
+ return {
200
+ name: m[1],
201
+ op: {
202
+ kind: "slice",
203
+ offset: Number(m[2]),
204
+ ...(m[3] === undefined ? {} : { length: Number(m[3]) }),
205
+ },
206
+ };
207
+ return undefined;
208
+ }
209
+ function globRegex(pattern) {
210
+ const source = [...pattern]
211
+ .map((c) => (c === "*" ? ".*" : c === "?" ? "." : c.replace(/[.+^${}()|[\]\\/-]/g, "\\$&")))
212
+ .join("");
213
+ return new RegExp(`^${source}$`, "s");
214
+ }
215
+ /**
216
+ * Applies a parameter operation to a value that is set and not empty, which is the only kind of
217
+ * value the evaluator knows.
218
+ */
219
+ export function applyParamOp(value, op) {
220
+ if (!op || op.kind === "default")
221
+ return value;
222
+ if (op.kind === "alternate")
223
+ return op.word;
224
+ if (op.kind === "length")
225
+ return String([...value].length);
226
+ if (op.kind === "slice")
227
+ return value.slice(op.offset, op.length === undefined ? undefined : op.offset + op.length);
228
+ const regex = globRegex(op.pattern);
229
+ const lengths = [...Array(value.length + 1).keys()];
230
+ if (op.longest)
231
+ lengths.reverse();
232
+ for (const n of lengths) {
233
+ const piece = op.suffix ? value.slice(value.length - n) : value.slice(0, n);
234
+ if (regex.test(piece))
235
+ return op.suffix ? value.slice(0, value.length - n) : value.slice(n);
236
+ }
237
+ return value;
238
+ }
239
+ const ANSI_ESCAPES = {
240
+ a: "\x07",
241
+ b: "\b",
242
+ e: "\x1b",
243
+ E: "\x1b",
244
+ f: "\f",
245
+ n: "\n",
246
+ r: "\r",
247
+ t: "\t",
248
+ v: "\v",
249
+ "\\": "\\",
250
+ '"': '"',
251
+ "?": "?",
252
+ };
253
+ /**
254
+ * `$'...'` starting at `command[at] === "$"`. `\'` is refused so that the plain single-quote scan
255
+ * used to find the end of a substitution agrees with the shell; so are NUL, `\c`, `\u` and `\U`.
256
+ */
257
+ function ansiString(command, at) {
258
+ let text = "";
259
+ for (let i = at + 2; i < command.length; i++) {
260
+ const c = command[i];
261
+ if (c === "'") {
262
+ if (text.includes(SUBSTITUTION) || text.includes("\0"))
263
+ return undefined;
264
+ return { kind: "text", text, next: i + 1, quoted: true };
265
+ }
266
+ if (c !== "\\") {
267
+ text += c;
268
+ continue;
269
+ }
270
+ const e = command[i + 1];
271
+ if (e === undefined || e === "'" || e === "c" || e === "u" || e === "U")
272
+ return undefined;
273
+ const known = ANSI_ESCAPES[e];
274
+ if (known !== undefined) {
275
+ text += known;
276
+ i++;
277
+ continue;
278
+ }
279
+ const hex = e === "x" ? /^[0-9A-Fa-f]{1,2}/.exec(command.slice(i + 2)) : null;
280
+ const octal = /^[0-7]{1,3}/.exec(command.slice(i + 1));
281
+ if (hex) {
282
+ text += String.fromCharCode(Number.parseInt(hex[0], 16));
283
+ i += 1 + hex[0].length;
284
+ }
285
+ else if (octal) {
286
+ text += String.fromCharCode(Number.parseInt(octal[0], 8) & 0xff);
287
+ i += octal[0].length;
288
+ }
289
+ else
290
+ text += c; // an unknown escape keeps its backslash; the next character follows
291
+ }
292
+ return undefined;
293
+ }
166
294
  /**
167
295
  * Reads the expansion that starts at `command[at] === "$"`, or undefined for one that is not
168
296
  * understood. Only HOME has a value known before anything runs; `$?`, `$#`, `$$` and PIPESTATUS
@@ -191,18 +319,34 @@ function expansion(command, at, quoted = false) {
191
319
  return undefined;
192
320
  return { kind: "unknown", next: end + 1, inner: command.slice(at + 2, end) };
193
321
  }
322
+ if (rest[0] === "'" && !quoted)
323
+ return ansiString(command, at);
194
324
  let name;
325
+ let op;
195
326
  let next;
196
327
  if (rest[0] === "{") {
197
328
  const close = rest.indexOf("}");
198
- name = close > 0 ? rest.slice(1, close) : undefined;
329
+ if (close <= 0)
330
+ return undefined;
331
+ const body = rest.slice(1, close);
199
332
  next = at + close + 2;
200
- if (name === undefined || (!NAME.test(name) && !UNKNOWN_PARAMETER.test(name)))
333
+ if (UNKNOWN_PARAMETER.test(body))
334
+ return { kind: "unknown", next };
335
+ const parsed = parameter(body);
336
+ if (!parsed)
201
337
  return undefined;
338
+ ({ name, op } = parsed);
339
+ }
340
+ else if (rest[0] && /[0-9]/.test(rest[0]) && /[0-9]/.test(rest[1] ?? "")) {
341
+ return undefined; // `$10` is `$1` then `0` in bash and sh, the tenth parameter in zsh
202
342
  }
203
- else if (rest[0] && "?#$".includes(rest[0])) {
343
+ else if (rest[0] && "?#$0".includes(rest[0])) {
204
344
  return { kind: "unknown", next: at + 2 };
205
345
  }
346
+ else if (rest[0] && /[1-9@*]/.test(rest[0])) {
347
+ name = rest[0];
348
+ next = at + 2;
349
+ }
206
350
  else {
207
351
  name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest)?.[0];
208
352
  if (!name)
@@ -213,9 +357,9 @@ function expansion(command, at, quoted = false) {
213
357
  return { kind: "unknown", next };
214
358
  if (name === "HOME") {
215
359
  const text = home();
216
- return text === undefined ? undefined : { kind: "text", text, next };
360
+ return text === undefined ? undefined : { kind: "text", text: applyParamOp(text, op), next };
217
361
  }
218
- return { kind: "var", name, next };
362
+ return op ? { kind: "var", name, next, op } : { kind: "var", name, next };
219
363
  }
220
364
  function tokenize(src) {
221
365
  const tokens = [];
@@ -227,7 +371,8 @@ function tokenize(src) {
227
371
  let quotedAny = false;
228
372
  let headPlain = true;
229
373
  let assignName;
230
- let braceChar = false;
374
+ let braceOpen = false;
375
+ let braceExpansion = false;
231
376
  let globChar = false;
232
377
  let quote = "";
233
378
  let pendingRedirect;
@@ -245,8 +390,8 @@ function tokenize(src) {
245
390
  if (!active)
246
391
  return;
247
392
  flush();
248
- const bare = parts.length === 1 && (parts[0] === "{" || parts[0] === "}");
249
- if (braceChar && !(bare && !quotedAny && assignName === undefined))
393
+ // `{a,b}` and `{1..3}` expand to several words; `{}`, `@{u}` and a lone `{` are literal.
394
+ if (braceExpansion)
250
395
  reject();
251
396
  const word = { parts, subs, quoted: quotedAny, assign: assignName, glob: globChar };
252
397
  parts = [];
@@ -255,7 +400,8 @@ function tokenize(src) {
255
400
  quotedAny = false;
256
401
  headPlain = true;
257
402
  assignName = undefined;
258
- braceChar = false;
403
+ braceOpen = false;
404
+ braceExpansion = false;
259
405
  globChar = false;
260
406
  if (pendingRedirect) {
261
407
  tokens.push({ t: "redir", redir: { ...pendingRedirect, target: word } });
@@ -277,11 +423,14 @@ function tokenize(src) {
277
423
  subs.push(inner);
278
424
  };
279
425
  const appendExpansion = (e, quoted) => {
280
- if (e.kind === "text")
426
+ if (e.kind === "text") {
281
427
  lit += e.text;
428
+ if (e.quoted)
429
+ quotedAny = true;
430
+ }
282
431
  else if (e.kind === "var") {
283
432
  flush();
284
- parts.push({ name: e.name, quoted });
433
+ parts.push(e.op ? { name: e.name, quoted, op: e.op } : { name: e.name, quoted });
285
434
  }
286
435
  else
287
436
  appendUnknown(quoted, e.inner);
@@ -382,9 +531,12 @@ function tokenize(src) {
382
531
  i++;
383
532
  continue;
384
533
  }
534
+ // History expansion is off in the non-interactive shells that run these commands, but `!(`
535
+ // is an extended glob and `!!`/`!$` are worth no risk; `!=` is a comparison operator.
385
536
  if (char === "!" &&
386
- !(active === false && (src[i + 1] === undefined || /\s/.test(src[i + 1])))) {
387
- reject(); // history expansion and `!` inside words
537
+ !(active === false && (src[i + 1] === undefined || /\s/.test(src[i + 1]))) &&
538
+ src[i + 1] !== "=") {
539
+ reject();
388
540
  }
389
541
  if (char === " " || char === "\t") {
390
542
  endWord();
@@ -453,7 +605,14 @@ function tokenize(src) {
453
605
  continue;
454
606
  }
455
607
  if (char === "(") {
456
- if (active || src[i + 1] === "(")
608
+ // `name()` starts a function definition; the parser checks the rest.
609
+ const definition = active &&
610
+ src[i + 1] === ")" &&
611
+ parts.length === 0 &&
612
+ !quotedAny &&
613
+ assignName === undefined &&
614
+ NAME.test(lit);
615
+ if ((active && !definition) || src[i + 1] === "(")
457
616
  reject();
458
617
  operator("(");
459
618
  continue;
@@ -468,8 +627,10 @@ function tokenize(src) {
468
627
  if (parts.length === 0 && /^[0-9]{2,}$/.test(lit))
469
628
  reject();
470
629
  }
471
- if (char === "{" || char === "}")
472
- braceChar = true;
630
+ if (char === "{")
631
+ braceOpen = true;
632
+ else if (braceOpen && (char === "," || (char === "." && src[i + 1] === ".")))
633
+ braceExpansion = true;
473
634
  if (char === "*" || char === "?" || char === "[")
474
635
  globChar = true;
475
636
  if (char === ">" || char === "<") {
@@ -561,6 +722,19 @@ function tokenize(src) {
561
722
  }
562
723
  if (assignName === undefined && !/[A-Za-z0-9_]/.test(char))
563
724
  headPlain = false;
725
+ // An assignment value starting with `~` or `~/` is the home directory.
726
+ if (char === "~" &&
727
+ assignName !== undefined &&
728
+ parts.length === 0 &&
729
+ lit === "" &&
730
+ !quotedAny &&
731
+ (src[i + 1] === undefined || /[/\s;&|)]/.test(src[i + 1]))) {
732
+ const path = homedir();
733
+ if (/[\s*?[\]'"$`~]/.test(path))
734
+ reject();
735
+ lit += path;
736
+ continue;
737
+ }
564
738
  lit += char;
565
739
  active = true;
566
740
  }
@@ -733,6 +907,24 @@ class Parser {
733
907
  return { kind: "subshell", body, redirects: this.redirects() };
734
908
  }
735
909
  const word = this.keyword(tok);
910
+ const open = this.tokens[this.pos + 1];
911
+ const close = this.tokens[this.pos + 2];
912
+ if (word === undefined &&
913
+ tok?.t === "word" &&
914
+ open?.t === "op" &&
915
+ open.op === "(" &&
916
+ close?.t === "op" &&
917
+ close.op === ")") {
918
+ const name = plainWord(tok.w);
919
+ if (name === undefined || !NAME.test(name) || depth >= MAX_DEPTH)
920
+ reject();
921
+ this.pos += 3;
922
+ this.skipNewlines();
923
+ const body = this.command(depth + 1);
924
+ if ((body.kind !== "group" && body.kind !== "subshell") || body.redirects.length)
925
+ reject();
926
+ return { kind: "function", name: name, body: body };
927
+ }
736
928
  if (word === undefined)
737
929
  return this.simple();
738
930
  if (depth >= MAX_DEPTH)
@@ -774,7 +966,13 @@ class Parser {
774
966
  this.expectKeyword("do");
775
967
  const body = this.list(new Set(["done"]), depth + 1);
776
968
  this.expectKeyword("done");
777
- return { kind: "while", cond, body, redirects: this.redirects() };
969
+ return {
970
+ kind: "while",
971
+ cond,
972
+ body,
973
+ redirects: this.redirects(),
974
+ ...(word === "until" ? { until: true } : {}),
975
+ };
778
976
  }
779
977
  case "if": {
780
978
  const clauses = [];
package/dist/service.d.ts CHANGED
@@ -7,7 +7,7 @@ interface Message {
7
7
  report?: OutcomeReport;
8
8
  phase?: string;
9
9
  }
10
- export declare function serve(harness: string, sessionId: string): Promise<void>;
10
+ export declare function serve(harness: string, sessionId: string, cliPath?: string): Promise<void>;
11
11
  export declare function send(harness: string, sessionId: string, message: Omit<Message, "token">): Promise<unknown>;
12
12
  /**
13
13
  * Stops a session's service. A session with no service (it never started, already ended, or the
package/dist/service.js CHANGED
@@ -3,7 +3,7 @@ import { chmodSync, existsSync } from "node:fs";
3
3
  import { createConnection, createServer } from "node:net";
4
4
  import { join } from "node:path";
5
5
  import { audit, sessionDirectory, sessionDirectoryPath, sessionToken } from "./audit.js";
6
- import { hash } from "./policy.js";
6
+ import { hash, requestHash } from "./policy.js";
7
7
  import { loadProfile, strictProfile } from "./profile.js";
8
8
  import { PolicySession } from "./session.js";
9
9
  function endpoint(directory) {
@@ -11,7 +11,7 @@ function endpoint(directory) {
11
11
  ? `\\\\.\\pipe\\acp-${hash(directory).slice(0, 32)}`
12
12
  : join(directory, "service.sock");
13
13
  }
14
- export async function serve(harness, sessionId) {
14
+ export async function serve(harness, sessionId, cliPath) {
15
15
  const directory = sessionDirectory(harness, sessionId), token = sessionToken(directory);
16
16
  let profile = strictProfile;
17
17
  let profileFailure = false;
@@ -21,7 +21,7 @@ export async function serve(harness, sessionId) {
21
21
  catch {
22
22
  profileFailure = true; // an unreadable or untrusted profile must never loosen policy
23
23
  }
24
- const session = new PolicySession(directory, harness, sessionId, profile);
24
+ const session = new PolicySession(directory, harness, sessionId, profile, cliPath);
25
25
  const server = createServer((socket) => {
26
26
  socket.setTimeout(3000, () => socket.destroy());
27
27
  let data = "";
@@ -44,7 +44,7 @@ export async function serve(harness, sessionId) {
44
44
  event: "request-envelope",
45
45
  payloadHash: hash(data.slice(0, end)),
46
46
  ...(message.request
47
- ? { requestHash: hash(message.request) }
47
+ ? { requestHash: requestHash(message.request) }
48
48
  : message.classification
49
49
  ? { requestHash: message.classification.requestHash }
50
50
  : message.report
package/dist/session.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Profile } from "./profile.js";
2
- import type { Classification, Decision, OutcomeReport, Request } from "./types.js";
2
+ import { type Classification, type Decision, type OutcomeReport, type Request } from "./types.js";
3
3
  /** AI approvals per session; beyond this, ambiguous requests go to a human. */
4
4
  export declare const MAX_AI_APPROVALS = 50;
5
5
  export declare class PolicySession {
@@ -7,12 +7,26 @@ export declare class PolicySession {
7
7
  readonly harness: string;
8
8
  readonly sessionId: string;
9
9
  readonly profile: Profile;
10
+ /** This package's `cli.js`: the path in the record command the hook gives the model. */
11
+ readonly cliPath?: string | undefined;
10
12
  private cache;
11
13
  private pending;
12
14
  private states;
13
15
  /** Requests the AI approved, counted once each however often they are retried. */
14
16
  private approvedByAi;
15
- constructor(directory: string, harness: string, sessionId: string, profile?: Profile);
17
+ /** Files this session created, and the paths each approved request may create. */
18
+ private created;
19
+ private creating;
20
+ constructor(directory: string, harness: string, sessionId: string, profile?: Profile,
21
+ /** This package's `cli.js`: the path in the record command the hook gives the model. */
22
+ cliPath?: string | undefined);
23
+ /**
24
+ * The record command the hook gives this session is approved before the policy runs: the
25
+ * engine cannot always verify an installed CLI outside the repository or a here-string (strict
26
+ * mode never can), so the round trip could not finish. Any other classification record, for
27
+ * another session or CLI or with anything added, goes to a person.
28
+ */
29
+ private classifyRecord;
16
30
  private state;
17
31
  private remember;
18
32
  /**
package/dist/session.js CHANGED
@@ -1,26 +1,64 @@
1
+ import { isClassifyRecord, looksLikeClassifyRecord } from "./adapters.js";
1
2
  import { audit, requestSummary } from "./audit.js";
2
- import { evaluate, hash } from "./policy.js";
3
+ import { creationTargets, pathKey, settle, withCreated, } from "./created.js";
4
+ import { evaluate, hash, requestHash as requestHashOf, result, SHELL_TOOLS } from "./policy.js";
3
5
  import { strictProfile } from "./profile.js";
4
6
  import { redactText } from "./redact.js";
7
+ import { CATEGORIES, } from "./types.js";
5
8
  /** How long a classification outcome for one exact request is remembered. */
6
9
  const CLASSIFICATION_TTL_MS = 5 * 60_000;
7
10
  /** AI approvals per session; beyond this, ambiguous requests go to a human. */
8
11
  export const MAX_AI_APPROVALS = 50;
12
+ /** How long after its approval an execution report may still record the files a tool created. */
13
+ const CREATION_REPORT_MS = 15 * 60_000;
9
14
  export class PolicySession {
10
15
  directory;
11
16
  harness;
12
17
  sessionId;
13
18
  profile;
19
+ cliPath;
14
20
  cache = new Map();
15
21
  pending = new Map();
16
22
  states = new Map();
17
23
  /** Requests the AI approved, counted once each however often they are retried. */
18
24
  approvedByAi = new Set();
19
- constructor(directory, harness, sessionId, profile = strictProfile) {
25
+ /** Files this session created, and the paths each approved request may create. */
26
+ created = new Map();
27
+ creating = new Map();
28
+ constructor(directory, harness, sessionId, profile = strictProfile,
29
+ /** This package's `cli.js`: the path in the record command the hook gives the model. */
30
+ cliPath) {
20
31
  this.directory = directory;
21
32
  this.harness = harness;
22
33
  this.sessionId = sessionId;
23
34
  this.profile = profile;
35
+ this.cliPath = cliPath;
36
+ }
37
+ /**
38
+ * The record command the hook gives this session is approved before the policy runs: the
39
+ * engine cannot always verify an installed CLI outside the repository or a here-string (strict
40
+ * mode never can), so the round trip could not finish. Any other classification record, for
41
+ * another session or CLI or with anything added, goes to a person.
42
+ */
43
+ classifyRecord(request) {
44
+ const input = request.input;
45
+ const command = input.command ?? input.cmd;
46
+ if (!SHELL_TOOLS.has(request.tool) ||
47
+ typeof command !== "string" ||
48
+ !looksLikeClassifyRecord(command))
49
+ return undefined;
50
+ const cwd = input.workdir ?? input.cwd ?? request.cwd;
51
+ if (this.cliPath &&
52
+ cwd === request.cwd &&
53
+ input.env === undefined &&
54
+ input.shell === undefined &&
55
+ input.stdin === undefined &&
56
+ isClassifyRecord(command, request.harness, {
57
+ cliPath: this.cliPath,
58
+ sessionId: this.sessionId,
59
+ }))
60
+ return result(request, "temp-write", "Records a classification for this session", true);
61
+ return result(request, "unknown", "A classification record for another session or CLI, or with anything added, requires human review");
24
62
  }
25
63
  state(requestHash) {
26
64
  const state = this.states.get(requestHash);
@@ -53,16 +91,7 @@ export class PolicySession {
53
91
  throw new Error("Session mismatch");
54
92
  audit(this.directory, { event: "request", ...requestSummary(request) });
55
93
  if (ai &&
56
- (![
57
- "code-read",
58
- "worktree-write",
59
- "cloud-read",
60
- "git-read",
61
- "impactful-write",
62
- "destructive",
63
- "sensitive",
64
- "unknown",
65
- ].includes(ai.category) ||
94
+ (!CATEGORIES.includes(ai.category) ||
66
95
  typeof ai.confidence !== "number" ||
67
96
  !Number.isFinite(ai.confidence) ||
68
97
  (ai.recoverable !== undefined && typeof ai.recoverable !== "boolean") ||
@@ -73,14 +102,18 @@ export class PolicySession {
73
102
  decision: "human",
74
103
  category: "unknown",
75
104
  reason: "Malformed AI classification",
76
- requestHash: hash(request),
105
+ requestHash: requestHashOf(request),
77
106
  });
78
107
  throw new Error("Malformed AI classification");
79
108
  }
80
- const key = hash([hash(request), "policy-v1", this.profile.digest ?? this.profile.mode]);
109
+ const key = hash([
110
+ requestHashOf(request),
111
+ "policy-v1",
112
+ this.profile.digest ?? this.profile.mode,
113
+ ]);
81
114
  const entry = this.cache.get(key);
82
115
  const cachedAi = entry && entry.expires > Date.now() ? entry.ai : undefined;
83
- const requestHash = hash(request);
116
+ const requestHash = requestHashOf(request);
84
117
  const known = ai ? undefined : this.state(requestHash);
85
118
  if (ai)
86
119
  audit(this.directory, {
@@ -91,7 +124,8 @@ export class PolicySession {
91
124
  ...(ai.recoverable === undefined ? {} : { recoverable: ai.recoverable }),
92
125
  ...(ai.rationale ? { rationale: redactText(ai.rationale, 200) } : {}),
93
126
  });
94
- let decision = evaluate(request, ai ?? cachedAi ?? known?.ai, this.profile);
127
+ let decision = this.classifyRecord(request) ??
128
+ withCreated(this.created, () => evaluate(request, ai ?? cachedAi ?? known?.ai, this.profile));
95
129
  if (decision.tier === "ambiguous") {
96
130
  if (ai && !decision.classification)
97
131
  this.remember(requestHash, { invalid: true });
@@ -169,6 +203,17 @@ export class PolicySession {
169
203
  this.pending.delete(this.pending.keys().next().value ?? "");
170
204
  this.pending.set(decision.requestHash, request);
171
205
  }
206
+ // Every decision replaces the pending creations for this request, so a report can only ever
207
+ // settle the most recent approval: an earlier approval whose report never came is forgotten.
208
+ this.creating.delete(decision.requestHash);
209
+ if (decision.decision === "approve") {
210
+ const targets = creationTargets(request, this.created);
211
+ if (targets.length) {
212
+ if (this.creating.size >= 256)
213
+ this.creating.delete(this.creating.keys().next().value ?? "");
214
+ this.creating.set(decision.requestHash, { targets, approvedAt: Date.now() });
215
+ }
216
+ }
172
217
  const { ai: classification, ...safe } = decision;
173
218
  audit(this.directory, {
174
219
  event: "decision",
@@ -215,6 +260,22 @@ export class PolicySession {
215
260
  ...(report.durationMs === undefined ? {} : { durationMs: report.durationMs }),
216
261
  summary: "Harness-reported execution result",
217
262
  });
263
+ // A target is the session's only if `settle` proves the file there is its own inode or a new
264
+ // one born after the approval; otherwise any earlier claim on the path is dropped.
265
+ // A report that comes too long after its approval records nothing.
266
+ const pending = this.creating.get(report.requestHash);
267
+ const fresh = pending && Date.now() - pending.approvedAt <= CREATION_REPORT_MS ? pending : undefined;
268
+ for (const target of fresh?.targets ?? []) {
269
+ const now = settle(target, fresh?.approvedAt ?? Number.POSITIVE_INFINITY);
270
+ if (!now)
271
+ this.created.delete(pathKey(target.path));
272
+ else {
273
+ if (this.created.size >= 4096)
274
+ this.created.clear();
275
+ this.created.set(pathKey(target.path), now);
276
+ }
277
+ }
278
+ this.creating.delete(report.requestHash);
218
279
  }
219
280
  else
220
281
  throw new Error("Invalid outcome event");
package/dist/types.d.ts CHANGED
@@ -1,4 +1,7 @@
1
- export type Category = "code-read" | "worktree-write" | "cloud-read" | "git-read" | "impactful-write" | "destructive" | "sensitive" | "unknown";
1
+ export declare const CATEGORIES: readonly ["code-read", "worktree-write",
2
+ /** A recoverable write outside any repository, such as the system temp directory. */
3
+ "temp-write", "cloud-read", "git-read", "impactful-write", "destructive", "sensitive", "unknown"];
4
+ export type Category = (typeof CATEGORIES)[number];
2
5
  export interface Request {
3
6
  sessionId: string;
4
7
  harness: "claude" | "codex" | "copilot";
@@ -18,8 +21,11 @@ export interface Classification {
18
21
  /** Where an ambiguous request stands in the AI classification flow. */
19
22
  export type ClassificationStage = "requested" | "approved" | "denied" | "fallback";
20
23
  export interface Decision {
21
- /** `deny` is a decision the model sees and works around; `human` asks the person. */
22
- decision: "approve" | "human" | "deny";
24
+ /**
25
+ * `deny` is a decision the model sees and works around; `human` asks the person; `native` makes
26
+ * no decision and leaves the request to the harness's own permission flow.
27
+ */
28
+ decision: "approve" | "human" | "deny" | "native";
23
29
  category: Category;
24
30
  reason: string;
25
31
  requestHash: string;
package/dist/types.js CHANGED
@@ -1,2 +1,13 @@
1
- export {};
1
+ export const CATEGORIES = [
2
+ "code-read",
3
+ "worktree-write",
4
+ /** A recoverable write outside any repository, such as the system temp directory. */
5
+ "temp-write",
6
+ "cloud-read",
7
+ "git-read",
8
+ "impactful-write",
9
+ "destructive",
10
+ "sensitive",
11
+ "unknown",
12
+ ];
2
13
  //# sourceMappingURL=types.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-corpus/policy-manager",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Deterministic, session-scoped permission decisions with audit logs and bounded AI classification.",
5
5
  "keywords": [
6
6
  "coding-agent",
@@ -50,6 +50,6 @@
50
50
  "postpack": "node -e \"require('fs').rmSync('LICENSE',{force:true})\""
51
51
  },
52
52
  "dependencies": {
53
- "@agent-corpus/audit-log": "^0.1.0"
53
+ "@agent-corpus/audit-log": "^0.1.1"
54
54
  }
55
55
  }