@rosenfan/matrix 0.1.4 → 0.1.6

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 (54) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +41 -40
  3. package/README.zh-CN.md +39 -38
  4. package/{.claude → assets}/skills/matrix/SKILL.md +79 -78
  5. package/{.claude → assets}/skills/matrix/agents/openai.yaml +4 -4
  6. package/{.claude → assets}/skills/matrix/scripts/matrix_claude.py +11 -11
  7. package/{.claude → assets}/skills/matrix/scripts/matrix_state.py +49 -49
  8. package/assets/skills/matrix/scripts/test_matrix_claude.py +69 -0
  9. package/assets/skills/matrix/scripts/test_matrix_state.py +69 -0
  10. package/{.claude → assets}/skills/matrix-archive/SKILL.md +36 -36
  11. package/{.claude/skills/matrix-hotfix → assets/skills/matrix-archive}/agents/openai.yaml +4 -4
  12. package/{.claude → assets}/skills/matrix-build/SKILL.md +41 -41
  13. package/{.claude/skills/matrix-archive → assets/skills/matrix-build}/agents/openai.yaml +4 -4
  14. package/{.claude → assets}/skills/matrix-design/SKILL.md +71 -65
  15. package/{.claude → assets}/skills/matrix-design/agents/openai.yaml +4 -4
  16. package/assets/skills/matrix-handoff/SKILL.md +89 -0
  17. package/{.claude/skills/matrix-claude → assets/skills/matrix-handoff}/agents/openai.yaml +4 -4
  18. package/{.claude → assets}/skills/matrix-hotfix/SKILL.md +8 -8
  19. package/{.claude/skills/matrix-build → assets/skills/matrix-hotfix}/agents/openai.yaml +4 -4
  20. package/{.claude → assets}/skills/matrix-open/SKILL.md +51 -40
  21. package/assets/skills/matrix-open/agents/openai.yaml +4 -0
  22. package/{.claude → assets}/skills/matrix-status/SKILL.md +15 -15
  23. package/{.claude → assets}/skills/matrix-status/agents/openai.yaml +4 -4
  24. package/{.claude → assets}/skills/matrix-tweak/SKILL.md +8 -8
  25. package/assets/skills/matrix-tweak/agents/openai.yaml +4 -0
  26. package/{.claude → assets}/skills/matrix-verify/SKILL.md +62 -62
  27. package/assets/skills/matrix-verify/agents/openai.yaml +4 -0
  28. package/assets/skills-zh-CN/matrix/SKILL.md +72 -71
  29. package/assets/skills-zh-CN/matrix-build/SKILL.md +4 -4
  30. package/assets/skills-zh-CN/matrix-design/SKILL.md +37 -20
  31. package/assets/skills-zh-CN/matrix-handoff/SKILL.md +79 -0
  32. package/assets/skills-zh-CN/matrix-open/SKILL.md +38 -28
  33. package/assets/skills-zh-CN/matrix-verify/SKILL.md +19 -19
  34. package/bin/matrix.js +15 -15
  35. package/package.json +4 -13
  36. package/src/catalog.js +79 -72
  37. package/src/cli.js +211 -141
  38. package/src/distribution.js +182 -179
  39. package/src/installer.js +10 -10
  40. package/src/matt-catalog.mjs +1 -1
  41. package/src/matt.js +9 -14
  42. package/src/messages.js +32 -23
  43. package/src/npm-invocation.js +23 -0
  44. package/src/project-index.js +43 -0
  45. package/src/runtime-resolver.js +76 -76
  46. package/src/self-update.js +88 -81
  47. package/src/ui.js +97 -89
  48. package/src/workflow-transaction.js +13 -13
  49. package/src/workflow.js +734 -705
  50. package/.claude/skills/matrix-claude/SKILL.md +0 -98
  51. package/.claude/skills/matrix-open/agents/openai.yaml +0 -4
  52. package/.claude/skills/matrix-tweak/agents/openai.yaml +0 -4
  53. package/.claude/skills/matrix-verify/agents/openai.yaml +0 -4
  54. package/assets/skills-zh-CN/matrix-claude/SKILL.md +0 -33
package/src/workflow.js CHANGED
@@ -1,47 +1,47 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
3
  import crypto from "node:crypto";
4
4
  import os from "node:os";
5
5
  import { spawnSync } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { MATT_AUTOMATIC_SKILLS, MATT_CATALOG_DIGEST, MATT_COMPATIBILITY, MATT_CONTENT_HASHES } from "./matt-catalog.mjs";
8
- import {
9
- captureWorkflowEntry,
10
- runWorkflowTransaction,
11
- workflowDoctor,
12
- workflowMkdirOperation,
13
- workflowMutationGate,
14
- workflowMoveOperation,
15
- workflowRemoveOperation,
16
- workflowWriteOperation
17
- } from "./workflow-transaction.js";
18
-
19
- const PHASES = ["open", "design", "build", "verify", "archive"];
20
- const FULL_PROFILE = {
21
- id: "full",
22
- next: { open: "design", design: "build", build: "verify", verify: "archive" },
23
- contractFiles: ["proposal.md", "design.md", "plan.md"]
24
- };
25
- const LIGHTWEIGHT_PROFILE = {
26
- id: "lightweight",
27
- next: { open: "build", build: "verify", verify: "archive" },
28
- contractFiles: ["proposal.md"]
29
- };
30
- const FULL_RETURNS = [
31
- { from: "build", to: "design", reason: "design-gap" },
32
- { from: "verify", to: "build", reason: "verification-failed" },
33
- { from: "verify", to: "design", reason: "acceptance-or-design-gap" },
34
- { from: "archive", to: "design", reason: "acceptance-or-design-gap" }
35
- ];
36
- const LIGHTWEIGHT_RETURNS = [
37
- { from: "build", to: "design", reason: "design-gap", upgrade: true },
38
- { from: "verify", to: "build", reason: "verification-failed" },
39
- { from: "verify", to: "design", reason: "acceptance-or-design-gap", upgrade: true },
40
- { from: "archive", to: "design", reason: "acceptance-or-design-gap", upgrade: true }
41
- ];
42
- const RETURN_REASONS = new Set([...FULL_RETURNS, ...LIGHTWEIGHT_RETURNS].map(({ reason }) => reason));
43
- const INVALIDATED_EVIDENCE = ["build", "test", "review", "archive"];
44
- const ABORT_REASONS = new Set(["requirement-cancelled", "superseded", "no-longer-valuable", "blocked", "other"]);
8
+ import {
9
+ captureWorkflowEntry,
10
+ runWorkflowTransaction,
11
+ workflowDoctor,
12
+ workflowMkdirOperation,
13
+ workflowMutationGate,
14
+ workflowMoveOperation,
15
+ workflowRemoveOperation,
16
+ workflowWriteOperation
17
+ } from "./workflow-transaction.js";
18
+
19
+ const PHASES = ["open", "design", "build", "verify", "archive"];
20
+ const FULL_PROFILE = {
21
+ id: "full",
22
+ next: { open: "design", design: "build", build: "verify", verify: "archive" },
23
+ contractFiles: ["proposal.md", "design.md", "plan.md"]
24
+ };
25
+ const LIGHTWEIGHT_PROFILE = {
26
+ id: "lightweight",
27
+ next: { open: "build", build: "verify", verify: "archive" },
28
+ contractFiles: ["proposal.md"]
29
+ };
30
+ const FULL_RETURNS = [
31
+ { from: "build", to: "design", reason: "design-gap" },
32
+ { from: "verify", to: "build", reason: "verification-failed" },
33
+ { from: "verify", to: "design", reason: "acceptance-or-design-gap" },
34
+ { from: "archive", to: "design", reason: "acceptance-or-design-gap" }
35
+ ];
36
+ const LIGHTWEIGHT_RETURNS = [
37
+ { from: "build", to: "design", reason: "design-gap", upgrade: true },
38
+ { from: "verify", to: "build", reason: "verification-failed" },
39
+ { from: "verify", to: "design", reason: "acceptance-or-design-gap", upgrade: true },
40
+ { from: "archive", to: "design", reason: "acceptance-or-design-gap", upgrade: true }
41
+ ];
42
+ const RETURN_REASONS = new Set([...FULL_RETURNS, ...LIGHTWEIGHT_RETURNS].map(({ reason }) => reason));
43
+ const INVALIDATED_EVIDENCE = ["build", "test", "review", "archive"];
44
+ const ABORT_REASONS = new Set(["requirement-cancelled", "superseded", "no-longer-valuable", "blocked", "other"]);
45
45
  const ORCHESTRATIONS = ["prim", "arch"];
46
46
  const quoteCommandPath = (value) => process.platform === "win32" ? `"${value}"` : `'${value.replaceAll("'", "'\\''")}'`;
47
47
  const workflowCommand = (argumentsText) => `node ${quoteCommandPath(fileURLToPath(import.meta.url))} ${argumentsText}`;
@@ -49,26 +49,26 @@ const LEGACY_ARCH_SKILLS = [
49
49
  "grilling", "domain-modeling", "research", "wayfinder", "prototype",
50
50
  "codebase-design", "tdd", "diagnosing-bugs", "resolving-merge-conflicts", "code-review"
51
51
  ];
52
- const ARTIFACT_POLICY = {
53
- proposal: ["## Goal", "## Scope", "## Non-goals", "## Acceptance", "## Risks"],
54
- design: ["## Decisions", "## Boundaries", "## Test seams", "## Risks"],
55
- plan: ["## Steps", "## Validation", "## Stop conditions"],
56
- build: ["## Build evidence"],
57
- verification: ["## Test evidence", "## Review evidence"]
58
- };
59
- const LIGHTWEIGHT_COMMON_PROPOSAL = ["## Goal", "## Scope", "## Non-goals", "## Approach", "## Acceptance", "## Validation", "## Risks", "## Upgrade conditions"];
60
- const LIGHTWEIGHT_POLICY = {
61
- hotfix: {
62
- proposal: [...LIGHTWEIGHT_COMMON_PROPOSAL, "## Expected behavior", "## Actual behavior", "## Reproduction"],
63
- build: ["## Build evidence", "## Reproduction evidence", "## Root cause"],
64
- verification: ["## Test evidence", "## Regression evidence", "## Review evidence"]
65
- },
66
- tweak: {
67
- proposal: [...LIGHTWEIGHT_COMMON_PROPOSAL, "## Current behavior", "## Preserved behavior", "## Diff boundary"],
68
- build: ["## Build evidence", "## Scope evidence"],
69
- verification: ["## Test evidence", "## Scope review evidence", "## Review evidence"]
70
- }
71
- };
52
+ const ARTIFACT_POLICY = {
53
+ proposal: ["## Goal", "## Scope", "## Non-goals", "## Acceptance", "## Risks"],
54
+ design: ["## Decisions", "## Boundaries", "## Test seams", "## Risks"],
55
+ plan: ["## Steps", "## Validation", "## Stop conditions"],
56
+ build: ["## Build evidence"],
57
+ verification: ["## Test evidence", "## Review evidence"]
58
+ };
59
+ const LIGHTWEIGHT_COMMON_PROPOSAL = ["## Goal", "## Scope", "## Non-goals", "## Approach", "## Acceptance", "## Validation", "## Risks", "## Upgrade conditions"];
60
+ const LIGHTWEIGHT_POLICY = {
61
+ hotfix: {
62
+ proposal: [...LIGHTWEIGHT_COMMON_PROPOSAL, "## Expected behavior", "## Actual behavior", "## Reproduction"],
63
+ build: ["## Build evidence", "## Reproduction evidence", "## Root cause"],
64
+ verification: ["## Test evidence", "## Regression evidence", "## Review evidence"]
65
+ },
66
+ tweak: {
67
+ proposal: [...LIGHTWEIGHT_COMMON_PROPOSAL, "## Current behavior", "## Preserved behavior", "## Diff boundary"],
68
+ build: ["## Build evidence", "## Scope evidence"],
69
+ verification: ["## Test evidence", "## Scope review evidence", "## Review evidence"]
70
+ }
71
+ };
72
72
  const WORKSPACE_BASELINE_FILE = "workspace-baseline.json";
73
73
  const WORKSPACE_EXCLUDES = new Set([".git", ".matrix", ".comet", "node_modules"]);
74
74
  const WORKSPACE_MAX_FILES = 50000;
@@ -78,139 +78,145 @@ const REVIEW_RECEIPT_SCHEMA = "matrix/review-receipt/v1";
78
78
  const REVIEW_SOURCES = new Set(["code-review", "matrix-fallback"]);
79
79
  const REVIEW_OUTCOMES = new Set(["passed", "failed"]);
80
80
  const REVIEW_FALLBACK_REASONS = new Set(["git-baseline-unavailable", "empty-head-diff", "uncommitted-worktree", "capability-execution-failed"]);
81
- const skill = (phase) => `$matrix-${phase}`;
82
- const stamp = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
83
- const rootFor = (cwd) => path.join(cwd, ".matrix");
84
- const exists = (file) => fs.existsSync(file);
85
- const read = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
86
-
87
- function fail(code, message) { return { ok: false, code, message }; }
88
- function option(args, name) { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : null; }
89
- function flatYaml(file) {
90
- try {
91
- return Object.fromEntries(fs.readFileSync(file, "utf8").split(/\r?\n/).filter((line) => line.includes(":") && !line.startsWith(" ")).map((line) => {
92
- const [key, ...value] = line.split(":");
93
- return [key.trim(), value.join(":").trim().replace(/^"|"$/g, "")];
94
- }));
95
- } catch { return {}; }
96
- }
97
- function excludedWorkspacePath(relative) {
98
- const first = relative.replaceAll("\\", "/").split("/")[0];
99
- return WORKSPACE_EXCLUDES.has(first);
100
- }
101
- function workspaceFiles(cwd) {
102
- const git = spawnSync("git", ["-C", cwd, "ls-files", "-co", "--exclude-standard", "-z"], {
103
- encoding: "buffer",
104
- windowsHide: true,
105
- maxBuffer: 64 * 1024 * 1024
106
- });
107
- if (!git.error && git.status === 0) {
108
- return {
109
- provider: "git",
110
- files: [...new Set(git.stdout.toString("utf8").split("\0").filter(Boolean))]
111
- .map((relative) => relative.replaceAll("\\", "/"))
112
- .filter((relative) => !excludedWorkspacePath(relative))
113
- .sort()
114
- };
115
- }
116
- const files = [];
117
- const visit = (directory, prefix = "") => {
118
- for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
119
- const relative = path.join(prefix, entry.name).replaceAll("\\", "/");
120
- if (!prefix && WORKSPACE_EXCLUDES.has(entry.name)) continue;
121
- if (entry.isDirectory()) visit(path.join(directory, entry.name), relative);
122
- else files.push(relative);
123
- if (files.length > WORKSPACE_MAX_FILES) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_FILES} files.`);
124
- }
125
- };
126
- visit(cwd);
127
- return { provider: "physical", files };
128
- }
129
- function captureWorkspaceBaseline(cwd) {
130
- const startedAt = Date.now();
131
- const selection = workspaceFiles(cwd);
132
- const hash = crypto.createHash("sha256");
133
- hash.update("matrix/workspace-baseline/v1\0", "utf8");
134
- let totalBytes = 0;
135
- let fileCount = 0;
136
- for (const relative of selection.files) {
137
- if (Date.now() - startedAt > WORKSPACE_MAX_DURATION_MS) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_DURATION_MS} milliseconds.`);
138
- if (fileCount >= WORKSPACE_MAX_FILES) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_FILES} files.`);
139
- const absolute = path.join(cwd, relative);
140
- const pathBytes = Buffer.from(relative, "utf8");
141
- const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
142
- hash.update(pathLength); hash.update(pathBytes);
143
- let stat;
144
- try { stat = fs.lstatSync(absolute); }
145
- catch (error) {
146
- if (error.code !== "ENOENT") throw error;
147
- hash.update("missing\0", "utf8");
148
- fileCount += 1;
149
- continue;
150
- }
151
- if (stat.isSymbolicLink()) {
152
- const target = Buffer.from(fs.readlinkSync(absolute), "utf8");
153
- hash.update("symlink\0", "utf8"); hash.update(target);
154
- totalBytes += target.length;
155
- } else if (stat.isFile()) {
156
- const bytes = fs.readFileSync(absolute);
157
- totalBytes += bytes.length;
158
- if (totalBytes > WORKSPACE_MAX_BYTES) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_BYTES} bytes.`);
159
- hash.update("file\0", "utf8"); hash.update(bytes);
160
- } else {
161
- hash.update("special\0", "utf8");
162
- }
163
- fileCount += 1;
164
- }
165
- return {
166
- schema: "matrix/workspace-baseline/v1",
167
- provider: selection.provider,
168
- hash: `sha256:${hash.digest("hex")}`,
169
- file_count: fileCount,
170
- content_bytes: totalBytes
171
- };
172
- }
173
- function workspaceOrderGuard(cwd, p) {
174
- let baseline;
175
- try { baseline = read(p.workspaceBaseline); }
176
- catch (error) {
177
- return fail("WORKSPACE_BASELINE_MISSING", `Lightweight workflow baseline is unavailable: ${error.message}`);
178
- }
179
- let current;
180
- try { current = captureWorkspaceBaseline(cwd); }
181
- catch (error) {
182
- return fail("WORKSPACE_INSPECTION_FAILED", `Could not inspect the lightweight workflow boundary: ${error.message}`);
183
- }
184
- if (baseline.schema !== "matrix/workspace-baseline/v1" || !/^sha256:[0-9a-f]{64}$/.test(baseline.hash ?? "")) {
185
- return fail("WORKSPACE_BASELINE_INVALID", "Lightweight workflow baseline is invalid.");
186
- }
187
- if (current.hash !== baseline.hash) {
188
- return {
189
- ...fail("PREMATURE_IMPLEMENTATION", "Project files changed after lightweight initialization and before Build approval."),
190
- baseline_hash: baseline.hash,
191
- current_hash: current.hash
192
- };
193
- }
194
- return { ok: true, code: "OK", baseline_hash: baseline.hash, current_hash: current.hash };
195
- }
196
- function hashDirectory(directory) {
197
- const hash = crypto.createHash("sha256");
198
- const files = [];
199
- const visit = (current, relative = "") => {
200
- for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
201
- const child = path.join(current, entry.name);
202
- const childRelative = path.join(relative, entry.name).replaceAll("\\", "/");
203
- if (entry.isDirectory()) visit(child, childRelative);
204
- else if (entry.isFile()) files.push([childRelative, fs.readFileSync(child)]);
205
- }
206
- };
207
- visit(directory);
208
- for (const [relative, contents] of files.sort(([left], [right]) => left.localeCompare(right))) {
209
- hash.update(`${relative}\0`);
210
- hash.update(contents);
211
- }
212
- return hash.digest("hex");
213
- }
81
+ const skill = (phase) => `$matrix-${phase}`;
82
+ const stamp = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
83
+ const rootFor = (cwd) => path.join(cwd, ".matrix");
84
+ const exists = (file) => fs.existsSync(file);
85
+ const read = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
86
+
87
+ function fail(code, message) { return { ok: false, code, message }; }
88
+ function option(args, name) { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : null; }
89
+ function flatYaml(file) {
90
+ try {
91
+ return Object.fromEntries(fs.readFileSync(file, "utf8").split(/\r?\n/).filter((line) => line.includes(":") && !line.startsWith(" ")).map((line) => {
92
+ const [key, ...value] = line.split(":");
93
+ return [key.trim(), value.join(":").trim().replace(/^"|"$/g, "")];
94
+ }));
95
+ } catch { return {}; }
96
+ }
97
+ function excludedWorkspacePath(relative) {
98
+ const first = relative.replaceAll("\\", "/").split("/")[0];
99
+ return WORKSPACE_EXCLUDES.has(first);
100
+ }
101
+ function workspaceFiles(cwd) {
102
+ const git = spawnSync("git", ["-C", cwd, "ls-files", "-co", "--exclude-standard", "-z"], {
103
+ encoding: "buffer",
104
+ windowsHide: true,
105
+ maxBuffer: 64 * 1024 * 1024
106
+ });
107
+ if (!git.error && git.status === 0) {
108
+ return {
109
+ provider: "git",
110
+ files: [...new Set(git.stdout.toString("utf8").split("\0").filter(Boolean))]
111
+ .map((relative) => relative.replaceAll("\\", "/"))
112
+ .filter((relative) => !excludedWorkspacePath(relative))
113
+ .sort()
114
+ };
115
+ }
116
+ const files = [];
117
+ const visit = (directory, prefix = "") => {
118
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
119
+ const relative = path.join(prefix, entry.name).replaceAll("\\", "/");
120
+ if (!prefix && WORKSPACE_EXCLUDES.has(entry.name)) continue;
121
+ if (entry.isDirectory()) visit(path.join(directory, entry.name), relative);
122
+ else files.push(relative);
123
+ if (files.length > WORKSPACE_MAX_FILES) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_FILES} files.`);
124
+ }
125
+ };
126
+ visit(cwd);
127
+ return { provider: "physical", files };
128
+ }
129
+ function captureWorkspaceBaseline(cwd) {
130
+ const startedAt = Date.now();
131
+ const selection = workspaceFiles(cwd);
132
+ const hash = crypto.createHash("sha256");
133
+ hash.update("matrix/workspace-baseline/v1\0", "utf8");
134
+ let totalBytes = 0;
135
+ let fileCount = 0;
136
+ for (const relative of selection.files) {
137
+ if (Date.now() - startedAt > WORKSPACE_MAX_DURATION_MS) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_DURATION_MS} milliseconds.`);
138
+ if (fileCount >= WORKSPACE_MAX_FILES) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_FILES} files.`);
139
+ const absolute = path.join(cwd, relative);
140
+ const pathBytes = Buffer.from(relative, "utf8");
141
+ const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
142
+ hash.update(pathLength); hash.update(pathBytes);
143
+ let stat;
144
+ try { stat = fs.lstatSync(absolute); }
145
+ catch (error) {
146
+ if (error.code !== "ENOENT") throw error;
147
+ hash.update("missing\0", "utf8");
148
+ fileCount += 1;
149
+ continue;
150
+ }
151
+ if (stat.isSymbolicLink()) {
152
+ const target = Buffer.from(fs.readlinkSync(absolute), "utf8");
153
+ hash.update("symlink\0", "utf8"); hash.update(target);
154
+ totalBytes += target.length;
155
+ } else if (stat.isFile()) {
156
+ const bytes = fs.readFileSync(absolute);
157
+ totalBytes += bytes.length;
158
+ if (totalBytes > WORKSPACE_MAX_BYTES) throw new Error(`Workspace baseline exceeds ${WORKSPACE_MAX_BYTES} bytes.`);
159
+ hash.update("file\0", "utf8"); hash.update(bytes);
160
+ } else {
161
+ hash.update("special\0", "utf8");
162
+ }
163
+ fileCount += 1;
164
+ }
165
+ return {
166
+ schema: "matrix/workspace-baseline/v1",
167
+ provider: selection.provider,
168
+ hash: `sha256:${hash.digest("hex")}`,
169
+ file_count: fileCount,
170
+ content_bytes: totalBytes
171
+ };
172
+ }
173
+ function workspaceOrderGuard(cwd, p) {
174
+ let baseline;
175
+ try { baseline = read(p.workspaceBaseline); }
176
+ catch (error) {
177
+ return fail("WORKSPACE_BASELINE_MISSING", `Lightweight workflow baseline is unavailable: ${error.message}`);
178
+ }
179
+ let current;
180
+ try { current = captureWorkspaceBaseline(cwd); }
181
+ catch (error) {
182
+ return fail("WORKSPACE_INSPECTION_FAILED", `Could not inspect the lightweight workflow boundary: ${error.message}`);
183
+ }
184
+ if (baseline.schema !== "matrix/workspace-baseline/v1" || !/^sha256:[0-9a-f]{64}$/.test(baseline.hash ?? "")) {
185
+ return fail("WORKSPACE_BASELINE_INVALID", "Lightweight workflow baseline is invalid.");
186
+ }
187
+ if (current.hash !== baseline.hash) {
188
+ return {
189
+ ...fail("PREMATURE_IMPLEMENTATION", "Project files changed after lightweight initialization and before Build approval."),
190
+ baseline_hash: baseline.hash,
191
+ current_hash: current.hash
192
+ };
193
+ }
194
+ return { ok: true, code: "OK", baseline_hash: baseline.hash, current_hash: current.hash };
195
+ }
196
+ // Same normalization contract as catalog.js hashDirectory: the Arch integrity check
197
+ // must agree with the installer digest regardless of checkout line endings, and
198
+ // generated caches must never enter either digest.
199
+ const normalizeEol = (contents) => Buffer.from(contents.toString("utf8").replaceAll("\r\n", "\n").replaceAll("\r", "\n"), "utf8");
200
+ const GENERATED_DIRS = new Set(["__pycache__"]);
201
+ function hashDirectory(directory) {
202
+ const hash = crypto.createHash("sha256");
203
+ const files = [];
204
+ const visit = (current, relative = "") => {
205
+ for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
206
+ if (entry.isDirectory() && GENERATED_DIRS.has(entry.name)) continue;
207
+ const child = path.join(current, entry.name);
208
+ const childRelative = path.join(relative, entry.name).replaceAll("\\", "/");
209
+ if (entry.isDirectory()) visit(child, childRelative);
210
+ else if (entry.isFile()) files.push([childRelative, fs.readFileSync(child)]);
211
+ }
212
+ };
213
+ visit(directory);
214
+ for (const [relative, contents] of files.sort(([left], [right]) => left.localeCompare(right))) {
215
+ hash.update(`${relative}\0`);
216
+ hash.update(normalizeEol(contents));
217
+ }
218
+ return hash.digest("hex");
219
+ }
214
220
  function orchestrationConfig(cwd) {
215
221
  const config = flatYaml(path.join(rootFor(cwd), "config.yaml"));
216
222
  const scope = config.installation_scope === "global" ? "global" : "project";
@@ -220,10 +226,10 @@ function orchestrationConfig(cwd) {
220
226
  let mattReceipt = null;
221
227
  try { manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8")); } catch {}
222
228
  try { mattReceipt = JSON.parse(fs.readFileSync(mattReceiptFile, "utf8")); } catch {}
223
- const defaultOrchestration = ORCHESTRATIONS.includes(config.default_orchestration) ? config.default_orchestration
224
- : ORCHESTRATIONS.includes(manifest?.orchestration?.default) ? manifest.orchestration.default : "prim";
225
- const artifactLanguage = ["en", "zh-CN"].includes(config.language) ? config.language
226
- : ["en", "zh-CN"].includes(manifest?.language) ? manifest.language : "en";
229
+ const defaultOrchestration = ORCHESTRATIONS.includes(config.default_orchestration) ? config.default_orchestration
230
+ : ORCHESTRATIONS.includes(manifest?.orchestration?.default) ? manifest.orchestration.default : "prim";
231
+ const artifactLanguage = ["en", "zh-CN"].includes(config.language) ? config.language
232
+ : ["en", "zh-CN"].includes(manifest?.language) ? manifest.language : "en";
227
233
  return { config, scope, manifestFile, manifest, mattReceiptFile, mattReceipt, defaultOrchestration, artifactLanguage };
228
234
  }
229
235
  function archIntegrity(cwd, flow = null, contentHashes = MATT_CONTENT_HASHES) {
@@ -258,26 +264,30 @@ function archIntegrity(cwd, flow = null, contentHashes = MATT_CONTENT_HASHES) {
258
264
  try {
259
265
  const actual = hashDirectory(target);
260
266
  if (legacy ? actual !== installed.hash : actual !== installed.hash || actual !== contentHashes[skill]) findings.push({ platform, skill, reason: "modified" });
261
- } catch { findings.push({ platform, skill, reason: "unreadable" }); }
262
- }
263
- }
267
+ } catch { findings.push({ platform, skill, reason: "unreadable" }); }
268
+ }
269
+ }
264
270
  return findings.length ? {
265
271
  ok: false, code: "ARCH_INSTALLATION_INCOMPLETE", message: "Arch installation integrity failed. Repair the managed cohort before continuing.",
266
272
  manifest: legacy ? manifestFile : mattReceiptFile, findings, recovery_command: "matrix init --with-mattpocock"
267
273
  } : { ok: true, code: "OK", manifest: legacy ? manifestFile : mattReceiptFile, platforms: platforms.map(([platform]) => platform), cohort: legacy ? "legacy-v0.1.3" : MATT_CATALOG_DIGEST, matt_release: legacy ? null : MATT_COMPATIBILITY.release };
268
274
  }
269
- function taskContent(change, taskId, proposal, design, plan, resultPath, contractHash, approvalRevision) {
270
- return `# Claude Code task: ${taskId}\n\n## Metadata\n\n| Field | Value |\n| --- | --- |\n| Status | CLAUDE_QUEUED |\n| Matrix change | ${change} |\n| Decision owner | Codex |\n| Implementation actor | Claude Code |\n| Approved contract | ${contractHash} |\n| Approval revision | ${approvalRevision} |\n| Result | ${resultPath} |\n\n## Objective\n\nThe frozen Matrix artifacts below are authoritative. Do not expand their scope.\n\n## Proposal\n\n${proposal}\n\n## Frozen design\n\n${design}\n\n## Ordered plan\n\n${plan}\n\n## Allowed work\n\n- Read repository instructions and existing tests before implementing.\n- Change only files required by the frozen design and plan.\n\n## Prohibited work\n\n- Do not edit Matrix state, transition its phase, archive it, or alter the frozen design.\n- Do not add unrelated features, public APIs, dependencies, or external side effects.\n- Do not claim completion without recording verifiable evidence.\n\n## Stop and report\n\nStop with \`NEEDS_DECISION\` if the scope must expand, the design conflicts with the repository, validation cannot pass within scope, or an authorization/safety issue arises.\n\n## Required result\n\nCreate \`${resultPath}\` with metadata, changed files and reasons, commands and outcomes, test results, boundary confirmation, residual risks, and any \`NEEDS_DECISION\` items. Codex reviews the result and the actual diff.\n`;
271
- }
272
- function activeBoard(taskId, taskPath, resultPath, change) {
273
- return `# Active task board\n\n## Current objective\n\n| Field | Value |\n| --- | --- |\n| ID | ${taskId} |\n| Status | CLAUDE_QUEUED |\n| Matrix change | ${change} |\n| Task | ${taskPath} |\n| Result | ${resultPath} |\n`;
274
- }
275
+ function taskContent(change, taskId, proposal, design, plan, resultPath, contractHash, approvalRevision, actor = {}) {
276
+ const agent = actor.agent ?? "Claude Code";
277
+ const owner = actor.owner ?? "Codex";
278
+ const statusToken = actor.statusToken ?? "CLAUDE_QUEUED";
279
+ const reviewer = actor.reviewer ?? "Codex";
280
+ return `# ${agent} task: ${taskId}\n\n## Metadata\n\n| Field | Value |\n| --- | --- |\n| Status | ${statusToken} |\n| Matrix change | ${change} |\n| Decision owner | ${owner} |\n| Implementation actor | ${agent} |\n| Approved contract | ${contractHash} |\n| Approval revision | ${approvalRevision} |\n| Result | ${resultPath} |\n\n## Objective\n\nThe frozen Matrix artifacts below are authoritative. Do not expand their scope.\n\n## Proposal\n\n${proposal}\n\n## Frozen design\n\n${design}\n\n## Ordered plan\n\n${plan}\n\n## Allowed work\n\n- Read repository instructions and existing tests before implementing.\n- Change only files required by the frozen design and plan.\n\n## Prohibited work\n\n- Do not edit Matrix state, transition its phase, archive it, or alter the frozen design.\n- Do not add unrelated features, public APIs, dependencies, or external side effects.\n- Do not claim completion without recording verifiable evidence.\n\n## Stop and report\n\nStop with \`NEEDS_DECISION\` if the scope must expand, the design conflicts with the repository, validation cannot pass within scope, or an authorization/safety issue arises.\n\n## Required result\n\nCreate \`${resultPath}\` with metadata, changed files and reasons, commands and outcomes, test results, boundary confirmation, residual risks, and any \`NEEDS_DECISION\` items. ${reviewer} reviews the result and the actual diff.\n`;
281
+ }
282
+ function activeBoard(taskId, taskPath, resultPath, change) {
283
+ return `# Active task board\n\n## Current objective\n\n| Field | Value |\n| --- | --- |\n| ID | ${taskId} |\n| Status | CLAUDE_QUEUED |\n| Matrix change | ${change} |\n| Task | ${taskPath} |\n| Result | ${resultPath} |\n`;
284
+ }
275
285
  function paths(cwd, id, archived = false) {
276
- const root = rootFor(cwd);
277
- const change = path.join(root, archived ? "archive" : "changes", id);
278
- return {
279
- root,
280
- active: path.join(root, "active.json"),
286
+ const root = rootFor(cwd);
287
+ const change = path.join(root, archived ? "archive" : "changes", id);
288
+ return {
289
+ root,
290
+ active: path.join(root, "active.json"),
281
291
  change,
282
292
  flow: path.join(change, "matrix.yaml"),
283
293
  artifacts: path.join(change, "artifacts"),
@@ -285,53 +295,53 @@ function paths(cwd, id, archived = false) {
285
295
  workspaceBaseline: path.join(change, WORKSPACE_BASELINE_FILE)
286
296
  };
287
297
  }
288
- function normalizeFlow(flow) {
289
- if (!flow) return null;
290
- if (flow.schema !== "matrix/change/v2") return flow.schema ? { unsupported_schema: flow.schema } : null;
291
- const revision = Number(flow.revision);
292
- const approved = flow.approved_contract_hash || null;
298
+ function normalizeFlow(flow) {
299
+ if (!flow) return null;
300
+ if (flow.schema !== "matrix/change/v2") return flow.schema ? { unsupported_schema: flow.schema } : null;
301
+ const revision = Number(flow.revision);
302
+ const approved = flow.approved_contract_hash || null;
293
303
  const approvalRevision = flow.contract_approved_revision === "" || flow.contract_approved_revision == null ? null : Number(flow.contract_approved_revision);
294
304
  const workflowProfile = flow.workflow_profile || null;
295
305
  const archCatalogDigest = flow.arch_catalog_digest || null;
296
306
  const mattRelease = flow.matt_release || null;
297
- if (
298
- typeof flow.id !== "string" || !flow.id ||
299
- !["full", "hotfix", "tweak"].includes(flow.workflow) ||
300
- !ORCHESTRATIONS.includes(flow.orchestration) ||
301
- !["active", "archived", "aborted"].includes(flow.status) ||
302
- !PHASES.includes(flow.phase) ||
303
- !Number.isInteger(revision) || revision < 1 ||
304
- (workflowProfile !== null && workflowProfile !== "lightweight") ||
305
- (workflowProfile === "lightweight" && !["hotfix", "tweak"].includes(flow.workflow)) ||
307
+ if (
308
+ typeof flow.id !== "string" || !flow.id ||
309
+ !["full", "hotfix", "tweak"].includes(flow.workflow) ||
310
+ !ORCHESTRATIONS.includes(flow.orchestration) ||
311
+ !["active", "archived", "aborted"].includes(flow.status) ||
312
+ !PHASES.includes(flow.phase) ||
313
+ !Number.isInteger(revision) || revision < 1 ||
314
+ (workflowProfile !== null && workflowProfile !== "lightweight") ||
315
+ (workflowProfile === "lightweight" && !["hotfix", "tweak"].includes(flow.workflow)) ||
306
316
  (flow.artifact_language != null && !["en", "zh-CN"].includes(flow.artifact_language)) ||
307
317
  Boolean(archCatalogDigest) !== Boolean(mattRelease) ||
308
318
  (archCatalogDigest && !/^[0-9a-f]{64}$/.test(archCatalogDigest)) ||
309
- Boolean(approved) !== Boolean(approvalRevision) ||
310
- (approved && !/^sha256:[0-9a-f]{64}$/.test(approved)) ||
311
- (approvalRevision != null && (!Number.isInteger(approvalRevision) || approvalRevision < 1 || approvalRevision > revision))
312
- ) return null;
319
+ Boolean(approved) !== Boolean(approvalRevision) ||
320
+ (approved && !/^sha256:[0-9a-f]{64}$/.test(approved)) ||
321
+ (approvalRevision != null && (!Number.isInteger(approvalRevision) || approvalRevision < 1 || approvalRevision > revision))
322
+ ) return null;
313
323
  return { ...flow, revision, workflow_profile: workflowProfile, artifact_language: flow.artifact_language ?? null, arch_catalog_digest: archCatalogDigest, matt_release: mattRelease, approved_contract_hash: approved, contract_approved_revision: approvalRevision };
314
- }
315
- function readFlow(p) {
316
- if (!fs.existsSync(p.flow)) return null;
317
- const parsed = Object.fromEntries(fs.readFileSync(p.flow, "utf8").split(/\r?\n/).filter((line) => line.includes(":") && !line.startsWith(" ")).map((line) => { const [key, ...value] = line.split(":"); return [key.trim(), value.join(":").trim().replace(/^"|"$/g, "")]; }));
318
- return normalizeFlow(parsed);
319
- }
320
- function flowContent(flow) {
324
+ }
325
+ function readFlow(p) {
326
+ if (!fs.existsSync(p.flow)) return null;
327
+ const parsed = Object.fromEntries(fs.readFileSync(p.flow, "utf8").split(/\r?\n/).filter((line) => line.includes(":") && !line.startsWith(" ")).map((line) => { const [key, ...value] = line.split(":"); return [key.trim(), value.join(":").trim().replace(/^"|"$/g, "")]; }));
328
+ return normalizeFlow(parsed);
329
+ }
330
+ function flowContent(flow) {
321
331
  const order = ["schema", "id", "workflow", "workflow_profile", "orchestration", "artifact_language", "arch_catalog_digest", "matt_release", "status", "phase", "revision", "approved_contract_hash", "contract_approved_revision", "title", "created_at", "updated_at", "acceptance", "scope"];
322
332
  return `${order.filter((key) => (!["workflow_profile", "artifact_language", "arch_catalog_digest", "matt_release"].includes(key) || flow[key])).map((key) => `${key}: ${flow[key] ?? ""}`).join("\n")}\n`;
323
- }
324
- function active(cwd) { const activeFile = path.join(rootFor(cwd), "active.json"); if (!fs.existsSync(activeFile)) return null; return read(activeFile).change_id; }
333
+ }
334
+ function active(cwd) { const activeFile = path.join(rootFor(cwd), "active.json"); if (!fs.existsSync(activeFile)) return null; return read(activeFile).change_id; }
325
335
  function meaningful(file, headings) {
326
- if (!fs.existsSync(file)) return false;
327
- const value = fs.readFileSync(file, "utf8").trim();
328
- if (value.length < 40) return false;
329
- return headings.every((heading) => {
330
- const start = value.indexOf(heading);
331
- if (start < 0) return false;
332
- const bodyStart = start + heading.length;
333
- const next = value.indexOf("\n## ", bodyStart);
334
- return value.slice(bodyStart, next < 0 ? value.length : next).trim().length >= 8;
336
+ if (!fs.existsSync(file)) return false;
337
+ const value = fs.readFileSync(file, "utf8").trim();
338
+ if (value.length < 40) return false;
339
+ return headings.every((heading) => {
340
+ const start = value.indexOf(heading);
341
+ if (start < 0) return false;
342
+ const bodyStart = start + heading.length;
343
+ const next = value.indexOf("\n## ", bodyStart);
344
+ return value.slice(bodyStart, next < 0 ? value.length : next).trim().length >= 8;
335
345
  });
336
346
  }
337
347
  function digestText(domain, value) {
@@ -457,188 +467,188 @@ function reviewReceiptGuard(p, flow) {
457
467
  }
458
468
  return { ok: true, code: "OK", receipt };
459
469
  }
460
- function shortcut(flow) { return flow.workflow === "hotfix" || flow.workflow === "tweak"; }
461
- function contractSnapshotForFiles(p, files) {
462
- const hash = crypto.createHash("sha256");
463
- hash.update("matrix/workflow-contract/v1\\0", "utf8");
464
- const contents = {};
465
- for (const name of files) {
466
- const logical = `artifacts/${name}`;
467
- let bytes;
468
- try { bytes = fs.readFileSync(path.join(p.artifacts, name)); }
469
- catch (error) { if (error.code === "ENOENT") return { missing: true, contents }; return { error, contents }; }
470
- const pathBytes = Buffer.from(logical, "utf8");
471
- const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
472
- const contentLength = Buffer.alloc(8); contentLength.writeBigUInt64BE(BigInt(bytes.length));
473
- hash.update(pathLength); hash.update(pathBytes); hash.update(contentLength); hash.update(bytes);
474
- contents[name] = bytes.toString("utf8");
475
- }
476
- return { hash: `sha256:${hash.digest("hex")}`, contents };
477
- }
478
- function workflowProfile(p, flow) {
479
- if (!shortcut(flow)) return FULL_PROFILE;
480
- return flow.workflow_profile === "lightweight" ? LIGHTWEIGHT_PROFILE : { ...FULL_PROFILE, id: "legacy-full" };
481
- }
482
- function evidencePolicy(flow, profile) {
483
- return profile.id === "lightweight" ? flow.workflow : "full";
484
- }
485
- function structuralGuard(p, flow, phase) {
486
- const base = p.artifacts;
487
- const profile = workflowProfile(p, flow);
488
- const policy = evidencePolicy(flow, profile);
489
- const shortcutPolicy = LIGHTWEIGHT_POLICY[policy];
490
- const checks = phase === "open" ? [["proposal", meaningful(path.join(base, "proposal.md"), shortcutPolicy?.proposal ?? ARTIFACT_POLICY.proposal)]]
491
- : phase === "design" ? [["proposal", meaningful(path.join(base, "proposal.md"), ARTIFACT_POLICY.proposal)], ["design", meaningful(path.join(base, "design.md"), ARTIFACT_POLICY.design)], ["plan", meaningful(path.join(base, "plan.md"), ARTIFACT_POLICY.plan)]]
492
- : phase === "build" ? [
493
- ...(profile.id === "lightweight" ? [] : [["plan", meaningful(path.join(base, "plan.md"), ARTIFACT_POLICY.plan)]]),
494
- ["build evidence", meaningful(path.join(base, "verification.md"), shortcutPolicy?.build ?? ARTIFACT_POLICY.build)]
495
- ]
496
- : [["verification", meaningful(path.join(base, "verification.md"), shortcutPolicy?.verification ?? ARTIFACT_POLICY.verification)]];
497
- return { pass: checks.every(([, result]) => result), checks };
498
- }
499
- function contractSnapshot(p, flow) {
500
- return contractSnapshotForFiles(p, workflowProfile(p, flow).contractFiles);
501
- }
502
- function contractState(p, flow) {
503
- const snapshot = contractSnapshot(p, flow);
504
- if (snapshot.error) return { status: "unreadable", snapshot };
505
- if (!flow.approved_contract_hash) return { status: "unapproved", snapshot };
506
- if (snapshot.missing || snapshot.hash !== flow.approved_contract_hash) return { status: "changed", snapshot };
507
- return { status: "approved-and-matching", snapshot };
508
- }
509
- function contractFields(flow, contract) {
510
- return {
511
- contract_status: contract.status,
512
- current_contract_hash: contract.snapshot.hash ?? null,
513
- approved_contract_hash: flow.approved_contract_hash,
514
- contract_approved_revision: flow.contract_approved_revision
515
- };
516
- }
517
- function contractFailure(flow, contract) {
518
- if (contract.status === "approved-and-matching") return null;
519
- if (contract.status === "unreadable") return { ...fail("CONTRACT_READ_FAILED", contract.snapshot.error.message), ...contractFields(flow, contract) };
520
- return { ...fail(contract.status === "unapproved" ? "CONTRACT_UNAPPROVED" : "CONTRACT_CHANGED", `Workflow contract is ${contract.status}.`), ...contractFields(flow, contract) };
521
- }
522
- function addFramedEntry(hash, type, logicalPath, content = Buffer.alloc(0)) {
523
- const typeBytes = Buffer.from(type, "utf8");
524
- const pathBytes = Buffer.from(logicalPath, "utf8");
525
- const typeLength = Buffer.alloc(4); typeLength.writeUInt32BE(typeBytes.length);
526
- const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
527
- const contentLength = Buffer.alloc(8); contentLength.writeBigUInt64BE(BigInt(content.length));
528
- hash.update(typeLength); hash.update(typeBytes); hash.update(pathLength); hash.update(pathBytes); hash.update(contentLength); hash.update(content);
529
- }
530
- function addFramedFile(hash, entry) {
531
- const typeBytes = Buffer.from(entry.type, "utf8");
532
- const pathBytes = Buffer.from(entry.logicalPath, "utf8");
533
- const typeLength = Buffer.alloc(4); typeLength.writeUInt32BE(typeBytes.length);
534
- const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
535
- const contentLength = Buffer.alloc(8); contentLength.writeBigUInt64BE(BigInt(entry.size));
536
- hash.update(typeLength); hash.update(typeBytes); hash.update(pathLength); hash.update(pathBytes); hash.update(contentLength);
537
- const descriptor = fs.openSync(entry.source, "r");
538
- try {
539
- const opened = fs.fstatSync(descriptor);
540
- if (!opened.isFile() || opened.size !== entry.size) throw new Error(`Archive file changed while opening: ${entry.logicalPath}.`);
541
- const chunk = Buffer.allocUnsafe(64 * 1024);
542
- let offset = 0;
543
- while (offset < entry.size) {
544
- const length = fs.readSync(descriptor, chunk, 0, Math.min(chunk.length, entry.size - offset), offset);
545
- if (length === 0) throw new Error(`Archive file changed while reading: ${entry.logicalPath}.`);
546
- hash.update(chunk.subarray(0, length));
547
- offset += length;
548
- }
549
- if (fs.readSync(descriptor, chunk, 0, 1, offset) !== 0) throw new Error(`Archive file changed while reading: ${entry.logicalPath}.`);
550
- } finally {
551
- fs.closeSync(descriptor);
552
- }
553
- }
554
- function archiveDirectoryEntries(root, relative = "") {
555
- const entries = [];
556
- const names = fs.readdirSync(path.join(root, relative)).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)));
557
- for (const name of names) {
558
- const childRelative = relative ? `${relative}/${name}` : name;
559
- const child = path.join(root, ...childRelative.split("/"));
560
- const stat = fs.lstatSync(child);
561
- if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
562
- const error = new Error(`Archive change contains unsupported filesystem entry: ${childRelative}.`);
563
- error.code = "ARCHIVE_ENTRY_UNSUPPORTED";
564
- throw error;
565
- }
566
- if (stat.isDirectory()) {
567
- entries.push({ type: "directory", logicalPath: `change/${childRelative}`, content: Buffer.alloc(0) });
568
- entries.push(...archiveDirectoryEntries(root, childRelative));
569
- } else {
570
- entries.push({ type: "file", logicalPath: `change/${childRelative}`, source: child, size: stat.size });
571
- }
572
- }
573
- return entries;
574
- }
575
- function requireArchiveEntry(file, kind, label) {
576
- let stat;
577
- try { stat = fs.lstatSync(file); }
578
- catch (error) { return fail("ARCHIVE_PREFLIGHT_UNSTABLE", `${label} could not be inspected: ${error.message}`); }
579
- const valid = kind === "directory" ? stat.isDirectory() : stat.isFile();
580
- return stat.isSymbolicLink() || !valid ? fail("ARCHIVE_ENTRY_UNSUPPORTED", `${label} must be an ordinary ${kind}.`) : null;
581
- }
582
- function captureArchivePreflightOnce(p, id) {
583
- const target = path.join(p.root, "archive", id);
584
- if (fs.existsSync(target)) return { failure: fail("ARCHIVE_TARGET_EXISTS", `Archive target already exists: ${id}.`) };
585
- for (const [file, kind, label] of [[p.root, "directory", "Matrix state root"], [p.change, "directory", "Active change root"], [path.join(p.root, "archive"), "directory", "Archive root"], [p.active, "file", "Active Selection"]]) {
586
- const failure = requireArchiveEntry(file, kind, label); if (failure) return { failure };
587
- }
588
- let selection;
589
- try { selection = fs.readFileSync(p.active); }
590
- catch (error) { return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", `Active Selection could not be captured: ${error.message}`) }; }
591
- let entries;
592
- try {
593
- entries = archiveDirectoryEntries(p.change);
594
- entries.sort((left, right) => Buffer.compare(Buffer.from(left.logicalPath), Buffer.from(right.logicalPath)));
595
- }
596
- catch (error) {
597
- if (error.code === "ARCHIVE_ENTRY_UNSUPPORTED") return { failure: fail(error.code, error.message) };
598
- return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", `Archive inputs changed or could not be captured: ${error.message}`) };
599
- }
600
- const hash = crypto.createHash("sha256");
601
- hash.update("matrix/archive-preflight/v1\\0", "utf8");
602
- addFramedEntry(hash, "identity", "change-id", Buffer.from(id, "utf8"));
603
- addFramedEntry(hash, "identity", "archive-target", Buffer.from(`.matrix/archive/${id}`, "utf8"));
604
- addFramedEntry(hash, "selection", ".matrix/active.json", selection);
605
- addFramedEntry(hash, "fact", "archive-target-state", Buffer.from("absent", "utf8"));
606
- let fileCount = 0; let directoryCount = 0; let totalBytes = 0;
607
- try {
608
- for (const entry of entries) {
609
- if (entry.type === "file") {
610
- addFramedFile(hash, entry);
611
- fileCount += 1;
612
- totalBytes += entry.size;
613
- } else {
614
- addFramedEntry(hash, entry.type, entry.logicalPath, entry.content);
615
- directoryCount += 1;
616
- }
617
- }
618
- } catch (error) {
619
- return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", `Archive inputs changed or could not be captured: ${error.message}`) };
620
- }
621
- return { hash: `sha256:${hash.digest("hex")}`, fileCount, directoryCount, totalBytes };
622
- }
623
- function captureArchivePreflight(p, id) {
624
- const first = captureArchivePreflightOnce(p, id); if (first.failure) return first;
625
- const second = captureArchivePreflightOnce(p, id); if (second.failure) return second;
626
- if (first.hash !== second.hash) return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", "Archive inputs changed while the preflight snapshot was being captured. Retry dry-run.") };
627
- return second;
628
- }
629
- function archivePreflightChanged(expected, current) {
630
- return {
631
- ...fail("ARCHIVE_PREFLIGHT_CHANGED", "Archive inputs changed after dry-run. Run dry-run again and review the new preflight."),
632
- expected_preflight_hash: expected,
633
- current_preflight_hash: current,
470
+ function shortcut(flow) { return flow.workflow === "hotfix" || flow.workflow === "tweak"; }
471
+ function contractSnapshotForFiles(p, files) {
472
+ const hash = crypto.createHash("sha256");
473
+ hash.update("matrix/workflow-contract/v1\\0", "utf8");
474
+ const contents = {};
475
+ for (const name of files) {
476
+ const logical = `artifacts/${name}`;
477
+ let bytes;
478
+ try { bytes = fs.readFileSync(path.join(p.artifacts, name)); }
479
+ catch (error) { if (error.code === "ENOENT") return { missing: true, contents }; return { error, contents }; }
480
+ const pathBytes = Buffer.from(logical, "utf8");
481
+ const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
482
+ const contentLength = Buffer.alloc(8); contentLength.writeBigUInt64BE(BigInt(bytes.length));
483
+ hash.update(pathLength); hash.update(pathBytes); hash.update(contentLength); hash.update(bytes);
484
+ contents[name] = bytes.toString("utf8");
485
+ }
486
+ return { hash: `sha256:${hash.digest("hex")}`, contents };
487
+ }
488
+ function workflowProfile(p, flow) {
489
+ if (!shortcut(flow)) return FULL_PROFILE;
490
+ return flow.workflow_profile === "lightweight" ? LIGHTWEIGHT_PROFILE : { ...FULL_PROFILE, id: "legacy-full" };
491
+ }
492
+ function evidencePolicy(flow, profile) {
493
+ return profile.id === "lightweight" ? flow.workflow : "full";
494
+ }
495
+ function structuralGuard(p, flow, phase) {
496
+ const base = p.artifacts;
497
+ const profile = workflowProfile(p, flow);
498
+ const policy = evidencePolicy(flow, profile);
499
+ const shortcutPolicy = LIGHTWEIGHT_POLICY[policy];
500
+ const checks = phase === "open" ? [["proposal", meaningful(path.join(base, "proposal.md"), shortcutPolicy?.proposal ?? ARTIFACT_POLICY.proposal)]]
501
+ : phase === "design" ? [["proposal", meaningful(path.join(base, "proposal.md"), ARTIFACT_POLICY.proposal)], ["design", meaningful(path.join(base, "design.md"), ARTIFACT_POLICY.design)], ["plan", meaningful(path.join(base, "plan.md"), ARTIFACT_POLICY.plan)]]
502
+ : phase === "build" ? [
503
+ ...(profile.id === "lightweight" ? [] : [["plan", meaningful(path.join(base, "plan.md"), ARTIFACT_POLICY.plan)]]),
504
+ ["build evidence", meaningful(path.join(base, "verification.md"), shortcutPolicy?.build ?? ARTIFACT_POLICY.build)]
505
+ ]
506
+ : [["verification", meaningful(path.join(base, "verification.md"), shortcutPolicy?.verification ?? ARTIFACT_POLICY.verification)]];
507
+ return { pass: checks.every(([, result]) => result), checks };
508
+ }
509
+ function contractSnapshot(p, flow) {
510
+ return contractSnapshotForFiles(p, workflowProfile(p, flow).contractFiles);
511
+ }
512
+ function contractState(p, flow) {
513
+ const snapshot = contractSnapshot(p, flow);
514
+ if (snapshot.error) return { status: "unreadable", snapshot };
515
+ if (!flow.approved_contract_hash) return { status: "unapproved", snapshot };
516
+ if (snapshot.missing || snapshot.hash !== flow.approved_contract_hash) return { status: "changed", snapshot };
517
+ return { status: "approved-and-matching", snapshot };
518
+ }
519
+ function contractFields(flow, contract) {
520
+ return {
521
+ contract_status: contract.status,
522
+ current_contract_hash: contract.snapshot.hash ?? null,
523
+ approved_contract_hash: flow.approved_contract_hash,
524
+ contract_approved_revision: flow.contract_approved_revision
525
+ };
526
+ }
527
+ function contractFailure(flow, contract) {
528
+ if (contract.status === "approved-and-matching") return null;
529
+ if (contract.status === "unreadable") return { ...fail("CONTRACT_READ_FAILED", contract.snapshot.error.message), ...contractFields(flow, contract) };
530
+ return { ...fail(contract.status === "unapproved" ? "CONTRACT_UNAPPROVED" : "CONTRACT_CHANGED", `Workflow contract is ${contract.status}.`), ...contractFields(flow, contract) };
531
+ }
532
+ function addFramedEntry(hash, type, logicalPath, content = Buffer.alloc(0)) {
533
+ const typeBytes = Buffer.from(type, "utf8");
534
+ const pathBytes = Buffer.from(logicalPath, "utf8");
535
+ const typeLength = Buffer.alloc(4); typeLength.writeUInt32BE(typeBytes.length);
536
+ const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
537
+ const contentLength = Buffer.alloc(8); contentLength.writeBigUInt64BE(BigInt(content.length));
538
+ hash.update(typeLength); hash.update(typeBytes); hash.update(pathLength); hash.update(pathBytes); hash.update(contentLength); hash.update(content);
539
+ }
540
+ function addFramedFile(hash, entry) {
541
+ const typeBytes = Buffer.from(entry.type, "utf8");
542
+ const pathBytes = Buffer.from(entry.logicalPath, "utf8");
543
+ const typeLength = Buffer.alloc(4); typeLength.writeUInt32BE(typeBytes.length);
544
+ const pathLength = Buffer.alloc(4); pathLength.writeUInt32BE(pathBytes.length);
545
+ const contentLength = Buffer.alloc(8); contentLength.writeBigUInt64BE(BigInt(entry.size));
546
+ hash.update(typeLength); hash.update(typeBytes); hash.update(pathLength); hash.update(pathBytes); hash.update(contentLength);
547
+ const descriptor = fs.openSync(entry.source, "r");
548
+ try {
549
+ const opened = fs.fstatSync(descriptor);
550
+ if (!opened.isFile() || opened.size !== entry.size) throw new Error(`Archive file changed while opening: ${entry.logicalPath}.`);
551
+ const chunk = Buffer.allocUnsafe(64 * 1024);
552
+ let offset = 0;
553
+ while (offset < entry.size) {
554
+ const length = fs.readSync(descriptor, chunk, 0, Math.min(chunk.length, entry.size - offset), offset);
555
+ if (length === 0) throw new Error(`Archive file changed while reading: ${entry.logicalPath}.`);
556
+ hash.update(chunk.subarray(0, length));
557
+ offset += length;
558
+ }
559
+ if (fs.readSync(descriptor, chunk, 0, 1, offset) !== 0) throw new Error(`Archive file changed while reading: ${entry.logicalPath}.`);
560
+ } finally {
561
+ fs.closeSync(descriptor);
562
+ }
563
+ }
564
+ function archiveDirectoryEntries(root, relative = "") {
565
+ const entries = [];
566
+ const names = fs.readdirSync(path.join(root, relative)).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)));
567
+ for (const name of names) {
568
+ const childRelative = relative ? `${relative}/${name}` : name;
569
+ const child = path.join(root, ...childRelative.split("/"));
570
+ const stat = fs.lstatSync(child);
571
+ if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
572
+ const error = new Error(`Archive change contains unsupported filesystem entry: ${childRelative}.`);
573
+ error.code = "ARCHIVE_ENTRY_UNSUPPORTED";
574
+ throw error;
575
+ }
576
+ if (stat.isDirectory()) {
577
+ entries.push({ type: "directory", logicalPath: `change/${childRelative}`, content: Buffer.alloc(0) });
578
+ entries.push(...archiveDirectoryEntries(root, childRelative));
579
+ } else {
580
+ entries.push({ type: "file", logicalPath: `change/${childRelative}`, source: child, size: stat.size });
581
+ }
582
+ }
583
+ return entries;
584
+ }
585
+ function requireArchiveEntry(file, kind, label) {
586
+ let stat;
587
+ try { stat = fs.lstatSync(file); }
588
+ catch (error) { return fail("ARCHIVE_PREFLIGHT_UNSTABLE", `${label} could not be inspected: ${error.message}`); }
589
+ const valid = kind === "directory" ? stat.isDirectory() : stat.isFile();
590
+ return stat.isSymbolicLink() || !valid ? fail("ARCHIVE_ENTRY_UNSUPPORTED", `${label} must be an ordinary ${kind}.`) : null;
591
+ }
592
+ function captureArchivePreflightOnce(p, id) {
593
+ const target = path.join(p.root, "archive", id);
594
+ if (fs.existsSync(target)) return { failure: fail("ARCHIVE_TARGET_EXISTS", `Archive target already exists: ${id}.`) };
595
+ for (const [file, kind, label] of [[p.root, "directory", "Matrix state root"], [p.change, "directory", "Active change root"], [path.join(p.root, "archive"), "directory", "Archive root"], [p.active, "file", "Active Selection"]]) {
596
+ const failure = requireArchiveEntry(file, kind, label); if (failure) return { failure };
597
+ }
598
+ let selection;
599
+ try { selection = fs.readFileSync(p.active); }
600
+ catch (error) { return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", `Active Selection could not be captured: ${error.message}`) }; }
601
+ let entries;
602
+ try {
603
+ entries = archiveDirectoryEntries(p.change);
604
+ entries.sort((left, right) => Buffer.compare(Buffer.from(left.logicalPath), Buffer.from(right.logicalPath)));
605
+ }
606
+ catch (error) {
607
+ if (error.code === "ARCHIVE_ENTRY_UNSUPPORTED") return { failure: fail(error.code, error.message) };
608
+ return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", `Archive inputs changed or could not be captured: ${error.message}`) };
609
+ }
610
+ const hash = crypto.createHash("sha256");
611
+ hash.update("matrix/archive-preflight/v1\\0", "utf8");
612
+ addFramedEntry(hash, "identity", "change-id", Buffer.from(id, "utf8"));
613
+ addFramedEntry(hash, "identity", "archive-target", Buffer.from(`.matrix/archive/${id}`, "utf8"));
614
+ addFramedEntry(hash, "selection", ".matrix/active.json", selection);
615
+ addFramedEntry(hash, "fact", "archive-target-state", Buffer.from("absent", "utf8"));
616
+ let fileCount = 0; let directoryCount = 0; let totalBytes = 0;
617
+ try {
618
+ for (const entry of entries) {
619
+ if (entry.type === "file") {
620
+ addFramedFile(hash, entry);
621
+ fileCount += 1;
622
+ totalBytes += entry.size;
623
+ } else {
624
+ addFramedEntry(hash, entry.type, entry.logicalPath, entry.content);
625
+ directoryCount += 1;
626
+ }
627
+ }
628
+ } catch (error) {
629
+ return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", `Archive inputs changed or could not be captured: ${error.message}`) };
630
+ }
631
+ return { hash: `sha256:${hash.digest("hex")}`, fileCount, directoryCount, totalBytes };
632
+ }
633
+ function captureArchivePreflight(p, id) {
634
+ const first = captureArchivePreflightOnce(p, id); if (first.failure) return first;
635
+ const second = captureArchivePreflightOnce(p, id); if (second.failure) return second;
636
+ if (first.hash !== second.hash) return { failure: fail("ARCHIVE_PREFLIGHT_UNSTABLE", "Archive inputs changed while the preflight snapshot was being captured. Retry dry-run.") };
637
+ return second;
638
+ }
639
+ function archivePreflightChanged(expected, current) {
640
+ return {
641
+ ...fail("ARCHIVE_PREFLIGHT_CHANGED", "Archive inputs changed after dry-run. Run dry-run again and review the new preflight."),
642
+ expected_preflight_hash: expected,
643
+ current_preflight_hash: current,
634
644
  recovery_command: workflowCommand("archive --dry-run")
635
- };
636
- }
645
+ };
646
+ }
637
647
  function guard(p, flow, phase) {
638
- if (!["build", "verify", "archive"].includes(phase)) {
639
- const structural = structuralGuard(p, flow, phase);
640
- return { ok: structural.pass, code: structural.pass ? "OK" : "GUARD_FAILED", ...structural };
641
- }
648
+ if (!["build", "verify", "archive"].includes(phase)) {
649
+ const structural = structuralGuard(p, flow, phase);
650
+ return { ok: structural.pass, code: structural.pass ? "OK" : "GUARD_FAILED", ...structural };
651
+ }
642
652
  const contract = contractState(p, flow); const failure = contractFailure(flow, contract);
643
653
  if (failure) return { ok: false, ...failure, checks: [["contract", false]] };
644
654
  const structural = structuralGuard(p, flow, phase);
@@ -656,115 +666,115 @@ function guard(p, flow, phase) {
656
666
  }
657
667
  return { ok: true, code: "OK", pass: true, ...contractFields(flow, contract), checks };
658
668
  }
659
- function eventContent(file, name, before, after, revision, details = {}) {
660
- const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
661
- return `${current}${JSON.stringify({ schema: "matrix/event/v1", at: stamp(), event: name, revision, from: before, to: after, ...details })}\n`;
662
- }
669
+ function eventContent(file, name, before, after, revision, details = {}) {
670
+ const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
671
+ return `${current}${JSON.stringify({ schema: "matrix/event/v1", at: stamp(), event: name, revision, from: before, to: after, ...details })}\n`;
672
+ }
663
673
  export function invoke(argv, { cwd = process.cwd(), failAfterOperation = null, mattContentHashes = MATT_CONTENT_HASHES } = {}) {
664
- const [command, ...args] = argv;
665
- if (command === "init") {
666
- const id = (args.shift() ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
667
- const workflow = args.includes("--workflow") ? args[args.indexOf("--workflow") + 1] : "full";
668
- const title = args.includes("--title") ? args[args.indexOf("--title") + 1] : null;
669
- const requestedOrchestration = option(args, "--orchestration");
670
- if (requestedOrchestration != null && !ORCHESTRATIONS.includes(requestedOrchestration)) return fail("INVALID_INTENT", "orchestration must be prim or arch.");
671
- const configured = orchestrationConfig(cwd);
672
- const orchestration = requestedOrchestration ?? configured.defaultOrchestration;
673
- if (!id || !title || !["full", "hotfix", "tweak"].includes(workflow)) return fail("INVALID_INTENT", "init requires a valid change id and --title.");
674
- if (orchestration === "arch") {
674
+ const [command, ...args] = argv;
675
+ if (command === "init") {
676
+ const id = (args.shift() ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
677
+ const workflow = args.includes("--workflow") ? args[args.indexOf("--workflow") + 1] : "full";
678
+ const title = args.includes("--title") ? args[args.indexOf("--title") + 1] : null;
679
+ const requestedOrchestration = option(args, "--orchestration");
680
+ if (requestedOrchestration != null && !ORCHESTRATIONS.includes(requestedOrchestration)) return fail("INVALID_INTENT", "orchestration must be prim or arch.");
681
+ const configured = orchestrationConfig(cwd);
682
+ const orchestration = requestedOrchestration ?? configured.defaultOrchestration;
683
+ if (!id || !title || !["full", "hotfix", "tweak"].includes(workflow)) return fail("INVALID_INTENT", "init requires a valid change id and --title.");
684
+ if (orchestration === "arch") {
675
685
  const integrity = archIntegrity(cwd, null, mattContentHashes);
676
- if (!integrity.ok) return { ...integrity, orchestration };
677
- }
678
- if (active(cwd)) return fail("ACTIVE_CHANGE_EXISTS", `Active Matrix change already exists: ${active(cwd)}.`);
679
- const p = paths(cwd, id); if (fs.existsSync(p.change) || fs.existsSync(path.join(p.root, "archive", id))) return fail("CHANGE_EXISTS", `Matrix change already exists: ${id}.`);
680
- let workspaceBaseline = null;
681
- if (workflow === "hotfix" || workflow === "tweak") {
682
- try { workspaceBaseline = captureWorkspaceBaseline(cwd); }
683
- catch (error) { return fail("WORKSPACE_BASELINE_FAILED", `Could not initialize the lightweight workflow boundary: ${error.message}`); }
684
- }
686
+ if (!integrity.ok) return { ...integrity, orchestration };
687
+ }
688
+ if (active(cwd)) return fail("ACTIVE_CHANGE_EXISTS", `Active Matrix change already exists: ${active(cwd)}.`);
689
+ const p = paths(cwd, id); if (fs.existsSync(p.change) || fs.existsSync(path.join(p.root, "archive", id))) return fail("CHANGE_EXISTS", `Matrix change already exists: ${id}.`);
690
+ let workspaceBaseline = null;
691
+ if (workflow === "hotfix" || workflow === "tweak") {
692
+ try { workspaceBaseline = captureWorkspaceBaseline(cwd); }
693
+ catch (error) { return fail("WORKSPACE_BASELINE_FAILED", `Could not initialize the lightweight workflow boundary: ${error.message}`); }
694
+ }
685
695
  const flow = { schema: "matrix/change/v2", id, workflow, ...(workflow === "full" ? {} : { workflow_profile: "lightweight" }), orchestration, artifact_language: configured.artifactLanguage, ...(orchestration === "arch" ? { arch_catalog_digest: MATT_CATALOG_DIGEST, matt_release: MATT_COMPATIBILITY.release } : {}), status: "active", phase: "open", revision: 1, title, created_at: stamp(), updated_at: stamp(), acceptance: "pending", scope: "pending" };
686
- const operations = [
687
- ...(!fs.existsSync(path.join(p.root, "archive")) ? [workflowMkdirOperation(cwd, path.join(p.root, "archive"))] : []),
688
- workflowMkdirOperation(cwd, p.artifacts),
689
- ...(!fs.existsSync(path.join(p.root, "config.yaml")) ? [workflowWriteOperation(cwd, path.join(p.root, "config.yaml"), `schema: matrix/config/v1\nauto_transition: true\ndefault_orchestration: ${configured.defaultOrchestration}\ninstallation_scope: project\nlanguage: ${configured.artifactLanguage}\n`)] : []),
696
+ const operations = [
697
+ ...(!fs.existsSync(path.join(p.root, "archive")) ? [workflowMkdirOperation(cwd, path.join(p.root, "archive"))] : []),
698
+ workflowMkdirOperation(cwd, p.artifacts),
699
+ ...(!fs.existsSync(path.join(p.root, "config.yaml")) ? [workflowWriteOperation(cwd, path.join(p.root, "config.yaml"), `schema: matrix/config/v1\nauto_transition: true\ndefault_orchestration: ${configured.defaultOrchestration}\ninstallation_scope: project\nlanguage: ${configured.artifactLanguage}\n`)] : []),
690
700
  ...(!fs.existsSync(path.join(p.root, ".gitignore")) ? [workflowWriteOperation(cwd, path.join(p.root, ".gitignore"), "active.json\ninstallation.json\nmatt-installation.json\nchanges/*/events.jsonl\nchanges/*/artifacts/handoff.md\n")] : []),
691
- workflowWriteOperation(cwd, p.flow, flowContent(flow)),
692
- ...(workspaceBaseline ? [workflowWriteOperation(cwd, p.workspaceBaseline, `${JSON.stringify(workspaceBaseline, null, 2)}\n`)] : []),
701
+ workflowWriteOperation(cwd, p.flow, flowContent(flow)),
702
+ ...(workspaceBaseline ? [workflowWriteOperation(cwd, p.workspaceBaseline, `${JSON.stringify(workspaceBaseline, null, 2)}\n`)] : []),
693
703
  workflowWriteOperation(cwd, path.join(p.change, "events.jsonl"), eventContent(path.join(p.change, "events.jsonl"), "initialized", null, "open", flow.revision, { workflow, orchestration, ...(orchestration === "arch" ? { arch_catalog_digest: MATT_CATALOG_DIGEST, matt_release: MATT_COMPATIBILITY.release } : {}), ...(shortcut(flow) ? { profile: "lightweight" } : {}) })),
694
- workflowWriteOperation(cwd, p.active, `${JSON.stringify({ change_id: id }, null, 2)}\n`)
695
- ];
696
- return runWorkflowTransaction({
697
- cwd,
698
- kind: "init",
699
- changeId: id,
700
- operations,
701
- failAfterOperation,
704
+ workflowWriteOperation(cwd, p.active, `${JSON.stringify({ change_id: id }, null, 2)}\n`)
705
+ ];
706
+ return runWorkflowTransaction({
707
+ cwd,
708
+ kind: "init",
709
+ changeId: id,
710
+ operations,
711
+ failAfterOperation,
702
712
  result: { ok: true, code: "OK", change_id: id, workflow, profile: shortcut(flow) ? "lightweight" : "full", evidence_policy: workflow === "full" ? "full" : workflow, orchestration, artifact_language: flow.artifact_language, arch_catalog_digest: flow.arch_catalog_digest ?? null, matt_release: flow.matt_release ?? null, status: flow.status, phase: flow.phase, revision: flow.revision, next_skill: skill("open") }
703
- });
704
- }
705
- if (command === "doctor") {
706
- const parsed = { repair: false, transaction: null, strategy: null, lock: null };
707
- for (let index = 0; index < args.length; index += 1) {
708
- const token = args[index];
709
- if (token === "--repair") {
710
- if (parsed.repair) return fail("INVALID_INTENT", "Workflow doctor options may not be repeated.");
711
- parsed.repair = true;
712
- continue;
713
- }
714
- const field = ({ "--transaction": "transaction", "--strategy": "strategy", "--lock": "lock" })[token];
715
- const value = args[index + 1];
716
- if (!field || parsed[field] || !value || value.startsWith("--")) return fail("INVALID_INTENT", "Workflow doctor accepts --repair with --transaction/--strategy or --lock.");
717
- parsed[field] = value;
718
- index += 1;
719
- }
720
- return workflowDoctor(cwd, parsed);
721
- }
722
- const selected = active(cwd);
723
- const requested = command === "inspect" ? (option(args, "--change") ?? args.find((arg) => !arg.startsWith("--"))) : null;
724
- const id = requested ?? selected;
725
- if (!id) return fail("NO_ACTIVE_CHANGE", "No active Matrix change. Start with $matrix <request>.");
726
- let p = paths(cwd, id);
727
- if (command === "inspect" && !fs.existsSync(p.change)) p = paths(cwd, id, true);
728
- const flow = readFlow(p);
729
- if (flow?.unsupported_schema) return fail("STATE_VERSION_UNSUPPORTED", `Unsupported Matrix state schema: ${flow.unsupported_schema}.`);
730
- if (!flow) return fail("STATE_INVALID", "active.json does not reference a valid Matrix change.");
731
- const artifactLanguage = flow.artifact_language ?? orchestrationConfig(cwd).artifactLanguage;
713
+ });
714
+ }
715
+ if (command === "doctor") {
716
+ const parsed = { repair: false, transaction: null, strategy: null, lock: null };
717
+ for (let index = 0; index < args.length; index += 1) {
718
+ const token = args[index];
719
+ if (token === "--repair") {
720
+ if (parsed.repair) return fail("INVALID_INTENT", "Workflow doctor options may not be repeated.");
721
+ parsed.repair = true;
722
+ continue;
723
+ }
724
+ const field = ({ "--transaction": "transaction", "--strategy": "strategy", "--lock": "lock" })[token];
725
+ const value = args[index + 1];
726
+ if (!field || parsed[field] || !value || value.startsWith("--")) return fail("INVALID_INTENT", "Workflow doctor accepts --repair with --transaction/--strategy or --lock.");
727
+ parsed[field] = value;
728
+ index += 1;
729
+ }
730
+ return workflowDoctor(cwd, parsed);
731
+ }
732
+ const selected = active(cwd);
733
+ const requested = command === "inspect" ? (option(args, "--change") ?? args.find((arg) => !arg.startsWith("--"))) : null;
734
+ const id = requested ?? selected;
735
+ if (!id) return fail("NO_ACTIVE_CHANGE", "No active Matrix change. Start with $matrix <request>.");
736
+ let p = paths(cwd, id);
737
+ if (command === "inspect" && !fs.existsSync(p.change)) p = paths(cwd, id, true);
738
+ const flow = readFlow(p);
739
+ if (flow?.unsupported_schema) return fail("STATE_VERSION_UNSUPPORTED", `Unsupported Matrix state schema: ${flow.unsupported_schema}.`);
740
+ if (!flow) return fail("STATE_INVALID", "active.json does not reference a valid Matrix change.");
741
+ const artifactLanguage = flow.artifact_language ?? orchestrationConfig(cwd).artifactLanguage;
732
742
  const integrity = flow.status === "active" && flow.orchestration === "arch" ? archIntegrity(cwd, flow, mattContentHashes) : { ok: true, code: "OK" };
733
- if (["transition", "return", "abort"].includes(command) || (command === "archive" && !args.includes("--dry-run"))) {
734
- const blocked = workflowMutationGate(cwd);
735
- if (blocked) return blocked;
736
- }
737
- if (command === "inspect") {
738
- const profile = workflowProfile(p, flow);
739
- const contract = contractState(p, flow);
740
- const result = guard(p, flow, flow.phase);
741
- const failure = contract.status === "unreadable" ? contractFailure(flow, contract) : null;
742
- return {
743
- ...(failure ?? (!integrity.ok ? integrity : { ok: true, code: "OK" })),
744
- change_id: id,
745
- workflow: flow.workflow,
746
- profile: profile.id,
747
- evidence_policy: evidencePolicy(flow, profile),
743
+ if (["transition", "return", "abort"].includes(command) || (command === "archive" && !args.includes("--dry-run"))) {
744
+ const blocked = workflowMutationGate(cwd);
745
+ if (blocked) return blocked;
746
+ }
747
+ if (command === "inspect") {
748
+ const profile = workflowProfile(p, flow);
749
+ const contract = contractState(p, flow);
750
+ const result = guard(p, flow, flow.phase);
751
+ const failure = contract.status === "unreadable" ? contractFailure(flow, contract) : null;
752
+ return {
753
+ ...(failure ?? (!integrity.ok ? integrity : { ok: true, code: "OK" })),
754
+ change_id: id,
755
+ workflow: flow.workflow,
756
+ profile: profile.id,
757
+ evidence_policy: evidencePolicy(flow, profile),
748
758
  orchestration: flow.orchestration,
749
759
  arch_catalog_digest: flow.arch_catalog_digest ?? null,
750
760
  matt_release: flow.matt_release ?? null,
751
- artifact_language: artifactLanguage,
752
- status: flow.status,
753
- phase: flow.phase,
754
- revision: flow.revision,
755
- next_skill: flow.status === "active" ? skill(flow.phase) : null,
756
- guard_pass: result.ok,
757
- ...contractFields(flow, contract)
758
- };
759
- }
760
- if (!integrity.ok && command !== "abort") {
761
- const profile = workflowProfile(p, flow);
762
- return { ...integrity, change_id: id, workflow: flow.workflow, profile: profile.id, evidence_policy: evidencePolicy(flow, profile), orchestration: flow.orchestration, artifact_language: artifactLanguage, status: flow.status, phase: flow.phase, revision: flow.revision, next_skill: skill(flow.phase) };
763
- }
761
+ artifact_language: artifactLanguage,
762
+ status: flow.status,
763
+ phase: flow.phase,
764
+ revision: flow.revision,
765
+ next_skill: flow.status === "active" ? skill(flow.phase) : null,
766
+ guard_pass: result.ok,
767
+ ...contractFields(flow, contract)
768
+ };
769
+ }
770
+ if (!integrity.ok && command !== "abort") {
771
+ const profile = workflowProfile(p, flow);
772
+ return { ...integrity, change_id: id, workflow: flow.workflow, profile: profile.id, evidence_policy: evidencePolicy(flow, profile), orchestration: flow.orchestration, artifact_language: artifactLanguage, status: flow.status, phase: flow.phase, revision: flow.revision, next_skill: skill(flow.phase) };
773
+ }
764
774
  if (command === "guard") {
765
- const phase = args[0] ?? flow.phase;
766
- if (!PHASES.includes(phase)) return fail("INVALID_INTENT", "Unknown phase.");
767
- const profile = workflowProfile(p, flow);
775
+ const phase = args[0] ?? flow.phase;
776
+ if (!PHASES.includes(phase)) return fail("INVALID_INTENT", "Unknown phase.");
777
+ const profile = workflowProfile(p, flow);
768
778
  if (profile.id === "lightweight" && phase === "design") return fail("PHASE_UNAVAILABLE", "Lightweight workflows do not have a Design phase.");
769
779
  return { phase, profile: profile.id, evidence_policy: evidencePolicy(flow, profile), artifact_language: artifactLanguage, ...guard(p, flow, phase) };
770
780
  }
@@ -846,50 +856,50 @@ export function invoke(argv, { cwd = process.cwd(), failAfterOperation = null, m
846
856
  });
847
857
  }
848
858
  if (command === "transition") {
849
- const to = args[0];
850
- const confirmed = args.includes("--confirmed");
851
- if (args.slice(1).some((arg) => arg !== "--confirmed")) return fail("INVALID_INTENT", "Transition accepts only a target phase and optional --confirmed.");
852
- if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
853
- const profile = workflowProfile(p, flow);
854
- if (profile.next[flow.phase] !== to) return fail("ILLEGAL_TRANSITION", `Illegal ${profile.id} transition ${flow.phase} -> ${to}.`);
855
- const result = guard(p, flow, flow.phase); if (!result.ok) return { ...result, message: result.message ?? "Current phase guard failed." };
856
- if (profile.id === "lightweight" && flow.phase === "open" && to === "build") {
857
- if (!confirmed) return fail("CONFIRMATION_REQUIRED", "Lightweight Open requires explicit user confirmation before Build.");
858
- const order = workspaceOrderGuard(cwd, p);
859
- if (!order.ok) return order;
860
- }
861
- const before = flow.phase;
862
- const approval = to === "build" ? contractState(p, flow) : null;
863
- if (approval && approval.status !== "approved-and-matching" && approval.status !== "unapproved") return { ...contractFailure(flow, approval), change_id: id };
864
- if (to === "build" && approval.snapshot.missing) return { ...fail("GUARD_FAILED", "Workflow contract artifacts are incomplete."), change_id: id };
865
- const next = { ...flow, schema: "matrix/change/v2", phase: to, revision: flow.revision + 1, updated_at: stamp(), ...(to === "build" ? { approved_contract_hash: approval.snapshot.hash, contract_approved_revision: flow.revision + 1 } : {}) };
866
- const nextProfile = workflowProfile(p, next);
867
- const details = to === "build"
868
- ? { approved_contract_hash: next.approved_contract_hash, contract_approved_revision: next.contract_approved_revision, ...(shortcut(flow) ? { confirmed, profile: nextProfile.id } : {}) }
869
- : shortcut(flow) ? { profile: nextProfile.id } : {};
870
- const resultFields = { ok: true, code: "OK", change_id: id, workflow: next.workflow, profile: nextProfile.id, evidence_policy: evidencePolicy(next, nextProfile), orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: to, revision: next.revision, next_skill: skill(to), ...contractFields(next, contractState(p, next)) };
871
- return runWorkflowTransaction({
872
- cwd,
873
- kind: "transition",
874
- changeId: id,
875
- failAfterOperation,
876
- operations: [
877
- workflowWriteOperation(cwd, p.flow, flowContent(next)),
878
- workflowWriteOperation(cwd, path.join(p.change, "events.jsonl"), eventContent(path.join(p.change, "events.jsonl"), "transition", before, to, next.revision, details))
879
- ],
880
- result: resultFields
881
- });
882
- }
883
- if (command === "return") {
884
- const to = args[0];
885
- const reason = option(args, "--reason");
886
- if (!reason) return fail("RETURN_REASON_REQUIRED", "Return requires --reason.");
887
- if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
888
- if (!RETURN_REASONS.has(reason)) return fail("RETURN_REASON_UNSUPPORTED", `Unsupported Return reason: ${reason}.`);
889
- const profile = workflowProfile(p, flow);
890
- const returns = profile.id === "lightweight" ? LIGHTWEIGHT_RETURNS : FULL_RETURNS;
891
- const returnRule = returns.find((entry) => entry.from === flow.phase && entry.to === to && entry.reason === reason);
892
- if (!returnRule) return fail("ILLEGAL_RETURN", `Illegal ${profile.id} Return ${flow.phase} -> ${to} for reason ${reason}.`);
859
+ const to = args[0];
860
+ const confirmed = args.includes("--confirmed");
861
+ if (args.slice(1).some((arg) => arg !== "--confirmed")) return fail("INVALID_INTENT", "Transition accepts only a target phase and optional --confirmed.");
862
+ if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
863
+ const profile = workflowProfile(p, flow);
864
+ if (profile.next[flow.phase] !== to) return fail("ILLEGAL_TRANSITION", `Illegal ${profile.id} transition ${flow.phase} -> ${to}.`);
865
+ const result = guard(p, flow, flow.phase); if (!result.ok) return { ...result, message: result.message ?? "Current phase guard failed." };
866
+ if (profile.id === "lightweight" && flow.phase === "open" && to === "build") {
867
+ if (!confirmed) return fail("CONFIRMATION_REQUIRED", "Lightweight Open requires explicit user confirmation before Build.");
868
+ const order = workspaceOrderGuard(cwd, p);
869
+ if (!order.ok) return order;
870
+ }
871
+ const before = flow.phase;
872
+ const approval = to === "build" ? contractState(p, flow) : null;
873
+ if (approval && approval.status !== "approved-and-matching" && approval.status !== "unapproved") return { ...contractFailure(flow, approval), change_id: id };
874
+ if (to === "build" && approval.snapshot.missing) return { ...fail("GUARD_FAILED", "Workflow contract artifacts are incomplete."), change_id: id };
875
+ const next = { ...flow, schema: "matrix/change/v2", phase: to, revision: flow.revision + 1, updated_at: stamp(), ...(to === "build" ? { approved_contract_hash: approval.snapshot.hash, contract_approved_revision: flow.revision + 1 } : {}) };
876
+ const nextProfile = workflowProfile(p, next);
877
+ const details = to === "build"
878
+ ? { approved_contract_hash: next.approved_contract_hash, contract_approved_revision: next.contract_approved_revision, ...(shortcut(flow) ? { confirmed, profile: nextProfile.id } : {}) }
879
+ : shortcut(flow) ? { profile: nextProfile.id } : {};
880
+ const resultFields = { ok: true, code: "OK", change_id: id, workflow: next.workflow, profile: nextProfile.id, evidence_policy: evidencePolicy(next, nextProfile), orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: to, revision: next.revision, next_skill: skill(to), ...contractFields(next, contractState(p, next)) };
881
+ return runWorkflowTransaction({
882
+ cwd,
883
+ kind: "transition",
884
+ changeId: id,
885
+ failAfterOperation,
886
+ operations: [
887
+ workflowWriteOperation(cwd, p.flow, flowContent(next)),
888
+ workflowWriteOperation(cwd, path.join(p.change, "events.jsonl"), eventContent(path.join(p.change, "events.jsonl"), "transition", before, to, next.revision, details))
889
+ ],
890
+ result: resultFields
891
+ });
892
+ }
893
+ if (command === "return") {
894
+ const to = args[0];
895
+ const reason = option(args, "--reason");
896
+ if (!reason) return fail("RETURN_REASON_REQUIRED", "Return requires --reason.");
897
+ if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
898
+ if (!RETURN_REASONS.has(reason)) return fail("RETURN_REASON_UNSUPPORTED", `Unsupported Return reason: ${reason}.`);
899
+ const profile = workflowProfile(p, flow);
900
+ const returns = profile.id === "lightweight" ? LIGHTWEIGHT_RETURNS : FULL_RETURNS;
901
+ const returnRule = returns.find((entry) => entry.from === flow.phase && entry.to === to && entry.reason === reason);
902
+ if (!returnRule) return fail("ILLEGAL_RETURN", `Illegal ${profile.id} Return ${flow.phase} -> ${to} for reason ${reason}.`);
893
903
  if (flow.phase === "verify" && to === "build") { const contract = contractState(p, flow); const failure = contractFailure(flow, contract); if (failure) return failure; }
894
904
  const verification = path.join(p.artifacts, "verification.md");
895
905
  let verificationDestination = null;
@@ -904,150 +914,169 @@ export function invoke(argv, { cwd = process.cwd(), failAfterOperation = null, m
904
914
  receiptDestination = path.join(history, `revision-${flow.revision}-review-receipt.json`);
905
915
  if (fs.existsSync(receiptDestination)) return fail("EVIDENCE_INVALIDATION_FAILED", `Review receipt history already exists for revision ${flow.revision}.`);
906
916
  }
907
- const next = {
908
- ...flow,
909
- schema: "matrix/change/v2",
910
- workflow: returnRule.upgrade ? "full" : flow.workflow,
911
- workflow_profile: returnRule.upgrade ? null : flow.workflow_profile,
912
- phase: to,
913
- revision: flow.revision + 1,
914
- updated_at: stamp(),
915
- ...(to === "design" ? { approved_contract_hash: null, contract_approved_revision: null } : {})
916
- };
917
- const nextProfile = workflowProfile(p, next);
918
- return runWorkflowTransaction({
919
- cwd,
920
- kind: "return",
921
- changeId: id,
917
+ const next = {
918
+ ...flow,
919
+ schema: "matrix/change/v2",
920
+ workflow: returnRule.upgrade ? "full" : flow.workflow,
921
+ workflow_profile: returnRule.upgrade ? null : flow.workflow_profile,
922
+ phase: to,
923
+ revision: flow.revision + 1,
924
+ updated_at: stamp(),
925
+ ...(to === "design" ? { approved_contract_hash: null, contract_approved_revision: null } : {})
926
+ };
927
+ const nextProfile = workflowProfile(p, next);
928
+ return runWorkflowTransaction({
929
+ cwd,
930
+ kind: "return",
931
+ changeId: id,
922
932
  failAfterOperation,
923
933
  operations: [
924
934
  ...(verificationDestination ? [workflowMoveOperation(cwd, verification, verificationDestination)] : []),
925
935
  ...(receiptDestination ? [workflowMoveOperation(cwd, p.reviewReceipt, receiptDestination)] : []),
926
936
  workflowWriteOperation(cwd, p.flow, flowContent(next)),
927
- workflowWriteOperation(cwd, path.join(p.change, "events.jsonl"), eventContent(path.join(p.change, "events.jsonl"), "returned", flow.phase, to, next.revision, { reason, invalidated_evidence: INVALIDATED_EVIDENCE, ...(returnRule.upgrade ? { workflow_from: flow.workflow, workflow_to: "full" } : {}) }))
928
- ],
929
- result: { ok: true, code: "OK", change_id: id, workflow: next.workflow, profile: nextProfile.id, evidence_policy: evidencePolicy(next, nextProfile), orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: to, revision: next.revision, next_skill: skill(to), event: "returned", invalidated_evidence: INVALIDATED_EVIDENCE, ...contractFields(next, contractState(p, next)) }
930
- });
931
- }
932
- if (command === "abort") {
933
- const reason = option(args, "--reason");
934
- const note = option(args, "--note");
935
- if (!reason) return fail("ABORT_REASON_REQUIRED", "Abort requires --reason.");
936
- if (!ABORT_REASONS.has(reason)) return fail("ABORT_REASON_UNSUPPORTED", `Unsupported Abort reason: ${reason}.`);
937
- if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
938
- const next = { ...flow, schema: "matrix/change/v2", status: "aborted", revision: flow.revision + 1, updated_at: stamp() };
939
- const target = path.join(p.root, "archive", id);
940
- if (fs.existsSync(target)) return fail("ARCHIVE_TARGET_EXISTS", `Archive target already exists: ${id}.`);
941
- const sourceEvents = path.join(p.change, "events.jsonl");
942
- const targetFlow = path.join(target, "matrix.yaml");
943
- const targetEvents = path.join(target, "events.jsonl");
944
- return runWorkflowTransaction({
945
- cwd,
946
- kind: "abort",
947
- changeId: id,
948
- failAfterOperation,
949
- operations: [
950
- workflowMoveOperation(cwd, p.change, target),
951
- workflowWriteOperation(cwd, targetFlow, flowContent(next), { before: captureWorkflowEntry(p.flow) }),
952
- workflowWriteOperation(cwd, targetEvents, eventContent(sourceEvents, "aborted", flow.phase, flow.phase, next.revision, { reason, ...(note ? { note } : {}) }), { before: captureWorkflowEntry(sourceEvents) }),
953
- workflowRemoveOperation(cwd, p.active)
954
- ],
955
- result: { ok: true, code: "OK", change_id: id, workflow: next.workflow, orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: next.phase, revision: next.revision, next_skill: null, event: "aborted" }
956
- });
957
- }
958
- if (command === "archive") {
959
- if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
960
- if (flow.phase !== "archive") return fail("ILLEGAL_TRANSITION", "Only an archive-phase change can be archived.");
961
- const profile = workflowProfile(p, flow);
962
- const dryRun = args.includes("--dry-run");
963
- const expected = option(args, "--expect-preflight");
964
- const confirmedByUser = args.includes("--confirmed");
965
- if ((dryRun && (expected || confirmedByUser)) || args.some((arg) => !["--dry-run", "--expect-preflight", "--confirmed", expected].includes(arg))) {
937
+ workflowWriteOperation(cwd, path.join(p.change, "events.jsonl"), eventContent(path.join(p.change, "events.jsonl"), "returned", flow.phase, to, next.revision, { reason, invalidated_evidence: INVALIDATED_EVIDENCE, ...(returnRule.upgrade ? { workflow_from: flow.workflow, workflow_to: "full" } : {}) }))
938
+ ],
939
+ result: { ok: true, code: "OK", change_id: id, workflow: next.workflow, profile: nextProfile.id, evidence_policy: evidencePolicy(next, nextProfile), orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: to, revision: next.revision, next_skill: skill(to), event: "returned", invalidated_evidence: INVALIDATED_EVIDENCE, ...contractFields(next, contractState(p, next)) }
940
+ });
941
+ }
942
+ if (command === "abort") {
943
+ const reason = option(args, "--reason");
944
+ const note = option(args, "--note");
945
+ if (!reason) return fail("ABORT_REASON_REQUIRED", "Abort requires --reason.");
946
+ if (!ABORT_REASONS.has(reason)) return fail("ABORT_REASON_UNSUPPORTED", `Unsupported Abort reason: ${reason}.`);
947
+ if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
948
+ const next = { ...flow, schema: "matrix/change/v2", status: "aborted", revision: flow.revision + 1, updated_at: stamp() };
949
+ const target = path.join(p.root, "archive", id);
950
+ if (fs.existsSync(target)) return fail("ARCHIVE_TARGET_EXISTS", `Archive target already exists: ${id}.`);
951
+ const sourceEvents = path.join(p.change, "events.jsonl");
952
+ const targetFlow = path.join(target, "matrix.yaml");
953
+ const targetEvents = path.join(target, "events.jsonl");
954
+ return runWorkflowTransaction({
955
+ cwd,
956
+ kind: "abort",
957
+ changeId: id,
958
+ failAfterOperation,
959
+ operations: [
960
+ workflowMoveOperation(cwd, p.change, target),
961
+ workflowWriteOperation(cwd, targetFlow, flowContent(next), { before: captureWorkflowEntry(p.flow) }),
962
+ workflowWriteOperation(cwd, targetEvents, eventContent(sourceEvents, "aborted", flow.phase, flow.phase, next.revision, { reason, ...(note ? { note } : {}) }), { before: captureWorkflowEntry(sourceEvents) }),
963
+ workflowRemoveOperation(cwd, p.active)
964
+ ],
965
+ result: { ok: true, code: "OK", change_id: id, workflow: next.workflow, orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: next.phase, revision: next.revision, next_skill: null, event: "aborted" }
966
+ });
967
+ }
968
+ if (command === "archive") {
969
+ if (flow.status !== "active") return fail("CHANGE_NOT_ACTIVE", `Matrix change is ${flow.status}.`);
970
+ if (flow.phase !== "archive") return fail("ILLEGAL_TRANSITION", "Only an archive-phase change can be archived.");
971
+ const profile = workflowProfile(p, flow);
972
+ const dryRun = args.includes("--dry-run");
973
+ const expected = option(args, "--expect-preflight");
974
+ const confirmedByUser = args.includes("--confirmed");
975
+ if ((dryRun && (expected || confirmedByUser)) || args.some((arg) => !["--dry-run", "--expect-preflight", "--confirmed", expected].includes(arg))) {
966
976
  return { ...fail("ARCHIVE_PREFLIGHT_INVALID", "Archive accepts either --dry-run or --expect-preflight <sha256>, not both or additional arguments."), recovery_command: workflowCommand("archive --dry-run") };
967
- }
977
+ }
968
978
  if (!dryRun && !expected) return { ...fail("ARCHIVE_PREFLIGHT_REQUIRED", "Archive requires an explicit dry-run followed by --expect-preflight <sha256>."), recovery_command: workflowCommand("archive --dry-run") };
969
979
  if (expected && !/^sha256:[0-9a-f]{64}$/.test(expected)) return { ...fail("ARCHIVE_PREFLIGHT_INVALID", "Expected preflight must be sha256 followed by 64 lowercase hexadecimal characters."), recovery_command: workflowCommand("archive --dry-run") };
970
980
  if (expected && shortcut(flow) && !confirmedByUser) return { ...fail("CONFIRMATION_REQUIRED", "Shortcut workflow Archive requires explicit user confirmation."), recovery_command: workflowCommand(`archive --expect-preflight ${expected} --confirmed`) };
971
- if (dryRun) {
972
- const result = guard(p, flow, "archive"); if (!result.ok) return { ...result, message: result.message ?? "Archive guard failed." };
973
- const captured = captureArchivePreflight(p, id); if (captured.failure) return captured.failure;
974
- const currentFlow = readFlow(p); if (!currentFlow) return fail("ARCHIVE_PREFLIGHT_UNSTABLE", "Canonical workflow state changed during dry-run.");
975
- const finalGuard = guard(p, currentFlow, "archive"); if (!finalGuard.ok) return { ...finalGuard, message: finalGuard.message ?? "Archive guard failed." };
976
- const confirmed = captureArchivePreflight(p, id); if (confirmed.failure) return confirmed.failure;
977
- if (captured.hash !== confirmed.hash) return fail("ARCHIVE_PREFLIGHT_UNSTABLE", "Archive inputs changed during dry-run. Retry dry-run.");
978
- return {
979
- ok: true, code: "OK", change_id: id, workflow: currentFlow.workflow, profile: profile.id, evidence_policy: evidencePolicy(currentFlow, profile), orchestration: currentFlow.orchestration, artifact_language: currentFlow.artifact_language ?? artifactLanguage, status: currentFlow.status, phase: currentFlow.phase, revision: currentFlow.revision,
980
- preflight_hash: confirmed.hash,
981
- effect_summary: { target: `.matrix/archive/${id}`, files: confirmed.fileCount, directories: confirmed.directoryCount, content_bytes: confirmed.totalBytes },
981
+ if (dryRun) {
982
+ const result = guard(p, flow, "archive"); if (!result.ok) return { ...result, message: result.message ?? "Archive guard failed." };
983
+ const captured = captureArchivePreflight(p, id); if (captured.failure) return captured.failure;
984
+ const currentFlow = readFlow(p); if (!currentFlow) return fail("ARCHIVE_PREFLIGHT_UNSTABLE", "Canonical workflow state changed during dry-run.");
985
+ const finalGuard = guard(p, currentFlow, "archive"); if (!finalGuard.ok) return { ...finalGuard, message: finalGuard.message ?? "Archive guard failed." };
986
+ const confirmed = captureArchivePreflight(p, id); if (confirmed.failure) return confirmed.failure;
987
+ if (captured.hash !== confirmed.hash) return fail("ARCHIVE_PREFLIGHT_UNSTABLE", "Archive inputs changed during dry-run. Retry dry-run.");
988
+ return {
989
+ ok: true, code: "OK", change_id: id, workflow: currentFlow.workflow, profile: profile.id, evidence_policy: evidencePolicy(currentFlow, profile), orchestration: currentFlow.orchestration, artifact_language: currentFlow.artifact_language ?? artifactLanguage, status: currentFlow.status, phase: currentFlow.phase, revision: currentFlow.revision,
990
+ preflight_hash: confirmed.hash,
991
+ effect_summary: { target: `.matrix/archive/${id}`, files: confirmed.fileCount, directories: confirmed.directoryCount, content_bytes: confirmed.totalBytes },
982
992
  commit_command: workflowCommand(`archive --expect-preflight ${confirmed.hash}${shortcut(currentFlow) ? " --confirmed" : ""}`),
983
- ...contractFields(currentFlow, contractState(p, currentFlow))
984
- };
985
- }
986
- const captured = captureArchivePreflight(p, id);
987
- if (captured.failure) return captured.failure;
988
- if (captured.hash !== expected) return archivePreflightChanged(expected, captured.hash);
989
- const currentFlow = readFlow(p);
990
- if (!currentFlow || currentFlow.status !== "active" || currentFlow.phase !== "archive") return archivePreflightChanged(expected, captured.hash);
991
- const result = guard(p, currentFlow, "archive");
992
- if (!result.ok) return { ...result, message: result.message ?? "Archive guard failed." };
993
- const confirmed = captureArchivePreflight(p, id);
994
- if (confirmed.failure) return confirmed.failure;
995
- if (confirmed.hash !== expected) return archivePreflightChanged(expected, confirmed.hash);
996
- const contract = contractState(p, currentFlow);
997
- const next = { ...currentFlow, schema: "matrix/change/v2", status: "archived", revision: currentFlow.revision + 1, updated_at: stamp() };
998
- const target = path.join(p.root, "archive", id);
999
- const sourceEvents = path.join(p.change, "events.jsonl");
1000
- const targetFlow = path.join(target, "matrix.yaml");
1001
- const targetEvents = path.join(target, "events.jsonl");
1002
- return runWorkflowTransaction({
1003
- cwd,
1004
- kind: "archive",
1005
- changeId: id,
1006
- failAfterOperation,
1007
- operations: [
1008
- workflowMoveOperation(cwd, p.change, target),
1009
- workflowWriteOperation(cwd, targetFlow, flowContent(next), { before: captureWorkflowEntry(p.flow) }),
1010
- workflowWriteOperation(cwd, targetEvents, eventContent(sourceEvents, "archived", "archive", "archive", next.revision, { preflight_hash: expected, confirmed: confirmedByUser }), { before: captureWorkflowEntry(sourceEvents) }),
1011
- workflowRemoveOperation(cwd, p.active)
1012
- ],
1013
- result: {
1014
- ok: true, code: "OK", archived: id, change_id: id, workflow: next.workflow, profile: profile.id, evidence_policy: evidencePolicy(next, profile), orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: next.phase, revision: next.revision, next_skill: null, event: "archived",
1015
- preflight_hash: expected,
1016
- effect_summary: { target: `.matrix/archive/${id}`, files: confirmed.fileCount, directories: confirmed.directoryCount, content_bytes: confirmed.totalBytes },
1017
- ...contractFields(next, contract)
1018
- }
1019
- });
1020
- }
1021
- if (command === "handoff") { const destination = path.join(p.artifacts, "handoff.md"); fs.writeFileSync(destination, `# Matrix handoff: ${id}\n\n- Workflow: ${flow.workflow}\n- Current phase: ${flow.phase}\n- Resume with: \`${skill(flow.phase)}\`\n- Guard passes: ${guard(p, flow, flow.phase).ok}\n`); return { ok: true, code: "OK", path: destination }; }
1022
- if (command === "export") {
1023
- if (flow.phase !== "build") return fail("ILLEGAL_PHASE", "Export requires the build phase.");
1024
- if (workflowProfile(p, flow).id === "lightweight") return fail("EXPORT_UNSUPPORTED_WORKFLOW", "Claude export requires the full three-artifact workflow contract.");
1025
- const contract = contractState(p, flow); const failure = contractFailure(flow, contract); if (failure) return failure;
1026
- const taskId = args.includes("--task-id") ? args[args.indexOf("--task-id") + 1] : args[0];
1027
- const target = args.includes("--target") ? args[args.indexOf("--target") + 1] : "generic";
1028
- const applyBoard = args.includes("--apply-fnsec-board");
1029
- if (!/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(taskId ?? "") || !["generic", "fnsec"].includes(target)) return fail("INVALID_INTENT", "export requires a task id and target generic or fnsec.");
1030
- const { proposal, design, plan } = contract.snapshot.contents;
1031
- if (target === "generic") {
1032
- const destination = path.join(p.artifacts, "claude-task.md"); const result = path.join(p.artifacts, "claude-result.md");
1033
- fs.writeFileSync(destination, taskContent(id, taskId, proposal, design, plan, path.relative(cwd, result).replaceAll("\\", "/"), flow.approved_contract_hash, flow.contract_approved_revision));
1034
- return { ok: true, code: "OK", path: destination };
1035
- }
1036
- const tasks = path.join(cwd, "docs", "tasks"); const board = path.join(tasks, "active.md");
1037
- if (!exists(tasks) || !exists(board)) return fail("FNSEC_TARGET_UNAVAILABLE", "FnSec target requires docs/tasks/active.md in the current project.");
1038
- const destination = path.join(tasks, `claude-task-${taskId}.md`); const result = path.join(tasks, `claude-result-${taskId}.md`);
1039
- if (exists(destination) || exists(result)) return fail("FNSEC_TASK_EXISTS", `FnSec task or result path already exists for ${taskId}.`);
1040
- const currentBoard = fs.readFileSync(board, "utf8");
1041
- if (applyBoard && !currentBoard.includes("NO_ACTIVE_OBJECTIVE")) return fail("FNSEC_BOARD_OCCUPIED", "FnSec active.md already has an objective; refused to overwrite it.");
1042
- fs.writeFileSync(destination, taskContent(id, taskId, proposal, design, plan, path.relative(cwd, result).replaceAll("\\", "/"), flow.approved_contract_hash, flow.contract_approved_revision));
1043
- if (applyBoard) fs.writeFileSync(board, activeBoard(taskId, path.relative(cwd, destination).replaceAll("\\", "/"), path.relative(cwd, result).replaceAll("\\", "/"), id));
1044
- return { ok: true, code: "OK", path: destination, board: applyBoard ? board : null };
1045
- }
1046
- return fail("INVALID_INTENT", `Unknown workflow command: ${command}.`);
1047
- }
1048
-
1049
- if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1].replaceAll("\\", "/")}`).href) {
1050
- const result = invoke(process.argv.slice(2));
1051
- console.log(JSON.stringify(result));
1052
- if (!result.ok) process.exitCode = 2;
1053
- }
993
+ ...contractFields(currentFlow, contractState(p, currentFlow))
994
+ };
995
+ }
996
+ const captured = captureArchivePreflight(p, id);
997
+ if (captured.failure) return captured.failure;
998
+ if (captured.hash !== expected) return archivePreflightChanged(expected, captured.hash);
999
+ const currentFlow = readFlow(p);
1000
+ if (!currentFlow || currentFlow.status !== "active" || currentFlow.phase !== "archive") return archivePreflightChanged(expected, captured.hash);
1001
+ const result = guard(p, currentFlow, "archive");
1002
+ if (!result.ok) return { ...result, message: result.message ?? "Archive guard failed." };
1003
+ const confirmed = captureArchivePreflight(p, id);
1004
+ if (confirmed.failure) return confirmed.failure;
1005
+ if (confirmed.hash !== expected) return archivePreflightChanged(expected, confirmed.hash);
1006
+ const contract = contractState(p, currentFlow);
1007
+ const next = { ...currentFlow, schema: "matrix/change/v2", status: "archived", revision: currentFlow.revision + 1, updated_at: stamp() };
1008
+ const target = path.join(p.root, "archive", id);
1009
+ const sourceEvents = path.join(p.change, "events.jsonl");
1010
+ const targetFlow = path.join(target, "matrix.yaml");
1011
+ const targetEvents = path.join(target, "events.jsonl");
1012
+ return runWorkflowTransaction({
1013
+ cwd,
1014
+ kind: "archive",
1015
+ changeId: id,
1016
+ failAfterOperation,
1017
+ operations: [
1018
+ workflowMoveOperation(cwd, p.change, target),
1019
+ workflowWriteOperation(cwd, targetFlow, flowContent(next), { before: captureWorkflowEntry(p.flow) }),
1020
+ workflowWriteOperation(cwd, targetEvents, eventContent(sourceEvents, "archived", "archive", "archive", next.revision, { preflight_hash: expected, confirmed: confirmedByUser }), { before: captureWorkflowEntry(sourceEvents) }),
1021
+ workflowRemoveOperation(cwd, p.active)
1022
+ ],
1023
+ result: {
1024
+ ok: true, code: "OK", archived: id, change_id: id, workflow: next.workflow, profile: profile.id, evidence_policy: evidencePolicy(next, profile), orchestration: next.orchestration, artifact_language: next.artifact_language ?? artifactLanguage, status: next.status, phase: next.phase, revision: next.revision, next_skill: null, event: "archived",
1025
+ preflight_hash: expected,
1026
+ effect_summary: { target: `.matrix/archive/${id}`, files: confirmed.fileCount, directories: confirmed.directoryCount, content_bytes: confirmed.totalBytes },
1027
+ ...contractFields(next, contract)
1028
+ }
1029
+ });
1030
+ }
1031
+ if (command === "handoff") { const destination = path.join(p.artifacts, "handoff.md"); fs.writeFileSync(destination, `# Matrix handoff: ${id}\n\n- Workflow: ${flow.workflow}\n- Current phase: ${flow.phase}\n- Resume with: \`${skill(flow.phase)}\`\n- Guard passes: ${guard(p, flow, flow.phase).ok}\n`); return { ok: true, code: "OK", path: destination }; }
1032
+ if (command === "export") {
1033
+ if (flow.phase !== "build") return fail("ILLEGAL_PHASE", "Export requires the build phase.");
1034
+ if (workflowProfile(p, flow).id === "lightweight") return fail("EXPORT_UNSUPPORTED_WORKFLOW", "Claude export requires the full three-artifact workflow contract.");
1035
+ const contract = contractState(p, flow); const failure = contractFailure(flow, contract); if (failure) return failure;
1036
+ const taskId = args.includes("--task-id") ? args[args.indexOf("--task-id") + 1] : args[0];
1037
+ const agent = args.includes("--agent") ? args[args.indexOf("--agent") + 1] : null;
1038
+ const from = args.includes("--from") ? args[args.indexOf("--from") + 1] : null;
1039
+ if (agent && args.includes("--target")) return fail("INVALID_INTENT", "export --agent and --target are mutually exclusive.");
1040
+ if (agent && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(agent)) return fail("INVALID_INTENT", "export --agent requires a kebab-case agent identifier.");
1041
+ if (from && !agent) return fail("INVALID_INTENT", "export --from requires --agent.");
1042
+ if (from && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(from)) return fail("INVALID_INTENT", "export --from requires a kebab-case agent identifier.");
1043
+ if (agent && (!args.includes("--task-id") || !/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(taskId ?? ""))) return fail("INVALID_INTENT", "export --agent requires --task-id.");
1044
+ const target = args.includes("--target") ? args[args.indexOf("--target") + 1] : "generic";
1045
+ const applyBoard = args.includes("--apply-fnsec-board");
1046
+ if (!/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(taskId ?? "") || !["generic", "fnsec"].includes(target)) return fail("INVALID_INTENT", "export requires a task id and target generic or fnsec.");
1047
+ const { proposal, design, plan } = contract.snapshot.contents;
1048
+ if (agent) {
1049
+ const destination = path.join(p.artifacts, `handoff-task-${taskId}.md`);
1050
+ const result = path.join(p.artifacts, `handoff-result-${taskId}.md`);
1051
+ const content = taskContent(id, taskId, proposal, design, plan, path.relative(cwd, result).replaceAll("\\", "/"), flow.approved_contract_hash, flow.contract_approved_revision, {
1052
+ agent,
1053
+ owner: from ?? "Matrix change owner",
1054
+ statusToken: `${agent.replaceAll("-", "_").toUpperCase()}_QUEUED`,
1055
+ reviewer: from ?? "Matrix change owner"
1056
+ });
1057
+ fs.writeFileSync(destination, content);
1058
+ return { ok: true, code: "OK", path: destination };
1059
+ }
1060
+ if (target === "generic") {
1061
+ const destination = path.join(p.artifacts, "claude-task.md"); const result = path.join(p.artifacts, "claude-result.md");
1062
+ fs.writeFileSync(destination, taskContent(id, taskId, proposal, design, plan, path.relative(cwd, result).replaceAll("\\", "/"), flow.approved_contract_hash, flow.contract_approved_revision));
1063
+ return { ok: true, code: "OK", path: destination };
1064
+ }
1065
+ const tasks = path.join(cwd, "docs", "tasks"); const board = path.join(tasks, "active.md");
1066
+ if (!exists(tasks) || !exists(board)) return fail("FNSEC_TARGET_UNAVAILABLE", "FnSec target requires docs/tasks/active.md in the current project.");
1067
+ const destination = path.join(tasks, `claude-task-${taskId}.md`); const result = path.join(tasks, `claude-result-${taskId}.md`);
1068
+ if (exists(destination) || exists(result)) return fail("FNSEC_TASK_EXISTS", `FnSec task or result path already exists for ${taskId}.`);
1069
+ const currentBoard = fs.readFileSync(board, "utf8");
1070
+ if (applyBoard && !currentBoard.includes("NO_ACTIVE_OBJECTIVE")) return fail("FNSEC_BOARD_OCCUPIED", "FnSec active.md already has an objective; refused to overwrite it.");
1071
+ fs.writeFileSync(destination, taskContent(id, taskId, proposal, design, plan, path.relative(cwd, result).replaceAll("\\", "/"), flow.approved_contract_hash, flow.contract_approved_revision));
1072
+ if (applyBoard) fs.writeFileSync(board, activeBoard(taskId, path.relative(cwd, destination).replaceAll("\\", "/"), path.relative(cwd, result).replaceAll("\\", "/"), id));
1073
+ return { ok: true, code: "OK", path: destination, board: applyBoard ? board : null };
1074
+ }
1075
+ return fail("INVALID_INTENT", `Unknown workflow command: ${command}.`);
1076
+ }
1077
+
1078
+ if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1].replaceAll("\\", "/")}`).href) {
1079
+ const result = invoke(process.argv.slice(2));
1080
+ console.log(JSON.stringify(result));
1081
+ if (!result.ok) process.exitCode = 2;
1082
+ }