@warpgogol/forge 10.0.0 → 10.1.1

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 (136) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/bin/cli.ts +17 -0
  3. package/dist/bin/cli.js +17 -0
  4. package/dist/bin/cli.js.map +1 -1
  5. package/dist/os/rfc/probe-batch.d.ts.map +1 -1
  6. package/dist/os/rfc/probe-batch.js +13 -6
  7. package/dist/os/rfc/probe-batch.js.map +1 -1
  8. package/dist/src/contract/core-nodes.d.ts +8 -0
  9. package/dist/src/contract/core-nodes.d.ts.map +1 -0
  10. package/dist/src/contract/core-nodes.js +101 -0
  11. package/dist/src/contract/core-nodes.js.map +1 -0
  12. package/dist/src/contract/evaluator.d.ts +48 -0
  13. package/dist/src/contract/evaluator.d.ts.map +1 -0
  14. package/dist/src/contract/evaluator.js +158 -0
  15. package/dist/src/contract/evaluator.js.map +1 -0
  16. package/dist/src/contract/evidence-store.d.ts +17 -0
  17. package/dist/src/contract/evidence-store.d.ts.map +1 -0
  18. package/dist/src/contract/evidence-store.js +113 -0
  19. package/dist/src/contract/evidence-store.js.map +1 -0
  20. package/dist/src/contract/executors/zero-deps.d.ts +3 -0
  21. package/dist/src/contract/executors/zero-deps.d.ts.map +1 -0
  22. package/dist/src/contract/executors/zero-deps.js +88 -0
  23. package/dist/src/contract/executors/zero-deps.js.map +1 -0
  24. package/dist/src/contract/fingerprint.d.ts +34 -0
  25. package/dist/src/contract/fingerprint.d.ts.map +1 -0
  26. package/dist/src/contract/fingerprint.js +153 -0
  27. package/dist/src/contract/fingerprint.js.map +1 -0
  28. package/dist/src/contract/graph.d.ts +23 -0
  29. package/dist/src/contract/graph.d.ts.map +1 -0
  30. package/dist/src/contract/graph.js +158 -0
  31. package/dist/src/contract/graph.js.map +1 -0
  32. package/dist/src/contract/migration-map.d.ts +51 -0
  33. package/dist/src/contract/migration-map.d.ts.map +1 -0
  34. package/dist/src/contract/migration-map.js +130 -0
  35. package/dist/src/contract/migration-map.js.map +1 -0
  36. package/dist/src/contract/types.d.ts +108 -0
  37. package/dist/src/contract/types.d.ts.map +1 -0
  38. package/dist/src/contract/types.js +23 -0
  39. package/dist/src/contract/types.js.map +1 -0
  40. package/dist/src/integration/drain.d.ts +37 -0
  41. package/dist/src/integration/drain.d.ts.map +1 -0
  42. package/dist/src/integration/drain.js +235 -0
  43. package/dist/src/integration/drain.js.map +1 -0
  44. package/dist/src/integration/enqueue.d.ts +30 -0
  45. package/dist/src/integration/enqueue.d.ts.map +1 -0
  46. package/dist/src/integration/enqueue.js +64 -0
  47. package/dist/src/integration/enqueue.js.map +1 -0
  48. package/dist/src/integration/gitops.d.ts +33 -0
  49. package/dist/src/integration/gitops.d.ts.map +1 -0
  50. package/dist/src/integration/gitops.js +128 -0
  51. package/dist/src/integration/gitops.js.map +1 -0
  52. package/dist/src/integration/lease.d.ts +16 -0
  53. package/dist/src/integration/lease.d.ts.map +1 -0
  54. package/dist/src/integration/lease.js +140 -0
  55. package/dist/src/integration/lease.js.map +1 -0
  56. package/dist/src/integration/materialize.d.ts +7 -0
  57. package/dist/src/integration/materialize.d.ts.map +1 -0
  58. package/dist/src/integration/materialize.js +34 -0
  59. package/dist/src/integration/materialize.js.map +1 -0
  60. package/dist/src/integration/store.d.ts +21 -0
  61. package/dist/src/integration/store.d.ts.map +1 -0
  62. package/dist/src/integration/store.js +131 -0
  63. package/dist/src/integration/store.js.map +1 -0
  64. package/dist/src/integration/types.d.ts +71 -0
  65. package/dist/src/integration/types.d.ts.map +1 -0
  66. package/dist/src/integration/types.js +18 -0
  67. package/dist/src/integration/types.js.map +1 -0
  68. package/dist/src/onboarding/init.d.ts.map +1 -1
  69. package/dist/src/onboarding/init.js +4 -0
  70. package/dist/src/onboarding/init.js.map +1 -1
  71. package/dist/src/onboarding/upgrade.d.ts.map +1 -1
  72. package/dist/src/onboarding/upgrade.js +77 -2
  73. package/dist/src/onboarding/upgrade.js.map +1 -1
  74. package/dist/src/sdk/cli-bridge.d.ts +26 -0
  75. package/dist/src/sdk/cli-bridge.d.ts.map +1 -0
  76. package/dist/src/sdk/cli-bridge.js +89 -0
  77. package/dist/src/sdk/cli-bridge.js.map +1 -0
  78. package/dist/src/sdk/context.d.ts +13 -0
  79. package/dist/src/sdk/context.d.ts.map +1 -0
  80. package/dist/src/sdk/context.js +128 -0
  81. package/dist/src/sdk/context.js.map +1 -0
  82. package/dist/src/sdk/hooks.d.ts +14 -0
  83. package/dist/src/sdk/hooks.d.ts.map +1 -0
  84. package/dist/src/sdk/hooks.js +35 -0
  85. package/dist/src/sdk/hooks.js.map +1 -0
  86. package/dist/src/sdk/loader.d.ts +26 -0
  87. package/dist/src/sdk/loader.d.ts.map +1 -0
  88. package/dist/src/sdk/loader.js +170 -0
  89. package/dist/src/sdk/loader.js.map +1 -0
  90. package/dist/src/sdk/scan.d.ts +16 -0
  91. package/dist/src/sdk/scan.d.ts.map +1 -0
  92. package/dist/src/sdk/scan.js +126 -0
  93. package/dist/src/sdk/scan.js.map +1 -0
  94. package/dist/src/sdk/skills-gen.d.ts +27 -0
  95. package/dist/src/sdk/skills-gen.d.ts.map +1 -0
  96. package/dist/src/sdk/skills-gen.js +87 -0
  97. package/dist/src/sdk/skills-gen.js.map +1 -0
  98. package/dist/src/sdk/types.d.ts +141 -0
  99. package/dist/src/sdk/types.d.ts.map +1 -0
  100. package/dist/src/sdk/types.js +34 -0
  101. package/dist/src/sdk/types.js.map +1 -0
  102. package/dist/src/utils/gitignore-entry.d.ts +3 -0
  103. package/dist/src/utils/gitignore-entry.d.ts.map +1 -0
  104. package/dist/src/utils/gitignore-entry.js +24 -0
  105. package/dist/src/utils/gitignore-entry.js.map +1 -0
  106. package/dist/src/utils/verifier-git.d.ts.map +1 -1
  107. package/dist/src/utils/verifier-git.js +18 -2
  108. package/dist/src/utils/verifier-git.js.map +1 -1
  109. package/os/rfc/probe-batch.ts +13 -6
  110. package/package.json +17 -1
  111. package/src/contract/core-nodes.ts +111 -0
  112. package/src/contract/evaluator.ts +207 -0
  113. package/src/contract/evidence-store.ts +119 -0
  114. package/src/contract/executors/zero-deps.ts +92 -0
  115. package/src/contract/fingerprint.ts +176 -0
  116. package/src/contract/graph.ts +181 -0
  117. package/src/contract/migration-map.ts +174 -0
  118. package/src/contract/types.ts +125 -0
  119. package/src/integration/drain.ts +323 -0
  120. package/src/integration/enqueue.ts +92 -0
  121. package/src/integration/gitops.ts +174 -0
  122. package/src/integration/lease.ts +144 -0
  123. package/src/integration/materialize.ts +40 -0
  124. package/src/integration/store.ts +153 -0
  125. package/src/integration/types.ts +79 -0
  126. package/src/onboarding/init.ts +4 -0
  127. package/src/onboarding/upgrade.ts +84 -1
  128. package/src/sdk/cli-bridge.ts +94 -0
  129. package/src/sdk/context.ts +135 -0
  130. package/src/sdk/hooks.ts +51 -0
  131. package/src/sdk/loader.ts +187 -0
  132. package/src/sdk/scan.ts +132 -0
  133. package/src/sdk/skills-gen.ts +104 -0
  134. package/src/sdk/types.ts +158 -0
  135. package/src/utils/gitignore-entry.ts +24 -0
  136. package/src/utils/verifier-git.ts +17 -2
@@ -0,0 +1,176 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Input fingerprinting for the contract-evidence graph (Werkstatt RFC-1646) —
5
+ canonical serialization, per-input-kind digest computation against a frozen
6
+ evaluation context, and the command-output deny-list. Nodes never read live
7
+ mutable state: git-ref inputs resolve exclusively from the change unit's
8
+ frozen values.
9
+ </purpose>
10
+ <non-goals>
11
+ <item>No scheduler logic — digests only; cone computation lives in the evaluator.</item>
12
+ </non-goals>
13
+ <CHANGE_SUMMARY>
14
+ <item>RFC-1646 (WP-3): initial fingerprinting machinery.</item>
15
+ </CHANGE_SUMMARY>
16
+ */
17
+
18
+ import { createHash } from "node:crypto";
19
+ import { readFileSync, readdirSync } from "node:fs";
20
+ import { join, relative, sep } from "node:path";
21
+ import picomatch from "picomatch";
22
+
23
+ import type { ChangeUnit, InputDecl, InputFingerprint } from "./types.ts";
24
+
25
+ export function sha256Hex(content: string | Buffer): string {
26
+ return createHash("sha256").update(content).digest("hex");
27
+ }
28
+
29
+ /** Canonical JSON — sorted object keys recursively, the only legal digest substrate. */
30
+ export function canonicalJson(value: unknown): string {
31
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
32
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
33
+ const obj = value as Record<string, unknown>;
34
+ const keys = Object.keys(obj).sort();
35
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
36
+ }
37
+
38
+ /**
39
+ * Commands banned as command-output inputs: time-dependent, random, or
40
+ * network-dependent without sealed inputs. Registration refuses them
41
+ * fail-closed (CG-REG-07). The list is deliberately conservative — a command
42
+ * not on it is still only legal when declared deterministic.
43
+ */
44
+ export const BANNED_COMMAND_INPUTS = new Set([
45
+ "date",
46
+ "curl",
47
+ "wget",
48
+ "ping",
49
+ "ssh",
50
+ "shuf",
51
+ "uuidgen",
52
+ "openssl",
53
+ "nc",
54
+ "dig",
55
+ "nslookup",
56
+ "npm",
57
+ "pnpm",
58
+ "yarn",
59
+ "git",
60
+ ]);
61
+
62
+ /** Resolution context — everything a digest computation may legally read. */
63
+ export interface FingerprintContext {
64
+ /** Filesystem root of the frozen tree under evaluation. */
65
+ treeRoot: string;
66
+ changeUnit: ChangeUnit;
67
+ /** Environment read — injectable for determinism in tests. */
68
+ env: Record<string, string | undefined>;
69
+ /** Deterministic command execution — injectable; returns stdout bytes. */
70
+ execCommand: (command: string, args: string[], cwd: string) => string;
71
+ /** Digests of dependency verdicts, keyed by node id — filled in topological order. */
72
+ verdictDigests: Record<string, string>;
73
+ }
74
+
75
+ function walkFiles(root: string, out: string[]): void {
76
+ let entries;
77
+ try {
78
+ entries = readdirSync(root, { withFileTypes: true });
79
+ } catch {
80
+ return;
81
+ }
82
+ for (const e of entries) {
83
+ const p = join(root, e.name);
84
+ if (e.isDirectory()) {
85
+ if (e.name === "node_modules" || e.name === ".git") continue;
86
+ walkFiles(p, out);
87
+ } else if (e.isFile()) {
88
+ out.push(p);
89
+ }
90
+ }
91
+ }
92
+
93
+ function digestFileGlob(pattern: string, ctx: FingerprintContext): string {
94
+ const all: string[] = [];
95
+ walkFiles(ctx.treeRoot, all);
96
+ const isMatch = picomatch(pattern, { dot: true });
97
+ const matched = all
98
+ .map((abs) => relative(ctx.treeRoot, abs).split(sep).join("/"))
99
+ .filter((rel) => isMatch(rel))
100
+ .sort();
101
+ const entries = matched.map((rel) => {
102
+ const content = readFileSync(join(ctx.treeRoot, rel));
103
+ return { path: rel, digest: sha256Hex(content) };
104
+ });
105
+ return sha256Hex(canonicalJson({ kind: "file-glob", pattern, entries }));
106
+ }
107
+
108
+ function digestOne(input: InputDecl, ctx: FingerprintContext): string {
109
+ switch (input.kind) {
110
+ case "file-glob":
111
+ return digestFileGlob(input.pattern, ctx);
112
+ case "file-content": {
113
+ const content = readFileSync(join(ctx.treeRoot, input.path));
114
+ return sha256Hex(canonicalJson({ kind: "file-content", path: input.path, digest: sha256Hex(content) }));
115
+ }
116
+ case "git-ref": {
117
+ // Snapshot isolation: the frozen unit value is the only legal source.
118
+ const frozen = ctx.changeUnit.frozenRefs[input.ref];
119
+ if (frozen === undefined) {
120
+ throw new Error(`git-ref input '${input.ref}' has no frozen value in change unit ${ctx.changeUnit.id}`);
121
+ }
122
+ return sha256Hex(canonicalJson({ kind: "git-ref", ref: input.ref, value: frozen }));
123
+ }
124
+ case "node-verdict": {
125
+ const digest = ctx.verdictDigests[input.nodeId];
126
+ if (digest === undefined) {
127
+ throw new Error(`node-verdict input '${input.nodeId}' has no verdict digest — topological order broken`);
128
+ }
129
+ return sha256Hex(canonicalJson({ kind: "node-verdict", nodeId: input.nodeId, verdictDigest: digest }));
130
+ }
131
+ case "command-output": {
132
+ if (BANNED_COMMAND_INPUTS.has(input.command)) {
133
+ throw new Error(`banned command-output input '${input.command}' reached fingerprinting — registration is fail-closed, this is a bug`);
134
+ }
135
+ const out = ctx.execCommand(input.command, input.args, ctx.treeRoot);
136
+ return sha256Hex(canonicalJson({ kind: "command-output", command: input.command, args: input.args, digest: sha256Hex(out) }));
137
+ }
138
+ case "environment": {
139
+ const values = input.keys.map((k) => ({ key: k, value: ctx.env[k] ?? null }));
140
+ return sha256Hex(canonicalJson({ kind: "environment", values }));
141
+ }
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Compute the input fingerprint of a node. Throws on unreadable files or
147
+ * unresolvable inputs — the caller treats this as a scheduling-time blocking
148
+ * error, never a cache-miss.
149
+ */
150
+ export function computeInputFingerprint(
151
+ nodeId: string,
152
+ inputs: InputDecl[],
153
+ ctx: FingerprintContext,
154
+ ): InputFingerprint {
155
+ const perInput: Record<string, string> = {};
156
+ inputs.forEach((input, i) => {
157
+ perInput[String(i)] = digestOne(input, ctx);
158
+ });
159
+ const digest = sha256Hex(canonicalJson({ nodeId, inputs: perInput }));
160
+ return {
161
+ nodeId,
162
+ digest,
163
+ inputs: perInput,
164
+ computedAt: new Date().toISOString(),
165
+ };
166
+ }
167
+
168
+ /** sha256(nodeId + inputDigest + executorVersion) — the evidence key, verbatim per RFC. */
169
+ export function evidenceKey(nodeId: string, inputDigest: string, executorVersion: string): string {
170
+ return sha256Hex(`${nodeId}${inputDigest}${executorVersion}`);
171
+ }
172
+
173
+ /** Digest of a verdict serialization — the substrate of node-verdict edges. */
174
+ export function verdictDigest(verdict: unknown): string {
175
+ return sha256Hex(canonicalJson(verdict));
176
+ }
@@ -0,0 +1,181 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Contract-graph loader (Werkstatt RFC-1646) — fail-closed registration of contract
5
+ nodes: closed input vocabulary enforced, dependsOn DAG with cycle refusal,
6
+ plugin id namespacing, executor presence validation, banned command-output
7
+ inputs refused at registration. A graph that fails validation never loads.
8
+ </purpose>
9
+ <non-goals>
10
+ <item>No evaluation — the loader produces validated immutable graph structure only.</item>
11
+ </non-goals>
12
+ <CHANGE_SUMMARY>
13
+ <item>RFC-1646 (WP-3): initial loader.</item>
14
+ </CHANGE_SUMMARY>
15
+ */
16
+
17
+ import { BANNED_COMMAND_INPUTS } from "./fingerprint.ts";
18
+ import { INPUT_KINDS, type ContractNode, type RegistrationError } from "./types.ts";
19
+
20
+ const INPUT_KIND_SET = new Set<string>(INPUT_KINDS);
21
+
22
+ export interface ContractGraph {
23
+ /** All validated nodes, keyed by id. Immutable after load. */
24
+ nodes: Readonly<Record<string, ContractNode>>;
25
+ /** Node ids in topological order (dependencies first). */
26
+ topologicalOrder: readonly string[];
27
+ }
28
+
29
+ function validateNode(
30
+ node: ContractNode,
31
+ ownerPluginId: string,
32
+ executorRefs: ReadonlySet<string>,
33
+ errors: RegistrationError[],
34
+ ): void {
35
+ if (!node.id || typeof node.id !== "string") {
36
+ errors.push({ ruleId: "CG-REG-06", message: "node id missing or not a string" });
37
+ return;
38
+ }
39
+ // Namespace: plugin nodes are prefixed "<pluginId>." — no core/plugin collision by construction.
40
+ if (ownerPluginId !== "core" && !node.id.startsWith(`${ownerPluginId}.`)) {
41
+ errors.push({
42
+ ruleId: "CG-REG-04",
43
+ nodeId: node.id,
44
+ message: `plugin node '${node.id}' must be namespaced '${ownerPluginId}.' — no core/plugin collisions by construction`,
45
+ });
46
+ }
47
+ if (node.owner !== ownerPluginId) {
48
+ errors.push({
49
+ ruleId: "CG-REG-04",
50
+ nodeId: node.id,
51
+ message: `node '${node.id}' declares owner '${node.owner}' but registers through '${ownerPluginId}'`,
52
+ });
53
+ }
54
+ for (const input of node.inputs ?? []) {
55
+ if (!INPUT_KIND_SET.has((input as { kind: string }).kind)) {
56
+ errors.push({
57
+ ruleId: "CG-REG-01",
58
+ nodeId: node.id,
59
+ message: `unknown input kind '${(input as { kind: string }).kind}' — the closed vocabulary is the incrementality guarantee`,
60
+ });
61
+ }
62
+ if (input.kind === "command-output" && BANNED_COMMAND_INPUTS.has(input.command)) {
63
+ errors.push({
64
+ ruleId: "CG-REG-07",
65
+ nodeId: node.id,
66
+ message: `command-output input '${input.command}' is banned (time/random/network-dependent without sealed inputs)`,
67
+ });
68
+ }
69
+ if (input.kind === "node-verdict" && !(node.dependsOn ?? []).includes(input.nodeId)) {
70
+ errors.push({
71
+ ruleId: "CG-REG-05",
72
+ nodeId: node.id,
73
+ message: `node-verdict input on '${input.nodeId}' without a matching dependsOn edge`,
74
+ });
75
+ }
76
+ }
77
+ if (!executorRefs.has(node.executorRef)) {
78
+ errors.push({
79
+ ruleId: "CG-REG-03",
80
+ nodeId: node.id,
81
+ message: `executor '${node.executorRef}' is not registered`,
82
+ });
83
+ }
84
+ }
85
+
86
+ function detectCycles(nodes: Readonly<Record<string, ContractNode>>): string[][] {
87
+ const cycles: string[][] = [];
88
+ const WHITE = 0, GRAY = 1, BLACK = 2;
89
+ const color = new Map<string, number>();
90
+ const stack: string[] = [];
91
+
92
+ const visit = (id: string): void => {
93
+ color.set(id, GRAY);
94
+ stack.push(id);
95
+ for (const dep of nodes[id]?.dependsOn ?? []) {
96
+ if (!nodes[dep]) continue;
97
+ const c = color.get(dep) ?? WHITE;
98
+ if (c === GRAY) {
99
+ const idx = stack.indexOf(dep);
100
+ cycles.push([...stack.slice(idx), dep]);
101
+ } else if (c === WHITE) {
102
+ visit(dep);
103
+ }
104
+ }
105
+ stack.pop();
106
+ color.set(id, BLACK);
107
+ };
108
+
109
+ for (const id of Object.keys(nodes)) {
110
+ if ((color.get(id) ?? WHITE) === WHITE) visit(id);
111
+ }
112
+ return cycles;
113
+ }
114
+
115
+ function topoSort(nodes: Readonly<Record<string, ContractNode>>): string[] {
116
+ const order: string[] = [];
117
+ const visited = new Set<string>();
118
+ const visit = (id: string): void => {
119
+ if (visited.has(id)) return;
120
+ visited.add(id);
121
+ for (const dep of nodes[id]?.dependsOn ?? []) {
122
+ if (nodes[dep]) visit(dep);
123
+ }
124
+ order.push(id);
125
+ };
126
+ for (const id of Object.keys(nodes)) visit(id);
127
+ return order;
128
+ }
129
+
130
+ export interface Registration {
131
+ pluginId: string;
132
+ nodes: ContractNode[];
133
+ }
134
+
135
+ /**
136
+ * Load and validate a contract graph fail-closed. Returns either the validated
137
+ * graph or the complete error list — never a partial graph.
138
+ */
139
+ export function loadContractGraph(
140
+ registrations: Registration[],
141
+ executorRefs: ReadonlySet<string>,
142
+ ): { ok: true; graph: ContractGraph } | { ok: false; errors: RegistrationError[] } {
143
+ const errors: RegistrationError[] = [];
144
+ const nodes: Record<string, ContractNode> = {};
145
+
146
+ for (const reg of registrations) {
147
+ for (const node of reg.nodes) {
148
+ validateNode(node, reg.pluginId, executorRefs, errors);
149
+ if (nodes[node.id]) {
150
+ errors.push({ ruleId: "CG-REG-06", nodeId: node.id, message: `duplicate node id '${node.id}'` });
151
+ } else {
152
+ nodes[node.id] = node;
153
+ }
154
+ }
155
+ }
156
+
157
+ // Unknown dependencies.
158
+ for (const node of Object.values(nodes)) {
159
+ for (const dep of node.dependsOn ?? []) {
160
+ if (!nodes[dep]) {
161
+ errors.push({
162
+ ruleId: "CG-REG-05",
163
+ nodeId: node.id,
164
+ message: `dependsOn references unknown node '${dep}'`,
165
+ });
166
+ }
167
+ }
168
+ }
169
+
170
+ // Cycles are configuration errors refused at load time.
171
+ for (const cycle of detectCycles(nodes)) {
172
+ errors.push({
173
+ ruleId: "CG-REG-02",
174
+ nodeId: cycle[0],
175
+ message: `dependsOn cycle: ${cycle.join(" -> ")}`,
176
+ });
177
+ }
178
+
179
+ if (errors.length > 0) return { ok: false, errors };
180
+ return { ok: true, graph: { nodes, topologicalOrder: topoSort(nodes) } };
181
+ }
@@ -0,0 +1,174 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Migration-map coverage proof (Werkstatt RFC-1646 AC-5) — every v9 protection
5
+ family in the protection migration map is accounted for exactly once: either
6
+ mapped to a live node id in the graph or consciously removed with a recorded
7
+ reason. The map is a versioned artifact whose completeness is itself a contract
8
+ node — the map validates itself. Silent loss is impossible.
9
+ </purpose>
10
+ <non-goals>
11
+ <item>No remediation machinery — proof emission only.</item>
12
+ </non-goals>
13
+ <CHANGE_SUMMARY>
14
+ <item>RFC-1646 (WP-3): initial coverage proof.</item>
15
+ </CHANGE_SUMMARY>
16
+ */
17
+
18
+ import { readFileSync } from "node:fs";
19
+ import yaml from "yaml";
20
+
21
+ import type { ContractGraph } from "./graph.ts";
22
+
23
+ export interface MigrationMapEntry {
24
+ id: string;
25
+ protection: string;
26
+ v9Home?: string;
27
+ disposition: string;
28
+ reason?: string;
29
+ restoredBy?: string;
30
+ /** Set when the protection is live as a v10 contract node. */
31
+ mappedNodeId?: string;
32
+ }
33
+
34
+ export interface CoverageGap {
35
+ entryId: string;
36
+ reason: string;
37
+ }
38
+
39
+ export interface CoverageProof {
40
+ complete: boolean;
41
+ entries: number;
42
+ mappedCount: number;
43
+ removedCount: number;
44
+ gaps: CoverageGap[];
45
+ }
46
+
47
+ /** Dispositions that constitute a conscious, recorded removal — never silent. */
48
+ const REMOVAL_DISPOSITIONS = new Set(["removed-at-wp8", "superseded", "transitional-host"]);
49
+
50
+ export function parseMigrationMapFull(path: string): { entries: MigrationMapEntry[]; families: MigrationFamily[] } {
51
+ const doc = yaml.parse(readFileSync(path, "utf8")) as { entries?: MigrationMapEntry[]; families?: MigrationFamily[] };
52
+ return { entries: doc.entries ?? [], families: doc.families ?? [] };
53
+ }
54
+
55
+ export function parseMigrationMap(path: string): MigrationMapEntry[] {
56
+ const doc = yaml.parse(readFileSync(path, "utf8")) as { entries?: MigrationMapEntry[] };
57
+ return doc.entries ?? [];
58
+ }
59
+
60
+ /**
61
+ * Emit the coverage proof: every entry either names a live graph node
62
+ * (`mappedNodeId` resolvable, or disposition `mapped` with the node present)
63
+ * or carries a removal disposition with a non-empty reason. Anything else is
64
+ * a gap — a silent-loss candidate the contract node refuses.
65
+ */
66
+ export function emitCoverageProof(entries: MigrationMapEntry[], graph: ContractGraph): CoverageProof {
67
+ const gaps: CoverageGap[] = [];
68
+ let mappedCount = 0;
69
+ let removedCount = 0;
70
+
71
+ for (const entry of entries) {
72
+ if (!entry.id || !entry.protection) {
73
+ gaps.push({ entryId: entry.id ?? "(missing id)", reason: "entry lacks id or protection description" });
74
+ continue;
75
+ }
76
+ if (entry.disposition === "mapped") {
77
+ const nodeId = entry.mappedNodeId ?? entry.restoredBy ?? "";
78
+ if (nodeId && graph.nodes[nodeId]) {
79
+ mappedCount += 1;
80
+ } else {
81
+ gaps.push({
82
+ entryId: entry.id,
83
+ reason: `disposition 'mapped' but node '${nodeId || "(none named)"}' is not in the graph`,
84
+ });
85
+ }
86
+ continue;
87
+ }
88
+ if (REMOVAL_DISPOSITIONS.has(entry.disposition)) {
89
+ if (!entry.reason || entry.reason.trim().length === 0) {
90
+ gaps.push({ entryId: entry.id, reason: `removal disposition '${entry.disposition}' without a recorded reason` });
91
+ } else {
92
+ removedCount += 1;
93
+ }
94
+ continue;
95
+ }
96
+ gaps.push({ entryId: entry.id, reason: `unknown disposition '${entry.disposition}'` });
97
+ }
98
+
99
+ return {
100
+ complete: gaps.length === 0,
101
+ entries: entries.length,
102
+ mappedCount,
103
+ removedCount,
104
+ gaps,
105
+ };
106
+ }
107
+
108
+ export interface MigrationFamily {
109
+ id: string;
110
+ disposition: string; // mapped | removed | superseded | pending
111
+ nodeStatus?: string; // live | staged
112
+ target?: string;
113
+ reason?: string;
114
+ note?: string;
115
+ }
116
+
117
+ /**
118
+ * Family-granularity coverage proof (WP-3 completion instrument). Rules:
119
+ * nothing stays pending; removed/superseded require a recorded reason;
120
+ * mapped requires a named target; nodeStatus 'live' additionally requires the
121
+ * target node present in the graph — a live claim that does not resolve is a
122
+ * silent-loss inversion and fails the proof.
123
+ */
124
+ export function emitFamiliesCoverageProof(
125
+ families: MigrationFamily[],
126
+ graph: ContractGraph,
127
+ ): CoverageProof {
128
+ const gaps: CoverageGap[] = [];
129
+ let mappedCount = 0;
130
+ let removedCount = 0;
131
+
132
+ for (const fam of families) {
133
+ if (!fam.id) {
134
+ gaps.push({ entryId: "(missing id)", reason: "family lacks id" });
135
+ continue;
136
+ }
137
+ if (fam.disposition === "pending" || !fam.disposition) {
138
+ gaps.push({ entryId: fam.id, reason: "disposition pending — nothing stays pending at WP-3 closure" });
139
+ continue;
140
+ }
141
+ if (fam.disposition === "removed" || fam.disposition === "superseded") {
142
+ if (!fam.reason || fam.reason.trim().length === 0) {
143
+ gaps.push({ entryId: fam.id, reason: `${fam.disposition} without a recorded reason` });
144
+ } else {
145
+ removedCount += 1;
146
+ }
147
+ continue;
148
+ }
149
+ if (fam.disposition === "mapped") {
150
+ if (!fam.target || fam.target.trim().length === 0) {
151
+ gaps.push({ entryId: fam.id, reason: "mapped without a named target node family" });
152
+ continue;
153
+ }
154
+ if (fam.nodeStatus === "live" && !graph.nodes[fam.target]) {
155
+ gaps.push({
156
+ entryId: fam.id,
157
+ reason: `claims nodeStatus live but target '${fam.target}' is not in the graph`,
158
+ });
159
+ continue;
160
+ }
161
+ mappedCount += 1;
162
+ continue;
163
+ }
164
+ gaps.push({ entryId: fam.id, reason: `unknown disposition '${fam.disposition}'` });
165
+ }
166
+
167
+ return {
168
+ complete: gaps.length === 0,
169
+ entries: families.length,
170
+ mappedCount,
171
+ removedCount,
172
+ gaps,
173
+ };
174
+ }
@@ -0,0 +1,125 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Contract-evidence graph schema types (Werkstatt RFC-1646) — the atom of protection,
5
+ the closed input vocabulary, verdicts, immutable evidence records, and the frozen
6
+ change unit. Schema-only: no evaluation or storage logic lives here.
7
+ </purpose>
8
+ <non-goals>
9
+ <item>Not the scheduler, not the executor runtime — those consume these types.</item>
10
+ </non-goals>
11
+ <CHANGE_SUMMARY>
12
+ <item>RFC-1646 (WP-3): initial schema contracts.</item>
13
+ </CHANGE_SUMMARY>
14
+ */
15
+
16
+ /** The atom of protection. Nodes form a DAG via declared dependsOn edges. */
17
+ export interface ContractNode {
18
+ /** Stable namespaced id, e.g. "forge.rfc.validate.V-25"; plugin nodes are prefixed by plugin id. */
19
+ id: string;
20
+ kind: "validator" | "oracle" | "auditor" | "invariant";
21
+ /** Plugin id or "core". */
22
+ owner: string;
23
+ inputs: InputDecl[];
24
+ substrate: "static" | "execution" | "review" | "external";
25
+ severity: "blocking" | "advisory";
26
+ /** SDK-registered executor reference. */
27
+ executorRef: string;
28
+ /** Semver — part of the evidence key. */
29
+ executorVersion: string;
30
+ /** Node ids; DAG enforced at load. */
31
+ dependsOn: string[];
32
+ cachePolicy: "content-addressed" | "uncacheable";
33
+ /** Human/agent-facing explanation template. */
34
+ description: string;
35
+ }
36
+
37
+ /** Closed input vocabulary — anything outside it cannot be declared. */
38
+ export type InputDecl =
39
+ | { kind: "file-glob"; pattern: string }
40
+ | { kind: "file-content"; path: string }
41
+ | { kind: "git-ref"; ref: string }
42
+ | { kind: "node-verdict"; nodeId: string }
43
+ | { kind: "command-output"; command: string; args: string[] }
44
+ | { kind: "environment"; keys: string[] };
45
+
46
+ export const INPUT_KINDS = [
47
+ "file-glob",
48
+ "file-content",
49
+ "git-ref",
50
+ "node-verdict",
51
+ "command-output",
52
+ "environment",
53
+ ] as const;
54
+
55
+ export interface InputFingerprint {
56
+ nodeId: string;
57
+ /** sha256 over canonical input serialization. */
58
+ digest: string;
59
+ /** Per-input digests — explainability. Keyed by input index. */
60
+ inputs: Record<string, string>;
61
+ /** Evidence metadata, not part of digest. */
62
+ computedAt: string;
63
+ }
64
+
65
+ export interface Violation {
66
+ ruleId: string;
67
+ message: string;
68
+ severity: "blocking" | "advisory";
69
+ file?: string;
70
+ line?: number;
71
+ }
72
+
73
+ export type Verdict =
74
+ | { status: "pass" }
75
+ | { status: "fail"; violations: Violation[] }
76
+ | { status: "uncacheable-pass" }
77
+ | { status: "error"; message: string };
78
+
79
+ /** Immutable, content-addressed evidence. Written once, never migrated. */
80
+ export interface EvidenceRecord {
81
+ schema: "forge:evidence/v1";
82
+ /** sha256(nodeId + inputDigest + executorVersion) */
83
+ key: string;
84
+ nodeId: string;
85
+ inputFingerprint: InputFingerprint;
86
+ verdict: Verdict;
87
+ executorVersion: string;
88
+ startedAt: string;
89
+ durationMs: number;
90
+ /** The frozen unit under evaluation. */
91
+ changeUnitId: string;
92
+ /** Content-addressed blobs (logs, reports). */
93
+ artifactRefs: string[];
94
+ }
95
+
96
+ /**
97
+ * The unit of evaluation — frozen at creation, immutable thereafter.
98
+ * `frozenRefs` holds the resolved values of every git-ref input the graph
99
+ * declares, captured at unit creation: nodes never read live mutable git
100
+ * state, so the frozen values are the only legal resolution source.
101
+ */
102
+ export interface ChangeUnit {
103
+ id: string;
104
+ /** sha256 of the frozen tree object. */
105
+ treeDigest: string;
106
+ /** Integration target ref at creation. */
107
+ baseRef: string;
108
+ createdAt: string;
109
+ frozenRefs: Record<string, string>;
110
+ metadata: Record<string, string>;
111
+ }
112
+
113
+ /** Typed configuration error for fail-closed registration refusal. */
114
+ export interface RegistrationError {
115
+ ruleId:
116
+ | "CG-REG-01" // unknown input kind
117
+ | "CG-REG-02" // dependsOn cycle
118
+ | "CG-REG-03" // missing executor
119
+ | "CG-REG-04" // namespace violation
120
+ | "CG-REG-05" // undeclared/unknown dependency
121
+ | "CG-REG-06" // duplicate node id
122
+ | "CG-REG-07"; // banned command-output input
123
+ message: string;
124
+ nodeId?: string;
125
+ }