@hassangameryt/freeflow 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +4 -5
  4. package/README.md +39 -55
  5. package/capabilities/cognitive-routing/SKILL.md +288 -130
  6. package/command-surface.json +0 -24
  7. package/hooks/freeflow-runtime-context.mjs +42 -477
  8. package/hooks/hooks.json +1 -26
  9. package/hooks/tests/check-runtime-context-hook.sh +108 -319
  10. package/package.json +4 -2
  11. package/pi-extension/dist/cognitive-routing/commands.js +3 -3
  12. package/pi-extension/dist/cognitive-routing/config.js +16 -20
  13. package/pi-extension/dist/cognitive-routing/controller.js +478 -48
  14. package/pi-extension/dist/cognitive-routing/history.js +12 -0
  15. package/pi-extension/dist/cognitive-routing/host.js +74 -12
  16. package/pi-extension/dist/cognitive-routing/pi-routing-session.js +414 -0
  17. package/pi-extension/dist/cognitive-routing/pi-session-control.js +320 -0
  18. package/pi-extension/dist/cognitive-routing/tool.js +1 -0
  19. package/pi-extension/dist/cognitive-routing/types.js +1 -1
  20. package/pi-extension/dist/index.js +236 -219
  21. package/pi-extension/dist/runtime/runtime-context.js +126 -286
  22. package/pi-extension/dist/settings/settings-ui.js +52 -336
  23. package/pi-extension/src/cognitive-routing/commands.ts +15 -5
  24. package/pi-extension/src/cognitive-routing/config.ts +16 -20
  25. package/pi-extension/src/cognitive-routing/controller.ts +561 -51
  26. package/pi-extension/src/cognitive-routing/history.ts +12 -0
  27. package/pi-extension/src/cognitive-routing/host.ts +110 -16
  28. package/pi-extension/src/cognitive-routing/pi-routing-session.ts +538 -0
  29. package/pi-extension/src/cognitive-routing/pi-session-control.ts +444 -0
  30. package/pi-extension/src/cognitive-routing/tool.ts +1 -0
  31. package/pi-extension/src/cognitive-routing/types.ts +1 -1
  32. package/pi-extension/src/index.ts +249 -239
  33. package/pi-extension/src/runtime/runtime-context.ts +129 -305
  34. package/pi-extension/src/settings/settings-ui.ts +53 -371
  35. package/pi-extension/tests/cognitive-routing/commands.test.js +1 -1
  36. package/pi-extension/tests/cognitive-routing/controller.test.js +69 -40
  37. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +128 -57
  38. package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +434 -0
  39. package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +174 -0
  40. package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +91 -0
  41. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +47 -4
  42. package/pi-extension/tests/integration/mode-free-core.test.js +218 -0
  43. package/pi-extension/tests/integration/pi-extension.test.js +430 -2478
  44. package/pi-extension/tests/integration/prompt-architecture.test.js +124 -79
  45. package/pi-extension/tests/integration/unaffected-regressions.test.js +411 -0
  46. package/runtime/prompts/cognitive-routing.md +5 -4
  47. package/runtime/prompts/conversation-history.md +1 -1
  48. package/runtime/prompts/core.md +77 -6
  49. package/runtime/prompts/interaction-contract.md +6 -2
  50. package/skills/action-selection/SKILL.md +93 -44
  51. package/skills/action-selection/references/trajectory-stalls.md +71 -0
  52. package/skills/bypass/SKILL.md +109 -39
  53. package/skills/commit-work/SKILL.md +94 -55
  54. package/skills/commit-work/references/git-state-edges.md +94 -0
  55. package/skills/commit-work/references/simple-push.md +92 -0
  56. package/skills/commit-work/references/staging-decisions.md +79 -46
  57. package/skills/decision-gate/SKILL.md +80 -22
  58. package/skills/design-for-depth/SKILL.md +208 -43
  59. package/skills/design-for-depth/references/design-pressure-signals.md +108 -240
  60. package/skills/design-for-depth/references/interface-design-loop.md +77 -97
  61. package/skills/design-for-depth/references/module-and-dependency-design.md +147 -0
  62. package/skills/design-for-depth/references/software-design-philosophy.md +127 -173
  63. package/skills/design-for-depth/references/state-and-failure-boundaries.md +136 -0
  64. package/skills/diagnose-failure/SKILL.md +198 -52
  65. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +19 -5
  66. package/skills/diagnose-failure/references/flaky-and-performance-diagnosis.md +13 -5
  67. package/skills/discuss/SKILL.md +118 -76
  68. package/skills/discuss/references/discussion-continuity.md +84 -32
  69. package/skills/evaluate-skill/SKILL.md +166 -52
  70. package/skills/evaluate-skill/references/evaluation-definition-schema.md +2 -2
  71. package/skills/evaluate-skill/references/evaluation-design.md +56 -30
  72. package/skills/evaluate-skill/references/execution-and-evidence.md +1 -1
  73. package/skills/evaluate-skill/references/review-and-revision.md +62 -21
  74. package/skills/execute-work/SKILL.md +98 -59
  75. package/skills/execute-work/references/code-practices.md +4 -4
  76. package/skills/execute-work/references/execute-work-edges.md +42 -22
  77. package/skills/review-artifact/SKILL.md +132 -71
  78. package/skills/review-artifact/references/adjudicate-artifact-review.md +101 -0
  79. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +52 -41
  80. package/skills/review-work/SKILL.md +115 -72
  81. package/skills/review-work/references/adjudicate-work-review.md +97 -0
  82. package/skills/review-work/references/independent-work-reviewer-contract.md +40 -35
  83. package/skills/review-work/references/security-risk-lens.md +17 -15
  84. package/skills/setup-freeflow/SKILL.md +14 -17
  85. package/skills/setup-freeflow/references/activation-contract.md +24 -30
  86. package/skills/setup-freeflow/references/host-setup.md +6 -7
  87. package/skills/simplify-code/SKILL.md +97 -39
  88. package/skills/simplify-code/references/simplification-patterns.md +1 -1
  89. package/skills/tdd/SKILL.md +108 -41
  90. package/skills/tdd/references/test-design.md +1 -1
  91. package/skills/track-work/SKILL.md +133 -300
  92. package/skills/track-work/references/working-record-format.md +515 -0
  93. package/skills/track-work/scripts/lib/document.mjs +713 -0
  94. package/skills/track-work/scripts/lib/format.mjs +166 -0
  95. package/skills/track-work/scripts/lib/store.mjs +233 -0
  96. package/skills/track-work/scripts/lib/transitions.mjs +790 -0
  97. package/skills/track-work/scripts/lib/views.mjs +27 -430
  98. package/skills/track-work/scripts/working-record.mjs +292 -98
  99. package/skills/verify-work/SKILL.md +46 -20
  100. package/skills/verify-work/references/browser-runtime-evidence.md +1 -1
  101. package/skills/verify-work/references/integration-evidence.md +1 -7
  102. package/skills/verify-work/references/performance-evidence.md +1 -1
  103. package/skills/workflow/SKILL.md +110 -80
  104. package/skills/workflow/references/domain-skill-composition.md +24 -18
  105. package/skills/write-skill/SKILL.md +218 -62
  106. package/skills/write-skill/references/activation-boundaries.md +63 -21
  107. package/skills/write-skill/references/agent-first-instructions.md +61 -27
  108. package/skills/write-skill/references/progressive-disclosure.md +91 -41
  109. package/skills/write-skill/references/skill-dependency-graphs.md +190 -0
  110. package/runtime/prompts/skills.md +0 -65
  111. package/skills/mode-contract/SKILL.md +0 -104
  112. package/skills/track-work/scripts/lib/codec.mjs +0 -570
  113. package/skills/track-work/scripts/lib/commands.mjs +0 -568
  114. package/skills/track-work/scripts/lib/contract.mjs +0 -303
  115. package/skills/track-work/scripts/lib/model.mjs +0 -506
  116. package/skills/track-work/scripts/lib/operations.mjs +0 -965
  117. package/skills/track-work/scripts/lib/record-store.mjs +0 -264
  118. package/skills/track-work/scripts/lib/result.mjs +0 -37
  119. package/skills/track-work/scripts/lib/rewrites.mjs +0 -740
  120. package/skills/track-work/scripts/lib/schema.mjs +0 -277
  121. package/skills/track-work/scripts/lib/source-inventory.mjs +0 -162
  122. package/skills/track-work/scripts/lib/workspace.mjs +0 -134
@@ -1,568 +0,0 @@
1
- import { basename, join, resolve } from "node:path";
2
- import { mkdir, readFile, readdir, rename, rm, unlink, writeFile } from "node:fs/promises";
3
- import { randomUUID } from "node:crypto";
4
- import {
5
- CommittedResultError,
6
- loadRecord,
7
- acquireLock,
8
- commitText,
9
- recoverStaleLock,
10
- requireV2,
11
- withMutationLock,
12
- } from "./record-store.mjs";
13
- import { parseRecord, renderRecord } from "./codec.mjs";
14
- import { applyOperation } from "./operations.mjs";
15
- import {
16
- WorkingRecordError,
17
- canonicalizeValue,
18
- changedSemanticPaths,
19
- clone,
20
- createRecord,
21
- fail,
22
- failureInjection,
23
- isoNow,
24
- sha256,
25
- validateModel,
26
- } from "./model.mjs";
27
- import {
28
- assertNoSymlinkPath,
29
- displayPath,
30
- exists,
31
- gitInfo,
32
- nextTaskNumber,
33
- resolveRecordPath,
34
- safeShortName,
35
- taskRoot,
36
- versionControlEvidence,
37
- } from "./workspace.mjs";
38
- import { baseEnvelope, errorItems, recordMetadata } from "./result.mjs";
39
- import { INIT_INPUT_KEYS, UNLOCK_INPUT_KEYS, VIEW_INPUT_KEYS } from "./contract.mjs";
40
- import {
41
- inspectData,
42
- legacyView,
43
- renderNamedSection,
44
- renderRecordHeaderOnly,
45
- renderView,
46
- unavailableRecord,
47
- } from "./views.mjs";
48
- import { renderCommandSchema } from "./schema.mjs";
49
- import { rewriteExisting } from "./rewrites.mjs";
50
-
51
- function normalizeInput(input) {
52
- if (!input || typeof input !== "object" || Array.isArray(input))
53
- fail("invalid-input", "Structured input must be a JSON object");
54
- return input;
55
- }
56
-
57
- function assertKnownInput(input, allowed, command) {
58
- for (const key of Object.keys(input))
59
- if (!allowed.has(key))
60
- fail("unknown-input-field", `Unknown ${command} input field: ${key}`, { path: `${command}.${key}` });
61
- }
62
-
63
- function readOnlyReason(loaded) {
64
- return loaded.kind === "legacy" ? "legacy-record" : "unsupported-schema";
65
- }
66
-
67
- function validateCandidate(root, candidate, candidateText, recordPath) {
68
- const parsedCandidate = parseRecord(candidateText, recordPath);
69
- const validation =
70
- parsedCandidate.kind === "v2"
71
- ? validateModel(parsedCandidate.data)
72
- : [{ code: "candidate-validation", message: "Candidate is not schema v2" }];
73
- if (validation.length) fail("candidate-validation-failure", "Candidate failed validation", { validation });
74
- if (JSON.stringify(canonicalizeValue(candidate)) !== JSON.stringify(canonicalizeValue(parsedCandidate.data)))
75
- fail("candidate-roundtrip-failure", "Candidate changed during Markdown parse", {
76
- path: displayPath(root, recordPath),
77
- });
78
- if (renderRecord(parsedCandidate.data) !== candidateText)
79
- fail("candidate-roundtrip-failure", "Candidate changed during Markdown render/parse round-trip", {
80
- path: displayPath(root, recordPath),
81
- });
82
- return parsedCandidate;
83
- }
84
-
85
- async function readStdin() {
86
- const chunks = [];
87
- for await (const chunk of process.stdin) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
88
- return Buffer.concat(chunks).toString("utf8");
89
- }
90
-
91
- export async function readJsonInput(options) {
92
- const inputPath = options["--input"];
93
- if (!inputPath) return {};
94
- const source = inputPath === "-" ? await readStdin() : await readFile(inputPath, "utf8");
95
- try {
96
- return normalizeInput(JSON.parse(source));
97
- } catch (error) {
98
- if (error instanceof WorkingRecordError) throw error;
99
- fail("invalid-input-json", `Input is not valid JSON: ${inputPath}`);
100
- }
101
- }
102
-
103
- function expectedSha(options, input) {
104
- return options["--expected-sha"] ?? options["--expected-sha256"] ?? input.expectedSha256 ?? input.expectedSha;
105
- }
106
-
107
- function shouldDryRun(options, input) {
108
- return options["--dry-run"] === true || input.dryRun === true;
109
- }
110
-
111
- async function mutateExisting(root, command, recordPath, input, options) {
112
- const dryRun = shouldDryRun(options, input);
113
- const expected = expectedSha(options, input);
114
- if (!expected) fail("missing-expected-sha", "Existing-record mutations require --expected-sha or expectedSha256");
115
- await assertNoSymlinkPath(recordPath, taskRoot(root));
116
- return withMutationLock(recordPath, { dryRun }, async () => {
117
- const loaded = await loadRecord(root, recordPath);
118
- requireV2(loaded);
119
- if (loaded.rawSha !== expected)
120
- fail("stale-sha", "Expected SHA-256 does not match the current record", {
121
- expectedSha256: expected,
122
- actualSha256: loaded.rawSha,
123
- });
124
- const before = clone(loaded.data);
125
- const candidate = clone(loaded.data);
126
- const operation = applyOperation(candidate, command, input);
127
- const changedPaths = changedSemanticPaths(before, candidate);
128
- if (changedPaths.length === 0) {
129
- const envelope = baseEnvelope(command, command, recordMetadata(root, recordPath, loaded.data, loaded.rawSha));
130
- envelope.beforeSha256 = loaded.rawSha;
131
- envelope.afterSha256 = loaded.rawSha;
132
- envelope.affectedIds = operation.affectedIds ?? [];
133
- envelope.changedPaths = [];
134
- if (dryRun) {
135
- envelope.status = "dry-run";
136
- envelope.prospective = {
137
- wouldChange: false,
138
- candidateSha256: loaded.rawSha,
139
- candidateTimestamp: loaded.data.lastUpdated,
140
- record: recordMetadata(root, recordPath, loaded.data, loaded.rawSha, "candidate"),
141
- };
142
- } else {
143
- envelope.status = "no-change";
144
- }
145
- return envelope;
146
- }
147
- candidate.lastUpdated = isoNow();
148
- const candidateText = renderRecord(candidate);
149
- if (failureInjection("candidate-validation"))
150
- fail("candidate-validation-failure", "Injected candidate-validation failure");
151
- validateCandidate(root, candidate, candidateText, recordPath);
152
- const candidateSha = sha256(candidateText);
153
- if (dryRun) {
154
- const envelope = baseEnvelope(command, command, recordMetadata(root, recordPath, loaded.data, loaded.rawSha));
155
- envelope.status = "dry-run";
156
- envelope.beforeSha256 = loaded.rawSha;
157
- envelope.afterSha256 = loaded.rawSha;
158
- envelope.affectedIds = operation.affectedIds ?? [];
159
- envelope.changedPaths = changedPaths;
160
- envelope.prospective = {
161
- wouldChange: true,
162
- candidateSha256: candidateSha,
163
- candidateTimestamp: candidate.lastUpdated,
164
- record: recordMetadata(root, recordPath, candidate, candidateSha, "candidate"),
165
- };
166
- return envelope;
167
- }
168
- try {
169
- const committed = await commitText(recordPath, candidateText, candidate);
170
- const envelope = baseEnvelope(
171
- command,
172
- command,
173
- recordMetadata(root, recordPath, committed.data, committed.sha256),
174
- );
175
- envelope.status = "updated";
176
- envelope.beforeSha256 = loaded.rawSha;
177
- envelope.afterSha256 = committed.sha256;
178
- envelope.affectedIds = operation.affectedIds ?? [];
179
- envelope.changedPaths = changedPaths;
180
- return envelope;
181
- } catch (error) {
182
- if (error instanceof WorkingRecordError && error.committed) {
183
- const envelope = baseEnvelope(
184
- command,
185
- "committed-unconfirmed",
186
- recordMetadata(
187
- root,
188
- recordPath,
189
- error.candidate?.data ?? candidate,
190
- error.candidate?.sha256 ?? candidateSha,
191
- "candidate",
192
- ["publicationConfirmation"],
193
- ),
194
- );
195
- envelope.status = "committed-unconfirmed";
196
- envelope.beforeSha256 = loaded.rawSha;
197
- envelope.afterSha256 = null;
198
- envelope.affectedIds = operation.affectedIds ?? [];
199
- envelope.changedPaths = changedPaths;
200
- envelope.errors = errorItems(error);
201
- envelope.recovery = {
202
- required: true,
203
- discardExpectedSha: true,
204
- steps: [
205
- "fresh read of the actual record path",
206
- "validate",
207
- "inspect when available",
208
- "establish confirmed task projection before another transition",
209
- ],
210
- };
211
- throw new CommittedResultError(envelope);
212
- }
213
- throw error;
214
- }
215
- });
216
- }
217
-
218
- async function initRecord(root, input, options) {
219
- assertKnownInput(input, INIT_INPUT_KEYS, "init");
220
- const shortName = safeShortName(options["--name"] ?? input.shortName ?? input.slug ?? input.name);
221
- const recordInput = { ...input, taskName: input.taskName ?? input.displayName ?? input.name ?? shortName };
222
- const tasks = taskRoot(root);
223
- await assertNoSymlinkPath(tasks, root);
224
- const git = await gitInfo(root);
225
- const number = (await exists(tasks)) ? nextTaskNumber(await readdir(tasks, { withFileTypes: true })) : 1;
226
- const taskDirectory = `task-${String(number).padStart(3, "0")}-${shortName}`;
227
- const taskDir = join(tasks, taskDirectory);
228
- const recordPath = join(taskDir, "record.md");
229
- const vc = await versionControlEvidence(root, recordPath);
230
- if (vc.available && !vc.ignored)
231
- fail("task-workspace-not-ignored", "Git-backed initialization requires .freeflow/tasks/** to be ignored", {
232
- path: displayPath(root, recordPath),
233
- });
234
- if (vc.available && vc.tracked)
235
- fail("tracked-task-file", "Initialization refuses to edit a tracked task path", {
236
- path: displayPath(root, recordPath),
237
- });
238
- if (await exists(taskDir))
239
- fail("task-already-exists", `Task directory already exists: ${displayPath(root, taskDir)}`);
240
- if (options["--dry-run"] || input.dryRun) {
241
- const candidate = createRecord(recordInput, isoNow());
242
- const text = renderRecord(candidate);
243
- validateCandidate(root, candidate, text, recordPath);
244
- const envelope = baseEnvelope(
245
- "init",
246
- "init",
247
- recordMetadata(root, recordPath, null, null, "unavailable", ["recordDoesNotExist"]),
248
- );
249
- envelope.status = "dry-run";
250
- envelope.affectedIds = candidate.currentWork.currentSlice ? [candidate.currentWork.currentSlice.id] : [];
251
- envelope.prospective = {
252
- wouldChange: true,
253
- candidateSha256: sha256(text),
254
- candidateTimestamp: candidate.lastUpdated,
255
- record: recordMetadata(root, recordPath, candidate, sha256(text), "candidate"),
256
- versionControl: vc,
257
- };
258
- if (!git.available)
259
- envelope.warnings.push({
260
- code: "version-control-unavailable",
261
- message: "Git ignore/tracked-file evidence is unavailable outside Git",
262
- });
263
- return envelope;
264
- }
265
- await mkdir(tasks, { recursive: true });
266
- const release = await acquireLock(join(tasks, ".init"));
267
- let createdDirectory = false;
268
- try {
269
- await mkdir(taskDir);
270
- createdDirectory = true;
271
- const candidate = createRecord(recordInput, isoNow());
272
- const text = renderRecord(candidate);
273
- const tempPath = join(taskDir, `.${basename(recordPath)}.${process.pid}.${randomUUID()}.tmp`);
274
- let committed = false;
275
- try {
276
- if (failureInjection("temp-write")) fail("temp-write-failure", "Injected temporary-write failure");
277
- await writeFile(tempPath, text, { encoding: "utf8", flag: "wx" });
278
- validateCandidate(root, candidate, text, recordPath);
279
- if (failureInjection("rename")) fail("rename-failure", "Injected atomic rename failure");
280
- await rename(tempPath, recordPath);
281
- committed = true;
282
- if (failureInjection("confirmation")) {
283
- const envelope = baseEnvelope(
284
- "init",
285
- "committed-unconfirmed",
286
- recordMetadata(root, recordPath, candidate, sha256(text), "candidate", ["publicationConfirmation"]),
287
- );
288
- envelope.status = "committed-unconfirmed";
289
- envelope.afterSha256 = null;
290
- envelope.errors = [
291
- { code: "publication-confirmation-failure", message: "Injected publication confirmation failure" },
292
- ];
293
- envelope.recovery = {
294
- required: true,
295
- discardExpectedSha: true,
296
- steps: ["fresh read", "validate", "inspect when available", "establish confirmed projection"],
297
- };
298
- throw new CommittedResultError(envelope);
299
- }
300
- if (failureInjection("confirmation-read"))
301
- fail("publication-confirmation-failure", "Injected post-rename confirmation read failure");
302
- const confirmedText = await readFile(recordPath, "utf8");
303
- const confirmed = parseRecord(confirmedText, recordPath);
304
- const confirmationErrors = validateModel(confirmed.data);
305
- if (confirmationErrors.length)
306
- fail("publication-confirmation-failure", "Committed record failed confirmation", {
307
- validation: confirmationErrors,
308
- });
309
- const envelope = baseEnvelope(
310
- "init",
311
- "init",
312
- recordMetadata(root, recordPath, confirmed.data, sha256(confirmedText)),
313
- );
314
- envelope.status = "updated";
315
- envelope.affectedIds = candidate.currentWork.currentSlice ? [candidate.currentWork.currentSlice.id] : [];
316
- if (!git.available)
317
- envelope.warnings.push({
318
- code: "version-control-unavailable",
319
- message: "Git ignore/tracked-file evidence is unavailable outside Git",
320
- });
321
- return envelope;
322
- } catch (error) {
323
- if (!committed) {
324
- await unlink(tempPath).catch(() => undefined);
325
- if (createdDirectory) await rm(taskDir, { recursive: true, force: true });
326
- } else if (error instanceof CommittedResultError) {
327
- throw error;
328
- } else {
329
- const candidateSha = sha256(text);
330
- const envelope = baseEnvelope(
331
- "init",
332
- "committed-unconfirmed",
333
- recordMetadata(root, recordPath, candidate, candidateSha, "candidate", ["publicationConfirmation"]),
334
- );
335
- envelope.status = "committed-unconfirmed";
336
- envelope.afterSha256 = null;
337
- envelope.errors = errorItems(error);
338
- envelope.recovery = {
339
- required: true,
340
- discardExpectedSha: true,
341
- steps: ["fresh read", "validate", "inspect when available", "establish confirmed projection"],
342
- };
343
- throw new CommittedResultError(envelope);
344
- }
345
- throw error;
346
- }
347
- } finally {
348
- await release();
349
- }
350
- }
351
- async function executeRewriteCommand(root, command, input, options) {
352
- const recordPath = resolveRecordPath(root, options);
353
- try {
354
- return await rewriteExisting(root, command, recordPath, input, options);
355
- } catch (error) {
356
- if (error instanceof WorkingRecordError && !error.committed && !error.record) {
357
- try {
358
- const loaded = await loadRecord(root, recordPath);
359
- if (loaded.kind === "v2") {
360
- const validation = validateModel(loaded.data);
361
- error.record = validation.length
362
- ? unavailableRecord(root, recordPath, loaded.rawSha, "invalid-record")
363
- : recordMetadata(root, recordPath, loaded.data, loaded.rawSha);
364
- } else {
365
- error.record = unavailableRecord(root, recordPath, loaded.rawSha, readOnlyReason(loaded), loaded.data);
366
- }
367
- } catch {
368
- const rawPath = error.details?.path ?? displayPath(root, recordPath);
369
- error.record = recordMetadata(root, recordPath, null, error.details?.sha256 ?? null, "unavailable", [
370
- "recordProjectionUnavailable",
371
- ]);
372
- error.record.path = rawPath;
373
- }
374
- }
375
- throw error;
376
- }
377
- }
378
-
379
- async function executeMutationCommand(root, command, input, options) {
380
- const recordPath = resolveRecordPath(root, options);
381
- try {
382
- return await mutateExisting(root, command, recordPath, input, options);
383
- } catch (error) {
384
- if (error instanceof WorkingRecordError && !error.committed && !error.record) {
385
- try {
386
- const loaded = await loadRecord(root, recordPath);
387
- if (loaded.kind === "v2") {
388
- const validation = validateModel(loaded.data);
389
- error.record = validation.length
390
- ? unavailableRecord(root, recordPath, loaded.rawSha, "invalid-record")
391
- : recordMetadata(root, recordPath, loaded.data, loaded.rawSha);
392
- } else {
393
- error.record = unavailableRecord(root, recordPath, loaded.rawSha, readOnlyReason(loaded), loaded.data);
394
- }
395
- } catch {
396
- const rawPath = error.details?.path ?? displayPath(root, recordPath);
397
- error.record = recordMetadata(root, recordPath, null, error.details?.sha256 ?? null, "unavailable", [
398
- "recordProjectionUnavailable",
399
- ]);
400
- error.record.path = rawPath;
401
- }
402
- }
403
- throw error;
404
- }
405
- }
406
-
407
- async function executeUnlockCommand(root, input, options) {
408
- assertKnownInput(input, UNLOCK_INPUT_KEYS, "unlock");
409
- if (typeof input.authoritySource !== "string" || !input.authoritySource.trim())
410
- fail("missing-authority", "unlock requires authoritySource");
411
- const scope = input.scope ?? "record";
412
- if (scope !== "record" && scope !== "init") fail("invalid-unlock-scope", "unlock scope must be record or init");
413
- if (!Number.isSafeInteger(input.lockPid) || input.lockPid <= 0)
414
- fail("invalid-lock-selector", "unlock requires a positive integer lockPid");
415
- if (typeof input.lockCreatedAt !== "string" || !Number.isFinite(Date.parse(input.lockCreatedAt)))
416
- fail("invalid-lock-selector", "unlock requires a valid lockCreatedAt timestamp");
417
- const ownerPath = scope === "init" ? join(taskRoot(root), ".init") : resolveRecordPath(root, options);
418
- const recovered = await recoverStaleLock(root, ownerPath, input);
419
- const envelope = baseEnvelope("unlock", "unlock");
420
- envelope.status = "unlocked";
421
- envelope.record = { path: displayPath(root, ownerPath), confirmation: "unchanged", scope };
422
- envelope.lock = {
423
- scope,
424
- lockPath: displayPath(root, recovered.lockPath),
425
- ownerPath: displayPath(root, recovered.ownerPath),
426
- pid: recovered.lock.pid,
427
- createdAt: recovered.lock.createdAt,
428
- authoritySource: input.authoritySource,
429
- };
430
- return envelope;
431
- }
432
-
433
- function executeSchemaCommand(input, options) {
434
- const command = options["--command"] ?? input.command ?? "all";
435
- return {
436
- status: "schema",
437
- operation: "schema",
438
- command,
439
- content: renderCommandSchema(command),
440
- errors: [],
441
- warnings: [],
442
- };
443
- }
444
-
445
- function parseViewLimit(input, options) {
446
- const raw = options["--limit"] ?? input.limit;
447
- if (raw === undefined) return 5;
448
- const limit = typeof raw === "number" ? raw : Number(raw);
449
- if (!Number.isInteger(limit) || limit < 1 || limit > 100)
450
- fail("invalid-limit", "View limit must be an integer from 1 through 100");
451
- return limit;
452
- }
453
-
454
- async function executeViewCommand(root, input, options, command) {
455
- assertKnownInput(input, VIEW_INPUT_KEYS, "view");
456
- const limit = parseViewLimit(input, options);
457
- const recordPath = resolveRecordPath(root, options);
458
- const loaded = await loadRecord(root, recordPath);
459
- const view = options["--view"] ?? input.view ?? "resume";
460
- const record =
461
- loaded.kind === "v2"
462
- ? recordMetadata(root, recordPath, loaded.data, loaded.rawSha)
463
- : unavailableRecord(root, recordPath, loaded.rawSha, readOnlyReason(loaded), loaded.data);
464
- const envelope = baseEnvelope(command, "view", record);
465
- envelope.status = "viewed";
466
- const entity = options["--entity"] ?? input.entity;
467
- const section = options["--section"] ?? input.section;
468
- if (view === "section" && loaded.kind === "v2") fail("invalid-view", "Unknown view: section");
469
- if (loaded.kind !== "v2") {
470
- envelope.warnings.push({
471
- code: loaded.kind === "legacy" ? "legacy-read-only" : "unsupported-schema-read-only",
472
- message: "Legacy or unsupported record was rendered read-only; explicit migration is required for mutation",
473
- });
474
- try {
475
- const content = legacyView(loaded, view, entity, section, limit);
476
- envelope.view = { name: view, sha256: sha256(content), content };
477
- return envelope;
478
- } catch (error) {
479
- if (error instanceof WorkingRecordError) error.record = record;
480
- throw error;
481
- }
482
- }
483
- const validation = validateModel(loaded.data);
484
- if (validation.length) {
485
- const error = new WorkingRecordError("invalid-record", "Record failed schema validation", {
486
- validation,
487
- path: displayPath(root, recordPath),
488
- sha256: loaded.rawSha,
489
- });
490
- error.record = unavailableRecord(root, recordPath, loaded.rawSha, "invalid-record");
491
- throw error;
492
- }
493
- const content =
494
- view === "section"
495
- ? `${renderRecordHeaderOnly(loaded.data)}\n${renderNamedSection(loaded.data, section)}`
496
- : renderView(loaded.data, view, entity, limit, loaded.rawSha);
497
- envelope.view = { name: view, sha256: sha256(content), content };
498
- return envelope;
499
- }
500
-
501
- async function executeValidateCommand(root, options, command = "validate") {
502
- const recordPath = resolveRecordPath(root, options);
503
- const loaded = await loadRecord(root, recordPath);
504
- const record =
505
- loaded.kind === "v2"
506
- ? recordMetadata(root, recordPath, loaded.data, loaded.rawSha)
507
- : unavailableRecord(root, recordPath, loaded.rawSha, readOnlyReason(loaded), loaded.data);
508
- const envelope = baseEnvelope(command, command, record);
509
- if (loaded.kind !== "v2") {
510
- envelope.status = "failed";
511
- envelope.errors = [
512
- {
513
- code: loaded.kind === "legacy" ? "legacy-read-only" : "unsupported-schema-read-only",
514
- message: "Legacy or unsupported record is parseable for read-only audit but is not schema-v2 valid or mutable",
515
- },
516
- ];
517
- envelope.validation = { valid: false, validForReadOnlyAudit: true, mutable: false, errors: envelope.errors };
518
- return envelope;
519
- }
520
- const errors = validateModel(loaded.data);
521
- envelope.validation = { valid: errors.length === 0, errors };
522
- if (errors.length) {
523
- envelope.status = "failed";
524
- envelope.record = unavailableRecord(root, recordPath, loaded.rawSha, "invalid-record");
525
- envelope.errors = errors;
526
- return envelope;
527
- }
528
- envelope.status = "valid";
529
- return envelope;
530
- }
531
-
532
- async function executeInspectCommand(root, options) {
533
- const recordPath = resolveRecordPath(root, options);
534
- const loaded = await loadRecord(root, recordPath);
535
- const record =
536
- loaded.kind === "v2"
537
- ? recordMetadata(root, recordPath, loaded.data, loaded.rawSha)
538
- : unavailableRecord(root, recordPath, loaded.rawSha, readOnlyReason(loaded), loaded.data);
539
- const envelope = baseEnvelope("inspect", "inspect", record);
540
- const validation = loaded.kind === "v2" ? validateModel(loaded.data) : [];
541
- envelope.inspection = await inspectData(root, loaded);
542
- envelope.warnings.push(...envelope.inspection.warnings);
543
- if (validation.length) {
544
- envelope.status = "failed";
545
- envelope.record = unavailableRecord(root, recordPath, loaded.rawSha, "invalid-record");
546
- envelope.errors = validation;
547
- return envelope;
548
- }
549
- envelope.status = "inspected";
550
- return envelope;
551
- }
552
-
553
- export async function executeCommand(command, { root = process.cwd(), options = {}, input = {} } = {}) {
554
- const workspaceRoot = resolve(root);
555
- const normalizedInput = normalizeInput(input);
556
- if (command === "init") return initRecord(workspaceRoot, normalizedInput, options);
557
- if (["view", "resume-view"].includes(command))
558
- return executeViewCommand(workspaceRoot, normalizedInput, options, "view");
559
- if (command === "validate") return executeValidateCommand(workspaceRoot, options);
560
- if (command === "inspect") return executeInspectCommand(workspaceRoot, options);
561
- if (command === "schema") return executeSchemaCommand(normalizedInput, options);
562
- if (command === "unlock") return executeUnlockCommand(workspaceRoot, normalizedInput, options);
563
- if (["update", "start", "block", "resume", "reopen", "close"].includes(command))
564
- return executeMutationCommand(workspaceRoot, command, normalizedInput, options);
565
- if (["migrate", "compress"].includes(command))
566
- return executeRewriteCommand(workspaceRoot, command, normalizedInput, options);
567
- fail("unknown-command", `Unknown command: ${command}`);
568
- }