@gtrabanco/agentic-workflow 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,570 @@
1
+ // Path-protection policy model, parsers, evaluator, and closed vocabularies.
2
+ //
3
+ // Single source of truth for the shipped default protected-path policy, the
4
+ // plan-declaration grammar, the escape-record grammar, and the deterministic
5
+ // evaluation the Tier 1 gate (`bin/path-guard.mjs`) consumes. Node standard
6
+ // library only, zero dependencies, read-only: nothing here writes.
7
+ //
8
+ // The three surfaces of the same policy are the crate module (canonical, this
9
+ // file), the template install seed (`template/.agentic-workflow/path-policy.json`,
10
+ // parity-pinned by the P2 done-when command) and the pi package mirror
11
+ // (parity-pinned by the pi suite). E-60-1.
12
+
13
+ export const PATH_POLICY_SCHEMA = "path-protection-policy@1";
14
+ export const PLAN_DECLARATION_SCHEMA = "path-protection-plan@1";
15
+ export const RECORDS_SCHEMA = "path-protection-records@1";
16
+
17
+ /** Requirement order: `none < justification < approval`. */
18
+ export const REQUIREMENTS = Object.freeze(["none", "justification", "approval"]);
19
+ export const OPERATIONS = Object.freeze(["create", "modify", "delete", "rename"]);
20
+ export const PHASE_STATES = Object.freeze(["pre-freeze", "post-freeze", "always"]);
21
+ export const DECLARATION_KINDS = Object.freeze(["created", "not-created", "ignored"]);
22
+ export const RECORD_KINDS = Object.freeze(["justification", "approval"]);
23
+
24
+ /** A project policy over this bound is `malformed-config` with the defaults in force. */
25
+ export const PATH_POLICY_MAX_BYTES = 256 * 1024;
26
+ /**
27
+ * A glob over this bound is refused by the policy reader. The memoised matcher
28
+ * is O(glob × path), so an unbounded glob accepted here could exhaust memory on
29
+ * the first match (F29); the bound keeps the accepted policy inside a small,
30
+ * predictable matcher footprint.
31
+ */
32
+ export const PATH_GLOB_MAX_LENGTH = 512;
33
+ /** A changed-path list over this bound is a usage error (exit 2), never a silent truncation. */
34
+ export const CHANGED_PATH_LIMIT = 10000;
35
+
36
+ /**
37
+ * The closed reason vocabulary. Adding a reason is a SPEC change, never a code
38
+ * path. Exported as a frozen literal array so the drift gate can read it via
39
+ * its `schema-export:` surface (published by the `path-protection-reasons`
40
+ * normative row).
41
+ */
42
+ export const PATH_GUARD_REASONS = Object.freeze([
43
+ "clean",
44
+ "justified",
45
+ "approved",
46
+ "protected-modification",
47
+ "approval-required",
48
+ "undeclared-test",
49
+ "unmatched-record",
50
+ "malformed-declaration",
51
+ "missing-config",
52
+ "malformed-config",
53
+ ]);
54
+
55
+ /** The published degradation codes a gate run may report. */
56
+ export const DEGRADATION_CODES = Object.freeze([
57
+ "missing-config",
58
+ "malformed-config",
59
+ "ignored-removal",
60
+ "ignored-lowering",
61
+ ]);
62
+
63
+ const DECLARATION_HEADER = ["kind", "path", "justification"];
64
+ const RECORDS_HEADER = ["kind", "paths", "phase", "date", "authority", "justification"];
65
+
66
+ const CLASS_NAMES = Object.freeze(["tests", "e2e", "test-file", "fixtures", "policy-config"]);
67
+
68
+ function defaultClasses() {
69
+ return {
70
+ tests: { globs: ["tests/**"], freeze: true },
71
+ e2e: { globs: ["e2e/**"], freeze: true },
72
+ "test-file": { globs: ["**/*.test.*"], freeze: true },
73
+ fixtures: { globs: ["fixtures/**", "**/fixtures/**"], freeze: true },
74
+ "policy-config": { globs: [".agentic-workflow/path-policy.json"], freeze: false },
75
+ };
76
+ }
77
+
78
+ /** The shipped-default policy: five classes, the three-row matrix (D4, AC-01). */
79
+ export const SHIPPED_PATH_POLICY = Object.freeze({
80
+ schema: PATH_POLICY_SCHEMA,
81
+ classes: Object.freeze(
82
+ Object.fromEntries(
83
+ Object.entries(defaultClasses()).map(([name, def]) => [
84
+ name,
85
+ Object.freeze({ globs: Object.freeze([...def.globs]), freeze: def.freeze }),
86
+ ]),
87
+ ),
88
+ ),
89
+ matrix: Object.freeze({
90
+ "pre-freeze": Object.freeze({
91
+ create: "none",
92
+ modify: "justification",
93
+ delete: "justification",
94
+ rename: "justification",
95
+ }),
96
+ "post-freeze": Object.freeze({
97
+ create: "justification",
98
+ modify: "approval",
99
+ delete: "approval",
100
+ rename: "approval",
101
+ }),
102
+ always: Object.freeze({
103
+ create: "approval",
104
+ modify: "approval",
105
+ delete: "approval",
106
+ rename: "approval",
107
+ }),
108
+ }),
109
+ });
110
+
111
+ /** Canonical seed serialization; P2 diffs the template seed against this byte-for-byte. */
112
+ export function serializeShippedPolicy() {
113
+ return `${JSON.stringify(SHIPPED_PATH_POLICY, null, 2)}\n`;
114
+ }
115
+
116
+ /* ------------------------------------------------------------------ helpers */
117
+
118
+ function isRecord(value) {
119
+ return typeof value === "object" && value !== null && !Array.isArray(value);
120
+ }
121
+
122
+ function rank(requirement) {
123
+ return REQUIREMENTS.indexOf(requirement);
124
+ }
125
+
126
+ /** Convert a glob to an anchored regexp. `**` crosses `/`, `*`/`?` do not. */
127
+ export function globToRegExp(glob) {
128
+ let out = "";
129
+ for (let index = 0; index < glob.length; index += 1) {
130
+ const char = glob[index];
131
+ if (char === "*") {
132
+ if (glob[index + 1] === "*") {
133
+ index += 1;
134
+ if (glob[index + 1] === "/") {
135
+ index += 1;
136
+ out += "(?:.*/)?";
137
+ } else {
138
+ out += ".*";
139
+ }
140
+ } else {
141
+ out += "[^/]*";
142
+ }
143
+ } else if (char === "?") {
144
+ out += "[^/]";
145
+ } else {
146
+ out += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
147
+ }
148
+ }
149
+ return new RegExp(`^${out}$`);
150
+ }
151
+
152
+ /**
153
+ * Linear-time glob match with the same semantics as `globToRegExp` (`**` crosses
154
+ * `/`; `*` and `?` do not). Memoised so a star-chain glob cannot trigger the
155
+ * catastrophic backtracking the RegExp form suffers (F20).
156
+ */
157
+ export function matchGlob(glob, target) {
158
+ const glen = glob.length;
159
+ const plen = target.length;
160
+ const memo = new Int8Array((glen + 1) * (plen + 1)).fill(-1);
161
+ const at = (gi, pi) => {
162
+ if (gi === glen) return pi === plen;
163
+ const key = gi * (plen + 1) + pi;
164
+ const cached = memo[key];
165
+ if (cached !== -1) return cached === 1;
166
+ let result = false;
167
+ const char = glob[gi];
168
+ if (char === "?") {
169
+ result = pi < plen && target[pi] !== "/" && at(gi + 1, pi + 1);
170
+ } else if (char === "*") {
171
+ if (glob[gi + 1] === "*") {
172
+ const after = gi + 2;
173
+ if (glob[after] === "/") {
174
+ // `**/` matches zero or more characters ending in `/`.
175
+ result = at(after + 1, pi);
176
+ for (let index = pi; index < plen && !result; index += 1) {
177
+ if (target[index] === "/") result = at(after + 1, index + 1);
178
+ }
179
+ } else {
180
+ // `**` matches any sequence, crossing `/`.
181
+ result = at(after, pi);
182
+ for (let index = pi; index < plen && !result; index += 1) {
183
+ result = at(after, index + 1);
184
+ }
185
+ }
186
+ } else {
187
+ // `*` matches any sequence within a path segment.
188
+ result = at(gi + 1, pi);
189
+ for (let index = pi; index < plen && !result && target[index] !== "/"; index += 1) {
190
+ result = at(gi + 1, index + 1);
191
+ }
192
+ }
193
+ } else {
194
+ result = pi < plen && target[pi] === char && at(gi + 1, pi + 1);
195
+ }
196
+ memo[key] = result ? 1 : 0;
197
+ return result;
198
+ };
199
+ return at(0, 0);
200
+ }
201
+
202
+ export function pathMatchesGlob(path, glob) {
203
+ return matchGlob(glob, path);
204
+ }
205
+
206
+ export function pathMatchesAny(path, globs) {
207
+ return globs.some((glob) => pathMatchesGlob(path, glob));
208
+ }
209
+
210
+ function failPolicy(message) {
211
+ return { ok: false, code: "malformed-config", message };
212
+ }
213
+
214
+ function failDeclaration(message) {
215
+ return { ok: false, code: "malformed-declaration", message };
216
+ }
217
+
218
+ const PHASE_RE = /^P(\d+)$/;
219
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
220
+
221
+ /* ------------------------------------------------------------- policy parse */
222
+
223
+ /**
224
+ * Validate one `path-protection-policy@1` JSON document. The reader fails
225
+ * closed: unknown keys, a wrong schema, a missing class/state/operation, an
226
+ * invalid glob, or an out-of-vocabulary requirement is a refusal.
227
+ */
228
+ export function parsePathPolicy(text) {
229
+ if (typeof text !== "string") return failPolicy("policy text must be a string");
230
+ if (text.length > PATH_POLICY_MAX_BYTES) return failPolicy(`policy exceeds the ${PATH_POLICY_MAX_BYTES}-byte bound`);
231
+ let value;
232
+ try {
233
+ value = JSON.parse(text);
234
+ } catch (error) {
235
+ return failPolicy(`invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
236
+ }
237
+ return validatePathPolicy(value);
238
+ }
239
+
240
+ function validatePathPolicy(value) {
241
+ if (!isRecord(value)) return failPolicy("policy root must be a JSON object");
242
+ for (const key of Object.keys(value)) {
243
+ if (key !== "schema" && key !== "classes" && key !== "matrix") {
244
+ return failPolicy(`unknown policy key "${key}"`);
245
+ }
246
+ }
247
+ if (value.schema !== PATH_POLICY_SCHEMA) return failPolicy(`schema must be "${PATH_POLICY_SCHEMA}"`);
248
+ if (!isRecord(value.classes)) return failPolicy("classes must be an object");
249
+ if (!isRecord(value.matrix)) return failPolicy("matrix must be an object");
250
+
251
+ const classNames = Object.keys(value.classes);
252
+ for (const name of CLASS_NAMES) {
253
+ if (!classNames.includes(name)) return failPolicy(`classes is missing "${name}"`);
254
+ }
255
+ for (const name of classNames) {
256
+ if (!CLASS_NAMES.includes(name)) return failPolicy(`unknown class "${name}"`);
257
+ }
258
+ const classes = {};
259
+ for (const name of CLASS_NAMES) {
260
+ const raw = value.classes[name];
261
+ if (!isRecord(raw)) return failPolicy(`class "${name}" must be an object`);
262
+ if (!Array.isArray(raw.globs)) return failPolicy(`class "${name}" globs must be an array`);
263
+ for (const glob of raw.globs) {
264
+ if (typeof glob !== "string" || glob.trim() === "") return failPolicy(`class "${name}" has an invalid glob`);
265
+ if (glob.length > PATH_GLOB_MAX_LENGTH) {
266
+ return failPolicy(`class "${name}" has a glob over the ${PATH_GLOB_MAX_LENGTH}-character bound`);
267
+ }
268
+ }
269
+ if (typeof raw.freeze !== "boolean") return failPolicy(`class "${name}" freeze must be a boolean`);
270
+ classes[name] = { globs: [...raw.globs], freeze: raw.freeze };
271
+ }
272
+
273
+ const states = Object.keys(value.matrix);
274
+ for (const state of PHASE_STATES) {
275
+ if (!states.includes(state)) return failPolicy(`matrix is missing "${state}"`);
276
+ }
277
+ for (const state of states) {
278
+ if (!PHASE_STATES.includes(state)) return failPolicy(`unknown matrix state "${state}"`);
279
+ }
280
+ const matrix = {};
281
+ for (const state of PHASE_STATES) {
282
+ const row = value.matrix[state];
283
+ if (!isRecord(row)) return failPolicy(`matrix "${state}" must be an object`);
284
+ const ops = Object.keys(row);
285
+ for (const op of OPERATIONS) {
286
+ if (!ops.includes(op)) return failPolicy(`matrix "${state}" is missing "${op}"`);
287
+ }
288
+ for (const op of ops) {
289
+ if (!OPERATIONS.includes(op)) return failPolicy(`matrix "${state}" has unknown operation "${op}"`);
290
+ }
291
+ matrix[state] = {};
292
+ for (const op of OPERATIONS) {
293
+ const requirement = row[op];
294
+ if (!REQUIREMENTS.includes(requirement)) {
295
+ return failPolicy(`matrix "${state}.${op}" must be one of ${REQUIREMENTS.join(", ")}`);
296
+ }
297
+ matrix[state][op] = requirement;
298
+ }
299
+ }
300
+
301
+ return { ok: true, policy: { schema: PATH_POLICY_SCHEMA, classes, matrix } };
302
+ }
303
+
304
+ /**
305
+ * Tighten-only resolution: globs union, requirements maximum, freeze never
306
+ * lowered. Every ignored removal/lowering appends one degradation record; the
307
+ * shipped protection always stays in force.
308
+ */
309
+ export function resolvePathPolicy(shipped = SHIPPED_PATH_POLICY, override = null) {
310
+ const degradations = [];
311
+ const classes = {};
312
+
313
+ const names = [...new Set([...Object.keys(shipped.classes), ...Object.keys(override?.classes ?? {})])];
314
+ for (const name of names) {
315
+ const base = shipped.classes[name];
316
+ const own = override?.classes?.[name];
317
+ if (base === undefined) {
318
+ classes[name] = { globs: [...own.globs], freeze: own.freeze };
319
+ continue;
320
+ }
321
+ if (own === undefined) {
322
+ classes[name] = { globs: [...base.globs], freeze: base.freeze };
323
+ continue;
324
+ }
325
+ const globs = [...base.globs];
326
+ for (const glob of own.globs) if (!globs.includes(glob)) globs.push(glob);
327
+ for (const glob of base.globs) {
328
+ if (!own.globs.includes(glob)) {
329
+ degradations.push({ code: "ignored-removal", detail: `class "${name}" omitted the shipped glob "${glob}"; kept` });
330
+ }
331
+ }
332
+ let freeze = base.freeze;
333
+ if (base.freeze === true && own.freeze === false) {
334
+ degradations.push({ code: "ignored-lowering", detail: `class "${name}" lowered freeze; kept true` });
335
+ freeze = true;
336
+ } else if (base.freeze === false && own.freeze === true) {
337
+ freeze = true;
338
+ }
339
+ classes[name] = { globs, freeze };
340
+ }
341
+
342
+ const matrix = {};
343
+ for (const state of PHASE_STATES) {
344
+ matrix[state] = {};
345
+ for (const op of OPERATIONS) {
346
+ const base = shipped.matrix?.[state]?.[op] ?? "none";
347
+ const own = override?.matrix?.[state]?.[op];
348
+ if (own === undefined) {
349
+ matrix[state][op] = base;
350
+ } else if (rank(own) < rank(base)) {
351
+ degradations.push({
352
+ code: "ignored-lowering",
353
+ detail: `matrix "${state}.${op}" lowered to "${own}"; kept "${base}"`,
354
+ });
355
+ matrix[state][op] = base;
356
+ } else {
357
+ matrix[state][op] = own;
358
+ }
359
+ }
360
+ }
361
+
362
+ return { schema: PATH_POLICY_SCHEMA, classes, matrix, degradations };
363
+ }
364
+
365
+ /* -------------------------------------------------------- block extraction */
366
+
367
+ /**
368
+ * The lines of the first fenced block carrying `marker`, without the marker
369
+ * line and without blank lines. `null` when the marker is absent.
370
+ */
371
+ export function extractFencedBlock(text, marker) {
372
+ const lines = String(text).split(/\r?\n/);
373
+ const start = lines.findIndex((line) => line.trim() === marker);
374
+ if (start === -1) return null;
375
+ const body = [];
376
+ for (let index = start + 1; index < lines.length; index += 1) {
377
+ const trimmed = lines[index].trim();
378
+ if (trimmed.startsWith("```")) break;
379
+ if (trimmed !== "") body.push(trimmed);
380
+ }
381
+ return body;
382
+ }
383
+
384
+ function splitRow(line) {
385
+ return line.split("|").map((cell) => cell.trim());
386
+ }
387
+
388
+ /* --------------------------------------------------------- plan declaration */
389
+
390
+ /**
391
+ * Parse the `path-protection-plan@1` block: the `freeze-after` line plus
392
+ * `created` / `not-created` / `ignored` rows, each with a non-empty
393
+ * justification. Anything malformed fails closed with `malformed-declaration`.
394
+ */
395
+ export function parsePlanDeclaration(text) {
396
+ const body = extractFencedBlock(text, PLAN_DECLARATION_SCHEMA);
397
+ if (body === null) return failDeclaration("the plan declaration block is missing");
398
+
399
+ let freezeAfter;
400
+ let headerSeen = false;
401
+ const rows = [];
402
+ for (const line of body) {
403
+ if (line.startsWith("freeze-after:")) {
404
+ const value = line.slice("freeze-after:".length).trim();
405
+ if (value !== "none" && !PHASE_RE.test(value)) {
406
+ return failDeclaration(`freeze-after must be "none" or P<n>, got "${value}"`);
407
+ }
408
+ freezeAfter = value === "none" ? null : value;
409
+ continue;
410
+ }
411
+ if (line === DECLARATION_HEADER.join(" | ")) {
412
+ headerSeen = true;
413
+ continue;
414
+ }
415
+ if (!headerSeen) continue;
416
+ const cells = splitRow(line);
417
+ if (cells.length !== 3) return failDeclaration(`declaration row needs 3 cells, got ${cells.length}`);
418
+ const [kind, path, justification] = cells;
419
+ if (!DECLARATION_KINDS.includes(kind)) return failDeclaration(`unknown declaration kind "${kind}"`);
420
+ if (path === "") return failDeclaration("declaration row has an empty path");
421
+ if (justification === "") return failDeclaration("declaration row has an empty justification");
422
+ rows.push({ kind, path, justification });
423
+ }
424
+
425
+ if (freezeAfter === undefined) return failDeclaration("the plan declaration is missing the freeze-after line");
426
+ if (!headerSeen) return failDeclaration("the plan declaration is missing its kind | path | justification header");
427
+ return { ok: true, declaration: { freezeAfter, rows } };
428
+ }
429
+
430
+ /* ----------------------------------------------------------- escape records */
431
+
432
+ /**
433
+ * Parse the `path-protection-records@1` block: append-only `justification` /
434
+ * `approval` rows. Authority is validated against the kind, so no auto-approval
435
+ * authority can be written.
436
+ */
437
+ export function parseRecords(text) {
438
+ const body = extractFencedBlock(text, RECORDS_SCHEMA);
439
+ if (body === null) return { ok: true, records: [] };
440
+
441
+ let headerSeen = false;
442
+ const records = [];
443
+ for (const line of body) {
444
+ if (line === RECORDS_HEADER.join(" | ")) {
445
+ headerSeen = true;
446
+ continue;
447
+ }
448
+ if (!headerSeen) continue;
449
+ const cells = splitRow(line);
450
+ if (cells.length !== 6) return failDeclaration(`record row needs 6 cells, got ${cells.length}`);
451
+ const [kind, pathsCell, phase, date, authority, justification] = cells;
452
+ if (!RECORD_KINDS.includes(kind)) return failDeclaration(`unknown record kind "${kind}"`);
453
+ const paths = pathsCell.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
454
+ if (paths.length === 0) return failDeclaration("record row has no paths");
455
+ if (!PHASE_RE.test(phase)) return failDeclaration(`record phase must be P<n>, got "${phase}"`);
456
+ if (!DATE_RE.test(date)) return failDeclaration(`record date must be YYYY-MM-DD, got "${date}"`);
457
+ const expected = kind === "justification" ? "execute-phase" : "human-owner";
458
+ if (authority !== expected) return failDeclaration(`a "${kind}" row must have authority "${expected}", got "${authority}"`);
459
+ if (justification === "") return failDeclaration("record row has an empty justification");
460
+ records.push({ kind, paths, phase, date, authority, justification });
461
+ }
462
+
463
+ if (!headerSeen) return failDeclaration("the record block is missing its header row");
464
+ return { ok: true, records };
465
+ }
466
+
467
+ /* --------------------------------------------------------------- evaluation */
468
+
469
+ function phaseOrdinal(phase) {
470
+ const match = PHASE_RE.exec(phase ?? "");
471
+ return match === null ? null : Number.parseInt(match[1], 10);
472
+ }
473
+
474
+ /** `pre-freeze` up to and including `freeze-after`; `post-freeze` after it. */
475
+ export function freezeStateFor(phase, freezeAfter) {
476
+ if (freezeAfter === null || freezeAfter === undefined) return "pre-freeze";
477
+ const current = phaseOrdinal(phase);
478
+ const boundary = phaseOrdinal(freezeAfter);
479
+ if (current === null || boundary === null) return "pre-freeze";
480
+ return current <= boundary ? "pre-freeze" : "post-freeze";
481
+ }
482
+
483
+ function declaredCreated(declaration, path) {
484
+ return declaration.rows.some((row) => row.kind === "created" && pathMatchesGlob(path, row.path));
485
+ }
486
+
487
+ function recordMatches(record, path) {
488
+ return record.paths.some((glob) => pathMatchesGlob(path, glob));
489
+ }
490
+
491
+ const FAIL_PRECEDENCE = ["malformed-declaration", "unmatched-record", "undeclared-test", "approval-required", "protected-modification"];
492
+
493
+ function pickReason(offenders) {
494
+ let best = FAIL_PRECEDENCE.length - 1;
495
+ for (const offender of offenders) {
496
+ const at = FAIL_PRECEDENCE.indexOf(offender.reason);
497
+ if (at !== -1 && at < best) best = at;
498
+ }
499
+ return FAIL_PRECEDENCE[best];
500
+ }
501
+
502
+ /**
503
+ * Evaluate every `(path, operation)` pair against the effective policy. Returns
504
+ * `{ verdict, reason, offenders }` with `reason` always from `PATH_GUARD_REASONS`.
505
+ */
506
+ export function evaluatePathGuard({ changes = [], policy = null, declaration = null, records = [], phase = "" }) {
507
+ const effective = policy ?? resolvePathPolicy(SHIPPED_PATH_POLICY, null);
508
+ if (declaration === null || declaration === undefined) {
509
+ return { verdict: "fail", reason: "malformed-declaration", offenders: [] };
510
+ }
511
+
512
+ const state = freezeStateFor(phase, declaration.freezeAfter ?? null);
513
+ const phaseRecords = records.filter((record) => record.phase === phase);
514
+ const offenders = [];
515
+
516
+ let sawProtected = false;
517
+ let maxRequirement = "none";
518
+
519
+ for (const change of changes) {
520
+ const { path, operation } = change;
521
+ const requirements = [];
522
+ let freezeEligible = false;
523
+ for (const name of Object.keys(effective.classes)) {
524
+ const cls = effective.classes[name];
525
+ if (!pathMatchesAny(path, cls.globs)) continue;
526
+ const classState = cls.freeze ? state : "always";
527
+ requirements.push(effective.matrix[classState]?.[operation] ?? "none");
528
+ if (cls.freeze) freezeEligible = true;
529
+ }
530
+ if (requirements.length === 0) continue;
531
+
532
+ sawProtected = true;
533
+ const requirement = requirements.reduce((best, current) => (rank(current) > rank(best) ? current : best));
534
+ if (rank(requirement) > rank(maxRequirement)) maxRequirement = requirement;
535
+
536
+ if (freezeEligible && operation === "create" && !declaredCreated(declaration, path)) {
537
+ offenders.push({ path, operation, reason: "undeclared-test" });
538
+ continue;
539
+ }
540
+ if (requirement === "none") continue;
541
+
542
+ const hasJustification = phaseRecords.some(
543
+ (record) => record.kind === "justification" && recordMatches(record, path),
544
+ );
545
+ const hasApproval = phaseRecords.some((record) => record.kind === "approval" && recordMatches(record, path));
546
+
547
+ if (requirement === "justification") {
548
+ if (!hasJustification) offenders.push({ path, operation, reason: "protected-modification" });
549
+ } else if (requirement === "approval") {
550
+ if (!hasJustification) offenders.push({ path, operation, reason: "protected-modification" });
551
+ else if (!hasApproval) offenders.push({ path, operation, reason: "approval-required" });
552
+ }
553
+ }
554
+
555
+ for (const record of phaseRecords) {
556
+ const matched = changes.some((change) => recordMatches(record, change.path));
557
+ if (!matched) {
558
+ offenders.push({ path: record.paths.join(","), operation: "record", reason: "unmatched-record" });
559
+ }
560
+ }
561
+
562
+ if (offenders.length > 0) {
563
+ return { verdict: "fail", reason: pickReason(offenders), offenders };
564
+ }
565
+
566
+ let reason = "clean";
567
+ if (sawProtected && maxRequirement === "approval") reason = "approved";
568
+ else if (sawProtected && maxRequirement === "justification") reason = "justified";
569
+ return { verdict: "pass", reason, offenders: [] };
570
+ }