@hassangameryt/freeflow 0.4.0 → 0.6.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 (285) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -1
  3. package/.codex-plugin/plugin.json +2 -1
  4. package/README.md +150 -155
  5. package/capabilities/cognitive-routing/SKILL.md +229 -0
  6. package/capabilities/context-virtualization/SKILL.md +103 -0
  7. package/capabilities/conversation-history/SKILL.md +53 -0
  8. package/command-surface.json +17 -13
  9. package/hooks/freeflow-runtime-context.mjs +393 -159
  10. package/hooks/hooks.json +26 -1
  11. package/hooks/tests/check-runtime-context-hook.sh +223 -54
  12. package/package.json +25 -16
  13. package/pi-extension/dist/cognitive-routing/commands.js +96 -0
  14. package/pi-extension/dist/cognitive-routing/config.js +236 -0
  15. package/pi-extension/dist/cognitive-routing/controller.js +862 -0
  16. package/pi-extension/dist/cognitive-routing/history.js +439 -0
  17. package/pi-extension/dist/cognitive-routing/host.js +126 -0
  18. package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
  19. package/pi-extension/dist/cognitive-routing/tool.js +211 -0
  20. package/pi-extension/dist/cognitive-routing/types.js +6 -0
  21. package/pi-extension/dist/context-virtualization/commands.js +89 -0
  22. package/pi-extension/dist/context-virtualization/projector.js +42 -0
  23. package/pi-extension/dist/context-virtualization/runtime.js +356 -0
  24. package/pi-extension/dist/context-virtualization/state.js +57 -0
  25. package/pi-extension/dist/context-virtualization/types.js +10 -0
  26. package/pi-extension/dist/conversation-history/passages.js +66 -0
  27. package/pi-extension/dist/conversation-history/ranking.js +105 -0
  28. package/pi-extension/dist/conversation-history/runtime.js +226 -0
  29. package/pi-extension/dist/conversation-history/search.js +56 -0
  30. package/pi-extension/dist/conversation-history/types.js +1 -0
  31. package/pi-extension/dist/freeflow-context/resolver.js +120 -0
  32. package/pi-extension/dist/freeflow-context/runtime.js +80 -0
  33. package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
  34. package/pi-extension/dist/freeflow-context/tool.js +308 -0
  35. package/pi-extension/dist/freeflow-context/types.js +12 -0
  36. package/pi-extension/dist/freeflow-context/visibility.js +28 -0
  37. package/pi-extension/dist/index.js +516 -98
  38. package/pi-extension/dist/runtime/runtime-context.js +318 -271
  39. package/pi-extension/dist/runtime/runtime-identity.js +5 -0
  40. package/pi-extension/dist/settings/settings-tui.js +78 -0
  41. package/pi-extension/dist/settings/settings-ui.js +593 -563
  42. package/pi-extension/dist/ui/text-component.js +57 -0
  43. package/pi-extension/src/cognitive-routing/commands.ts +119 -0
  44. package/pi-extension/src/cognitive-routing/config.ts +307 -0
  45. package/pi-extension/src/cognitive-routing/controller.ts +1118 -0
  46. package/pi-extension/src/cognitive-routing/history.ts +638 -0
  47. package/pi-extension/src/cognitive-routing/host.ts +172 -0
  48. package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
  49. package/pi-extension/src/cognitive-routing/tool.ts +272 -0
  50. package/pi-extension/src/cognitive-routing/types.ts +89 -0
  51. package/pi-extension/src/context-virtualization/commands.ts +111 -0
  52. package/pi-extension/src/context-virtualization/projector.ts +62 -0
  53. package/pi-extension/src/context-virtualization/runtime.ts +406 -0
  54. package/pi-extension/src/context-virtualization/state.ts +79 -0
  55. package/pi-extension/src/context-virtualization/types.ts +92 -0
  56. package/pi-extension/src/conversation-history/passages.ts +81 -0
  57. package/pi-extension/src/conversation-history/ranking.ts +155 -0
  58. package/pi-extension/src/conversation-history/runtime.ts +250 -0
  59. package/pi-extension/src/conversation-history/search.ts +79 -0
  60. package/pi-extension/src/conversation-history/types.ts +31 -0
  61. package/pi-extension/src/freeflow-context/resolver.ts +139 -0
  62. package/pi-extension/src/freeflow-context/runtime.ts +100 -0
  63. package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
  64. package/pi-extension/src/freeflow-context/tool.ts +360 -0
  65. package/pi-extension/src/freeflow-context/types.ts +70 -0
  66. package/pi-extension/src/freeflow-context/visibility.ts +53 -0
  67. package/pi-extension/src/index.ts +553 -101
  68. package/pi-extension/src/runtime/runtime-context.ts +339 -281
  69. package/pi-extension/src/runtime/runtime-identity.ts +8 -0
  70. package/pi-extension/src/settings/settings-tui.ts +93 -0
  71. package/pi-extension/src/settings/settings-ui.ts +700 -613
  72. package/pi-extension/src/ui/text-component.ts +66 -0
  73. package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
  74. package/pi-extension/tests/cognitive-routing/controller.test.js +1099 -0
  75. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1071 -0
  76. package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
  77. package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
  78. package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
  79. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +236 -0
  80. package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
  81. package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
  82. package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
  83. package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
  84. package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
  85. package/pi-extension/tests/conversation-history/search.test.js +97 -0
  86. package/pi-extension/tests/integration/pi-extension.test.js +928 -2047
  87. package/pi-extension/tests/integration/prompt-architecture.test.js +305 -0
  88. package/runtime/prompts/cognitive-routing.md +9 -0
  89. package/runtime/prompts/context-virtualization.md +3 -0
  90. package/runtime/prompts/conversation-history.md +3 -0
  91. package/runtime/prompts/core.md +13 -0
  92. package/runtime/prompts/interaction-contract.md +7 -0
  93. package/runtime/prompts/skills.md +65 -0
  94. package/skills/action-selection/SKILL.md +91 -0
  95. package/skills/bypass/SKILL.md +3 -2
  96. package/skills/commit-work/SKILL.md +1 -1
  97. package/skills/commit-work/references/staging-decisions.md +1 -1
  98. package/skills/decision-gate/SKILL.md +1 -1
  99. package/skills/design-for-depth/SKILL.md +14 -33
  100. package/skills/design-for-depth/references/design-pressure-signals.md +1 -1
  101. package/skills/design-for-depth/references/interface-design-loop.md +1 -1
  102. package/skills/design-for-depth/references/software-design-philosophy.md +1 -1
  103. package/skills/diagnose-failure/SKILL.md +20 -14
  104. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +1 -3
  105. package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +1 -1
  106. package/skills/discuss/SKILL.md +34 -22
  107. package/skills/discuss/references/discussion-continuity.md +71 -0
  108. package/skills/evaluate-skill/SKILL.md +5 -5
  109. package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +42 -2
  110. package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
  111. package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
  112. package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
  113. package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
  114. package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
  115. package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
  116. package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
  117. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
  118. package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
  119. package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
  120. package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
  121. package/skills/execute-work/SKILL.md +18 -15
  122. package/skills/execute-work/references/code-practices.md +1 -1
  123. package/skills/execute-work/references/execute-work-edges.md +42 -0
  124. package/skills/finish-branch/SKILL.md +2 -2
  125. package/skills/finish-branch/references/integration-options.md +1 -1
  126. package/skills/handoff/SKILL.md +3 -3
  127. package/skills/launch-work/SKILL.md +1 -1
  128. package/skills/launch-work/references/launch-readiness.md +2 -2
  129. package/skills/migration-work/SKILL.md +2 -2
  130. package/skills/migration-work/references/migration-lifecycle.md +1 -1
  131. package/skills/mode-contract/SKILL.md +32 -10
  132. package/skills/release-work/SKILL.md +1 -1
  133. package/skills/release-work/references/release-evidence.md +1 -1
  134. package/skills/review-artifact/SKILL.md +28 -26
  135. package/skills/review-work/SKILL.md +28 -26
  136. package/skills/review-work/references/{reviewer-prompt.md → independent-work-reviewer-contract.md} +1 -1
  137. package/skills/review-work/references/security-risk-lens.md +1 -1
  138. package/skills/setup-freeflow/SKILL.md +6 -10
  139. package/skills/setup-freeflow/references/activation-contract.md +5 -10
  140. package/skills/setup-freeflow/references/host-setup.md +3 -7
  141. package/skills/simplify-code/SKILL.md +1 -1
  142. package/skills/simplify-code/references/simplification-patterns.md +1 -1
  143. package/skills/tdd/SKILL.md +18 -38
  144. package/skills/tdd/references/test-design.md +2 -2
  145. package/skills/track-work/SKILL.md +362 -58
  146. package/skills/track-work/scripts/lib/codec.mjs +570 -0
  147. package/skills/track-work/scripts/lib/commands.mjs +568 -0
  148. package/skills/track-work/scripts/lib/contract.mjs +303 -0
  149. package/skills/track-work/scripts/lib/model.mjs +506 -0
  150. package/skills/track-work/scripts/lib/operations.mjs +965 -0
  151. package/skills/track-work/scripts/lib/record-store.mjs +264 -0
  152. package/skills/track-work/scripts/lib/result.mjs +37 -0
  153. package/skills/track-work/scripts/lib/rewrites.mjs +740 -0
  154. package/skills/track-work/scripts/lib/schema.mjs +277 -0
  155. package/skills/track-work/scripts/lib/source-inventory.mjs +162 -0
  156. package/skills/track-work/scripts/lib/views.mjs +443 -0
  157. package/skills/track-work/scripts/lib/workspace.mjs +134 -0
  158. package/skills/track-work/scripts/working-record.mjs +122 -0
  159. package/skills/verify-work/SKILL.md +14 -2
  160. package/skills/verify-work/references/browser-runtime-evidence.md +1 -1
  161. package/skills/verify-work/references/integration-evidence.md +1 -1
  162. package/skills/verify-work/references/performance-evidence.md +1 -1
  163. package/skills/workflow/SKILL.md +105 -53
  164. package/skills/workflow/references/domain-skill-composition.md +22 -42
  165. package/skills/write-plan/SKILL.md +1 -1
  166. package/skills/write-skill/SKILL.md +3 -2
  167. package/skills/write-skill/references/progressive-disclosure.md +17 -3
  168. package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
  169. package/pi-extension/dist/output-router/native-safety-net.js +0 -216
  170. package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
  171. package/pi-extension/dist/output-router/renderers.js +0 -1023
  172. package/pi-extension/dist/output-router/router-tools.js +0 -554
  173. package/pi-extension/dist/output-router/schemas.js +0 -383
  174. package/pi-extension/dist/output-router/status.js +0 -744
  175. package/pi-extension/dist/output-router/utils.js +0 -502
  176. package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
  177. package/pi-extension/src/output-router/native-safety-net.ts +0 -248
  178. package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
  179. package/pi-extension/src/output-router/renderers.ts +0 -1108
  180. package/pi-extension/src/output-router/router-tools.ts +0 -579
  181. package/pi-extension/src/output-router/schemas.ts +0 -387
  182. package/pi-extension/src/output-router/status.ts +0 -791
  183. package/pi-extension/src/output-router/utils.ts +0 -554
  184. package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
  185. package/pi-extension/tests/output-router/search.test.js +0 -722
  186. package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
  187. package/router/dist/benchmarks/benchmark-harness.js +0 -92
  188. package/router/dist/benchmarks/benchmarks.d.ts +0 -109
  189. package/router/dist/benchmarks/benchmarks.js +0 -979
  190. package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
  191. package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
  192. package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
  193. package/router/dist/benchmarks/command-benchmarks.js +0 -698
  194. package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
  195. package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
  196. package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
  197. package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
  198. package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
  199. package/router/dist/benchmarks/context-saving-baseline.js +0 -470
  200. package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
  201. package/router/dist/benchmarks/index-benchmarks.js +0 -862
  202. package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
  203. package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
  204. package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
  205. package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
  206. package/router/dist/config/config.d.ts +0 -103
  207. package/router/dist/config/config.js +0 -632
  208. package/router/dist/config/router-contract.d.ts +0 -10
  209. package/router/dist/config/router-contract.js +0 -54
  210. package/router/dist/config/schema.d.ts +0 -27
  211. package/router/dist/config/schema.js +0 -648
  212. package/router/dist/config/types.d.ts +0 -573
  213. package/router/dist/config/types.js +0 -41
  214. package/router/dist/evidence/bounded-evidence.d.ts +0 -40
  215. package/router/dist/evidence/bounded-evidence.js +0 -323
  216. package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
  217. package/router/dist/evidence/evidence-range-selector.js +0 -232
  218. package/router/dist/evidence/evidence-search.d.ts +0 -27
  219. package/router/dist/evidence/evidence-search.js +0 -490
  220. package/router/dist/evidence/evidence.d.ts +0 -38
  221. package/router/dist/evidence/evidence.js +0 -200
  222. package/router/dist/evidence/failure-contracts.d.ts +0 -37
  223. package/router/dist/evidence/failure-contracts.js +0 -166
  224. package/router/dist/evidence/line-ranges.d.ts +0 -24
  225. package/router/dist/evidence/line-ranges.js +0 -22
  226. package/router/dist/experiments/local-index.d.ts +0 -64
  227. package/router/dist/experiments/local-index.js +0 -581
  228. package/router/dist/index.d.ts +0 -30
  229. package/router/dist/index.js +0 -32
  230. package/router/dist/local/local-traversal.d.ts +0 -18
  231. package/router/dist/local/local-traversal.js +0 -334
  232. package/router/dist/processing/engine.d.ts +0 -132
  233. package/router/dist/processing/engine.js +0 -533
  234. package/router/dist/processing/reducers.d.ts +0 -280
  235. package/router/dist/processing/reducers.js +0 -1673
  236. package/router/dist/processing/renderers.d.ts +0 -31
  237. package/router/dist/processing/renderers.js +0 -195
  238. package/router/dist/processing/scripts.d.ts +0 -91
  239. package/router/dist/processing/scripts.js +0 -386
  240. package/router/dist/repo/repo-traversal.d.ts +0 -18
  241. package/router/dist/repo/repo-traversal.js +0 -245
  242. package/router/dist/routing/observed-reducers.d.ts +0 -41
  243. package/router/dist/routing/observed-reducers.js +0 -661
  244. package/router/dist/routing/observed-routing.d.ts +0 -26
  245. package/router/dist/routing/observed-routing.js +0 -378
  246. package/router/dist/routing/parsers.d.ts +0 -16
  247. package/router/dist/routing/parsers.js +0 -521
  248. package/router/dist/routing/run-filters.d.ts +0 -60
  249. package/router/dist/routing/run-filters.js +0 -238
  250. package/router/dist/routing/run-reducers.d.ts +0 -49
  251. package/router/dist/routing/run-reducers.js +0 -122
  252. package/router/dist/sandbox/adapter-roots.d.ts +0 -46
  253. package/router/dist/sandbox/adapter-roots.js +0 -66
  254. package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
  255. package/router/dist/sandbox/eryx-python-adapter.js +0 -868
  256. package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
  257. package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
  258. package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
  259. package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
  260. package/router/dist/sandbox/script-sandbox.d.ts +0 -134
  261. package/router/dist/sandbox/script-sandbox.js +0 -337
  262. package/router/dist/setup/script-transform-adapters.d.ts +0 -32
  263. package/router/dist/setup/script-transform-adapters.js +0 -278
  264. package/router/dist/tools/batch.d.ts +0 -33
  265. package/router/dist/tools/batch.js +0 -586
  266. package/router/dist/tools/run.d.ts +0 -62
  267. package/router/dist/tools/run.js +0 -1304
  268. package/router/dist/tools/search.d.ts +0 -66
  269. package/router/dist/tools/search.js +0 -1364
  270. package/router/dist/transform/engine.d.ts +0 -168
  271. package/router/dist/transform/engine.js +0 -2072
  272. package/router/dist/vault/vault-index.d.ts +0 -125
  273. package/router/dist/vault/vault-index.js +0 -416
  274. package/router/dist/vault/vault.d.ts +0 -138
  275. package/router/dist/vault/vault.js +0 -630
  276. package/runtime/interaction-contract.md +0 -16
  277. package/skills/discuss/references/checkpoints.md +0 -66
  278. package/skills/execute-work/references/execution-loop.md +0 -77
  279. package/skills/output-router/SKILL.md +0 -206
  280. package/skills/output-router/references/safety-policy.md +0 -40
  281. package/skills/setup-freeflow/references/output-router-setup.md +0 -110
  282. package/skills/track-work/references/working-record-schema.md +0 -378
  283. package/skills/workflow/references/workflow-loop.md +0 -92
  284. /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
  285. /package/skills/review-artifact/references/{reviewer-prompt.md → independent-artifact-reviewer-contract.md} +0 -0
@@ -0,0 +1,568 @@
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
+ }