@warpgogol/forge 8.0.2 → 8.0.4

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 (71) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/bin/cli.ts +3 -2
  3. package/dist/bin/cli.js +3 -2
  4. package/dist/bin/cli.js.map +1 -1
  5. package/dist/os/authority/authority.module.d.ts +3 -0
  6. package/dist/os/authority/authority.module.d.ts.map +1 -0
  7. package/dist/os/authority/authority.module.js +169 -0
  8. package/dist/os/authority/authority.module.js.map +1 -0
  9. package/dist/os/authority/handlers/delegate-revoke.d.ts +15 -0
  10. package/dist/os/authority/handlers/delegate-revoke.d.ts.map +1 -0
  11. package/dist/os/authority/handlers/delegate-revoke.js +91 -0
  12. package/dist/os/authority/handlers/delegate-revoke.js.map +1 -0
  13. package/dist/os/authority/handlers/delegate.d.ts +14 -0
  14. package/dist/os/authority/handlers/delegate.d.ts.map +1 -0
  15. package/dist/os/authority/handlers/delegate.js +134 -0
  16. package/dist/os/authority/handlers/delegate.js.map +1 -0
  17. package/dist/os/authority/handlers/delegation-list.d.ts +12 -0
  18. package/dist/os/authority/handlers/delegation-list.d.ts.map +1 -0
  19. package/dist/os/authority/handlers/delegation-list.js +54 -0
  20. package/dist/os/authority/handlers/delegation-list.js.map +1 -0
  21. package/dist/os/authority/handlers/delegation-validate.d.ts +11 -0
  22. package/dist/os/authority/handlers/delegation-validate.d.ts.map +1 -0
  23. package/dist/os/authority/handlers/delegation-validate.js +132 -0
  24. package/dist/os/authority/handlers/delegation-validate.js.map +1 -0
  25. package/dist/os/authority/helpers.d.ts +36 -0
  26. package/dist/os/authority/helpers.d.ts.map +1 -0
  27. package/dist/os/authority/helpers.js +83 -0
  28. package/dist/os/authority/helpers.js.map +1 -0
  29. package/dist/os/authority/index.d.ts +2 -0
  30. package/dist/os/authority/index.d.ts.map +1 -0
  31. package/dist/os/authority/index.js +14 -0
  32. package/dist/os/authority/index.js.map +1 -0
  33. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  34. package/dist/os/rfc/handlers/validate-rules.js +30 -1
  35. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  36. package/dist/os/rfc/types.d.ts +8 -0
  37. package/dist/os/rfc/types.d.ts.map +1 -1
  38. package/dist/os/rfc/types.js +2 -0
  39. package/dist/os/rfc/types.js.map +1 -1
  40. package/dist/os/session/handlers/save.d.ts.map +1 -1
  41. package/dist/os/session/handlers/save.js +41 -10
  42. package/dist/os/session/handlers/save.js.map +1 -1
  43. package/dist/src/authority/delegations.d.ts +108 -0
  44. package/dist/src/authority/delegations.d.ts.map +1 -0
  45. package/dist/src/authority/delegations.js +217 -0
  46. package/dist/src/authority/delegations.js.map +1 -0
  47. package/dist/src/authority/index.d.ts +3 -0
  48. package/dist/src/authority/index.d.ts.map +1 -0
  49. package/dist/src/authority/index.js +17 -0
  50. package/dist/src/authority/index.js.map +1 -0
  51. package/dist/src/authority/signing.d.ts +8 -0
  52. package/dist/src/authority/signing.d.ts.map +1 -0
  53. package/dist/src/authority/signing.js +72 -0
  54. package/dist/src/authority/signing.js.map +1 -0
  55. package/os/authority/authority.module.ts +183 -0
  56. package/os/authority/authority.test.ts +328 -0
  57. package/os/authority/handlers/delegate-revoke.ts +123 -0
  58. package/os/authority/handlers/delegate.ts +190 -0
  59. package/os/authority/handlers/delegation-list.ts +80 -0
  60. package/os/authority/handlers/delegation-validate.ts +231 -0
  61. package/os/authority/helpers.ts +111 -0
  62. package/os/authority/index.ts +14 -0
  63. package/os/rfc/handlers/validate-rules.ts +42 -6
  64. package/os/rfc/types.ts +10 -0
  65. package/os/session/handlers/save.ts +43 -9
  66. package/package.json +13 -1
  67. package/src/authority/delegations.ts +267 -0
  68. package/src/authority/index.ts +38 -0
  69. package/src/authority/signing.ts +73 -0
  70. package/src/tests/rfc-validate-delegation.test.ts +178 -0
  71. package/src/tests/session-handlers.test.ts +65 -0
@@ -0,0 +1,267 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: forge/authority-delegations@1 — the workspace-root
4
+ delegation registry schema plus the portable loader/resolver every
5
+ human-gated consumer shares. A delegation grants one declared agent
6
+ (grantedTo) the right to run one scope on behalf of a named human
7
+ (grantedBy), site-bounded, expirable, and revocable. The registry is
8
+ policy plus audit evidence — not a cryptographic security boundary.</purpose>
9
+ <non-goals>
10
+ <item>Do not import kernel/site/engine packages — forge stays runtime-autonomous (FORGE-AUTONOMY-01).</item>
11
+ <item>Do not police which process may invoke the mutating commands — the human-only rule on authority.delegate is workspace policy (AGENTS.md), not a check inside this module.</item>
12
+ </non-goals>
13
+ </MODULE_CONTRACT>
14
+ <KEY_DECISIONS>
15
+ <item>Registry absence is tolerance-neutral — ENOENT yields an empty registry; consumers treat "no file" and "no grant" identically (RFC-1336 unchanged-behavior rule).</item>
16
+ <item>DelegationQuery carries an optional grantedBy — consumers that already know the deciding human (e.g. bordbuch.append --delegated-by) bind the query to the grantor so delegatedBy provenance cannot be fabricated against a different human's grant.</item>
17
+ <item>sites: "workspace" covers every site; an explicit id list bounds site scope. Site-scoped queries with no site never match a site-listed grant.</item>
18
+ </KEY_DECISIONS>
19
+ <CHANGE_SUMMARY>
20
+ <item>RFC-1336: initial module — schema, scope catalog, loader, resolver, serializer.</item>
21
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
22
+ <item>RFC-1336: delegated editorial sign-off (RFC-1336 step 3)
23
+
24
+ editorial.review.signoff admits agent:<id> reviewers under an active
25
+ editorial.signoff delegation — the record and the editorial-signoff
26
+ bordbuch event carry delegatedBy + delegationId provenance; the sign-off
27
+ schema fails closed on agent reviewers without it. leitstand.ship gains
28
+ an editorial-delegated-signoff step between sync-after-alt and
29
+ certify-main that prepares the packet (if absent) and signs as the
30
+ delegate — a journaled no-op with no delegation, so the operator path is
31
+ unchanged. certify/promote precondition remediation now names an active
32
+ delegation when one covers the site.</item>
33
+ <item>RFC-1336: delegated rfc.decision/version.major/onboarding.decision + docs (RFC-1336 steps 4-5)</item>
34
+ </CHANGE_SUMMARY>
35
+ */
36
+
37
+ import path from "node:path";
38
+ import YAML from "yaml";
39
+ import { z } from "zod";
40
+
41
+ import type { WorkspaceIO } from "../types.ts";
42
+ import { resolveIo } from "../utils/io.ts";
43
+ import { canonicalJson } from "./signing.ts";
44
+
45
+ export const AUTHORITY_DELEGATIONS_SCHEMA_ID = "forge/authority-delegations@1";
46
+ export const DELEGATIONS_FILENAME = "authority.delegations.yaml";
47
+
48
+ export const AGENT_ID_PATTERN = /^agent:[a-z0-9][a-z0-9-]*$/;
49
+ export const AGENT_OR_WILDCARD_PATTERN = /^agent:([a-z0-9][a-z0-9-]*|\*)$/;
50
+ export const HUMAN_ID_PATTERN = /^human:[a-z0-9][a-z0-9-]*$/;
51
+
52
+ /**
53
+ * The delegable scope catalogue (RFC-1336). `bordbuch.<kind>` is a
54
+ * parameterized family — any concrete Bordbuch entry kind appends its own
55
+ * scope (`bordbuch.editorial-signoff`, `bordbuch.operator-note`, …).
56
+ */
57
+ export const DELEGABLE_SCOPES = [
58
+ "editorial.signoff",
59
+ "rfc.decision",
60
+ "version.major",
61
+ "onboarding.decision",
62
+ "fleet.notify",
63
+ ] as const;
64
+
65
+ export const BORDBUCH_SCOPE_PREFIX = "bordbuch.";
66
+
67
+ /**
68
+ * Scopes that MUST NOT be delegated (RFC-1336 non-goals): security-sensitive
69
+ * or irreversible flows stay human-only. Checked at grant write time and by
70
+ * authority.delegation.validate (DELEG-04).
71
+ */
72
+ export const NON_DELEGABLE_SCOPES = [
73
+ "sternsystem.handover",
74
+ "nachweis.sign",
75
+ "nachweis.timestamp",
76
+ "cloudflare.token",
77
+ "fleet.claims.merge",
78
+ ] as const;
79
+
80
+ const isoDatetime = z.string().refine((v) => !Number.isNaN(Date.parse(v)), {
81
+ message: "must be an ISO-8601 datetime",
82
+ });
83
+
84
+ export const delegationEntrySchema = z
85
+ .object({
86
+ id: z.string().regex(/^del-[0-9]{4,}$/),
87
+ scope: z.string().min(1),
88
+ grantedTo: z.string().regex(AGENT_OR_WILDCARD_PATTERN),
89
+ grantedBy: z.string().regex(HUMAN_ID_PATTERN),
90
+ sites: z.union([z.literal("workspace"), z.array(z.string().min(1)).min(1)]),
91
+ grantedAt: isoDatetime,
92
+ expiresAt: isoDatetime.nullish(),
93
+ revokedAt: isoDatetime.nullish(),
94
+ revokedBy: z.string().regex(HUMAN_ID_PATTERN).optional(),
95
+ note: z.string().optional(),
96
+ /** Optional `--sign` provenance: "ed25519:<publicKeyHex>:<signatureHex>". */
97
+ signature: z.string().optional(),
98
+ })
99
+ .strict();
100
+
101
+ export const authorityDelegationsSchema = z
102
+ .object({
103
+ schema: z.literal(AUTHORITY_DELEGATIONS_SCHEMA_ID),
104
+ delegations: z.array(delegationEntrySchema).default([]),
105
+ })
106
+ .strict();
107
+
108
+ export type DelegationEntry = z.infer<typeof delegationEntrySchema>;
109
+ export type AuthorityDelegations = z.infer<typeof authorityDelegationsSchema>;
110
+
111
+ export class DelegationRegistryError extends Error {
112
+ constructor(message: string) {
113
+ super(message);
114
+ this.name = "DelegationRegistryError";
115
+ }
116
+ }
117
+
118
+ export function delegationsPath(workspaceRoot: string): string {
119
+ return path.join(workspaceRoot, DELEGATIONS_FILENAME);
120
+ }
121
+
122
+ /** True when the scope string names a delegable scope (catalogue or bordbuch.*). */
123
+ export function isDelegableScope(scope: string): boolean {
124
+ return (
125
+ (DELEGABLE_SCOPES as readonly string[]).includes(scope) ||
126
+ scope.startsWith(BORDBUCH_SCOPE_PREFIX)
127
+ );
128
+ }
129
+
130
+ /**
131
+ * Load the delegation registry. An absent file means zero delegations (RFC-1336:
132
+ * the file is optional); parse/schema failures are load-bearing and throw
133
+ * DelegationRegistryError — a corrupted registry must never silently resolve
134
+ * to "no delegations" or every gate disarms.
135
+ */
136
+ export async function loadDelegations(
137
+ workspaceRoot: string,
138
+ io?: WorkspaceIO,
139
+ ): Promise<AuthorityDelegations> {
140
+ const effectiveIo = resolveIo(io);
141
+ const filePath = delegationsPath(workspaceRoot);
142
+ let source: string;
143
+ try {
144
+ source = await effectiveIo.readFile(filePath);
145
+ } catch (e) {
146
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") {
147
+ return { schema: AUTHORITY_DELEGATIONS_SCHEMA_ID, delegations: [] };
148
+ }
149
+ throw new DelegationRegistryError(
150
+ `cannot read ${DELEGATIONS_FILENAME}: ${e instanceof Error ? e.message : String(e)}`,
151
+ );
152
+ }
153
+ let raw: unknown;
154
+ try {
155
+ raw = YAML.parse(source);
156
+ } catch (e) {
157
+ throw new DelegationRegistryError(
158
+ `${DELEGATIONS_FILENAME} is not parseable YAML: ${e instanceof Error ? e.message : String(e)}`,
159
+ );
160
+ }
161
+ const parsed = authorityDelegationsSchema.safeParse(raw);
162
+ if (!parsed.success) {
163
+ const issues = parsed.error.issues
164
+ .map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`)
165
+ .join("; ");
166
+ throw new DelegationRegistryError(`${DELEGATIONS_FILENAME} schema violation — ${issues}`);
167
+ }
168
+ return parsed.data;
169
+ }
170
+
171
+ const REGISTRY_HEADER = `# Operator authority delegations (RFC-1336) — ${AUTHORITY_DELEGATIONS_SCHEMA_ID}
172
+ # Human-granted, scoped, revocable powers for agent delegates.
173
+ # Agents MUST NOT edit this file — grants and revocations go through
174
+ # authority.delegate / authority.delegate.revoke (operator-only).
175
+ `;
176
+
177
+ /** Serialize a registry for write-back — canonical header, stable key order. */
178
+ export function serializeDelegations(registry: AuthorityDelegations): string {
179
+ return REGISTRY_HEADER + YAML.stringify(registry);
180
+ }
181
+
182
+ /**
183
+ * The bytes a `--sign` signature covers: canonical JSON of the entry without
184
+ * its signature field (imported here so signers and verifiers share one
185
+ * canonicalization — signing.ts owns the crypto).
186
+ */
187
+ export function canonicalDelegationPayload(entry: DelegationEntry): string {
188
+ const { signature: _signature, ...rest } = entry;
189
+ return canonicalJson(rest);
190
+ }
191
+
192
+ /**
193
+ * Query a loaded registry for an active grant. A delegation is active when it
194
+ * is not revoked and not expired (expiresAt strictly in the future, or null).
195
+ * `grantedBy` binds the query to the grantor when the caller already knows
196
+ * which human must have authorized the act; `site` limits the match to grants
197
+ * covering that site (`sites: "workspace"` covers all). Multiple matches
198
+ * resolve to the most recently granted entry.
199
+ */
200
+ export interface DelegationQuery {
201
+ scope: string;
202
+ /**
203
+ * Acting agent identity — "agent:<id>". When omitted the query is an
204
+ * existence check: any active grant covering scope+site matches regardless
205
+ * of grantee (used by precondition helpers that only need to know a
206
+ * delegation exists).
207
+ */
208
+ agent?: string;
209
+ /** Site the operation targets; absent means a workspace-scope operation. */
210
+ site?: string;
211
+ /** When set, only grants recorded by this human match (grantor binding). */
212
+ grantedBy?: string;
213
+ }
214
+
215
+ export function resolveDelegation(
216
+ registry: AuthorityDelegations,
217
+ query: DelegationQuery,
218
+ now: Date = new Date(),
219
+ ): DelegationEntry | null {
220
+ const matches = registry.delegations.filter((d) => {
221
+ if (d.scope !== query.scope) return false;
222
+ if (d.revokedAt) return false;
223
+ if (d.expiresAt && new Date(d.expiresAt).getTime() <= now.getTime()) return false;
224
+ if (query.agent !== undefined && d.grantedTo !== query.agent && d.grantedTo !== "agent:*") {
225
+ return false;
226
+ }
227
+ if (query.grantedBy !== undefined && d.grantedBy !== query.grantedBy) return false;
228
+ if (d.sites === "workspace") return true;
229
+ return query.site !== undefined && d.sites.includes(query.site);
230
+ });
231
+ if (matches.length === 0) return null;
232
+ // Most specific grantee first (an explicit agent:<id> beats the wildcard),
233
+ // then most recently granted.
234
+ const specificity = (d: DelegationEntry) => (d.grantedTo === "agent:*" ? 0 : 1);
235
+ return matches.reduce((a, b) =>
236
+ specificity(a) !== specificity(b)
237
+ ? specificity(a) > specificity(b)
238
+ ? a
239
+ : b
240
+ : a.grantedAt >= b.grantedAt
241
+ ? a
242
+ : b,
243
+ );
244
+ }
245
+
246
+ /**
247
+ * The actor identity a delegated operation records. A grant to an explicit
248
+ * `agent:<id>` names its actor; a wildcard `agent:*` grant requires the caller
249
+ * to supply the session's agent id so provenance stays specific.
250
+ */
251
+ export function delegationActor(grant: DelegationEntry, sessionAgentId?: string): string | null {
252
+ if (grant.grantedTo !== "agent:*") return grant.grantedTo;
253
+ if (sessionAgentId && AGENT_ID_PATTERN.test(sessionAgentId)) return sessionAgentId;
254
+ return null;
255
+ }
256
+
257
+ /**
258
+ * Normalize a session-declared agent id — callers read WERKSTATT_AGENT_ID,
259
+ * which accepts both "devin" and "agent:devin". Anything else is not a
260
+ * usable actor id and returns undefined (callers fail closed).
261
+ */
262
+ export function normalizeAgentId(raw: string | undefined): string | undefined {
263
+ const trimmed = raw?.trim();
264
+ if (!trimmed) return undefined;
265
+ const id = trimmed.startsWith("agent:") ? trimmed : `agent:${trimmed}`;
266
+ return AGENT_ID_PATTERN.test(id) ? id : undefined;
267
+ }
@@ -0,0 +1,38 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: authority barrel — the consumer-facing surface of the
4
+ delegation model (schema, loader, resolver, scope catalogue). Werkstatt
5
+ engine/site consumers import from @warpgogol/forge/authority.</purpose>
6
+ <non-goals>
7
+ <item>Do not re-export signing internals — signature verification is a validator concern (verifyDelegationSignature is importable from ./signing.ts for tests).</item>
8
+ </non-goals>
9
+ </MODULE_CONTRACT>
10
+ <CHANGE_SUMMARY>
11
+ <item>RFC-1336: initial barrel.</item>
12
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
13
+ <item>RFC-1336: delegated rfc.decision/version.major/onboarding.decision + docs (RFC-1336 steps 4-5)</item>
14
+ </CHANGE_SUMMARY>
15
+ */
16
+
17
+ export {
18
+ AGENT_ID_PATTERN,
19
+ AGENT_OR_WILDCARD_PATTERN,
20
+ AUTHORITY_DELEGATIONS_SCHEMA_ID,
21
+ BORDBUCH_SCOPE_PREFIX,
22
+ DELEGABLE_SCOPES,
23
+ DELEGATIONS_FILENAME,
24
+ DelegationRegistryError,
25
+ HUMAN_ID_PATTERN,
26
+ NON_DELEGABLE_SCOPES,
27
+ authorityDelegationsSchema,
28
+ canonicalDelegationPayload,
29
+ delegationActor,
30
+ delegationEntrySchema,
31
+ delegationsPath,
32
+ isDelegableScope,
33
+ loadDelegations,
34
+ normalizeAgentId,
35
+ resolveDelegation,
36
+ serializeDelegations,
37
+ } from "./delegations.ts";
38
+ export type { AuthorityDelegations, DelegationEntry, DelegationQuery } from "./delegations.ts";
@@ -0,0 +1,73 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: optional Ed25519 provenance signatures on delegation
4
+ entries (`authority.delegate --sign`). Signs the canonical JSON of the
5
+ entry under SIGNING_PRIVATE_KEY (hex-encoded 32-byte seed — the same
6
+ convention as werkstatt-shared/signing) and stores
7
+ "ed25519:<publicKeyHex>:<signatureHex>". Implemented on node:crypto —
8
+ forge carries no @noble dependency (FORGE-AUTONOMY-01).</purpose>
9
+ <non-goals>
10
+ <item>Does not turn the registry into a security boundary — the signature is provenance evidence; the entry's authority still flows from declared policy.</item>
11
+ </non-goals>
12
+ </MODULE_CONTRACT>
13
+ <CHANGE_SUMMARY>
14
+ <item>RFC-1336: initial module — seed→PKCS8 reconstruction, canonical JSON, sign/verify.</item>
15
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
16
+ </CHANGE_SUMMARY>
17
+ */
18
+
19
+ import { createPrivateKey, createPublicKey, sign, verify } from "node:crypto";
20
+
21
+ /** PKCS8 DER prefix wrapping a raw 32-byte Ed25519 seed. */
22
+ const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
23
+ /** SPKI DER prefix wrapping a raw 32-byte Ed25519 public key. */
24
+ const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
25
+
26
+ /** Deterministic sorted-key serialization — the signature's signed payload. */
27
+ export function canonicalJson(value: unknown): string {
28
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
29
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
30
+ const entries = Object.entries(value as Record<string, unknown>)
31
+ .filter(([, v]) => v !== undefined)
32
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
33
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`);
34
+ return `{${entries.join(",")}}`;
35
+ }
36
+
37
+ export function publicKeyHexFromSeed(privateKeyHex: string): string {
38
+ const key = createPrivateKey({
39
+ key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(privateKeyHex, "hex")]),
40
+ format: "der",
41
+ type: "pkcs8",
42
+ });
43
+ const jwk = createPublicKey(key).export({ format: "jwk" }) as { x: string };
44
+ return Buffer.from(jwk.x, "base64url").toString("hex");
45
+ }
46
+
47
+ /** Sign a payload with a hex-encoded Ed25519 seed; returns "<pubHex>:<sigHex>". */
48
+ export function signDelegationPayload(privateKeyHex: string, payload: string): string {
49
+ const key = createPrivateKey({
50
+ key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(privateKeyHex, "hex")]),
51
+ format: "der",
52
+ type: "pkcs8",
53
+ });
54
+ const signature = sign(null, Buffer.from(payload, "utf8"), key);
55
+ return `${publicKeyHexFromSeed(privateKeyHex)}:${signature.toString("hex")}`;
56
+ }
57
+
58
+ /** Verify a "ed25519:<pubHex>:<sigHex>"-shaped signature against a payload. */
59
+ export function verifyDelegationSignature(signature: string, payload: string): boolean {
60
+ const bare = signature.startsWith("ed25519:") ? signature.slice("ed25519:".length) : signature;
61
+ const [pubHex, sigHex] = bare.split(":");
62
+ if (!pubHex || !sigHex || pubHex.length !== 64 || sigHex.length !== 128) return false;
63
+ try {
64
+ const key = createPublicKey({
65
+ key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(pubHex, "hex")]),
66
+ format: "der",
67
+ type: "spki",
68
+ });
69
+ return verify(null, Buffer.from(payload, "utf8"), key, Buffer.from(sigHex, "hex"));
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
@@ -0,0 +1,178 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ RFC-1336: V-25 delegation coverage — an agent:&lt;id&gt; reviewer on a decided
5
+ RFC is valid iff frontmatter decidedBy names the granting human AND an active
6
+ rfc.decision delegation covers the agent under that grantor
7
+ (authority.delegations.yaml). Human reviewers and the no-delegation path are
8
+ unchanged.
9
+ </purpose>
10
+ <non-goals>
11
+ <item>Not a contract source of truth — the module under test owns the authoritative behavior; fixtures are minimal scaffolding only.</item>
12
+ </non-goals>
13
+ </MODULE_CONTRACT>
14
+ <CHANGE_SUMMARY>
15
+ <item>RFC-1336: initial test — V-25 delegated reviewer verdicts over tmp registries.</item>
16
+ <item>RFC-1336: delegated rfc.decision/version.major/onboarding.decision + docs (RFC-1336 steps 4-5)</item>
17
+ </CHANGE_SUMMARY>
18
+ */
19
+
20
+ import { test, expect, describe, beforeEach, afterEach } from "vitest";
21
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import { tmpdir } from "node:os";
24
+ import { validateSingleRfc, type AddViolationFn } from "../../os/rfc/handlers/validate-rules.ts";
25
+ import type { ParsedRfc } from "../../os/rfc/frontmatter-io.ts";
26
+
27
+ let workspace: string;
28
+
29
+ beforeEach(() => {
30
+ workspace = mkdtempSync(join(tmpdir(), "v25-deleg-"));
31
+ });
32
+
33
+ afterEach(() => {
34
+ rmSync(workspace, { recursive: true, force: true });
35
+ });
36
+
37
+ const BODY = `
38
+ # RFC-9999: Test RFC
39
+
40
+ ## Context
41
+
42
+ x
43
+
44
+ ## Problem
45
+
46
+ x
47
+
48
+ ## Decision
49
+
50
+ x
51
+
52
+ ## Architectural fit
53
+
54
+ x
55
+
56
+ ## Design
57
+
58
+ x
59
+
60
+ ## Rollout
61
+
62
+ x
63
+
64
+ ## Alternatives considered
65
+
66
+ x
67
+
68
+ ## Risks
69
+
70
+ x
71
+
72
+ ## Acceptance criteria
73
+
74
+ x
75
+
76
+ ## Implementation notes for agents
77
+
78
+ x
79
+ `;
80
+
81
+ function makeParsed(extraFm: Record<string, unknown> = {}): ParsedRfc {
82
+ return {
83
+ frontmatter: {
84
+ id: "RFC-9999",
85
+ title: "Test RFC",
86
+ status: "accepted",
87
+ kind: "command",
88
+ scope: "workspace",
89
+ owners: ["architecture"],
90
+ createdAt: "2026-10-19",
91
+ updatedAt: "2026-10-19",
92
+ ...extraFm,
93
+ },
94
+ body: BODY,
95
+ };
96
+ }
97
+
98
+ function writeRegistry(yaml: string): void {
99
+ writeFileSync(join(workspace, "authority.delegations.yaml"), yaml);
100
+ }
101
+
102
+ const GRANTOR = "human:andrii-syrokomskyi";
103
+
104
+ function delegationRegistry(grantedTo: string, grantedBy = GRANTOR): string {
105
+ return `schema: forge/authority-delegations@1
106
+ delegations:
107
+ - id: del-0050
108
+ scope: rfc.decision
109
+ grantedTo: ${grantedTo}
110
+ grantedBy: ${grantedBy}
111
+ grantedAt: "2026-10-19T10:00:00.000Z"
112
+ sites: workspace
113
+ `;
114
+ }
115
+
116
+ async function runValidate(
117
+ parsed: ParsedRfc,
118
+ ): Promise<{ rfcId: string; rule: string; message: string; severity: string }[]> {
119
+ const violations: { rfcId: string; rule: string; message: string; severity: string }[] = [];
120
+ const add: AddViolationFn = (rfcId, _file, rule, message, severity = "error") => {
121
+ violations.push({ rfcId, rule, message, severity });
122
+ };
123
+ await validateSingleRfc(
124
+ "rfc-9999-test.md",
125
+ parsed,
126
+ new Map(),
127
+ new Map(),
128
+ new Set(),
129
+ new Set(),
130
+ new Set(Object.keys(parsed.frontmatter)),
131
+ workspace,
132
+ add,
133
+ );
134
+ return violations.filter((v) => v.rule === "V-25");
135
+ }
136
+
137
+ describe("V-25 delegated reviewers (RFC-1336)", () => {
138
+ test("human reviewer — unchanged, no V-25", async () => {
139
+ const v = await runValidate(makeParsed({ reviewers: ["human:andrii"] }));
140
+ expect(v).toHaveLength(0);
141
+ });
142
+
143
+ test("agent reviewer without decidedBy — V-25 (legacy rule intact)", async () => {
144
+ const v = await runValidate(makeParsed({ reviewers: ["agent:devin"] }));
145
+ expect(v).toHaveLength(1);
146
+ expect(v[0].message).toContain("decidedBy");
147
+ });
148
+
149
+ test("agent reviewer + decidedBy, no registry — V-25", async () => {
150
+ const v = await runValidate(makeParsed({ reviewers: ["agent:devin"], decidedBy: GRANTOR }));
151
+ expect(v).toHaveLength(1);
152
+ expect(v[0].message).toContain("rfc.decision delegation");
153
+ });
154
+
155
+ test("agent reviewer + decidedBy + active delegation — no V-25", async () => {
156
+ writeRegistry(delegationRegistry("agent:devin"));
157
+ const v = await runValidate(makeParsed({ reviewers: ["agent:devin"], decidedBy: GRANTOR }));
158
+ expect(v).toHaveLength(0);
159
+ });
160
+
161
+ test("delegation granted by a different human than decidedBy — V-25 (grantor binding)", async () => {
162
+ writeRegistry(delegationRegistry("agent:devin", "human:someone-else"));
163
+ const v = await runValidate(makeParsed({ reviewers: ["agent:devin"], decidedBy: GRANTOR }));
164
+ expect(v).toHaveLength(1);
165
+ });
166
+
167
+ test("delegation to a different agent does not cover this reviewer", async () => {
168
+ writeRegistry(delegationRegistry("agent:cursor"));
169
+ const v = await runValidate(makeParsed({ reviewers: ["agent:devin"], decidedBy: GRANTOR }));
170
+ expect(v).toHaveLength(1);
171
+ });
172
+
173
+ test("wildcard delegation covers a named agent", async () => {
174
+ writeRegistry(delegationRegistry("agent:*"));
175
+ const v = await runValidate(makeParsed({ reviewers: ["agent:devin"], decidedBy: GRANTOR }));
176
+ expect(v).toHaveLength(0);
177
+ });
178
+ });
@@ -14,6 +14,7 @@ Unit tests for session handlers covering session.save; session.archive; session.
14
14
 
15
15
  import { test, expect, describe, beforeAll, afterAll } from "vitest";
16
16
  import { join } from "node:path";
17
+ import { execFileSync } from "node:child_process";
17
18
  import { mkdtemp, rm, mkdir, writeFile, readFile, readdir } from "node:fs/promises";
18
19
  import { tmpdir } from "node:os";
19
20
  import type { ForgeCommandInput, ForgeRuntimeContext, ForgeFlagValue } from "../../src/types.ts";
@@ -175,6 +176,70 @@ Commands: session.save`;
175
176
  await expect(readFile(rawPath, "utf-8")).rejects.toThrow();
176
177
  });
177
178
 
179
+ test("metadata extraction verifies commit hex against git and strips path punctuation", async () => {
180
+ const gitDir = await makeTempDir();
181
+ try {
182
+ await mkdir(join(gitDir, "docs/sessions/.raw"), { recursive: true });
183
+ execFileSync("git", ["init", "--initial-branch=main"], { cwd: gitDir, stdio: "pipe" });
184
+ execFileSync("git", ["config", "user.email", "forge@warpgogol.dev"], {
185
+ cwd: gitDir,
186
+ stdio: "pipe",
187
+ });
188
+ execFileSync("git", ["config", "user.name", "Forge Test"], { cwd: gitDir, stdio: "pipe" });
189
+ await writeFile(join(gitDir, "seed.txt"), "seed", "utf-8");
190
+ execFileSync("git", ["add", "seed.txt"], { cwd: gitDir, stdio: "pipe" });
191
+ execFileSync("git", ["commit", "-m", "seed"], { cwd: gitDir, stdio: "pipe" });
192
+ const realSha = execFileSync("git", ["rev-parse", "--short", "HEAD"], {
193
+ cwd: gitDir,
194
+ encoding: "utf8",
195
+ }).trim();
196
+
197
+ // Defect fixtures from the personal-agent handoff: 82b439b9808e is an
198
+ // approvals.id (random 12-hex), not a git object; path tokens carry
199
+ // trailing `:` / `,` from enumerated assistant prose.
200
+ const atif = `2026-10-19T09:30:00+02:00
201
+ User: approved request 82b439b9808e — update packages/agent/data/agent.db:
202
+ Assistant: Done in ${realSha}. Touched docs/audits/, docs/plans/plan-*.md:, docs/reviews/code/packages-agent/, packages/agent/deploy/personal-agent.service, and packages/agent/data/agent.db.
203
+ Commit: ${realSha}`;
204
+ await writeFile(join(gitDir, "docs/sessions/.raw", "extract-regression.atif"), atif, "utf-8");
205
+
206
+ const result = await runSessionSave(makeInput(), makeContext(gitDir));
207
+ const data = result.data as SessionSaveResult;
208
+
209
+ expect(data.extractedMetadata.commits).toContain(realSha);
210
+ expect(data.extractedMetadata.commits).not.toContain("82b439b9808e");
211
+
212
+ const { files, relatedArtifacts } = data.extractedMetadata;
213
+ expect(files).toContain("packages/agent/data/agent.db");
214
+ expect(files).toContain("docs/plans/plan-*.md");
215
+ expect(files).toContain("packages/agent/deploy/personal-agent.service");
216
+ for (const token of [...files, ...relatedArtifacts]) {
217
+ expect(token).not.toMatch(/[.,;:!?()\[\]{}]$/);
218
+ }
219
+ } finally {
220
+ await rm(gitDir, { recursive: true, force: true });
221
+ }
222
+ });
223
+
224
+ test("drops unverifiable commit hex in a non-git workspace (no repo to verify against)", async () => {
225
+ const noGitDir = await makeTempDir();
226
+ try {
227
+ await mkdir(join(noGitDir, "docs/sessions/.raw"), { recursive: true });
228
+ const atif = `2026-10-19T10:00:00+02:00
229
+ User: update the approval 82b439b9808e
230
+ Assistant: done
231
+ Commit: a3f2c1d`;
232
+ await writeFile(join(noGitDir, "docs/sessions/.raw", "nogit.atif"), atif, "utf-8");
233
+
234
+ const result = await runSessionSave(makeInput(), makeContext(noGitDir));
235
+ const data = result.data as SessionSaveResult;
236
+ expect(data.id).not.toBe("");
237
+ expect(data.extractedMetadata.commits).toEqual([]);
238
+ } finally {
239
+ await rm(noGitDir, { recursive: true, force: true });
240
+ }
241
+ });
242
+
178
243
  test("no raw files — exit zero with summary", async () => {
179
244
  const emptyDir = await makeTempDir();
180
245
  try {