@lannguyensi/harness 0.50.0 → 0.52.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +247 -0
  2. package/dist/cli/approve/understanding.d.ts +97 -0
  3. package/dist/cli/approve/understanding.js +67 -24
  4. package/dist/cli/approve/understanding.js.map +1 -1
  5. package/dist/cli/audit.d.ts +29 -0
  6. package/dist/cli/audit.js +130 -17
  7. package/dist/cli/audit.js.map +1 -1
  8. package/dist/cli/delegate/index.d.ts +63 -0
  9. package/dist/cli/delegate/index.js +313 -0
  10. package/dist/cli/delegate/index.js.map +1 -0
  11. package/dist/cli/doctor/auto-approve-mode.d.ts +37 -0
  12. package/dist/cli/doctor/auto-approve-mode.js +80 -0
  13. package/dist/cli/doctor/auto-approve-mode.js.map +1 -0
  14. package/dist/cli/doctor/claude-mcp.d.ts +14 -0
  15. package/dist/cli/doctor/claude-mcp.js +7 -1
  16. package/dist/cli/doctor/claude-mcp.js.map +1 -1
  17. package/dist/cli/doctor/codex-config-drift.d.ts +28 -0
  18. package/dist/cli/doctor/codex-config-drift.js +240 -0
  19. package/dist/cli/doctor/codex-config-drift.js.map +1 -0
  20. package/dist/cli/doctor/format.js +67 -1
  21. package/dist/cli/doctor/format.js.map +1 -1
  22. package/dist/cli/doctor/index.d.ts +20 -0
  23. package/dist/cli/doctor/index.js +84 -1
  24. package/dist/cli/doctor/index.js.map +1 -1
  25. package/dist/cli/doctor/settings-drift.d.ts +25 -0
  26. package/dist/cli/doctor/settings-drift.js +203 -0
  27. package/dist/cli/doctor/settings-drift.js.map +1 -0
  28. package/dist/cli/doctor/types.d.ts +69 -0
  29. package/dist/cli/doctor/types.js.map +1 -1
  30. package/dist/cli/doctor/ug-auto-approvals.d.ts +40 -0
  31. package/dist/cli/doctor/ug-auto-approvals.js +116 -0
  32. package/dist/cli/doctor/ug-auto-approvals.js.map +1 -0
  33. package/dist/cli/doctor/ug-delegations.d.ts +26 -0
  34. package/dist/cli/doctor/ug-delegations.js +112 -0
  35. package/dist/cli/doctor/ug-delegations.js.map +1 -0
  36. package/dist/cli/doctor/understanding-mode-env.d.ts +12 -0
  37. package/dist/cli/doctor/understanding-mode-env.js +16 -1
  38. package/dist/cli/doctor/understanding-mode-env.js.map +1 -1
  39. package/dist/cli/index.js +100 -1
  40. package/dist/cli/index.js.map +1 -1
  41. package/dist/cli/pack/approve-escape.js +16 -7
  42. package/dist/cli/pack/approve-escape.js.map +1 -1
  43. package/dist/cli/pack/auto-approve-path.d.ts +135 -0
  44. package/dist/cli/pack/auto-approve-path.js +400 -0
  45. package/dist/cli/pack/auto-approve-path.js.map +1 -0
  46. package/dist/cli/pack/hook-codex-pre-tool-use.d.ts +9 -0
  47. package/dist/cli/pack/hook-codex-pre-tool-use.js +118 -4
  48. package/dist/cli/pack/hook-codex-pre-tool-use.js.map +1 -1
  49. package/dist/cli/pack/hook-pre-tool-use.d.ts +36 -0
  50. package/dist/cli/pack/hook-pre-tool-use.js +402 -3
  51. package/dist/cli/pack/hook-pre-tool-use.js.map +1 -1
  52. package/dist/cli/pack/transcript-report-scan.d.ts +71 -0
  53. package/dist/cli/pack/transcript-report-scan.js +359 -0
  54. package/dist/cli/pack/transcript-report-scan.js.map +1 -0
  55. package/dist/cli/smoke/index.d.ts +18 -1
  56. package/dist/cli/smoke/index.js +54 -0
  57. package/dist/cli/smoke/index.js.map +1 -1
  58. package/dist/cli/validate/checks.js +81 -0
  59. package/dist/cli/validate/checks.js.map +1 -1
  60. package/dist/policy-packs/builtin/understanding-before-execution/auto-approve.d.ts +210 -0
  61. package/dist/policy-packs/builtin/understanding-before-execution/auto-approve.js +361 -0
  62. package/dist/policy-packs/builtin/understanding-before-execution/auto-approve.js.map +1 -0
  63. package/dist/policy-packs/builtin/understanding-before-execution/delegation-markers.d.ts +223 -0
  64. package/dist/policy-packs/builtin/understanding-before-execution/delegation-markers.js +633 -0
  65. package/dist/policy-packs/builtin/understanding-before-execution/delegation-markers.js.map +1 -0
  66. package/dist/policy-packs/builtin/understanding-before-execution/index.d.ts +3 -1
  67. package/dist/policy-packs/builtin/understanding-before-execution/index.js +10 -1
  68. package/dist/policy-packs/builtin/understanding-before-execution/index.js.map +1 -1
  69. package/dist/policy-packs/builtin/understanding-before-execution/measured-permission-modes.d.ts +29 -0
  70. package/dist/policy-packs/builtin/understanding-before-execution/measured-permission-modes.js +82 -0
  71. package/dist/policy-packs/builtin/understanding-before-execution/measured-permission-modes.js.map +1 -0
  72. package/dist/policy-packs/builtin/understanding-before-execution/persisted-reports.d.ts +23 -0
  73. package/dist/policy-packs/builtin/understanding-before-execution/persisted-reports.js +29 -0
  74. package/dist/policy-packs/builtin/understanding-before-execution/persisted-reports.js.map +1 -1
  75. package/dist/policy-packs/builtin/understanding-before-execution.d.ts +42 -0
  76. package/dist/policy-packs/builtin/understanding-before-execution.js +56 -1
  77. package/dist/policy-packs/builtin/understanding-before-execution.js.map +1 -1
  78. package/dist/runtime/approval-signing.d.ts +22 -0
  79. package/dist/runtime/approval-signing.js +83 -1
  80. package/dist/runtime/approval-signing.js.map +1 -1
  81. package/package.json +1 -1
@@ -0,0 +1,361 @@
1
+ // `auto_approve` pack-config parsing and shared conventions, split out
2
+ // alongside lifecycle.ts (structural sibling of the former monolithic
3
+ // understanding-before-execution-runtime.ts, agent-tasks 348a4d42).
4
+ // Implements slice 1 of docs/decisions/2026-08-27-ug-auto-mode-approval.md
5
+ // (agent-tasks 74b4b17d): the strict pack-config block that lets an
6
+ // operator opt a permission mode into the hook-written signed
7
+ // auto-marker path, plus the shared `approvedBy` / ledger-tag
8
+ // conventions the hook and doctor consume so there is one authority
9
+ // for the string shapes instead of each caller reimplementing them.
10
+ //
11
+ // This module owns no gate decision and no marker write: it only
12
+ // parses the opt-in config (fail-closed: any malformed shape is
13
+ // treated as "not opted in", never as a partial default) and builds /
14
+ // parses the string conventions the ADR's "Audit and doctor" section
15
+ // documents. The PreToolUse hook (auto-path condition checks) and
16
+ // `harness doctor` (auto-approval listing) are the consumers; both
17
+ // land in later slice-1 tasks and import from here.
18
+ //
19
+ // Slice 3 (agent-tasks 37ad0b05) adds `report_scan.max_wait`: the bound
20
+ // of the child's transcript poll under `claude -p` ("Report capture
21
+ // under `-p`" in the ADR). It lives in this block because it tunes the
22
+ // same opt-in path, and it is parsed here rather than at the hook so
23
+ // the lint-time schema and the runtime hook agree on one parser.
24
+ import { InvalidDurationError, parseDurationSeconds } from "../../../policies/index.js";
25
+ /**
26
+ * Prefix every auto-minted marker's `approvedBy` carries, distinguishing
27
+ * it from a human `harness approve understanding` marker (which carries
28
+ * the operator's own identity string, never this prefix).
29
+ */
30
+ export const AUTO_APPROVED_BY_PREFIX = "auto-mode:";
31
+ /** The harness identifier the Claude Code PreToolUse hook mints markers for. */
32
+ export const CLAUDE_CODE_HARNESS = "claude-code";
33
+ /**
34
+ * The harness identifier the Codex PreToolUse hook mints markers for
35
+ * (slice 2 of the ADR: same auto path, same fail-closed conditions, a
36
+ * distinct `approvedBy` segment so an audit can tell the two runtimes
37
+ * apart). Deliberately NOT re-exported through
38
+ * `understanding-before-execution/index.ts`: its only consumer is
39
+ * `src/cli/pack/hook-codex-pre-tool-use.ts`, and widening the runtime
40
+ * shim's pinned public surface (tests/policy-packs/ube-export-surface.test.ts)
41
+ * is a separate, conscious act.
42
+ */
43
+ export const CODEX_HARNESS = "codex";
44
+ /**
45
+ * Build the `approvedBy` value the hook writes into a signed auto-marker:
46
+ * `auto-mode:<harness>:<mode>`, for example `auto-mode:claude-code:bypassPermissions`
47
+ * or `auto-mode:codex:bypassPermissions` ("Audit and doctor" in the ADR).
48
+ * Neither `harness` nor `mode` is validated here; callers pass
49
+ * already-known-good values (one of the fixed harness constants above and
50
+ * a `when`-matched mode string).
51
+ */
52
+ export function autoApprovedByFor(harness, mode) {
53
+ return `${AUTO_APPROVED_BY_PREFIX}${harness}:${mode}`;
54
+ }
55
+ /**
56
+ * Parse an `approvedBy` string back into its harness/mode pair. Returns
57
+ * `null` for anything that is not exactly `auto-mode:<harness>:<mode>`
58
+ * with both segments non-empty, including a human marker's `approvedBy`
59
+ * (which never carries this prefix) and a malformed or truncated auto
60
+ * value. A slice 3 delegation suffix (`;delegated:<parent-sid>`) is
61
+ * tolerated: it is stripped before parsing and otherwise ignored, per
62
+ * the ADR's "Audit and doctor" convention that the delegation binding
63
+ * packs into the same field without changing the harness/mode shape.
64
+ */
65
+ export function parseAutoApprovedBy(approvedBy) {
66
+ if (typeof approvedBy !== "string")
67
+ return null;
68
+ if (!approvedBy.startsWith(AUTO_APPROVED_BY_PREFIX))
69
+ return null;
70
+ const withoutPrefix = approvedBy.slice(AUTO_APPROVED_BY_PREFIX.length);
71
+ const [withoutDelegation] = withoutPrefix.split(";delegated:");
72
+ const segments = (withoutDelegation ?? "").split(":");
73
+ if (segments.length !== 2)
74
+ return null;
75
+ const [harness, mode] = segments;
76
+ if (!harness || !mode)
77
+ return null;
78
+ return { harness, mode };
79
+ }
80
+ /**
81
+ * Build the audit-only ledger fact the ADR's "Audit and doctor" section
82
+ * names: `understanding-auto-approved:<sid>`, distinct from the human
83
+ * `understanding-approved:<sid>` tag (`ledger.ts`), following the same
84
+ * `...:forced:<field>` suffix precedent the ADR cites. Ledger only, never
85
+ * consulted for the gate decision itself.
86
+ */
87
+ export function autoApprovedLedgerTagFor(sessionId) {
88
+ return `understanding-auto-approved:${sessionId}`;
89
+ }
90
+ /**
91
+ * The harness identifiers `auto_approve.harnesses` accepts, in the order
92
+ * the schema and every diagnostic list them. Shared with the pack's zod
93
+ * `configSchema` (`../understanding-before-execution.ts`) so the lint-time
94
+ * enum and this runtime parser cannot drift apart.
95
+ */
96
+ export const AUTO_APPROVE_HARNESS_VALUES = [CLAUDE_CODE_HARNESS, CODEX_HARNESS];
97
+ /**
98
+ * What `auto_approve.harnesses` resolves to when the key is ABSENT.
99
+ * Claude Code only, deliberately: slice 1 shipped `auto_approve` as a
100
+ * Claude-only opt-in, so a repo that opted in before slice 2 must keep
101
+ * exactly the meaning it had — adding the Codex hook to the shared body
102
+ * must not silently extend an existing opt-in to a second runtime
103
+ * (reviewer round-1 finding on slice 2). Opting Codex in is an explicit,
104
+ * visible config edit.
105
+ */
106
+ export const DEFAULT_AUTO_APPROVE_HARNESSES = [CLAUDE_CODE_HARNESS];
107
+ /**
108
+ * What `auto_approve.report_scan.max_wait` resolves to when the key is
109
+ * ABSENT: the bound the child's PreToolUse hook waits for its own
110
+ * Understanding Report to reach the session transcript before it blocks
111
+ * (ADR "Report capture under `-p`", slice 3 acceptance criterion 3).
112
+ *
113
+ * The value is measured, not guessed: under `claude -p` the report is
114
+ * absent from the transcript at the instant PreToolUse fires and lands
115
+ * some time later, on a lag that scales with report length, so the
116
+ * bound is set from the real end-to-end runs (a full-length grill_me
117
+ * report), not only the shorter probe reports that first-guessed 500ms.
118
+ * The measurement and the retuning derivation are both in
119
+ * `docs/okf/understanding-gate-auto-mode-signals.md` ("Chosen
120
+ * `report_scan.max_wait` default" section), from
121
+ * `dogfood/ug-auto-mode-signals/`.
122
+ *
123
+ * ONE named constant on purpose: the hook, the schema default and every
124
+ * test read this symbol, so re-tuning the bound against a new
125
+ * measurement is a one-line change with no literal to hunt down.
126
+ */
127
+ export const DEFAULT_REPORT_SCAN_MAX_WAIT_MS = 2_000;
128
+ /**
129
+ * Hard ceiling for `auto_approve.report_scan.max_wait`. A larger value
130
+ * is a `harness validate` schema error AND a runtime parse failure (which
131
+ * fails the whole `auto_approve` block closed), so no configuration can
132
+ * make a PreToolUse hook sit on a session for an arbitrary time. 5 s is
133
+ * an order of magnitude above the measured worst-case flush, which is
134
+ * generous for a bound whose only job is to cover a transcript write
135
+ * already in flight.
136
+ */
137
+ export const REPORT_SCAN_MAX_WAIT_CEILING_MS = 5_000;
138
+ const KNOWN_AUTO_APPROVE_KEYS = new Set([
139
+ "when",
140
+ "harnesses",
141
+ "require_report",
142
+ "report_scan",
143
+ ]);
144
+ /** The only key `auto_approve.report_scan` accepts. */
145
+ const KNOWN_REPORT_SCAN_KEYS = new Set(["max_wait"]);
146
+ /** Sub-second shorthand the shared duration parser does not model. */
147
+ const MILLISECOND_SHORTHAND = /^(\d+)ms$/;
148
+ /**
149
+ * Parse `auto_approve.report_scan.max_wait` into milliseconds.
150
+ *
151
+ * Duration grammar: the pack's SHARED parser
152
+ * ({@link parseDurationSeconds}, the same one `approval_lifecycle.max_age`
153
+ * uses), plus an `<n>ms` shorthand it does not model. The extension is
154
+ * not cosmetic: this bound is a transcript-flush allowance measured in
155
+ * tens of milliseconds, so a second-granularity grammar could not express
156
+ * the values the measurement actually argues for, and widening
157
+ * `parseDurationSeconds` itself would change the grammar of every
158
+ * `within:` / `max_age:` / `--since` value in the repo for one key's sake.
159
+ *
160
+ * Both bounds are errors, never clamps: zero or negative (a bound that
161
+ * would disable the poll while the block still claimed to have one) and
162
+ * anything above {@link REPORT_SCAN_MAX_WAIT_CEILING_MS} (a bound that
163
+ * could park a PreToolUse hook). Returning a RESULT rather than throwing
164
+ * keeps the two consumers symmetric: the zod schema turns it into a
165
+ * `harness validate` diagnostic, the runtime parser into one stderr line
166
+ * and a fail-closed `null`.
167
+ */
168
+ export function parseReportScanMaxWait(raw) {
169
+ if (typeof raw !== "string" || raw.trim().length === 0) {
170
+ return {
171
+ ok: false,
172
+ reason: `expected a duration string like "500ms", "1500ms" or "2s", got ${typeof raw === "string" ? "an empty string" : typeof raw}`,
173
+ };
174
+ }
175
+ const trimmed = raw.trim();
176
+ let maxWaitMs;
177
+ const ms = MILLISECOND_SHORTHAND.exec(trimmed);
178
+ if (ms) {
179
+ maxWaitMs = Number.parseInt(ms[1], 10);
180
+ }
181
+ else {
182
+ try {
183
+ maxWaitMs = parseDurationSeconds(trimmed) * 1_000;
184
+ }
185
+ catch (err) {
186
+ return {
187
+ ok: false,
188
+ reason: err instanceof InvalidDurationError ? err.message : String(err),
189
+ };
190
+ }
191
+ }
192
+ if (!Number.isFinite(maxWaitMs) || maxWaitMs <= 0) {
193
+ return {
194
+ ok: false,
195
+ reason: `must be greater than zero, got ${JSON.stringify(trimmed)}`,
196
+ };
197
+ }
198
+ if (maxWaitMs > REPORT_SCAN_MAX_WAIT_CEILING_MS) {
199
+ return {
200
+ ok: false,
201
+ reason: `must not exceed the ${REPORT_SCAN_MAX_WAIT_CEILING_MS}ms hard ceiling (a PreToolUse hook must never park a session), got ${JSON.stringify(trimmed)}`,
202
+ };
203
+ }
204
+ return { ok: true, maxWaitMs };
205
+ }
206
+ /**
207
+ * Parse the optional `auto_approve` pack-config block
208
+ * (docs/decisions/2026-08-27-ug-auto-mode-approval.md, "Option A").
209
+ *
210
+ * FAIL CLOSED, unlike {@link parseApprovalLifecycle}'s best-effort
211
+ * fallback: this block is an opt-IN to a hook-side signing path
212
+ * (hardening item 3 in the ADR's threat model (b) — `require_report:
213
+ * false` must be a schema error, not a silently-ignored key), so any
214
+ * malformed shape here means "not opted in" (`null`), never a partial
215
+ * or default-filled config that could still enable the auto path. The
216
+ * `configSchema` zod block in `../understanding-before-execution.ts` is
217
+ * the first line of defence (`harness validate` / `harness doctor`
218
+ * reject a malformed manifest at lint time); this parser is the second,
219
+ * defensive line for the runtime hook, which must not trust that every
220
+ * config it sees on disk passed the schema.
221
+ *
222
+ * `undefined` / `null` (the block is simply absent) returns `null`
223
+ * silently — that is the ordinary "not opted in" case, not a warning.
224
+ * Every other malformed shape writes exactly one stderr line and
225
+ * returns `null`.
226
+ *
227
+ * `label` is the stderr prefix of the calling hook, so a Codex-side
228
+ * warning reads `harness pack hook codex: ...` like every other line
229
+ * that hook writes. The default reproduces the Claude Code hook's
230
+ * wording byte-for-byte.
231
+ */
232
+ export function parseAutoApprove(raw, stderr, label = "harness pack hook") {
233
+ if (raw === undefined || raw === null)
234
+ return null;
235
+ if (typeof raw !== "object" || Array.isArray(raw)) {
236
+ stderr?.write(`${label}: config.auto_approve ignored (expected object, got ${typeof raw})\n`);
237
+ return null;
238
+ }
239
+ const obj = raw;
240
+ const unknownKeys = Object.keys(obj).filter((k) => !KNOWN_AUTO_APPROVE_KEYS.has(k));
241
+ if (unknownKeys.length > 0) {
242
+ stderr?.write(`${label}: config.auto_approve ignored (unknown key(s): ${unknownKeys.join(", ")})\n`);
243
+ return null;
244
+ }
245
+ const whenRaw = obj["when"];
246
+ if (!Array.isArray(whenRaw) || whenRaw.length === 0) {
247
+ stderr?.write(`${label}: config.auto_approve.when ignored (expected a non-empty string[], got ${Array.isArray(whenRaw) ? "empty array" : typeof whenRaw})\n`);
248
+ return null;
249
+ }
250
+ const when = [];
251
+ for (const v of whenRaw) {
252
+ if (typeof v !== "string" || v.length === 0) {
253
+ stderr?.write(`${label}: config.auto_approve.when ignored (every entry must be a non-empty string, got ${typeof v})\n`);
254
+ return null;
255
+ }
256
+ when.push(v);
257
+ }
258
+ // `harnesses`: absent means the slice-1 default (Claude Code only).
259
+ // Present means an exact, non-empty, duplicate-free list of the known
260
+ // harness identifiers — anything else fails the whole block closed,
261
+ // like every other malformed shape here, so a typo'd entry can never
262
+ // widen the opt-in to a runtime the operator did not name.
263
+ const harnessesRaw = obj["harnesses"];
264
+ let harnesses = [...DEFAULT_AUTO_APPROVE_HARNESSES];
265
+ if (harnessesRaw !== undefined) {
266
+ if (!Array.isArray(harnessesRaw) || harnessesRaw.length === 0) {
267
+ stderr?.write(`${label}: config.auto_approve.harnesses ignored (expected a non-empty array of ${AUTO_APPROVE_HARNESS_VALUES.join(" | ")}, got ${Array.isArray(harnessesRaw) ? "empty array" : typeof harnessesRaw})\n`);
268
+ return null;
269
+ }
270
+ const seen = [];
271
+ for (const v of harnessesRaw) {
272
+ if (typeof v !== "string" || !AUTO_APPROVE_HARNESS_VALUES.includes(v)) {
273
+ stderr?.write(`${label}: config.auto_approve.harnesses ignored (every entry must be one of ${AUTO_APPROVE_HARNESS_VALUES.join(", ")}, got ${typeof v === "string" ? `"${v}"` : typeof v})\n`);
274
+ return null;
275
+ }
276
+ if (seen.includes(v)) {
277
+ stderr?.write(`${label}: config.auto_approve.harnesses ignored (duplicate entry "${v}")\n`);
278
+ return null;
279
+ }
280
+ seen.push(v);
281
+ }
282
+ harnesses = seen;
283
+ }
284
+ // `report_scan`: absent means the measured default
285
+ // ({@link DEFAULT_REPORT_SCAN_MAX_WAIT_MS}). Present means an object
286
+ // carrying exactly `max_wait` and nothing else, parsed and
287
+ // range-checked by `parseReportScanMaxWait`. Anything else fails the
288
+ // WHOLE block closed, like every other malformed shape here, so a
289
+ // typo'd bound can never silently fall back to the default while the
290
+ // operator believes they tuned it.
291
+ const reportScanRaw = obj["report_scan"];
292
+ let reportScanMaxWaitMs = DEFAULT_REPORT_SCAN_MAX_WAIT_MS;
293
+ if (reportScanRaw !== undefined) {
294
+ if (reportScanRaw === null || typeof reportScanRaw !== "object" || Array.isArray(reportScanRaw)) {
295
+ stderr?.write(`${label}: config.auto_approve.report_scan ignored (expected object, got ${reportScanRaw === null ? "null" : Array.isArray(reportScanRaw) ? "array" : typeof reportScanRaw})\n`);
296
+ return null;
297
+ }
298
+ const reportScanObj = reportScanRaw;
299
+ const unknownScanKeys = Object.keys(reportScanObj).filter((k) => !KNOWN_REPORT_SCAN_KEYS.has(k));
300
+ if (unknownScanKeys.length > 0) {
301
+ stderr?.write(`${label}: config.auto_approve.report_scan ignored (unknown key(s): ${unknownScanKeys.join(", ")})\n`);
302
+ return null;
303
+ }
304
+ const maxWait = parseReportScanMaxWait(reportScanObj["max_wait"]);
305
+ if (!maxWait.ok) {
306
+ stderr?.write(`${label}: config.auto_approve.report_scan.max_wait ignored (${maxWait.reason})\n`);
307
+ return null;
308
+ }
309
+ reportScanMaxWaitMs = maxWait.maxWaitMs;
310
+ }
311
+ const requireReport = obj["require_report"];
312
+ if (requireReport !== true) {
313
+ stderr?.write(`${label}: config.auto_approve ignored (require_report must be true, got ${requireReport === false ? "false" : typeof requireReport})\n`);
314
+ return null;
315
+ }
316
+ return { when, harnesses, reportScan: { maxWaitMs: reportScanMaxWaitMs } };
317
+ }
318
+ /**
319
+ * ADR "Additional hardening to specify" item 2: `when` is an allowlist
320
+ * of payload literals, membership by exact string equality, no case
321
+ * folding, no substring, no wildcards. `mode` absent, empty, or not a
322
+ * string means no auto-approval, and `cfg === null` (block absent or
323
+ * malformed) means no auto-approval regardless of `mode`.
324
+ *
325
+ * Takes only the `when` slice of the config rather than the whole block:
326
+ * this predicate reads exactly one field, and saying so in the signature
327
+ * keeps it honest as the block grows further keys (`harnesses`,
328
+ * `report_scan`) that have nothing to do with mode membership.
329
+ */
330
+ export function permissionModeAllowed(cfg, mode) {
331
+ if (cfg === null)
332
+ return false;
333
+ if (typeof mode !== "string" || mode.length === 0)
334
+ return false;
335
+ return cfg.when.includes(mode);
336
+ }
337
+ /**
338
+ * Per-harness opt-in membership, the same exact-string-equality
339
+ * discipline {@link permissionModeAllowed} applies to `when`. `cfg ===
340
+ * null` (block absent or malformed) means no auto-approval regardless of
341
+ * the harness, and an unlisted harness means no auto-approval regardless
342
+ * of `when` — the two allowlists are independent AND conditions, not
343
+ * alternatives.
344
+ *
345
+ * Re-exported through `understanding-before-execution/index.ts` (round-2
346
+ * review finding on slice 2): its call site (`src/cli/pack/auto-approve-path.ts`)
347
+ * imports every sibling symbol it needs (`parseAutoApprove`,
348
+ * `permissionModeAllowed`, ...) through the runtime shim already, so this
349
+ * one was pulled onto the pinned shim surface
350
+ * (tests/policy-packs/ube-export-surface.test.ts) to match, unlike
351
+ * {@link CODEX_HARNESS} which still has exactly one consumer and stays a
352
+ * direct import.
353
+ */
354
+ export function harnessAllowed(cfg, harness) {
355
+ if (cfg === null)
356
+ return false;
357
+ if (typeof harness !== "string" || harness.length === 0)
358
+ return false;
359
+ return cfg.harnesses.includes(harness);
360
+ }
361
+ //# sourceMappingURL=auto-approve.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-approve.js","sourceRoot":"","sources":["../../../../src/policy-packs/builtin/understanding-before-execution/auto-approve.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,sEAAsE;AACtE,oEAAoE;AACp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atedDir`. */
2
+ export declare const DELEGATION_MARKER_DIRNAME = ".delegations";
3
+ /**
4
+ * The signed markerId for a child session: `delegation-<child-sid>`.
5
+ * Binding it into the signed payload is what stops a validly signed
6
+ * delegation from being copied onto another child id, or onto a session
7
+ * marker's id, and still verifying (`task-markers.ts` precedent).
8
+ */
9
+ export declare function delegationMarkerIdFor(childSessionId: string): string;
10
+ /**
11
+ * Filesystem path of a child session's delegation marker. Rejects a
12
+ * malformed session id the same way `approvalMarkerPathFor` does (the
13
+ * value lands in a `path.join` verbatim).
14
+ */
15
+ export declare function delegationMarkerPathFor(generatedDir: string, childSessionId: string): string;
16
+ /**
17
+ * sha256 hex of a filesystem path, canonicalized through `realpathSync`
18
+ * when the path exists and through `path.resolve` when it does not.
19
+ *
20
+ * The canonicalization is the point, not an optimization: the parent
21
+ * writing the delegation and the child reporting its cwd routinely spell
22
+ * the same directory differently (on macOS `os.tmpdir()` hands out
23
+ * `/var/folders/...` while the process reports `/private/var/folders/...`,
24
+ * because `/var` is a symlink), and an uncanonicalized comparison would
25
+ * refuse a perfectly legitimate delegation. Falling back to `resolve` for
26
+ * a non-existent path keeps the function total: a path that cannot be
27
+ * canonicalized still hashes deterministically, and a delegation bound to
28
+ * it simply will not match a cwd that resolves elsewhere.
29
+ *
30
+ * Named for its primary use; the fallback shape hashes the launcher-
31
+ * supplied report file's PATH with the same function, so that WHERE the
32
+ * parent put the report is part of what was signed.
33
+ */
34
+ export declare function hashDelegationCwd(targetPath: string): string;
35
+ /** The bindings packed into a delegation's `approvedBy` string. */
36
+ export interface DelegationApprovedByFields {
37
+ parentSessionId: string;
38
+ /** sha256 of the child's expected cwd, or `null` for a task-only delegation. */
39
+ cwdHash: string | null;
40
+ /** The task id the child is delegated for, or `null` for a cwd-only delegation. */
41
+ taskId: string | null;
42
+ /** ISO-8601 instant at which the delegation stops being valid. */
43
+ expiresAt: string;
44
+ /** sha256 of the launcher-supplied report file's PATH; present only in the fallback shape. */
45
+ reportPathHash?: string;
46
+ }
47
+ /**
48
+ * Build the `approvedBy` string a delegation signs:
49
+ * `delegated:<parent>;cwd=<sha256|->;task=<id|->;expires=<iso>` plus
50
+ * `;report=<sha256>` in the fallback shape.
51
+ *
52
+ * Throws on any input that would corrupt the encoding (an empty value, a
53
+ * value carrying a `;` or `=` delimiter or a control character, a
54
+ * malformed parent session id (`rejectMalformedSessionId`), a cwd/report
55
+ * hash that is not a sha256 digest, a non-ISO expiry, or the literal `-`
56
+ * as a task id, which would round-trip as "no task bound"). A silently
57
+ * mis-encoded delegation would be signed and then read back with
58
+ * different bindings than the caller intended, so this fails loudly at
59
+ * the only place that can still tell the difference.
60
+ */
61
+ export declare function buildDelegationApprovedBy(fields: DelegationApprovedByFields): string;
62
+ /** Bindings read back out of a delegation's `approvedBy` string. */
63
+ export interface ParsedDelegationApprovedBy {
64
+ parentSessionId: string;
65
+ /** `null` when the delegation binds no cwd (`cwd=-`). */
66
+ cwdHash: string | null;
67
+ /** `null` when the delegation binds no task (`task=-`). */
68
+ taskId: string | null;
69
+ expiresAt: string;
70
+ /** Present only in the fallback shape. */
71
+ reportPathHash?: string;
72
+ }
73
+ export type DelegationApprovedByParse = {
74
+ ok: true;
75
+ value: ParsedDelegationApprovedBy;
76
+ } | {
77
+ ok: false;
78
+ reason: string;
79
+ };
80
+ /**
81
+ * Strict inverse of {@link buildDelegationApprovedBy}. All four of
82
+ * `delegated`, `cwd`, `task` and `expires` are required and `report` is
83
+ * optional; a missing, duplicated, unknown, empty or malformed segment is
84
+ * an error RESULT, never a default. Segment order is not enforced (the
85
+ * signature already pins the exact bytes), but every other deviation is
86
+ * refused: this string is the only place a delegation's bindings live, so
87
+ * "read it partially and assume the rest" is the one failure mode that
88
+ * would quietly widen a delegation past what the parent signed.
89
+ */
90
+ export declare function parseDelegationApprovedBy(approvedBy: unknown): DelegationApprovedByParse;
91
+ export interface WriteDelegationMarkerOptions {
92
+ generatedDir: string;
93
+ /** Session id of the `claude -p` child this delegation authorizes. Becomes the file name. */
94
+ childSessionId: string;
95
+ /** Session id of the already-approved parent issuing the delegation. */
96
+ parentSessionId: string;
97
+ /** {@link hashDelegationCwd} of the child's expected cwd, or `null` for a task-only delegation. */
98
+ cwdHash: string | null;
99
+ /** Task id the child is delegated for, or `null` for a cwd-only delegation. */
100
+ taskId: string | null;
101
+ /** ISO-8601 instant the delegation expires at. */
102
+ expiresAt: string;
103
+ /** Fallback shape: {@link hashDelegationCwd} of the launcher-supplied report file's path. */
104
+ reportPathHash?: string;
105
+ /** Fallback shape: sha256 of that file's CONTENT. Omitted (written as `null`) in the base shape. */
106
+ reportContentHash?: string;
107
+ /** Override the issue timestamp for deterministic tests. */
108
+ now?: Date;
109
+ }
110
+ export type WriteDelegationMarkerResult = {
111
+ ok: true;
112
+ filePath: string;
113
+ markerId: string;
114
+ approvedAt: string;
115
+ approvedBy: string;
116
+ } | {
117
+ ok: false;
118
+ reason: "signing-key-absent" | "invalid-input" | "write-failed";
119
+ detail: string;
120
+ };
121
+ /**
122
+ * Write a signed delegation marker through the shared `signMarker` path,
123
+ * under markerId `delegation-<child-sid>`, at
124
+ * `<generatedDir>/.delegations/<child-sid>`. Atomic and mode 0600, like
125
+ * every other marker write.
126
+ *
127
+ * NEVER CREATES THE SIGNING KEY. `signMarker` -> `getOrCreateSigningKey`
128
+ * treats a missing key as a case to REPAIR, generating one and signing
129
+ * with it; key creation is an operator-side act (`harness init`,
130
+ * `harness approve`), and a delegation minted on a machine that never had
131
+ * a key would be a marker signed by whoever asked for it. So this
132
+ * prechecks `signingKeyExists` and returns `signing-key-absent` without
133
+ * reaching the write path at all (ADR threat model (b) item 5, the same
134
+ * rule slice 1's auto path follows).
135
+ *
136
+ * Returns a result rather than throwing, for every failure mode: the
137
+ * callers are a CLI verb and, later, a hook, and both must fail closed
138
+ * with a diagnostic instead of unwinding.
139
+ *
140
+ * Deliberately does NOT refuse a delegation that binds neither cwd nor
141
+ * task. That refusal belongs to the issuing verb (ADR slice 3 acceptance
142
+ * criterion 1) and to `verifyDelegation`, which reports `no_binding`;
143
+ * keeping the writer able to produce one is what lets the test suite
144
+ * exercise that verifier branch against a genuinely signed artifact
145
+ * rather than a hand-rolled fake.
146
+ */
147
+ export declare function writeDelegationMarker(opts: WriteDelegationMarkerOptions): WriteDelegationMarkerResult;
148
+ /**
149
+ * Why a delegation was refused. Every value is reachable and distinct;
150
+ * there is no "unknown" bucket and no branch that falls through to
151
+ * allow.
152
+ */
153
+ export type DelegationRefusalReason =
154
+ /** No delegation file for this child session (also: a child session id that cannot name a file). */
155
+ "missing"
156
+ /** The file exists but its integrity cannot be established right now: symlink, non-regular, I/O error, or an unavailable signing key. Not a claim of tampering. */
157
+ | "unreadable"
158
+ /** A file was there and its signature does not verify against `delegation-<child-sid>`: unsigned, wrong alg, tampered, or copied from another child's delegation. */
159
+ | "forged"
160
+ /** Validly signed, but its `approvedBy` bindings cannot be read in full. */
161
+ | "unparseable" | "expired" | "cwd_mismatch" | "task_mismatch"
162
+ /** Binds neither a cwd nor a task, so it would authorize the child anywhere, for anything. */
163
+ | "no_binding"
164
+ /** Fallback shape: the launcher report is not at the path the parent signed. */
165
+ | "report_path_mismatch"
166
+ /** Fallback shape: the launcher report's content is not what the parent signed (including a report that cannot be read). */
167
+ | "report_content_mismatch";
168
+ export type DelegationVerification = {
169
+ ok: true;
170
+ parentSessionId: string;
171
+ expiresAt: string;
172
+ boundCwdHash: string | null;
173
+ boundTaskId: string | null;
174
+ reportPathHash?: string;
175
+ } | {
176
+ ok: false;
177
+ reason: DelegationRefusalReason;
178
+ detail: string;
179
+ };
180
+ export interface VerifyDelegationOptions {
181
+ generatedDir: string;
182
+ /** The child session whose delegation is being checked. */
183
+ childSessionId: string;
184
+ /** The child's actual cwd, or `null` when the caller has none to offer. */
185
+ cwd: string | null;
186
+ /** The child's actual task id, or `null` when the caller has none to offer. */
187
+ taskId: string | null;
188
+ /** Fallback shape: the launcher-supplied report file the parent bound. */
189
+ launcherReportPath?: string;
190
+ /** Override "now" for deterministic tests. */
191
+ now?: Date;
192
+ }
193
+ /**
194
+ * Gate-side: is there a valid, unexpired, matching delegation for this
195
+ * child session? Checks, in order (ADR slice 3 acceptance criterion 2):
196
+ *
197
+ * 1. the file is present and JSON-readable,
198
+ * 2. its signature verifies against markerId `delegation-<child-sid>`,
199
+ * 3. its `approvedBy` segments parse in full,
200
+ * 4. it binds at least one of cwd / task,
201
+ * 5. it has not expired,
202
+ * 6. the bound cwd hash-matches the caller's cwd,
203
+ * 7. the bound task equals the caller's task,
204
+ * 8. in the fallback shape, the launcher report sits at the bound path
205
+ * AND hashes to the bound content.
206
+ *
207
+ * Reads only `.delegations/`; an artifact in `.approvals/` is `missing`
208
+ * here, whatever it contains.
209
+ *
210
+ * NEVER CREATES THE SIGNING KEY, on the READ path either.
211
+ * `verifyMarkerSignature` obtains the key through
212
+ * `getOrCreateSigningKey`, which treats a missing key as a case to
213
+ * REPAIR and generates one; on a machine the operator never initialized
214
+ * that would make a mere gate-time read perform the operator-side act of
215
+ * minting the key. It cannot make a foreign-signed delegation verify, but
216
+ * it does leave a key behind that every LATER write path would then
217
+ * happily sign with, so the never-create rule applies here exactly as it
218
+ * does to `writeDelegationMarker` and to slice 1's auto path. An absent
219
+ * key is reported as `unreadable` (we could not check, not "we checked
220
+ * and it is a forgery"), the same class `verifyMarkerSignature`'s own
221
+ * `key-unavailable` lands in below.
222
+ */
223
+ export declare function verifyDelegation(opts: VerifyDelegationOptions): DelegationVerification;