orkeon-code 0.0.0-stage → 1.0.0-rc.2

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 (552) hide show
  1. package/.orkeon-runtime +10 -0
  2. package/.orkeon-version +1 -0
  3. package/LICENSE.md +21 -0
  4. package/NOTICE.md +17 -0
  5. package/README.fr.md +163 -0
  6. package/README.md +156 -2
  7. package/config/appsettings.anthropic.example.json +77 -0
  8. package/config/appsettings.example.json +71 -0
  9. package/config/appsettings.jev.example.json +131 -0
  10. package/config/appsettings.kev.example.json +133 -0
  11. package/config/appsettings.liquid.example.json +132 -0
  12. package/config/appsettings.ollama-whisper.example.json +93 -0
  13. package/config/appsettings.ollama.example.json +70 -0
  14. package/config/appsettings.whisper.example.json +32 -0
  15. package/mcp/whisper/README.md +294 -0
  16. package/mcp/whisper/pyproject.toml +32 -0
  17. package/mcp/whisper/uv.lock +1641 -0
  18. package/mcp/whisper/whisper_mcp.py +1053 -0
  19. package/orkeon-code +1092 -0
  20. package/orkeon-code.mjs +71 -0
  21. package/orkeon-code.ps1 +939 -0
  22. package/package.json +58 -4
  23. package/scripts/install.ps1 +156 -0
  24. package/scripts/install.sh +148 -0
  25. package/scripts/session-start.ork.ts +90 -0
  26. package/scripts/session-start.sh +74 -0
  27. package/scripts/setup-fixture.sh +88 -0
  28. package/src/commands/.orkeon/orkeon-cli.d.ts +559 -0
  29. package/src/commands/_lib/args.ts +194 -0
  30. package/src/commands/_lib/dev/dev-batches.ts +366 -0
  31. package/src/commands/_lib/dev/dev-implement.ts +185 -0
  32. package/src/commands/_lib/dev/dev-source.ts +61 -0
  33. package/src/commands/_lib/dev/dev.ts +341 -0
  34. package/src/commands/_lib/dev/markers.ts +7 -0
  35. package/src/commands/_lib/dev/messages.ts +112 -0
  36. package/src/commands/_lib/dev-step.ts +145 -0
  37. package/src/commands/_lib/dispatch.ts +254 -0
  38. package/src/commands/_lib/effort.ts +15 -0
  39. package/src/commands/_lib/git/branch.ts +94 -0
  40. package/src/commands/_lib/git/commit.ts +90 -0
  41. package/src/commands/_lib/git/diff.ts +107 -0
  42. package/src/commands/_lib/git/messages.ts +54 -0
  43. package/src/commands/_lib/git/review.ts +108 -0
  44. package/src/commands/_lib/memory/memory-admit.ts +148 -0
  45. package/src/commands/_lib/memory/memory.ts +52 -0
  46. package/src/commands/_lib/memory/messages.ts +32 -0
  47. package/src/commands/_lib/messages.ts +48 -0
  48. package/src/commands/_lib/pr-context.ts +32 -0
  49. package/src/commands/_lib/project/analyze.ts +24 -0
  50. package/src/commands/_lib/project/messages.ts +8 -0
  51. package/src/commands/_lib/session/export.ts +105 -0
  52. package/src/commands/_lib/session/messages.ts +87 -0
  53. package/src/commands/_lib/session/prompts.ts +4 -0
  54. package/src/commands/_lib/session/resume.ts +151 -0
  55. package/src/commands/_lib/session/tasks.ts +181 -0
  56. package/src/commands/_lib/settings/advisor.ts +75 -0
  57. package/src/commands/_lib/settings/agents.ts +137 -0
  58. package/src/commands/_lib/settings/choices.ts +8 -0
  59. package/src/commands/_lib/settings/config.ts +141 -0
  60. package/src/commands/_lib/settings/effort.ts +147 -0
  61. package/src/commands/_lib/settings/hooks.ts +50 -0
  62. package/src/commands/_lib/settings/messages.ts +408 -0
  63. package/src/commands/_lib/settings/mode.ts +100 -0
  64. package/src/commands/_lib/settings/model.ts +181 -0
  65. package/src/commands/_lib/settings/output-style.ts +39 -0
  66. package/src/commands/_lib/settings/permissions.ts +287 -0
  67. package/src/commands/_lib/settings/route.ts +63 -0
  68. package/src/commands/_lib/settings/session-config.ts +49 -0
  69. package/src/commands/_lib/settings/skills.ts +93 -0
  70. package/src/commands/_lib/settings/theme.ts +42 -0
  71. package/src/commands/_lib/speech/messages.ts +58 -0
  72. package/src/commands/_lib/speech/prompts.ts +4 -0
  73. package/src/commands/_lib/speech/say.ts +95 -0
  74. package/src/commands/_lib/speech/transcribe.ts +121 -0
  75. package/src/commands/_lib/speech/voice.ts +142 -0
  76. package/src/commands/_lib/status/cache.ts +31 -0
  77. package/src/commands/_lib/status/context.ts +57 -0
  78. package/src/commands/_lib/status/doctor.ts +205 -0
  79. package/src/commands/_lib/status/messages.ts +100 -0
  80. package/src/commands/_lib/status/meta.ts +24 -0
  81. package/src/commands/_lib/status/status.ts +128 -0
  82. package/src/commands/_lib/status/usage-tools.ts +48 -0
  83. package/src/commands/_lib/status/usage.ts +128 -0
  84. package/src/commands/_lib/view.ts +34 -0
  85. package/src/commands/dev/dev-batches.cmd.ts +109 -0
  86. package/src/commands/dev/dev-learn.cmd.ts +29 -0
  87. package/src/commands/dev/dev-plan.cmd.ts +51 -0
  88. package/src/commands/dev/dev-spec.cmd.ts +54 -0
  89. package/src/commands/dev/dev-status.cmd.ts +16 -0
  90. package/src/commands/git/branch.cmd.ts +27 -0
  91. package/src/commands/git/commit.cmd.ts +48 -0
  92. package/src/commands/git/diff.cmd.ts +26 -0
  93. package/src/commands/git/review.cmd.ts +36 -0
  94. package/src/commands/memory/memory.cmd.ts +48 -0
  95. package/src/commands/project/analyze.cmd.ts +32 -0
  96. package/src/commands/project/debug-tool-call.cmd.ts +62 -0
  97. package/src/commands/project/files.cmd.ts +22 -0
  98. package/src/commands/project/init-verifiers.cmd.ts +14 -0
  99. package/src/commands/project/init.cmd.ts +14 -0
  100. package/src/commands/project/verify.cmd.ts +27 -0
  101. package/src/commands/session/assistant.cmd.ts +40 -0
  102. package/src/commands/session/btw.cmd.ts +18 -0
  103. package/src/commands/session/clear.cmd.ts +19 -0
  104. package/src/commands/session/compact.cmd.ts +16 -0
  105. package/src/commands/session/copy.cmd.ts +45 -0
  106. package/src/commands/session/exit.cmd.ts +9 -0
  107. package/src/commands/session/export.cmd.ts +28 -0
  108. package/src/commands/session/rename.cmd.ts +18 -0
  109. package/src/commands/session/resume.cmd.ts +19 -0
  110. package/src/commands/session/rewind.cmd.ts +25 -0
  111. package/src/commands/session/summary.cmd.ts +27 -0
  112. package/src/commands/session/tasks.cmd.ts +46 -0
  113. package/src/commands/settings/advisor.cmd.ts +38 -0
  114. package/src/commands/settings/agents.cmd.ts +19 -0
  115. package/src/commands/settings/config.cmd.ts +19 -0
  116. package/src/commands/settings/effort.cmd.ts +19 -0
  117. package/src/commands/settings/fast.cmd.ts +18 -0
  118. package/src/commands/settings/hooks.cmd.ts +17 -0
  119. package/src/commands/settings/mode.cmd.ts +20 -0
  120. package/src/commands/settings/model.cmd.ts +21 -0
  121. package/src/commands/settings/output-style.cmd.ts +19 -0
  122. package/src/commands/settings/permissions.cmd.ts +25 -0
  123. package/src/commands/settings/proactive.cmd.ts +16 -0
  124. package/src/commands/settings/route.cmd.ts +16 -0
  125. package/src/commands/settings/skills.cmd.ts +17 -0
  126. package/src/commands/settings/theme.cmd.ts +14 -0
  127. package/src/commands/speech/say.cmd.ts +24 -0
  128. package/src/commands/speech/transcribe.cmd.ts +29 -0
  129. package/src/commands/speech/voice.cmd.ts +30 -0
  130. package/src/commands/status/context.cmd.ts +18 -0
  131. package/src/commands/status/doctor.cmd.ts +27 -0
  132. package/src/commands/status/release-notes.cmd.ts +9 -0
  133. package/src/commands/status/status.cmd.ts +25 -0
  134. package/src/commands/status/usage.cmd.ts +21 -0
  135. package/src/crews/.orkeon/orkeon.d.ts +4391 -0
  136. package/src/crews/_probe-shared-memory/domain/messages.ts +54 -0
  137. package/src/crews/_probe-shared-memory/domain/probe-verdict.ts +188 -0
  138. package/src/crews/_probe-shared-memory/domain/prompts.ts +5 -0
  139. package/src/crews/_probe-shared-memory/probe.ork.ts +100 -0
  140. package/src/crews/advisor/application/messages.ts +4 -0
  141. package/src/crews/advisor/application/prompts.ts +4 -0
  142. package/src/crews/advisor/application/run-advisor.ts +41 -0
  143. package/src/crews/advisor/crew.ork.ts +44 -0
  144. package/src/crews/advisor/domain/advice.ts +119 -0
  145. package/src/crews/advisor/domain/messages.ts +8 -0
  146. package/src/crews/advisor/domain/prompts.ts +26 -0
  147. package/src/crews/agent-run/application/messages.ts +18 -0
  148. package/src/crews/agent-run/application/run-agent-run.ts +43 -0
  149. package/src/crews/agent-run/crew.ork.ts +67 -0
  150. package/src/crews/analyze/application/messages.ts +27 -0
  151. package/src/crews/analyze/application/prompts.ts +4 -0
  152. package/src/crews/analyze/application/run-analyze.ts +120 -0
  153. package/src/crews/analyze/crew.ork.ts +41 -0
  154. package/src/crews/analyze/domain/harvest.ts +269 -0
  155. package/src/crews/analyze/domain/prompts.ts +86 -0
  156. package/src/crews/code-review/application/lens-material.ts +24 -0
  157. package/src/crews/code-review/application/messages.ts +17 -0
  158. package/src/crews/code-review/application/prompts.ts +126 -0
  159. package/src/crews/code-review/application/review.ts +74 -0
  160. package/src/crews/code-review/application/run-code-review.ts +121 -0
  161. package/src/crews/code-review/crew.ork.ts +52 -0
  162. package/src/crews/code-review/domain/lenses.ts +154 -0
  163. package/src/crews/code-review/domain/messages.ts +25 -0
  164. package/src/crews/code-review/domain/prompts.ts +58 -0
  165. package/src/crews/code-review/domain/report.ts +58 -0
  166. package/src/crews/code-review/domain/scope.ts +106 -0
  167. package/src/crews/dev-batches/application/messages.ts +127 -0
  168. package/src/crews/dev-batches/application/plan-close.ts +181 -0
  169. package/src/crews/dev-batches/application/prompts.ts +10 -0
  170. package/src/crews/dev-batches/application/run-dev-batches.ts +676 -0
  171. package/src/crews/dev-batches/application/run-wave.ts +452 -0
  172. package/src/crews/dev-batches/application/seed-harvest.ts +163 -0
  173. package/src/crews/dev-batches/crew.ork.ts +146 -0
  174. package/src/crews/dev-batches/domain/batch-waves.ts +70 -0
  175. package/src/crews/dev-batches/domain/batches-budget.ts +52 -0
  176. package/src/crews/dev-batches/domain/batches-log.ts +52 -0
  177. package/src/crews/dev-batches/domain/markers.ts +5 -0
  178. package/src/crews/dev-batches/domain/messages.ts +6 -0
  179. package/src/crews/dev-batches/domain/wave-order.ts +44 -0
  180. package/src/crews/dev-change/application/change-material.ts +44 -0
  181. package/src/crews/dev-change/application/evidence.ts +172 -0
  182. package/src/crews/dev-change/application/messages.ts +81 -0
  183. package/src/crews/dev-change/application/prompts.ts +101 -0
  184. package/src/crews/dev-change/application/run-dev-change.ts +324 -0
  185. package/src/crews/dev-change/crew.ork.ts +114 -0
  186. package/src/crews/dev-change/domain/change-answer.ts +163 -0
  187. package/src/crews/dev-change/domain/change-render.ts +77 -0
  188. package/src/crews/dev-change/domain/markers.ts +28 -0
  189. package/src/crews/dev-change/domain/messages.ts +16 -0
  190. package/src/crews/dev-implement/application/close.ts +186 -0
  191. package/src/crews/dev-implement/application/count-open-steps.ts +24 -0
  192. package/src/crews/dev-implement/application/locate-sheet.ts +82 -0
  193. package/src/crews/dev-implement/application/messages.ts +161 -0
  194. package/src/crews/dev-implement/application/observe.ts +52 -0
  195. package/src/crews/dev-implement/application/prompts.ts +9 -0
  196. package/src/crews/dev-implement/application/report-writes.ts +46 -0
  197. package/src/crews/dev-implement/application/run-dev-implement.ts +822 -0
  198. package/src/crews/dev-implement/application/run-role.ts +27 -0
  199. package/src/crews/dev-implement/application/suite-job.ts +122 -0
  200. package/src/crews/dev-implement/application/touched.ts +74 -0
  201. package/src/crews/dev-implement/crew.ork.ts +69 -0
  202. package/src/crews/dev-implement/domain/contracts.ts +255 -0
  203. package/src/crews/dev-implement/domain/correction.ts +103 -0
  204. package/src/crews/dev-implement/domain/cycles.ts +36 -0
  205. package/src/crews/dev-implement/domain/implement-budget.ts +29 -0
  206. package/src/crews/dev-implement/domain/markers.ts +23 -0
  207. package/src/crews/dev-implement/domain/messages.ts +58 -0
  208. package/src/crews/dev-implement/domain/prompts.ts +93 -0
  209. package/src/crews/dev-implement/domain/roles.ts +49 -0
  210. package/src/crews/dev-implement/domain/sheet-edits.ts +76 -0
  211. package/src/crews/dev-implement/domain/sheet-ticks.ts +23 -0
  212. package/src/crews/dev-implement/domain/step-checks.ts +137 -0
  213. package/src/crews/dev-implement/domain/step-section.ts +129 -0
  214. package/src/crews/dev-learn/application/learn-backlog.ts +58 -0
  215. package/src/crews/dev-learn/application/learn-prompt-fit.ts +63 -0
  216. package/src/crews/dev-learn/application/messages.ts +51 -0
  217. package/src/crews/dev-learn/application/prompts.ts +99 -0
  218. package/src/crews/dev-learn/application/run-dev-learn.ts +558 -0
  219. package/src/crews/dev-learn/crew.ork.ts +53 -0
  220. package/src/crews/dev-learn/domain/learn-answer.ts +233 -0
  221. package/src/crews/dev-learn/domain/messages.ts +65 -0
  222. package/src/crews/dev-learn/domain/owner-lines.ts +89 -0
  223. package/src/crews/dev-learn/domain/proposals-render.ts +95 -0
  224. package/src/crews/dev-plan/application/anchor-paths.ts +113 -0
  225. package/src/crews/dev-plan/application/inventory.ts +174 -0
  226. package/src/crews/dev-plan/application/messages.ts +88 -0
  227. package/src/crews/dev-plan/application/plan-prompt-fit.ts +44 -0
  228. package/src/crews/dev-plan/application/prompts.ts +141 -0
  229. package/src/crews/dev-plan/application/run-dev-plan.ts +483 -0
  230. package/src/crews/dev-plan/crew.ork.ts +112 -0
  231. package/src/crews/dev-plan/domain/inventory-model.ts +95 -0
  232. package/src/crews/dev-plan/domain/markers.ts +18 -0
  233. package/src/crews/dev-plan/domain/messages.ts +118 -0
  234. package/src/crews/dev-plan/domain/plan-answer.ts +753 -0
  235. package/src/crews/dev-plan/domain/plan-render.ts +306 -0
  236. package/src/crews/dev-plan/domain/prompts.ts +44 -0
  237. package/src/crews/dev-spec/application/messages.ts +30 -0
  238. package/src/crews/dev-spec/application/prompts.ts +93 -0
  239. package/src/crews/dev-spec/application/run-dev-spec.ts +237 -0
  240. package/src/crews/dev-spec/application/spec-material.ts +42 -0
  241. package/src/crews/dev-spec/crew.ork.ts +110 -0
  242. package/src/crews/dev-spec/domain/markers.ts +30 -0
  243. package/src/crews/dev-spec/domain/messages.ts +39 -0
  244. package/src/crews/dev-spec/domain/spec-answer.ts +252 -0
  245. package/src/crews/dev-spec/domain/spec-render.ts +76 -0
  246. package/src/crews/dev-verify/application/audit-brief.ts +187 -0
  247. package/src/crews/dev-verify/application/audit.ts +267 -0
  248. package/src/crews/dev-verify/application/capture.ts +311 -0
  249. package/src/crews/dev-verify/application/messages.ts +119 -0
  250. package/src/crews/dev-verify/application/prompts.ts +209 -0
  251. package/src/crews/dev-verify/application/run-dev-verify.ts +423 -0
  252. package/src/crews/dev-verify/application/run-gate.ts +204 -0
  253. package/src/crews/dev-verify/crew.ork.ts +103 -0
  254. package/src/crews/dev-verify/domain/audit-answer.ts +154 -0
  255. package/src/crews/dev-verify/domain/auditor-charter.ts +21 -0
  256. package/src/crews/dev-verify/domain/capture-sections.ts +138 -0
  257. package/src/crews/dev-verify/domain/commands.ts +103 -0
  258. package/src/crews/dev-verify/domain/gate.ts +131 -0
  259. package/src/crews/dev-verify/domain/markers.ts +16 -0
  260. package/src/crews/dev-verify/domain/mechanical-table.ts +156 -0
  261. package/src/crews/dev-verify/domain/messages.ts +92 -0
  262. package/src/crews/dev-verify/domain/runtime-cut.ts +13 -0
  263. package/src/crews/dev-verify/domain/sheet-facts.ts +4 -0
  264. package/src/crews/dev-verify/domain/text.ts +20 -0
  265. package/src/crews/dev-verify/domain/verdict.ts +127 -0
  266. package/src/crews/git-commit/application/draft.ts +133 -0
  267. package/src/crews/git-commit/application/messages.ts +15 -0
  268. package/src/crews/git-commit/application/prompts.ts +47 -0
  269. package/src/crews/git-commit/application/run-git-commit.ts +117 -0
  270. package/src/crews/git-commit/crew.ork.ts +53 -0
  271. package/src/crews/git-commit/domain/commit.ts +200 -0
  272. package/src/crews/git-commit/domain/markers.ts +4 -0
  273. package/src/crews/git-commit/domain/messages.ts +48 -0
  274. package/src/crews/init-verifiers/application/authoring.ts +90 -0
  275. package/src/crews/init-verifiers/application/messages.ts +13 -0
  276. package/src/crews/init-verifiers/application/prompts.ts +107 -0
  277. package/src/crews/init-verifiers/application/run-init-verifiers.ts +26 -0
  278. package/src/crews/init-verifiers/crew.ork.ts +35 -0
  279. package/src/crews/init-verifiers/domain/commands-section.ts +36 -0
  280. package/src/crews/init-verifiers/domain/readiness.ts +23 -0
  281. package/src/crews/main-loop/application/auto-compact.ts +78 -0
  282. package/src/crews/main-loop/application/context-gather.ts +133 -0
  283. package/src/crews/main-loop/application/messages.ts +81 -0
  284. package/src/crews/main-loop/application/prompts.ts +12 -0
  285. package/src/crews/main-loop/application/run-main-loop.ts +383 -0
  286. package/src/crews/main-loop/application/turn-context.ts +111 -0
  287. package/src/crews/main-loop/crew.ork.ts +124 -0
  288. package/src/crews/main-loop/domain/autocompact.ts +27 -0
  289. package/src/crews/main-loop/domain/prompt-assembly.ts +338 -0
  290. package/src/crews/main-loop/domain/prompts.ts +336 -0
  291. package/src/crews/main-loop/domain/turn-chains.ts +130 -0
  292. package/src/crews/project-init/application/detect.ts +123 -0
  293. package/src/crews/project-init/application/messages.ts +15 -0
  294. package/src/crews/project-init/application/prompts.ts +105 -0
  295. package/src/crews/project-init/application/run-project-init.ts +31 -0
  296. package/src/crews/project-init/crew.ork.ts +36 -0
  297. package/src/crews/project-init/domain/conventions.ts +36 -0
  298. package/src/crews/project-init/domain/existing-files.ts +65 -0
  299. package/src/crews/project-init/domain/messages.ts +13 -0
  300. package/src/crews/project-init/domain/package-map.ts +73 -0
  301. package/src/crews/project-init/domain/prompts.ts +10 -0
  302. package/src/crews/session-compact/application/prompts.ts +5 -0
  303. package/src/crews/session-compact/crew.ork.ts +56 -0
  304. package/src/crews/shared-memory-admit/application/prompts.ts +5 -0
  305. package/src/crews/shared-memory-admit/crew.ork.ts +49 -0
  306. package/src/crews/speech/application/messages.ts +3 -0
  307. package/src/crews/speech/application/prompts.ts +3 -0
  308. package/src/crews/speech/application/run-speech.ts +26 -0
  309. package/src/crews/speech/crew.ork.ts +38 -0
  310. package/src/shared/application/agents/child-agent.ts +259 -0
  311. package/src/shared/application/agents/messages.ts +35 -0
  312. package/src/shared/application/agents/route-agent.ts +115 -0
  313. package/src/shared/application/agents/run-sub-agent.ts +119 -0
  314. package/src/shared/application/answer-language.ts +14 -0
  315. package/src/shared/application/attached-skills.ts +36 -0
  316. package/src/shared/application/compaction/compact-session.ts +242 -0
  317. package/src/shared/application/compaction/extract-memories.ts +38 -0
  318. package/src/shared/application/compaction/messages.ts +20 -0
  319. package/src/shared/application/compaction/prune-context.ts +94 -0
  320. package/src/shared/application/compaction/pruned-llm.ts +35 -0
  321. package/src/shared/application/compaction/restore-context.ts +78 -0
  322. package/src/shared/application/config-store.ts +123 -0
  323. package/src/shared/application/dev/brief-inventory.ts +115 -0
  324. package/src/shared/application/dev/close-batch.ts +85 -0
  325. package/src/shared/application/dev/find-repo-pack.ts +78 -0
  326. package/src/shared/application/dev/learn-decision.ts +254 -0
  327. package/src/shared/application/dev/load-dev-context.ts +265 -0
  328. package/src/shared/application/dev/measure-access-cost.ts +69 -0
  329. package/src/shared/application/dev/messages.ts +132 -0
  330. package/src/shared/application/dev/phase-timer.ts +54 -0
  331. package/src/shared/application/dev/plan-source.ts +116 -0
  332. package/src/shared/application/dev/preflight.ts +71 -0
  333. package/src/shared/application/dev/project-files.ts +17 -0
  334. package/src/shared/application/dev/prompts.ts +34 -0
  335. package/src/shared/application/dev/question-round.ts +60 -0
  336. package/src/shared/application/dev/resolve-work-folder.ts +134 -0
  337. package/src/shared/application/dev/script-tool-slot.ts +27 -0
  338. package/src/shared/application/dev/settle-questions.ts +57 -0
  339. package/src/shared/application/dev/source-review.ts +67 -0
  340. package/src/shared/application/dev/source-step.ts +152 -0
  341. package/src/shared/application/dev/spend.ts +55 -0
  342. package/src/shared/application/dev/step-precedents.ts +90 -0
  343. package/src/shared/application/dev/tool-call-policy.ts +87 -0
  344. package/src/shared/application/dev/tool-callbacks.ts +262 -0
  345. package/src/shared/application/dev/tool-trace-recorder.ts +46 -0
  346. package/src/shared/application/dev/verdict-sources.ts +50 -0
  347. package/src/shared/application/dev/wrapped-tools.ts +147 -0
  348. package/src/shared/application/extra-tools.ts +71 -0
  349. package/src/shared/application/git/batch-worktree.ts +102 -0
  350. package/src/shared/application/git/commit-files.ts +191 -0
  351. package/src/shared/application/git/merge-batch.ts +67 -0
  352. package/src/shared/application/git/messages.ts +75 -0
  353. package/src/shared/application/git/open-pull-request.ts +52 -0
  354. package/src/shared/application/host-context.ts +59 -0
  355. package/src/shared/application/host-layout-store.ts +45 -0
  356. package/src/shared/application/instructions-file.ts +19 -0
  357. package/src/shared/application/json-file.ts +34 -0
  358. package/src/shared/application/llm-profile.ts +36 -0
  359. package/src/shared/application/messages.ts +14 -0
  360. package/src/shared/application/permission-rules.ts +169 -0
  361. package/src/shared/application/ports/approvals.ts +20 -0
  362. package/src/shared/application/ports/clock.ts +5 -0
  363. package/src/shared/application/ports/code-index.ts +93 -0
  364. package/src/shared/application/ports/crew.ts +60 -0
  365. package/src/shared/application/ports/decision.ts +14 -0
  366. package/src/shared/application/ports/files.ts +21 -0
  367. package/src/shared/application/ports/human.ts +38 -0
  368. package/src/shared/application/ports/llm.ts +83 -0
  369. package/src/shared/application/ports/memory.ts +30 -0
  370. package/src/shared/application/ports/progress.ts +23 -0
  371. package/src/shared/application/ports/runtime.ts +15 -0
  372. package/src/shared/application/ports/session.ts +74 -0
  373. package/src/shared/application/ports/shared-memory.ts +26 -0
  374. package/src/shared/application/ports/shell.ts +40 -0
  375. package/src/shared/application/ports/telemetry.ts +45 -0
  376. package/src/shared/application/ports/theme.ts +11 -0
  377. package/src/shared/application/ports/tools.ts +46 -0
  378. package/src/shared/application/ports/usage.ts +45 -0
  379. package/src/shared/application/ports.ts +29 -0
  380. package/src/shared/application/project-manifests.ts +106 -0
  381. package/src/shared/application/session-io.ts +85 -0
  382. package/src/shared/application/session-state.ts +36 -0
  383. package/src/shared/application/shared-memory/admit-entries.ts +179 -0
  384. package/src/shared/application/shared-memory/harvest-after-gaps.ts +69 -0
  385. package/src/shared/application/shared-memory/harvest-mistakes.ts +45 -0
  386. package/src/shared/application/shared-memory/import-agent-memory.ts +119 -0
  387. package/src/shared/application/shared-memory/memory-files.ts +111 -0
  388. package/src/shared/application/shared-memory/memory-settings.ts +94 -0
  389. package/src/shared/application/shared-memory/messages.ts +63 -0
  390. package/src/shared/application/shared-memory/push-candidate.ts +149 -0
  391. package/src/shared/application/shared-memory/recall-precedents.ts +70 -0
  392. package/src/shared/application/skills/messages.ts +4 -0
  393. package/src/shared/application/skills/suggest-skills.ts +102 -0
  394. package/src/shared/application/state-snapshot.ts +38 -0
  395. package/src/shared/application/workflow/messages.ts +8 -0
  396. package/src/shared/application/workflow/workflow-state.ts +136 -0
  397. package/src/shared/domain/agent-policy/behavior-flags.ts +162 -0
  398. package/src/shared/domain/agent-policy/extra-tools.ts +67 -0
  399. package/src/shared/domain/agent-policy/memory-categories.ts +6 -0
  400. package/src/shared/domain/agent-policy/messages.ts +66 -0
  401. package/src/shared/domain/agent-policy/mode-policy.ts +51 -0
  402. package/src/shared/domain/agent-policy/output-styles.ts +11 -0
  403. package/src/shared/domain/agent-policy/path-rules.ts +299 -0
  404. package/src/shared/domain/agent-policy/permission.ts +625 -0
  405. package/src/shared/domain/agent-policy/prompts.ts +17 -0
  406. package/src/shared/domain/agent-policy/reasoning.ts +59 -0
  407. package/src/shared/domain/agent-policy/rule-sets.ts +416 -0
  408. package/src/shared/domain/agent-policy/tool-access.ts +91 -0
  409. package/src/shared/domain/agent-registry.ts +143 -0
  410. package/src/shared/domain/agents/built-in-charters.ts +43 -0
  411. package/src/shared/domain/agents/chain.ts +30 -0
  412. package/src/shared/domain/agents/charter.ts +64 -0
  413. package/src/shared/domain/agents/exclusive.ts +25 -0
  414. package/src/shared/domain/agents/instances.ts +252 -0
  415. package/src/shared/domain/agents/messages.ts +39 -0
  416. package/src/shared/domain/agents/model-route.ts +199 -0
  417. package/src/shared/domain/agents/prompts.ts +20 -0
  418. package/src/shared/domain/code-intel-contract.ts +357 -0
  419. package/src/shared/domain/code-intel-routing.ts +60 -0
  420. package/src/shared/domain/compact-outcome.ts +46 -0
  421. package/src/shared/domain/compaction-thresholds.ts +162 -0
  422. package/src/shared/domain/compaction.ts +288 -0
  423. package/src/shared/domain/config-schema.ts +434 -0
  424. package/src/shared/domain/context-prune.ts +176 -0
  425. package/src/shared/domain/decision/questions.ts +102 -0
  426. package/src/shared/domain/dev/access-cost.ts +230 -0
  427. package/src/shared/domain/dev/artefacts.ts +50 -0
  428. package/src/shared/domain/dev/batches-concurrency.ts +35 -0
  429. package/src/shared/domain/dev/batches-state.ts +49 -0
  430. package/src/shared/domain/dev/build-commands.ts +45 -0
  431. package/src/shared/domain/dev/call-guard.ts +342 -0
  432. package/src/shared/domain/dev/carried-text.ts +47 -0
  433. package/src/shared/domain/dev/design-rules.ts +100 -0
  434. package/src/shared/domain/dev/learn-proposals.ts +176 -0
  435. package/src/shared/domain/dev/learn-state.ts +94 -0
  436. package/src/shared/domain/dev/markers.ts +107 -0
  437. package/src/shared/domain/dev/messages.ts +259 -0
  438. package/src/shared/domain/dev/path-args.ts +42 -0
  439. package/src/shared/domain/dev/path-rebase.ts +93 -0
  440. package/src/shared/domain/dev/phase-timing.ts +50 -0
  441. package/src/shared/domain/dev/plan-checks.ts +191 -0
  442. package/src/shared/domain/dev/plan-format.ts +170 -0
  443. package/src/shared/domain/dev/project-files.ts +29 -0
  444. package/src/shared/domain/dev/prompts/brief-blocks.ts +20 -0
  445. package/src/shared/domain/dev/prompts.ts +251 -0
  446. package/src/shared/domain/dev/questions.ts +267 -0
  447. package/src/shared/domain/dev/reading-rule.ts +41 -0
  448. package/src/shared/domain/dev/repo-pack.ts +240 -0
  449. package/src/shared/domain/dev/review-answer.ts +173 -0
  450. package/src/shared/domain/dev/review-brief.ts +54 -0
  451. package/src/shared/domain/dev/reviewer-charter.ts +35 -0
  452. package/src/shared/domain/dev/sheet-facts.ts +81 -0
  453. package/src/shared/domain/dev/spec-format.ts +182 -0
  454. package/src/shared/domain/dev/step-budget.ts +74 -0
  455. package/src/shared/domain/dev/step-rules.ts +109 -0
  456. package/src/shared/domain/dev/test-commands.ts +94 -0
  457. package/src/shared/domain/dev/test-output.ts +33 -0
  458. package/src/shared/domain/dev/test-paths.ts +40 -0
  459. package/src/shared/domain/dev/tool-guards.ts +65 -0
  460. package/src/shared/domain/dev/trait-pattern.ts +87 -0
  461. package/src/shared/domain/dev/verdict-format.ts +162 -0
  462. package/src/shared/domain/dev/whitespace.ts +35 -0
  463. package/src/shared/domain/dev/work-folder.ts +68 -0
  464. package/src/shared/domain/dev/yaml-subset.ts +385 -0
  465. package/src/shared/domain/error-text.ts +13 -0
  466. package/src/shared/domain/git/close.ts +274 -0
  467. package/src/shared/domain/git/messages.ts +20 -0
  468. package/src/shared/domain/git/pull-request.ts +96 -0
  469. package/src/shared/domain/git/worktree.ts +46 -0
  470. package/src/shared/domain/host-layout.ts +147 -0
  471. package/src/shared/domain/host-paths.ts +399 -0
  472. package/src/shared/domain/index-languages.ts +16 -0
  473. package/src/shared/domain/instructions-file.ts +18 -0
  474. package/src/shared/domain/iso-day.ts +4 -0
  475. package/src/shared/domain/llm-failure.ts +134 -0
  476. package/src/shared/domain/llm-profile.ts +44 -0
  477. package/src/shared/domain/marked-message.ts +29 -0
  478. package/src/shared/domain/markers.ts +30 -0
  479. package/src/shared/domain/messages.ts +291 -0
  480. package/src/shared/domain/model-catalog.ts +79 -0
  481. package/src/shared/domain/permission-modes.ts +99 -0
  482. package/src/shared/domain/prelude.ts +92 -0
  483. package/src/shared/domain/project-manifests.ts +84 -0
  484. package/src/shared/domain/prompts.ts +233 -0
  485. package/src/shared/domain/search-routing.ts +77 -0
  486. package/src/shared/domain/secret-patterns.ts +46 -0
  487. package/src/shared/domain/session-keys.ts +92 -0
  488. package/src/shared/domain/session-start.ts +61 -0
  489. package/src/shared/domain/severity.ts +72 -0
  490. package/src/shared/domain/sha1.ts +61 -0
  491. package/src/shared/domain/shared-memory/agent-memory-import.ts +145 -0
  492. package/src/shared/domain/shared-memory/candidates.ts +40 -0
  493. package/src/shared/domain/shared-memory/entry.ts +151 -0
  494. package/src/shared/domain/shared-memory/front-matter.ts +187 -0
  495. package/src/shared/domain/shared-memory/gate.ts +45 -0
  496. package/src/shared/domain/shared-memory/harvest.ts +64 -0
  497. package/src/shared/domain/shared-memory/layout.ts +190 -0
  498. package/src/shared/domain/shared-memory/markers.ts +9 -0
  499. package/src/shared/domain/shared-memory/messages.ts +66 -0
  500. package/src/shared/domain/shared-memory/precedents-block.ts +82 -0
  501. package/src/shared/domain/shared-memory/prompts.ts +28 -0
  502. package/src/shared/domain/shared-memory/refused.ts +84 -0
  503. package/src/shared/domain/shared-memory/verdict-rows.ts +134 -0
  504. package/src/shared/domain/skills/prompts.ts +4 -0
  505. package/src/shared/domain/skills/shortlist.ts +149 -0
  506. package/src/shared/domain/snip-turns.ts +33 -0
  507. package/src/shared/domain/speech.ts +21 -0
  508. package/src/shared/domain/strip.ts +88 -0
  509. package/src/shared/domain/tool-trace.ts +120 -0
  510. package/src/shared/domain/types.ts +67 -0
  511. package/src/shared/domain/verifiers.ts +33 -0
  512. package/src/shared/domain/vfs.ts +16 -0
  513. package/src/shared/domain/workflow/prompts.ts +15 -0
  514. package/src/shared/domain/workflow/state-file.ts +142 -0
  515. package/src/shared/infrastructure/globals.ts +57 -0
  516. package/src/shared/infrastructure/orkeon/approvals.ts +24 -0
  517. package/src/shared/infrastructure/orkeon/child-agents.ts +122 -0
  518. package/src/shared/infrastructure/orkeon/chooser.ts +32 -0
  519. package/src/shared/infrastructure/orkeon/code-index.ts +120 -0
  520. package/src/shared/infrastructure/orkeon/crew-host.ts +27 -0
  521. package/src/shared/infrastructure/orkeon/crew-memory.ts +12 -0
  522. package/src/shared/infrastructure/orkeon/decision-model.ts +31 -0
  523. package/src/shared/infrastructure/orkeon/dev-deps.ts +179 -0
  524. package/src/shared/infrastructure/orkeon/files.ts +58 -0
  525. package/src/shared/infrastructure/orkeon/github-pull-requests.ts +30 -0
  526. package/src/shared/infrastructure/orkeon/host-context.ts +36 -0
  527. package/src/shared/infrastructure/orkeon/host-provider.ts +22 -0
  528. package/src/shared/infrastructure/orkeon/human-input.ts +55 -0
  529. package/src/shared/infrastructure/orkeon/llm-profile.ts +58 -0
  530. package/src/shared/infrastructure/orkeon/llm.ts +164 -0
  531. package/src/shared/infrastructure/orkeon/markers.ts +6 -0
  532. package/src/shared/infrastructure/orkeon/memory-store.ts +41 -0
  533. package/src/shared/infrastructure/orkeon/memory-tools.ts +129 -0
  534. package/src/shared/infrastructure/orkeon/messages.ts +15 -0
  535. package/src/shared/infrastructure/orkeon/permission-rules.ts +42 -0
  536. package/src/shared/infrastructure/orkeon/progress.ts +24 -0
  537. package/src/shared/infrastructure/orkeon/prompts.ts +47 -0
  538. package/src/shared/infrastructure/orkeon/reasoning.ts +40 -0
  539. package/src/shared/infrastructure/orkeon/run-state.ts +17 -0
  540. package/src/shared/infrastructure/orkeon/runtime-info.ts +30 -0
  541. package/src/shared/infrastructure/orkeon/runtime-tools.ts +60 -0
  542. package/src/shared/infrastructure/orkeon/script-tools.ts +129 -0
  543. package/src/shared/infrastructure/orkeon/session-store.ts +94 -0
  544. package/src/shared/infrastructure/orkeon/session-switch.ts +23 -0
  545. package/src/shared/infrastructure/orkeon/shared-memory.ts +61 -0
  546. package/src/shared/infrastructure/orkeon/shell-jobs.ts +81 -0
  547. package/src/shared/infrastructure/orkeon/shell.ts +39 -0
  548. package/src/shared/infrastructure/orkeon/telemetry.ts +63 -0
  549. package/src/shared/infrastructure/orkeon/tool-catalogue.ts +76 -0
  550. package/src/shared/infrastructure/orkeon/tool-results.ts +120 -0
  551. package/src/shared/infrastructure/orkeon/usage.ts +74 -0
  552. package/src/shared/infrastructure/orkeon/wiring.ts +174 -0
@@ -0,0 +1,72 @@
1
+ // Finding severity ordering + dedup/rank — pure, no IO. Extracted verbatim in
2
+ // behaviour from code-review/crew.ork.ts:68-77 so it can be unit-tested
3
+ // without a live LLM run.
4
+
5
+ import type { Finding } from "./types.ts";
6
+
7
+ /** Canonical severity ladder, most→least severe. */
8
+ export const SEVERITY_ORDER: Record<string, number> = {
9
+ blocker: 0,
10
+ high: 1,
11
+ medium: 2,
12
+ low: 3,
13
+ nit: 4,
14
+ };
15
+
16
+ /** Rank a severity for sorting; unknown severities sort last (9). */
17
+ export function severityRank(severity: string | undefined): number {
18
+ return SEVERITY_ORDER[String(severity ?? "").toLowerCase()] ?? 9;
19
+ }
20
+
21
+ /** How many characters of the claim the dedup key keeps. */
22
+ export const DEDUP_CLAIM_CHARS = 40;
23
+
24
+ /** Stable dedup key: file + line + category (lower-cased, empty when absent) + the
25
+ * start of the claim (the first {@link DEDUP_CLAIM_CHARS} characters of `finding`,
26
+ * trimmed and lower-cased). The claim opens a finding, so two faults of one lens on
27
+ * one line stay apart, while passes or lenses that give the same category and the
28
+ * same claim opening collapse; each lens names its own category, so two lenses
29
+ * rarely do. */
30
+ export function findingDedupKey(f: Finding): string {
31
+ const claim = String(f.finding ?? "").trim().toLowerCase().slice(0, DEDUP_CLAIM_CHARS);
32
+ return `${f.file}:${f.line}:${(f.category ?? "").toLowerCase()}:${claim}`;
33
+ }
34
+
35
+ /** Whether `a` outranks `b` on one key: the more severe, or at equal severity a
36
+ * `shown` over a finding that is not, so the report never calls plausible what a
37
+ * pass showed. */
38
+ function outranks(a: Finding, b: Finding): boolean {
39
+ const bySeverity = severityRank(a.severity) - severityRank(b.severity);
40
+ if (bySeverity !== 0) return bySeverity < 0;
41
+ return a.confidence === "shown" && b.confidence !== "shown";
42
+ }
43
+
44
+ /**
45
+ * Merge lens results, drop duplicates (by {@link findingDedupKey}), and sort by
46
+ * severity. On a collision the most severe finding is kept, at equal severity the
47
+ * `shown` one, else the first, so a blocker is never dropped behind a low on the
48
+ * same key. Each input group
49
+ * carries its lens so the kept finding records which lens surfaced it.
50
+ * Order-stable for equal severities (sort is stable in V8).
51
+ */
52
+ export function dedupAndRank(
53
+ groups: ReadonlyArray<{ lens: string; findings: Finding[] }>,
54
+ ): Finding[] {
55
+ const at = new Map<string, number>();
56
+ const all: Finding[] = [];
57
+ for (const g of groups) {
58
+ for (const f of g.findings) {
59
+ const key = findingDedupKey(f);
60
+ const kept = { ...f, lens: f.lens ?? g.lens };
61
+ const index = at.get(key);
62
+ if (index === undefined) {
63
+ at.set(key, all.length);
64
+ all.push(kept);
65
+ } else if (outranks(kept, all[index])) {
66
+ all[index] = kept;
67
+ }
68
+ }
69
+ }
70
+ all.sort((a, b) => severityRank(a.severity) - severityRank(b.severity));
71
+ return all;
72
+ }
@@ -0,0 +1,61 @@
1
+ // SHA-1 over the UTF-8 bytes of a string, in plain TypeScript: the REPL runtime has
2
+ // neither TextEncoder nor a hash module, and the learning ids must equal the ones the
3
+ // harness's script computes with Python's hashlib. Pure, no IO, never throws.
4
+
5
+ /** The UTF-8 bytes of a string; a lone surrogate encodes as U+FFFD (EF BF BD). */
6
+ export function utf8Bytes(text: string): number[] {
7
+ const out: number[] = [];
8
+ for (let i = 0; i < text.length; i++) {
9
+ let c = text.charCodeAt(i);
10
+ if (c >= 0xd800 && c <= 0xdbff) {
11
+ const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;
12
+ if (next >= 0xdc00 && next <= 0xdfff) {
13
+ c = 0x10000 + ((c - 0xd800) << 10) + (next - 0xdc00);
14
+ i++;
15
+ } else c = 0xfffd;
16
+ } else if (c >= 0xdc00 && c <= 0xdfff) c = 0xfffd;
17
+ if (c < 0x80) out.push(c);
18
+ else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));
19
+ else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
20
+ else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
21
+ }
22
+ return out;
23
+ }
24
+
25
+ function rotl(x: number, n: number): number {
26
+ return ((x << n) | (x >>> (32 - n))) >>> 0;
27
+ }
28
+
29
+ /** SHA-1 (FIPS 180-4) of the UTF-8 bytes of text, 40 lower-case hex digits. */
30
+ export function sha1Hex(text: string): string {
31
+ const bytes = utf8Bytes(text);
32
+ const bits = bytes.length * 8;
33
+ bytes.push(0x80);
34
+ while (bytes.length % 64 !== 56) bytes.push(0);
35
+ const high = Math.floor(bits / 2 ** 32);
36
+ const low = bits >>> 0;
37
+ bytes.push((high >>> 24) & 0xff, (high >>> 16) & 0xff, (high >>> 8) & 0xff, high & 0xff);
38
+ bytes.push((low >>> 24) & 0xff, (low >>> 16) & 0xff, (low >>> 8) & 0xff, low & 0xff);
39
+
40
+ let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;
41
+ const w = new Array<number>(80);
42
+ for (let off = 0; off < bytes.length; off += 64) {
43
+ for (let t = 0; t < 16; t++) {
44
+ const j = off + t * 4;
45
+ w[t] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) >>> 0;
46
+ }
47
+ for (let t = 16; t < 80; t++) w[t] = rotl(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1);
48
+ let a = h0, b = h1, c = h2, d = h3, e = h4;
49
+ for (let t = 0; t < 80; t++) {
50
+ let f: number, k: number;
51
+ if (t < 20) { f = (b & c) | (~b & d); k = 0x5a827999; }
52
+ else if (t < 40) { f = b ^ c ^ d; k = 0x6ed9eba1; }
53
+ else if (t < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8f1bbcdc; }
54
+ else { f = b ^ c ^ d; k = 0xca62c1d6; }
55
+ const temp = (rotl(a, 5) + (f >>> 0) + e + k + w[t]) >>> 0;
56
+ e = d; d = c; c = rotl(b, 30); b = a; a = temp;
57
+ }
58
+ h0 = (h0 + a) >>> 0; h1 = (h1 + b) >>> 0; h2 = (h2 + c) >>> 0; h3 = (h3 + d) >>> 0; h4 = (h4 + e) >>> 0;
59
+ }
60
+ return [h0, h1, h2, h3, h4].map((h) => h.toString(16).padStart(8, "0")).join("");
61
+ }
@@ -0,0 +1,145 @@
1
+ // The harness's agent memory read as shared-memory candidates (lot M-9, temp/05 § 8.2), pure: one
2
+ // top-level list item of a .claude/agent-memory/<agent>/MEMORY.md is one entry, its linked note (a
3
+ // .md file of the same folder) read when there is one. Every entry becomes a `method` candidate whose
4
+ // source is the import itself: /memory-admit still asks for each one.
5
+
6
+ import { MAX_BODY_CHARS, MAX_TITLE_CHARS, entryIdPrefix } from "./entry.ts";
7
+ import type { MemoryEntry } from "./entry.ts";
8
+ import { topicOf } from "./refused.ts";
9
+ import { HOW_TO_APPLY_LABEL } from "./markers.ts";
10
+ import { importedFrom } from "./prompts.ts";
11
+
12
+ /** The harness's agent memory, relative to the project. */
13
+ export const HARNESS_AGENT_MEMORY_DIR = ".claude/agent-memory";
14
+ export const AGENT_MEMORY_INDEX = "MEMORY.md";
15
+ /** How many characters of a linked note are read. */
16
+ export const MAX_NOTE_CHARS = 8_000;
17
+
18
+ export interface AgentMemoryItem {
19
+ /** 1-based line of the item in MEMORY.md. */
20
+ line: number;
21
+ title: string;
22
+ /** The text after the link (or the whole item when it has none). */
23
+ hook: string;
24
+ /** The linked note's file name, when it is a plain .md name of the agent's folder. */
25
+ note?: string;
26
+ }
27
+
28
+ const ITEM = /^[-*]\s+(.*)$/;
29
+ const LINKED = /^\[([^\]]+)\]\(([^)\s]+)\)\s*(?:[—–:-]+\s*)?(.*)$/;
30
+ const NOTE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/;
31
+
32
+ /** How many characters of a sentence (a hook, a Why, a How to apply) an entry keeps. */
33
+ export const MAX_SENTENCE_CHARS = 300;
34
+
35
+ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim();
36
+ const plain = (text: string): string => text.replace(/\*\*|__|`/g, "");
37
+
38
+ /** At most `max` characters, cut at a word. */
39
+ function cut(text: string, max: number): string {
40
+ const t = oneLine(text);
41
+ if (Array.from(t).length <= max) return t;
42
+ const head = Array.from(t).slice(0, max - 1).join("");
43
+ const at = head.lastIndexOf(" ");
44
+ return `${(at > max / 2 ? head.slice(0, at) : head).trimEnd()}…`;
45
+ }
46
+
47
+ /** A title of at most MAX_TITLE_CHARS, cut at a word. */
48
+ export function shortTitle(text: string): string {
49
+ return cut(plain(text), MAX_TITLE_CHARS);
50
+ }
51
+
52
+ /** The entries of a MEMORY.md: its top-level list items, an indented line continuing the item above. */
53
+ export function parseAgentMemoryIndex(text: string): AgentMemoryItem[] {
54
+ const items: Array<{ line: number; text: string }> = [];
55
+ let fenced = false;
56
+ let current: { line: number; text: string } | null = null;
57
+ text.replace(/\r\n?/g, "\n").split("\n").forEach((raw, i) => {
58
+ if (/^\s*(```|~~~)/.test(raw)) { fenced = !fenced; current = null; return; }
59
+ if (fenced) return;
60
+ const m = ITEM.exec(raw);
61
+ if (m !== null) {
62
+ current = { line: i + 1, text: m[1] };
63
+ items.push(current);
64
+ } else if (current !== null && /^\s+\S/.test(raw)) {
65
+ current.text += ` ${raw.trim()}`;
66
+ } else {
67
+ current = null;
68
+ }
69
+ });
70
+ return items.flatMap(({ line, text: item }) => {
71
+ const body = oneLine(item);
72
+ // A thematic break (`* * *`, `- - -`) is not an entry.
73
+ if (body === "" || /^([-*_])(\s*\1)+$/.test(body)) return [];
74
+ const link = LINKED.exec(body);
75
+ if (link === null) return [{ line, title: shortTitle(body), hook: body }];
76
+ const title = shortTitle(link[1]);
77
+ const hook = oneLine(link[3]) || title;
78
+ return [NOTE_NAME.test(link[2]) ? { line, title, hook, note: link[2] } : { line, title, hook }];
79
+ }).filter((item) => /[A-Za-z0-9]/.test(item.title));
80
+ }
81
+
82
+ export interface AgentNote {
83
+ /** The note without its front matter. */
84
+ body: string;
85
+ why?: string;
86
+ howToApply?: string;
87
+ }
88
+
89
+ /** A linked note: its front matter dropped, its `**Why:**` and `**How to apply:**` sentences picked. */
90
+ export function parseAgentNote(text: string): AgentNote {
91
+ let body = text.replace(/\r\n?/g, "\n");
92
+ const fm = /^---\n[\s\S]*?\n---\n?/.exec(body);
93
+ if (fm !== null) body = body.slice(fm[0].length);
94
+ body = body.trim();
95
+ // A label is a bold run ending in a colon (`**Why:**`); a sentence ends at the next label or a blank line.
96
+ const pick = (label: string): string | undefined => {
97
+ const m = new RegExp(`\\*\\*${label}:\\*\\*\\s*([\\s\\S]*?)(?=\\*\\*[A-Za-z][^*\\n]{0,30}:\\*\\*|\\n\\s*\\n|$)`, "i").exec(body);
98
+ const value = m === null ? "" : oneLine(m[1]);
99
+ return value === "" ? undefined : value;
100
+ };
101
+ const note: AgentNote = { body };
102
+ const why = pick("Why");
103
+ const how = pick(HOW_TO_APPLY_LABEL);
104
+ if (why !== undefined) note.why = why;
105
+ if (how !== undefined) note.howToApply = how;
106
+ return note;
107
+ }
108
+
109
+ export interface ImportContext {
110
+ agent: string;
111
+ project: string;
112
+ /** YYYY-MM-DD. */
113
+ date: string;
114
+ }
115
+
116
+ const TAG = /^[a-z0-9][a-z0-9.+#-]*$/;
117
+
118
+ /** The candidate an item becomes (its id not yet made unique; the domain's entryProblems still applies). */
119
+ export function importedEntry(item: AgentMemoryItem, note: AgentNote | null, ctx: ImportContext): MemoryEntry {
120
+ const index = `${HARNESS_AGENT_MEMORY_DIR}/${ctx.agent}/${AGENT_MEMORY_INDEX}`;
121
+ const topic = topicOf(item.title);
122
+ const evidence = [`- \`${index}:${item.line}\``];
123
+ if (note !== null && item.note !== undefined) evidence.push(`- \`${HARNESS_AGENT_MEMORY_DIR}/${ctx.agent}/${item.note}\``);
124
+ const hook = cut(item.hook, MAX_SENTENCE_CHARS);
125
+ const head = ["## Context", importedFrom(ctx.agent, index, item.line)];
126
+ // Without a note the item itself is the content: it is not repeated here.
127
+ if (note !== null && item.hook !== item.title) head.push(hook);
128
+ const tail = ["", "## Evidence", ...evidence];
129
+ // A note's own headings are flattened: the entry's three sections stay the only ones.
130
+ let fenced = false;
131
+ const content = (note?.body ?? item.hook).split("\n").map((l) => {
132
+ if (/^\s*(```|~~~)/.test(l)) fenced = !fenced;
133
+ return fenced ? l : l.replace(/^#{1,6}\s+/, "");
134
+ }).join("\n").trim() || item.title;
135
+ const room = MAX_BODY_CHARS - (head.join("\n").length + tail.join("\n").length + "\n\n## Content\n\n".length + 1);
136
+ const shown = content.length <= room ? content : `${content.slice(0, Math.max(0, room - 1)).trimEnd()}…`;
137
+ return {
138
+ id: `${entryIdPrefix(ctx.project, "method", ctx.date)}${topic}`,
139
+ type: "method", title: item.title, project: ctx.project, date: ctx.date, topic,
140
+ appliesWhen: cut(note?.howToApply ?? hook, MAX_SENTENCE_CHARS), rationale: cut(note?.why ?? hook, MAX_SENTENCE_CHARS),
141
+ source: `human:${ctx.date} import ${index}`, status: "candidate", supersedes: [],
142
+ tags: ["agent-memory", ...(TAG.test(ctx.agent) ? [ctx.agent] : [])], stack: [],
143
+ body: [...head, "", "## Content", shown, ...tail].join("\n") + "\n",
144
+ };
145
+ }
@@ -0,0 +1,40 @@
1
+ // The shared memory's generated lists, pure: candidates/CANDIDATES.md (the pending candidates) and
2
+ // INDEX.md (every entry of entries/). Both are views rebuilt from the files, which stay the truth.
3
+ // A decided candidate cannot be deleted (no file tool removes a file): its file is rewritten to one
4
+ // pointer line, which never parses as an entry, so it is no longer a candidate.
5
+
6
+ import type { MemoryEntry } from "./entry.ts";
7
+ import { admittedPointer, CANDIDATES_INTRO, INDEX_INTRO, refusedPointer } from "./messages.ts";
8
+
9
+ export const CANDIDATES_TITLE = "# Memory candidates";
10
+ export const INDEX_TITLE = "# Shared memory";
11
+
12
+ const cell = (text: string): string => text.replace(/\r?\n/g, " ").replace(/\\/g, "\\\\").replace(/\|/g, "\\|").trim();
13
+
14
+ function table(head: readonly string[], rows: ReadonlyArray<readonly string[]>): string[] {
15
+ return [`| ${head.join(" | ")} |`, `|${head.map(() => "---").join("|")}|`, ...rows.map((r) => `| ${r.map(cell).join(" | ")} |`)];
16
+ }
17
+
18
+ /** How many distinct batches a source names (`<code>/<CODE>-VERIFY-F<n>.md`), for the batches column; "-" when none. */
19
+ export function batchesOf(source: string): string {
20
+ const batches = new Set([...source.matchAll(/([^\s,:/]+)\/[^\s,/]*-VERIFY-(F\d+)/g)].map((m) => `${m[1]}/${m[2]}`));
21
+ return batches.size === 0 ? "-" : String(batches.size);
22
+ }
23
+
24
+ export function candidatesList(candidates: readonly MemoryEntry[]): string {
25
+ const rows = [...candidates].sort((a, b) => a.id.localeCompare(b.id))
26
+ .map((c) => [c.id, c.type, c.topic, c.source, batchesOf(c.source)]);
27
+ return [CANDIDATES_TITLE, "", CANDIDATES_INTRO, "", ...table(["id", "type", "topic", "source", "batches"], rows)].join("\n") + "\n";
28
+ }
29
+
30
+ export function entriesIndex(entries: readonly MemoryEntry[]): string {
31
+ const rows = [...entries].sort((a, b) => a.id.localeCompare(b.id)).map((e) => [e.id, e.type, e.status, e.title]);
32
+ return [INDEX_TITLE, "", INDEX_INTRO, "", ...table(["id", "type", "status", "title"], rows)].join("\n") + "\n";
33
+ }
34
+
35
+ /** What a decided candidate's file becomes. */
36
+ export function decidedPointer(decision: "admitted" | "refused", date: string, entryFile?: string): string {
37
+ return decision === "admitted"
38
+ ? admittedPointer(date, entryFile)
39
+ : refusedPointer(date);
40
+ }
@@ -0,0 +1,151 @@
1
+ // A shared-memory entry, pure: its fields, its id scheme, and the checks that decide
2
+ // whether it may be stored as data (shape, secrets, provenance markers). Parsing the
3
+ // file lives in front-matter.ts; this module never reads or writes anything.
4
+
5
+ import { secretLikePaths, secretPatternsIn } from "../secret-patterns.ts";
6
+ import { MAX_TOPIC_CHARS, TOPIC_PATTERN } from "./refused.ts";
7
+ import {
8
+ aMistakeNeeds, APPLIES_WHEN_EMPTY, BODY_SECTIONS_IN_ORDER, bodyTooLong, carriesProvenanceMarker, dateNotIso,
9
+ evidenceNamesSecret, forAMistakeOnly, idIsNot, itemNotAToken, looksLikeSecret, projectNotKebab, RATIONALE_EMPTY,
10
+ SOURCE_MUST_START, statusMustBeOneOf, SUPERSEDED_BY_EXACTLY, supersedesOtherProject, titleOneLine, topicNotKebab,
11
+ typeMustBeOneOf,
12
+ } from "./messages.ts";
13
+
14
+ export const ENTRY_TYPES = ["decision", "code-structure", "method", "mistake"] as const;
15
+ export type EntryType = (typeof ENTRY_TYPES)[number];
16
+ export const ENTRY_STATUSES = ["candidate", "admitted", "superseded"] as const;
17
+ export type EntryStatus = (typeof ENTRY_STATUSES)[number];
18
+ export const SOURCE_KINDS = ["verdict", "audit", "human"] as const;
19
+ /** The front-matter keys, in the order serializeEntry writes them (temp/05 § 2). */
20
+ export const ENTRY_KEYS: readonly string[] = [
21
+ "id", "type", "title", "project", "date", "topic", "applies_when", "rationale", "correction", "detection_signal",
22
+ "source", "status", "supersedes", "superseded_by", "tags", "stack",
23
+ ];
24
+ export const ENTRY_SECTIONS = ["Context", "Content", "Evidence"] as const;
25
+ export const MAX_TITLE_CHARS = 90;
26
+ export const MAX_BODY_CHARS = 2_000;
27
+
28
+ export interface MemoryEntry {
29
+ id: string; type: EntryType; title: string; project: string; date: string; topic: string;
30
+ appliesWhen: string; rationale: string; correction?: string; detectionSignal?: string;
31
+ source: string; status: EntryStatus; supersedes: string[]; supersededBy?: string;
32
+ tags: string[]; stack: string[];
33
+ /** The text after the front matter, from "## Context" on. */
34
+ body: string;
35
+ }
36
+
37
+ const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
38
+ const SOURCE = /^(verdict|audit|human):\S/;
39
+ const TOKEN = /^[a-z0-9][a-z0-9.+#-]*$/;
40
+
41
+ /** "<project>-<type>-<yyyymmdd>-": what every id of this project, type and date starts with. */
42
+ export function entryIdPrefix(project: string, type: EntryType, date: string): string {
43
+ return `${project}-${type}-${date.replace(/-/g, "")}-`;
44
+ }
45
+
46
+ function isCalendarDate(text: string): boolean {
47
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
48
+ if (!m) return false;
49
+ const [year, month, day] = [Number(m[1]), Number(m[2]), Number(m[3])];
50
+ const date = new Date(Date.UTC(year, month - 1, day));
51
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
52
+ }
53
+
54
+ const present = (value: string | undefined): boolean => value !== undefined && value.trim() !== "";
55
+
56
+ /** The front-matter values of the entry, by key, in ENTRY_KEYS order (absent optional keys left out). */
57
+ function entryValues(entry: MemoryEntry): Array<[string, string]> {
58
+ const values: Record<string, string | string[] | undefined> = {
59
+ id: entry.id, type: entry.type, title: entry.title, project: entry.project, date: entry.date, topic: entry.topic,
60
+ applies_when: entry.appliesWhen, rationale: entry.rationale, correction: entry.correction,
61
+ detection_signal: entry.detectionSignal, source: entry.source, status: entry.status, supersedes: entry.supersedes,
62
+ superseded_by: entry.supersededBy, tags: entry.tags, stack: entry.stack,
63
+ };
64
+ return ENTRY_KEYS.flatMap((key): Array<[string, string]> => {
65
+ const value = values[key];
66
+ if (value === undefined) return [];
67
+ return [[key, Array.isArray(value) ? value.join("\n") : String(value)]];
68
+ });
69
+ }
70
+
71
+ /** The paths the "## Evidence" section names, as `path` or path:line, each once. */
72
+ function evidencePaths(body: string): string[] {
73
+ const lines = body.split("\n");
74
+ const start = lines.findIndex((line) => /^## Evidence\s*$/.test(line));
75
+ if (start < 0) return [];
76
+ const end = lines.findIndex((line, i) => i > start && /^## /.test(line));
77
+ const section = lines.slice(start + 1, end < 0 ? undefined : end).join("\n");
78
+ const paths: string[] = [];
79
+ for (const m of section.matchAll(/`([^`\s]+)`/g)) paths.push(m[1].replace(/:\d+(?:-\d+)?$/, ""));
80
+ for (const m of section.replace(/`[^`]*`/g, " ").matchAll(/([^\s`'"(),;]+):\d+/g)) paths.push(m[1]);
81
+ return [...new Set(paths.filter((path) => path.length > 0))];
82
+ }
83
+
84
+ function sectionsInOrder(body: string): boolean {
85
+ const lines = body.split("\n");
86
+ let from = 0;
87
+ for (const name of ENTRY_SECTIONS) {
88
+ const at = lines.findIndex((line, i) => i >= from && line.trimEnd() === `## ${name}`);
89
+ if (at < 0) return false;
90
+ from = at + 1;
91
+ }
92
+ return true;
93
+ }
94
+
95
+ /** Every problem, in the order of the design's table; empty when the entry is admissible as data. */
96
+ export function entryProblems(entry: MemoryEntry, markers: readonly RegExp[] = []): string[] {
97
+ const problems: string[] = [];
98
+ const typeOk = (ENTRY_TYPES as readonly string[]).includes(entry.type);
99
+ const prefix = entryIdPrefix(entry.project, entry.type, entry.date);
100
+ if (!KEBAB.test(entry.id) || !entry.id.startsWith(prefix) || !KEBAB.test(entry.id.slice(prefix.length))) {
101
+ problems.push(idIsNot(entry.id, `${entry.project}-${entry.type}-${entry.date.replace(/-/g, "")}`));
102
+ }
103
+ if (!typeOk) problems.push(typeMustBeOneOf(ENTRY_TYPES.join(", ")));
104
+ if (entry.title.length < 1 || entry.title.length > MAX_TITLE_CHARS || /[\r\n]/.test(entry.title)) {
105
+ problems.push(titleOneLine(MAX_TITLE_CHARS));
106
+ }
107
+ if (!KEBAB.test(entry.project)) problems.push(projectNotKebab(entry.project));
108
+ if (!isCalendarDate(entry.date)) problems.push(dateNotIso(entry.date));
109
+ if (!TOPIC_PATTERN.test(entry.topic)) {
110
+ problems.push(topicNotKebab(entry.topic, MAX_TOPIC_CHARS));
111
+ }
112
+ if (!present(entry.appliesWhen)) problems.push(APPLIES_WHEN_EMPTY);
113
+ if (!present(entry.rationale)) problems.push(RATIONALE_EMPTY);
114
+ const mistakeKeys: Array<[string, string | undefined]> = [
115
+ ["correction", entry.correction], ["detection_signal", entry.detectionSignal],
116
+ ];
117
+ for (const [key, value] of mistakeKeys) {
118
+ if (entry.type === "mistake" && !present(value)) problems.push(aMistakeNeeds(key));
119
+ if (entry.type !== "mistake" && present(value)) problems.push(forAMistakeOnly(key));
120
+ }
121
+ if (!SOURCE.test(entry.source)) problems.push(SOURCE_MUST_START);
122
+ if (!(ENTRY_STATUSES as readonly string[]).includes(entry.status)) {
123
+ problems.push(statusMustBeOneOf(ENTRY_STATUSES.join(", ")));
124
+ }
125
+ for (const id of entry.supersedes) {
126
+ if (!id.startsWith(`${entry.project}-`)) problems.push(supersedesOtherProject(id, entry.project));
127
+ }
128
+ if ((entry.status === "superseded") !== present(entry.supersededBy)) {
129
+ problems.push(SUPERSEDED_BY_EXACTLY);
130
+ }
131
+ for (const [key, items] of [["tags", entry.tags], ["stack", entry.stack]] as const) {
132
+ for (const item of items) if (!TOKEN.test(item)) problems.push(itemNotAToken(key, item));
133
+ }
134
+ if (!sectionsInOrder(entry.body)) problems.push(BODY_SECTIONS_IN_ORDER);
135
+ if (entry.body.length > MAX_BODY_CHARS) {
136
+ problems.push(bodyTooLong(entry.body.length, MAX_BODY_CHARS));
137
+ }
138
+ for (const path of secretLikePaths(evidencePaths(entry.body))) problems.push(evidenceNamesSecret(path));
139
+ const texts: Array<[string, string]> = [...entryValues(entry), ["body", entry.body]];
140
+ for (const [key, text] of texts) {
141
+ for (const name of secretPatternsIn(text)) problems.push(looksLikeSecret(key, name));
142
+ }
143
+ for (const [key, text] of texts) {
144
+ for (const marker of markers) {
145
+ if (new RegExp(marker.source, marker.flags.replace(/[gy]/g, "")).test(text)) {
146
+ problems.push(carriesProvenanceMarker(key, marker.source));
147
+ }
148
+ }
149
+ }
150
+ return problems;
151
+ }
@@ -0,0 +1,187 @@
1
+ // The flat front matter of a memory entry, pure: "---", one "key: value" per line (a
2
+ // scalar, a JSON string, or an inline list), "---", then the body as written. No
3
+ // nesting and no comments: a "#" in a value is text. The parser is ours because the
4
+ // runtime loads no package, and it lives in the domain so the use cases test in Node.
5
+
6
+ import { ENTRY_KEYS } from "./entry.ts";
7
+ import type { EntryStatus, EntryType, MemoryEntry } from "./entry.ts";
8
+ import {
9
+ BAD_QUOTED_VALUE, duplicateKey, FRONT_MATTER_NOT_CLOSED, FRONT_MATTER_NOT_OPENED, mustBeAList, mustBeText,
10
+ notKeyValue, valueIsOneLine,
11
+ } from "./messages.ts";
12
+
13
+ export type FlatValue = string | string[];
14
+ export interface FrontMatter { fields: Array<{ key: string; value: FlatValue; line: number }>; body: string }
15
+ export type FrontMatterParse = { ok: true; doc: FrontMatter } | { ok: false; problems: string[] };
16
+
17
+ const FENCE = "---";
18
+ const KEY_LINE = /^([a-z][a-z_]*):(?: (.*))?$/;
19
+
20
+ class ValueError extends Error {}
21
+
22
+ /** One JSON string starting at `from`; returns the decoded text and the index after it. */
23
+ function readQuoted(text: string, from: number): { value: string; next: number } {
24
+ let i = from + 1;
25
+ while (i < text.length && text[i] !== "\"") i += text[i] === "\\" ? 2 : 1;
26
+ if (i >= text.length) throw new ValueError(BAD_QUOTED_VALUE);
27
+ let value: unknown;
28
+ try { value = JSON.parse(text.slice(from, i + 1)); } catch { throw new ValueError(BAD_QUOTED_VALUE); }
29
+ if (typeof value !== "string") throw new ValueError(BAD_QUOTED_VALUE);
30
+ return { value, next: i + 1 };
31
+ }
32
+
33
+ function parseList(inner: string): string[] {
34
+ if (inner.trim() === "") return [];
35
+ const items: string[] = [];
36
+ let i = 0;
37
+ for (;;) {
38
+ while (inner[i] === " ") i++;
39
+ if (inner[i] === "\"") {
40
+ const quoted = readQuoted(inner, i);
41
+ items.push(quoted.value);
42
+ i = quoted.next;
43
+ while (inner[i] === " ") i++;
44
+ if (i < inner.length && inner[i] !== ",") throw new ValueError(BAD_QUOTED_VALUE);
45
+ } else {
46
+ const comma = inner.indexOf(",", i);
47
+ const item = inner.slice(i, comma < 0 ? inner.length : comma).trim();
48
+ if (/[[\]]/.test(item)) throw new ValueError("unclosed list");
49
+ if (item.includes("\"")) throw new ValueError(BAD_QUOTED_VALUE);
50
+ items.push(item);
51
+ i = comma < 0 ? inner.length : comma;
52
+ }
53
+ if (i >= inner.length) return items;
54
+ i++; // the comma
55
+ }
56
+ }
57
+
58
+ function parseValue(raw: string): FlatValue {
59
+ const text = raw.trim();
60
+ if (text.startsWith("[")) {
61
+ if (!text.endsWith("]")) throw new ValueError("unclosed list");
62
+ return parseList(text.slice(1, -1));
63
+ }
64
+ if (text.startsWith("\"")) {
65
+ const quoted = readQuoted(text, 0);
66
+ if (quoted.next !== text.length) throw new ValueError(BAD_QUOTED_VALUE);
67
+ return quoted.value;
68
+ }
69
+ return text;
70
+ }
71
+
72
+ export function parseFrontMatter(text: string): FrontMatterParse {
73
+ const lines = String(text ?? "").split("\n");
74
+ const strip = (line: string): string => line.replace(/\r$/, "");
75
+ if (strip(lines[0]) !== FENCE) return { ok: false, problems: [FRONT_MATTER_NOT_OPENED] };
76
+ const close = lines.findIndex((line, i) => i > 0 && strip(line) === FENCE);
77
+ if (close < 0) return { ok: false, problems: [FRONT_MATTER_NOT_CLOSED] };
78
+ const problems: string[] = [];
79
+ const fields: FrontMatter["fields"] = [];
80
+ const seen = new Set<string>();
81
+ for (let i = 1; i < close; i++) {
82
+ const raw = strip(lines[i]);
83
+ const n = i + 1;
84
+ const m = KEY_LINE.exec(raw);
85
+ if (!m) { problems.push(notKeyValue(n, raw)); continue; }
86
+ const key = m[1];
87
+ if (seen.has(key)) { problems.push(duplicateKey(n, key)); continue; }
88
+ seen.add(key);
89
+ try {
90
+ fields.push({ key, value: parseValue(m[2] ?? ""), line: n });
91
+ } catch (error) {
92
+ if (!(error instanceof ValueError)) throw error;
93
+ problems.push(`line ${n}: ${error.message}`);
94
+ }
95
+ }
96
+ if (problems.length > 0) return { ok: false, problems };
97
+ return { ok: true, doc: { fields, body: lines.slice(close + 1).join("\n") } };
98
+ }
99
+
100
+ function needsQuotes(value: string): boolean {
101
+ return value === "" || value.startsWith("[") || value.startsWith("\"") || value !== value.trim()
102
+ || value.includes(": ") || value.includes(" #");
103
+ }
104
+
105
+ function itemNeedsQuotes(item: string): boolean {
106
+ return item === "" || item !== item.trim() || /[,[\]"]/.test(item) || /[\r\n]/.test(item);
107
+ }
108
+
109
+ function writeValue(key: string, value: FlatValue): string {
110
+ if (Array.isArray(value)) {
111
+ return `[${value.map((item) => (itemNeedsQuotes(item) ? JSON.stringify(item) : item)).join(", ")}]`;
112
+ }
113
+ if (/[\r\n]/.test(value)) throw new Error(valueIsOneLine(key));
114
+ return needsQuotes(value) ? JSON.stringify(value) : value;
115
+ }
116
+
117
+ export function serializeFrontMatter(doc: FrontMatter): string {
118
+ const lines = doc.fields.map((field) => `${field.key}: ${writeValue(field.key, field.value)}`);
119
+ return [FENCE, ...lines, FENCE].join("\n") + "\n" + doc.body;
120
+ }
121
+
122
+ const LIST_KEYS = new Set(["supersedes", "tags", "stack"]);
123
+ const OPTIONAL_KEYS = new Set(["correction", "detection_signal", "superseded_by", "supersedes", "tags", "stack"]);
124
+
125
+ export function entryFromFrontMatter(
126
+ doc: FrontMatter,
127
+ ): { ok: true; entry: MemoryEntry } | { ok: false; problems: string[] } {
128
+ const problems: string[] = [];
129
+ const text: Record<string, string> = {};
130
+ const lists: Record<string, string[]> = {};
131
+ for (const { key, value } of doc.fields) {
132
+ if (!ENTRY_KEYS.includes(key)) { problems.push(`unknown key '${key}'`); continue; }
133
+ if (LIST_KEYS.has(key)) {
134
+ if (Array.isArray(value)) lists[key] = value;
135
+ else problems.push(mustBeAList(key));
136
+ } else if (Array.isArray(value)) {
137
+ problems.push(mustBeText(key));
138
+ } else {
139
+ text[key] = value;
140
+ }
141
+ }
142
+ const given = new Set(doc.fields.map((field) => field.key));
143
+ for (const key of ENTRY_KEYS) {
144
+ if (!OPTIONAL_KEYS.has(key) && !given.has(key)) problems.push(`missing key '${key}'`);
145
+ }
146
+ if (problems.length > 0) return { ok: false, problems };
147
+ const entry: MemoryEntry = {
148
+ id: text.id, type: text.type as EntryType, title: text.title, project: text.project, date: text.date,
149
+ topic: text.topic, appliesWhen: text.applies_when, rationale: text.rationale,
150
+ source: text.source, status: text.status as EntryStatus,
151
+ supersedes: lists.supersedes ?? [], tags: lists.tags ?? [], stack: lists.stack ?? [],
152
+ body: doc.body,
153
+ };
154
+ if (text.correction !== undefined) entry.correction = text.correction;
155
+ if (text.detection_signal !== undefined) entry.detectionSignal = text.detection_signal;
156
+ if (text.superseded_by !== undefined) entry.supersededBy = text.superseded_by;
157
+ return { ok: true, entry };
158
+ }
159
+
160
+ /** A prose value on one line: a wrapped rationale is joined, since a front-matter scalar holds no line break. */
161
+ const joined = (text: string | undefined): string | undefined =>
162
+ text === undefined || !/[\r\n]/.test(text) ? text : text.split(/\r\n|\r|\n/).map((part) => part.trim()).filter(Boolean).join(" ");
163
+
164
+ /** The entry's front matter, keys in ENTRY_KEYS order, optional absent keys omitted; prose values joined on one line. */
165
+ export function entryToFrontMatter(entry: MemoryEntry): FrontMatter {
166
+ const values: Record<string, FlatValue | undefined> = {
167
+ id: entry.id, type: entry.type, title: entry.title, project: entry.project, date: entry.date, topic: entry.topic,
168
+ applies_when: joined(entry.appliesWhen), rationale: joined(entry.rationale), correction: joined(entry.correction),
169
+ detection_signal: joined(entry.detectionSignal), source: entry.source, status: entry.status, supersedes: entry.supersedes,
170
+ superseded_by: entry.supersededBy, tags: entry.tags, stack: entry.stack,
171
+ };
172
+ const fields: FrontMatter["fields"] = [];
173
+ for (const key of ENTRY_KEYS) {
174
+ const value = values[key];
175
+ if (value !== undefined) fields.push({ key, value, line: fields.length + 2 });
176
+ }
177
+ return { fields, body: entry.body };
178
+ }
179
+
180
+ export function parseEntry(text: string): { ok: true; entry: MemoryEntry } | { ok: false; problems: string[] } {
181
+ const parsed = parseFrontMatter(text);
182
+ return parsed.ok ? entryFromFrontMatter(parsed.doc) : parsed;
183
+ }
184
+
185
+ export function serializeEntry(entry: MemoryEntry): string {
186
+ return serializeFrontMatter(entryToFrontMatter(entry));
187
+ }