@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,328 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: authority module tests — delegation schema, loader
4
+ absence-tolerance/fail-closed parse, resolveDelegation matching matrix
5
+ (scope/site/agent/grantedBy/expiry/revocation), delegationActor wildcard
6
+ binding, signature round-trip, and the delegate/revoke command handlers.</purpose>
7
+ <non-goals>
8
+ <item>Not a contract source of truth — the module under test owns the authoritative behavior; fixtures are minimal scaffolding only.</item>
9
+ </non-goals>
10
+ </MODULE_CONTRACT>
11
+ <CHANGE_SUMMARY>
12
+ <item>RFC-1336: initial test suite.</item>
13
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
14
+ </CHANGE_SUMMARY>
15
+ */
16
+
17
+ import { test, expect, describe, beforeEach, afterEach } from "vitest";
18
+ import fs from "node:fs/promises";
19
+ import path from "node:path";
20
+ import os from "node:os";
21
+
22
+ import {
23
+ delegationActor,
24
+ delegationEntrySchema,
25
+ loadDelegations,
26
+ resolveDelegation,
27
+ type AuthorityDelegations,
28
+ type DelegationEntry,
29
+ } from "../../src/authority/delegations.ts";
30
+ import {
31
+ canonicalJson,
32
+ signDelegationPayload,
33
+ verifyDelegationSignature,
34
+ } from "../../src/authority/signing.ts";
35
+ import { runAuthorityDelegate } from "./handlers/delegate.ts";
36
+ import { runAuthorityDelegateRevoke } from "./handlers/delegate-revoke.ts";
37
+ import { runAuthorityDelegationValidate } from "./handlers/delegation-validate.ts";
38
+ import type { ForgeCommandInput, ForgeFlagValue, ForgeRuntimeContext } from "../../src/types.ts";
39
+
40
+ let tmpDir: string;
41
+ let sandboxDir: string;
42
+
43
+ const LOG = {
44
+ section: () => {},
45
+ info: () => {},
46
+ warn: () => {},
47
+ error: () => {},
48
+ success: () => {},
49
+ };
50
+
51
+ function cmd(flags: Record<string, ForgeFlagValue>): ForgeCommandInput {
52
+ return { argv: [], flags };
53
+ }
54
+
55
+ function ctx(extra?: Partial<ForgeRuntimeContext>): ForgeRuntimeContext {
56
+ return {
57
+ workspaceRoot: tmpDir,
58
+ logger: LOG,
59
+ dryRun: false,
60
+ outputFormat: "json",
61
+ ...extra,
62
+ };
63
+ }
64
+
65
+ function grant(partial: Partial<DelegationEntry> = {}): DelegationEntry {
66
+ return delegationEntrySchema.parse({
67
+ id: "del-0001",
68
+ scope: "editorial.signoff",
69
+ grantedTo: "agent:devin",
70
+ grantedBy: "human:andrii",
71
+ sites: ["acme"],
72
+ grantedAt: "2026-10-19T10:00:00.000Z",
73
+ ...partial,
74
+ });
75
+ }
76
+
77
+ function registry(entries: DelegationEntry[]): AuthorityDelegations {
78
+ return { schema: "forge/authority-delegations@1", delegations: entries };
79
+ }
80
+
81
+ beforeEach(async () => {
82
+ // systems-cache/<id> is a sibling of the workspace root (RFC-0790 layout).
83
+ sandboxDir = await fs.mkdtemp(path.join(os.tmpdir(), "authority-test-"));
84
+ tmpDir = path.join(sandboxDir, "workshop");
85
+ await fs.mkdir(tmpDir, { recursive: true });
86
+ await fs.mkdir(path.join(sandboxDir, "systems-cache", "acme"), { recursive: true });
87
+ });
88
+
89
+ afterEach(async () => {
90
+ await fs.rm(sandboxDir, { recursive: true, force: true });
91
+ });
92
+
93
+ describe("delegationEntrySchema", () => {
94
+ test("round-trips a full entry", () => {
95
+ const entry = grant({ note: "ship unattended", expiresAt: "2026-11-01T00:00:00.000Z" });
96
+ expect(entry.id).toBe("del-0001");
97
+ expect(entry.sites).toEqual(["acme"]);
98
+ });
99
+
100
+ test("rejects a human grantee — humans never need delegation", () => {
101
+ const result = delegationEntrySchema.safeParse({ ...grant(), grantedTo: "human:x" });
102
+ expect(result.success).toBe(false);
103
+ });
104
+
105
+ test("rejects a non-human grantor — provenance must name a human", () => {
106
+ const result = delegationEntrySchema.safeParse({ ...grant(), grantedBy: "agent:devin" });
107
+ expect(result.success).toBe(false);
108
+ });
109
+ });
110
+
111
+ describe("loadDelegations", () => {
112
+ test("absent registry resolves to zero delegations (RFC-1336 unchanged behavior)", async () => {
113
+ const r = await loadDelegations(tmpDir);
114
+ expect(r.delegations).toEqual([]);
115
+ });
116
+
117
+ test("corrupted registry throws — gates must never fail open", async () => {
118
+ await fs.writeFile(path.join(tmpDir, "authority.delegations.yaml"), "delegations: [unclosed\n");
119
+ await expect(loadDelegations(tmpDir)).rejects.toThrow(/authority\.delegations\.yaml/);
120
+ });
121
+ });
122
+
123
+ describe("resolveDelegation", () => {
124
+ const base = {
125
+ scope: "editorial.signoff",
126
+ agent: "agent:devin",
127
+ site: "acme",
128
+ };
129
+
130
+ test("matches an active grant", () => {
131
+ expect(resolveDelegation(registry([grant()]), base)?.id).toBe("del-0001");
132
+ });
133
+
134
+ test("no registry grant → null (the missing-delegation error path)", () => {
135
+ expect(resolveDelegation(registry([]), base)).toBeNull();
136
+ });
137
+
138
+ test("revoked grant does not match", () => {
139
+ const g = grant({ revokedAt: "2026-10-19T12:00:00.000Z" });
140
+ expect(resolveDelegation(registry([g]), base)).toBeNull();
141
+ });
142
+
143
+ test("expired grant does not match", () => {
144
+ const g = grant({ expiresAt: "2026-01-01T00:00:00.000Z" });
145
+ expect(resolveDelegation(registry([g]), base, new Date("2026-10-19"))).toBeNull();
146
+ });
147
+
148
+ test("wrong-site grant does not match a site query", () => {
149
+ const g = grant({ sites: ["other-site"] });
150
+ expect(resolveDelegation(registry([g]), base)).toBeNull();
151
+ });
152
+
153
+ test("workspace grant covers every site", () => {
154
+ const g = grant({ sites: "workspace" });
155
+ expect(resolveDelegation(registry([g]), { ...base, site: "anywhere" })?.id).toBe("del-0001");
156
+ });
157
+
158
+ test("site-listed grant does not cover a site-less workspace query", () => {
159
+ const g = grant({ sites: ["acme"] });
160
+ expect(resolveDelegation(registry([g]), { ...base, site: undefined })).toBeNull();
161
+ });
162
+
163
+ test("agent mismatch does not match; wildcard does", () => {
164
+ const specific = grant({ grantedTo: "agent:other" });
165
+ expect(resolveDelegation(registry([specific]), base)).toBeNull();
166
+ const wild = grant({ grantedTo: "agent:*" });
167
+ expect(resolveDelegation(registry([wild]), base)?.id).toBe("del-0001");
168
+ });
169
+
170
+ test("grantedBy binding rejects a grant from a different human (audit F2)", () => {
171
+ const g = grant({ grantedBy: "human:mallory" });
172
+ expect(resolveDelegation(registry([g]), { ...base, grantedBy: "human:andrii" })).toBeNull();
173
+ });
174
+
175
+ test("most recent matching grant wins", () => {
176
+ const older = grant({ id: "del-0001", grantedAt: "2026-10-01T00:00:00.000Z" });
177
+ const newer = grant({ id: "del-0002", grantedAt: "2026-10-15T00:00:00.000Z" });
178
+ expect(resolveDelegation(registry([older, newer]), base)?.id).toBe("del-0002");
179
+ });
180
+ });
181
+
182
+ describe("delegationActor", () => {
183
+ test("explicit grant names its actor", () => {
184
+ expect(delegationActor(grant())).toBe("agent:devin");
185
+ });
186
+
187
+ test("wildcard requires a session agent id", () => {
188
+ const wild = grant({ grantedTo: "agent:*" });
189
+ expect(delegationActor(wild, "agent:devin")).toBe("agent:devin");
190
+ expect(delegationActor(wild)).toBeNull();
191
+ expect(delegationActor(wild, "not-an-agent")).toBeNull();
192
+ });
193
+ });
194
+
195
+ describe("signing", () => {
196
+ const seed = "ab".repeat(32);
197
+
198
+ test("round-trips a signature over the canonical payload", () => {
199
+ const payload = canonicalJson({ scope: "x", id: "del-0001" });
200
+ const sig = `ed25519:${signDelegationPayload(seed, payload)}`;
201
+ expect(verifyDelegationSignature(sig, payload)).toBe(true);
202
+ expect(verifyDelegationSignature(sig, payload + "x")).toBe(false);
203
+ });
204
+ });
205
+
206
+ describe("authority.delegate", () => {
207
+ test("writes a site-scoped grant and serializes the registry", async () => {
208
+ const res = await runAuthorityDelegate(
209
+ cmd({
210
+ scope: "editorial.signoff",
211
+ to: "agent:devin",
212
+ by: "human:andrii",
213
+ site: ["acme"],
214
+ }),
215
+ ctx(),
216
+ );
217
+ expect(res.data?.delegation?.id).toBe("del-0001");
218
+ const reloaded = await loadDelegations(tmpDir);
219
+ expect(reloaded.delegations).toHaveLength(1);
220
+ expect(reloaded.delegations[0]?.grantedBy).toBe("human:andrii");
221
+ expect(res.data?.bordbuch?.skipped).toBe(true); // no kernel host in tests
222
+ });
223
+
224
+ test("absent --site means a workspace grant", async () => {
225
+ const res = await runAuthorityDelegate(
226
+ cmd({ scope: "rfc.decision", to: "agent:devin", by: "human:andrii" }),
227
+ ctx(),
228
+ );
229
+ expect(res.data?.delegation?.sites).toBe("workspace");
230
+ });
231
+
232
+ test("rejects a non-delegable scope before any write", async () => {
233
+ await expect(
234
+ runAuthorityDelegate(
235
+ cmd({ scope: "sternsystem.handover", to: "agent:devin", by: "human:andrii" }),
236
+ ctx(),
237
+ ),
238
+ ).rejects.toThrow(/non-delegable/);
239
+ expect((await loadDelegations(tmpDir)).delegations).toHaveLength(0);
240
+ });
241
+
242
+ test("rejects an unknown site", async () => {
243
+ await expect(
244
+ runAuthorityDelegate(
245
+ cmd({
246
+ scope: "editorial.signoff",
247
+ to: "agent:devin",
248
+ by: "human:andrii",
249
+ site: ["ghost"],
250
+ }),
251
+ ctx(),
252
+ ),
253
+ ).rejects.toThrow(/ghost/);
254
+ });
255
+
256
+ test("rejects a human grantee identity", async () => {
257
+ await expect(
258
+ runAuthorityDelegate(
259
+ cmd({ scope: "editorial.signoff", to: "human:andrii", by: "human:andrii" }),
260
+ ctx(),
261
+ ),
262
+ ).rejects.toThrow(/agent/);
263
+ });
264
+ });
265
+
266
+ describe("authority.delegate.revoke", () => {
267
+ test("revokes an active grant; a second run is an idempotent no-op", async () => {
268
+ await runAuthorityDelegate(
269
+ cmd({ scope: "version.major", to: "agent:devin", by: "human:andrii" }),
270
+ ctx(),
271
+ );
272
+ const res = await runAuthorityDelegateRevoke(
273
+ cmd({ id: "del-0001", by: "human:andrii" }),
274
+ ctx(),
275
+ );
276
+ expect(res.data?.revokedAt).toBeTruthy();
277
+ const reloaded = await loadDelegations(tmpDir);
278
+ expect(reloaded.delegations[0]?.revokedAt).toBeTruthy();
279
+ expect(reloaded.delegations[0]?.revokedBy).toBe("human:andrii");
280
+
281
+ const again = await runAuthorityDelegateRevoke(cmd({ id: "del-0001" }), ctx());
282
+ expect(again.data?.alreadyRevoked).toBe(true);
283
+ expect(again.exitCode).toBe(0);
284
+ });
285
+
286
+ test("revoking an unknown id fails", async () => {
287
+ await expect(runAuthorityDelegateRevoke(cmd({ id: "del-9999" }), ctx())).rejects.toThrow(
288
+ /del-9999/,
289
+ );
290
+ });
291
+ });
292
+
293
+ describe("authority.delegation.validate", () => {
294
+ test("absent registry passes clean", async () => {
295
+ const res = await runAuthorityDelegationValidate(cmd({}), ctx());
296
+ expect(res.data?.status).toBe("pass");
297
+ expect(res.exitCode).toBe(0);
298
+ });
299
+
300
+ test("agent:* wildcard warns (DELEG-06) without failing", async () => {
301
+ await runAuthorityDelegate(
302
+ cmd({ scope: "rfc.decision", to: "agent:*", by: "human:andrii" }),
303
+ ctx(),
304
+ );
305
+ const res = await runAuthorityDelegationValidate(cmd({}), ctx());
306
+ expect(res.data?.status).toBe("pass");
307
+ expect(res.data?.warnings.some((w) => w.ruleId === "DELEG-06")).toBe(true);
308
+ });
309
+
310
+ test("non-delegable scope in registry is DELEG-04", async () => {
311
+ await fs.writeFile(
312
+ path.join(tmpDir, "authority.delegations.yaml"),
313
+ [
314
+ "schema: forge/authority-delegations@1",
315
+ "delegations:",
316
+ " - id: del-0001",
317
+ " scope: sternsystem.handover",
318
+ " grantedTo: agent:devin",
319
+ " grantedBy: human:andrii",
320
+ " sites: workspace",
321
+ " grantedAt: '2026-10-19T10:00:00Z'",
322
+ ].join("\n"),
323
+ );
324
+ const res = await runAuthorityDelegationValidate(cmd({}), ctx());
325
+ expect(res.data?.status).toBe("fail");
326
+ expect(res.data?.errors.some((e) => e.ruleId === "DELEG-04")).toBe(true);
327
+ });
328
+ });
@@ -0,0 +1,123 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: authority.delegate.revoke — operator-only revocation.
4
+ Sets revokedAt (+ revokedBy when --by is given) on an existing entry and
5
+ fans out an authority-delegation-revoked Bordbuch event per covered site.
6
+ Re-running on an already-revoked id is a no-op exit-0 — revocation is
7
+ idempotent.</purpose>
8
+ <non-goals>
9
+ <item>Do not delete entries — the registry is append-only evidence; revocation is a state transition, not erasure.</item>
10
+ </non-goals>
11
+ </MODULE_CONTRACT>
12
+ <CHANGE_SUMMARY>
13
+ <item>RFC-1336: initial handler — revokedAt stamp + per-site Bordbuch fan-out.</item>
14
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
15
+ </CHANGE_SUMMARY>
16
+ */
17
+
18
+ import {
19
+ HUMAN_ID_PATTERN,
20
+ loadDelegations,
21
+ serializeDelegations,
22
+ delegationsPath,
23
+ } from "../../../src/authority/delegations.ts";
24
+ import type {
25
+ ForgeCommandInput,
26
+ ForgeCommandResult,
27
+ ForgeRuntimeContext,
28
+ } from "../../../src/types.ts";
29
+ import { resolveIo } from "../../../src/utils/io.ts";
30
+ import { appendAuthorityEvent, coveredSites, flagString } from "../helpers.ts";
31
+
32
+ export interface AuthorityDelegateRevokeResult {
33
+ command: "authority.delegate.revoke";
34
+ status: "pass" | "fail";
35
+ id: string;
36
+ revokedAt?: string;
37
+ alreadyRevoked?: boolean;
38
+ bordbuch?: { appended: string[]; skipped: boolean };
39
+ diagnostics: string[];
40
+ }
41
+
42
+ export async function runAuthorityDelegateRevoke(
43
+ input: ForgeCommandInput,
44
+ context: ForgeRuntimeContext,
45
+ ): Promise<ForgeCommandResult<AuthorityDelegateRevokeResult>> {
46
+ const { workspaceRoot, logger } = context;
47
+ const id = flagString(input, "id");
48
+ const by = flagString(input, "by");
49
+
50
+ if (!id) throw new Error("authority.delegate.revoke requires --id del-NNNN");
51
+ if (by !== undefined && !HUMAN_ID_PATTERN.test(by)) {
52
+ throw new Error(`--by must name the revoking human (human:<handle>) — got "${by}"`);
53
+ }
54
+
55
+ const registry = await loadDelegations(workspaceRoot, context.io);
56
+ const entry = registry.delegations.find((d) => d.id === id);
57
+ if (!entry) {
58
+ throw new Error(`no delegation "${id}" in the registry`);
59
+ }
60
+ if (entry.revokedAt) {
61
+ return {
62
+ data: {
63
+ command: "authority.delegate.revoke",
64
+ status: "pass",
65
+ id,
66
+ alreadyRevoked: true,
67
+ diagnostics: [`${id} was already revoked at ${entry.revokedAt}`],
68
+ },
69
+ summary: `[authority.delegate.revoke] ${id} already revoked at ${entry.revokedAt}`,
70
+ exitCode: 0,
71
+ };
72
+ }
73
+
74
+ entry.revokedAt = new Date().toISOString();
75
+ if (by !== undefined) entry.revokedBy = by;
76
+
77
+ if (context.dryRun) {
78
+ return {
79
+ data: {
80
+ command: "authority.delegate.revoke",
81
+ status: "pass",
82
+ id,
83
+ revokedAt: entry.revokedAt,
84
+ diagnostics: ["dry-run — registry unchanged"],
85
+ },
86
+ summary: `[authority.delegate.revoke] would revoke ${id}`,
87
+ exitCode: 0,
88
+ };
89
+ }
90
+
91
+ await resolveIo(context.io).writeFile(
92
+ delegationsPath(workspaceRoot),
93
+ serializeDelegations(registry),
94
+ );
95
+
96
+ const covered = await coveredSites(workspaceRoot, entry, context.io);
97
+ const bordbuch = await appendAuthorityEvent(context, {
98
+ kind: "authority-delegation-revoked",
99
+ sites: covered,
100
+ summary: `Delegation ${entry.id} revoked${by ? ` by ${by}` : ""} (${entry.scope} → ${entry.grantedTo})`,
101
+ actor: by ?? entry.grantedBy,
102
+ metadata: {
103
+ delegationId: entry.id,
104
+ scope: entry.scope,
105
+ grantedTo: entry.grantedTo,
106
+ ...(by !== undefined ? { revokedBy: by } : {}),
107
+ },
108
+ });
109
+
110
+ logger.success(`[authority.delegate.revoke] revoked ${id} (${entry.scope} → ${entry.grantedTo})`);
111
+ return {
112
+ data: {
113
+ command: "authority.delegate.revoke",
114
+ status: "pass",
115
+ id,
116
+ revokedAt: entry.revokedAt,
117
+ bordbuch,
118
+ diagnostics: [],
119
+ },
120
+ summary: `[authority.delegate.revoke] ${id} revoked at ${entry.revokedAt}`,
121
+ exitCode: 0,
122
+ };
123
+ }
@@ -0,0 +1,190 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: authority.delegate — operator-only grant path. Writes one
4
+ entry into the workspace-root authority.delegations.yaml registry and, when
5
+ running under a kernel host, fans out an authority-delegation Bordbuch event
6
+ to every covered site. Rejects non-delegable scopes, malformed actors,
7
+ unknown sites, and past expirations before any write.</purpose>
8
+ <non-goals>
9
+ <item>Do not decide who may run this command — the human-only rule is workspace policy (AGENTS.md), not a process check.</item>
10
+ </non-goals>
11
+ </MODULE_CONTRACT>
12
+ <KEY_DECISIONS>
13
+ <item>Registry write is the durable act; the Bordbuch event is audit evidence fanned out per site and never authoritative.</item>
14
+ <item>--site absent means a workspace grant; --site values must resolve to systems-cache siblings — a site that does not exist makes the grant meaningless.</item>
15
+ </KEY_DECISIONS>
16
+ <CHANGE_SUMMARY>
17
+ <item>RFC-1336: initial handler — grant append, site probe, optional --sign, per-site Bordbuch fan-out.</item>
18
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
19
+ </CHANGE_SUMMARY>
20
+ */
21
+
22
+ import {
23
+ AGENT_OR_WILDCARD_PATTERN,
24
+ DELEGABLE_SCOPES,
25
+ HUMAN_ID_PATTERN,
26
+ NON_DELEGABLE_SCOPES,
27
+ BORDBUCH_SCOPE_PREFIX,
28
+ isDelegableScope,
29
+ loadDelegations,
30
+ serializeDelegations,
31
+ delegationsPath,
32
+ canonicalDelegationPayload,
33
+ type DelegationEntry,
34
+ } from "../../../src/authority/delegations.ts";
35
+ import { signDelegationPayload } from "../../../src/authority/signing.ts";
36
+ import type {
37
+ ForgeCommandInput,
38
+ ForgeCommandResult,
39
+ ForgeRuntimeContext,
40
+ } from "../../../src/types.ts";
41
+ import {
42
+ appendAuthorityEvent,
43
+ coveredSites,
44
+ flagString,
45
+ flagStringList,
46
+ systemsCacheSiteExists,
47
+ } from "../helpers.ts";
48
+
49
+ export interface AuthorityDelegateResult {
50
+ command: "authority.delegate";
51
+ status: "pass" | "fail";
52
+ delegation?: DelegationEntry;
53
+ bordbuch?: { appended: string[]; skipped: boolean };
54
+ diagnostics: string[];
55
+ }
56
+
57
+ function nextDelegationId(entries: DelegationEntry[]): string {
58
+ const max = entries.reduce((acc, e) => {
59
+ const m = e.id.match(/^del-(\d{4,})$/);
60
+ return m ? Math.max(acc, parseInt(m[1], 10)) : acc;
61
+ }, 0);
62
+ return `del-${String(max + 1).padStart(4, "0")}`;
63
+ }
64
+
65
+ export async function runAuthorityDelegate(
66
+ input: ForgeCommandInput,
67
+ context: ForgeRuntimeContext,
68
+ ): Promise<ForgeCommandResult<AuthorityDelegateResult>> {
69
+ const { workspaceRoot, logger } = context;
70
+ const scope = flagString(input, "scope");
71
+ const to = flagString(input, "to");
72
+ const by = flagString(input, "by");
73
+ const sites = flagStringList(input, "site");
74
+ const expires = flagString(input, "expires");
75
+ const note = flagString(input, "note");
76
+ const sign = input.flags["sign"] === true || input.flags["sign"] === "true";
77
+
78
+ if (!scope) throw new Error("authority.delegate requires --scope <scope-id>");
79
+ if (!to) throw new Error("authority.delegate requires --to agent:<id>");
80
+ if (!by) throw new Error("authority.delegate requires --by human:<handle>");
81
+ if (!AGENT_OR_WILDCARD_PATTERN.test(to)) {
82
+ throw new Error(
83
+ `--to must name an agent identity (agent:<id>) or the agent:* wildcard — got "${to}". Agents may only act as themselves; human:<handle> grantees are not allowed.`,
84
+ );
85
+ }
86
+ if (!HUMAN_ID_PATTERN.test(by)) {
87
+ throw new Error(`--by must name the granting human (human:<handle>) — got "${by}"`);
88
+ }
89
+ if ((NON_DELEGABLE_SCOPES as readonly string[]).includes(scope)) {
90
+ throw new Error(
91
+ `scope "${scope}" is non-delegable (RFC-1336) — security-sensitive or irreversible flows stay human-only`,
92
+ );
93
+ }
94
+ if (!isDelegableScope(scope)) {
95
+ throw new Error(
96
+ `unknown scope "${scope}" — delegable scopes: ${[...DELEGABLE_SCOPES, `${BORDBUCH_SCOPE_PREFIX}<kind>`].join(", ")}`,
97
+ );
98
+ }
99
+ if (to === "agent:*") {
100
+ logger.warn(
101
+ " [authority] granting to the agent:* wildcard — any agent may claim this delegation; prefer an explicit agent:<id>",
102
+ );
103
+ }
104
+ if (expires !== undefined && Number.isNaN(Date.parse(expires))) {
105
+ throw new Error(`--expires must be an ISO-8601 datetime — got "${expires}"`);
106
+ }
107
+ if (expires !== undefined && new Date(expires).getTime() <= Date.now()) {
108
+ throw new Error(`--expires "${expires}" is already in the past — grant would be born dead`);
109
+ }
110
+
111
+ for (const siteId of sites) {
112
+ if (!(await systemsCacheSiteExists(workspaceRoot, siteId, context.io))) {
113
+ throw new Error(
114
+ `--site "${siteId}" does not resolve — no systems-cache/${siteId} sibling exists; site-scoped grants must name a real site`,
115
+ );
116
+ }
117
+ }
118
+
119
+ const registry = await loadDelegations(workspaceRoot, context.io);
120
+ const grantedAt = new Date().toISOString();
121
+ const entry: DelegationEntry = {
122
+ id: nextDelegationId(registry.delegations),
123
+ scope,
124
+ grantedTo: to,
125
+ grantedBy: by,
126
+ sites: sites.length === 0 ? "workspace" : sites,
127
+ grantedAt,
128
+ expiresAt: expires ?? null,
129
+ revokedAt: null,
130
+ ...(note !== undefined ? { note } : {}),
131
+ };
132
+
133
+ if (sign) {
134
+ const seed = process.env["SIGNING_PRIVATE_KEY"];
135
+ if (!seed || !/^[0-9a-fA-F]{64}$/.test(seed)) {
136
+ throw new Error(
137
+ "--sign requires SIGNING_PRIVATE_KEY (hex-encoded 32-byte Ed25519 seed) in the environment",
138
+ );
139
+ }
140
+ entry.signature = `ed25519:${signDelegationPayload(seed, canonicalDelegationPayload(entry))}`;
141
+ }
142
+
143
+ if (context.dryRun) {
144
+ return {
145
+ data: {
146
+ command: "authority.delegate",
147
+ status: "pass",
148
+ delegation: entry,
149
+ diagnostics: ["dry-run — registry unchanged"],
150
+ },
151
+ summary: `[authority.delegate] would grant ${entry.id} (${scope} → ${to})`,
152
+ exitCode: 0,
153
+ };
154
+ }
155
+
156
+ registry.delegations.push(entry);
157
+ const { resolveIo } = await import("../../../src/utils/io.ts");
158
+ await resolveIo(context.io).writeFile(
159
+ delegationsPath(workspaceRoot),
160
+ serializeDelegations(registry),
161
+ );
162
+
163
+ const covered = await coveredSites(workspaceRoot, entry, context.io);
164
+ const bordbuch = await appendAuthorityEvent(context, {
165
+ kind: "authority-delegation",
166
+ sites: covered,
167
+ summary: `Delegation ${entry.id}: ${scope} granted to ${to} by ${by}`,
168
+ actor: by,
169
+ metadata: {
170
+ delegationId: entry.id,
171
+ scope,
172
+ grantedTo: to,
173
+ expiresAt: entry.expiresAt ?? null,
174
+ ...(note !== undefined ? { note } : {}),
175
+ },
176
+ });
177
+
178
+ logger.success(`[authority.delegate] granted ${entry.id}: ${scope} → ${to}`);
179
+ return {
180
+ data: {
181
+ command: "authority.delegate",
182
+ status: "pass",
183
+ delegation: entry,
184
+ bordbuch,
185
+ diagnostics: [],
186
+ },
187
+ summary: `[authority.delegate] ${entry.id}: ${scope} → ${to} (by ${by}${expires ? `, expires ${expires}` : ""})`,
188
+ exitCode: 0,
189
+ };
190
+ }