@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
@@ -7,13 +7,11 @@
7
7
  </non-goals>
8
8
  </MODULE_CONTRACT>
9
9
  <CHANGE_SUMMARY>
10
- <item>RFC-1097: sweep — werkstatt-engine clean
11
-
12
- Sweep batch 4: 73 Compass headers on headerless engine files (certification, component-runtime, isolation, evolution, testing), real KEY_DECISIONS on 75 files (kernel, cache, dht, swim, gitmesh, runtime), ~80 purpose expansions (CONTRACT-02/PURPOSE-02), non-goals on 13 CONTRACT-03 files, CS-07 history literal fix repo-wide (253 files). Policy: .template.ts/.template.astro excludedPaths. werkstatt-engine now 0 diagnostics.</item>
13
10
  <item>RFC-1173: declare mutatesState on all kernel commands — collectDeclarationDiagnostics emits error-severity MUTATES-STATE-DECLARED, command.manifest.validate is the blocking consumer in packages.check, sweep declares the flag on every command definition (factories hardcode false for read-only check specs)</item>
14
11
  <item>RFC-1231: rfc.verification.refresh gains acceptsAllFlag: true — the declared --all flag is now reachable via werkstatt run (consumed selector re-injected as flags.all after the gate).</item>
15
12
  <item>RFC-1237: honor dry-run via context.dryRun across kernel commands; verification envelopes keep emit-canonical ownership</item>
16
13
  <item>RFC-1249: wire werkstatt.commands.validate into packages.check + retire CMD-OUTPUT debt</item>
14
+ <item>RFC-1271: review wave — deep probe normalization, malformed-envelope fail-closed, post-stamp re-emit, honest repair hints</item>
17
15
  <history>RFC-0260, RFC-0795, RFC-1097</history>
18
16
  </CHANGE_SUMMARY>
19
17
  */
@@ -268,6 +266,11 @@ export async function createForgeRfcModule(): Promise<ForgeModule> {
268
266
  kind: "boolean",
269
267
  description: "Run probes and report results without writing envelope files.",
270
268
  },
269
+ check: {
270
+ kind: "boolean",
271
+ description:
272
+ "RFC-1271: recompute evidence and compare the committed envelope against a fresh run on non-volatile fields (rfcFileHash, acceptanceHash, probes[].ok, probes.length, overall). Writes nothing; exits 1 on divergence or a missing envelope — detects forged/hand-edited evidence.",
273
+ },
271
274
  concurrency: {
272
275
  kind: "string",
273
276
  description:
@@ -456,11 +459,14 @@ export async function createForgeRfcModule(): Promise<ForgeModule> {
456
459
  description:
457
460
  "RFC-0476: the exclusive atomic path for accepted → implemented transitions. " +
458
461
  "Verifies preconditions (accepted status, checked+evidenced criteria, clean tree, " +
459
- "reachable RFC-referencing commit, passing probe evidence) then atomically sets " +
460
- "status: implemented, implementedAt, and updatedAt. Use --dry-run to preview. Required flags: `--id`.",
462
+ "reachable RFC-referencing commit, passing probe evidence, fresh evidence hashes — " +
463
+ "RFC-IMP-09 stale-evidence gate from RFC-1271) then atomically sets " +
464
+ "status: implemented, implementedAt, and updatedAt. For probe-bearing RFCs the " +
465
+ "evidence envelope is re-emitted post-mutation so it binds the implemented-state " +
466
+ "file (RFC-1271). Use --dry-run to preview. Required flags: `--id`.",
461
467
  scope: "workspace",
462
468
  mutatesState: true,
463
- writes: ["docs/rfcs/**/*.md"],
469
+ writes: ["docs/rfcs/**/*.md", "docs/rfcs/verification/*.generated.yaml"],
464
470
  generates: [],
465
471
  reads: ["docs/rfcs/**/*.md", "docs/rfcs/verification/*.generated.yaml"],
466
472
  cacheable: false,
package/os/rfc/types.ts CHANGED
@@ -12,7 +12,6 @@
12
12
  * </non-goals>
13
13
  * </MODULE_CONTRACT>
14
14
  * * <CHANGE_SUMMARY>
15
- <item>RFC-0998: added TestProbe and JsonSchemaProbe to AcceptanceProbe union for test and json-schema acceptance probe kinds.</item>
16
15
  <item>RFC-0999: added lastRefreshedAt to VerificationEvidence; added RfcVerificationRefreshResult interface.</item>
17
16
  <item>RFC-1097: step 6 — compass.migrate codemod run
18
17
 
@@ -21,7 +20,8 @@ Mechanical v1 to v2 header migration across the workspace: 942 files rewritten
21
20
 
22
21
  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>
23
22
  <item>RFC-1249: wire werkstatt.commands.validate into packages.check + retire CMD-OUTPUT debt</item>
24
- <history>RFC-0465, RFC-0478, RFC-0480, RFC-0795</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-0465, RFC-0478, RFC-0480, RFC-0795, RFC-0998</history>
25
25
  </CHANGE_SUMMARY>
26
26
  ***************************************************************/
27
27
 
@@ -88,6 +88,36 @@ export const RFC_KINDS: readonly RfcKind[] = [
88
88
  export type RfcScope = "app" | "workspace";
89
89
 
90
90
  export const RFC_SCOPES: readonly RfcScope[] = ["app", "workspace"] as const; // ─── Frontmatter ─────────────────────────────────────────────────────────────
91
+
92
+ /**
93
+ * RFC-1271: optional verification rigor declaration — standard (default)
94
+ * checks, high (adds negative-path + independent verification where it
95
+ * genuinely reduces risk), formal (opt-in formal/property methods for
96
+ * precisely specifiable properties). Tier semantics live in
97
+ * `.agents/skills/_shared/agent-operating-model.md`.
98
+ */
99
+ export type RfcVerificationTier = "standard" | "high" | "formal";
100
+
101
+ export const RFC_VERIFICATION_TIERS: readonly RfcVerificationTier[] = [
102
+ "standard",
103
+ "high",
104
+ "formal",
105
+ ] as const;
106
+
107
+ /**
108
+ * RFC-1271: where a check's expected result originates. `self` is
109
+ * implementer-derived (diagnostic, not sole proof); `requirement` follows an
110
+ * accepted requirement; `independent` is fixed before/independently of the
111
+ * implementation; `external` comes from an authoritative external system.
112
+ */
113
+ export type RfcExpectationSource = "self" | "requirement" | "independent" | "external";
114
+
115
+ export const RFC_EXPECTATION_SOURCES: readonly RfcExpectationSource[] = [
116
+ "self",
117
+ "requirement",
118
+ "independent",
119
+ "external",
120
+ ] as const;
91
121
  /**
92
122
  * Tracks which OS commands this RFC adds, changes, or removes.
93
123
  * Used by rfc.validate to cross-check that proposed commands
@@ -269,7 +299,12 @@ export interface RfcFrontmatter {
269
299
  * site-kernel CLI itself (string must start with "site-kernel ") — no
270
300
  * arbitrary shell, keeping the probe surface auditable and platform-independent.
271
301
  */
272
- export type AcceptanceProbe =
302
+ export interface AcceptanceProbeMeta {
303
+ expectationSource?: RfcExpectationSource;
304
+ limitations?: string;
305
+ }
306
+
307
+ export type AcceptanceProbe = (
273
308
  | { probe: "run"; command: string; expect: { exitCode: number }; criterion?: string }
274
309
  | { probe: "file-exists"; path: string; criterion?: string }
275
310
  | { probe: "file-contains"; path: string; pattern: string; criterion?: string }
@@ -300,7 +335,9 @@ export type AcceptanceProbe =
300
335
  artifact: string;
301
336
  schemaInline: Record<string, unknown>;
302
337
  criterion?: string;
303
- };
338
+ }
339
+ ) &
340
+ AcceptanceProbeMeta;
304
341
 
305
342
  export interface ProbeResult {
306
343
  probe: AcceptanceProbe;
@@ -357,6 +394,9 @@ export interface RfcVerificationEmitResult {
357
394
  skipped: Array<{ rfcId: string; reason: "no-probes" }>;
358
395
  diagnostics: Diagnostic[];
359
396
  delta?: VerificationDelta;
397
+ /** RFC-1271 `--check`: committed-vs-fresh comparison per RFC — populated
398
+ * only in check mode; `emitted` stays empty (nothing is written). */
399
+ check?: Array<{ rfcId: string; match: boolean; mismatches: string[] }>;
360
400
  }
361
401
 
362
402
  export interface RfcVerificationRefreshResult {
@@ -559,6 +599,7 @@ export interface RfcImplementStampData {
559
599
  stampedAt: string;
560
600
  criteriaChecked: number;
561
601
  evidencePath?: string;
602
+ evidenceReEmitted?: boolean;
562
603
  metricsPath?: string;
563
604
  }
564
605
 
@@ -570,7 +611,8 @@ export type RfcImplementStampRule =
570
611
  | "RFC-IMP-05"
571
612
  | "RFC-IMP-06"
572
613
  | "RFC-IMP-07"
573
- | "RFC-IMP-08";
614
+ | "RFC-IMP-08"
615
+ | "RFC-IMP-09";
574
616
 
575
617
  export interface RfcImplementStampViolation {
576
618
  rule: RfcImplementStampRule;
@@ -630,6 +672,7 @@ export const RFC_KNOWN_KEYS: readonly string[] = [
630
672
  "satisfies",
631
673
  "specRef",
632
674
  "versionBump",
675
+ "verificationTier",
633
676
  "breaksC",
634
677
  "liveSpec",
635
678
  "dependsOn",
@@ -0,0 +1,201 @@
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 { parse as yamlParse, stringify as yamlStringify } from "yaml";
7
+
8
+ import { runRfcVerificationEmit } from "./verification-evidence.ts";
9
+ import type { ForgeCommandInput, ForgeRuntimeContext } from "../../src/types.ts";
10
+
11
+ const { mockRunProbe } = vi.hoisted(() => ({
12
+ mockRunProbe: vi.fn(),
13
+ }));
14
+
15
+ vi.mock("./acceptance.ts", () => ({
16
+ runProbe: mockRunProbe,
17
+ }));
18
+
19
+ const PROBE = { probe: "file-exists", path: "src/index.ts", criterion: "AC-1" };
20
+
21
+ const RFC_FRONTMATTER = (id: string, probes: Record<string, unknown>[]) => {
22
+ const probeYaml = probes
23
+ .map(
24
+ (p) =>
25
+ ` - probe: ${p.probe}\n path: ${p.path ?? ""}\n criterion: ${p.criterion ?? ""}`,
26
+ )
27
+ .join("\n");
28
+ return `---\nid: ${id}\ntitle: "Test ${id}"\nstatus: accepted\nkind: command\nscope: workspace\nowners:\n - architecture\ncreatedAt: 2026-01-01\nupdatedAt: 2026-01-01\nacceptance:\n${probeYaml}\n---\n\n# ${id}\n## Context\nTest.\n`;
29
+ };
30
+
31
+ const envelopePath = (root: string, rfcId: string) =>
32
+ path.join(root, "docs", "rfcs", "verification", `${rfcId.toLowerCase()}.generated.yaml`);
33
+
34
+ async function setupWorkspace(
35
+ rfcMarkdown: string,
36
+ ): Promise<{ workspaceRoot: string; cleanup: () => Promise<void> }> {
37
+ const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "tmp-rfc-check-"));
38
+ const rfcDir = path.join(tmpDir, "docs", "rfcs");
39
+ await fs.mkdir(rfcDir, { recursive: true });
40
+ await fs.writeFile(path.join(rfcDir, "rfc-0100-check.md"), rfcMarkdown);
41
+ return {
42
+ workspaceRoot: tmpDir,
43
+ cleanup: () => fs.rm(tmpDir, { recursive: true, force: true }),
44
+ };
45
+ }
46
+
47
+ function makeContext(workspaceRoot: string) {
48
+ return {
49
+ workspaceRoot,
50
+ logger: { info: () => {}, warn: () => {} },
51
+ outputFormat: "json" as const,
52
+ commandRegistry: undefined,
53
+ dryRun: false,
54
+ } as unknown as ForgeRuntimeContext;
55
+ }
56
+
57
+ const emit = (root: string, flags: Record<string, unknown>) =>
58
+ runRfcVerificationEmit(
59
+ { flags } as unknown as ForgeCommandInput,
60
+ makeContext(root),
61
+ );
62
+
63
+ /** Emit a real envelope so committed hashes match the fixture exactly. */
64
+ async function emitRealEnvelope(root: string) {
65
+ mockRunProbe.mockResolvedValue({ probe: PROBE, ok: true, detail: "exists" });
66
+ const r = await emit(root, { id: "RFC-0100" });
67
+ expect(r.exitCode).toBe(0);
68
+ const envelope = yamlParse(await fs.readFile(envelopePath(root, "RFC-0100"), "utf-8"));
69
+ return envelope as Record<string, unknown> & { probes: Record<string, unknown>[] };
70
+ }
71
+
72
+ async function rewriteEnvelope(root: string, mutate: (e: Record<string, unknown>) => void) {
73
+ const file = envelopePath(root, "RFC-0100");
74
+ const envelope = yamlParse(await fs.readFile(file, "utf-8")) as Record<string, unknown>;
75
+ mutate(envelope);
76
+ await fs.writeFile(file, yamlStringify(envelope) + "\n");
77
+ }
78
+
79
+ beforeEach(() => {
80
+ mockRunProbe.mockReset();
81
+ });
82
+
83
+ afterEach(() => {
84
+ vi.restoreAllMocks();
85
+ });
86
+
87
+ describe("rfc.verification.emit --check (RFC-1271)", () => {
88
+ test("clean envelope matches a fresh recomputation", async () => {
89
+ const md = RFC_FRONTMATTER("RFC-0100", [PROBE]);
90
+ const { workspaceRoot, cleanup } = await setupWorkspace(md);
91
+ try {
92
+ await emitRealEnvelope(workspaceRoot);
93
+ const result = await emit(workspaceRoot, { id: "RFC-0100", check: true });
94
+ expect(result.exitCode).toBe(0);
95
+ expect(result.data!.check).toEqual([
96
+ { rfcId: "RFC-0100", match: true, mismatches: [] },
97
+ ]);
98
+ // Nothing was written — emitted stays empty in check mode.
99
+ expect(result.data!.emitted).toHaveLength(0);
100
+ } finally {
101
+ await cleanup();
102
+ }
103
+ });
104
+
105
+ test("forged overall: pass → exit 1, names overall", async () => {
106
+ const md = RFC_FRONTMATTER("RFC-0100", [PROBE]);
107
+ const { workspaceRoot, cleanup } = await setupWorkspace(md);
108
+ try {
109
+ // Emit a FAILING envelope, then forge it to pass.
110
+ mockRunProbe.mockResolvedValue({ probe: PROBE, ok: false, detail: "missing" });
111
+ const emitted = await emit(workspaceRoot, { id: "RFC-0100" });
112
+ expect(emitted.exitCode).toBe(1);
113
+ await rewriteEnvelope(workspaceRoot, (e) => {
114
+ e["overall"] = "pass";
115
+ (e["probes"] as Record<string, unknown>[])[0]!["ok"] = true;
116
+ });
117
+
118
+ mockRunProbe.mockResolvedValue({ probe: PROBE, ok: false, detail: "missing" });
119
+ const result = await emit(workspaceRoot, { id: "RFC-0100", check: true });
120
+ expect(result.exitCode).toBe(1);
121
+ const entry = result.data!.check![0]!;
122
+ expect(entry.match).toBe(false);
123
+ expect(entry.mismatches).toContain("overall");
124
+ expect(entry.mismatches).toContain("probes[0].ok");
125
+ } finally {
126
+ await cleanup();
127
+ }
128
+ });
129
+
130
+ test("stale acceptanceHash (acceptance list changed post-emit) → exit 1", async () => {
131
+ const md = RFC_FRONTMATTER("RFC-0100", [PROBE]);
132
+ const { workspaceRoot, cleanup } = await setupWorkspace(md);
133
+ try {
134
+ await emitRealEnvelope(workspaceRoot);
135
+ // Retarget the probe's criterion — same key shape, different value.
136
+ const changed = RFC_FRONTMATTER("RFC-0100", [{ ...PROBE, criterion: "AC-9" }]);
137
+ await fs.writeFile(
138
+ path.join(workspaceRoot, "docs", "rfcs", "rfc-0100-check.md"),
139
+ changed,
140
+ );
141
+ const result = await emit(workspaceRoot, { id: "RFC-0100", check: true });
142
+ expect(result.exitCode).toBe(1);
143
+ const mismatches = result.data!.check![0]!.mismatches;
144
+ expect(mismatches).toContain("acceptanceHash");
145
+ expect(mismatches).toContain("rfcFileHash");
146
+ } finally {
147
+ await cleanup();
148
+ }
149
+ });
150
+
151
+ test("probe added post-emit → probes.length mismatch", async () => {
152
+ const md = RFC_FRONTMATTER("RFC-0100", [PROBE]);
153
+ const { workspaceRoot, cleanup } = await setupWorkspace(md);
154
+ try {
155
+ await emitRealEnvelope(workspaceRoot);
156
+ const changed = RFC_FRONTMATTER("RFC-0100", [
157
+ PROBE,
158
+ { probe: "file-exists", path: "src/other.ts", criterion: "AC-2" },
159
+ ]);
160
+ await fs.writeFile(
161
+ path.join(workspaceRoot, "docs", "rfcs", "rfc-0100-check.md"),
162
+ changed,
163
+ );
164
+ mockRunProbe.mockResolvedValue({ probe: PROBE, ok: true, detail: "exists" });
165
+ const result = await emit(workspaceRoot, { id: "RFC-0100", check: true });
166
+ expect(result.exitCode).toBe(1);
167
+ expect(result.data!.check![0]!.mismatches).toContain("probes.length");
168
+ } finally {
169
+ await cleanup();
170
+ }
171
+ });
172
+
173
+ test("hand-edited hash field (forged acceptanceHash value) → exit 1", async () => {
174
+ const md = RFC_FRONTMATTER("RFC-0100", [PROBE]);
175
+ const { workspaceRoot, cleanup } = await setupWorkspace(md);
176
+ try {
177
+ await emitRealEnvelope(workspaceRoot);
178
+ await rewriteEnvelope(workspaceRoot, (e) => {
179
+ e["acceptanceHash"] = "deadbeef";
180
+ });
181
+ const result = await emit(workspaceRoot, { id: "RFC-0100", check: true });
182
+ expect(result.exitCode).toBe(1);
183
+ expect(result.data!.check![0]!.mismatches).toContain("acceptanceHash");
184
+ } finally {
185
+ await cleanup();
186
+ }
187
+ });
188
+
189
+ test("missing envelope → exit 1, envelope-missing", async () => {
190
+ const md = RFC_FRONTMATTER("RFC-0100", [PROBE]);
191
+ const { workspaceRoot, cleanup } = await setupWorkspace(md);
192
+ try {
193
+ mockRunProbe.mockResolvedValue({ probe: PROBE, ok: true, detail: "exists" });
194
+ const result = await emit(workspaceRoot, { id: "RFC-0100", check: true });
195
+ expect(result.exitCode).toBe(1);
196
+ expect(result.data!.check![0]!.mismatches).toEqual(["envelope-missing"]);
197
+ } finally {
198
+ await cleanup();
199
+ }
200
+ });
201
+ });
@@ -20,6 +20,7 @@ shared emit-canonical serializer restoring the structured YAML marker-key
20
20
  header (generatedMarker/doNotEdit/ownerCommand/editInstead/regenerateCommand
21
21
  with "pnpm exec werkstatt run" prefix), also consumed by refresh.</item>
22
22
  <item>RFC-1249: wire werkstatt.commands.validate into packages.check + retire CMD-OUTPUT debt</item>
23
+ <item>RFC-1271: review wave — deep probe normalization, malformed-envelope fail-closed, post-stamp re-emit, honest repair hints</item>
23
24
  </CHANGE_SUMMARY>
24
25
  */
25
26
 
@@ -160,8 +161,27 @@ export function serializeEvidenceEnvelope(envelope: VerificationEvidence): strin
160
161
  })}\n`;
161
162
  }
162
163
 
163
- function normalizeProbes(probes: AcceptanceProbe[]): string {
164
- return JSON.stringify(probes, Object.keys(probes[0] ?? {}).sort());
164
+ /**
165
+ * RFC-1271: canonical serialization for acceptanceHash. Keys are sorted
166
+ * recursively at every depth and NO key is filtered — every probe field
167
+ * (top-level or nested inside expect/schemaInline) must reach the hash,
168
+ * otherwise retargeting a nested probe field leaves the hash unchanged.
169
+ * Exported so rfc.implement.stamp recomputes with the identical function.
170
+ */
171
+ export function normalizeProbes(probes: AcceptanceProbe[]): string {
172
+ return JSON.stringify(sortKeysDeep(probes));
173
+ }
174
+
175
+ function sortKeysDeep(value: unknown): unknown {
176
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
177
+ if (value !== null && typeof value === "object") {
178
+ return Object.fromEntries(
179
+ Object.entries(value as Record<string, unknown>)
180
+ .sort(([a], [b]) => a.localeCompare(b))
181
+ .map(([k, v]) => [k, sortKeysDeep(v)]),
182
+ );
183
+ }
184
+ return value;
165
185
  }
166
186
 
167
187
  export function buildEvidenceEnvelope(
@@ -191,6 +211,32 @@ export function buildEvidenceEnvelope(
191
211
  };
192
212
  }
193
213
 
214
+ /**
215
+ * RFC-1271 `--check`: compare a committed envelope against a fresh
216
+ * computation on non-volatile fields only. Volatile per-run metadata
217
+ * (emittedAt, lastRefreshedAt, durationMs, commit, workingTreeDirty,
218
+ * kernelVersion, probe details) is per-run evidence context, not evidence
219
+ * identity — it is intentionally not compared.
220
+ */
221
+ export function checkEvidenceEnvelope(
222
+ committed: Partial<VerificationEvidence>,
223
+ fresh: VerificationEvidence,
224
+ ): string[] {
225
+ const mismatches: string[] = [];
226
+ if (committed.rfcFileHash !== fresh.rfcFileHash) mismatches.push("rfcFileHash");
227
+ if (committed.acceptanceHash !== fresh.acceptanceHash) mismatches.push("acceptanceHash");
228
+ const committedProbes = committed.probes ?? [];
229
+ if (committedProbes.length !== fresh.probes.length) {
230
+ mismatches.push("probes.length");
231
+ } else {
232
+ fresh.probes.forEach((rec, i) => {
233
+ if (committedProbes[i]?.ok !== rec.ok) mismatches.push(`probes[${i}].ok`);
234
+ });
235
+ }
236
+ if (committed.overall !== fresh.overall) mismatches.push("overall");
237
+ return mismatches;
238
+ }
239
+
194
240
  export async function runRfcVerificationEmit(
195
241
  input: ForgeCommandInput,
196
242
  context: ForgeRuntimeContext,
@@ -199,6 +245,7 @@ export async function runRfcVerificationEmit(
199
245
  const { workspaceRoot, logger, outputFormat } = context;
200
246
  const rfcDirPath = join(workspaceRoot, RFC_DIR);
201
247
  const targetId = input.flags["id"] as string | undefined;
248
+ const checkOnly = input.flags["check"] === true;
202
249
  const targetStatus = input.flags["status"] as string | undefined;
203
250
  // RFC-1237: consumeCommonFlags strips --dry-run into context.dryRun before
204
251
  // dispatch — the input.flags read stays for direct/programmatic callers.
@@ -235,13 +282,14 @@ export async function runRfcVerificationEmit(
235
282
  }
236
283
  const kernelVersion = await getKernelVersion(workspaceRoot);
237
284
  const verificationDirAbs = join(workspaceRoot, VERIFICATION_DIR);
238
- if (!dryRun) await io.mkdir(verificationDirAbs);
285
+ if (!dryRun && !checkOnly) await io.mkdir(verificationDirAbs);
239
286
 
240
287
  const processFile = async (
241
288
  fileName: string,
242
289
  ): Promise<{
243
290
  emittedEntry?: NonNullable<RfcVerificationEmitResult["emitted"]>[number];
244
291
  skippedEntry?: NonNullable<RfcVerificationEmitResult["skipped"]>[number];
292
+ checkEntry?: NonNullable<RfcVerificationEmitResult["check"]>[number];
245
293
  diagnostic?: Diagnostic;
246
294
  }> => {
247
295
  const parsedFile = await readAndParseRfc(rfcDirPath, fileName);
@@ -293,6 +341,21 @@ export async function runRfcVerificationEmit(
293
341
  const evidenceRelPath = join(VERIFICATION_DIR, evidenceFileName);
294
342
  const evidenceAbsPath = join(workspaceRoot, evidenceRelPath);
295
343
 
344
+ // RFC-1271 --check: same probe run as emit, but the committed envelope is
345
+ // compared to the fresh computation and nothing is written. A missing
346
+ // envelope is itself a divergence.
347
+ if (checkOnly) {
348
+ let committed: Partial<VerificationEvidence> | null = null;
349
+ try {
350
+ committed = yamlParse(await io.readFile(evidenceAbsPath)) as Partial<VerificationEvidence>;
351
+ } catch {
352
+ // No committed envelope.
353
+ }
354
+ const mismatches =
355
+ committed === null ? ["envelope-missing"] : checkEvidenceEnvelope(committed, envelope);
356
+ return { checkEntry: { rfcId, match: mismatches.length === 0, mismatches } };
357
+ }
358
+
296
359
  // Committed-envelope baseline for the sweep delta — lets a fail-heavy run
297
360
  // separate still-failing drift from fresh regressions without git diff.
298
361
  let previousOverall: "pass" | "fail" | undefined;
@@ -340,13 +403,15 @@ export async function runRfcVerificationEmit(
340
403
  };
341
404
 
342
405
  const results = await mapWithConcurrency(allFiles, concurrency, processFile);
406
+ const checked: NonNullable<RfcVerificationEmitResult["check"]> = [];
343
407
  for (const r of results) {
344
408
  if (r.emittedEntry) emitted.push(r.emittedEntry);
345
409
  if (r.skippedEntry) skipped.push(r.skippedEntry);
410
+ if (r.checkEntry) checked.push(r.checkEntry);
346
411
  if (r.diagnostic) diagnostics.push(r.diagnostic);
347
412
  }
348
413
 
349
- const hasFailures = emitted.some((e) => e.overall === "fail");
414
+ const hasFailures = emitted.some((e) => e.overall === "fail") || checked.some((c) => !c.match);
350
415
  const status: RfcVerificationEmitResult["status"] = hasFailures ? "fail" : "pass";
351
416
  const delta = {
352
417
  recovered: emitted
@@ -369,8 +434,11 @@ export async function runRfcVerificationEmit(
369
434
  skipped,
370
435
  diagnostics,
371
436
  delta,
437
+ ...(checkOnly ? { check: checked } : {}),
372
438
  },
373
439
  exitCode: hasFailures ? 1 : 0,
374
- summary: `rfc.verification.emit: ${emitted.length} emitted, ${skipped.length} skipped${deltaSummary}${dryRun ? ", dry-run" : ""}`,
440
+ summary: checkOnly
441
+ ? `rfc.verification.emit --check: ${checked.filter((c) => c.match).length} match, ${checked.filter((c) => !c.match).length} diverged, ${skipped.length} skipped`
442
+ : `rfc.verification.emit: ${emitted.length} emitted, ${skipped.length} skipped${deltaSummary}${dryRun ? ", dry-run" : ""}`,
375
443
  };
376
444
  }
@@ -0,0 +1,61 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, test } from "vitest";
3
+
4
+ import { byteHashHex, normalizeProbes } from "./verification-evidence.ts";
5
+ import type { AcceptanceProbe } from "./types.ts";
6
+
7
+ const hash = (probes: AcceptanceProbe[]) => byteHashHex(normalizeProbes(probes));
8
+
9
+ describe("normalizeProbes — acceptanceHash identity (RFC-1271)", () => {
10
+ test("key order inside a probe does not change the hash", () => {
11
+ const a = [
12
+ { probe: "file-exists", path: "src/a.ts", criterion: "AC-1" },
13
+ ] as AcceptanceProbe[];
14
+ const b = [
15
+ { criterion: "AC-1", probe: "file-exists", path: "src/a.ts" },
16
+ ] as unknown as AcceptanceProbe[];
17
+ expect(hash(a)).toBe(hash(b));
18
+ });
19
+
20
+ test("a field unique to a LATER probe changes the hash (union-keys regression)", () => {
21
+ // Regression: whitelisting keys from probes[0] only drops criterion/
22
+ // pattern fields that exist solely on later probes — a retarget passes
23
+ // undetected.
24
+ const base = [
25
+ { probe: "file-exists", path: "src/a.ts" },
26
+ { probe: "file-contains", path: "src/b.ts", pattern: "alpha", criterion: "AC-2" },
27
+ ] as AcceptanceProbe[];
28
+ const retargeted = [
29
+ { probe: "file-exists", path: "src/a.ts" },
30
+ { probe: "file-contains", path: "src/b.ts", pattern: "alpha", criterion: "AC-9" },
31
+ ] as AcceptanceProbe[];
32
+ expect(hash(base)).not.toBe(hash(retargeted));
33
+ });
34
+
35
+ test("a nested expect/schemaInline field change changes the hash (deep-bind regression)", () => {
36
+ // Regression: an array replacer whitelists keys recursively — nested
37
+ // probe interiors (expect.exitCode, schemaInline) serialize as {} and
38
+ // never reach acceptanceHash.
39
+ const base = [
40
+ { probe: "run", command: "werkstatt run x.validate", expect: { exitCode: 0 }, criterion: "AC-1" },
41
+ ] as AcceptanceProbe[];
42
+ const nestedChanged = [
43
+ { probe: "run", command: "werkstatt run x.validate", expect: { exitCode: 1 }, criterion: "AC-1" },
44
+ ] as AcceptanceProbe[];
45
+ expect(hash(base)).not.toBe(hash(nestedChanged));
46
+
47
+ const schemaA = [
48
+ { probe: "json-schema", artifact: "out.json", schemaInline: { type: "object" } },
49
+ ] as AcceptanceProbe[];
50
+ const schemaB = [
51
+ { probe: "json-schema", artifact: "out.json", schemaInline: { type: "array" } },
52
+ ] as AcceptanceProbe[];
53
+ expect(hash(schemaA)).not.toBe(hash(schemaB));
54
+ });
55
+
56
+ test("probe ordering changes the hash (list identity is ordered)", () => {
57
+ const p1 = { probe: "file-exists", path: "src/a.ts" } as AcceptanceProbe;
58
+ const p2 = { probe: "file-exists", path: "src/b.ts" } as AcceptanceProbe;
59
+ expect(hash([p1, p2])).not.toBe(hash([p2, p1]));
60
+ });
61
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warpgogol/forge",
3
- "version": "6.3.5",
3
+ "version": "7.0.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -0,0 +1,83 @@
1
+ # Agent Operating Model
2
+
3
+ Normative rules binding agent sessions in Forge consumers. Brief reminders live in generated `AGENTS.md`; this document is the detail layer. Mode of work and verification rigor are separate axes — pick both.
4
+
5
+ ## 1. Work modes
6
+
7
+ - **EXPLORE** — ideas, hypotheses, prototypes, technical research. The agent experiments freely inside an isolated scope within budget and authority. Full RFC, TDD, durable tests, and production polish are NOT required. The result is a reproducible demonstration, observations, limitations, and a disposition decision (adopt / park / discard). An experiment MUST NOT silently mutate production surfaces or count as accepted functionality — promotion requires the ROUTINE or GOVERNED path (exploration notes live in `docs/explorations/`).
8
+ - **ROUTINE** — small, local, reversible changes that touch no normative architecture, public contract, data schema, security surface, or Forge rule. Examples: local bugfix restoring intended behavior, content data correction, cosmetic cleanup, refactoring without behavior change. No new RFC/ADR is required beyond what standing policy already mandates; an authoritative task source, a clear expected result, and a proportionate check suffice. Do not create documents or plans for ceremony.
9
+ - **GOVERNED** — changes to architecture, public contracts, data schemas, security, critical algorithms, or the rules of Forge itself. Runs the existing RFC workflow; ADRs only for decisions genuinely worth keeping separate. An accepted RFC, not agent judgment, is the authority here.
10
+
11
+ ## 2. Autonomy by default
12
+
13
+ An agent performs autonomously every action that is simultaneously: within granted authority, compliant with accepted requirements, reversible or safely isolated, free of unacceptable external effects, and free of unknown business decisions.
14
+
15
+ No permission is needed for: reading files, analysis, planning, editing permitted files, local verification, fixing the agent's own mistakes, or choosing libraries / internal code organization / helper names that can be decided on technical merit. Tool availability is not blanket authority for every use of that tool.
16
+
17
+ ## 3. Escalation boundaries — ask the operator ONLY when
18
+
19
+ 1. Ambiguity changes user-visible behavior, business meaning, or an acceptance criterion.
20
+ 2. A previously accepted normative decision must be changed.
21
+ 3. An irreversible or significant external action is required.
22
+ 4. There is material risk to security, privacy, or data preservation.
23
+ 5. Additional authority, spend, or infrastructure is needed.
24
+ 6. Standing repository policy explicitly requires human sign-off.
25
+
26
+ Research available sources and resolve ambiguity yourself first, when doing so does not change operator intent. When a decision is genuinely required, batch related questions into ONE appeal with a recommended option, alternatives, and consequences — never a drip of small questions. While awaiting an answer, continue the independent safe parts of the work.
27
+
28
+ ## 4. Forbidden without explicit authority
29
+
30
+ - destroying user data, cleaning unknown files or working directories, force-resetting or overwriting others' work;
31
+ - production data changes, deployments, releases, publishing, payments, emails — any real-world side effect;
32
+ - disabling or weakening protective checks, changing access policies, expanding the agent's own authority;
33
+ - accepting normative decisions on the operator's behalf — RFC/ADR status transitions and `reviewers` are human-set; the agent implements `accepted`, never self-accepts `draft`.
34
+
35
+ Ordinary file deletion/rename inside an agreed task is allowed when reversible, destroying nobody's work, and visible in the diff. `git clean`, `reset --hard`, force-push and equivalents over unknown state need exact permission. Text rules are backed by technical guards (`git-wrapper.sh`, hooks, `ecosystem.commit` gates, `generated.edit.guard`) — do not treat their absence in a given sandbox as permission.
36
+
37
+ ## 5. Requirements are not substitutable
38
+
39
+ Keep separate: operator intent, accepted requirements, accepted decisions, agent assumptions, proposed requirement changes, observed behavior. Never present the agent's interpretation as an operator decision. Never edit acceptance criteria, normative specs, expected results, or check conditions to ease implementation — if a requirement is wrong or infeasible, propose its change through the decision machinery (amendment / `rfc.supersede.propose`), don't work around it.
40
+
41
+ ## 6. Verification portfolio — TDD is not mandatory
42
+
43
+ Choose checks by the nature of the change and the risk of error, not by methodology fashion. Allowed methods: existing unit/integration tests, targeted regression checks, API/CLI probes, real user E2E flows, browser tooling, end-state data checks, static analysis and type checking, property-based testing and fuzzing, log/trace/telemetry analysis, model checking, formal verification.
44
+
45
+ New automated tests need a concrete reason: a protected requirement, a reproduced defect, a significant invariant, or regression risk. Test count, coverage percentage, green CI, clean logs, and a successful boot are NOT standalone evidence that requirements are met. Logs and traces confirm concrete observable properties; "no errors in logs" alone confirms nothing. Use E2E for important end-to-end and negative scenarios; do not build E2E infrastructure for a local fix. Existing mandatory checks MUST NOT be deleted, bypassed, or weakened for green status.
46
+
47
+ ## 7. Risk tiers
48
+
49
+ - **STANDARD** — ordinary local changes: relevant existing checks, build/type/static checks, and observed verification of the changed behavior.
50
+ - **HIGH** — security, access rights, contracts, data, migrations, critical integrations, significant external effects: additionally verify negative scenarios, boundaries, invariants, rollback, compatibility. Use independent verification where it genuinely reduces risk (e.g. clean-context review).
51
+ - **FORMAL** — only for important, stable, precisely specifiable properties where formalization cost is justified. Tool by task: Lean (math/inductive), Dafny (algorithm correctness), Verus (supported Rust), TLA+/model checking (protocols/concurrency), property/fuzz (broad input classes without full proof). Not installed globally, never mandatory for ordinary changes; record spec, assumptions, proof scope, tool version, and unverified runtime boundaries — a successful proof does not prove business intent or the whole system.
52
+
53
+ ## 8. Expectation sources
54
+
55
+ Every significant check has an expectation origin:
56
+
57
+ - **self** — formulated by the implementer from their own implementation. Useful for diagnostics; not sole proof of a contested business requirement.
58
+ - **requirement** — follows from an accepted requirement, invariant, or standard.
59
+ - **independent** — fixed before implementation or prepared independently of the implementer.
60
+ - **external** — an authoritative external system, reference data, or observable environment supplies ground truth.
61
+
62
+ Another AI agent is not automatically an independent verifier — independence is defined by criterion origin, access to normative sources, and real ability to catch the executor's error. Declare the class on probes via `expectationSource:`; declare what a check does not cover via `limitations:`.
63
+
64
+ ## 9. Evidence trust boundary
65
+
66
+ An agent's claim that a check ran is not a substitute for the tool's result. Evidence binds: requirement identifier → expected-result source → verified code version → applicable criteria/checks → method and executed command → environment/tool → observed result → machine-artifact link → check limitations. Group checks into one reproducible result; no per-action receipts for trivia.
67
+
68
+ A local file written by the agent is not trusted proof merely because it contains `passed` or a hash. Trusted verification runs through mechanisms whose integrity the checked agent cannot arbitrarily alter — the committed-envelope chain (`rfc.verification.emit` + `rfc.implement.stamp` staleness gate + `emit --check` recompute), generated-file guards, protected CI gates, branch policies, trusted runners. Hash freshness binds the envelope to the current bytes — it does not by itself prove the recorded results are true: a forged `overall: pass` with recomputed hashes stays undetected until `emit --check` re-executes the probes, so the `--check` recompute path and protected CI are what bind results to reality, not the envelope alone. Results on a dirty worktree are preliminary; authoritative results bind to an exactly identified source state. When sources, criteria, probes, check config, or assumptions change, affected evidence is stale — re-verify; when applicability cannot be proven, treat it as stale. A change to the verification mechanism inside a PR must not let that PR silently weaken its own acceptance.
69
+
70
+ ## 10. Completion vocabulary
71
+
72
+ Report completion by state, never by the word "done":
73
+
74
+ - **IMPLEMENTED** — the change is implemented.
75
+ - **VERIFIED** — required checks ran against the corresponding version.
76
+ - **ACCEPTED** — the result was accepted by the authorized mechanism or person.
77
+ - **RELEASED** — the release actually happened.
78
+
79
+ Never claim a check you lack an actual run result for; never claim release or merge that did not occur; do not flood the operator with a log of intermediate technical actions.
80
+
81
+ ## 11. Change control
82
+
83
+ Weakening this model or its enforcement mechanics requires a superseding RFC. Cost is a first-class concern: any new gate or workflow whose cost exceeds its measurable benefit and defended risk must be reviewed for simplification or removal.