@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,80 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: authority.delegation.list — read-only registry listing.
4
+ Defaults to active grants; --history includes revoked and expired entries.
5
+ --site filters to grants covering one site.</purpose>
6
+ <non-goals>
7
+ <item>Do not evaluate whether a grant authorizes a specific act — resolveDelegation does that; this reports registry content.</item>
8
+ </non-goals>
9
+ </MODULE_CONTRACT>
10
+ <CHANGE_SUMMARY>
11
+ <item>RFC-1336: initial handler — active-only default, --history flag, --site filter.</item>
12
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
13
+ </CHANGE_SUMMARY>
14
+ */
15
+
16
+ import { loadDelegations, type DelegationEntry } from "../../../src/authority/delegations.ts";
17
+ import type {
18
+ ForgeCommandInput,
19
+ ForgeCommandResult,
20
+ ForgeRuntimeContext,
21
+ } from "../../../src/types.ts";
22
+ import { flagString } from "../helpers.ts";
23
+
24
+ export interface AuthorityDelegationListResult {
25
+ command: "authority.delegation.list";
26
+ status: "pass" | "fail";
27
+ total: number;
28
+ shown: number;
29
+ delegations: DelegationEntry[];
30
+ diagnostics: string[];
31
+ }
32
+
33
+ export async function runAuthorityDelegationList(
34
+ input: ForgeCommandInput,
35
+ context: ForgeRuntimeContext,
36
+ ): Promise<ForgeCommandResult<AuthorityDelegationListResult>> {
37
+ const { workspaceRoot, logger, outputFormat } = context;
38
+ const site = flagString(input, "site");
39
+ const history = input.flags["history"] === true || input.flags["history"] === "true";
40
+
41
+ const registry = await loadDelegations(workspaceRoot, context.io);
42
+ const now = new Date();
43
+ const isActive = (d: DelegationEntry) =>
44
+ !d.revokedAt && (!d.expiresAt || new Date(d.expiresAt).getTime() > now.getTime());
45
+ const coversSite = (d: DelegationEntry) =>
46
+ site === undefined || d.sites === "workspace" || d.sites.includes(site);
47
+
48
+ const shown = registry.delegations.filter((d) => (history || isActive(d)) && coversSite(d));
49
+
50
+ if (outputFormat === "pretty") {
51
+ logger.section("Authority delegations");
52
+ if (shown.length === 0) {
53
+ logger.info(" (none)");
54
+ }
55
+ for (const d of shown) {
56
+ const state = d.revokedAt
57
+ ? `revoked ${d.revokedAt}`
58
+ : d.expiresAt && new Date(d.expiresAt).getTime() <= now.getTime()
59
+ ? `expired ${d.expiresAt}`
60
+ : "active";
61
+ const sites = d.sites === "workspace" ? "workspace" : d.sites.join(",");
62
+ logger.info(
63
+ ` ${d.id} ${d.scope} → ${d.grantedTo} by ${d.grantedBy} [${sites}] ${state}`,
64
+ );
65
+ }
66
+ }
67
+
68
+ return {
69
+ data: {
70
+ command: "authority.delegation.list",
71
+ status: "pass",
72
+ total: registry.delegations.length,
73
+ shown: shown.length,
74
+ delegations: shown,
75
+ diagnostics: [],
76
+ },
77
+ summary: `${shown.length}/${registry.delegations.length} delegation(s)${history ? "" : " active"}`,
78
+ exitCode: 0,
79
+ };
80
+ }
@@ -0,0 +1,231 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: authority.delegation.validate — the registry's validator
4
+ (DNA-91 contract authority, rules DELEG-01..08). Absent registry is a clean
5
+ pass; schema violations and non-delegable scopes block; agent:* wildcards,
6
+ unknown sites, unknown scopes, and bad signatures warn.</purpose>
7
+ <non-goals>
8
+ <item>Do not mutate the registry — read-only validator.</item>
9
+ </non-goals>
10
+ </MODULE_CONTRACT>
11
+ <CHANGE_SUMMARY>
12
+ <item>RFC-1336: initial handler — DELEG-01..08.</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 YAML from "yaml";
18
+
19
+ import {
20
+ DELEGATIONS_FILENAME,
21
+ NON_DELEGABLE_SCOPES,
22
+ authorityDelegationsSchema,
23
+ canonicalDelegationPayload,
24
+ delegationsPath,
25
+ isDelegableScope,
26
+ } from "../../../src/authority/delegations.ts";
27
+ import { verifyDelegationSignature } from "../../../src/authority/signing.ts";
28
+ import type {
29
+ Diagnostic,
30
+ ForgeCommandInput,
31
+ ForgeCommandResult,
32
+ ForgeRuntimeContext,
33
+ } from "../../../src/types.ts";
34
+ import { resolveIo } from "../../../src/utils/io.ts";
35
+ import { flagString, systemsCacheSiteExists } from "../helpers.ts";
36
+
37
+ export interface AuthorityDelegationValidateResult {
38
+ command: "authority.delegation.validate";
39
+ status: "pass" | "fail";
40
+ file: string;
41
+ delegations: number;
42
+ errors: Diagnostic[];
43
+ warnings: Diagnostic[];
44
+ }
45
+
46
+ function diag(
47
+ ruleId: string,
48
+ severity: "error" | "warning",
49
+ message: string,
50
+ file?: string,
51
+ ): Diagnostic {
52
+ return { ruleId, severity, message, file };
53
+ }
54
+
55
+ export async function runAuthorityDelegationValidate(
56
+ input: ForgeCommandInput,
57
+ context: ForgeRuntimeContext,
58
+ ): Promise<ForgeCommandResult<AuthorityDelegationValidateResult>> {
59
+ const { workspaceRoot, logger, outputFormat } = context;
60
+ const siteFilter = flagString(input, "site");
61
+ const errors: Diagnostic[] = [];
62
+ const warnings: Diagnostic[] = [];
63
+ const io = resolveIo(context.io);
64
+ const filePath = delegationsPath(workspaceRoot);
65
+
66
+ // DELEG-01: absent registry is legal (zero delegations); unreadable or
67
+ // unparseable registry is a blocking load failure — never fail open.
68
+ let raw: unknown;
69
+ try {
70
+ raw = YAML.parse(await io.readFile(filePath));
71
+ } catch (e) {
72
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") {
73
+ return {
74
+ data: {
75
+ command: "authority.delegation.validate",
76
+ status: "pass",
77
+ file: DELEGATIONS_FILENAME,
78
+ delegations: 0,
79
+ errors,
80
+ warnings,
81
+ },
82
+ summary: "no delegation registry — zero delegations",
83
+ exitCode: 0,
84
+ };
85
+ }
86
+ errors.push(
87
+ diag(
88
+ "DELEG-01",
89
+ "error",
90
+ `cannot read/parse ${DELEGATIONS_FILENAME}: ${e instanceof Error ? e.message : String(e)}`,
91
+ DELEGATIONS_FILENAME,
92
+ ),
93
+ );
94
+ return { data: resultData(errors, warnings, 0), summary: "registry unreadable", exitCode: 1 };
95
+ }
96
+
97
+ // DELEG-02: schema violations.
98
+ const parsed = authorityDelegationsSchema.safeParse(raw);
99
+ const entries = parsed.success
100
+ ? parsed.data.delegations
101
+ : Array.isArray((raw as { delegations?: unknown[] })?.delegations)
102
+ ? ((raw as { delegations: unknown[] }).delegations.filter(
103
+ (d): d is Record<string, unknown> => typeof d === "object" && d !== null,
104
+ ) as never[])
105
+ : [];
106
+ if (!parsed.success) {
107
+ for (const issue of parsed.error.issues) {
108
+ errors.push(
109
+ diag(
110
+ "DELEG-02",
111
+ "error",
112
+ `schema violation at ${issue.path.join(".") || "<root>"}: ${issue.message}`,
113
+ DELEGATIONS_FILENAME,
114
+ ),
115
+ );
116
+ }
117
+ }
118
+
119
+ // Semantic checks run over whatever parsed — per-entry diagnostics.
120
+ const seen = new Set<string>();
121
+ const now = Date.now();
122
+ for (const d of entries) {
123
+ const id = typeof d.id === "string" ? d.id : "<unknown>";
124
+ if (seen.has(id)) {
125
+ errors.push(
126
+ diag("DELEG-03", "error", `duplicate delegation id "${id}"`, DELEGATIONS_FILENAME),
127
+ );
128
+ }
129
+ seen.add(id);
130
+
131
+ const scope = typeof d.scope === "string" ? d.scope : "";
132
+ if ((NON_DELEGABLE_SCOPES as readonly string[]).includes(scope)) {
133
+ errors.push(
134
+ diag(
135
+ "DELEG-04",
136
+ "error",
137
+ `"${id}" delegates non-delegable scope "${scope}" (RFC-1336: human-only)`,
138
+ DELEGATIONS_FILENAME,
139
+ ),
140
+ );
141
+ } else if (scope && !isDelegableScope(scope)) {
142
+ warnings.push(
143
+ diag(
144
+ "DELEG-05",
145
+ "warning",
146
+ `"${id}" uses unknown scope "${scope}" — not in the RFC-1336 catalogue`,
147
+ DELEGATIONS_FILENAME,
148
+ ),
149
+ );
150
+ }
151
+
152
+ if (d.grantedTo === "agent:*") {
153
+ warnings.push(
154
+ diag(
155
+ "DELEG-06",
156
+ "warning",
157
+ `"${id}" grants the agent:* wildcard — prefer an explicit agent:<id>`,
158
+ DELEGATIONS_FILENAME,
159
+ ),
160
+ );
161
+ }
162
+
163
+ if (Array.isArray(d.sites)) {
164
+ for (const siteId of d.sites as string[]) {
165
+ if (siteFilter && siteId !== siteFilter && siteFilter !== undefined) continue;
166
+ if (!(await systemsCacheSiteExists(workspaceRoot, siteId, context.io))) {
167
+ warnings.push(
168
+ diag(
169
+ "DELEG-07",
170
+ "warning",
171
+ `"${id}" references site "${siteId}" — no systems-cache/${siteId} sibling exists`,
172
+ DELEGATIONS_FILENAME,
173
+ ),
174
+ );
175
+ }
176
+ }
177
+ }
178
+
179
+ if (typeof d.signature === "string" && parsed.success) {
180
+ const entry = parsed.data.delegations.find((e) => e.id === id);
181
+ if (
182
+ entry &&
183
+ !verifyDelegationSignature(entry.signature!, canonicalDelegationPayload(entry))
184
+ ) {
185
+ warnings.push(
186
+ diag(
187
+ "DELEG-08",
188
+ "warning",
189
+ `"${id}" signature does not verify against its canonical payload`,
190
+ DELEGATIONS_FILENAME,
191
+ ),
192
+ );
193
+ }
194
+ }
195
+
196
+ // Informational: expired-but-unrevoked entries are legal history, no signal.
197
+ void now;
198
+ }
199
+
200
+ const status = errors.length === 0 ? "pass" : "fail";
201
+ if (outputFormat === "pretty") {
202
+ logger.section(`Authority delegations: ${DELEGATIONS_FILENAME}`);
203
+ logger.info(` ${entries.length} delegation(s)`);
204
+ for (const w of warnings) logger.warn(` ${w.ruleId}: ${w.message}`);
205
+ for (const e of errors) logger.error(` ${e.ruleId}: ${e.message}`);
206
+ }
207
+
208
+ return {
209
+ data: resultData(errors, warnings, entries.length),
210
+ summary:
211
+ status === "pass"
212
+ ? `delegation registry valid: ${entries.length} delegation(s), ${warnings.length} warning(s)`
213
+ : `delegation registry invalid: ${errors.length} error(s)`,
214
+ exitCode: status === "pass" ? 0 : 1,
215
+ };
216
+
217
+ function resultData(
218
+ errs: Diagnostic[],
219
+ warns: Diagnostic[],
220
+ count: number,
221
+ ): AuthorityDelegationValidateResult {
222
+ return {
223
+ command: "authority.delegation.validate",
224
+ status: errs.length === 0 ? "pass" : "fail",
225
+ file: DELEGATIONS_FILENAME,
226
+ delegations: count,
227
+ errors: errs,
228
+ warnings: warns,
229
+ };
230
+ }
231
+ }
@@ -0,0 +1,111 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: shared authority-module helpers — werkstatt-layout site
4
+ probes (systems-cache sibling convention) and Bordbuch audit-event emission
5
+ through the kernel's sibling-invocation port (ForgeRuntimeContext.invoke,
6
+ RFC-1306). All engine touchpoints degrade cleanly under the standalone
7
+ forge CLI where no kernel host exists.</purpose>
8
+ <non-goals>
9
+ <item>Do not import @warpgogol/* runtime packages — FORGE-AUTONOMY-01; the invoke port is the only engine surface.</item>
10
+ </non-goals>
11
+ </MODULE_CONTRACT>
12
+ <CHANGE_SUMMARY>
13
+ <item>RFC-1336: initial module — systemsCacheSiteExists, coveredSites, appendAuthorityEvent.</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 path from "node:path";
19
+
20
+ import type { DelegationEntry } from "../../src/authority/delegations.ts";
21
+ import type { ForgeRuntimeContext, WorkspaceIO } from "../../src/types.ts";
22
+ import { resolveIo } from "../../src/utils/io.ts";
23
+
24
+ /**
25
+ * Werkstatt layout: systems-cache/<id> is a sibling of the workshop root
26
+ * (mirrors[0], RFC-0790). A declared site-scoped grant must name a site that
27
+ * actually exists — a typo'd site would silently bind to nothing.
28
+ */
29
+ export async function systemsCacheSiteExists(
30
+ workspaceRoot: string,
31
+ siteId: string,
32
+ io?: WorkspaceIO,
33
+ ): Promise<boolean> {
34
+ const effectiveIo = resolveIo(io);
35
+ const siteDir = path.resolve(workspaceRoot, "..", "systems-cache", siteId);
36
+ return effectiveIo.exists(siteDir);
37
+ }
38
+
39
+ /**
40
+ * Enumerate the sites a grant covers for audit-event fan-out: explicit ids,
41
+ * or every systems-cache sibling dir for "workspace" grants.
42
+ */
43
+ export async function coveredSites(
44
+ workspaceRoot: string,
45
+ grant: Pick<DelegationEntry, "sites">,
46
+ io?: WorkspaceIO,
47
+ ): Promise<string[]> {
48
+ if (grant.sites !== "workspace") return grant.sites;
49
+ const effectiveIo = resolveIo(io);
50
+ const cacheDir = path.resolve(workspaceRoot, "..", "systems-cache");
51
+ if (!(await effectiveIo.exists(cacheDir))) return [];
52
+ const entries = await effectiveIo.readdir(cacheDir);
53
+ return entries.filter((e) => e.isDirectory).map((e) => e.name);
54
+ }
55
+
56
+ /**
57
+ * Append one audit event per covered site via bordbuch.append — the
58
+ * sibling-invocation port exists only under a kernel host; under the
59
+ * standalone forge CLI the registry write has already landed (it is the
60
+ * source of truth) and the event degrades to a warning.
61
+ */
62
+ export async function appendAuthorityEvent(
63
+ context: ForgeRuntimeContext,
64
+ opts: {
65
+ kind: "authority-delegation" | "authority-delegation-revoked";
66
+ sites: string[];
67
+ summary: string;
68
+ actor: string;
69
+ metadata: Record<string, unknown>;
70
+ },
71
+ ): Promise<{ appended: string[]; skipped: boolean }> {
72
+ if (!context.invoke) {
73
+ context.logger.warn(
74
+ ` [authority] bordbuch event '${opts.kind}' not recorded — no kernel host (registry is the source of truth)`,
75
+ );
76
+ return { appended: [], skipped: true };
77
+ }
78
+ const appended: string[] = [];
79
+ for (const siteId of opts.sites) {
80
+ const result = await context.invoke("bordbuch.append", {
81
+ system: siteId,
82
+ kind: opts.kind,
83
+ summary: opts.summary,
84
+ actor: opts.actor,
85
+ "writer-role": "operator",
86
+ metadata: JSON.stringify(opts.metadata),
87
+ });
88
+ if (result.ok || result.exitCode === 0) {
89
+ appended.push(siteId);
90
+ } else {
91
+ context.logger.warn(
92
+ ` [authority] bordbuch event for '${siteId}' failed: ${result.summary ?? "unknown"}`,
93
+ );
94
+ }
95
+ }
96
+ return { appended, skipped: false };
97
+ }
98
+
99
+ export function flagString(
100
+ input: { flags: Record<string, unknown> },
101
+ key: string,
102
+ ): string | undefined {
103
+ const v = input.flags[key];
104
+ return typeof v === "string" && v.length > 0 ? v : undefined;
105
+ }
106
+
107
+ export function flagStringList(input: { flags: Record<string, unknown> }, key: string): string[] {
108
+ const v = input.flags[key];
109
+ if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string");
110
+ return typeof v === "string" && v.length > 0 ? [v] : [];
111
+ }
@@ -0,0 +1,14 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: authority module barrel — re-exports the module factory.</purpose>
4
+ <non-goals>
5
+ <item>Do not add handler logic — that lives in handlers/.</item>
6
+ </non-goals>
7
+ </MODULE_CONTRACT>
8
+ <CHANGE_SUMMARY>
9
+ <item>RFC-1336: initial barrel.</item>
10
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
11
+ </CHANGE_SUMMARY>
12
+ */
13
+
14
+ export { createForgeAuthorityModule } from "./authority.module.ts";
@@ -12,6 +12,7 @@ Sweep batch 2: real KEY_DECISIONS on 10 files, expanded purposes (CONTRACT-02/PU
12
12
  <item>RFC-1271: V-43 verificationTier enum check; V-23 archive exemption (isArchived paths skip evidence-presence — archive-freeze precedent).</item>
13
13
  <item>RFC-1322: fo-review fix pass — V-37 annotation extraction takes the LAST (evidence: ...) occurrence, matching the stamp resolver (prose mentions no longer shadow the real annotation).</item>
14
14
  <item>RFC-1330: V-44 presence-only behavioral criteria; shared listBehavioralCriteria.</item>
15
+ <item>RFC-1336: V-25 admits agent:&lt;id&gt; reviewers iff frontmatter decidedBy names a human:&lt;handle&gt; AND an active rfc.decision delegation covers the agent under that grantor (authority.delegations.yaml).</item>
15
16
  <item>RFC-1334: step 4 — reachable acceptance probe (symbol and command modes) and V-45</item>
16
17
  <history>RFC-0303, RFC-0722, RFC-0755, RFC-0795, RFC-0997, RFC-1006, RFC-1097</history>
17
18
  </CHANGE_SUMMARY>
@@ -19,6 +20,11 @@ Sweep batch 2: real KEY_DECISIONS on 10 files, expanded purposes (CONTRACT-02/PU
19
20
 
20
21
  import path from "node:path";
21
22
  import { ambientIo } from "../../../src/utils/io.ts";
23
+ import {
24
+ HUMAN_ID_PATTERN,
25
+ loadDelegations,
26
+ resolveDelegation,
27
+ } from "../../../src/authority/delegations.ts";
22
28
 
23
29
  import { execFile } from "../../../src/utils/sync-fs.ts";
24
30
 
@@ -1250,12 +1256,42 @@ export async function validateSingleRfc(
1250
1256
  `reviewer "${entry}" does not match the identity format ^(human|agent):[a-z0-9][a-z0-9-]*$ (RFC-0335).`,
1251
1257
  );
1252
1258
  } else if (entry.startsWith("agent:")) {
1253
- addViolation(
1254
- rfcId,
1255
- relFile,
1256
- "V-25",
1257
- `agent reviewer identities are reserved until an RFC grants AI reviewer authority over RFC governance (see RFC-0279 for the pattern) (RFC-0335).`,
1258
- );
1259
+ // RFC-1336: an agent reviewer is admitted iff the frontmatter records
1260
+ // the granting human (decidedBy: human:<handle>) AND an active
1261
+ // rfc.decision delegation covers this agent under that grantor —
1262
+ // provenance is honest in both directions: the ledger shows who
1263
+ // decided, the registry proves they authorized the delegate.
1264
+ const decidedBy = typeof fm["decidedBy"] === "string" ? fm["decidedBy"] : "";
1265
+ if (!HUMAN_ID_PATTERN.test(decidedBy)) {
1266
+ addViolation(
1267
+ rfcId,
1268
+ relFile,
1269
+ "V-25",
1270
+ `agent reviewer "${entry}" requires decidedBy: human:<handle> naming the granting operator (RFC-1336) — an unsigned agent attestation is not a decision.`,
1271
+ );
1272
+ } else {
1273
+ let delegated = false;
1274
+ try {
1275
+ const registry = await loadDelegations(workspaceRoot, io);
1276
+ delegated =
1277
+ resolveDelegation(registry, {
1278
+ scope: "rfc.decision",
1279
+ agent: entry,
1280
+ grantedBy: decidedBy,
1281
+ }) !== null;
1282
+ } catch {
1283
+ // Registry unreadable/corrupt — fail closed: the violation stands.
1284
+ delegated = false;
1285
+ }
1286
+ if (!delegated) {
1287
+ addViolation(
1288
+ rfcId,
1289
+ relFile,
1290
+ "V-25",
1291
+ `agent reviewer "${entry}" has no active rfc.decision delegation granted by ${decidedBy} (RFC-1336) — grant one via authority.delegate, or record a human reviewer instead.`,
1292
+ );
1293
+ }
1294
+ }
1259
1295
  }
1260
1296
  }
1261
1297
  }
package/os/rfc/types.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  <item>RFC-1330: origin contracts, RFC_ORIGIN_CUTOFF, RFC-IMP-10/11 rule ids, stamp warnings.</item>
18
18
  <item>RFC-1333: steps 1-3 — report contract, rfc.verify.workspace export, RFC-IMP-12 gate, RFC-IMP-11 blocking</item>
19
19
  <item>RFC-1334: step 4 — reachable acceptance probe (symbol and command modes) and V-45</item>
20
+ <item>RFC-1336: RfcFrontmatter.decidedBy — the granting human when an agent:&lt;id&gt; reviewer decided under an rfc.decision delegation; added to RFC_KNOWN_KEYS.</item>
20
21
  <history>RFC-0465, RFC-0478, RFC-0480, RFC-0795, RFC-0998, RFC-0999, RFC-1097, RFC-1249, RFC-1271, RFC-1306, RFC-1310, RFC-1320</history>
21
22
  </CHANGE_SUMMARY>
22
23
  ***************************************************************/
@@ -158,6 +159,14 @@ export interface RfcFrontmatter {
158
159
  /** Optional additional reviewers. */
159
160
  reviewers?: string[];
160
161
 
162
+ /**
163
+ * RFC-1336: the granting human when a reviewer is `agent:<id>` —
164
+ * V-25 admits an agent reviewer only when decidedBy names the operator
165
+ * AND an active `rfc.decision` delegation covers the agent under that
166
+ * grantor. Absent on human-decided RFCs.
167
+ */
168
+ decidedBy?: string;
169
+
161
170
  /** ISO 8601 date of creation. */
162
171
  createdAt: string;
163
172
 
@@ -736,6 +745,7 @@ export const RFC_KNOWN_KEYS: readonly string[] = [
736
745
  "scope",
737
746
  "owners",
738
747
  "reviewers",
748
+ "decidedBy",
739
749
  "createdAt",
740
750
  "updatedAt",
741
751
  "enhancedAt",
@@ -24,6 +24,7 @@ Sweep batch 4: 73 Compass headers on headerless engine files (certification, com
24
24
  */
25
25
 
26
26
  import { ambientIo as fs } from "../../../src/utils/io.ts";
27
+ import { execFile } from "../../../src/utils/sync-fs.ts";
27
28
  import path from "node:path";
28
29
  import { createHash } from "node:crypto";
29
30
  import YAML from "yaml";
@@ -45,7 +46,9 @@ import {
45
46
 
46
47
  const RFC_PATTERN = /\bRFC-\d{4}\b/g;
47
48
  const FILE_PATH_PATTERN = /\b(?:packages|docs|services|systems|tools|scripts)\/[^\s"'`<>|]+/g;
49
+ const PATH_EDGE_PUNCTUATION = /[.,;:!?()[\]{}]+$/;
48
50
  const COMMIT_HASH_PATTERN = /\b[0-9a-f]{7,40}\b/g;
51
+ const GIT_VERIFY_TIMEOUT_MS = 15_000;
49
52
  const COMMAND_PATTERN =
50
53
  /\b(?:session|rfc|adr|plan|audit|docs|mission|forge|compass|werkstatt|spec|naming|workflow|bordbuch|sternsystem|release)\.\w+/g;
51
54
 
@@ -70,19 +73,50 @@ function extractRfcIds(content: string): string[] {
70
73
 
71
74
  function extractFilePaths(content: string): string[] {
72
75
  const matches = content.match(FILE_PATH_PATTERN);
73
- return matches ? [...new Set(matches)] : [];
76
+ if (!matches) return [];
77
+ // Strip sentence punctuation clinging to path tokens in enumerated prose
78
+ // ("docs/foo.md:", "docs/foo/,") before accepting the token.
79
+ const cleaned = matches
80
+ .map((m) => m.replace(PATH_EDGE_PUNCTUATION, ""))
81
+ .filter((m) => m.includes("/"));
82
+ return [...new Set(cleaned)];
74
83
  }
75
84
 
76
- function extractCommitHashes(content: string): string[] {
85
+ async function extractCommitHashes(content: string, cwd: string): Promise<string[]> {
77
86
  const matches = content.match(COMMIT_HASH_PATTERN);
78
87
  if (!matches) return [];
79
88
  // Filter to plausible git hashes (7-40 hex chars, but exclude pure version numbers)
80
- const filtered = matches.filter((h) => {
81
- // Exclude strings that look like version numbers (e.g. 1.0.0)
82
- if (/^\d+$/.test(h) && h.length <= 8) return false;
83
- return true;
84
- });
85
- return [...new Set(filtered)];
89
+ const candidates = [...new Set(matches.filter((h) => !/^\d+$/.test(h) || h.length > 8))];
90
+ if (candidates.length === 0) return [];
91
+
92
+ // A hex token is recorded as a commit only when it resolves to a commit
93
+ // object in the workspace repository — random hex ids (approval ids,
94
+ // checksums, foreign-repo shas) are dropped rather than claimed.
95
+ const verified = new Set<string>();
96
+ try {
97
+ const stdout = await new Promise<string>((resolvePromise, rejectPromise) => {
98
+ const child = execFile(
99
+ "git",
100
+ ["cat-file", "--batch-check"],
101
+ { cwd, timeout: GIT_VERIFY_TIMEOUT_MS, encoding: "utf8" },
102
+ (err, out) => (err ? rejectPromise(err) : resolvePromise(out)),
103
+ );
104
+ // The child may exit before draining stdin (e.g. not a git repo —
105
+ // cat-file fails fast and the pipe closes mid-write → EPIPE). The
106
+ // execFile callback carries the real outcome; stdin errors are noise.
107
+ child.stdin?.on("error", () => {});
108
+ child.stdin?.end(candidates.map((c) => `${c}^{commit}`).join("\n") + "\n");
109
+ });
110
+ // One answer line per input, in order: `<sha> commit <size>` when the
111
+ // candidate resolves to a commit, `<input>^{commit} missing` otherwise.
112
+ const lines = stdout.split("\n");
113
+ candidates.forEach((candidate, i) => {
114
+ if (lines[i]?.split(/\s+/)[1] === "commit") verified.add(candidate);
115
+ });
116
+ } catch {
117
+ // Not a git repository or git unavailable — no candidate is verifiable.
118
+ }
119
+ return [...verified];
86
120
  }
87
121
 
88
122
  function extractCommands(content: string): string[] {
@@ -272,7 +306,7 @@ export async function runSessionSave(
272
306
  const fullContent = rawContent;
273
307
  const relatedRfcs = extractRfcIds(fullContent);
274
308
  const relatedArtifacts = extractFilePaths(fullContent);
275
- const commits = extractCommitHashes(fullContent);
309
+ const commits = await extractCommitHashes(fullContent, workspaceRoot);
276
310
  const files = extractFilePaths(fullContent);
277
311
  const commands = extractCommands(fullContent);
278
312
  const types = detectSessionTypes(fullContent);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warpgogol/forge",
3
- "version": "8.0.2",
3
+ "version": "8.0.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -155,6 +155,18 @@
155
155
  "./os/queue-module": {
156
156
  "types": "./os/queue/queue.module.ts",
157
157
  "default": "./os/queue/queue.module.ts"
158
+ },
159
+ "./authority": {
160
+ "types": "./src/authority/index.ts",
161
+ "default": "./src/authority/index.ts"
162
+ },
163
+ "./os/authority": {
164
+ "types": "./os/authority/index.ts",
165
+ "default": "./os/authority/index.ts"
166
+ },
167
+ "./os/authority-module": {
168
+ "types": "./os/authority/authority.module.ts",
169
+ "default": "./os/authority/authority.module.ts"
158
170
  }
159
171
  },
160
172
  "files": [