@warpgogol/forge 6.3.5 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +2 -1
  3. package/dist/os/rfc/acceptance.d.ts.map +1 -1
  4. package/dist/os/rfc/acceptance.js +15 -1
  5. package/dist/os/rfc/acceptance.js.map +1 -1
  6. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  7. package/dist/os/rfc/handlers/implement-stamp.js +98 -13
  8. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  9. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  10. package/dist/os/rfc/handlers/validate-rules.js +13 -4
  11. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  12. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  13. package/dist/os/rfc/rfc.module.js +11 -6
  14. package/dist/os/rfc/rfc.module.js.map +1 -1
  15. package/dist/os/rfc/types.d.ts +34 -5
  16. package/dist/os/rfc/types.d.ts.map +1 -1
  17. package/dist/os/rfc/types.js +14 -2
  18. package/dist/os/rfc/types.js.map +1 -1
  19. package/dist/os/rfc/verification-evidence.d.ts +16 -0
  20. package/dist/os/rfc/verification-evidence.d.ts.map +1 -1
  21. package/dist/os/rfc/verification-evidence.js +71 -5
  22. package/dist/os/rfc/verification-evidence.js.map +1 -1
  23. package/dist/src/knowledge/sync.d.ts +1 -1
  24. package/dist/src/knowledge/sync.d.ts.map +1 -1
  25. package/dist/src/knowledge/sync.js +15 -3
  26. package/dist/src/knowledge/sync.js.map +1 -1
  27. package/dist/src/skill-schema.d.ts +2 -0
  28. package/dist/src/skill-schema.d.ts.map +1 -1
  29. package/dist/src/skill-schema.js +9 -1
  30. package/dist/src/skill-schema.js.map +1 -1
  31. package/os/rfc/acceptance.test.ts +111 -0
  32. package/os/rfc/acceptance.ts +20 -1
  33. package/os/rfc/handlers/implement-stamp-stale.test.ts +267 -0
  34. package/os/rfc/handlers/implement-stamp.ts +116 -15
  35. package/os/rfc/handlers/validate-rules.test.ts +42 -0
  36. package/os/rfc/handlers/validate-rules.ts +22 -4
  37. package/os/rfc/rfc-0000-template.md +18 -1
  38. package/os/rfc/rfc.module.ts +12 -6
  39. package/os/rfc/types.ts +48 -5
  40. package/os/rfc/verification-emit-check.test.ts +201 -0
  41. package/os/rfc/verification-evidence.ts +73 -5
  42. package/os/rfc/verification-normalize.test.ts +61 -0
  43. package/package.json +1 -1
  44. package/skills/_shared/agent-operating-model.md +83 -0
  45. package/skills/fo/fo-idea/SKILL.md +6 -3
  46. package/src/knowledge/__tests__/sync.test.ts +40 -0
  47. package/src/knowledge/sync.ts +20 -5
  48. package/src/onboarding/templates/behavioral-layer-core.md +8 -0
  49. package/src/skill-schema.ts +9 -1
  50. package/src/tests/fixtures/agents-generate-business-before.txt +8 -0
  51. package/src/tests/skill-schema.test.ts +39 -0
@@ -0,0 +1,267 @@
1
+ // @vitest-environment node
2
+ import { test, expect, describe, vi, beforeEach, afterEach } from "vitest";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { execFileSync } from "node:child_process";
7
+ import { parse as yamlParse, stringify as yamlStringify } from "yaml";
8
+
9
+ import { runRfcImplementStamp } from "./implement-stamp.ts";
10
+ import { runRfcVerificationEmit } from "../verification-evidence.ts";
11
+ import type { ForgeCommandInput, ForgeRuntimeContext } from "../../../src/types.ts";
12
+
13
+ const { mockRunProbe } = vi.hoisted(() => ({
14
+ mockRunProbe: vi.fn(),
15
+ }));
16
+
17
+ vi.mock("../acceptance.ts", () => ({
18
+ runProbe: mockRunProbe,
19
+ }));
20
+
21
+ const PROBE = { probe: "file-exists", path: "src/index.ts", criterion: "AC-1" };
22
+
23
+ const RFC_MD = (id: string, probes: Record<string, unknown>[] | null, body = "Test.\n") => {
24
+ const probeYaml = (probes ?? [])
25
+ .map((p) => ` - probe: ${p.probe}\n path: ${p.path}\n criterion: ${p.criterion}`)
26
+ .join("\n");
27
+ const acceptanceBlock = probes === null ? "" : `acceptance:\n${probeYaml}\n`;
28
+ return `---\nid: ${id}\ntitle: "Test ${id}"\nstatus: accepted\nkind: command\nscope: workspace\nowners:\n - architecture\ncreatedAt: 2026-10-01\nupdatedAt: 2026-10-01\n${acceptanceBlock}---\n\n# ${id}\n## Context\n${body}\n## Acceptance criteria\n\n- [x] AC-1: THE thing SHALL work (evidence: test: packages/forge/x.test.ts)\n`;
29
+ };
30
+
31
+ const git = (dir: string, args: string[]) =>
32
+ execFileSync("git", args, { cwd: dir, encoding: "utf-8" }).trim();
33
+
34
+ const commitAll = (dir: string, msg: string) => {
35
+ git(dir, ["add", "-A"]);
36
+ git(dir, ["commit", "-qm", msg]);
37
+ return git(dir, ["rev-parse", "HEAD"]);
38
+ };
39
+
40
+ async function setupGitWorkspace(): Promise<{
41
+ dir: string;
42
+ rfcDir: string;
43
+ cleanup: () => Promise<void>;
44
+ }> {
45
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "tmp-stamp-"));
46
+ git(dir, ["init", "-q"]);
47
+ git(dir, ["config", "user.email", "t@t.t"]);
48
+ git(dir, ["config", "user.name", "t"]);
49
+ const rfcDir = path.join(dir, "docs", "rfcs");
50
+ await fs.mkdir(rfcDir, { recursive: true });
51
+ return {
52
+ dir,
53
+ rfcDir,
54
+ cleanup: () => fs.rm(dir, { recursive: true, force: true }),
55
+ };
56
+ }
57
+
58
+ function makeContext(workspaceRoot: string) {
59
+ return {
60
+ workspaceRoot,
61
+ logger: { info: () => {}, warn: () => {} },
62
+ outputFormat: "json" as const,
63
+ commandRegistry: undefined,
64
+ dryRun: false,
65
+ } as unknown as ForgeRuntimeContext;
66
+ }
67
+
68
+ const writeRfc = async (rfcDir: string, md: string) =>
69
+ fs.writeFile(path.join(rfcDir, "rfc-0100-stale.md"), md);
70
+
71
+ async function emitEnvelope(dir: string) {
72
+ mockRunProbe.mockResolvedValue({ probe: PROBE, ok: true, detail: "exists" });
73
+ const r = await runRfcVerificationEmit(
74
+ { flags: { id: "RFC-0100" } } as unknown as ForgeCommandInput,
75
+ makeContext(dir),
76
+ );
77
+ expect(r.exitCode).toBe(0);
78
+ }
79
+
80
+ const stamp = (dir: string, commit: string) =>
81
+ runRfcImplementStamp(
82
+ {
83
+ flags: { id: "RFC-0100", "implementation-commit": commit },
84
+ } as unknown as ForgeCommandInput,
85
+ makeContext(dir),
86
+ );
87
+
88
+ const rules = (result: Awaited<ReturnType<typeof stamp>>) =>
89
+ (result.data!.violations ?? []).map((v) => v.rule);
90
+
91
+ beforeEach(() => {
92
+ mockRunProbe.mockReset();
93
+ });
94
+
95
+ afterEach(() => {
96
+ vi.restoreAllMocks();
97
+ });
98
+
99
+ describe("rfc.implement.stamp — RFC-IMP-09 stale evidence gate (RFC-1271)", () => {
100
+ test("matching evidence does NOT emit RFC-IMP-09 (AC-8)", async () => {
101
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
102
+ try {
103
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
104
+ await emitEnvelope(dir);
105
+ const sha = commitAll(dir, "feat: implement RFC-0100 evidence-driven gate");
106
+
107
+ const result = await stamp(dir, sha);
108
+ expect(rules(result)).not.toContain("RFC-IMP-09");
109
+ expect(rules(result)).toEqual([]);
110
+ } finally {
111
+ await cleanup();
112
+ }
113
+ });
114
+
115
+ test("stale acceptanceHash — probe criterion changed post-emit (AC-1)", async () => {
116
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
117
+ try {
118
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
119
+ await emitEnvelope(dir);
120
+ commitAll(dir, "feat: implement RFC-0100");
121
+
122
+ // Criterion retarget on the probe — committed, so IMP-04 passes.
123
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [{ ...PROBE, criterion: "AC-9" }]));
124
+ commitAll(dir, "chore: tweak RFC-0100 probes");
125
+
126
+ const result = await stamp(dir, git(dir, ["rev-parse", "HEAD"]));
127
+ expect(rules(result)).toContain("RFC-IMP-09");
128
+ const v = result.data!.violations.find((x) => x.rule === "RFC-IMP-09")!;
129
+ expect(v.message).toContain("acceptanceHash");
130
+ expect(v.message).toContain("rfc.verification.emit --id RFC-0100");
131
+ } finally {
132
+ await cleanup();
133
+ }
134
+ });
135
+
136
+ test("stale rfcFileHash — body changed post-emit (AC-2)", async () => {
137
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
138
+ try {
139
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
140
+ await emitEnvelope(dir);
141
+ commitAll(dir, "feat: implement RFC-0100");
142
+
143
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE], "Edited body.\n"));
144
+ commitAll(dir, "chore: edit RFC-0100 body");
145
+
146
+ const result = await stamp(dir, git(dir, ["rev-parse", "HEAD"]));
147
+ expect(rules(result)).toContain("RFC-IMP-09");
148
+ const v = result.data!.violations.find((x) => x.rule === "RFC-IMP-09")!;
149
+ expect(v.message).toContain("rfcFileHash");
150
+ expect(v.message).not.toContain("acceptanceHash mismatch");
151
+ } finally {
152
+ await cleanup();
153
+ }
154
+ });
155
+
156
+ test("acceptance list deleted post-emit → IMP-09 names probe deletion", async () => {
157
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
158
+ try {
159
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
160
+ await emitEnvelope(dir);
161
+ commitAll(dir, "feat: implement RFC-0100");
162
+
163
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", null));
164
+ commitAll(dir, "chore: drop RFC-0100 probes");
165
+
166
+ const result = await stamp(dir, git(dir, ["rev-parse", "HEAD"]));
167
+ expect(rules(result)).toContain("RFC-IMP-09");
168
+ const v = result.data!.violations.find((x) => x.rule === "RFC-IMP-09")!;
169
+ expect(v.message).toContain("probes were deleted");
170
+ } finally {
171
+ await cleanup();
172
+ }
173
+ });
174
+
175
+ test("malformed scalar envelope → IMP-09 fail-closed (no evasion)", async () => {
176
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
177
+ try {
178
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
179
+ const envPath = path.join(dir, "docs", "rfcs", "verification", "rfc-0100.generated.yaml");
180
+ await fs.mkdir(path.dirname(envPath), { recursive: true });
181
+ // yamlParse("0") → 0 — falsy scalar must NOT slip the gate open.
182
+ await fs.writeFile(envPath, "0\n");
183
+ commitAll(dir, "feat: implement RFC-0100 with forged scalar envelope");
184
+
185
+ const result = await stamp(dir, git(dir, ["rev-parse", "HEAD"]));
186
+ expect(rules(result)).toContain("RFC-IMP-09");
187
+ const v = result.data!.violations.find((x) => x.rule === "RFC-IMP-09")!;
188
+ expect(v.message).toContain("malformed");
189
+ } finally {
190
+ await cleanup();
191
+ }
192
+ });
193
+
194
+ test("unparseable envelope → IMP-09 fail-closed", async () => {
195
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
196
+ try {
197
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
198
+ const envPath = path.join(dir, "docs", "rfcs", "verification", "rfc-0100.generated.yaml");
199
+ await fs.mkdir(path.dirname(envPath), { recursive: true });
200
+ await fs.writeFile(envPath, "{{{not yaml: [unclosed\n");
201
+ commitAll(dir, "feat: implement RFC-0100 with broken envelope");
202
+
203
+ const result = await stamp(dir, git(dir, ["rev-parse", "HEAD"]));
204
+ expect(rules(result)).toContain("RFC-IMP-09");
205
+ const v = result.data!.violations.find((x) => x.rule === "RFC-IMP-09")!;
206
+ expect(v.message).toContain("malformed");
207
+ } finally {
208
+ await cleanup();
209
+ }
210
+ });
211
+
212
+ test("successful stamp auto re-emits — envelope binds the implemented-state file", async () => {
213
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
214
+ try {
215
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
216
+ await emitEnvelope(dir);
217
+ const sha = commitAll(dir, "feat: implement RFC-0100");
218
+
219
+ const result = await stamp(dir, sha);
220
+ expect(rules(result)).toEqual([]);
221
+ expect(result.data!.data?.evidenceReEmitted).toBe(true);
222
+
223
+ // Born-stale regression: the envelope MUST describe the post-mutation
224
+ // file — a fresh emit --check on the stamped state diverges on nothing.
225
+ const envPath = path.join(dir, "docs", "rfcs", "verification", "rfc-0100.generated.yaml");
226
+ const env = yamlParse(await fs.readFile(envPath, "utf-8")) as Record<string, unknown>;
227
+ expect(env["rfcStatus"]).toBe("implemented");
228
+
229
+ mockRunProbe.mockResolvedValue({ probe: PROBE, ok: true, detail: "exists" });
230
+ const check = await runRfcVerificationEmit(
231
+ { flags: { id: "RFC-0100", check: true } } as unknown as ForgeCommandInput,
232
+ makeContext(dir),
233
+ );
234
+ expect(check.exitCode).toBe(0);
235
+ expect(check.data!.check![0]).toMatchObject({
236
+ rfcId: "RFC-0100",
237
+ match: true,
238
+ });
239
+ } finally {
240
+ await cleanup();
241
+ }
242
+ });
243
+
244
+ test("envelope lacking hash fields → IMP-09 fail-closed", async () => {
245
+ const { dir, rfcDir, cleanup } = await setupGitWorkspace();
246
+ try {
247
+ await writeRfc(rfcDir, RFC_MD("RFC-0100", [PROBE]));
248
+ await emitEnvelope(dir);
249
+ commitAll(dir, "feat: implement RFC-0100");
250
+
251
+ // Strip the hash fields to simulate a pre-RFC-0330 envelope.
252
+ const envPath = path.join(dir, "docs", "rfcs", "verification", "rfc-0100.generated.yaml");
253
+ const env = yamlParse(await fs.readFile(envPath, "utf-8")) as Record<string, unknown>;
254
+ delete env["rfcFileHash"];
255
+ delete env["acceptanceHash"];
256
+ await fs.writeFile(envPath, yamlStringify(env) + "\n");
257
+ commitAll(dir, "chore: age RFC-0100 envelope");
258
+
259
+ const result = await stamp(dir, git(dir, ["rev-parse", "HEAD"]));
260
+ expect(rules(result)).toContain("RFC-IMP-09");
261
+ const v = result.data!.violations.find((x) => x.rule === "RFC-IMP-09")!;
262
+ expect(v.message).toContain("lacks hash fields");
263
+ } finally {
264
+ await cleanup();
265
+ }
266
+ });
267
+ });
@@ -12,7 +12,6 @@ verification evidence, and atomically mutates RFC frontmatter.
12
12
  </non-goals>
13
13
  </MODULE_CONTRACT>
14
14
  <CHANGE_SUMMARY>
15
- <item>RFC-1053: integrate generateRfcMetrics after successful stamp (non-fatal, guarded by !isDryRun).</item>
16
15
  <item>RFC-1097: step 6 — compass.migrate codemod run
17
16
 
18
17
  Mechanical v1 to v2 header migration across the workspace: 942 files rewritten — CHANGE_SUMMARY windows collapsed into history, forbidden v1 blocks stripped, KEY_DECISIONS seeded from @ai-invariant comments (5 files) or TODO placeholders (103 files), blocks reordered to canonical order.</item>
@@ -21,7 +20,8 @@ Mechanical v1 to v2 header migration across the workspace: 942 files rewritten
21
20
  Sweep batch 2: real KEY_DECISIONS on 10 files, expanded purposes (CONTRACT-02/PURPOSE-02), headers on mission/index + gen-upstreams, sanitizeItemText in summary.record (literal Compass tags corrupted history), excludedPaths for wrangler types, test-fixtures testPattern. forge+services now 0 diagnostics under --mode error.</item>
22
21
  <item>Session-retro 2026-10-08: auto-detect picks the sole implement/feat-prefixed candidate among multi-commit references (RFC-IMP-03 no longer blocks full pipelines); ambiguous sets keep blocking with annotated candidate list + earliest-candidate suggestion.</item>
23
22
  <item>RFC-1249: wire werkstatt.commands.validate into packages.check + retire CMD-OUTPUT debt</item>
24
- <history>RFC-0268, RFC-0476, RFC-0756, RFC-0795, RFC-0997, RFC-IMP-07</history>
23
+ <item>RFC-1271: review wave — deep probe normalization, malformed-envelope fail-closed, post-stamp re-emit, honest repair hints</item>
24
+ <history>RFC-0268, RFC-0476, RFC-0756, RFC-0795, RFC-0997, RFC-1053, RFC-IMP-07</history>
25
25
  </CHANGE_SUMMARY>
26
26
  */
27
27
 
@@ -42,8 +42,15 @@ import {
42
42
  } from "../frontmatter-io.ts";
43
43
  import { evaluateAcceptanceCriteria } from "./validate-rules.ts";
44
44
  import { toIsoDate } from "./shared.ts";
45
+ import { byteHashHex, normalizeProbes, runRfcVerificationEmit } from "../verification-evidence.ts";
45
46
  import { RFC_DIR, RFC_METADATA_CUTOFF, RFC_PROBE_BINDING_CUTOFF } from "../types.ts";
46
- import type { RfcStatus, RfcImplementStampViolation, RfcImplementStampResult } from "../types.ts";
47
+ import type {
48
+ RfcStatus,
49
+ RfcImplementStampViolation,
50
+ RfcImplementStampResult,
51
+ AcceptanceProbe,
52
+ VerificationEvidence,
53
+ } from "../types.ts";
47
54
 
48
55
  // Ambient default for helper fns without a context param — handlers override
49
56
  // with `const io = resolveIo(context.io)` inside their own scope.
@@ -200,16 +207,38 @@ async function releaseRfcLock(lockPath: string): Promise<void> {
200
207
  async function checkExistingEvidence(
201
208
  workspaceRoot: string,
202
209
  rfcId: string,
203
- ): Promise<{ exists: boolean; overall: string }> {
210
+ ): Promise<{
211
+ exists: boolean;
212
+ overall: string;
213
+ envelope: VerificationEvidence | null;
214
+ malformed: boolean;
215
+ }> {
204
216
  const slug = rfcId.toLowerCase();
205
217
  const evidencePath = join(workspaceRoot, VERIFICATION_DIR, `${slug}.generated.yaml`);
218
+ let content: string;
219
+ try {
220
+ content = await io.readFile(evidencePath);
221
+ } catch {
222
+ return { exists: false, overall: "missing", envelope: null, malformed: false };
223
+ }
224
+ let parsed: unknown;
206
225
  try {
207
- const content = await io.readFile(evidencePath);
208
- const evidence = yamlParse(content) as { overall?: string };
209
- return { exists: true, overall: String(evidence.overall ?? "") };
226
+ parsed = yamlParse(content);
210
227
  } catch {
211
- return { exists: false, overall: "missing" };
228
+ return { exists: true, overall: "malformed", envelope: null, malformed: true };
212
229
  }
230
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
231
+ // Fail closed: a committed envelope that parses to a scalar/array is
232
+ // malformed evidence, not absent evidence.
233
+ return { exists: true, overall: "malformed", envelope: null, malformed: true };
234
+ }
235
+ const evidence = parsed as VerificationEvidence;
236
+ return {
237
+ exists: true,
238
+ overall: String(evidence.overall ?? ""),
239
+ envelope: evidence,
240
+ malformed: false,
241
+ };
213
242
  }
214
243
 
215
244
  // ─── Frontmatter mutation ────────────────────────────────────────────────────
@@ -425,11 +454,17 @@ export async function runRfcImplementStamp(
425
454
  const hasProbes = Array.isArray(acceptance) && (acceptance as unknown[]).length > 0;
426
455
  const createdAtStr = String(fm["createdAt"] ?? "");
427
456
  const requiresEvidence = createdAtStr >= RFC_METADATA_CUTOFF && hasProbes;
457
+ const rfcFilePath = join(rfcDirPath, targetFile);
428
458
 
429
459
  let evidenceRelPath: string | undefined;
430
460
 
461
+ // RFC-1271: the envelope is fetched unconditionally — a committed envelope
462
+ // must also be evaluated when hasProbes is now false, because probe
463
+ // deletion IS a criteria change and would otherwise slip past
464
+ // requiresEvidence entirely (RFC-IMP-08 exempts policy/deprecation kinds).
465
+ const evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
466
+
431
467
  if (requiresEvidence) {
432
- const evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
433
468
  if (!evidenceCheck.exists || evidenceCheck.overall !== "pass") {
434
469
  violations.push({
435
470
  rule: "RFC-IMP-06",
@@ -441,6 +476,50 @@ export async function runRfcImplementStamp(
441
476
  }
442
477
  }
443
478
 
479
+ // ── RFC-IMP-09: stale evidence gate (RFC-1271) ────────────────────────────
480
+ // Hashes are recomputed from the working tree; combined with RFC-IMP-04
481
+ // (the RFC file must be committed-clean to stamp) the compared bytes are
482
+ // effectively the committed bytes — deliberate, keeps the gate honest
483
+ // without a second git read. Fires before any frontmatter mutation.
484
+ if (evidenceCheck.exists) {
485
+ if (evidenceCheck.malformed || !evidenceCheck.envelope) {
486
+ violations.push({
487
+ rule: "RFC-IMP-09",
488
+ message: `RFC ${targetId} evidence envelope is malformed (unreadable YAML or non-object content). Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope — or delete the stale envelope file.`,
489
+ });
490
+ } else if (!hasProbes) {
491
+ violations.push({
492
+ rule: "RFC-IMP-09",
493
+ message: `RFC ${targetId} has a committed evidence envelope but no acceptance: list — probes were deleted after emission, which is a criteria change. Either restore the probes and re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope — or delete the stale envelope file (rfc.verification.emit skips probe-less RFCs, so re-emit alone cannot clear this).`,
494
+ });
495
+ } else {
496
+ const rfcMarkdown = await io.readFile(rfcFilePath);
497
+ const currentFileHash = byteHashHex(rfcMarkdown);
498
+ const currentAcceptanceHash = byteHashHex(normalizeProbes(acceptance as AcceptanceProbe[]));
499
+ const env = evidenceCheck.envelope;
500
+ if (!env.rfcFileHash || !env.acceptanceHash) {
501
+ violations.push({
502
+ rule: "RFC-IMP-09",
503
+ message: `RFC ${targetId} evidence envelope lacks hash fields (pre-RFC-0330 format). Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope.`,
504
+ });
505
+ } else if (
506
+ env.rfcFileHash !== currentFileHash ||
507
+ env.acceptanceHash !== currentAcceptanceHash
508
+ ) {
509
+ const staleFields = [
510
+ env.rfcFileHash !== currentFileHash ? "rfcFileHash" : "",
511
+ env.acceptanceHash !== currentAcceptanceHash ? "acceptanceHash" : "",
512
+ ]
513
+ .filter(Boolean)
514
+ .join(" + ");
515
+ violations.push({
516
+ rule: "RFC-IMP-09",
517
+ message: `RFC ${targetId} evidence is stale: ${staleFields} mismatch — the RFC file or its acceptance list changed after emission. Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope.`,
518
+ });
519
+ }
520
+ }
521
+ }
522
+
444
523
  // ── RFC-IMP-08: minimum-one-probe gate (RFC-0997) ─────────────────────────
445
524
  // Post-cutoff architecture/contract/command RFCs must declare at least one
446
525
  // acceptance probe. Policy and deprecation kinds are exempt.
@@ -470,7 +549,6 @@ export async function runRfcImplementStamp(
470
549
 
471
550
  try {
472
551
  // ── Atomic mutation ──────────────────────────────────────────────────────
473
- const rfcFilePath = join(rfcDirPath, targetFile);
474
552
  const rfcSource = await io.readFile(rfcFilePath);
475
553
 
476
554
  const today = toIsoDate(new Date());
@@ -519,11 +597,33 @@ export async function runRfcImplementStamp(
519
597
  }
520
598
  }
521
599
 
522
- // ── Re-emit evidence if probes exist (to update with new status) ─────────
523
- if (hasProbes && requiresEvidence && evidenceRelPath) {
524
- // Evidence already exists and passed — no need to re-emit on stamp
525
- // The evidence was generated before stamping; the status change is
526
- // recorded in the RFC frontmatter, not in the evidence file.
600
+ // ── RFC-1271: post-stamp evidence re-emit ────────────────────────────────
601
+ // The frontmatter mutation above changes the bytes RFC-IMP-09 binds via
602
+ // rfcFileHash — without re-emission every successful stamp manufactures a
603
+ // stale envelope. Re-emit inside the stamp for probe-bearing RFCs so the
604
+ // committed envelope describes the implemented-state file. Non-fatal:
605
+ // the mutation is already written; a failed re-emit leaves a stale
606
+ // envelope the operator re-emits manually.
607
+ let evidenceReEmitted = false;
608
+ if (hasProbes) {
609
+ try {
610
+ const emitResult = await runRfcVerificationEmit(
611
+ { argv: [], flags: { id: targetId } },
612
+ context,
613
+ );
614
+ evidenceReEmitted = emitResult.exitCode === 0;
615
+ if (evidenceReEmitted) {
616
+ evidenceRelPath = join(VERIFICATION_DIR, `${targetId.toLowerCase()}.generated.yaml`);
617
+ } else {
618
+ logger.warn(
619
+ `[evidence] post-stamp re-emit failed for ${targetId} — re-run: site-kernel run rfc.verification.emit --id ${targetId}`,
620
+ );
621
+ }
622
+ } catch (emitErr) {
623
+ logger.warn(
624
+ `[evidence] post-stamp re-emit failed for ${targetId}: ${(emitErr as Error).message}`,
625
+ );
626
+ }
527
627
  }
528
628
 
529
629
  if (outputFormat === "pretty") {
@@ -546,6 +646,7 @@ export async function runRfcImplementStamp(
546
646
  stampedAt,
547
647
  criteriaChecked: criteriaEval.totalChecked,
548
648
  ...(evidenceRelPath ? { evidencePath: evidenceRelPath } : {}),
649
+ ...(hasProbes ? { evidenceReEmitted } : {}),
549
650
  ...(metricsPath ? { metricsPath } : {}),
550
651
  },
551
652
  violations: [],
@@ -760,6 +760,48 @@ describe("RFC-DIR-01: directory structure convention (RFC-0722)", () => {
760
760
  expect(dir01).toHaveLength(0);
761
761
  });
762
762
 
763
+ test("V-23 fires on non-archived implemented RFC with missing evidence", async () => {
764
+ const parsed = makeParsed("implemented", BASE_BODY, {
765
+ createdAt: "2026-10-01",
766
+ acceptance: [{ probe: "file-exists", path: "x.ts", criterion: "AC-1" }],
767
+ });
768
+ const { add, violations } = makeViolationsCollector();
769
+ await validateSingleRfc(
770
+ "rfc-9999-test.md",
771
+ parsed,
772
+ new Map(),
773
+ new Map(),
774
+ new Set(),
775
+ new Set(),
776
+ new Set(Object.keys(parsed.frontmatter)),
777
+ testWorkspace,
778
+ add,
779
+ );
780
+ const v23 = filterRule(violations, "V-23");
781
+ expect(v23).toHaveLength(1);
782
+ });
783
+
784
+ test("V-23 skips archived implemented RFCs (RFC-1271 — historical evidence drift is not debt)", async () => {
785
+ const parsed = makeParsed("implemented", BASE_BODY, {
786
+ createdAt: "2026-10-01",
787
+ acceptance: [{ probe: "file-exists", path: "x.ts", criterion: "AC-1" }],
788
+ });
789
+ const { add, violations } = makeViolationsCollector();
790
+ await validateSingleRfc(
791
+ "archive/implemented/rfc-9999-test.md",
792
+ parsed,
793
+ new Map(),
794
+ new Map(),
795
+ new Set(),
796
+ new Set(),
797
+ new Set(Object.keys(parsed.frontmatter)),
798
+ testWorkspace,
799
+ add,
800
+ );
801
+ const v23 = filterRule(violations, "V-23");
802
+ expect(v23).toHaveLength(0);
803
+ });
804
+
763
805
  test("no warning when RFC file is in verification/ subdirectory", async () => {
764
806
  const parsed = makeParsed("accepted", BASE_BODY);
765
807
  const { add, violations } = makeViolationsCollector();
@@ -6,7 +6,6 @@
6
6
  </non-goals>
7
7
  </MODULE_CONTRACT>
8
8
  <CHANGE_SUMMARY>
9
- <item>RFC-0795: add V-33 dependsOn referential integrity/self-dependency/rejected-dependency and V-34 batch slug format rules.</item>
10
9
  <item>RFC-0997: add V-35 probe→criterion referential integrity, V-36 criterion identifier discipline, V-37 evidence mechanism validity, and computeProbeCoverage for non-blocking coverage reports.</item>
11
10
  <item>RFC-1006: add V-38 document readiness completeness, V-39 non-atomic criterion, V-40 unbounded quantity, V-41 weasel verb, V-42 criterion versioning annotation format. Add evaluateDocumentReadiness and extend evaluateAcceptanceCriteria with supersession tracking and reject-checklist scans.</item>
12
11
  <item>RFC-1097: step 6 — compass.migrate codemod run
@@ -15,7 +14,8 @@ Mechanical v1 to v2 header migration across the workspace: 942 files rewritten
15
14
  <item>RFC-1097: sweep — packages/forge + services clean
16
15
 
17
16
  Sweep batch 2: real KEY_DECISIONS on 10 files, expanded purposes (CONTRACT-02/PURPOSE-02), headers on mission/index + gen-upstreams, sanitizeItemText in summary.record (literal Compass tags corrupted history), excludedPaths for wrangler types, test-fixtures testPattern. forge+services now 0 diagnostics under --mode error.</item>
18
- <history>RFC-0303, RFC-0722, RFC-0755</history>
17
+ <item>RFC-1271: V-43 verificationTier enum check; V-23 archive exemption (isArchived paths skip evidence-presence — archive-freeze precedent).</item>
18
+ <history>RFC-0303, RFC-0722, RFC-0755, RFC-0795</history>
19
19
  </CHANGE_SUMMARY>
20
20
  */
21
21
 
@@ -28,13 +28,14 @@ import { parse as yamlParse } from "yaml";
28
28
  import { validateAcceptanceShape } from "../acceptance.ts";
29
29
  import type { ParsedRfc } from "../frontmatter-io.ts";
30
30
  import type { ReadAndParseRfcResult } from "../frontmatter-io.ts";
31
- import type { RfcStatus, RfcKind, RfcScope, Marker } from "../types.ts";
31
+ import type { RfcStatus, RfcKind, RfcScope, RfcVerificationTier, Marker } from "../types.ts";
32
32
  import {
33
33
  RFC_DIR,
34
34
  RFC_ID_PATTERN,
35
35
  RFC_STATUSES,
36
36
  RFC_KINDS,
37
37
  RFC_SCOPES,
38
+ RFC_VERIFICATION_TIERS,
38
39
  RFC_FULL_REQUIRED_SECTIONS,
39
40
  RFC_METADATA_CUTOFF,
40
41
  RFC_VERSION_BUMP_CUTOFF,
@@ -926,6 +927,20 @@ export async function validateSingleRfc(
926
927
  }
927
928
  }
928
929
 
930
+ // V-43: valid verificationTier (RFC-1271 — optional; absent is valid)
931
+ const verificationTier = fm["verificationTier"];
932
+ if (
933
+ verificationTier !== undefined &&
934
+ !RFC_VERIFICATION_TIERS.includes(verificationTier as RfcVerificationTier)
935
+ ) {
936
+ addViolation(
937
+ rfcId,
938
+ relFile,
939
+ "V-43",
940
+ `Invalid verificationTier "${String(verificationTier)}". Must be one of: ${RFC_VERIFICATION_TIERS.join(", ")}`,
941
+ );
942
+ }
943
+
929
944
  // V-15: title consistency
930
945
  const titleStr = String(fm["title"] ?? "");
931
946
  const headingMatch = body.match(/^#\s+(?:RFC-\d{4}:\s*)?(.+)$/m);
@@ -1106,9 +1121,12 @@ export async function validateSingleRfc(
1106
1121
  }
1107
1122
 
1108
1123
  // V-23: verification evidence for post-cutoff, probe-bearing, implemented RFCs
1124
+ // Skip for archived RFCs — archival freezes the document; its envelope records
1125
+ // the state at stamp time and probe decay over moved/renamed paths is expected
1126
+ // historical drift, not actionable debt (precedent: V-13/V-15 archive skips).
1109
1127
  const createdAtStr = String(fm["createdAt"] ?? "");
1110
1128
  const hasProbes = Array.isArray(fm["acceptance"]) && (fm["acceptance"] as unknown[]).length > 0;
1111
- if (createdAtStr >= RFC_METADATA_CUTOFF && hasProbes && status === "implemented") {
1129
+ if (!isArchived && createdAtStr >= RFC_METADATA_CUTOFF && hasProbes && status === "implemented") {
1112
1130
  const slug = rfcId.toLowerCase();
1113
1131
  const evidenceRelPath = path.join(RFC_DIR, "verification", `${slug}.generated.yaml`);
1114
1132
  const evidenceAbsPath = path.join(workspaceRoot, evidenceRelPath);
@@ -52,15 +52,24 @@ appsImpacted: []
52
52
  packagesImpacted: []
53
53
  successSignals: []
54
54
  nonGoals: []
55
+ # RFC-1271: Verification tier declares the expected rigor of the acceptance
56
+ # portfolio — standard (default) | high | formal. Policy-level signal reviewed
57
+ # at acceptance; tier-to-portfolio guidance lives in
58
+ # packages/forge/skills/_shared/agent-operating-model.md.
59
+ # verificationTier: standard
55
60
  # OPTIONAL machine-checkable acceptance probes, executed on-demand
56
61
  # via `pnpm exec forge rfc.acceptance.run --id <this-rfc-id>` (never
57
62
  # automatically inside build pipelines).
63
+ # RFC-1271: a probe MAY declare `expectationSource` — who authored the
64
+ # expected result: self | requirement | independent | external — and
65
+ # `limitations`, a free-text caveat about coverage gaps. Both optional.
58
66
  # acceptance:
59
67
  # - probe: run
60
68
  # criterion: AC-1
61
- # command: "pnpm exec forge some.command.validate"
69
+ # command: "werkstatt run some.command.validate"
62
70
  # expect:
63
71
  # exitCode: 0
72
+ # expectationSource: independent
64
73
  # - probe: file-exists
65
74
  # criterion: AC-2
66
75
  # path: "packages/my-package/src/some-new-module.ts"
@@ -234,6 +243,14 @@ interface ExampleResult {
234
243
  in the same commit.
235
244
  - Agents MUST NOT weaken or remove enforcement rules established by this RFC
236
245
  without a new RFC that supersedes it.
246
+ - Agents report completion with the RFC-1271 vocabulary: IMPLEMENTED (code
247
+ landed), VERIFIED (independent probes pass), ACCEPTED (human/contract
248
+ acceptance), RELEASED (shipped to consumers). Do not claim a later state
249
+ than the evidence supports.
250
+ - Verification follows the portfolio model in
251
+ packages/forge/skills/_shared/agent-operating-model.md — TDD is one tool,
252
+ not a mandate; proportionate evidence (probes, tests, manual checks)
253
+ is required.
237
254
  - If implementation reveals an invariant conflict, run
238
255
  `pnpm exec forge rfc.supersede.propose --id <this-rfc-id> --reason "..." --invariant "DNA-N"`
239
256
  instead of working around it.