@tea-agent/loop-agent 0.1.0-fe-test.4 → 0.1.0-fe-test.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (555) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +442 -2524
  3. package/README.md +19 -12
  4. package/dist/adapters/loop-agent.js +34 -0
  5. package/dist/application/dag/args.js +8 -0
  6. package/dist/application/dag/run-dag.js +5 -0
  7. package/dist/application/evaluation/budget.js +40 -1
  8. package/dist/application/evaluation/corpus-hash.js +10 -15
  9. package/dist/application/evaluation/corpus.js +2 -1
  10. package/dist/application/evaluation/frontend-browser-acceptance.js +77 -0
  11. package/dist/application/evaluation/frontend-corpus-browser-acceptance.js +175 -0
  12. package/dist/application/evaluation/frontend-gateway-evidence.js +226 -0
  13. package/dist/application/evaluation/frontend-pair-registration.js +143 -0
  14. package/dist/application/evaluation/frontend-paired-summary.js +150 -0
  15. package/dist/application/evaluation/frontend-run-observation.js +144 -0
  16. package/dist/application/evaluation/frontend-shared-evidence.js +105 -0
  17. package/dist/application/evaluation/types.js +45 -12
  18. package/dist/application/task-lifecycle/advance.js +64 -15
  19. package/dist/application/task-lifecycle/observe.js +69 -30
  20. package/dist/application/task-lifecycle/plan-transitions.js +5 -4
  21. package/dist/build-stamp.json +3 -3
  22. package/dist/cli/command-definitions.js +18 -5
  23. package/dist/cli/program.js +8 -5
  24. package/dist/cli/update/init-surface-notifier.js +2 -0
  25. package/dist/cli/update/policy.js +2 -0
  26. package/dist/commands/client-recovery.js +20 -55
  27. package/dist/commands/cursor-prompt.js +2 -0
  28. package/dist/commands/dag-approve.js +2 -0
  29. package/dist/commands/dag-final-verification.js +2 -0
  30. package/dist/commands/dag-init-hybrid.js +2 -0
  31. package/dist/commands/dag-reconcile-tasks.js +2 -0
  32. package/dist/commands/dag-reject.js +2 -0
  33. package/dist/commands/dag-report.js +2 -0
  34. package/dist/commands/dag-rerun.js +2 -0
  35. package/dist/commands/dag-resume.js +2 -0
  36. package/dist/commands/dag-workflow-compile.js +2 -0
  37. package/dist/commands/dag-workflow-plan.js +2 -0
  38. package/dist/commands/dag-workflow-validate.js +2 -0
  39. package/dist/commands/delegate.js +2 -0
  40. package/dist/commands/examples.js +2 -0
  41. package/dist/commands/import-prd.js +2 -0
  42. package/dist/commands/init-legacy-audit.js +330 -0
  43. package/dist/commands/init-model-catalog.js +2 -0
  44. package/dist/commands/init-upgrade.js +644 -104
  45. package/dist/commands/init.js +700 -338
  46. package/dist/commands/instructions.js +2 -0
  47. package/dist/commands/knowledge.js +2 -0
  48. package/dist/commands/loop-benchmark.js +2 -0
  49. package/dist/commands/operator-guide.js +99 -0
  50. package/dist/commands/operator.js +16 -3
  51. package/dist/commands/pi-prompt.js +2 -0
  52. package/dist/commands/pi-reuse-benchmark.js +2 -0
  53. package/dist/commands/promote-run.js +2 -0
  54. package/dist/commands/stats.js +1 -1
  55. package/dist/commands/study-init.js +2 -0
  56. package/dist/commands/task-advance.js +32 -0
  57. package/dist/commands/task-source-prepare.js +18 -2
  58. package/dist/commands/worktree-create.js +2 -0
  59. package/dist/commands/worktree-remove.js +2 -0
  60. package/dist/executors/dag-pi/guards.js +4 -0
  61. package/dist/executors/dag-pi/model-config.js +30 -0
  62. package/dist/executors/dag-pi/plan/fact-adoption.js +55 -0
  63. package/dist/executors/dag-pi/plan/facts.js +180 -0
  64. package/dist/executors/dag-pi/plan/finalize-tools.js +259 -0
  65. package/dist/executors/dag-pi/plan/ledger-contract.js +55 -0
  66. package/dist/executors/dag-pi/plan/record-tools.js +861 -0
  67. package/dist/executors/dag-pi/plan/schema.js +129 -0
  68. package/dist/executors/dag-pi/plan/tool-helpers.js +16 -0
  69. package/dist/executors/dag-pi/sessions/index.js +6 -0
  70. package/dist/executors/dag-pi/sessions/plan-batches.js +280 -0
  71. package/dist/executors/dag-pi/sessions/plan-prompts.js +367 -0
  72. package/dist/executors/dag-pi/sessions/scout-parallel.js +197 -0
  73. package/dist/executors/dag-pi/sessions/segmented-plan.js +1184 -0
  74. package/dist/executors/dag-pi/sessions/writer-evidence.js +60 -0
  75. package/dist/executors/dag-pi/tools/contract-tools.js +515 -0
  76. package/dist/executors/dag-pi/tools/design-terminal-tools.js +159 -0
  77. package/dist/executors/dag-pi/tools/plan-decision-tools.js +529 -0
  78. package/dist/executors/dag-pi/tools/review-terminal-tools.js +159 -0
  79. package/dist/executors/dag-pi/tools/scout-evidence-tools.js +270 -0
  80. package/dist/executors/dag-pi-executor.js +1517 -3180
  81. package/dist/executors/pi-executor.js +112 -4
  82. package/dist/executors/pi-sdk-executor.js +258 -44
  83. package/dist/executors/pi-writer-tool-policy.js +60 -4
  84. package/dist/executors/playwright-cli-launcher.js +31 -45
  85. package/dist/executors/shell-executor.js +358 -48
  86. package/dist/executors/shell-presets.js +1 -1
  87. package/dist/executors/shell-verification.js +3 -0
  88. package/dist/executors/shell-write-guard.js +77 -102
  89. package/dist/governance/exec-plans.js +16 -4
  90. package/dist/governance/harness.js +2 -7
  91. package/dist/governance/manifest-types.js +28 -9
  92. package/dist/governance/project-capability-scanner.js +263 -0
  93. package/dist/governance/project-config.js +96 -0
  94. package/dist/governance/resource-catalog.js +151 -0
  95. package/dist/infrastructure/console/app-data.js +12 -2
  96. package/dist/infrastructure/console/operation-store.js +48 -14
  97. package/dist/infrastructure/evaluation/corpus-store.js +37 -12
  98. package/dist/shared/artifacts-core.js +2 -0
  99. package/dist/shared/backend-dogfood-preflight.js +47 -0
  100. package/dist/shared/dag-failure-category.js +9 -0
  101. package/dist/shared/file-identity.js +23 -0
  102. package/dist/shared/frontend-execution-policy.js +23 -0
  103. package/dist/shared/git-progress.js +2 -0
  104. package/dist/shared/git-workspace-status.js +482 -0
  105. package/dist/shared/one-shot-prompt-args.js +2 -0
  106. package/dist/shared/operator/capabilities.js +185 -0
  107. package/dist/shared/package-metadata.js +29 -11
  108. package/dist/shared/path-safety.js +2 -2
  109. package/dist/shared/pi-context-pressure/extension.js +49 -16
  110. package/dist/shared/pi-context-pressure/index.js +1 -0
  111. package/dist/shared/pi-context-pressure/sift-bridge.js +1 -1
  112. package/dist/shared/pi-context-pressure/telemetry.js +4 -0
  113. package/dist/shared/pi-context-pressure/tool-result-pruner.js +98 -0
  114. package/dist/shared/pi-provider-recovery.js +182 -0
  115. package/dist/shared/pi-retry-settings.js +40 -0
  116. package/dist/shared/reference-context.js +2 -0
  117. package/dist/shared/update/npm-client.js +49 -1
  118. package/dist/shared/wizard-local-telemetry.js +51 -0
  119. package/dist/task/config-types.js +51 -2
  120. package/dist/task/contract/apply.js +36 -2
  121. package/dist/task/contract/project.js +22 -0
  122. package/dist/task/contract/recover.js +6 -0
  123. package/dist/task/contract/schema.js +12 -0
  124. package/dist/task/frontend-preflight.js +1 -1
  125. package/dist/task/source-prepare/artifact-meta.js +9 -2
  126. package/dist/task/source-prepare/build-draft.js +61 -0
  127. package/dist/task/source-prepare/fragment-inventory.js +4 -1
  128. package/dist/task/source-prepare/ledger-reconciliation.js +2 -2
  129. package/dist/task/source-prepare/ledger-review.js +6 -9
  130. package/dist/task/source-prepare/parse-intent.js +165 -14
  131. package/dist/task/source-prepare/path-policy.js +17 -7
  132. package/dist/task/source-prepare/prepare.js +6 -1
  133. package/dist/task/source-prepare/semantic-intake.js +33 -28
  134. package/dist/task/source-prepare/source-execution.js +65 -0
  135. package/dist/task/source-prepare/source-fidelity-pi.js +49 -17
  136. package/dist/task/source-prepare/source-provider-budget.js +290 -0
  137. package/dist/task/source-references.js +48 -23
  138. package/dist/task/task-demand-routing.js +5 -2
  139. package/dist/worker/cli.js +3 -5
  140. package/dist/worker/console/chat/assistant-content.js +5 -13
  141. package/dist/worker/console/chat/browser-automation.js +937 -0
  142. package/dist/worker/console/chat/browser-content.js +74 -0
  143. package/dist/worker/console/chat/browser-diagnostics.js +250 -0
  144. package/dist/worker/console/chat/browser-evaluation.js +58 -0
  145. package/dist/worker/console/chat/browser-operation-queue.js +19 -0
  146. package/dist/worker/console/chat/browser-pick.js +113 -0
  147. package/dist/worker/console/chat/browser-policy.js +113 -0
  148. package/dist/worker/console/chat/browser-routes.js +329 -0
  149. package/dist/worker/console/chat/browser-screenshot-result.js +47 -0
  150. package/dist/worker/console/chat/browser-storage.js +89 -0
  151. package/dist/worker/console/chat/chat-event-store.js +73 -18
  152. package/dist/worker/console/chat/context-insights.js +788 -0
  153. package/dist/worker/console/chat/conversation-nodes.js +383 -0
  154. package/dist/worker/console/chat/db-connections.js +854 -0
  155. package/dist/worker/console/chat/explore-tools.js +18 -2
  156. package/dist/worker/console/chat/pet/pet-affinity.js +169 -0
  157. package/dist/worker/console/chat/pet/pet-persist.js +109 -0
  158. package/dist/worker/console/chat/pet/pet-registry.js +142 -0
  159. package/dist/worker/console/chat/pet/pet-remarks.js +48 -0
  160. package/dist/worker/console/chat/pet/pet-routes.js +125 -0
  161. package/dist/worker/console/chat/pet/pet-service.js +262 -0
  162. package/dist/worker/console/chat/pet/pet-state.js +99 -0
  163. package/dist/worker/console/chat/pi-mode-loop-isolation.js +170 -0
  164. package/dist/worker/console/chat/pi-runtime/custom-tools/ask-user-question.js +44 -0
  165. package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +135 -0
  166. package/dist/worker/console/chat/pi-runtime/custom-tools/explore-tools.js +202 -0
  167. package/dist/worker/console/chat/pi-runtime/custom-tools/goal-tools.js +79 -0
  168. package/dist/worker/console/chat/pi-runtime/custom-tools/operator-tools.js +94 -0
  169. package/dist/worker/console/chat/pi-runtime/custom-tools/scheduled-goal-tools.js +22 -0
  170. package/dist/worker/console/chat/pi-runtime/custom-tools/sql-tools.js +670 -0
  171. package/dist/worker/console/chat/pi-runtime/custom-tools/todo-write.js +38 -0
  172. package/dist/worker/console/chat/pi-runtime/inspection-types.js +28 -0
  173. package/dist/worker/console/chat/pi-runtime/inspection.js +439 -0
  174. package/dist/worker/console/chat/pi-runtime/progressive-tools.js +195 -0
  175. package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +153 -0
  176. package/dist/worker/console/chat/pi-runtime/sdk-session.js +5 -0
  177. package/dist/worker/console/chat/pi-runtime.js +793 -1230
  178. package/dist/worker/console/chat/provider-error.js +0 -12
  179. package/dist/worker/console/chat/repo-browser.js +132 -6
  180. package/dist/worker/console/chat/repo-preview-kind.js +155 -0
  181. package/dist/worker/console/chat/resource-loader.js +4 -1
  182. package/dist/worker/console/chat/routes.js +861 -148
  183. package/dist/worker/console/chat/scheduled-goal-booking.js +59 -0
  184. package/dist/worker/console/chat/scheduled-goal-delivery.js +27 -0
  185. package/dist/worker/console/chat/scheduled-goal-request.js +198 -0
  186. package/dist/worker/console/chat/scm-routes.js +217 -0
  187. package/dist/worker/console/chat/scm-service.js +283 -0
  188. package/dist/worker/console/chat/scm-tools.js +111 -0
  189. package/dist/worker/console/chat/sdd-data-alignment.js +85 -41
  190. package/dist/worker/console/chat/session-catalog.js +32 -0
  191. package/dist/worker/console/chat/session-mode-view.js +49 -0
  192. package/dist/worker/console/chat/session-mode.js +224 -0
  193. package/dist/worker/console/chat/session-store.js +232 -32
  194. package/dist/worker/console/chat/shortcuts.js +13 -0
  195. package/dist/worker/console/chat/subagents/agent-tool.js +62 -0
  196. package/dist/worker/console/chat/subagents/explore-agent.js +169 -0
  197. package/dist/worker/console/chat/subagents/index.js +5 -0
  198. package/dist/worker/console/chat/subagents/orchestrator.js +273 -0
  199. package/dist/worker/console/chat/subagents/tool-policy.js +53 -0
  200. package/dist/worker/console/chat/subagents/types.js +13 -0
  201. package/dist/worker/console/chat/terminal-routes.js +216 -0
  202. package/dist/worker/console/chat/terminal-sessions.js +348 -0
  203. package/dist/worker/console/chat/terminal-tools.js +211 -0
  204. package/dist/worker/console/chat/timeline-message-order.js +22 -0
  205. package/dist/worker/console/chat/tool-preview.js +136 -0
  206. package/dist/worker/console/chat/tools.js +69 -1
  207. package/dist/worker/console/chat/turn-order.js +13 -0
  208. package/dist/worker/console/chat/turn-process.js +210 -36
  209. package/dist/worker/console/chat/user-turn-outline.js +19 -0
  210. package/dist/worker/console/console-shutdown.js +34 -0
  211. package/dist/worker/console/console-update-and-init.js +1 -19
  212. package/dist/worker/console/console-update-runtime.js +7 -22
  213. package/dist/worker/console/dag-confirmation.js +3 -0
  214. package/dist/worker/console/dag-execution-receipt.js +3 -0
  215. package/dist/worker/console/interview/tools.js +1 -0
  216. package/dist/worker/console/operator-actions.js +95 -4
  217. package/dist/worker/console/operator-user-error.js +28 -1
  218. package/dist/worker/console/pi-readiness.js +4 -4
  219. package/dist/worker/console/prd-intake-bridge.js +47 -1
  220. package/dist/worker/console/recovery-cta.js +14 -14
  221. package/dist/worker/console/routes.js +13 -0
  222. package/dist/worker/console/scheduled-goal-host.js +98 -0
  223. package/dist/worker/console/scheduled-goal-operation-adapter.js +127 -0
  224. package/dist/worker/console/server.js +33 -31
  225. package/dist/worker/console/static/app-icon.svg +39 -0
  226. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BZogYNl1.js → abnfDiagram-N423BO3Z-DASc69AM.js} +1 -1
  227. package/dist/worker/console/static/assets/{arc-DcJTLe2v.js → arc-h09p-LAc.js} +1 -1
  228. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B39EQQ9n.js → architectureDiagram-T3A2C74G-CZ3dtLkh.js} +1 -1
  229. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-CitCGV56.js → blockDiagram-VBNYF7ZC-DMrRhMXG.js} +1 -1
  230. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-rvWuOHLG.js → c4Diagram-5PPSVZJV-DQxisHV6.js} +1 -1
  231. package/dist/worker/console/static/assets/channel-D1zgKZfg.js +1 -0
  232. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DGXplIJs.js → chunk-2GRJ4B5K-CefVN9zh.js} +1 -1
  233. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-ur9OqjPn.js → chunk-2Q5K7J3B-DmR1Koq2.js} +1 -1
  234. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-D1KqU_Vi.js → chunk-5RXB4S5H-NlzrSW7L.js} +1 -1
  235. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BlVZrbtM.js → chunk-5VM5RSS4-DfelJv-0.js} +1 -1
  236. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-BAzz3nQy.js → chunk-6Q2QTUOP-BK6RFy58.js} +1 -1
  237. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-CP_nYuCV.js → chunk-GF5L2VYU-BAeh9lz4.js} +1 -1
  238. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CWvKQ80X.js → chunk-JWPE2WC7-ChPS5WzG.js} +1 -1
  239. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CyUki8wp.js → chunk-KBJHAD2P-BoVe5IM6.js} +1 -1
  240. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-5NYzNKfY.js → chunk-RYQCIY6F-C4q_0Lw9.js} +1 -1
  241. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DHdUgjS-.js → chunk-XXDRQBXY-Bb9TvjeY.js} +1 -1
  242. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CXNNsY2M.js +1 -0
  243. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CXNNsY2M.js +1 -0
  244. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-ANQ5g_t6.js → cose-bilkent-JH36ORCC-DmNnL8Ff.js} +1 -1
  245. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-CruT_4-0.js → cynefin-VYW2F7L2-Contvx58.js} +1 -1
  246. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-rbFo77ID.js → cynefinDiagram-MW4NZA55-Cigq7cjk.js} +1 -1
  247. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-asstxBQs.js → dagre-VZM6K2ZE-dEbC0nxb.js} +1 -1
  248. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DzTyBZwI.js → diagram-7IWD3JNH-CzIztESV.js} +1 -1
  249. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-gw8ccH3B.js → diagram-B4RE2ZJO-Bo14zbaY.js} +1 -1
  250. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B8RpZzOf.js → diagram-LBJQPF4R-C4xUyil6.js} +1 -1
  251. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-B1zJkCS9.js → diagram-Q27KOJAE-CaBY_uYa.js} +1 -1
  252. package/dist/worker/console/static/assets/{diagram-UB23O5K3-B6JLWZmO.js → diagram-UB23O5K3-ClUXUeiu.js} +1 -1
  253. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-q2iZP-Ps.js → ebnfDiagram-BXEA7PRR-BbGCgjC6.js} +1 -1
  254. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-B3dbbktQ.js → erDiagram-JOGREHBK-Dr-AcwSl.js} +1 -1
  255. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-C-zc6-kB.js → flowDiagram-UKHOOZJN-BG8Gcfyc.js} +1 -1
  256. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-BSolnot9.js → ganttDiagram-PKOTCBZU-CFVaPs5r.js} +1 -1
  257. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js → gitGraphDiagram-DS77QQ5N-ChJ8pm-O.js} +1 -1
  258. package/dist/worker/console/static/assets/index-B_5GhVIO.js +488 -0
  259. package/dist/worker/console/static/assets/index-C7YMBluX.css +1 -0
  260. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DQaZqJOH.js → infoDiagram-6WML65LV-C5J9-uCZ.js} +1 -1
  261. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-DsdX1WnE.js → ishikawaDiagram-WSZJBQD7-BcfjqzDv.js} +1 -1
  262. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CP5EYDZL.js → journeyDiagram-NVQOT4AX-BzzCO-rD.js} +1 -1
  263. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DAm14Dr8.js → kanban-definition-27J2QSJJ-NCHUZ46h.js} +1 -1
  264. package/dist/worker/console/static/assets/{linear-gZECoLc5.js → linear-BKZlWCUU.js} +1 -1
  265. package/dist/worker/console/static/assets/{mermaid.core-BRJNIM6p.js → mermaid.core-DbTaQjFE.js} +5 -5
  266. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-Cja3kLkR.js → mindmap-definition-FAOFIHXS-CroYl5xQ.js} +1 -1
  267. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-22ZGFisL.js → pegDiagram-VL7TDLO6-DgMBx-9k.js} +1 -1
  268. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BXin0Y1o.js → pieDiagram-7S7Q4E2Y-CyWDmbq1.js} +1 -1
  269. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js → quadrantDiagram-CIZ2JOQS-BgGEOqSP.js} +1 -1
  270. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-C1-gTieN.js → railroadDiagram-AXF67PYL-BMZ7oeeV.js} +1 -1
  271. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP--H5N2iI1.js → requirementDiagram-LRYGKXZP-DxqyGhcc.js} +1 -1
  272. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-CgWAPeRz.js → sankeyDiagram-W5VNT64P-DnSvNCG8.js} +1 -1
  273. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-CrKqzGvt.js → sequenceDiagram-SI44F4Z6-BiZh6f-R.js} +1 -1
  274. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BB3wG06K.js → sizeCapture-X5ZJPWSS-BKXSI8WB.js} +1 -1
  275. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-DjsGgdgY.js → stateDiagram-OKZ733FA-CfSgoYFm.js} +1 -1
  276. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DgHi3vjb.js +1 -0
  277. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DYKEbvAR.js → swimlanes-SLNWSIFB-CyGADcHe.js} +2 -2
  278. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Bgvdt1Y0.js +8 -0
  279. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-eQOb5k9Y.js → timeline-definition-Z64GVDOM-HmPaSPOK.js} +1 -1
  280. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B2-l9FIu.js → vennDiagram-T6HMQDX7-VA2VBbez.js} +1 -1
  281. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BX2Cda3l.js → wardleyDiagram-T6FBY63Y-BxjiBPZa.js} +1 -1
  282. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-D9S892ph.js → xychartDiagram-ELKLHX3M--hUY-qFj.js} +1 -1
  283. package/dist/worker/console/static/index.html +5 -2
  284. package/dist/worker/console/static/manifest.webmanifest +19 -0
  285. package/dist/worker/console/static/pets/ember/pet.json +167 -0
  286. package/dist/worker/console/static/pets/ember/spritesheet.png +0 -0
  287. package/dist/worker/console/static-src/app/console-types.js +9 -1
  288. package/dist/worker/console/static-src/chat-view-types.js +1 -1
  289. package/dist/worker/console/static-src/operator-chat/active-turn-tail.js +10 -0
  290. package/dist/worker/console/static-src/operator-chat/animation-frame-batcher.js +38 -0
  291. package/dist/worker/console/static-src/operator-chat/chat-link.js +114 -0
  292. package/dist/worker/console/static-src/operator-chat/chat-scroll-position.js +24 -0
  293. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +360 -14
  294. package/dist/worker/console/static-src/operator-chat/chat-stream-continuity.js +101 -0
  295. package/dist/worker/console/static-src/operator-chat/compaction-message.js +10 -2
  296. package/dist/worker/console/static-src/operator-chat/composer-session-ledger.js +192 -0
  297. package/dist/worker/console/static-src/operator-chat/context-insights-store.js +64 -0
  298. package/dist/worker/console/static-src/operator-chat/details-rail-surfaces.js +99 -0
  299. package/dist/worker/console/static-src/operator-chat/file-palette-nav.js +81 -0
  300. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +57 -9
  301. package/dist/worker/console/static-src/operator-chat/pending-user-message.js +66 -0
  302. package/dist/worker/console/static-src/operator-chat/process-label.js +63 -0
  303. package/dist/worker/console/static-src/operator-chat/slash-palette-nav.js +15 -5
  304. package/dist/worker/console/static-src/operator-chat/timeline-merge.js +29 -0
  305. package/dist/worker/console/static-src/operator-chat/tools-catalog.js +36 -8
  306. package/dist/worker/console/static-src/operator-chat/transcript-mode.js +21 -0
  307. package/dist/worker/console/static-src/operator-chat/turn-group-equality.js +16 -0
  308. package/dist/worker/console/static-src/operator-chat/turn-process-disclosure.js +18 -0
  309. package/dist/worker/console/static-src/operator-chat/turn-state-projection.js +166 -0
  310. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +58 -2
  311. package/dist/worker/console/static-src/operator-chat/use-searchable-hidden.js +51 -0
  312. package/dist/worker/console/static-src/operator-chat/use-stat-dialog.js +95 -0
  313. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +338 -93
  314. package/dist/worker/console/static-src/operator-chat/useChatStream.js +310 -106
  315. package/dist/worker/console/static-src/operator-chat/useChatThread.js +179 -75
  316. package/dist/worker/console/static-src/operator-chat/useComposer.js +281 -79
  317. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +21 -3
  318. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +36 -17
  319. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +18 -0
  320. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  321. package/dist/worker/console/static-src/operator-chat/user-turn-anchor-equality.js +21 -0
  322. package/dist/worker/console/static-src/prd-file-import.js +3 -1
  323. package/dist/worker/console/static-src/shell/console-update-reload.js +1 -1
  324. package/dist/worker/console/workspace-context.js +54 -1
  325. package/dist/worker/console/workspace-initialization.js +218 -0
  326. package/dist/worker/delivery/git-transaction.js +2 -0
  327. package/dist/worker/delivery/package.js +4 -1
  328. package/dist/worker/feature/fullstack-validate.js +2 -0
  329. package/dist/worker/loop-agent/loop-agent-client.js +8 -2
  330. package/dist/worker/materialize/harness-task-lineage.js +4 -2
  331. package/dist/worker/materialize/harness-task-materializer.js +4 -1
  332. package/dist/worker/metrics/projector.js +1 -1
  333. package/dist/worker/observability/event-store.js +4 -1
  334. package/dist/worker/observability/read-model.js +27 -3
  335. package/dist/worker/observe/node-context-insights.js +479 -0
  336. package/dist/worker/observe/node-transparency.js +103 -72
  337. package/dist/worker/observe/routes.js +24 -1
  338. package/dist/worker/observe/static/console-theme.css +178 -0
  339. package/dist/worker/observe/static/console-theme.js +74 -0
  340. package/dist/worker/observe/static/dag-inspector-humanize.js +3 -0
  341. package/dist/worker/observe/static/dom.js +20 -1
  342. package/dist/worker/observe/static/format-pool.d.ts +2 -0
  343. package/dist/worker/observe/static/format-pool.js +6 -0
  344. package/dist/worker/observe/static/format.js +7 -0
  345. package/dist/worker/observe/static/inspect-workspace.js +34 -7
  346. package/dist/worker/observe/static/inspector-submission.js +32 -0
  347. package/dist/worker/observe/static/kpi.js +1 -0
  348. package/dist/worker/observe/static/operator-chrome.css +85 -0
  349. package/dist/worker/observe/static/operator-chrome.js +13 -1
  350. package/dist/worker/observe/static/relations.js +2 -0
  351. package/dist/worker/observe/static/router.js +13 -0
  352. package/dist/worker/observe/static/run-processing.js +2 -0
  353. package/dist/worker/observe/static/shell-chrome.js +36 -3
  354. package/dist/worker/observe/static/state.js +35 -2
  355. package/dist/worker/observe/static/styles.css +263 -39
  356. package/dist/worker/observe/static/task-failure-labels.d.ts +4 -0
  357. package/dist/worker/observe/static/task-failure-labels.js +67 -0
  358. package/dist/worker/observe/static/task-history.js +12 -0
  359. package/dist/worker/observe/static/views/batch.js +6 -13
  360. package/dist/worker/observe/static/views/dag-graph.js +50 -3
  361. package/dist/worker/observe/static/views/dag-inspector.js +742 -268
  362. package/dist/worker/observe/static/views/dag-trajectory.js +3 -0
  363. package/dist/worker/observe/static/views/dag.d.ts +6 -0
  364. package/dist/worker/observe/static/views/dag.js +49 -11
  365. package/dist/worker/observe/static/views/dags.js +2 -0
  366. package/dist/worker/observe/static/views/dashboard.js +21 -12
  367. package/dist/worker/observe/static/views/failures.js +21 -11
  368. package/dist/worker/observe/static/views/feature.js +11 -29
  369. package/dist/worker/observe/static/views/pool.js +37 -28
  370. package/dist/worker/observe/static/views/run.js +48 -5
  371. package/dist/worker/observe/static/views/session-timeline.js +189 -240
  372. package/dist/worker/observe/static/views/task.js +81 -62
  373. package/dist/worker/outcomes/declared-artifacts.js +2 -0
  374. package/dist/worker/preflight.js +3 -0
  375. package/dist/worker/scheduler/scheduled-goal-dispatch.js +118 -0
  376. package/dist/worker/scheduler/scheduled-goal-evidence.js +230 -0
  377. package/dist/worker/scheduler/scheduled-goal-recovery.js +62 -0
  378. package/dist/worker/scheduler/scheduled-goal-store.js +709 -0
  379. package/dist/worker/scheduler/scheduled-goal-supervisor.js +132 -0
  380. package/dist/worker/scheduler/scheduled-goal-time.js +102 -0
  381. package/dist/worker/scheduler/scheduled-goal-types.js +95 -0
  382. package/dist/worker/task-spec/validate.js +4 -1
  383. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +3 -1
  384. package/dist/workflows/dag/backend-test-layout.js +27 -7
  385. package/dist/workflows/dag/backend-test-markdown-workflow.js +9 -25
  386. package/dist/workflows/dag/backend-test-plan-protocol.js +82 -5
  387. package/dist/workflows/dag/backend-test-pytest-collection.js +4 -1
  388. package/dist/workflows/dag/budget-enforcement.js +82 -3
  389. package/dist/workflows/dag/checkpoint.js +686 -0
  390. package/dist/workflows/dag/dag-retry-schema.js +14 -0
  391. package/dist/workflows/dag/decision-envelope.js +2 -0
  392. package/dist/workflows/dag/dynamic-runtime/map.js +15 -2
  393. package/dist/workflows/dag/dynamic-runtime/shared.js +2 -2
  394. package/dist/workflows/dag/final-verification.js +45 -10
  395. package/dist/workflows/dag/frontend-capacity.js +9 -0
  396. package/dist/workflows/dag/frontend-closeout.js +5 -1
  397. package/dist/workflows/dag/frontend-committed-facts.js +461 -0
  398. package/dist/workflows/dag/frontend-contract-facts.js +133 -0
  399. package/dist/workflows/dag/frontend-design-policy.js +107 -21
  400. package/dist/workflows/dag/frontend-durable-tools.js +225 -0
  401. package/dist/workflows/dag/frontend-execution-groups.js +24 -0
  402. package/dist/workflows/dag/frontend-implementation-contract.js +554 -26
  403. package/dist/workflows/dag/frontend-input-projection.js +76 -0
  404. package/dist/workflows/dag/frontend-plan-canary.js +103 -0
  405. package/dist/workflows/dag/frontend-plan-decision-contract.js +795 -0
  406. package/dist/workflows/dag/frontend-plan-progress.js +92 -0
  407. package/dist/workflows/dag/frontend-plan-recovery-policy.js +18 -0
  408. package/dist/workflows/dag/frontend-plan-render.js +21 -5
  409. package/dist/workflows/dag/frontend-provider-capability-matrix.js +8 -61
  410. package/dist/workflows/dag/frontend-recovery-controller.js +7 -7
  411. package/dist/workflows/dag/frontend-recovery-lineage.js +13 -0
  412. package/dist/workflows/dag/frontend-recovery-plan.js +10 -5
  413. package/dist/workflows/dag/frontend-recovery-run.js +148 -47
  414. package/dist/workflows/dag/frontend-repair-assertions.js +36 -0
  415. package/dist/workflows/dag/frontend-repair.js +79 -76
  416. package/dist/workflows/dag/frontend-review-context.js +71 -69
  417. package/dist/workflows/dag/frontend-review-scopes.js +237 -0
  418. package/dist/workflows/dag/frontend-risk.js +101 -12
  419. package/dist/workflows/dag/frontend-root-observation.js +261 -0
  420. package/dist/workflows/dag/frontend-session-budget.js +376 -0
  421. package/dist/workflows/dag/frontend-session-context.js +10 -0
  422. package/dist/workflows/dag/frontend-shape-facts.js +12 -2
  423. package/dist/workflows/dag/frontend-shape.js +27 -32
  424. package/dist/workflows/dag/frontend-test-case-checklist.js +14 -3
  425. package/dist/workflows/dag/frontend-test-case-generation-assessment.js +88 -0
  426. package/dist/workflows/dag/frontend-test-case-manifest.js +6 -1
  427. package/dist/workflows/dag/frontend-test-case-quality.js +3 -3
  428. package/dist/workflows/dag/frontend-test-environment-probe.js +0 -2
  429. package/dist/workflows/dag/frontend-test-execution-evidence.js +328 -0
  430. package/dist/workflows/dag/frontend-test-framework-adapters.js +309 -0
  431. package/dist/workflows/dag/frontend-test-layout.js +41 -12
  432. package/dist/workflows/dag/frontend-test-result-contract.js +15 -1
  433. package/dist/workflows/dag/frontend-typed-event-store.js +57 -26
  434. package/dist/workflows/dag/frontend-verification-trace.js +65 -48
  435. package/dist/workflows/dag/frontend-writer-admission.js +6 -48
  436. package/dist/workflows/dag/frontend-writer-status.js +0 -23
  437. package/dist/workflows/dag/hybrid/sources.js +1831 -0
  438. package/dist/workflows/dag/hybrid/templates/backend-test.js +1822 -0
  439. package/dist/workflows/dag/hybrid/templates/frontend-test.js +807 -0
  440. package/dist/workflows/dag/hybrid/templates/frontend.js +1529 -0
  441. package/dist/workflows/dag/hybrid/templates/index.js +8 -0
  442. package/dist/workflows/dag/hybrid/templates/kg-bootstrap.js +449 -0
  443. package/dist/workflows/dag/hybrid/templates/knowledge-sync.js +495 -0
  444. package/dist/workflows/dag/hybrid/templates/shared.js +101 -0
  445. package/dist/workflows/dag/hybrid/templates/standard.js +265 -0
  446. package/dist/workflows/dag/hybrid/types.js +32 -0
  447. package/dist/workflows/dag/init-hybrid.js +57 -7077
  448. package/dist/workflows/dag/interrupt-request.js +2 -0
  449. package/dist/workflows/dag/lifecycle.js +11 -2
  450. package/dist/workflows/dag/node-execution.js +257 -247
  451. package/dist/workflows/dag/output-protocol.js +1 -0
  452. package/dist/workflows/dag/prompt.js +4 -0
  453. package/dist/workflows/dag/reconcile-run.js +2 -0
  454. package/dist/workflows/dag/repair-artifact.js +3 -1
  455. package/dist/workflows/dag/report.js +2 -0
  456. package/dist/workflows/dag/rerun-feedback.js +36 -4
  457. package/dist/workflows/dag/rerun-plan.js +106 -4
  458. package/dist/workflows/dag/rerun-run.js +7 -0
  459. package/dist/workflows/dag/rerun-task.js +75 -1
  460. package/dist/workflows/dag/retry-policy.js +34 -10
  461. package/dist/workflows/dag/runner-exit-diagnostics.js +125 -0
  462. package/dist/workflows/dag/runner.js +38 -1074
  463. package/dist/workflows/dag/scheduler.js +2 -4
  464. package/dist/workflows/dag/skill-instructions.js +102 -32
  465. package/dist/workflows/dag/skill-snapshot.js +3 -0
  466. package/dist/workflows/dag/skills.js +7 -7
  467. package/dist/workflows/dag/structured-output-repair.js +4 -1
  468. package/dist/workflows/dag/terminal-status.js +502 -0
  469. package/dist/workflows/dag/test-artifact-namespace.js +73 -0
  470. package/dist/workflows/dag/types.js +79 -7
  471. package/dist/workflows/dag/validate.js +38 -13
  472. package/dist/workflows/dag/workspace-checkpoint.js +79 -1
  473. package/dist/workflows/loop/benchmark.js +11 -8
  474. package/docs/README.md +2 -1
  475. package/docs/architecture/dag-execution.md +4 -4
  476. package/docs/architecture/runtime-boundaries.md +29 -23
  477. package/docs/governance/README.md +1 -0
  478. package/docs/governance/harness-methodology-verification.md +11 -0
  479. package/docs/init-surface.manifest.json +44 -295
  480. package/docs/operations/README.md +4 -0
  481. package/docs/templates/README.md +5 -5
  482. package/docs/templates/agent-dag.base.json +9 -9
  483. package/docs/templates/agent-dag.final-verification.json +6 -6
  484. package/docs/templates/agent-dag.schema.json +2 -2
  485. package/docs/templates/agent-dag.supervised-implementation.json +12 -12
  486. package/docs/templates/backend-test-dag.generate-pytest.prompt.md +3 -3
  487. package/docs/templates/backend-test-dag.json +708 -703
  488. package/docs/templates/backend-test-dag.review-cases.prompt.md +3 -3
  489. package/docs/templates/frontend-design-contract.md +4 -4
  490. package/docs/templates/frontend-implementation-contract.schema.json +99 -22
  491. package/docs/templates/frontend-implementation-dag.json +7 -7
  492. package/docs/templates/frontend-test-case-checklist.md +2 -2
  493. package/docs/templates/frontend-test-case.example.md +2 -0
  494. package/docs/templates/frontend-test-dag.generate-cases.prompt.md +1 -1
  495. package/docs/templates/frontend-test-dag.json +48 -39
  496. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +2 -2
  497. package/docs/templates/frontend-test-dag.retrospect.prompt.md +1 -1
  498. package/docs/templates/frontend-test-dag.review-cases.prompt.md +1 -1
  499. package/docs/templates/hybrid-dag.json +9 -9
  500. package/docs/templates/knowledge-sync-dag.json +8 -8
  501. package/harness.json +1 -1
  502. package/package.json +27 -8
  503. package/resource-catalog.v1.json +1981 -0
  504. package/resources/agent-bridge/loop-agent/SKILL.md +40 -0
  505. package/resources/init-history/legacy-surface.v1.json +33 -0
  506. package/skills/fe-test-ui-scout/SKILL.md +4 -4
  507. package/skills/fe-test-ui-scout/references/ledger-schema.md +1 -1
  508. package/skills/frontend-bounded-implement/references/code-standards.md +3 -3
  509. package/skills/frontend-contract/SKILL.md +2 -1
  510. package/skills/frontend-contract/references/contract-protocol.md +22 -4
  511. package/skills/frontend-design-review/SKILL.md +16 -18
  512. package/skills/frontend-design-review/references/review-checklist.md +3 -4
  513. package/skills/frontend-plan/SKILL.md +25 -3
  514. package/skills/frontend-plan/references/decision-contract.md +117 -8
  515. package/skills/frontend-plan/references/design-decisions.md +32 -0
  516. package/skills/frontend-review/SKILL.md +29 -36
  517. package/skills/frontend-review/references/review-findings.md +8 -3
  518. package/skills/frontend-scout/references/scout-evidence.md +4 -0
  519. package/skills/init-update/SKILL.md +34 -0
  520. package/skills/init-update/agents/openai.yaml +6 -0
  521. package/skills/loop-agent/references/command-reference.md +8 -0
  522. package/skills/loop-agent/references/hybrid-dag.md +1 -1
  523. package/skills/playwright-cli/SKILL.md +1 -1
  524. package/skills/playwright-cli-case-generator/SKILL.md +7 -5
  525. package/dist/commands/new-task.js +0 -5
  526. package/dist/commands/status.js +0 -57
  527. package/dist/commands/task-contract.js +0 -269
  528. package/dist/shared/prompts.js +0 -26
  529. package/dist/task/config.js +0 -2
  530. package/dist/task/contract/validate-draft.js +0 -106
  531. package/dist/task/goal.js +0 -3
  532. package/dist/task/index.js +0 -12
  533. package/dist/task/lifecycle.js +0 -1
  534. package/dist/task/operator/capabilities.js +0 -6
  535. package/dist/task/operator/envelope.js +0 -2
  536. package/dist/task/operator/index.js +0 -5
  537. package/dist/task/operator/registry.js +0 -2
  538. package/dist/task/paths.js +0 -1
  539. package/dist/task/source-state.js +0 -1
  540. package/dist/task/subagent-guidance.js +0 -1
  541. package/dist/worker/console/chat/sift-bridge.js +0 -1
  542. package/dist/worker/console/index.js +0 -20
  543. package/dist/worker/console/static/assets/channel-CXqdP5pW.js +0 -1
  544. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +0 -1
  545. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +0 -1
  546. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +0 -1
  547. package/dist/worker/console/static/assets/index-DhfjOafu.js +0 -449
  548. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +0 -1
  549. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +0 -8
  550. package/dist/worker/scheduler/index.js +0 -25
  551. package/dist/workflows/dag/facts.js +0 -4
  552. package/dist/workflows/dag/frontend-shadow-dual-write.js +0 -941
  553. package/dist/workflows/dag/index.js +0 -6
  554. package/dist/workflows/dynamic/index.js +0 -7
  555. /package/dist/{task/operator/types.js → executors/dag-pi/plan/session.js} +0 -0
@@ -1,13 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
- import { access, copyFile, mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
3
- import os from "node:os";
2
+ import { access, copyFile, lstat, mkdir, readdir, readFile, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
4
3
  import path from "node:path";
5
4
  import { isDeepStrictEqual } from "node:util";
6
5
  import { fileURLToPath } from "node:url";
7
6
  import { isInitRuntimeActive, } from "../shared/runtime-activity.js";
8
7
  import { loadHarnessManifest } from "../governance/harness.js";
9
- import { OPENCODE_CONTEXT_OVERFLOW_COMPACT_PLUGIN_PATH, OPENCODE_TRANSIENT_RETRY_PLUGIN_PATH, PI_CONTEXT_OVERFLOW_EXTENSION_PATH, PI_PROJECT_SETTINGS_PATH, applyPiRetryMerge, applyProjectPiSettingsMerge, buildOpenCodeContextOverflowCompactPluginSource, buildProjectPiSettingsSource, buildOpenCodeTransientRetryPluginSource, buildPiContextOverflowExtensionSource, inspectProjectPiSettings, parseClientRecoveryMode, runClientRecovery, } from "./client-recovery.js";
8
+ import { OPENCODE_CONTEXT_OVERFLOW_COMPACT_PLUGIN_PATH, OPENCODE_TRANSIENT_RETRY_PLUGIN_PATH, PI_CONTEXT_OVERFLOW_EXTENSION_PATH, PI_PROJECT_SETTINGS_PATH, applyProjectPiSettingsMerge, buildOpenCodeContextOverflowCompactPluginSource, buildProjectPiSettingsSource, buildOpenCodeTransientRetryPluginSource, buildPiContextOverflowExtensionSource, inspectProjectPiSettings, } from "./client-recovery.js";
10
9
  import { assessInitPiModelReadiness, discoverInitModelCatalog, validateInitModelMatrixAgainstCatalog, } from "./init-model-catalog.js";
10
+ import { auditLegacyInitSurface, inspectContainedRegularFile, legacyAuditReceipt, removeContainedRegularFileWithSha256Cas, } from "./init-legacy-audit.js";
11
11
  const MANAGED_BLOCK_START = "<!-- LOOP_AGENT_INIT_START -->";
12
12
  const MANAGED_BLOCK_END = "<!-- LOOP_AGENT_INIT_END -->";
13
13
  const GITIGNORE_BLOCK_START = "# LOOP_AGENT_INIT_START";
@@ -817,6 +817,18 @@ function mergeRecord(base, patch) {
817
817
  ...patch,
818
818
  };
819
819
  }
820
+ function normalizeLegacyWorkflowPolicy(value) {
821
+ if (!isRecord(value))
822
+ return {};
823
+ const normalized = { ...value };
824
+ if (isRecord(normalized.dag)) {
825
+ const dag = { ...normalized.dag };
826
+ if (dag.defaultEntry === "dag run-task")
827
+ dag.defaultEntry = "task advance";
828
+ normalized.dag = dag;
829
+ }
830
+ return normalized;
831
+ }
820
832
  async function loadManagedAgentsTemplate(assetRoot) {
821
833
  if (managedAgentsTemplateCache !== undefined)
822
834
  return managedAgentsTemplateCache;
@@ -853,27 +865,34 @@ function mergeGitignoreManagedBlock(existing, block) {
853
865
  const start = existing.indexOf(GITIGNORE_BLOCK_START);
854
866
  const end = existing.indexOf(GITIGNORE_BLOCK_END);
855
867
  if (start >= 0 && end > start) {
856
- return (`${existing.slice(0, start).trimEnd()}\n\n${block}\n${existing.slice(end + GITIGNORE_BLOCK_END.length).trimStart()}`.trimEnd() +
857
- "\n");
868
+ return `${[
869
+ existing.slice(0, start).trimEnd(),
870
+ block,
871
+ existing.slice(end + GITIGNORE_BLOCK_END.length).trimStart(),
872
+ ]
873
+ .filter((part) => part.length > 0)
874
+ .join("\n\n")}\n`;
858
875
  }
859
876
  if (!existing.trim())
860
877
  return `${block}\n`;
861
878
  return `${existing.trimEnd()}\n\n${block}\n`;
862
879
  }
863
880
  /**
864
- * Shared ignore rules for loop-agent runtime facts. The four directories are
865
- * local, rebuildable runtime surface: every developer runs loop-agent init
866
- * after cloning, so nothing inside them is team-shareable by default.
867
- * `scripts/` and `ai_workspace/loop-agent/` stay on the shared commit surface.
881
+ * Shared ignore rules for loop-agent init surface: everything init regenerates
882
+ * in the target project is local and rebuildable, so none of it is
883
+ * team-shareable by default. `AGENTS.md` and `README.md` stay on the shared
884
+ * commit surface (they carry the governance handoff and are not ignored);
885
+ * `.opencode/` and `.pi/` project adapters are left to the user's discretion.
868
886
  */
869
- export function buildManagedGitignoreBlock() {
887
+ export function buildManagedGitignoreBlock(_governanceRoot = DEFAULT_GOVERNANCE_ROOT) {
870
888
  return [
871
889
  GITIGNORE_BLOCK_START,
872
- "# loop-agent runtime: local, rebuildable facts; do not ignore scripts/ or ai_workspace/loop-agent/",
890
+ "# loop-agent local runtime and machine-specific execution config",
873
891
  ".harness/",
874
- ".agents/",
892
+ ".playwright-cli/",
875
893
  ".task-pool/",
876
894
  ".worktrees/",
895
+ "harness.json",
877
896
  GITIGNORE_BLOCK_END,
878
897
  ].join("\n");
879
898
  }
@@ -918,16 +937,8 @@ function buildHarness(input) {
918
937
  delete pi.defaultModel;
919
938
  mergedExecutors.pi = pi;
920
939
  }
921
- const harness = {
922
- ...input.existing,
923
- $schema: expectedHarnessSchemaRef(input.governanceRoot),
924
- version: 1,
925
- project: input.projectName,
926
- adapter: "loop-agent",
927
- governanceRoot: input.governanceRoot,
928
- features: mergeRecord(input.template.features, input.existing.features),
929
- workflowPolicy: mergeRecord(input.template.workflowPolicy, input.existing.workflowPolicy),
930
- entrypoints: mergeRecord(input.existing.entrypoints, {
940
+ const legacyControllerMaps = {
941
+ entrypoints: {
931
942
  readme: "README.md",
932
943
  agents: "AGENTS.md",
933
944
  governanceIndex: `${input.governanceRoot}/README.md`,
@@ -935,16 +946,16 @@ function buildHarness(input) {
935
946
  workflow: `${input.governanceRoot}/feature-workflow.md`,
936
947
  verificationMatrix: `${input.governanceRoot}/verification-matrix.md`,
937
948
  loopAgentHarness: `${input.governanceRoot}/loop-agent-harness.md`,
938
- }),
939
- artifacts: mergeRecord(input.existing.artifacts, {
949
+ },
950
+ artifacts: {
940
951
  templatesDir: `${input.governanceRoot}/templates`,
941
952
  execPlansDir: `${input.governanceRoot}/exec-plans`,
942
953
  progressDir: `${input.governanceRoot}/progress`,
943
954
  reportsDir: `${input.governanceRoot}/reports`,
944
955
  decisionsDir: `${input.governanceRoot}/decisions`,
945
956
  taskPoolDir: ".harness/task-pool",
946
- }),
947
- scripts: mergeRecord(input.existing.scripts, {
957
+ },
958
+ scripts: {
948
959
  checkEngineeringStructure: "scripts/check-engineering-structure.sh",
949
960
  checkDocIndex: "scripts/check-doc-index.sh",
950
961
  checkDocLinks: "scripts/check-doc-links.sh",
@@ -960,7 +971,38 @@ function buildHarness(input) {
960
971
  quickVerify: "bash scripts/check-repo.sh",
961
972
  standardVerify: "bash scripts/ci-governance.sh",
962
973
  fullVerify: "bash scripts/ci.sh",
963
- }),
974
+ },
975
+ };
976
+ const preserveCustomMap = (name) => {
977
+ const current = isRecord(input.existing[name]) ? input.existing[name] : {};
978
+ return Object.fromEntries(Object.entries(current).filter(([key, value]) => legacyControllerMaps[name]?.[key] !== value));
979
+ };
980
+ const harness = {
981
+ version: 2,
982
+ project: input.projectName,
983
+ adapter: "loop-agent",
984
+ ...(isRecord(input.existing.features)
985
+ ? { features: input.existing.features }
986
+ : {}),
987
+ workflowPolicy: mergeRecord(input.template.workflowPolicy, normalizeLegacyWorkflowPolicy(input.existing.workflowPolicy)),
988
+ ...(Object.keys(preserveCustomMap("entrypoints")).length > 0
989
+ ? { entrypoints: preserveCustomMap("entrypoints") }
990
+ : {}),
991
+ ...(Object.keys(preserveCustomMap("artifacts")).length > 0
992
+ ? { artifacts: preserveCustomMap("artifacts") }
993
+ : {}),
994
+ ...(Object.keys(preserveCustomMap("scripts")).length > 0
995
+ ? { scripts: preserveCustomMap("scripts") }
996
+ : {}),
997
+ ...(isRecord(input.existing.verification)
998
+ ? { verification: input.existing.verification }
999
+ : {}),
1000
+ ...(isRecord(input.existing.workerPolicy)
1001
+ ? { workerPolicy: input.existing.workerPolicy }
1002
+ : {}),
1003
+ ...(isRecord(input.existing.worktree)
1004
+ ? { worktree: input.existing.worktree }
1005
+ : {}),
964
1006
  executors: mergedExecutors,
965
1007
  };
966
1008
  // Fresh init owns only the current DAG-facing surface. Legacy step routing is
@@ -997,6 +1039,16 @@ async function writeText(input) {
997
1039
  await writeFile(target, input.content, "utf-8");
998
1040
  input.written.push(input.relativePath);
999
1041
  }
1042
+ async function writeTextIfChanged(input) {
1043
+ const target = path.join(input.repoRoot, input.relativePath);
1044
+ await mkdir(path.dirname(target), { recursive: true });
1045
+ if ((await exists(target)) && (await readFile(target, "utf-8")) === input.content) {
1046
+ input.skipped.push(input.relativePath);
1047
+ return;
1048
+ }
1049
+ await writeFile(target, input.content, "utf-8");
1050
+ input.written.push(input.relativePath);
1051
+ }
1000
1052
  async function copyFileIfMissing(input) {
1001
1053
  const source = path.join(input.assetRoot, input.sourceRelativePath);
1002
1054
  const target = path.join(input.repoRoot, input.targetRelativePath);
@@ -1198,38 +1250,21 @@ async function readPackageVersion(assetRoot) {
1198
1250
  async function readInitSurfaceManifest(assetRoot) {
1199
1251
  const manifestPath = path.join(assetRoot, "docs", "init-surface.manifest.json");
1200
1252
  const raw = await readFile(manifestPath, "utf-8");
1201
- const manifest = JSON.parse(raw);
1202
- const initFullRequired = manifest.initFullRequired ?? [];
1203
- const initSurface = manifest.initSurface ?? {};
1204
- const seenPaths = new Set();
1205
- const entries = [];
1206
- for (const relativePath of initFullRequired) {
1207
- if (seenPaths.has(relativePath))
1208
- continue;
1209
- seenPaths.add(relativePath);
1210
- entries.push({
1211
- path: relativePath,
1212
- mode: initSurface[relativePath] ?? inferInitSurfaceMode(relativePath),
1213
- });
1253
+ const parsed = JSON.parse(raw);
1254
+ if (parsed.version !== 2 || !isRecord(parsed.initSurface)) {
1255
+ throw new Error("INIT_SURFACE_MANIFEST_INVALID: expected version 2 initSurface contract");
1214
1256
  }
1215
- // Fresh `init --profile full` copies the entire `docs/templates/` and
1216
- // `skills/` directories via copyDirMerge. Every file actually projected to a
1217
- // target project must be represented in the desired init surface so that
1218
- // check-update can detect missing or stale copies during controller upgrades.
1219
- // The static manifest intentionally only pins explicit modes for the subset
1220
- // that needs them; the rest are auto-discovered here as "copied" entries.
1221
- for (const discovered of await discoverCopiedSurfaceFiles(assetRoot)) {
1222
- if (seenPaths.has(discovered))
1223
- continue;
1224
- seenPaths.add(discovered);
1225
- entries.push({
1226
- path: discovered,
1227
- mode: initSurface[discovered] ?? inferInitSurfaceMode(discovered),
1228
- });
1257
+ const entries = [];
1258
+ for (const [entryPath, mode] of Object.entries(parsed.initSurface)) {
1259
+ if (!["generated", "copied", "managed-block", "directory", "state"].includes(String(mode))) {
1260
+ throw new Error(`INIT_SURFACE_MANIFEST_INVALID: unsupported mode for ${entryPath}`);
1261
+ }
1262
+ entries.push({ path: normalizeRelativePath(entryPath), mode: mode });
1229
1263
  }
1230
- if (!entries.some((entry) => entry.path === INIT_SURFACE_STATE_PATH)) {
1231
- entries.push({ path: INIT_SURFACE_STATE_PATH, mode: "state" });
1264
+ if (entries.length === 0 || !entries.some((entry) => entry.path === INIT_SURFACE_STATE_PATH)) {
1265
+ throw new Error("INIT_SURFACE_MANIFEST_INVALID: state entry is required");
1232
1266
  }
1267
+ const manifest = parsed;
1233
1268
  return { manifest, raw, sha256: sha256Text(raw), entries };
1234
1269
  }
1235
1270
  /**
@@ -1291,6 +1326,15 @@ function inferInitSurfaceMode(relativePath) {
1291
1326
  return "copied";
1292
1327
  }
1293
1328
  async function buildDesiredSurfaceContent(input) {
1329
+ if (input.entry.path === ".agents/skills/loop-agent/SKILL.md") {
1330
+ const bridgePath = path.join(input.assetRoot, "resources", "agent-bridge", "loop-agent", "SKILL.md");
1331
+ const fallbackPath = path.join(input.assetRoot, "skills", "loop-agent", "SKILL.md");
1332
+ const sourcePath = (await exists(bridgePath)) ? bridgePath : fallbackPath;
1333
+ return {
1334
+ content: await readFile(sourcePath, "utf-8"),
1335
+ sourcePath,
1336
+ };
1337
+ }
1294
1338
  const manifestPath = targetPathToManifestPath(input.entry.path, input.governanceRoot);
1295
1339
  if (input.entry.mode === "directory" || input.entry.mode === "state")
1296
1340
  return {};
@@ -1312,7 +1356,7 @@ async function buildDesiredSurfaceContent(input) {
1312
1356
  };
1313
1357
  }
1314
1358
  if (manifestPath === ".gitignore") {
1315
- return { content: buildManagedGitignoreBlock() };
1359
+ return { content: buildManagedGitignoreBlock(input.governanceRoot) };
1316
1360
  }
1317
1361
  if (manifestPath === "harness.json") {
1318
1362
  const template = await readJsonIfExists(path.join(input.assetRoot, "harness.json"));
@@ -1395,7 +1439,9 @@ async function readExistingSurfaceState(repoRoot) {
1395
1439
  if (!(await exists(filePath)))
1396
1440
  return undefined;
1397
1441
  const parsed = JSON.parse(await readFile(filePath, "utf-8"));
1398
- if (!isRecord(parsed) || parsed.schemaVersion !== 1)
1442
+ if (!isRecord(parsed) ||
1443
+ (parsed.schemaVersion !== 1 && parsed.schemaVersion !== 2) ||
1444
+ !isRecord(parsed.files))
1399
1445
  return undefined;
1400
1446
  return parsed;
1401
1447
  }
@@ -1630,21 +1676,37 @@ async function buildCurrentSurfaceState(input) {
1630
1676
  };
1631
1677
  }
1632
1678
  return {
1633
- schemaVersion: 1,
1679
+ schemaVersion: 2,
1634
1680
  controllerVersion,
1635
1681
  stateKind: input.stateKind,
1636
1682
  generatedAt: input.generatedAt ?? new Date().toISOString(),
1637
1683
  manifestSha256: manifest.sha256,
1638
1684
  files,
1685
+ dispositions: [],
1686
+ actionReceipts: [],
1639
1687
  };
1640
1688
  }
1641
1689
  async function writeInitSurfaceState(input) {
1642
1690
  const state = await buildCurrentSurfaceState(input);
1643
- if (input.stateKind === "recorded" && input.preserveOwnershipFrom) {
1691
+ state.dispositions = [
1692
+ ...(input.preserveOwnershipFrom?.dispositions ?? []),
1693
+ ...(input.dispositions ?? []),
1694
+ ];
1695
+ state.actionReceipts = [
1696
+ ...(input.preserveOwnershipFrom?.actionReceipts ?? []),
1697
+ ...(input.actionReceipts ?? []),
1698
+ ];
1699
+ state.legacyAudit = input.legacyAudit ?? input.preserveOwnershipFrom?.legacyAudit;
1700
+ if (input.preserveOwnershipFrom) {
1644
1701
  for (const [pathName, file] of Object.entries(state.files)) {
1645
1702
  if (file.relationship !== "local-existing-unknown")
1646
1703
  continue;
1647
1704
  const priorFile = input.preserveOwnershipFrom.files[pathName];
1705
+ if (priorFile?.acceptedMerge) {
1706
+ file.acceptedMerge = { ...priorFile.acceptedMerge };
1707
+ }
1708
+ if (input.stateKind !== "recorded")
1709
+ continue;
1648
1710
  const priorHash = priorFile?.currentSha256;
1649
1711
  if (priorHash !== undefined) {
1650
1712
  file.currentSha256 = priorHash;
@@ -1652,10 +1714,9 @@ async function writeInitSurfaceState(input) {
1652
1714
  else {
1653
1715
  delete file.currentSha256;
1654
1716
  }
1655
- if (priorFile?.acceptedMerge) {
1656
- file.acceptedMerge = { ...priorFile.acceptedMerge };
1657
- }
1658
1717
  }
1718
+ }
1719
+ if (input.stateKind === "recorded" && input.preserveOwnershipFrom) {
1659
1720
  for (const [pathName, priorFile] of Object.entries(input.preserveOwnershipFrom.files)) {
1660
1721
  if (state.files[pathName] || priorFile.mode === "state")
1661
1722
  continue;
@@ -1680,6 +1741,13 @@ async function writeInitSurfaceState(input) {
1680
1741
  }
1681
1742
  const target = path.join(input.repoRoot, INIT_SURFACE_STATE_PATH);
1682
1743
  await mkdir(path.dirname(target), { recursive: true });
1744
+ const previous = await readExistingSurfaceState(input.repoRoot);
1745
+ if (previous?.schemaVersion === 2) {
1746
+ const previousComparable = { ...previous, generatedAt: "" };
1747
+ const nextComparable = { ...state, generatedAt: "" };
1748
+ if (JSON.stringify(previousComparable) === JSON.stringify(nextComparable))
1749
+ return previous;
1750
+ }
1683
1751
  await writeFile(target, `${JSON.stringify(state, null, 2)}\n`, "utf-8");
1684
1752
  return state;
1685
1753
  }
@@ -1898,7 +1966,10 @@ async function collectRetiredLayoutActions(input) {
1898
1966
  const retiredOwnedPaths = [];
1899
1967
  const currentPaths = new Set(Object.keys(input.currentState.files));
1900
1968
  const recordedPaths = new Set(Object.keys(input.recordedState.files));
1969
+ const disposedPaths = new Set((input.recordedState.dispositions ?? []).map((receipt) => receipt.path));
1901
1970
  for (const [oldPath, oldState] of Object.entries(input.recordedState.files)) {
1971
+ if (disposedPaths.has(oldPath))
1972
+ continue;
1902
1973
  const targetPath = normalizeRelativePath(manifestPathToTargetPath(oldPath, input.governanceRoot));
1903
1974
  if (targetPath === oldPath || !currentPaths.has(targetPath))
1904
1975
  continue;
@@ -1964,6 +2035,8 @@ async function collectRetiredLayoutActions(input) {
1964
2035
  for (const legacyRoot of ["docs", "skills"]) {
1965
2036
  for (const relativePath of await listRelativeFiles(path.join(input.repoRoot, legacyRoot))) {
1966
2037
  const oldPath = `${legacyRoot}/${relativePath}`;
2038
+ if (disposedPaths.has(oldPath))
2039
+ continue;
1967
2040
  if (recordedPaths.has(oldPath))
1968
2041
  continue;
1969
2042
  const targetPath = normalizeRelativePath(manifestPathToTargetPath(oldPath, input.governanceRoot));
@@ -2518,84 +2591,45 @@ function buildGovernanceDirectoryReadme(input) {
2518
2591
  }
2519
2592
  export function buildInitInstructions(input) {
2520
2593
  const projectName = input.projectName ?? path.basename(path.resolve(input.repoRoot));
2521
- const governanceRoot = input.governanceRoot ?? DEFAULT_GOVERNANCE_ROOT;
2522
2594
  return [
2523
2595
  "# loop-agent Initialization Instructions",
2524
2596
  "",
2525
- `Initialize the target repository as a loop-agent harness project: \`${input.repoRoot}\`.`,
2597
+ `Initialize the target repository as a minimal loop-agent project: \`${input.repoRoot}\`.`,
2526
2598
  "",
2527
- "## Confirm With User",
2599
+ "## Project Inputs",
2528
2600
  "",
2529
2601
  `- Project name: default \`${projectName}\`.`,
2530
- `- Governance root: default \`${governanceRoot}\`.`,
2531
2602
  "- Discover a credential-safe Pi/OpenCode model catalog with `loop-agent init model-catalog --repo-root <target> --json`. The command exposes only allowlisted model metadata, Pi setup status, and credential-readiness booleans, never raw config or credentials.",
2532
2603
  "- Preserve every existing LOW/MED/HIGH reference that still resolves in Pi. Select only missing or removed tiers from `eligibleForHarness=true`, then apply the complete matrix with `--low-model`, `--med-model`, and `--high-model`; update code keeps valid tiers unchanged.",
2533
- "- If `piSetup.status` is `model-definition-required`, ask only for the missing provider/model id, API/base URL, context window, maximum output, inputs/reasoning, cost constraints, and credential method. Help merge Pi models.json without exposing credential values, rerun the catalog, and only then initialize. If definitions exist but credentials are missing, configure auth instead of rewriting harness tiers.",
2534
- "- Default: merge existing AGENTS.md, harness.json, and loop-agent governance docs instead of overwriting user content.",
2604
+ "- Ask only when credentials, cost/compliance constraints, a bridge-path conflict, or an ownership decision cannot be inferred safely.",
2535
2605
  "",
2536
2606
  "## Initialization Upgrade Routing",
2537
2607
  "",
2538
2608
  "When the user says `loop-agent初始化更新`, `loop-agent 初始化更新`, `更新 loop-agent 初始化内容`, or an equivalent write request, run `loop-agent init upgrade --repo-root . --json` as the single controller-owned entry. Complete returned single-file allowedPaths merge tasks and call `--continue` until a stable terminal result; do not stop at check-update, needs-safe-update, needs-model-merge, or verification-pending.",
2539
2609
  "Explicit `检查初始化更新`, `初始化更新校验`, or `只检查,不要修改` stays strictly read-only: run only `loop-agent init check-update --repo-root . --markdown` and do not create an upgrade run.",
2540
- "Upgrade manages project `.opencode/plugins/`, `.pi/extensions/`, and `.pi/settings.json` by nested merge. Pi must trust the project before loading these settings; do not read or write `~/.pi/agent/settings.json` by default.",
2541
- "The upgrade also writes a read-only gitignore migration assessment (`.harness/init-upgrades/<run-id>/gitignore-migration.json`): tracked `.harness/**` and `.agents/**` get index-only `git rm -r --cached --ignore-unmatch` guidance (working-tree files are kept). Pause for human review when `.agents` content is tracked or when staged changes / git query failures block safe guidance; never run git rm yourself.",
2610
+ "The upgrade removes only controller-owned bytes that still match their recorded hash. Modified or unproven legacy files are preserved for an explicit bounded decision.",
2611
+ "Do not change the Git index implicitly. Follow only the path-specific migration guidance returned by the controller.",
2612
+ "",
2613
+ "## Minimal Managed Surface",
2542
2614
  "",
2543
- "## Apply Defaults",
2615
+ "Fresh init manages only `.gitignore`, `harness.json`, `.agents/skills/loop-agent/SKILL.md`, and `.harness/init-surface.json`.",
2616
+ "Do not create or modify root `README.md`, `AGENTS.md`, project `docs/`, project `scripts/`, client adapters, or mirrored built-in Skills.",
2617
+ "General governance, templates, checks, and built-in Skills come from the installed loop-agent package. Project facts continue to come from the repository's own files.",
2618
+ "The bridge Skill is the only default repo-local integration for external Agents. It routes them to `loop-agent --repo-root . operator guide --json`; it is not a copy of the controller policy.",
2544
2619
  "",
2545
- '- Use the current loop-agent harness.json as the default template, but write target project name plus `adapter: "loop-agent"` and a Pi-only `executors.pi.LOW/MED/HIGH` matrix. Do not write `defaultModel` when all three tiers exist, and never project `model`, `models`, `modelProfiles`, `modelRouting`, `verify`, or `sequentialWorkflowRole`.',
2620
+ "## Verification And DAG",
2621
+ "",
2622
+ "Project verification comes from `.loop-agent/project.json`, additive local `harness.json` commands, or bounded capability scanning. Never assume deleted projected scripts still exist.",
2546
2623
  `- ${DAG_HARD_GATE_TRIGGER}`,
2547
- "- Generate the target project's loop-agent script matrix from templates: structure check, docs index/link checks, active plan status, exec-plan index sync, harness runtime cleanliness, architecture boundaries, skill entry integrity, governance CI, project-test CI, and full CI.",
2548
- "- Copy or project only stack-agnostic governance scripts. For project-specific verification, packaging, release, or maintenance commands, generate the target-project version from templates plus the target repository's actual files instead of copying loop-agent's own TypeScript-specific scripts.",
2549
- "- Do not assume the target project is TypeScript, Node.js, frontend, backend, or any other specific stack.",
2550
- "- `scripts/ci-tests.sh` must be language-neutral: detect common project verification entrypoints conservatively, run only commands that exist, and clearly report when project-specific verification needs model/user adaptation.",
2551
- "- Default verification entries: quick `bash scripts/check-repo.sh`, standard `bash scripts/ci-governance.sh`, full `bash scripts/ci.sh`.",
2552
- `- Generate target-project versions of \`${governanceRoot}/README.md\`, \`${governanceRoot}/development-principles.md\`, \`${governanceRoot}/architecture/runtime-boundaries.md\`, \`${governanceRoot}/feature-workflow.md\`, \`${governanceRoot}/verification-matrix.md\`, and \`${governanceRoot}/loop-agent-harness.md\`; copy only generic methodology/template material as-is.`,
2553
- "- After deterministic initialization, inspect README/config/build files (for example package.json, pyproject.toml, go.mod, Cargo.toml, pom.xml, Gradle files, Makefile, .sln/.csproj, or project-specific scripts) and adapt `scripts/ci-tests.sh` plus the verification matrix to the real project.",
2554
- "- Enrich the root `README.md`: keep the deterministic project title and the loop-agent managed block intact, and fill the human-authored sections (项目概览, 技术栈与目录结构, 开发与验证) from the target project's actual files. The root README must serve both as a human-first project entry and as an agent work entry; replace the initialization-model supplement comments when the project files provide the information.",
2555
- `- Populate \`${governanceRoot}/verification-matrix.md\` with the target project's actual quick, standard, and full verification commands derived from its real language and toolchain, keeping the governance rows intact.`,
2556
- "- Project repo-local skills live in `.agents/skills/`. Do not create a root `skills/` directory in the target project; the package's bundled `skills/` remains the built-in fallback.",
2557
- "- Merge a loop-agent managed block into `.gitignore` that ignores exactly the four local, rebuildable runtime directories (`.harness/`, `.agents/`, `.task-pool/`, `.worktrees/`) while keeping `scripts/` and `ai_workspace/loop-agent/` on the shared commit surface; keep all user rules outside the block untouched.",
2558
- "- Do not copy examples by default; examples stay bundled in the tool and are available through `loop-agent examples`.",
2559
- "- Add or update a loop-agent managed block in AGENTS.md.",
2560
- "- The generated AGENTS.md must include documentation convergence and structured DAG write-boundary rules so target projects keep the same working discipline as this repository.",
2561
- "- The generated target docs must surface the production readiness checklist and the operator recovery path: `dag report`, `dag doctor --run-id --markdown`, and failed-run `dag closeout-draft` failure handoff.",
2562
- "- Create `.harness/` runtime directories but do not create historical run facts.",
2563
- "",
2564
- "## Automatic Workflow For Model-Executed Init",
2565
- "",
2566
- "When a model/agent is asked to initialize a target project, treat initialization as one automated workflow. Do not run deterministic init and then wait for another user turn to fill project-specific content.",
2567
- "",
2568
- "1. Run `init model-catalog` and inspect `piSetup`. When Pi has no usable model setup, collect only the missing provider/model metadata or credential method, help configure Pi, and rerun the catalog before writing harness.json.",
2569
- "2. Inspect the target repository. Preserve existing tiers that still resolve in Pi and select only missing/removed tiers from credential-ready Pi-compatible entries. OpenCode-only entries are context, not proof that the Pi executor can use them.",
2570
- "3. Resolve with the user only inputs that remain genuinely unsafe to assume: material credential/cost/compliance choices, non-default governance root, overwrite policy, or deployment side effects.",
2571
- "4. Run deterministic init with all three tier flags and merge defaults.",
2572
- "5. Continue immediately into project inspection and adaptation.",
2573
- "6. Finish by running the init health checks and quick verification; `init doctor` must confirm the Pi model matrix before any DAG is started.",
2574
- "",
2575
- "A model reference that remains in Pi is project-owned and must not be reset merely because init templates changed. If its credentials are missing, preserve the tier and repair authentication. If a reference has left Pi, replace only that tier. Ask the user only when required model metadata, credentials, cost, compliance, or availability cannot be inferred. An ambiguous old model configuration stays in a bounded harness.json model merge/human decision; never silently reinterpret it.",
2576
- "",
2577
- "## Required Model Adaptation",
2578
- "",
2579
- "Do not stop after the deterministic `loop-agent init` command. When these instructions are executed by an agent/model, the initialization is not complete until the target project has been inspected and the generated scaffolding has been adapted.",
2580
- "",
2581
- "Required post-init steps:",
2582
- "",
2583
- "1. Read the target project's existing README, manifest/build/config files, and top-level source/module directories.",
2584
- "2. Replace the root README's `初始化模型补充` comments when the information can be inferred from files. At minimum, fill project overview, technology stack/directory structure, and development/verification commands.",
2585
- `3. Update \`${governanceRoot}/verification-matrix.md\` with the target project's actual quick, standard, and full verification commands.`,
2586
- `4. Confirm the generated docs expose \`${governanceRoot}/templates/production-readiness-checklist.md\` plus the operator recovery path: \`dag report\`, \`dag doctor --run-id --markdown\`, and failed-run \`dag closeout-draft\` failure handoff.`,
2587
- "5. Update `scripts/ci-tests.sh` only when the conservative generated detector is insufficient for the target project.",
2588
- "6. Run `loop-agent init doctor`, `loop-agent inspect`, `loop-agent docs audit`, and the quick verification command.",
2589
- "",
2590
- "Completion rule: if target files provide enough evidence, the final README should not leave generic `初始化模型补充` comments in the sections that can be filled. If a section truly cannot be inferred, write a short explicit note such as `尚未从仓库文件中识别到 ...` instead of asking the user to fill it later.",
2624
+ "- A real DAG must be owned by Console operation or another durable foreground controller. Do not launch a long-running DAG from a transient Agent shell.",
2625
+ "- Run `loop-agent init doctor`, `loop-agent --repo-root . operator guide --json`, and the selected project verification before starting new governed work.",
2591
2626
  "",
2592
2627
  "## Suggested Command",
2593
2628
  "",
2594
2629
  "```bash",
2595
- `loop-agent init --repo-root ${input.repoRoot} --profile full --merge`,
2630
+ `loop-agent init --repo-root ${input.repoRoot} --merge`,
2596
2631
  "loop-agent init doctor --repo-root <target>",
2597
- "loop-agent inspect --repo-root <target>",
2598
- "loop-agent docs audit --repo-root <target>",
2632
+ "loop-agent --repo-root <target> operator guide --json",
2599
2633
  "```",
2600
2634
  ].join("\n");
2601
2635
  }
@@ -2603,8 +2637,6 @@ export async function initializeLoopAgentProject(options) {
2603
2637
  const repoRoot = path.resolve(options.repoRoot);
2604
2638
  const projectName = options.projectName ?? path.basename(repoRoot);
2605
2639
  const governanceRoot = options.governanceRoot ?? DEFAULT_GOVERNANCE_ROOT;
2606
- const profile = options.profile ?? "full";
2607
- const merge = options.merge ?? true;
2608
2640
  const model = normalizeInitModelReference(options);
2609
2641
  const modelMatrix = options.modelMatrix;
2610
2642
  const written = [];
@@ -2622,21 +2654,6 @@ export async function initializeLoopAgentProject(options) {
2622
2654
  }
2623
2655
  }
2624
2656
  await mkdir(repoRoot, { recursive: true });
2625
- const readmePath = path.join(repoRoot, "README.md");
2626
- const existingReadme = (await exists(readmePath))
2627
- ? await readFile(readmePath, "utf-8")
2628
- : undefined;
2629
- const readmeContent = existingReadme
2630
- ? mergeManagedBlock(existingReadme, buildManagedReadmeBlock({ projectName, governanceRoot }))
2631
- : buildTargetReadme({ projectName, governanceRoot });
2632
- await writeText({
2633
- repoRoot,
2634
- relativePath: "README.md",
2635
- content: readmeContent,
2636
- merge: true,
2637
- written,
2638
- skipped,
2639
- });
2640
2657
  const harness = buildHarness({
2641
2658
  existing: existingHarness,
2642
2659
  template,
@@ -2645,27 +2662,10 @@ export async function initializeLoopAgentProject(options) {
2645
2662
  model,
2646
2663
  modelMatrix,
2647
2664
  });
2648
- await writeText({
2665
+ await writeTextIfChanged({
2649
2666
  repoRoot,
2650
2667
  relativePath: "harness.json",
2651
2668
  content: `${JSON.stringify(harness, null, 2)}\n`,
2652
- merge: true,
2653
- written,
2654
- skipped,
2655
- });
2656
- const agentsPath = path.join(repoRoot, "AGENTS.md");
2657
- const existingAgents = (await exists(agentsPath))
2658
- ? await readFile(agentsPath, "utf-8")
2659
- : `# AGENTS.md\n`;
2660
- await writeText({
2661
- repoRoot,
2662
- relativePath: "AGENTS.md",
2663
- content: mergeManagedBlock(existingAgents, await buildManagedAgentsBlock({
2664
- assetRoot,
2665
- projectName,
2666
- governanceRoot,
2667
- })),
2668
- merge: true,
2669
2669
  written,
2670
2670
  skipped,
2671
2671
  });
@@ -2673,122 +2673,45 @@ export async function initializeLoopAgentProject(options) {
2673
2673
  const existingGitignore = (await exists(gitignorePath))
2674
2674
  ? await readFile(gitignorePath, "utf-8")
2675
2675
  : "";
2676
- await writeText({
2676
+ await writeTextIfChanged({
2677
2677
  repoRoot,
2678
2678
  relativePath: ".gitignore",
2679
- content: mergeGitignoreManagedBlock(existingGitignore, buildManagedGitignoreBlock()),
2680
- merge: true,
2679
+ content: mergeGitignoreManagedBlock(existingGitignore, buildManagedGitignoreBlock(governanceRoot)),
2681
2680
  written,
2682
2681
  skipped,
2683
2682
  });
2684
- for (const doc of CORE_DOC_FILES) {
2685
- const generated = buildGeneratedCoreDoc({
2686
- doc: doc.target,
2687
- projectName,
2688
- governanceRoot,
2689
- });
2690
- if (generated) {
2691
- await writeTextIfMissing({
2692
- repoRoot,
2693
- relativePath: path.join(governanceRoot, doc.target),
2694
- content: generated,
2695
- merge,
2696
- written,
2697
- skipped,
2698
- });
2699
- continue;
2700
- }
2701
- await copyFileIfMissing({
2702
- assetRoot,
2703
- repoRoot,
2704
- sourceRelativePath: path.join("docs", doc.source),
2705
- targetRelativePath: path.join(governanceRoot, doc.target),
2706
- merge,
2707
- written,
2708
- skipped,
2709
- });
2710
- }
2711
- for (const dir of GOVERNANCE_README_DIRS) {
2712
- await writeTextIfMissing({
2713
- repoRoot,
2714
- relativePath: path.join(governanceRoot, dir, "README.md"),
2715
- content: buildGovernanceDirectoryReadme({ dir, projectName }),
2716
- merge,
2717
- written,
2718
- skipped,
2719
- });
2720
- }
2721
- await copyDirMerge({
2683
+ const bridgeEntry = {
2684
+ path: ".agents/skills/loop-agent/SKILL.md",
2685
+ mode: "copied",
2686
+ };
2687
+ const bridge = await buildDesiredSurfaceContent({
2722
2688
  assetRoot,
2723
2689
  repoRoot,
2724
- sourceRelativePath: "docs/templates",
2725
- targetRelativePath: path.join(governanceRoot, "templates"),
2726
- written,
2727
- });
2728
- await writeTextIfMissing({
2729
- repoRoot,
2730
- relativePath: path.join(governanceRoot, "spec-registry.json"),
2731
- content: buildSpecRegistry(),
2732
- merge,
2733
- written,
2734
- skipped,
2690
+ projectName,
2691
+ governanceRoot,
2692
+ entry: bridgeEntry,
2735
2693
  });
2736
- if (profile === "full") {
2737
- // Project repo-local skills live only under `.agents/skills/`.
2738
- // The package still ships `skills/` as the built-in fallback source.
2739
- await copyDirMerge({
2740
- assetRoot,
2741
- repoRoot,
2742
- sourceRelativePath: "skills",
2743
- targetRelativePath: ".agents/skills",
2744
- written,
2745
- });
2694
+ if (bridge.content === undefined) {
2695
+ throw new Error("AGENT_BRIDGE_RESOURCE_MISSING: bundled loop-agent bridge is unavailable");
2696
+ }
2697
+ const bridgeTarget = path.join(repoRoot, bridgeEntry.path);
2698
+ if (await exists(bridgeTarget)) {
2699
+ const existingBridge = await readFile(bridgeTarget, "utf-8");
2700
+ if (existingBridge !== bridge.content) {
2701
+ throw new Error("BRIDGE_PATH_CONFLICT: .agents/skills/loop-agent/SKILL.md already contains user or legacy content; run init upgrade to resolve it explicitly");
2702
+ }
2703
+ skipped.push(bridgeEntry.path);
2746
2704
  }
2747
2705
  else {
2748
- skipped.push(".agents/skills/");
2749
- }
2750
- skipped.push("examples/");
2751
- for (const [relativePath, content] of Object.entries(buildInitScriptFiles(governanceRoot))) {
2752
- await writeText({
2706
+ await writeTextIfChanged({
2753
2707
  repoRoot,
2754
- relativePath,
2755
- content,
2756
- merge: true,
2708
+ relativePath: bridgeEntry.path,
2709
+ content: bridge.content,
2757
2710
  written,
2758
2711
  skipped,
2759
2712
  });
2760
2713
  }
2761
- await ensureHarnessDirs(repoRoot, written);
2762
- await writeCompatPrompts({ repoRoot, merge, written, skipped });
2763
- const clientRecoveryMode = options.clientRecovery ?? "auto";
2764
- const clientRecovery = clientRecoveryMode === "off"
2765
- ? undefined
2766
- : await runClientRecovery({
2767
- repoRoot,
2768
- mode: clientRecoveryMode,
2769
- });
2770
- const clientRecoveryPaths = [
2771
- OPENCODE_TRANSIENT_RETRY_PLUGIN_PATH,
2772
- OPENCODE_CONTEXT_OVERFLOW_COMPACT_PLUGIN_PATH,
2773
- PI_CONTEXT_OVERFLOW_EXTENSION_PATH,
2774
- PI_PROJECT_SETTINGS_PATH,
2775
- ];
2776
- if (clientRecoveryMode === "off") {
2777
- for (const recoveryPath of clientRecoveryPaths)
2778
- skipped.push(recoveryPath);
2779
- }
2780
- else if (clientRecovery) {
2781
- const installResults = [
2782
- clientRecovery.plugin,
2783
- clientRecovery.overflowPlugin,
2784
- clientRecovery.piExtension,
2785
- { written: clientRecovery.pi?.wrote === true },
2786
- ];
2787
- for (const [index, recoveryPath] of clientRecoveryPaths.entries()) {
2788
- if (installResults[index]?.written)
2789
- written.push(recoveryPath);
2790
- }
2791
- }
2714
+ const stateBefore = await fileSha256IfExists(path.join(repoRoot, INIT_SURFACE_STATE_PATH));
2792
2715
  await writeInitSurfaceState({
2793
2716
  repoRoot,
2794
2717
  projectName,
@@ -2796,15 +2719,18 @@ export async function initializeLoopAgentProject(options) {
2796
2719
  stateKind: "recorded",
2797
2720
  acceptCurrentHarnessAsMerge: model !== undefined || modelMatrix !== undefined,
2798
2721
  });
2799
- written.push(INIT_SURFACE_STATE_PATH);
2722
+ const stateAfter = await fileSha256IfExists(path.join(repoRoot, INIT_SURFACE_STATE_PATH));
2723
+ if (stateBefore !== stateAfter)
2724
+ written.push(INIT_SURFACE_STATE_PATH);
2725
+ else
2726
+ skipped.push(INIT_SURFACE_STATE_PATH);
2800
2727
  return {
2801
2728
  repoRoot,
2802
2729
  projectName,
2803
2730
  governanceRoot,
2804
- profile,
2731
+ profile: "minimal",
2805
2732
  written,
2806
2733
  skipped,
2807
- clientRecovery,
2808
2734
  };
2809
2735
  }
2810
2736
  function actionForMissing(pathName, state) {
@@ -2842,7 +2768,7 @@ function modelMergeTaskFor(pathName, state, allPaths, recordedState) {
2842
2768
  taskId: `init-merge-${sha256Text(pathName).slice(0, 12)}`,
2843
2769
  path: pathName,
2844
2770
  reason: "target file exists but does not match the current loop-agent initialization surface",
2845
- sourcePath: state.sourcePath,
2771
+ sourcePath: state?.sourcePath,
2846
2772
  allowedPaths: [pathName],
2847
2773
  forbiddenPaths: [
2848
2774
  ...allPaths.filter((candidate) => candidate !== pathName),
@@ -2861,9 +2787,9 @@ function modelMergeTaskFor(pathName, state, allPaths, recordedState) {
2861
2787
  ],
2862
2788
  evidence: {
2863
2789
  baseSha256: recordedState?.files[pathName]?.currentSha256,
2864
- currentSha256: state.currentSha256,
2865
- desiredSha256: state.sourceSha256,
2866
- sourceAnchorSha256: state.sourceAnchorSha256,
2790
+ currentSha256: state?.currentSha256,
2791
+ desiredSha256: state?.sourceSha256,
2792
+ sourceAnchorSha256: state?.sourceAnchorSha256,
2867
2793
  },
2868
2794
  };
2869
2795
  }
@@ -2873,13 +2799,17 @@ function recommendedNextFor(report) {
2873
2799
  next.push("loop-agent init update --repo-root <target> --bootstrap-surface");
2874
2800
  }
2875
2801
  if (report.deterministicActions.some((action) => action.type !== "bootstrap-surface")) {
2876
- next.push("loop-agent init update --repo-root <target> --apply-safe");
2802
+ next.push(report.legacyAudit
2803
+ ? "loop-agent init update --repo-root <target> --apply-safe --legacy-audit"
2804
+ : "loop-agent init update --repo-root <target> --apply-safe");
2877
2805
  }
2878
2806
  if (report.modelMergeTasks.length > 0) {
2879
2807
  next.push("loop-agent init check-update --repo-root <target> --markdown");
2880
2808
  }
2881
2809
  if (report.humanDecisions.length > 0) {
2882
- next.push("Review humanDecisions before applying semantic or policy-sensitive changes.");
2810
+ next.push(report.humanDecisions.some((decision) => decision.candidateId)
2811
+ ? "Invoke /skill:init-update to review hash-bound legacy candidates."
2812
+ : "Review humanDecisions before applying semantic or policy-sensitive changes.");
2883
2813
  }
2884
2814
  if (next.length === 0)
2885
2815
  next.push("No init update actions are needed.");
@@ -2901,9 +2831,8 @@ export async function checkInitUpdate(input) {
2901
2831
  projectName: input.projectName,
2902
2832
  governanceRoot: input.governanceRoot,
2903
2833
  });
2904
- const clientRecoveryMode = input.clientRecovery ?? "auto";
2905
- const skipClientRecoverySurfaces = clientRecoveryMode === "off";
2906
2834
  const recordedState = await readExistingSurfaceState(repoRoot);
2835
+ const disposedPaths = new Set((recordedState?.dispositions ?? []).map((receipt) => receipt.path));
2907
2836
  const assetRoot = await findPackageRoot();
2908
2837
  const surfaceState = recordedState?.stateKind ?? "missing";
2909
2838
  const currentState = await buildCurrentSurfaceState({
@@ -2942,10 +2871,6 @@ export async function checkInitUpdate(input) {
2942
2871
  });
2943
2872
  }
2944
2873
  for (const [pathName, state] of Object.entries(currentState.files)) {
2945
- // Mirror fresh init: client-recovery=off never reinstalls recovery surfaces.
2946
- if (skipClientRecoverySurfaces && isClientRecoverySurfacePath(pathName)) {
2947
- continue;
2948
- }
2949
2874
  // `.pi/settings.json` is a structured project configuration: fill only
2950
2875
  // absent nested recovery fields and preserve every explicit project value.
2951
2876
  if (pathName === PI_PROJECT_SETTINGS_PATH &&
@@ -2980,6 +2905,30 @@ export async function checkInitUpdate(input) {
2980
2905
  continue;
2981
2906
  }
2982
2907
  if (state.relationship === "local-existing-unknown") {
2908
+ if (pathName === ".agents/skills/loop-agent/SKILL.md") {
2909
+ const recordedBridge = recordedState?.files[pathName];
2910
+ const decisionOwnedBridge = recordedState?.actionReceipts?.some((receipt) => receipt.type === "replace-owned-file" &&
2911
+ receipt.path === pathName &&
2912
+ receipt.afterSha256 === state.currentSha256);
2913
+ if ((recordedState?.stateKind === "recorded" &&
2914
+ recordedBridge?.currentSha256 === state.currentSha256) ||
2915
+ decisionOwnedBridge) {
2916
+ deterministicActions.push({
2917
+ type: "replace-owned-file",
2918
+ path: pathName,
2919
+ expectedSha256: state.currentSha256,
2920
+ mode: state.mode,
2921
+ reason: "replace the unchanged controller-owned loop-agent Skill with the current external Agent bridge",
2922
+ });
2923
+ }
2924
+ else {
2925
+ humanDecisions.push({
2926
+ path: pathName,
2927
+ reason: "bridge-path-conflict: existing loop-agent Skill is not proven controller-owned and unchanged",
2928
+ });
2929
+ }
2930
+ continue;
2931
+ }
2983
2932
  const acceptedMerge = recordedState?.files[pathName]?.acceptedMerge;
2984
2933
  if (acceptedMerge) {
2985
2934
  // Generated acceptance is bound to the stable source anchor so that
@@ -3034,11 +2983,29 @@ export async function checkInitUpdate(input) {
3034
2983
  if (recordedState) {
3035
2984
  for (const [pathName, recordedFile] of Object.entries(recordedState.files)) {
3036
2985
  if (currentState.files[pathName] ||
2986
+ disposedPaths.has(pathName) ||
3037
2987
  retiredActionPaths.has(pathName) ||
3038
2988
  recordedFile.mode === "state" ||
3039
2989
  recordedFile.mode === "directory") {
3040
2990
  continue;
3041
2991
  }
2992
+ if (recordedFile.mode === "managed-block") {
2993
+ const target = path.join(repoRoot, pathName);
2994
+ if (!(await exists(target)))
2995
+ continue;
2996
+ const content = await readFile(target, "utf-8");
2997
+ const block = pathName === ".gitignore"
2998
+ ? extractGitignoreManagedBlock(content)
2999
+ : extractManagedBlock(content);
3000
+ if (block) {
3001
+ deterministicActions.push({
3002
+ type: "strip-managed-block",
3003
+ path: pathName,
3004
+ reason: "remove the retired loop-agent managed block while preserving surrounding project content",
3005
+ });
3006
+ }
3007
+ continue;
3008
+ }
3042
3009
  const currentSha256 = await fileSha256IfExists(path.join(repoRoot, pathName));
3043
3010
  if (!currentSha256)
3044
3011
  continue;
@@ -3069,15 +3036,6 @@ export async function checkInitUpdate(input) {
3069
3036
  const harness = JSON.parse(await readFile(harnessPath, "utf-8"));
3070
3037
  if (isRecord(harness))
3071
3038
  currentHarness = harness;
3072
- if (recordedState &&
3073
- isRecord(harness) &&
3074
- harness.$schema !== expectedHarnessSchemaRef(governanceRoot)) {
3075
- deterministicActions.push({
3076
- type: "add-harness-schema-ref",
3077
- path: "harness.json",
3078
- reason: "harness.json is missing or has a stale IDE JSON Schema reference",
3079
- });
3080
- }
3081
3039
  if (recordedState &&
3082
3040
  isRecord(harness) &&
3083
3041
  governanceRoot !== "docs" &&
@@ -3117,7 +3075,6 @@ export async function checkInitUpdate(input) {
3117
3075
  mergeTask.verification = [
3118
3076
  "loop-agent init check-update --repo-root . --json",
3119
3077
  "loop-agent inspect --repo-root .",
3120
- "bash scripts/check-repo.sh",
3121
3078
  ];
3122
3079
  const existingTask = modelMergeTasks.findIndex((task) => task.path === "harness.json");
3123
3080
  if (existingTask >= 0)
@@ -3137,8 +3094,13 @@ export async function checkInitUpdate(input) {
3137
3094
  entry: { path: "harness.json", mode: "generated" },
3138
3095
  });
3139
3096
  if (desired.content !== undefined) {
3140
- const desiredHarness = JSON.parse(desired.content);
3141
- const reconciled = reconcileHarnessStructure(harness, desiredHarness);
3097
+ const template = await readJsonIfExists(path.join(assetRoot, "harness.json"));
3098
+ const reconciled = buildHarness({
3099
+ existing: harness,
3100
+ template,
3101
+ projectName,
3102
+ governanceRoot,
3103
+ });
3142
3104
  if (!isDeepStrictEqual(reconciled, harness)) {
3143
3105
  deterministicActions.push({
3144
3106
  type: "reconcile-harness-structure",
@@ -3166,6 +3128,7 @@ export async function checkInitUpdate(input) {
3166
3128
  modelReadiness?.status === "reselection-required") {
3167
3129
  const state = currentState.files["harness.json"];
3168
3130
  const task = modelMergeTaskFor("harness.json", state, allPaths, recordedState);
3131
+ task.purpose = "pi-model-matrix-selection";
3169
3132
  task.reason =
3170
3133
  modelReadiness.status === "selection-required"
3171
3134
  ? "harness.json has no complete Pi model matrix that resolves against the current Pi model catalog"
@@ -3174,14 +3137,13 @@ export async function checkInitUpdate(input) {
3174
3137
  `Preserve these currently resolvable tiers byte-for-byte: ${modelReadiness.preserveTiers.join(", ") || "none"}.`,
3175
3138
  `Select replacements only for: ${modelReadiness.reselectTiers.join(", ")}.`,
3176
3139
  "Choose replacements from eligibleReferences using target-project needs, capability, context window, latency, and cost; tiers may intentionally share a model.",
3177
- "Apply the complete matrix through init update --apply-safe with all three tier flags so code can revalidate it; valid existing tiers must keep their current effective reference.",
3140
+ "Write the complete matrix directly to harness.json; do not run init update because this task authorizes only harness.json. The controller will revalidate all three tiers on continue.",
3178
3141
  "Do not add credentials or raw Pi configuration to harness.json.",
3179
3142
  ];
3180
3143
  task.verification = [
3181
3144
  "loop-agent init model-catalog --repo-root . --json",
3182
3145
  "loop-agent init check-update --repo-root . --json",
3183
3146
  "loop-agent init doctor --repo-root .",
3184
- "bash scripts/check-repo.sh",
3185
3147
  ];
3186
3148
  const existingTask = modelMergeTasks.findIndex((candidate) => candidate.path === "harness.json");
3187
3149
  if (existingTask >= 0)
@@ -3203,6 +3165,34 @@ export async function checkInitUpdate(input) {
3203
3165
  reason,
3204
3166
  });
3205
3167
  }
3168
+ let legacyAudit;
3169
+ if (input.legacyAudit && recordedState) {
3170
+ legacyAudit = await auditLegacyInitSurface({
3171
+ repoRoot,
3172
+ assetRoot,
3173
+ surface: recordedState,
3174
+ });
3175
+ for (const candidate of legacyAudit.candidates) {
3176
+ if (candidate.automaticAction && !deterministicActions.some((action) => action.path === candidate.path)) {
3177
+ deterministicActions.push({
3178
+ type: "remove-owned-file",
3179
+ path: candidate.path,
3180
+ expectedSha256: candidate.rawSha256,
3181
+ candidateId: candidate.candidateId,
3182
+ evidenceClass: candidate.evidenceClass,
3183
+ reason: candidate.reason,
3184
+ });
3185
+ }
3186
+ else if (!candidate.terminalDisposition && !candidate.automaticAction && !humanDecisions.some((decision) => decision.path === candidate.path)) {
3187
+ humanDecisions.push(legacyDecision(candidate));
3188
+ }
3189
+ }
3190
+ }
3191
+ const legacyCandidatePaths = new Set(legacyAudit?.candidates.map((candidate) => candidate.path) ?? []);
3192
+ const blockingModelMerge = modelMergeTasks.some((task) => task.path !== "harness.json" || modelReadiness?.status !== "ready");
3193
+ const coreBlocked = deterministicActions.some((action) => !legacyCandidatePaths.has(action.path)) ||
3194
+ blockingModelMerge ||
3195
+ humanDecisions.some((decision) => !decision.candidateId);
3206
3196
  const partial = {
3207
3197
  repoRoot,
3208
3198
  controllerVersion: currentState.controllerVersion,
@@ -3210,6 +3200,9 @@ export async function checkInitUpdate(input) {
3210
3200
  deterministicActions,
3211
3201
  modelMergeTasks,
3212
3202
  humanDecisions,
3203
+ coreState: coreBlocked ? "blocked" : "ready",
3204
+ migrationState: legacyAudit?.migrationState ?? recordedState?.legacyAudit?.migrationState ?? "clean",
3205
+ ...(legacyAudit ? { legacyAudit } : {}),
3213
3206
  ...(modelReadiness ? { modelReadiness } : {}),
3214
3207
  summary: {
3215
3208
  missing: deterministicActions.filter((action) => action.type !== "bootstrap-surface").length,
@@ -3234,6 +3227,16 @@ export async function checkInitUpdate(input) {
3234
3227
  },
3235
3228
  };
3236
3229
  }
3230
+ function legacyDecision(candidate) {
3231
+ return {
3232
+ path: candidate.path,
3233
+ reason: candidate.reason,
3234
+ candidateId: candidate.candidateId,
3235
+ expectedSha256: candidate.rawSha256,
3236
+ evidenceClass: candidate.evidenceClass,
3237
+ consumers: candidate.consumers,
3238
+ };
3239
+ }
3237
3240
  async function applySafeAction(input) {
3238
3241
  if (input.action.type === "merge-pi-project-settings") {
3239
3242
  return (await applyProjectPiSettingsMerge({ repoRoot: input.repoRoot })).wrote === true;
@@ -3329,6 +3332,13 @@ async function applySafeAction(input) {
3329
3332
  return true;
3330
3333
  }
3331
3334
  if (input.action.type === "remove-owned-file") {
3335
+ if (input.action.candidateId && input.action.expectedSha256) {
3336
+ return ((await removeContainedRegularFileWithSha256Cas({
3337
+ repoRoot: input.repoRoot,
3338
+ relativePath: input.action.path,
3339
+ expectedSha256: input.action.expectedSha256,
3340
+ })) === "removed");
3341
+ }
3332
3342
  const target = path.join(input.repoRoot, input.action.path);
3333
3343
  if (!(await exists(target)))
3334
3344
  return false;
@@ -3339,6 +3349,28 @@ async function applySafeAction(input) {
3339
3349
  await rm(target, { force: true });
3340
3350
  return true;
3341
3351
  }
3352
+ if (input.action.type === "strip-managed-block") {
3353
+ const target = path.join(input.repoRoot, input.action.path);
3354
+ if (!(await exists(target)))
3355
+ return false;
3356
+ const current = await readFile(target, "utf-8");
3357
+ const startMarker = input.action.path === ".gitignore"
3358
+ ? GITIGNORE_BLOCK_START
3359
+ : MANAGED_BLOCK_START;
3360
+ const endMarker = input.action.path === ".gitignore"
3361
+ ? GITIGNORE_BLOCK_END
3362
+ : MANAGED_BLOCK_END;
3363
+ const start = current.indexOf(startMarker);
3364
+ const end = current.indexOf(endMarker, start + startMarker.length);
3365
+ if (start < 0 || end < start)
3366
+ return false;
3367
+ const next = `${current.slice(0, start)}${current.slice(end + endMarker.length)}`;
3368
+ if (next.trim().length === 0)
3369
+ await rm(target, { force: true });
3370
+ else
3371
+ await writeFile(target, next, "utf-8");
3372
+ return true;
3373
+ }
3342
3374
  if (input.action.type === "reconcile-harness-structure") {
3343
3375
  const target = path.join(input.repoRoot, "harness.json");
3344
3376
  if (!(await exists(target)))
@@ -3356,7 +3388,13 @@ async function applySafeAction(input) {
3356
3388
  });
3357
3389
  if (desired.content === undefined)
3358
3390
  return false;
3359
- const next = reconcileHarnessStructure(current, JSON.parse(desired.content));
3391
+ const template = await readJsonIfExists(path.join(assetRoot, "harness.json"));
3392
+ const next = buildHarness({
3393
+ existing: current,
3394
+ template,
3395
+ projectName: input.projectName,
3396
+ governanceRoot: input.governanceRoot,
3397
+ });
3360
3398
  if (isDeepStrictEqual(next, current))
3361
3399
  return false;
3362
3400
  await writeFile(target, `${JSON.stringify(next, null, 2)}\n`, "utf-8");
@@ -3421,6 +3459,13 @@ async function applySafeAction(input) {
3421
3459
  await writeFile(target, desired.content, "utf-8");
3422
3460
  return true;
3423
3461
  }
3462
+ if (input.action.type === "replace-owned-file") {
3463
+ if (input.action.expectedSha256 &&
3464
+ (await fileSha256IfExists(target)) !== input.action.expectedSha256)
3465
+ return false;
3466
+ await writeFile(target, desired.content, "utf-8");
3467
+ return true;
3468
+ }
3424
3469
  if (await exists(target))
3425
3470
  return false;
3426
3471
  await writeFile(target, desired.content, "utf-8");
@@ -3435,7 +3480,6 @@ export async function applyInitUpdate(input) {
3435
3480
  });
3436
3481
  const applied = [];
3437
3482
  const skipped = [];
3438
- const clientRecoveryMode = input.clientRecovery ?? "auto";
3439
3483
  const requestedModelMatrix = input.modelMatrix ??
3440
3484
  (input.model
3441
3485
  ? { LOW: input.model, MED: input.model, HIGH: input.model }
@@ -3497,6 +3541,8 @@ export async function applyInitUpdate(input) {
3497
3541
  }
3498
3542
  if (input.applySafe) {
3499
3543
  const existingSurface = await readExistingSurfaceState(repoRoot);
3544
+ const actionReceipts = [];
3545
+ const dispositions = [];
3500
3546
  // Preserve source strength: recorded stays recorded so unchanged owned files
3501
3547
  // remain deterministic refresh candidates; bootstrap/inferred stays inferred.
3502
3548
  const preservedStateKind = existingSurface?.stateKind === "recorded"
@@ -3506,9 +3552,8 @@ export async function applyInitUpdate(input) {
3506
3552
  repoRoot,
3507
3553
  projectName,
3508
3554
  governanceRoot,
3509
- clientRecovery: clientRecoveryMode,
3510
- homeDir: input.homeDir,
3511
3555
  modelCatalog: input.modelCatalog,
3556
+ legacyAudit: input.legacyAudit,
3512
3557
  });
3513
3558
  for (const action of report.deterministicActions) {
3514
3559
  if (action.type === "bootstrap-surface") {
@@ -3518,8 +3563,35 @@ export async function applyInitUpdate(input) {
3518
3563
  // The report was produced immediately before this batch. Each action also
3519
3564
  // performs its own target check; missing-file writes refuse existing paths,
3520
3565
  // while managed blocks merge into the latest user-authored content.
3521
- if (await applySafeAction({ repoRoot, projectName, governanceRoot, action }))
3566
+ const beforeSha256 = await fileSha256IfExists(path.join(repoRoot, action.path));
3567
+ if (await applySafeAction({ repoRoot, projectName, governanceRoot, action })) {
3522
3568
  applied.push(action);
3569
+ const afterSha256 = await fileSha256IfExists(path.join(repoRoot, action.path));
3570
+ actionReceipts.push({
3571
+ type: action.type,
3572
+ path: action.path,
3573
+ ...(beforeSha256 ? { beforeSha256 } : {}),
3574
+ ...(afterSha256 ? { afterSha256 } : {}),
3575
+ appliedAt: new Date().toISOString(),
3576
+ });
3577
+ if (action.type === "remove-owned-file" ||
3578
+ action.type === "strip-managed-block") {
3579
+ const previous = existingSurface?.files[action.path];
3580
+ if ((previous || action.candidateId) && existingSurface) {
3581
+ dispositions.push({
3582
+ path: action.path,
3583
+ disposition: "removed",
3584
+ previousMode: previous?.mode ?? "copied",
3585
+ ...(previous?.currentSha256 || action.expectedSha256
3586
+ ? { recordedSha256: previous?.currentSha256 ?? action.expectedSha256 }
3587
+ : {}),
3588
+ ...(afterSha256 ? { resultSha256: afterSha256 } : {}),
3589
+ controllerVersion: existingSurface.controllerVersion,
3590
+ recordedAt: new Date().toISOString(),
3591
+ });
3592
+ }
3593
+ }
3594
+ }
3523
3595
  else
3524
3596
  skipped.push(action);
3525
3597
  }
@@ -3529,14 +3601,11 @@ export async function applyInitUpdate(input) {
3529
3601
  governanceRoot,
3530
3602
  stateKind: preservedStateKind,
3531
3603
  preserveOwnershipFrom: existingSurface,
3532
- });
3533
- }
3534
- // Pi user config is only mutated with explicit --client-recovery=user.
3535
- // Do not reinstall the project plugin here — that would bypass ownership and
3536
- // clobber user-modified plugins; plugin updates stay on deterministic actions.
3537
- if (clientRecoveryMode === "user") {
3538
- await applyPiRetryMerge({
3539
- homeDir: input.homeDir ?? os.homedir(),
3604
+ dispositions,
3605
+ actionReceipts,
3606
+ ...(report.legacyAudit
3607
+ ? { legacyAudit: legacyAuditReceipt(report.legacyAudit, applied.filter((action) => Boolean(action.candidateId)).length) }
3608
+ : {}),
3540
3609
  });
3541
3610
  }
3542
3611
  return {
@@ -3546,12 +3615,313 @@ export async function applyInitUpdate(input) {
3546
3615
  repoRoot,
3547
3616
  projectName,
3548
3617
  governanceRoot,
3549
- clientRecovery: clientRecoveryMode,
3550
- homeDir: input.homeDir,
3551
3618
  modelCatalog: input.modelCatalog,
3619
+ legacyAudit: input.legacyAudit,
3552
3620
  }),
3553
3621
  };
3554
3622
  }
3623
+ function canonicalInitAuthorityJson(value) {
3624
+ if (value === null || typeof value !== "object")
3625
+ return JSON.stringify(value);
3626
+ if (Array.isArray(value)) {
3627
+ return `[${value.map(canonicalInitAuthorityJson).join(",")}]`;
3628
+ }
3629
+ const record = value;
3630
+ return `{${Object.keys(record)
3631
+ .sort()
3632
+ .map((key) => `${JSON.stringify(key)}:${canonicalInitAuthorityJson(record[key])}`)
3633
+ .join(",")}}`;
3634
+ }
3635
+ async function assertInitDecisionResumeAuthority(input) {
3636
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(input.authority.runId) ||
3637
+ !/^[a-f0-9]{64}$/.test(input.authority.pendingSha256)) {
3638
+ throw new Error("init decision resume authority is invalid");
3639
+ }
3640
+ const repoRoot = await realpath(input.repoRoot).catch(() => {
3641
+ throw new Error("init decision resume authority requires a readable Git repository");
3642
+ });
3643
+ const marker = path.join(repoRoot, ".git");
3644
+ const markerStat = await lstat(marker).catch(() => undefined);
3645
+ let gitDirectory;
3646
+ if (markerStat?.isDirectory()) {
3647
+ gitDirectory = await realpath(marker);
3648
+ }
3649
+ else if (markerStat?.isFile()) {
3650
+ const text = await readFile(marker, "utf-8").catch(() => "");
3651
+ const match = /^gitdir:\s*(.+?)\s*\r?\n?$/.exec(text);
3652
+ if (!match?.[1]) {
3653
+ throw new Error("init decision resume authority rejected an invalid Git worktree file");
3654
+ }
3655
+ gitDirectory = await realpath(path.resolve(path.dirname(marker), match[1]));
3656
+ }
3657
+ else {
3658
+ throw new Error("init decision resume authority requires a Git repository");
3659
+ }
3660
+ const anchorRoot = await realpath(path.join(gitDirectory, "loop-agent-init-upgrades")).catch(() => {
3661
+ throw new Error("init decision resume authority anchor is missing");
3662
+ });
3663
+ const relativeAnchorRoot = path.relative(gitDirectory, anchorRoot);
3664
+ if (relativeAnchorRoot === "" ||
3665
+ relativeAnchorRoot === ".." ||
3666
+ relativeAnchorRoot.startsWith(`..${path.sep}`) ||
3667
+ path.isAbsolute(relativeAnchorRoot)) {
3668
+ throw new Error("init decision resume authority anchor escapes Git directory");
3669
+ }
3670
+ const anchorPath = path.join(anchorRoot, `${sha256Text(`${repoRoot}\0${input.authority.runId}`)}.json`);
3671
+ let anchor;
3672
+ try {
3673
+ anchor = JSON.parse(await readFile(anchorPath, "utf-8"));
3674
+ }
3675
+ catch {
3676
+ throw new Error("init decision resume authority anchor is missing or invalid");
3677
+ }
3678
+ if (!isRecord(anchor) || anchor.schemaVersion !== 1) {
3679
+ throw new Error("init decision resume authority anchor is invalid");
3680
+ }
3681
+ const decisionAuthority = anchor.decisionAuthority;
3682
+ if (!isRecord(decisionAuthority) || !isRecord(decisionAuthority.pending)) {
3683
+ throw new Error("init decision resume authority is not pending");
3684
+ }
3685
+ const pending = decisionAuthority.pending;
3686
+ if (anchor.repoRoot !== repoRoot ||
3687
+ anchor.runId !== input.authority.runId ||
3688
+ decisionAuthority.pendingSha256 !== input.authority.pendingSha256 ||
3689
+ sha256Text(canonicalInitAuthorityJson(pending)) !==
3690
+ input.authority.pendingSha256 ||
3691
+ pending.schemaVersion !== 1 ||
3692
+ pending.repoRoot !== repoRoot ||
3693
+ pending.runId !== input.authority.runId ||
3694
+ !isRecord(pending.document) ||
3695
+ pending.document.schemaVersion !== 1 ||
3696
+ pending.document.runId !== input.authority.runId ||
3697
+ !Array.isArray(pending.document.decisions) ||
3698
+ !isDeepStrictEqual(pending.document.decisions, input.actions)) {
3699
+ throw new Error("init decision resume authority does not match pending actions");
3700
+ }
3701
+ }
3702
+ export async function applyInitDecisionBoundActions(input) {
3703
+ const repoRoot = path.resolve(input.repoRoot);
3704
+ if (input.resumeAuthority) {
3705
+ await assertInitDecisionResumeAuthority({
3706
+ repoRoot,
3707
+ actions: input.actions,
3708
+ authority: input.resumeAuthority,
3709
+ });
3710
+ }
3711
+ const { projectName, governanceRoot } = await resolveInitProjectContext({
3712
+ repoRoot,
3713
+ });
3714
+ const existingSurface = await readExistingSurfaceState(repoRoot);
3715
+ if (!existingSurface) {
3716
+ throw new Error("init decision-bound actions require an existing init surface");
3717
+ }
3718
+ const report = await checkInitUpdate({ repoRoot, legacyAudit: true });
3719
+ const pending = new Map(report.humanDecisions.map((decision) => [decision.path, decision]));
3720
+ const seen = new Set();
3721
+ const validated = [];
3722
+ const assetRoot = await findPackageRoot();
3723
+ for (const action of input.actions) {
3724
+ const normalized = normalizeRelativePath(action.path);
3725
+ if (normalized !== action.path ||
3726
+ path.isAbsolute(action.path) ||
3727
+ action.path.startsWith("../") ||
3728
+ action.path.includes("/../")) {
3729
+ throw new Error(`invalid init decision path: ${action.path}`);
3730
+ }
3731
+ if (seen.has(action.path)) {
3732
+ throw new Error(`duplicate init decision path: ${action.path}`);
3733
+ }
3734
+ seen.add(action.path);
3735
+ const pendingDecision = pending.get(action.path);
3736
+ if (!pendingDecision && !input.resumeAuthority) {
3737
+ throw new Error(`init decision is not currently pending: ${action.path}`);
3738
+ }
3739
+ const isBridge = action.path === ".agents/skills/loop-agent/SKILL.md";
3740
+ const isLegacyCandidate = Boolean(action.candidateId);
3741
+ if (isLegacyCandidate) {
3742
+ if (!input.resumeAuthority &&
3743
+ (!pendingDecision?.candidateId ||
3744
+ pendingDecision.candidateId !== action.candidateId ||
3745
+ pendingDecision.expectedSha256 !== action.expectedSha256)) {
3746
+ throw new Error(`stale or mismatched legacy init candidate decision: ${action.path}`);
3747
+ }
3748
+ if (action.disposition !== "retain-project-content" &&
3749
+ action.disposition !== "preserve-unproven" &&
3750
+ action.disposition !== "delete-listed-file") {
3751
+ throw new Error(`unsupported legacy init disposition for ${action.path}: ${action.disposition}`);
3752
+ }
3753
+ if (action.disposition === "delete-listed-file" &&
3754
+ (pendingDecision?.consumers?.length ?? 0) > 0) {
3755
+ throw new Error(`legacy init candidate still has consumers and cannot be deleted: ${action.path}`);
3756
+ }
3757
+ }
3758
+ else if ((isBridge && action.disposition !== "replace-with-bridge") ||
3759
+ (!isBridge && action.disposition !== "detach-as-project-content")) {
3760
+ throw new Error(`unsupported init decision disposition for ${action.path}: ${action.disposition}`);
3761
+ }
3762
+ const absolutePath = path.resolve(repoRoot, action.path);
3763
+ const relative = path.relative(repoRoot, absolutePath);
3764
+ if (relative.length === 0 ||
3765
+ relative.startsWith(`..${path.sep}`) ||
3766
+ path.isAbsolute(relative)) {
3767
+ throw new Error(`init decision path escapes the repository: ${action.path}`);
3768
+ }
3769
+ const inspected = await inspectContainedRegularFile(repoRoot, action.path);
3770
+ if (!inspected &&
3771
+ input.resumeAuthority &&
3772
+ isLegacyCandidate &&
3773
+ action.disposition === "delete-listed-file") {
3774
+ validated.push({
3775
+ action,
3776
+ absolutePath,
3777
+ currentSha256: action.expectedSha256,
3778
+ alreadyAbsent: true,
3779
+ });
3780
+ continue;
3781
+ }
3782
+ if (!inspected || "conflict" in inspected) {
3783
+ throw new Error(`init decision target is not a regular file: ${action.path}`);
3784
+ }
3785
+ const currentSha256 = sha256Buffer(inspected.bytes);
3786
+ let desiredBridgeContent;
3787
+ let desiredBridgeSha256;
3788
+ if (isBridge) {
3789
+ const desired = await buildDesiredSurfaceContent({
3790
+ assetRoot,
3791
+ repoRoot,
3792
+ projectName,
3793
+ governanceRoot,
3794
+ entry: {
3795
+ path: ".agents/skills/loop-agent/SKILL.md",
3796
+ mode: "copied",
3797
+ },
3798
+ });
3799
+ if (desired.content === undefined) {
3800
+ throw new Error("AGENT_BRIDGE_RESOURCE_MISSING: bundled loop-agent bridge is unavailable");
3801
+ }
3802
+ desiredBridgeContent = desired.content;
3803
+ desiredBridgeSha256 = sha256Text(desired.content);
3804
+ }
3805
+ if (currentSha256 !== action.expectedSha256 &&
3806
+ !(input.resumeAuthority && desiredBridgeSha256 === currentSha256)) {
3807
+ throw new Error(`stale init decision for ${action.path}: expected ${action.expectedSha256}, observed ${currentSha256}`);
3808
+ }
3809
+ validated.push({
3810
+ action,
3811
+ absolutePath,
3812
+ currentSha256,
3813
+ desiredBridgeContent,
3814
+ desiredBridgeSha256,
3815
+ });
3816
+ }
3817
+ const dispositionReceipts = [];
3818
+ const actionReceipts = [];
3819
+ const results = [];
3820
+ for (const entry of validated) {
3821
+ let resultSha256 = entry.currentSha256;
3822
+ if (entry.action.disposition === "replace-with-bridge") {
3823
+ if (!entry.desiredBridgeContent || !entry.desiredBridgeSha256) {
3824
+ throw new Error("AGENT_BRIDGE_RESOURCE_MISSING: bundled loop-agent bridge is unavailable");
3825
+ }
3826
+ resultSha256 = entry.desiredBridgeSha256;
3827
+ if (entry.currentSha256 !== resultSha256) {
3828
+ await writeFile(entry.absolutePath, entry.desiredBridgeContent, "utf-8");
3829
+ }
3830
+ const alreadyRecorded = existingSurface.actionReceipts?.some((receipt) => receipt.type === "replace-owned-file" &&
3831
+ receipt.path === entry.action.path &&
3832
+ receipt.beforeSha256 === entry.action.expectedSha256 &&
3833
+ receipt.afterSha256 === resultSha256);
3834
+ if (!alreadyRecorded) {
3835
+ actionReceipts.push({
3836
+ type: "replace-owned-file",
3837
+ path: entry.action.path,
3838
+ beforeSha256: entry.action.expectedSha256,
3839
+ afterSha256: resultSha256,
3840
+ appliedAt: new Date().toISOString(),
3841
+ });
3842
+ }
3843
+ }
3844
+ else if (entry.action.disposition === "delete-listed-file") {
3845
+ if (!entry.alreadyAbsent) {
3846
+ const removal = await removeContainedRegularFileWithSha256Cas({
3847
+ repoRoot,
3848
+ relativePath: entry.action.path,
3849
+ expectedSha256: entry.action.expectedSha256,
3850
+ });
3851
+ if (removal === "rejected") {
3852
+ throw new Error(`legacy init decision target changed or escaped containment before deletion: ${entry.action.path}`);
3853
+ }
3854
+ }
3855
+ dispositionReceipts.push({
3856
+ path: entry.action.path,
3857
+ disposition: "removed",
3858
+ previousMode: existingSurface.files[entry.action.path]?.mode ?? "copied",
3859
+ recordedSha256: entry.action.expectedSha256,
3860
+ controllerVersion: existingSurface.controllerVersion,
3861
+ recordedAt: new Date().toISOString(),
3862
+ });
3863
+ actionReceipts.push({
3864
+ type: "remove-owned-file",
3865
+ path: entry.action.path,
3866
+ beforeSha256: entry.action.expectedSha256,
3867
+ appliedAt: new Date().toISOString(),
3868
+ });
3869
+ }
3870
+ else {
3871
+ const disposition = entry.action.disposition === "retain-project-content"
3872
+ ? "retained-project-content"
3873
+ : entry.action.disposition === "preserve-unproven"
3874
+ ? "preserved-unproven-legacy"
3875
+ : "detached-as-project-content";
3876
+ const alreadyRecorded = existingSurface.dispositions?.some((receipt) => receipt.path === entry.action.path &&
3877
+ receipt.disposition === disposition &&
3878
+ receipt.recordedSha256 === entry.action.expectedSha256 &&
3879
+ receipt.resultSha256 === resultSha256);
3880
+ if (!alreadyRecorded) {
3881
+ dispositionReceipts.push({
3882
+ path: entry.action.path,
3883
+ disposition,
3884
+ previousMode: existingSurface.files[entry.action.path]?.mode ?? "copied",
3885
+ recordedSha256: entry.action.expectedSha256,
3886
+ resultSha256,
3887
+ controllerVersion: existingSurface.controllerVersion,
3888
+ recordedAt: new Date().toISOString(),
3889
+ });
3890
+ }
3891
+ }
3892
+ results.push({
3893
+ path: entry.action.path,
3894
+ disposition: entry.action.disposition,
3895
+ expectedSha256: entry.action.expectedSha256,
3896
+ resultSha256,
3897
+ ...(entry.action.candidateId
3898
+ ? { candidateId: entry.action.candidateId }
3899
+ : {}),
3900
+ });
3901
+ }
3902
+ await writeInitSurfaceState({
3903
+ repoRoot,
3904
+ projectName,
3905
+ governanceRoot,
3906
+ stateKind: existingSurface.stateKind,
3907
+ preserveOwnershipFrom: existingSurface,
3908
+ dispositions: dispositionReceipts,
3909
+ actionReceipts,
3910
+ });
3911
+ const postDecisionReport = await checkInitUpdate({ repoRoot, legacyAudit: true });
3912
+ if (postDecisionReport.legacyAudit) {
3913
+ const updatedSurface = await readExistingSurfaceState(repoRoot);
3914
+ await writeInitSurfaceState({
3915
+ repoRoot,
3916
+ projectName,
3917
+ governanceRoot,
3918
+ stateKind: existingSurface.stateKind,
3919
+ preserveOwnershipFrom: updatedSurface,
3920
+ legacyAudit: legacyAuditReceipt(postDecisionReport.legacyAudit, validated.filter((entry) => entry.action.disposition === "delete-listed-file").length),
3921
+ });
3922
+ }
3923
+ return results;
3924
+ }
3555
3925
  function formatClientRecoverySummary(report) {
3556
3926
  if (!report.clientRecovery?.pi)
3557
3927
  return [];
@@ -3577,6 +3947,8 @@ function formatCheckUpdateText(report) {
3577
3947
  `loop-agent init update check for ${report.repoRoot}`,
3578
3948
  `controllerVersion: ${report.controllerVersion}`,
3579
3949
  `surfaceState: ${report.surfaceState}`,
3950
+ `coreState: ${report.coreState}`,
3951
+ `migrationState: ${report.migrationState}`,
3580
3952
  `deterministicActions: ${report.deterministicActions.length}`,
3581
3953
  `modelMergeTasks: ${report.modelMergeTasks.length}`,
3582
3954
  `humanDecisions: ${report.humanDecisions.length}`,
@@ -3594,6 +3966,8 @@ function formatCheckUpdateMarkdown(report) {
3594
3966
  `- repoRoot: \`${report.repoRoot}\``,
3595
3967
  `- controllerVersion: \`${report.controllerVersion}\``,
3596
3968
  `- surfaceState: \`${report.surfaceState}\``,
3969
+ `- coreState: \`${report.coreState}\``,
3970
+ `- migrationState: \`${report.migrationState}\``,
3597
3971
  ...(report.modelReadiness
3598
3972
  ? [
3599
3973
  "",
@@ -3635,7 +4009,6 @@ export async function runInitDoctor(input) {
3635
4009
  try {
3636
4010
  const manifest = await loadHarnessManifest(repoRoot);
3637
4011
  add("harness.json", manifest.adapter === "loop-agent" || manifest.project === "loop-agent", `project=${manifest.project}`);
3638
- add("governance root", await exists(path.join(repoRoot, manifest.governanceRoot, "README.md")), manifest.governanceRoot);
3639
4012
  if (input.modelCatalog) {
3640
4013
  const readiness = assessInitPiModelReadiness(isRecord(manifest.executors?.pi)
3641
4014
  ? manifest.executors.pi
@@ -3648,31 +4021,14 @@ export async function runInitDoctor(input) {
3648
4021
  catch (error) {
3649
4022
  add("harness.json", false, error instanceof Error ? error.message : String(error));
3650
4023
  }
3651
- const agents = path.join(repoRoot, "AGENTS.md");
3652
- add("AGENTS.md loop-agent block", (await exists(agents)) &&
3653
- (await readFile(agents, "utf-8")).includes(MANAGED_BLOCK_START), "managed block present");
3654
- const readme = path.join(repoRoot, "README.md");
3655
- add("README loop-agent block", (await exists(readme)) &&
3656
- (await readFile(readme, "utf-8")).includes(MANAGED_BLOCK_START), "managed block present");
3657
- add("repo-local skills", await exists(path.join(repoRoot, ".agents", "skills", "loop-agent", "SKILL.md")), ".agents/skills/loop-agent/SKILL.md");
4024
+ add("external Agent bridge", await exists(path.join(repoRoot, ".agents", "skills", "loop-agent", "SKILL.md")), ".agents/skills/loop-agent/SKILL.md");
3658
4025
  const gitignorePath = path.join(repoRoot, ".gitignore");
3659
4026
  const gitignoreContent = (await exists(gitignorePath))
3660
4027
  ? await readFile(gitignorePath, "utf-8")
3661
4028
  : "";
3662
4029
  add("gitignore loop-agent block", gitignoreContent.includes(GITIGNORE_BLOCK_START) &&
3663
4030
  gitignoreContent.includes(".harness/"), ".gitignore managed runtime ignores");
3664
- const requiredScripts = Object.keys(INIT_SCRIPT_FILES);
3665
- const missingScripts = [];
3666
- for (const script of requiredScripts) {
3667
- if (!(await exists(path.join(repoRoot, script))))
3668
- missingScripts.push(script);
3669
- }
3670
- add("script matrix", missingScripts.length === 0, missingScripts.length === 0
3671
- ? `${requiredScripts.length} scripts`
3672
- : `missing: ${missingScripts.join(", ")}`);
3673
- add("compat prompts", (await exists(path.join(repoRoot, ".harness", "prompts", "analyze.md"))) &&
3674
- (await exists(path.join(repoRoot, ".harness", "prompts", "plan.md"))), ".harness/prompts/analyze.md");
3675
- add("harness runtime dirs", await exists(path.join(repoRoot, ".harness", "dag-runs", "active")), ".harness/dag-runs/active");
4031
+ add("init surface state", await exists(path.join(repoRoot, INIT_SURFACE_STATE_PATH)), INIT_SURFACE_STATE_PATH);
3676
4032
  return {
3677
4033
  ok: checks.every((check) => check.ok),
3678
4034
  repoRoot,
@@ -3724,25 +4080,27 @@ function parseInitArgs(repoRoot, args) {
3724
4080
  let subcommand;
3725
4081
  let projectName;
3726
4082
  let governanceRoot;
3727
- let profile = "full";
3728
4083
  let merge = true;
3729
4084
  let provider;
3730
4085
  let model;
3731
4086
  let lowModel;
3732
4087
  let medModel;
3733
4088
  let highModel;
3734
- let clientRecovery = "auto";
3735
4089
  let json = false;
3736
4090
  let markdown = false;
3737
4091
  let bootstrapSurface = false;
3738
4092
  let applySafe = false;
4093
+ let legacyAudit = false;
3739
4094
  let runId;
3740
4095
  let upgradeStatus = false;
3741
4096
  let upgradeContinue = false;
3742
4097
  let upgradeReport = false;
3743
4098
  let versionChoice;
4099
+ let decisionFile;
3744
4100
  for (let i = 0; i < args.length; i += 1) {
3745
4101
  const arg = args[i];
4102
+ if (arg === undefined)
4103
+ break;
3746
4104
  if ((arg === "instructions" ||
3747
4105
  arg === "doctor" ||
3748
4106
  arg === "model-catalog" ||
@@ -3762,10 +4120,8 @@ function parseInitArgs(repoRoot, args) {
3762
4120
  governanceRoot = args[++i] ?? governanceRoot;
3763
4121
  else if (arg.startsWith("--governance-root="))
3764
4122
  governanceRoot = arg.slice("--governance-root=".length);
3765
- else if (arg === "--profile")
3766
- profile = args[++i] ?? profile;
3767
- else if (arg.startsWith("--profile="))
3768
- profile = arg.slice("--profile=".length);
4123
+ else if (arg === "--profile" || arg.startsWith("--profile="))
4124
+ throw new Error("INIT_PROFILE_REMOVED: minimal initialization is now the only init architecture; remove --profile");
3769
4125
  else if (arg === "--merge")
3770
4126
  merge = true;
3771
4127
  else if (arg === "--no-merge")
@@ -3790,10 +4146,9 @@ function parseInitArgs(repoRoot, args) {
3790
4146
  highModel = args[++i];
3791
4147
  else if (arg.startsWith("--high-model="))
3792
4148
  highModel = arg.slice("--high-model=".length);
3793
- else if (arg === "--client-recovery")
3794
- clientRecovery = parseClientRecoveryMode(args[++i]);
3795
- else if (arg.startsWith("--client-recovery="))
3796
- clientRecovery = parseClientRecoveryMode(arg.slice("--client-recovery=".length));
4149
+ else if (arg === "--client-recovery" ||
4150
+ arg.startsWith("--client-recovery="))
4151
+ throw new Error("INIT_CLIENT_RECOVERY_REMOVED: default init no longer installs client recovery files; remove --client-recovery (explicit client adapters are not available in this release)");
3797
4152
  else if (arg === "--json")
3798
4153
  json = true;
3799
4154
  else if (arg === "--markdown")
@@ -3802,6 +4157,8 @@ function parseInitArgs(repoRoot, args) {
3802
4157
  bootstrapSurface = true;
3803
4158
  else if (arg === "--apply-safe")
3804
4159
  applySafe = true;
4160
+ else if (arg === "--legacy-audit")
4161
+ legacyAudit = true;
3805
4162
  else if (arg === "--run-id")
3806
4163
  runId = args[++i];
3807
4164
  else if (arg.startsWith("--run-id="))
@@ -3816,13 +4173,15 @@ function parseInitArgs(repoRoot, args) {
3816
4173
  versionChoice = args[++i];
3817
4174
  else if (arg.startsWith("--version-choice="))
3818
4175
  versionChoice = arg.slice("--version-choice=".length);
4176
+ else if (arg === "--decision-file")
4177
+ decisionFile = args[++i];
4178
+ else if (arg.startsWith("--decision-file="))
4179
+ decisionFile = arg.slice("--decision-file=".length);
3819
4180
  else if (arg.startsWith("-"))
3820
4181
  throw new Error(`unknown init flag: ${arg}`);
3821
4182
  else
3822
4183
  throw new Error(`unexpected init argument: ${arg}`);
3823
4184
  }
3824
- if (profile !== "full" && profile !== "minimal")
3825
- throw new Error("init --profile must be full or minimal");
3826
4185
  if (versionChoice && !["current", "upgrade", "cancel", "retry"].includes(versionChoice)) {
3827
4186
  throw new Error("init upgrade --version-choice must be current|upgrade|cancel|retry");
3828
4187
  }
@@ -3838,22 +4197,23 @@ function parseInitArgs(repoRoot, args) {
3838
4197
  repoRoot,
3839
4198
  projectName,
3840
4199
  governanceRoot,
3841
- profile,
4200
+ profile: "minimal",
3842
4201
  merge,
3843
4202
  provider,
3844
4203
  model: normalizedModel,
3845
4204
  modelMatrix,
3846
- clientRecovery,
3847
4205
  subcommand,
3848
4206
  json,
3849
4207
  markdown,
3850
4208
  bootstrapSurface,
3851
4209
  applySafe,
4210
+ legacyAudit,
3852
4211
  runId,
3853
4212
  upgradeStatus,
3854
4213
  upgradeContinue,
3855
4214
  upgradeReport,
3856
4215
  versionChoice,
4216
+ decisionFile,
3857
4217
  };
3858
4218
  }
3859
4219
  async function discoverInitCatalogForRepo(repoRoot) {
@@ -3941,6 +4301,7 @@ export async function runInit(repoRoot, rawArgs, dependencies) {
3941
4301
  runId: parsed.runId,
3942
4302
  mode,
3943
4303
  versionChoice: parsed.versionChoice,
4304
+ decisionFile: parsed.decisionFile,
3944
4305
  readRuntimeActivity: dependencies.readRuntimeActivity,
3945
4306
  modelCatalog,
3946
4307
  });
@@ -3997,6 +4358,8 @@ function formatInitUpgradeResult(result) {
3997
4358
  `phase: ${result.phase}`,
3998
4359
  `modelMergeTasks: ${result.modelMergeTasks.length}`,
3999
4360
  `humanDecisions: ${result.humanDecisions.length}`,
4361
+ `coreState: ${result.coreState}`,
4362
+ `migrationState: ${result.migrationState}`,
4000
4363
  `next: ${result.nextAction}`,
4001
4364
  ].join("\n");
4002
4365
  }
@@ -4007,6 +4370,8 @@ function formatInitUpdateResult(result) {
4007
4370
  `skipped: ${result.skipped.length}`,
4008
4371
  `remaining deterministicActions: ${result.report.deterministicActions.length}`,
4009
4372
  `remaining modelMergeTasks: ${result.report.modelMergeTasks.length}`,
4373
+ `coreState: ${result.report.coreState}`,
4374
+ `migrationState: ${result.report.migrationState}`,
4010
4375
  "recommendedNext:",
4011
4376
  ...result.report.recommendedNext.map((item) => `- ${item}`),
4012
4377
  ].join("\n");
@@ -4030,14 +4395,11 @@ function formatReconcileResult(result) {
4030
4395
  }
4031
4396
  function formatInitResult(result) {
4032
4397
  return [
4033
- `Initialized loop-agent harness at ${result.repoRoot}`,
4398
+ `Initialized minimal loop-agent project surface at ${result.repoRoot}`,
4034
4399
  `project: ${result.projectName}`,
4035
- `governanceRoot: ${result.governanceRoot}`,
4036
- `profile: ${result.profile}`,
4037
4400
  `written: ${result.written.length}`,
4038
4401
  `skipped: ${result.skipped.length}`,
4039
4402
  "next: loop-agent init doctor --repo-root <target>",
4040
- `model-executed init: continue automatically by inspecting the target project, adapting README.md, ${result.governanceRoot}/verification-matrix.md, and scripts/ci-tests.sh when needed, then run inspect/docs audit/quick verification.`,
4041
4403
  ].join("\n");
4042
4404
  }
4043
4405
  export async function listInitializedFiles(repoRoot) {