@ornexus/neocortex 4.60.78 → 4.60.80

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 (247) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1206
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +214 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +443 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +260 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +338 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +358 -5
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.js +635 -2
  37. package/packages/client/dist/commands/invoke.js +7712 -143
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  39. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  40. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  42. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  43. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  44. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  45. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  47. package/packages/client/dist/commands/mutation-qa.js +220 -1
  48. package/packages/client/dist/commands/native-agent.js +136 -2
  49. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  50. package/packages/client/dist/commands/planning-generation.js +53 -1
  51. package/packages/client/dist/commands/planning-memory.js +40 -1
  52. package/packages/client/dist/commands/planning-research.js +42 -1
  53. package/packages/client/dist/commands/private-session.js +75 -1
  54. package/packages/client/dist/commands/property-qa.js +139 -1
  55. package/packages/client/dist/commands/qa-control.js +16 -1
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  58. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  59. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  60. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  66. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  67. package/packages/client/dist/commands/refactor-commit.js +399 -13
  68. package/packages/client/dist/commands/refactor-control.js +142 -3
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  70. package/packages/client/dist/commands/refactor-review.js +283 -5
  71. package/packages/client/dist/commands/refactor-root.js +588 -7
  72. package/packages/client/dist/commands/refresh-memory.d.ts +3 -1
  73. package/packages/client/dist/commands/refresh-memory.js +174 -3
  74. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  76. package/packages/client/dist/config/host-auth-broker.js +60 -1
  77. package/packages/client/dist/config/host-auth-reference.js +93 -1
  78. package/packages/client/dist/config/profile-directory.js +13 -1
  79. package/packages/client/dist/config/resolver-selection.js +278 -1
  80. package/packages/client/dist/config/secure-config.js +281 -12
  81. package/packages/client/dist/config.js +223 -2
  82. package/packages/client/dist/constants.js +25 -1
  83. package/packages/client/dist/context/context-collector.js +222 -2
  84. package/packages/client/dist/context/context-sanitizer.js +145 -1
  85. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  86. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  87. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  88. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  89. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  90. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  91. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  92. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  93. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  94. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  95. package/packages/client/dist/continuity/native-agent-types.js +105 -1
  96. package/packages/client/dist/continuity/outbox.js +117 -1
  97. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  98. package/packages/client/dist/continuity/sqlite-store.js +2612 -81
  99. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  100. package/packages/client/dist/errors/error-messages.js +258 -2
  101. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  102. package/packages/client/dist/evidence/collector.js +347 -1
  103. package/packages/client/dist/evidence/index.js +1 -1
  104. package/packages/client/dist/evidence/types.js +2 -0
  105. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  106. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  107. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  108. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  109. package/packages/client/dist/git/direct-yolo-checkpoint.js +1456 -4
  110. package/packages/client/dist/git/epic-operational-state.js +672 -2
  111. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  112. package/packages/client/dist/git/git-lifecycle-store.js +2188 -10
  113. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  114. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  115. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  116. package/packages/client/dist/git/neocortex-trailers.d.ts +26 -0
  117. package/packages/client/dist/git/neocortex-trailers.js +53 -0
  118. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  119. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  120. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  121. package/packages/client/dist/i18n/first-run.js +60 -2
  122. package/packages/client/dist/index.js +50 -1
  123. package/packages/client/dist/invocation/invoke-input.js +24 -1
  124. package/packages/client/dist/license/host-auth-recovery.js +401 -1
  125. package/packages/client/dist/license/index.js +5 -1
  126. package/packages/client/dist/license/license-client.js +337 -1
  127. package/packages/client/dist/machine/fingerprint.js +163 -2
  128. package/packages/client/dist/machine/index.js +5 -1
  129. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  130. package/packages/client/dist/memory/project-memory-writer.d.ts +16 -1
  131. package/packages/client/dist/memory/project-memory-writer.js +1117 -41
  132. package/packages/client/dist/memory/shared-project-memory-types.js +259 -2
  133. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -3
  134. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  135. package/packages/client/dist/migrations/project-identity.js +493 -7
  136. package/packages/client/dist/migrations/state-json.js +393 -4
  137. package/packages/client/dist/policy/architecture-policy.js +184 -2
  138. package/packages/client/dist/policy/index.js +7 -1
  139. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  140. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  141. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  142. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  143. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  144. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  145. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  146. package/packages/client/dist/private-execution/delivery.js +410 -13
  147. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  148. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  149. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  150. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  151. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  152. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  153. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  154. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  155. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  156. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  157. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  158. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  159. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  160. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  161. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  162. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  163. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  164. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  165. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  166. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  167. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  168. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  169. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  170. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  171. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  172. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  173. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  174. package/packages/client/dist/private-execution/session-lease.js +63 -1
  175. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  176. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  177. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  178. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  179. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  180. package/packages/client/dist/registry/registry-reconciliation.js +234 -1
  181. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  182. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  183. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  184. package/packages/client/dist/resilience/index.js +8 -1
  185. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  186. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  187. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  188. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  189. package/packages/client/dist/runner/binary.js +404 -1
  190. package/packages/client/dist/runner/cli.js +1571 -17
  191. package/packages/client/dist/runner/epic-background-dispatcher.js +124 -1
  192. package/packages/client/dist/runner/headless/adapters.js +49 -1
  193. package/packages/client/dist/runner/headless/background-root.js +85 -1
  194. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  195. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  196. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  197. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +111 -2
  198. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1464 -10
  199. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +357 -2
  200. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  201. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +274 -1
  202. package/packages/client/dist/runner/headless/managed-profile.js +149 -1
  203. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  204. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  205. package/packages/client/dist/runner/headless/resolver.js +231 -1
  206. package/packages/client/dist/runner/headless/run-yolo.js +886 -1
  207. package/packages/client/dist/runner/headless/run-yoloop.js +2586 -2
  208. package/packages/client/dist/runner/headless/types.js +575 -2
  209. package/packages/client/dist/runner/host-capacity.js +59 -1
  210. package/packages/client/dist/runner/local-console.js +396 -13
  211. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  212. package/packages/client/dist/runner/project-identity.js +106 -1
  213. package/packages/client/dist/runner/scheduler.js +995 -7
  214. package/packages/client/dist/runner-cli.js +18 -2
  215. package/packages/client/dist/state/invocation-shape.js +13 -1
  216. package/packages/client/dist/state/project-state-snapshot.js +1751 -1
  217. package/packages/client/dist/state/state-json-repair.js +785 -3
  218. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  219. package/packages/client/dist/telemetry/index.js +5 -1
  220. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  221. package/packages/client/dist/tier/index.js +5 -1
  222. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  223. package/packages/client/dist/types/index.js +38 -1
  224. package/packages/client/dist/version.js +27 -1
  225. package/packages/client/dist/yolo/change-evidence-collector.d.ts +1 -1
  226. package/packages/client/dist/yolo/change-evidence-collector.js +245 -1
  227. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  228. package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
  229. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  230. package/packages/client/dist/yoloop/index.js +8 -1
  231. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  232. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  233. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  234. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  235. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
  236. package/packages/shared/dist/yoloop/epic-terminal-git.js +12 -0
  237. package/targets-stubs/antigravity/gemini.md +1 -1
  238. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  239. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  240. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  241. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  242. package/targets-stubs/claude-code/neocortex.md +2 -2
  243. package/targets-stubs/codex/AGENTS.md +1 -1
  244. package/targets-stubs/cursor/agent.md +2 -2
  245. package/targets-stubs/gemini-cli/agent.md +2 -2
  246. package/targets-stubs/opencode/neocortex-root.md +1 -1
  247. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1 +1,1751 @@
1
- import{createHash as B}from"node:crypto";import{analyzeDependencyDag as C,StructuralDagError as y}from"./structural-dag-projection.js";import{classifyInvocationShapeV2 as O}from"./invocation-shape.js";const U=12,J=16,k=["active","archived","rolled-back","synthetic","orphan"],X=new Set(["in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","partial"]);function Q(r){return r==="STRUCTURAL_TARGET_NOT_FOUND"?"registration-missing":r==="STRUCTURAL_DEPENDENCY_CYCLE"?"dependency-cycle":"dependency-missing"}function Fe(r){const e=/^[a-f0-9]{64}$/,t=/^P[1-9][0-9]*(?:\.[0-9]+)*$/,i=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/;if(r.schemaVersion!=="EpicOperationalPublicProjection/1.0"||!e.test(r.repositoryFingerprint)||!e.test(r.identityHash)||!t.test(r.epicId)||!i.test(r.executionBranch)||!e.test(r.graphRevision)||!Number.isSafeInteger(r.storeRevision)||r.storeRevision<0||!Number.isSafeInteger(r.writerEpoch)||r.writerEpoch<1||r.runId!==null&&r.runId.length>128||r.runStatus!==null&&r.runStatus.length>32||r.runRevision!==null&&(!Number.isSafeInteger(r.runRevision)||r.runRevision<0)||r.snapshotHash!==null&&!e.test(r.snapshotHash)||!e.test(r.continuationSessionHash)||!e.test(r.pendingAuthorityHash)||!Number.isSafeInteger(r.pendingAuthorityCount)||r.pendingAuthorityCount<0||r.pendingAuthorityCount>1024||r.reasonCodes.length>16||r.reasonCodes.some(c=>!/^[a-z0-9][a-z0-9-]{0,79}$/.test(c))||r.publicSafe!==!0)throw new Error("epic-operational-projection-invalid");return Object.freeze({schemaVersion:r.schemaVersion,repositoryFingerprint:r.repositoryFingerprint,identityHash:r.identityHash,epicId:r.epicId,executionBranch:r.executionBranch,graphRevision:r.graphRevision,storeRevision:r.storeRevision,writerEpoch:r.writerEpoch,runId:r.runId,runStatus:r.runStatus,runRevision:r.runRevision,snapshotHash:r.snapshotHash,continuationSessionHash:r.continuationSessionHash,pendingAuthorityHash:r.pendingAuthorityHash,pendingAuthorityCount:r.pendingAuthorityCount,lockActive:r.lockActive,currentSessionActive:r.currentSessionActive,journalActive:r.journalActive,reasonCodes:[...r.reasonCodes],publicSafe:!0})}const o=(r,e,t={})=>({commandId:r,stateProjectionPolicy:e,...t}),A=Object.freeze({status:o("status","full"),"arch-plan":o("arch-plan","full"),"arch-prd":o("arch-prd","full"),"arch-architecture":o("arch-architecture","epic-targeted",{structuralRequired:!0}),"arch-api-contracts":o("arch-api-contracts","epic-targeted",{structuralRequired:!0}),"arch-api-integrations":o("arch-api-integrations","epic-targeted",{structuralRequired:!0}),"arch-database":o("arch-database","epic-targeted",{structuralRequired:!0}),"arch-security":o("arch-security","epic-targeted",{structuralRequired:!0}),"arch-design-system":o("arch-design-system","epic-targeted",{structuralRequired:!0}),"arch-ux-design":o("arch-ux-design","epic-targeted",{structuralRequired:!0}),"arch-performance":o("arch-performance","epic-targeted",{structuralRequired:!0}),"arch-testing":o("arch-testing","epic-targeted",{structuralRequired:!0}),"arch-infrastructure":o("arch-infrastructure","epic-targeted",{structuralRequired:!0}),"arch-review":o("arch-review","epic-targeted",{structuralRequired:!0}),"arch-fitness-functions":o("arch-fitness-functions","epic-targeted",{structuralRequired:!0}),"create-epic":o("create-epic","epic-summary"),"idea-diagnose":o("idea-diagnose","full"),"idea-research":o("idea-research","epic-targeted",{structuralRequired:!0}),"generate-epic":o("generate-epic","epic-targeted",{structuralRequired:!0}),exec:o("exec","story-targeted",{structuralRequired:!0}),yolo:o("yolo","story-targeted",{structuralRequired:!0}),"yolo-inline":o("yolo-inline","story-targeted",{structuralRequired:!0}),epic:o("epic","epic-targeted",{structuralRequired:!0}),"setup-branch":o("setup-branch","story-targeted",{structuralRequired:!0}),diagnose:o("diagnose","adaptive-targeted"),"diagnose-inline":o("diagnose-inline","full"),research:o("research","adaptive-targeted"),"research-inline":o("research-inline","full"),"write-spec":o("write-spec","story-targeted",{structuralRequired:!0}),"create-tasks":o("create-tasks","story-targeted",{structuralRequired:!0}),implement:o("implement","story-targeted",{structuralRequired:!0}),commit:o("commit","story-targeted",{structuralRequired:!0}),"commit-push":o("commit","story-targeted",{structuralRequired:!0}),sync:o("sync","story-targeted",{structuralRequired:!0}),"sync-main":o("sync","story-targeted",{structuralRequired:!0}),"create-pr":o("create-pr","story-targeted",{structuralRequired:!0}),review:o("review","story-targeted"),"review-pr":o("review","story-targeted"),merge:o("merge","story-targeted",{structuralRequired:!0}),"merge-pr":o("merge","story-targeted",{structuralRequired:!0}),"fix-blocked":o("fix-blocked","story-targeted"),"finalize-epic":o("finalize-epic","epic-targeted"),"resolve-conflicts":o("resolve-conflicts","story-targeted"),"update-memory":o("update-memory","full"),"update-project-memory":o("update-memory","story-targeted",{structuralRequired:!0}),refactor:o("refactor","adaptive-targeted"),"refactor-suggest":o("refactor","story-targeted",{structuralRequired:!0}),cleanup:o("cleanup","full"),audit:o("audit","full"),"tech-debt":o("tech-debt","full"),menu:o("menu","full"),plans:o("plans","full"),billing:o("billing","full"),subscribe:o("subscribe","full"),"qa-scan":o("qa-scan","full"),yoloop:o("yoloop","yoloop-targeted",{structuralRequired:!0}),"migrate-state":o("migrate-state","full"),"migrate-project-id":o("migrate-project-id","full"),"policy-audit":o("policy-audit","full"),"mutation-test":o("mutation-test","full"),"sync-openapi":o("sync-openapi","full"),"generate-pacts":o("generate-pacts","full"),"verify-pacts":o("verify-pacts","full"),"property-test":o("property-test","full"),"property-tests":o("property-test","story-targeted",{structuralRequired:!0}),"chaos-plan":o("chaos-plan","full"),"ui-ux-review":o("ui-ux-review","adaptive-targeted"),"solyd-system":o("solyd-system","adaptive-targeted"),goal:o("goal","continuity-scoped"),loop:o("loop","continuity-scoped"),jobs:o("jobs","continuity-scoped"),runner:o("runner","continuity-scoped"),"goal-tick":o("goal-tick","continuity-scoped"),"loop-tick":o("loop-tick","continuity-scoped"),"validate-tests":o("validate-tests","story-targeted",{structuralRequired:!0}),"qa-gate":o("qa-gate","story-targeted",{structuralRequired:!0})}),ee=Object.freeze({st:"status",arquitetura:"arch-plan",architecture:"arch-plan",arch:"arch-plan",prd:"arch-prd","product-requirements":"arch-prd","arch-doc":"arch-architecture","tech-architecture":"arch-architecture","api-contracts":"arch-api-contracts","api-contract":"arch-api-contracts","api-integrations":"arch-api-integrations","api-int":"arch-api-integrations","database-schema":"arch-database","db-schema":"arch-database",db:"arch-database","cyber-security":"arch-security",security:"arch-security",sec:"arch-security","design-system":"arch-design-system",ds:"arch-design-system","atomic-design":"arch-design-system","ux-design":"arch-ux-design",ux:"arch-ux-design",wireframes:"arch-ux-design",wireframe:"arch-ux-design","user-flows":"arch-ux-design",performance:"arch-performance",perf:"arch-performance","capacity-planning":"arch-performance",capacity:"arch-performance","arch-perf":"arch-performance","performance-strategy":"arch-performance","testing-strategy":"arch-testing","test-plan":"arch-testing","test-strategy":"arch-testing","arch-test":"arch-testing",infrastructure:"arch-infrastructure",infra:"arch-infrastructure","deploy-plan":"arch-infrastructure",deployment:"arch-infrastructure","arch-infra":"arch-infrastructure","arch-deploy":"arch-infrastructure","review-consolidation":"arch-review",consolidation:"arch-review","architecture-review":"arch-review","arch-consolidation":"arch-review",fitness:"arch-fitness-functions","fitness-functions":"arch-fitness-functions",archfit:"arch-fitness-functions","arch-fit":"arch-fitness-functions","fit-funcs":"arch-fitness-functions","criar-epic":"create-epic",planejamento:"create-epic","idea-diag":"idea-diagnose","idea-pesq":"idea-research","gerar-epic":"generate-epic",executar:"exec",pipeline:"exec","parallel-epic":"epic",setup:"setup-branch",branch:"setup-branch",diag:"diagnose",diagnostico:"diagnose",c02:"diagnose",pesquisar:"research",pesq:"research","research-fix":"research",c03:"research",spec:"write-spec",especificacao:"write-spec",c04:"write-spec",tasks:"create-tasks",tarefas:"create-tasks",c05:"create-tasks",impl:"implement",implementar:"implement",c06:"implement",push:"commit",commit_push:"commit",cp:"commit",c07:"commit",sincronizar:"sync",c08:"sync",pr:"create-pr",c09:"create-pr",revisar:"review",c11:"review",mesclar:"merge",c12:"merge",fix:"fix-blocked",corrigir:"fix-blocked",finalizar:"finalize-epic",conflitos:"resolve-conflicts",memoria:"update-memory",refactoring:"refactor",refact:"refactor",refac:"refactor",rf:"refactor","cleanup-code":"refactor","code-cleanup":"refactor","code-quality":"refactor","improve-code":"refactor",modernize:"refactor",modernization:"refactor",legacy:"refactor","legacy-code":"refactor","debt-pay":"refactor","pay-debt":"refactor","debt-reduction":"refactor","smell-fix":"refactor","fix-smells":"refactor","code-smells":"refactor",strangler:"refactor","strangler-fig":"refactor",limpar:"cleanup",limpeza:"cleanup",auditar:"audit",auditoria:"audit",debt:"tech-debt",debts:"tech-debt","debt-list":"tech-debt","tech-debts":"tech-debt",td:"tech-debt",help:"menu",ajuda:"menu","?":"menu",commands:"menu",cmds:"menu",planos:"plans",pricing:"plans",bill:"billing",subscription:"billing",sub:"billing",upgrade:"subscribe",checkout:"subscribe",qa:"qa-scan","qa-test":"qa-scan","visual-qa":"qa-scan","e2e-scan":"qa-scan",troubleshoot:"qa-scan","debug-ui":"qa-scan",scan:"qa-scan",a11y:"qa-scan",accessibility:"qa-scan",wcag:"qa-scan","auto-yolo":"yoloop","epic-runner":"yoloop","story-runner":"yoloop","loop-yolo":"yoloop","auto-epic":"yoloop",migrate:"migrate-state","state-migrate":"migrate-state","schema-migrate":"migrate-state",policy:"policy-audit","audit-policy":"policy-audit","policy-history":"policy-audit",policies:"policy-audit",mutation:"mutation-test",stryker:"mutation-test","kill-mutants":"mutation-test","openapi-sync":"sync-openapi","api-sync":"sync-openapi","spec-sync":"sync-openapi","regen-openapi":"sync-openapi",pacts:"generate-pacts","gen-pacts":"generate-pacts","regen-pacts":"generate-pacts","create-pacts":"generate-pacts","verify-pact":"verify-pacts","pact-verify":"verify-pacts","check-pacts":"verify-pacts","pact-check":"verify-pacts",property:"property-test",pbt:"property-test",proptest:"property-test","invariant-test":"property-test",chaos:"chaos-plan",gameday:"chaos-plan","resilience-test":"chaos-plan","ux-review":"ui-ux-review","design-review":"ui-ux-review","visual-review":"ui-ux-review","product-polish":"ui-ux-review","security-system":"solyd-system","authorized-security":"solyd-system","sec-system":"solyd-system",goals:"goal","durable-goal":"goal","continuity-goal":"goal",loops:"loop","durable-loop":"loop","continuity-loop":"loop",job:"jobs","continuity-jobs":"jobs","neocortex-runner":"runner","continuity-runner":"runner"}),te=Object.freeze({1:"status",3:"arch-plan",4:"arch-prd",5:"arch-architecture",6:"arch-api-contracts",7:"arch-api-integrations",8:"arch-database",9:"arch-security",10:"arch-design-system",11:"arch-ux-design",12:"arch-performance",13:"arch-testing",14:"arch-infrastructure",15:"arch-review",16:"arch-fitness-functions",17:"create-epic",18:"idea-diagnose",19:"idea-research",20:"generate-epic",21:"exec",22:"yolo",23:"epic",24:"setup-branch",25:"diagnose",26:"research",27:"write-spec",28:"create-tasks",29:"implement",30:"commit",31:"sync",32:"create-pr",33:"review",34:"merge",35:"fix-blocked",36:"finalize-epic",37:"resolve-conflicts",38:"update-memory",39:"refactor",40:"cleanup",41:"audit",42:"tech-debt",43:"menu",44:"plans",45:"billing",46:"subscribe",47:"qa-scan",48:"yoloop",49:"migrate-state",50:"policy-audit",51:"mutation-test",52:"sync-openapi",53:"generate-pacts",54:"verify-pacts",55:"property-test",56:"chaos-plan",57:"ui-ux-review",58:"solyd-system",59:"goal",60:"loop",61:"jobs",62:"runner"});function d(r,e=120){if(typeof r!="string")return;const t=r.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,e)}function T(r,e=120){if(typeof r!="string")return;const t=r.trim(),i=d(r,e);return i===t?i:void 0}function w(r){if(typeof r!="string")return;const e=r.trim();if(!(!e||e.length>240||!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(e)||e.includes("..")||e.includes("//")||e.includes("@{")||e.endsWith("/")||e.endsWith(".")||e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))))return e}function re(r){if(typeof r!="string")return;const e=r.replace(/\\/g,"/");if(!(!e||e.length>240||e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.includes("..")||e.includes("//")||e.split("/").includes(".")||!/^[A-Za-z0-9._/:@#-]+$/.test(e)))return e}function S(r){if(r===void 0||!Array.isArray(r)||r.length>128)return;const e=r.map(re);if(!e.some(t=>t===void 0))return[...new Set(e)].sort((t,i)=>t.localeCompare(i,"en"))}function ie(r){return typeof r=="string"&&X.has(r.trim().toLowerCase().replace(/_/g,"-"))}function v(r,e){const t={};for(const i of e){const c=r[i];typeof c=="string"||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)?t[i]=c:Array.isArray(c)&&c.every(n=>typeof n=="string")&&(t[i]=[...c])}return t}function ce(r,e){const t=e.checkpoint;if(!h(t)||t.schemaVersion!==1||t.storyId!==r||t.epicId!==e.epic_id||!w(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.headSha)||t.baseSha===t.headSha||!T(t.idempotencyKey)||typeof t.recordedAt!="string"||!Number.isFinite(Date.parse(t.recordedAt))||!Array.isArray(t.commits)||t.commits.length===0||t.commits.length>256||t.commits.some(c=>typeof c!="string"||!/^[0-9a-f]{7,64}$/i.test(c))||!Array.isArray(t.receiptRefs)||t.receiptRefs.length===0||t.receiptRefs.length>256||t.receiptRefs.some(c=>typeof c!="string"||c.length>240||c.includes("..")||!/^[A-Za-z0-9._:/#\-[\]]+$/.test(c))||!h(t.qaReceipt)||t.qaReceipt.kind!=="story_qa_evidence"||t.qaReceipt.producer!=="local-yolo-tdd"||!["passed","blocked"].includes(String(t.qaVerdict))||!["approved","changes-requested","pending"].includes(String(t.reviewVerdict))||(t.reviewVerdict==="pending"?t.reviewReceipt!==void 0:!h(t.reviewReceipt)))return;const i=v(t,["schemaVersion","storyId","epicId","branch","baseSha","headSha","idempotencyKey","dispatchId","bundleId","bundleDigest","graphRevision","claimRevision","qaVerdict","reviewVerdict","recordedAt","commits","receiptRefs"]);return i.qaReceipt=v(t.qaReceipt,["schemaVersion","kind","producer","evidenceVersion","storyId","epicId","contract","command","manifestDigest","gateIds","resultDigest","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","verdict","checkedAt","receiptRef"]),h(t.reviewReceipt)&&(i.reviewReceipt=v(t.reviewReceipt,["schemaVersion","kind","producer","storyId","epicId","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","qaReceiptRef","verdict","reviewedAt","receiptRef"])),i}function ne(r,e){const t=e.checkpoint_verification;if(!(!h(t)||t.schemaVersion!==1||t.kind!=="story_checkpoint_physical_verification"||t.producer!=="client-p205-transient-v1"||t.publicSafe!==!0||t.storyId!==r||t.epicId!==e.epic_id||!["verified","rejected"].includes(String(t.verdict))))return v(t,["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","aggregateHeadSha","commitBodyDigest","changedPathsDigest","claimVerification","effectiveClaimRevision","command","manifestDigest","gateIds","resultDigest","graphRevision","executionEvidenceDigest","sourceEvidenceDigest","verifiedAt","verdict","reasonCodes","publicSafe"])}function M(r,e){const t=e.scheduling_checkpoint_evidence,i=new Set(["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"]);if(!(!h(t)||Object.keys(t).some(c=>!i.has(c))||t.schemaVersion!==1||t.kind!=="story_scheduling_checkpoint_evidence"||t.producer!=="client-git-physical-v1"||t.publicSafe!==!0||t.integrationAuthorized!==!1||t.storyId!==r||t.epicId!==e.epic_id||!w(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{40,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{40,64}$/i.test(t.headSha)||typeof t.graphRevision!="string"||!/^[0-9a-f]{64}$/i.test(t.graphRevision)||typeof t.effectiveClaimRevision!="string"||!/^[0-9a-f]{64}$/i.test(t.effectiveClaimRevision)||typeof t.sourceEvidenceDigest!="string"||!/^[0-9a-f]{64}$/i.test(t.sourceEvidenceDigest)||typeof t.verifiedAt!="string"||!Number.isFinite(Date.parse(t.verifiedAt))||!Array.isArray(t.reasonCodes)||t.reasonCodes.length!==1||t.reasonCodes[0]!=="checkpoint-git-scheduling-verified"))return v(t,[...i])}function oe(r,e){const t={...e},i=M(r,e);return i?(t.scheduling_checkpoint_evidence=i,delete t.checkpoint,delete t.checkpoint_verification):delete t.scheduling_checkpoint_evidence,t}function h(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function _(...r){const e=new Set,t=[];for(const i of r)for(const c of i??[]){const n=d(c,80);if(!(!n||e.has(n))&&(e.add(n),t.push(n),t.length>=J))return t}return t}function se(r){return r.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function ae(r){return r.trim().split(/\s+/,1)[0]??""}function z(r){if(/^@epic-P[0-9]{1,12}$/.test(r.trim()))return A.epic;const e=ae(r);if(!e)return A.menu;const t=se(e),i=te[t]??ee[t]??t;return A[i]??null}function de(r,e,t,i="full-compatible",c=["full-state"]){return{kind:"full",commandId:t?.commandId??null,stateProjectionPolicy:t?.stateProjectionPolicy??null,projectionMode:i,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(e.stories).length,includedEpicCount:Object.keys(e.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",reasonCodes:_(c)}}function Le(r,e,t,i="full-compatible",c=["full-state"]){const n=de(r,e,t,i,c);return I({...e,scope:n},e,n)}function ue(r){const[e]=r.trim().split(/\s+/,1);return e?/^[A-Z]?\d+(?:\.\d+)+$/i.test(e.replace(/^@/,""))||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(e.replace(/^@/,"")):!1}function F(r){const e=r.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return e?.[1]?e[1]:r.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function le(r){const e=r.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function q(r){return le(r).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function $e(r){return q(r)[0]??null}function P(r,e){const i=r.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),c=[i,i.toUpperCase(),/^p\d+$/i.test(i)?`P${i.replace(/^p/i,"")}`:null,/^\d+$/.test(i)?`P${i}`:null].filter(n=>typeof n=="string"&&n.length>0);for(const n of c)if(e.epics[n])return n;return null}function pe(r,e){const t=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?P(t[1],e):null}function R(r,e){const t=r.trim().match(/^@epic-(P[0-9]{1,12})$/);if(t)return P(t[1],e);const i=pe(r,e);if(i)return i;for(const c of q(r)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(c))continue;const n=P(c,e);if(n)return n}return null}function fe(r,e){const t=R(r,e);if(t)return t;const i=e.yoloop,c=i?.state?.currentSession?.currentEpicId;if(typeof c=="string"&&e.epics[c])return c;const n=i?.lock?.currentEpicId??i?.lock?.epicId;return typeof n=="string"&&e.epics[n]?n:null}function ye(r){const e=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];if(e)return/^P/i.test(e)?e.toUpperCase():`P${e}`;for(const t of q(r)){if(/^P\d+$/i.test(t))return t.toUpperCase();if(/^\d+$/.test(t))return`P${t}`}return null}function j(r,e){if(typeof r.epic_id=="string"&&r.epic_id.length>0)return r.epic_id;const t=e.split(".").slice(0,-1).join(".");return t.length>0?t:null}function L(r){return typeof r=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(r.toLowerCase())}function x(r,e,t){if(t.has(r))return;const i=e.stories[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const n of c)typeof n=="string"&&x(n,e,t)}function me(r,e){const t=C(e.stories,[r]),i={};for(const c of t.orderedIds){const n=e.stories[c];n&&(i[c]=n)}return i}function $(r,e,t=[]){const i={};for(const c of t)e.epics[c]&&(i[c]=e.epics[c]);for(const[c,n]of Object.entries(r)){const s=j(n,c);s&&e.epics[s]&&(i[s]=e.epics[s])}return i}function ge(r,e,t){if(t.has(r))return;const i=e.epics[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const n of c)typeof n=="string"&&n.length>0&&ge(n,e,t)}function V(r,e,t){const i=C(t.epics,[r]),c=new Set(i.orderedIds);for(const[s,a]of Object.entries(e)){const u=j(a,s);u&&t.epics[u]&&c.add(u)}const n={};for(const s of[...c].sort((a,u)=>a.localeCompare(u,"en"))){const a=t.epics[s];a&&(n[s]=s===r?a:H(s,a))}return n}function G(r,e,t){const i=e.stories;if(!Array.isArray(i)||i.some(s=>typeof s!="string"||s.length===0))throw new y("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedStoryMemberships:1});const c=C(t.stories,i),n={};for(const s of c.orderedIds){const a=t.stories[s];a&&(n[s]=j(a,s)===r?oe(s,a):Y(s,a))}return n}function he(r,e,t){const i=[...e.stories].sort((s,a)=>s.localeCompare(a,"en")),c=Object.entries(t).filter(([s,a])=>j(a,s)===r).map(([s])=>s).sort((s,a)=>s.localeCompare(a,"en")),n=B("sha256").update(`target-epic-coverage-v1\0${JSON.stringify({targetEpicId:r,declaredStoryIds:i,includedStoryIds:c})}`).digest("hex");return{schemaVersion:"TargetEpicCoverage/1.0",targetEpicId:r,declaredStoryIds:i,includedStoryIds:c,membershipSha256:n,publicSafe:!0}}function Y(r,e){const t=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(m=>typeof m=="string"&&m.length>0))].sort((m,E)=>m.localeCompare(E,"en")):[],i={id:d(e.id)??r,...d(e.epic_id)?{epic_id:d(e.epic_id)}:{},...d(e.status,40)?{status:d(e.status,40)}:{},depends_on:t},c=M(r,e);if(!ie(e.status))return{...i,...c?{scheduling_checkpoint_evidence:c}:{}};const n=e.source==="create-epic"||e.source==="discovered"?e.source:void 0,s=w(e.branch_name),a=T(e.last_step,120),u=Array.isArray(e.steps_completed)&&e.steps_completed.length<=64?e.steps_completed.map(m=>T(m,120)):[],l=u.length>0&&u.every(m=>m!==void 0)?u:void 0,f=typeof e.pr_number=="number"&&Number.isSafeInteger(e.pr_number)&&e.pr_number>0?e.pr_number:void 0,p=ce(r,e),g=p?ne(r,e):void 0;return{...i,...n?{source:n}:{},...s?{branch_name:s}:{},...a?{last_step:a}:{},...l?{steps_completed:l}:{},...f?{pr_number:f}:{},...p?{checkpoint:p}:{},...g?{checkpoint_verification:g}:{},...c?{scheduling_checkpoint_evidence:c}:{},...S(e.files_to_modify)!==void 0?{files_to_modify:S(e.files_to_modify)}:{},...S(e.contracts)!==void 0?{contracts:S(e.contracts)}:{},...S(e.contract_refs)!==void 0?{contract_refs:S(e.contract_refs)}:{},...S(e.shared_surfaces)!==void 0?{shared_surfaces:S(e.shared_surfaces)}:{}}}function H(r,e){const t=Array.isArray(e.stories)?[...new Set(e.stories.filter(c=>typeof c=="string"&&c.length>0))].sort((c,n)=>c.localeCompare(n,"en")):[],i=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(c=>typeof c=="string"&&c.length>0))].sort((c,n)=>c.localeCompare(n,"en")):[];return{id:d(e.id)??r,...d(e.status,40)?{status:d(e.status,40)}:{},...d(e.lifecycle_classification,40)?{lifecycle_classification:d(e.lifecycle_classification,40)}:{},stories:t,depends_on:i}}function be(r,e,t){const i=C(e.stories),c=C(e.epics),n=Object.fromEntries(i.orderedIds.map(u=>[u,Y(u,e.stories[u])])),s=Object.fromEntries(c.orderedIds.map(u=>[u,H(u,e.epics[u])])),a={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"yoloop-discovery",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:i.orderedIds.length,includedEpicCount:c.orderedIds.length,omittedStoryCount:0,omittedEpicCount:0,reason:"targeted-invocation",reasonCodes:_(["structural-required","yoloop-discovery",`structural-edges-${i.edgeCount+c.edgeCount}`,"content-fields-omitted"])};return I({...e,stories:n,epics:s,scope:a},e,a)}function _e(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const n of i)typeof n=="string"&&x(n,e,t);const c={};for(const n of t){const s=e.stories[n];s&&(c[n]=s)}return c}function Se(r){const e={};for(const[t,i]of Object.entries(r.epics))e[t]={id:d(i.id)??t,...d(i.status)?{status:d(i.status)}:{},...k.includes(i.lifecycle_classification)?{lifecycle_classification:i.lifecycle_classification}:{},...typeof i.total_stories=="number"&&Number.isFinite(i.total_stories)?{total_stories:i.total_stories}:{},...typeof i.completed_stories=="number"&&Number.isFinite(i.completed_stories)?{completed_stories:i.completed_stories}:{}};return e}function K(r){const e={};for(const t of Object.values(r)){const i=d(t.status,40)??"unknown";e[i]=(e[i]??0)+1}return e}function je(r){const e=Object.fromEntries(k.map(t=>[t,0]));for(const t of Object.values(r)){const i=k.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[i]=(e[i]??0)+1}return e}function N(r,e){if(!e)return!0;const t=r.epics[e];return t?!k.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function Z(r){for(const e of["last_updated","updated_at","completed_at","created_at","discovered_at"]){const t=r[e];if(typeof t!="string")continue;const i=Date.parse(t);if(Number.isFinite(i))return i}return 0}function Ie(r){return Object.entries(r.stories).map(([e,t])=>({id:e,story:t,timestamp:Z(t)})).sort((e,t)=>t.timestamp-e.timestamp||e.id.localeCompare(t.id)).slice(0,U).map(({id:e,story:t})=>({id:e,...d(t.epic_id)?{epicId:d(t.epic_id)}:{},...d(t.status,40)?{status:d(t.status,40)}:{},...d(t.last_step??t.lastStep)?{lastStep:d(t.last_step??t.lastStep)}:{},...d(t.last_updated??t.updated_at??t.completed_at??t.created_at)?{lastUpdated:d(t.last_updated??t.updated_at??t.completed_at??t.created_at)}:{}}))}function Ce(r){const e=r.current_session;if(!e)return;const t={activeEpicId:d(e.active_epic_id)??null,activeStoryId:d(e.active_story_id)??null,activeStepId:d(e.active_step_id)??null,sessionId:d(e.session_id)??null,startedAt:d(e.started_at)??null};return Object.values(t).some(i=>i!=null)?t:void 0}function ke(r){const e=r.yoloop;if(!h(e))return;const t=h(e.state)?e.state:void 0,i=h(t?.currentSession)?t.currentSession:void 0,c=h(e.lock)?e.lock:void 0,n={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:d(i?.currentEpicId??e.currentEpicId)??null,currentStoryId:d(i?.currentStoryId??e.currentStoryId)??null,sessionId:d(i?.sessionId??e.sessionId)??null,lockEpicId:d(c?.currentEpicId??c?.epicId)??null};return Object.keys(n).length>0?n:void 0}function ve(r){const e=r.continuity;if(!h(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(i=>typeof i=="string"):void 0;return{present:!0,activeJobId:d(e.activeJobId??e.jobId)??null,activeGoalId:d(e.activeGoalId??e.goalId)??null,activeLoopId:d(e.activeLoopId??e.loopId)??null,...t&&t.length>0?{reasonCodes:_(t)}:{}}}function Ee(r,e,t){const i=d(e?.activeStoryId),c=d(e?.activeEpicId),n=d(e?.activeStepId),s=i&&r.stories[i]?j(r.stories[i],i):null;if((i||c||n)&&N(r,c??s))return{epicId:c??null,storyId:i??null,stepId:n??null};const a=d(t?.currentStoryId),u=d(t?.currentEpicId??t?.lockEpicId);if((a||u)&&N(r,u))return{epicId:u??null,storyId:a??null,stepId:null};const l=Object.entries(r.stories).map(([f,p])=>({id:f,story:p,timestamp:Z(p)})).filter(({id:f,story:p})=>!L(p.status)&&N(r,j(p,f))).sort((f,p)=>p.timestamp-f.timestamp||f.id.localeCompare(p.id))[0];return l?{epicId:j(l.story,l.id),storyId:l.id,stepId:d(l.story.last_step??l.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function Re(r,e){const t=K(r.stories),i=K(r.epics),c=je(r.epics),n=Object.values(r.epics).filter(g=>(k.includes(g.lifecycle_classification)?g.lifecycle_classification:"active")==="active"&&!L(g.status)).length,s=Ce(r),a=ke(r),u=ve(r),l=Ee(r,s,a),f=Ie(r),p=_(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",f.length>=U?"recent-stories-capped":"recent-stories-bounded",l.storyId||l.epicId?"active-ref-derived":"active-ref-empty",a?"yoloop-session-present":"yoloop-session-absent",u?"continuity-session-present":"continuity-session-absent"]);return{schemaVersion:1,totals:{stories:Object.keys(r.stories).length,epics:Object.keys(r.epics).length,storyStatus:t,epicStatus:i,epicLifecycle:c,activeEpics:n,blockedStories:t.blocked??0},active:l,blockedCount:t.blocked??0,recentStories:f,...s?{currentSession:s}:{},...a?{currentYoloopSession:a}:{},...u?{currentContinuitySession:u}:{},projection:{commandId:e.commandId??null,stateProjectionPolicy:e.stateProjectionPolicy??null,projectionMode:e.projectionMode,scopeKind:e.kind,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??Object.keys(r.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:p,publicSafe:!0}}function I(r,e,t){return{...r,stateSummary:Re(e,t)}}function Oe(r,e,t){const i={};for(const n of Object.keys(e.epics))i[n]={id:n};const c={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"summary-only",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(i).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:0,reason:"epic-summary",reasonCodes:["epic-summary","stories-omitted","epic-stubs-only"]};return I({...e,stories:{},epics:i,scope:c},e,c)}function b(r,e,t,i=["summary-only","stories-omitted"],c="summary-only"){const n=Se(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(n).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(n).length),reason:"summary-only",reasonCodes:_(i)};return I({...e,stories:{},epics:n,scope:s},e,s)}function D(r,e,t,i,c,n){const s=e.stories[i];if(!s)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"});const a=j(s,i);if(!a)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=e.epics[a];if(!u)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const l=c==="yolo-story",f=l?G(a,u,e):me(i,e),p=l?V(a,f,e):$(f,e);if(!f[i]||!p[a])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(f).length,epics:Object.keys(p).length,targetKind:"story"});const g={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:a,targetStoryId:i,includedStoryCount:Object.keys(f).length,includedEpicCount:Object.keys(p).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(f).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(p).length),reason:"targeted-invocation",reasonCodes:_(n,l?["epic-graph-authority-complete"]:[])};return I({...e,stories:f,epics:p,scope:g},e,g)}function W(r,e,t,i,c,n){const s=e.epics[i];if(!s)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=_e(s,e),u=$(a,e,[i]);if(!u[i])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(a).length,epics:Object.keys(u).length,targetKind:"epic"});const l={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:i,targetStoryId:null,includedStoryCount:Object.keys(a).length,includedEpicCount:Object.keys(u).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(a).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(u).length),reason:"targeted-invocation",reasonCodes:_(n)};return I({...e,stories:a,epics:u,scope:l},e,l)}function Ae(r,e,t){const i=ye(r),c=R(r,e);if(i&&!c)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const n=fe(r,e),s=O({commandId:t.commandId,explicitYoloopEpicId:c,sessionYoloopEpicId:c?null:n});if(s==="yoloop-discovery")return be(r,e,t);if(!n||s!=="yoloop-target"&&s!=="yoloop-session")throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=e.epics[n];if(!a)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=G(n,a,e),l=V(n,u,e);if(!l[n])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(u).length,epics:Object.keys(l).length,targetKind:"epic"});const f=s,p={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:f,trigger:r,targetEpicId:n,targetStoryId:null,targetEpicCoverage:he(n,a,u),includedStoryCount:Object.keys(u).length,includedEpicCount:Object.keys(l).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(u).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(l).length),reason:"targeted-invocation",reasonCodes:["structural-required",f,"yoloop-targeted"]};return I({...e,stories:u,epics:l,scope:p},e,p)}function Te(r,e){const t={};for(const[i,c]of Object.entries(r.epics)){const n=Array.isArray(c.stories)?c.stories.filter(s=>typeof s=="string"&&e.has(s)):[];t[i]={id:d(c.id)??i,...d(c.status,40)?{status:d(c.status,40)}:{},...typeof c.total_stories=="number"&&Number.isFinite(c.total_stories)?{total_stories:c.total_stories}:{},...typeof c.completed_stories=="number"&&Number.isFinite(c.completed_stories)?{completed_stories:c.completed_stories}:{},...n.length>0?{stories:n}:{},...n.length>0&&Array.isArray(c.depends_on)?{depends_on:c.depends_on.filter(s=>typeof s=="string"&&s.length>0)}:{},...n.length>0&&(c.branch_mode==="epic"||c.branch_mode==="story")?{branch_mode:c.branch_mode}:{},...n.length>0&&typeof c.execution_branch=="string"?{execution_branch:c.execution_branch}:{},...n.length>0&&typeof c.origin_branch=="string"?{origin_branch:c.origin_branch}:{},...n.length>0&&(c.branch_lease===null||typeof c.branch_lease=="object")?{branch_lease:c.branch_lease}:{},...n.length>0&&(c.origin_binding===null||typeof c.origin_binding=="object")?{origin_binding:c.origin_binding}:{},...n.length>0&&(c.aggregate_qa_receipt===null||typeof c.aggregate_qa_receipt=="object")?{aggregate_qa_receipt:c.aggregate_qa_receipt}:{},...n.length>0&&(c.head_reconciliation_receipt===null||typeof c.head_reconciliation_receipt=="object")?{head_reconciliation_receipt:c.head_reconciliation_receipt}:{}}}return t}function we(r){return r.stateSummary?.totals.stories??(r.scope?.includedStoryCount??Object.keys(r.stories).length)+(r.scope?.omittedStoryCount??0)}function qe(r){return r.stateSummary?.totals.epics??(r.scope?.includedEpicCount??Object.keys(r.epics).length)+(r.scope?.omittedEpicCount??0)}function Pe(r,e){if(r.stateSummary)return{...r.stateSummary,projection:{...r.stateSummary.projection,scopeKind:"projected",projectionMode:e.projectionMode,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??r.stateSummary.projection.includedEpicCount,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:"body-size"},reasonCodes:_(r.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function Ve(r){const e=r.scope,t=new Set,i=e?.projectionMode==="structural-required"||e?.projectionMode==="yolo-story"||e?.projectionMode==="yoloop-target"||e?.projectionMode==="yoloop-session"||e?.projectionMode==="yoloop-discovery";if(i)for(const m of Object.keys(r.stories))t.add(m);else e?.targetStoryId&&x(e.targetStoryId,r,t);const c={};for(const m of t){const E=r.stories[m];E&&(c[m]=E)}const n=Te(r,t),s=Object.keys(c).length,a=Object.keys(n).length,u=Math.max(0,we(r)-s),l=Math.max(0,qe(r)-a),f=i?e?.projectionMode??"structural-required":e?.projectionMode==="yolo-story"?"yolo-story":"summary-only",p={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:f,targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,...e?.targetEpicCoverage?{targetEpicCoverage:e.targetEpicCoverage}:{},includedStoryCount:s,includedEpicCount:a,omittedStoryCount:u,omittedEpicCount:l,reason:"body-size",reasonCodes:_(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved","redundant-trigger-omitted"])},g=Pe(r,p);return{...r,stories:c,epics:n,scope:p,...g?{stateSummary:g}:{}}}function xe(r,e){const t=r.trim(),i=z(t);try{if(!i){if(ue(t)){const n=o("story-reference","story-targeted"),s=F(t);if(s)return D(t,e,n,s,"targeted-story",["story-reference-targeted"])}return b(t,e,o("unknown","adaptive-targeted"),["unknown-command-summary-only"])}if(i.stateProjectionPolicy==="epic-summary")return Oe(t,e,i);if(i.stateProjectionPolicy==="yoloop-targeted")return Ae(t,e,i);const c=F(t);if(i.stateProjectionPolicy==="story-targeted"){if(c){const s=O({commandId:i.commandId,targetStoryId:c})==="yolo-story";return D(t,e,i,c,s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story",[s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story"])}if(i.commandId==="yolo"||i.commandId==="yolo-inline"){const n=O({commandId:i.commandId});return b(t,e,i,["yolo-inline","stories-omitted","historical-content-omitted"],n??"yolo-inline")}return i.commandId==="commit"&&/^\*?(?:commit|commit-push)$/i.test(t)?b(t,e,i,["working-tree-commit","stories-omitted","historical-content-omitted"]):i.structuralRequired?(()=>{throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"})})():b(t,e,i,["story-target-missing-summary-only"])}if(i.stateProjectionPolicy==="adaptive-targeted"){if(c&&e.stories[c])return D(t,e,i,c,"targeted-story",["adaptive-story-targeted"]);const n=R(t,e);return n?W(t,e,i,n,"targeted-epic",["adaptive-epic-targeted"]):b(t,e,i,["adaptive-summary-only","target-unresolved-summary-only"])}if(i.stateProjectionPolicy==="epic-targeted"){if(i.commandId.startsWith("arch-")&&/(?:^|\s)epic-arch\s*$/i.test(t)&&e.archPlan?.execution?.currentStageCommand===i.commandId)return b(t,e,i,["architecture-root-delegated"]);const n=R(t,e);return n?W(t,e,i,n,i.structuralRequired?"structural-required":"targeted-epic",[i.structuralRequired?"structural-required":"targeted-epic"]):i.structuralRequired?(()=>{throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"})})():b(t,e,i,["epic-target-missing-summary-only"])}return i.stateProjectionPolicy==="continuity-scoped"?b(t,e,i,["continuity-scoped-summary-only"]):b(t,e,i,["policy-full-summary-only"])}catch(c){if(c instanceof y)throw c;if(i?.structuralRequired)throw new y("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,projectionErrors:1});return b(t,e,i??o("unknown","adaptive-targeted"),["projection-error-summary-only"])}}const Ne=new Set(["yolo-story","yolo-inline","yoloop-target","yoloop-session","yoloop-discovery"]);function De(r){let e=0;for(const t of[r.stories,r.epics])for(const i of Object.values(t))Array.isArray(i.depends_on)&&(e+=i.depends_on.filter(c=>typeof c=="string").length);return e}function Ge(r,e){const t=z(r.trim());if(!t||!["yolo","yolo-inline","yoloop"].includes(t.commandId))return null;try{const i=xe(r,e),c=i.scope?.projectionMode;if(!c||!Ne.has(c))throw new y("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(i.stories).length,epics:Object.keys(i.epics).length,projectionShapeErrors:1});return Object.freeze({ok:!0,version:2,shape:c,snapshot:i,included:{epics:i.scope?.includedEpicCount??Object.keys(i.epics).length,stories:i.scope?.includedStoryCount??Object.keys(i.stories).length,edges:De(i)},omitted:{epics:i.scope?.omittedEpicCount??0,stories:i.scope?.omittedStoryCount??0},cycleCount:0})}catch(i){if(!(i instanceof y))throw i;return Object.freeze({ok:!1,code:i.code,publicDetails:{...i.publicDetails,...i.code==="STRUCTURAL_CONTEXT_TOO_LARGE"?{}:{planningCause:Q(i.code)}}})}}export{Ve as degradeStateSnapshotForPayloadLimit,Q as planningProjectionCauseForStructuralCode,Fe as projectEpicOperationalEvidenceForRequest,xe as projectStateSnapshotForInvoke,Ge as projectStateSnapshotResultV2ForInvoke};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * Pure request-scoped projection helpers for invoke state snapshots.
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ import { analyzeDependencyDag, StructuralDagError, } from './structural-dag-projection.js';
9
+ import { classifyInvocationShapeV2 } from './invocation-shape.js';
10
+ const RECENT_STORY_LIMIT = 12;
11
+ const REASON_CODE_LIMIT = 16;
12
+ const EPIC_LIFECYCLE_CLASSIFICATIONS = ['active', 'archived', 'rolled-back', 'synthetic', 'orphan'];
13
+ // Publish-safe shadow of packages/shared/src/yoloop/status-policy.ts. The
14
+ // standalone client tarball cannot take a runtime dependency on @neocortex/shared.
15
+ const YOLOOP_ACTIVE_STORY_STATUS_SET = new Set([
16
+ 'in-progress', 'branch-ready', 'diagnose', 'research', 'write-spec',
17
+ 'create-tasks', 'implemented', 'refactor-suggest-done',
18
+ 'property-tests-emitted', 'tests-validated', 'qa-gate-passed',
19
+ 'memory-updated', 'committed', 'synced', 'pr-created', 'pr-reviewed',
20
+ 'partial',
21
+ ]);
22
+ /**
23
+ * Stable public mapping for planning projection failures. The caller exposes
24
+ * only this enum plus existing bounded structural counts; target names and
25
+ * checkpoint content never become error telemetry.
26
+ */
27
+ export function planningProjectionCauseForStructuralCode(code) {
28
+ if (code === 'STRUCTURAL_TARGET_NOT_FOUND')
29
+ return 'registration-missing';
30
+ if (code === 'STRUCTURAL_DEPENDENCY_CYCLE')
31
+ return 'dependency-cycle';
32
+ return 'dependency-missing';
33
+ }
34
+ /**
35
+ * P224.01 bounded common-authority evidence for a future invoke handoff.
36
+ * This module remains pure: callers read the private store elsewhere and pass
37
+ * only the already-redacted projection. Absolute paths, source bytes, unknown
38
+ * private fields and certificates are intentionally impossible to project.
39
+ */
40
+ export function projectEpicOperationalEvidenceForRequest(value) {
41
+ const hash = /^[a-f0-9]{64}$/;
42
+ const safeId = /^P[1-9][0-9]*(?:\.[0-9]+)*$/;
43
+ const safeBranch = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/;
44
+ if (value.schemaVersion !== 'EpicOperationalPublicProjection/1.0'
45
+ || !hash.test(value.repositoryFingerprint)
46
+ || !hash.test(value.identityHash)
47
+ || !safeId.test(value.epicId)
48
+ || !safeBranch.test(value.executionBranch)
49
+ || !hash.test(value.graphRevision)
50
+ || !Number.isSafeInteger(value.storeRevision) || value.storeRevision < 0
51
+ || !Number.isSafeInteger(value.writerEpoch) || value.writerEpoch < 1
52
+ || (value.runId !== null && value.runId.length > 128)
53
+ || (value.runStatus !== null && value.runStatus.length > 32)
54
+ || (value.runRevision !== null && (!Number.isSafeInteger(value.runRevision) || value.runRevision < 0))
55
+ || (value.snapshotHash !== null && !hash.test(value.snapshotHash))
56
+ || !hash.test(value.continuationSessionHash)
57
+ || !hash.test(value.pendingAuthorityHash)
58
+ || !Number.isSafeInteger(value.pendingAuthorityCount) || value.pendingAuthorityCount < 0
59
+ || value.pendingAuthorityCount > 1_024
60
+ || value.reasonCodes.length > 16
61
+ || value.reasonCodes.some((reason) => !/^[a-z0-9][a-z0-9-]{0,79}$/.test(reason))
62
+ || value.publicSafe !== true) {
63
+ throw new Error('epic-operational-projection-invalid');
64
+ }
65
+ return Object.freeze({
66
+ schemaVersion: value.schemaVersion,
67
+ repositoryFingerprint: value.repositoryFingerprint,
68
+ identityHash: value.identityHash,
69
+ epicId: value.epicId,
70
+ executionBranch: value.executionBranch,
71
+ graphRevision: value.graphRevision,
72
+ storeRevision: value.storeRevision,
73
+ writerEpoch: value.writerEpoch,
74
+ runId: value.runId,
75
+ runStatus: value.runStatus,
76
+ runRevision: value.runRevision,
77
+ snapshotHash: value.snapshotHash,
78
+ continuationSessionHash: value.continuationSessionHash,
79
+ pendingAuthorityHash: value.pendingAuthorityHash,
80
+ pendingAuthorityCount: value.pendingAuthorityCount,
81
+ lockActive: value.lockActive,
82
+ currentSessionActive: value.currentSessionActive,
83
+ journalActive: value.journalActive,
84
+ reasonCodes: [...value.reasonCodes],
85
+ publicSafe: true,
86
+ });
87
+ }
88
+ const policy = (commandId, stateProjectionPolicy, options = {}) => ({
89
+ commandId,
90
+ stateProjectionPolicy,
91
+ ...options,
92
+ });
93
+ // P198.03: local publish-safe shadow of the P198.01 shared command-context
94
+ // projection policies. The published CLI does not ship `packages/shared/dist`, so
95
+ // this file must not add a runtime `@neocortex/shared` import until packaging is
96
+ // changed. Keep ids/aliases/numbers aligned with the public command registry.
97
+ const COMMAND_POLICY_BY_ID = Object.freeze({
98
+ status: policy('status', 'full'),
99
+ 'arch-plan': policy('arch-plan', 'full'),
100
+ 'arch-prd': policy('arch-prd', 'full'),
101
+ 'arch-architecture': policy('arch-architecture', 'epic-targeted', { structuralRequired: true }),
102
+ 'arch-api-contracts': policy('arch-api-contracts', 'epic-targeted', { structuralRequired: true }),
103
+ 'arch-api-integrations': policy('arch-api-integrations', 'epic-targeted', { structuralRequired: true }),
104
+ 'arch-database': policy('arch-database', 'epic-targeted', { structuralRequired: true }),
105
+ 'arch-security': policy('arch-security', 'epic-targeted', { structuralRequired: true }),
106
+ 'arch-design-system': policy('arch-design-system', 'epic-targeted', { structuralRequired: true }),
107
+ 'arch-ux-design': policy('arch-ux-design', 'epic-targeted', { structuralRequired: true }),
108
+ 'arch-performance': policy('arch-performance', 'epic-targeted', { structuralRequired: true }),
109
+ 'arch-testing': policy('arch-testing', 'epic-targeted', { structuralRequired: true }),
110
+ 'arch-infrastructure': policy('arch-infrastructure', 'epic-targeted', { structuralRequired: true }),
111
+ 'arch-review': policy('arch-review', 'epic-targeted', { structuralRequired: true }),
112
+ 'arch-fitness-functions': policy('arch-fitness-functions', 'epic-targeted', { structuralRequired: true }),
113
+ 'create-epic': policy('create-epic', 'epic-summary'),
114
+ 'idea-diagnose': policy('idea-diagnose', 'full'),
115
+ 'idea-research': policy('idea-research', 'epic-targeted', { structuralRequired: true }),
116
+ 'generate-epic': policy('generate-epic', 'epic-targeted', { structuralRequired: true }),
117
+ exec: policy('exec', 'story-targeted', { structuralRequired: true }),
118
+ yolo: policy('yolo', 'story-targeted', { structuralRequired: true }),
119
+ 'yolo-inline': policy('yolo-inline', 'story-targeted', { structuralRequired: true }),
120
+ epic: policy('epic', 'epic-targeted', { structuralRequired: true }),
121
+ 'setup-branch': policy('setup-branch', 'story-targeted', { structuralRequired: true }),
122
+ diagnose: policy('diagnose', 'adaptive-targeted'),
123
+ 'diagnose-inline': policy('diagnose-inline', 'full'),
124
+ research: policy('research', 'adaptive-targeted'),
125
+ 'research-inline': policy('research-inline', 'full'),
126
+ 'write-spec': policy('write-spec', 'story-targeted', { structuralRequired: true }),
127
+ 'create-tasks': policy('create-tasks', 'story-targeted', { structuralRequired: true }),
128
+ implement: policy('implement', 'story-targeted', { structuralRequired: true }),
129
+ commit: policy('commit', 'story-targeted', { structuralRequired: true }),
130
+ 'commit-push': policy('commit', 'story-targeted', { structuralRequired: true }),
131
+ sync: policy('sync', 'story-targeted', { structuralRequired: true }),
132
+ 'sync-main': policy('sync', 'story-targeted', { structuralRequired: true }),
133
+ 'create-pr': policy('create-pr', 'story-targeted', { structuralRequired: true }),
134
+ review: policy('review', 'story-targeted'),
135
+ 'review-pr': policy('review', 'story-targeted'),
136
+ merge: policy('merge', 'story-targeted', { structuralRequired: true }),
137
+ 'merge-pr': policy('merge', 'story-targeted', { structuralRequired: true }),
138
+ 'fix-blocked': policy('fix-blocked', 'story-targeted'),
139
+ 'finalize-epic': policy('finalize-epic', 'epic-targeted'),
140
+ 'resolve-conflicts': policy('resolve-conflicts', 'story-targeted'),
141
+ 'update-memory': policy('update-memory', 'full'),
142
+ 'update-project-memory': policy('update-memory', 'story-targeted', { structuralRequired: true }),
143
+ refactor: policy('refactor', 'adaptive-targeted'),
144
+ 'refactor-suggest': policy('refactor', 'story-targeted', { structuralRequired: true }),
145
+ cleanup: policy('cleanup', 'full'),
146
+ audit: policy('audit', 'full'),
147
+ 'tech-debt': policy('tech-debt', 'full'),
148
+ menu: policy('menu', 'full'),
149
+ plans: policy('plans', 'full'),
150
+ billing: policy('billing', 'full'),
151
+ subscribe: policy('subscribe', 'full'),
152
+ 'qa-scan': policy('qa-scan', 'full'),
153
+ yoloop: policy('yoloop', 'yoloop-targeted', { structuralRequired: true }),
154
+ 'migrate-state': policy('migrate-state', 'full'),
155
+ 'migrate-project-id': policy('migrate-project-id', 'full'),
156
+ 'policy-audit': policy('policy-audit', 'full'),
157
+ 'mutation-test': policy('mutation-test', 'full'),
158
+ 'sync-openapi': policy('sync-openapi', 'full'),
159
+ 'generate-pacts': policy('generate-pacts', 'full'),
160
+ 'verify-pacts': policy('verify-pacts', 'full'),
161
+ 'property-test': policy('property-test', 'full'),
162
+ 'property-tests': policy('property-test', 'story-targeted', { structuralRequired: true }),
163
+ 'chaos-plan': policy('chaos-plan', 'full'),
164
+ 'ui-ux-review': policy('ui-ux-review', 'adaptive-targeted'),
165
+ 'solyd-system': policy('solyd-system', 'adaptive-targeted'),
166
+ goal: policy('goal', 'continuity-scoped'),
167
+ loop: policy('loop', 'continuity-scoped'),
168
+ jobs: policy('jobs', 'continuity-scoped'),
169
+ runner: policy('runner', 'continuity-scoped'),
170
+ 'goal-tick': policy('goal-tick', 'continuity-scoped'),
171
+ 'loop-tick': policy('loop-tick', 'continuity-scoped'),
172
+ 'validate-tests': policy('validate-tests', 'story-targeted', { structuralRequired: true }),
173
+ 'qa-gate': policy('qa-gate', 'story-targeted', { structuralRequired: true }),
174
+ });
175
+ const COMMAND_ALIAS_TO_ID = Object.freeze({
176
+ st: 'status',
177
+ arquitetura: 'arch-plan',
178
+ architecture: 'arch-plan',
179
+ arch: 'arch-plan',
180
+ prd: 'arch-prd',
181
+ 'product-requirements': 'arch-prd',
182
+ 'arch-doc': 'arch-architecture',
183
+ 'tech-architecture': 'arch-architecture',
184
+ 'api-contracts': 'arch-api-contracts',
185
+ 'api-contract': 'arch-api-contracts',
186
+ 'api-integrations': 'arch-api-integrations',
187
+ 'api-int': 'arch-api-integrations',
188
+ 'database-schema': 'arch-database',
189
+ 'db-schema': 'arch-database',
190
+ db: 'arch-database',
191
+ 'cyber-security': 'arch-security',
192
+ security: 'arch-security',
193
+ sec: 'arch-security',
194
+ 'design-system': 'arch-design-system',
195
+ ds: 'arch-design-system',
196
+ 'atomic-design': 'arch-design-system',
197
+ 'ux-design': 'arch-ux-design',
198
+ ux: 'arch-ux-design',
199
+ wireframes: 'arch-ux-design',
200
+ wireframe: 'arch-ux-design',
201
+ 'user-flows': 'arch-ux-design',
202
+ performance: 'arch-performance',
203
+ perf: 'arch-performance',
204
+ 'capacity-planning': 'arch-performance',
205
+ capacity: 'arch-performance',
206
+ 'arch-perf': 'arch-performance',
207
+ 'performance-strategy': 'arch-performance',
208
+ 'testing-strategy': 'arch-testing',
209
+ 'test-plan': 'arch-testing',
210
+ 'test-strategy': 'arch-testing',
211
+ 'arch-test': 'arch-testing',
212
+ infrastructure: 'arch-infrastructure',
213
+ infra: 'arch-infrastructure',
214
+ 'deploy-plan': 'arch-infrastructure',
215
+ deployment: 'arch-infrastructure',
216
+ 'arch-infra': 'arch-infrastructure',
217
+ 'arch-deploy': 'arch-infrastructure',
218
+ 'review-consolidation': 'arch-review',
219
+ consolidation: 'arch-review',
220
+ 'architecture-review': 'arch-review',
221
+ 'arch-consolidation': 'arch-review',
222
+ fitness: 'arch-fitness-functions',
223
+ 'fitness-functions': 'arch-fitness-functions',
224
+ archfit: 'arch-fitness-functions',
225
+ 'arch-fit': 'arch-fitness-functions',
226
+ 'fit-funcs': 'arch-fitness-functions',
227
+ 'criar-epic': 'create-epic',
228
+ planejamento: 'create-epic',
229
+ 'idea-diag': 'idea-diagnose',
230
+ 'idea-pesq': 'idea-research',
231
+ 'gerar-epic': 'generate-epic',
232
+ executar: 'exec',
233
+ pipeline: 'exec',
234
+ 'parallel-epic': 'epic',
235
+ setup: 'setup-branch',
236
+ branch: 'setup-branch',
237
+ diag: 'diagnose',
238
+ diagnostico: 'diagnose',
239
+ c02: 'diagnose',
240
+ pesquisar: 'research',
241
+ pesq: 'research',
242
+ 'research-fix': 'research',
243
+ c03: 'research',
244
+ spec: 'write-spec',
245
+ especificacao: 'write-spec',
246
+ c04: 'write-spec',
247
+ tasks: 'create-tasks',
248
+ tarefas: 'create-tasks',
249
+ c05: 'create-tasks',
250
+ impl: 'implement',
251
+ implementar: 'implement',
252
+ c06: 'implement',
253
+ push: 'commit',
254
+ 'commit_push': 'commit',
255
+ cp: 'commit',
256
+ c07: 'commit',
257
+ sincronizar: 'sync',
258
+ c08: 'sync',
259
+ pr: 'create-pr',
260
+ c09: 'create-pr',
261
+ revisar: 'review',
262
+ c11: 'review',
263
+ mesclar: 'merge',
264
+ c12: 'merge',
265
+ fix: 'fix-blocked',
266
+ corrigir: 'fix-blocked',
267
+ finalizar: 'finalize-epic',
268
+ conflitos: 'resolve-conflicts',
269
+ memoria: 'update-memory',
270
+ refactoring: 'refactor',
271
+ refact: 'refactor',
272
+ refac: 'refactor',
273
+ rf: 'refactor',
274
+ 'cleanup-code': 'refactor',
275
+ 'code-cleanup': 'refactor',
276
+ 'code-quality': 'refactor',
277
+ 'improve-code': 'refactor',
278
+ modernize: 'refactor',
279
+ modernization: 'refactor',
280
+ legacy: 'refactor',
281
+ 'legacy-code': 'refactor',
282
+ 'debt-pay': 'refactor',
283
+ 'pay-debt': 'refactor',
284
+ 'debt-reduction': 'refactor',
285
+ 'smell-fix': 'refactor',
286
+ 'fix-smells': 'refactor',
287
+ 'code-smells': 'refactor',
288
+ strangler: 'refactor',
289
+ 'strangler-fig': 'refactor',
290
+ limpar: 'cleanup',
291
+ limpeza: 'cleanup',
292
+ auditar: 'audit',
293
+ auditoria: 'audit',
294
+ debt: 'tech-debt',
295
+ debts: 'tech-debt',
296
+ 'debt-list': 'tech-debt',
297
+ 'tech-debts': 'tech-debt',
298
+ td: 'tech-debt',
299
+ help: 'menu',
300
+ ajuda: 'menu',
301
+ '?': 'menu',
302
+ commands: 'menu',
303
+ cmds: 'menu',
304
+ planos: 'plans',
305
+ pricing: 'plans',
306
+ bill: 'billing',
307
+ subscription: 'billing',
308
+ sub: 'billing',
309
+ upgrade: 'subscribe',
310
+ checkout: 'subscribe',
311
+ qa: 'qa-scan',
312
+ 'qa-test': 'qa-scan',
313
+ 'visual-qa': 'qa-scan',
314
+ 'e2e-scan': 'qa-scan',
315
+ troubleshoot: 'qa-scan',
316
+ 'debug-ui': 'qa-scan',
317
+ scan: 'qa-scan',
318
+ a11y: 'qa-scan',
319
+ accessibility: 'qa-scan',
320
+ wcag: 'qa-scan',
321
+ 'auto-yolo': 'yoloop',
322
+ 'epic-runner': 'yoloop',
323
+ 'story-runner': 'yoloop',
324
+ 'loop-yolo': 'yoloop',
325
+ 'auto-epic': 'yoloop',
326
+ migrate: 'migrate-state',
327
+ 'state-migrate': 'migrate-state',
328
+ 'schema-migrate': 'migrate-state',
329
+ policy: 'policy-audit',
330
+ 'audit-policy': 'policy-audit',
331
+ 'policy-history': 'policy-audit',
332
+ policies: 'policy-audit',
333
+ mutation: 'mutation-test',
334
+ stryker: 'mutation-test',
335
+ 'kill-mutants': 'mutation-test',
336
+ 'openapi-sync': 'sync-openapi',
337
+ 'api-sync': 'sync-openapi',
338
+ 'spec-sync': 'sync-openapi',
339
+ 'regen-openapi': 'sync-openapi',
340
+ pacts: 'generate-pacts',
341
+ 'gen-pacts': 'generate-pacts',
342
+ 'regen-pacts': 'generate-pacts',
343
+ 'create-pacts': 'generate-pacts',
344
+ 'verify-pact': 'verify-pacts',
345
+ 'pact-verify': 'verify-pacts',
346
+ 'check-pacts': 'verify-pacts',
347
+ 'pact-check': 'verify-pacts',
348
+ property: 'property-test',
349
+ pbt: 'property-test',
350
+ proptest: 'property-test',
351
+ 'invariant-test': 'property-test',
352
+ chaos: 'chaos-plan',
353
+ gameday: 'chaos-plan',
354
+ 'resilience-test': 'chaos-plan',
355
+ 'ux-review': 'ui-ux-review',
356
+ 'design-review': 'ui-ux-review',
357
+ 'visual-review': 'ui-ux-review',
358
+ 'product-polish': 'ui-ux-review',
359
+ 'security-system': 'solyd-system',
360
+ 'authorized-security': 'solyd-system',
361
+ 'sec-system': 'solyd-system',
362
+ goals: 'goal',
363
+ 'durable-goal': 'goal',
364
+ 'continuity-goal': 'goal',
365
+ loops: 'loop',
366
+ 'durable-loop': 'loop',
367
+ 'continuity-loop': 'loop',
368
+ job: 'jobs',
369
+ 'continuity-jobs': 'jobs',
370
+ 'neocortex-runner': 'runner',
371
+ 'continuity-runner': 'runner',
372
+ });
373
+ const COMMAND_NUMBER_TO_ID = Object.freeze({
374
+ '1': 'status',
375
+ '3': 'arch-plan',
376
+ '4': 'arch-prd',
377
+ '5': 'arch-architecture',
378
+ '6': 'arch-api-contracts',
379
+ '7': 'arch-api-integrations',
380
+ '8': 'arch-database',
381
+ '9': 'arch-security',
382
+ '10': 'arch-design-system',
383
+ '11': 'arch-ux-design',
384
+ '12': 'arch-performance',
385
+ '13': 'arch-testing',
386
+ '14': 'arch-infrastructure',
387
+ '15': 'arch-review',
388
+ '16': 'arch-fitness-functions',
389
+ '17': 'create-epic',
390
+ '18': 'idea-diagnose',
391
+ '19': 'idea-research',
392
+ '20': 'generate-epic',
393
+ '21': 'exec',
394
+ '22': 'yolo',
395
+ '23': 'epic',
396
+ '24': 'setup-branch',
397
+ '25': 'diagnose',
398
+ '26': 'research',
399
+ '27': 'write-spec',
400
+ '28': 'create-tasks',
401
+ '29': 'implement',
402
+ '30': 'commit',
403
+ '31': 'sync',
404
+ '32': 'create-pr',
405
+ '33': 'review',
406
+ '34': 'merge',
407
+ '35': 'fix-blocked',
408
+ '36': 'finalize-epic',
409
+ '37': 'resolve-conflicts',
410
+ '38': 'update-memory',
411
+ '39': 'refactor',
412
+ '40': 'cleanup',
413
+ '41': 'audit',
414
+ '42': 'tech-debt',
415
+ '43': 'menu',
416
+ '44': 'plans',
417
+ '45': 'billing',
418
+ '46': 'subscribe',
419
+ '47': 'qa-scan',
420
+ '48': 'yoloop',
421
+ '49': 'migrate-state',
422
+ '50': 'policy-audit',
423
+ '51': 'mutation-test',
424
+ '52': 'sync-openapi',
425
+ '53': 'generate-pacts',
426
+ '54': 'verify-pacts',
427
+ '55': 'property-test',
428
+ '56': 'chaos-plan',
429
+ '57': 'ui-ux-review',
430
+ '58': 'solyd-system',
431
+ '59': 'goal',
432
+ '60': 'loop',
433
+ '61': 'jobs',
434
+ '62': 'runner',
435
+ });
436
+ function safeToken(value, maxLength = 120) {
437
+ if (typeof value !== 'string')
438
+ return undefined;
439
+ const trimmed = value.trim();
440
+ if (!trimmed)
441
+ return undefined;
442
+ return trimmed.replace(/[^a-z0-9_.:-]+/gi, '_').slice(0, maxLength);
443
+ }
444
+ function safeCanonicalToken(value, maxLength = 120) {
445
+ if (typeof value !== 'string')
446
+ return undefined;
447
+ const trimmed = value.trim();
448
+ const safe = safeToken(value, maxLength);
449
+ return safe === trimmed ? safe : undefined;
450
+ }
451
+ function safeGitRef(value) {
452
+ if (typeof value !== 'string')
453
+ return undefined;
454
+ const trimmed = value.trim();
455
+ if (!trimmed || trimmed.length > 240 || !/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(trimmed)
456
+ || trimmed.includes('..') || trimmed.includes('//') || trimmed.includes('@{')
457
+ || trimmed.endsWith('/') || trimmed.endsWith('.')
458
+ || trimmed.split('/').some((part) => !part || part.startsWith('.') || part.endsWith('.lock')))
459
+ return undefined;
460
+ return trimmed;
461
+ }
462
+ function safeWriteRef(value) {
463
+ if (typeof value !== 'string')
464
+ return undefined;
465
+ const normalized = value.replace(/\\/g, '/');
466
+ if (!normalized || normalized.length > 240 || normalized.startsWith('/')
467
+ || /^[A-Za-z]:/.test(normalized) || normalized.includes('..') || normalized.includes('//')
468
+ || normalized.split('/').includes('.') || !/^[A-Za-z0-9._/:@#-]+$/.test(normalized))
469
+ return undefined;
470
+ return normalized;
471
+ }
472
+ function safeWriteRefs(value) {
473
+ if (value === undefined)
474
+ return undefined;
475
+ if (!Array.isArray(value) || value.length > 128)
476
+ return undefined;
477
+ const refs = value.map(safeWriteRef);
478
+ if (refs.some((ref) => ref === undefined))
479
+ return undefined;
480
+ return [...new Set(refs)].sort((left, right) => left.localeCompare(right, 'en'));
481
+ }
482
+ function isActiveYoloopStory(status) {
483
+ return typeof status === 'string'
484
+ && YOLOOP_ACTIVE_STORY_STATUS_SET.has(status.trim().toLowerCase().replace(/_/g, '-'));
485
+ }
486
+ function pickPublicScalarFields(value, allowlist) {
487
+ const result = {};
488
+ for (const key of allowlist) {
489
+ const field = value[key];
490
+ if (typeof field === 'string' || typeof field === 'boolean'
491
+ || typeof field === 'number' && Number.isFinite(field))
492
+ result[key] = field;
493
+ else if (Array.isArray(field) && field.every((item) => typeof item === 'string'))
494
+ result[key] = [...field];
495
+ }
496
+ return result;
497
+ }
498
+ function publicResumeCheckpoint(storyId, story) {
499
+ const value = story.checkpoint;
500
+ if (!isRecord(value) || value.schemaVersion !== 1 || value.storyId !== storyId
501
+ || value.epicId !== story.epic_id || !safeGitRef(value.branch)
502
+ || typeof value.baseSha !== 'string' || !/^[0-9a-f]{7,64}$/i.test(value.baseSha)
503
+ || typeof value.headSha !== 'string' || !/^[0-9a-f]{7,64}$/i.test(value.headSha)
504
+ || value.baseSha === value.headSha || !safeCanonicalToken(value.idempotencyKey)
505
+ || typeof value.recordedAt !== 'string' || !Number.isFinite(Date.parse(value.recordedAt))
506
+ || !Array.isArray(value.commits) || value.commits.length === 0 || value.commits.length > 256
507
+ || value.commits.some((sha) => typeof sha !== 'string' || !/^[0-9a-f]{7,64}$/i.test(sha))
508
+ || !Array.isArray(value.receiptRefs) || value.receiptRefs.length === 0 || value.receiptRefs.length > 256
509
+ || value.receiptRefs.some((ref) => typeof ref !== 'string' || ref.length > 240 || ref.includes('..')
510
+ || !/^[A-Za-z0-9._:/#\-[\]]+$/.test(ref))
511
+ || !isRecord(value.qaReceipt) || value.qaReceipt.kind !== 'story_qa_evidence'
512
+ || value.qaReceipt.producer !== 'local-yolo-tdd'
513
+ || !['passed', 'blocked'].includes(String(value.qaVerdict))
514
+ || !['approved', 'changes-requested', 'pending'].includes(String(value.reviewVerdict)))
515
+ return undefined;
516
+ if (value.reviewVerdict === 'pending' ? value.reviewReceipt !== undefined : !isRecord(value.reviewReceipt))
517
+ return undefined;
518
+ // collectStateSnapshot already validated field values. Re-project the exact
519
+ // public allowlist so later hooks or synthetic callers cannot append content.
520
+ const result = pickPublicScalarFields(value, [
521
+ 'schemaVersion', 'storyId', 'epicId', 'branch', 'baseSha', 'headSha',
522
+ 'idempotencyKey', 'dispatchId', 'bundleId', 'bundleDigest', 'graphRevision',
523
+ 'claimRevision', 'qaVerdict', 'reviewVerdict', 'recordedAt', 'commits',
524
+ 'receiptRefs',
525
+ ]);
526
+ result.qaReceipt = pickPublicScalarFields(value.qaReceipt, [
527
+ 'schemaVersion', 'kind', 'producer', 'evidenceVersion', 'storyId', 'epicId',
528
+ 'contract', 'command', 'manifestDigest', 'gateIds', 'resultDigest', 'baseSha',
529
+ 'headSha', 'bundleDigest', 'graphRevision', 'sourceEvidenceDigest', 'verdict',
530
+ 'checkedAt', 'receiptRef',
531
+ ]);
532
+ if (isRecord(value.reviewReceipt)) {
533
+ result.reviewReceipt = pickPublicScalarFields(value.reviewReceipt, [
534
+ 'schemaVersion', 'kind', 'producer', 'storyId', 'epicId', 'baseSha',
535
+ 'headSha', 'bundleDigest', 'graphRevision', 'sourceEvidenceDigest',
536
+ 'qaReceiptRef', 'verdict', 'reviewedAt', 'receiptRef',
537
+ ]);
538
+ }
539
+ return result;
540
+ }
541
+ function publicCheckpointVerification(storyId, story) {
542
+ const value = story.checkpoint_verification;
543
+ if (!isRecord(value) || value.schemaVersion !== 1
544
+ || value.kind !== 'story_checkpoint_physical_verification'
545
+ || value.producer !== 'client-p205-transient-v1' || value.publicSafe !== true
546
+ || value.storyId !== storyId || value.epicId !== story.epic_id
547
+ || !['verified', 'rejected'].includes(String(value.verdict)))
548
+ return undefined;
549
+ return pickPublicScalarFields(value, [
550
+ 'schemaVersion', 'kind', 'producer', 'storyId', 'epicId', 'branch',
551
+ 'baseSha', 'headSha', 'aggregateHeadSha', 'commitBodyDigest',
552
+ 'changedPathsDigest', 'claimVerification', 'effectiveClaimRevision',
553
+ 'command', 'manifestDigest', 'gateIds', 'resultDigest', 'graphRevision',
554
+ 'executionEvidenceDigest', 'sourceEvidenceDigest', 'verifiedAt', 'verdict',
555
+ 'reasonCodes', 'publicSafe',
556
+ ]);
557
+ }
558
+ function publicSchedulingCheckpointEvidence(storyId, story) {
559
+ const value = story.scheduling_checkpoint_evidence;
560
+ const allowed = new Set([
561
+ 'schemaVersion', 'kind', 'producer', 'storyId', 'epicId', 'branch', 'baseSha', 'headSha',
562
+ 'graphRevision', 'effectiveClaimRevision', 'sourceEvidenceDigest', 'verifiedAt', 'reasonCodes',
563
+ 'integrationAuthorized', 'publicSafe',
564
+ ]);
565
+ if (!isRecord(value) || Object.keys(value).some((key) => !allowed.has(key))
566
+ || value.schemaVersion !== 1 || value.kind !== 'story_scheduling_checkpoint_evidence'
567
+ || value.producer !== 'client-git-physical-v1' || value.publicSafe !== true
568
+ || value.integrationAuthorized !== false || value.storyId !== storyId || value.epicId !== story.epic_id
569
+ || !safeGitRef(value.branch) || typeof value.baseSha !== 'string' || !/^[0-9a-f]{40,64}$/i.test(value.baseSha)
570
+ || typeof value.headSha !== 'string' || !/^[0-9a-f]{40,64}$/i.test(value.headSha)
571
+ || typeof value.graphRevision !== 'string' || !/^[0-9a-f]{64}$/i.test(value.graphRevision)
572
+ || typeof value.effectiveClaimRevision !== 'string' || !/^[0-9a-f]{64}$/i.test(value.effectiveClaimRevision)
573
+ || typeof value.sourceEvidenceDigest !== 'string' || !/^[0-9a-f]{64}$/i.test(value.sourceEvidenceDigest)
574
+ || typeof value.verifiedAt !== 'string' || !Number.isFinite(Date.parse(value.verifiedAt))
575
+ || !Array.isArray(value.reasonCodes) || value.reasonCodes.length !== 1
576
+ || value.reasonCodes[0] !== 'checkpoint-git-scheduling-verified')
577
+ return undefined;
578
+ return pickPublicScalarFields(value, [...allowed]);
579
+ }
580
+ function projectSchedulingLane(storyId, story) {
581
+ const projected = { ...story };
582
+ const evidence = publicSchedulingCheckpointEvidence(storyId, story);
583
+ if (evidence) {
584
+ projected.scheduling_checkpoint_evidence = evidence;
585
+ delete projected.checkpoint;
586
+ delete projected.checkpoint_verification;
587
+ }
588
+ else {
589
+ delete projected.scheduling_checkpoint_evidence;
590
+ }
591
+ return projected;
592
+ }
593
+ function isRecord(value) {
594
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
595
+ }
596
+ function safeReasonCodes(...groups) {
597
+ const seen = new Set();
598
+ const reasonCodes = [];
599
+ for (const group of groups) {
600
+ for (const reasonCode of group ?? []) {
601
+ const safe = safeToken(reasonCode, 80);
602
+ if (!safe || seen.has(safe))
603
+ continue;
604
+ seen.add(safe);
605
+ reasonCodes.push(safe);
606
+ if (reasonCodes.length >= REASON_CODE_LIMIT)
607
+ return reasonCodes;
608
+ }
609
+ }
610
+ return reasonCodes;
611
+ }
612
+ function normalizeCommandToken(input) {
613
+ return input.trim().replace(/^@?\*/, '').replace(/^@/, '').toLowerCase();
614
+ }
615
+ function leadingCommandToken(input) {
616
+ return input.trim().split(/\s+/, 1)[0] ?? '';
617
+ }
618
+ function resolveCommandProjectionPolicy(args) {
619
+ // The exact published @epic-P{N} spelling is a one-token command and its
620
+ // own target. It must receive the same structural projection as *epic.
621
+ if (/^@epic-P[0-9]{1,12}$/.test(args.trim()))
622
+ return COMMAND_POLICY_BY_ID.epic;
623
+ const token = leadingCommandToken(args);
624
+ if (!token)
625
+ return COMMAND_POLICY_BY_ID.menu;
626
+ const normalized = normalizeCommandToken(token);
627
+ const commandId = COMMAND_NUMBER_TO_ID[normalized]
628
+ ?? COMMAND_ALIAS_TO_ID[normalized]
629
+ ?? normalized;
630
+ return COMMAND_POLICY_BY_ID[commandId] ?? null;
631
+ }
632
+ function createFullScope(trigger, snapshot, commandPolicy, projectionMode = 'full-compatible', reasonCodes = ['full-state']) {
633
+ return {
634
+ kind: 'full',
635
+ commandId: commandPolicy?.commandId ?? null,
636
+ stateProjectionPolicy: commandPolicy?.stateProjectionPolicy ?? null,
637
+ projectionMode,
638
+ trigger,
639
+ targetEpicId: null,
640
+ targetStoryId: null,
641
+ includedStoryCount: Object.keys(snapshot.stories).length,
642
+ includedEpicCount: Object.keys(snapshot.epics).length,
643
+ omittedStoryCount: 0,
644
+ omittedEpicCount: 0,
645
+ reason: 'full-state',
646
+ reasonCodes: safeReasonCodes(reasonCodes),
647
+ };
648
+ }
649
+ function fullSnapshot(trigger, snapshot, commandPolicy, projectionMode = 'full-compatible', reasonCodes = ['full-state']) {
650
+ const scope = createFullScope(trigger, snapshot, commandPolicy, projectionMode, reasonCodes);
651
+ return withStateSummary({
652
+ ...snapshot,
653
+ scope,
654
+ }, snapshot, scope);
655
+ }
656
+ function firstTokenIsStoryReference(args) {
657
+ const [firstToken] = args.trim().split(/\s+/, 1);
658
+ if (!firstToken)
659
+ return false;
660
+ return (/^[A-Z]?\d+(?:\.\d+)+$/i.test(firstToken.replace(/^@/, '')) ||
661
+ /(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(firstToken.replace(/^@/, '')));
662
+ }
663
+ function extractStoryId(args) {
664
+ const storyFileMatch = args.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);
665
+ if (storyFileMatch?.[1])
666
+ return storyFileMatch[1];
667
+ const storyIdMatch = args.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i);
668
+ return storyIdMatch?.[1] ?? null;
669
+ }
670
+ function triggerRemainder(args) {
671
+ const trimmed = args.trim();
672
+ const firstWhitespace = trimmed.search(/\s/);
673
+ return firstWhitespace === -1 ? '' : trimmed.slice(firstWhitespace).trim();
674
+ }
675
+ function positionalTokens(args) {
676
+ return triggerRemainder(args)
677
+ .split(/\s+/)
678
+ .map((token) => token.replace(/^@/, '').replace(/^['"]|['"]$/g, ''))
679
+ .filter((token) => token.length > 0 && !token.startsWith('-'));
680
+ }
681
+ function firstPositionalArg(args) {
682
+ return positionalTokens(args)[0] ?? null;
683
+ }
684
+ function resolveEpicId(candidate, snapshot) {
685
+ const normalized = candidate.replace(/^@/, '').replace(/^epic-/i, '');
686
+ const withoutExtension = normalized.replace(/\.md$/i, '');
687
+ const candidates = [
688
+ withoutExtension,
689
+ withoutExtension.toUpperCase(),
690
+ /^p\d+$/i.test(withoutExtension)
691
+ ? `P${withoutExtension.replace(/^p/i, '')}`
692
+ : null,
693
+ /^\d+$/.test(withoutExtension) ? `P${withoutExtension}` : null,
694
+ ].filter((entry) => typeof entry === 'string' && entry.length > 0);
695
+ for (const entry of candidates) {
696
+ if (snapshot.epics[entry])
697
+ return entry;
698
+ }
699
+ return null;
700
+ }
701
+ function extractEpicIdFromCanonicalFile(args, snapshot) {
702
+ const match = args.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);
703
+ if (!match?.[1])
704
+ return null;
705
+ return resolveEpicId(match[1], snapshot);
706
+ }
707
+ function extractTargetEpicId(args, snapshot) {
708
+ const directEpic = args.trim().match(/^@epic-(P[0-9]{1,12})$/);
709
+ if (directEpic)
710
+ return resolveEpicId(directEpic[1], snapshot);
711
+ const fromFile = extractEpicIdFromCanonicalFile(args, snapshot);
712
+ if (fromFile)
713
+ return fromFile;
714
+ for (const token of positionalTokens(args)) {
715
+ if (/^[A-Z]?\d+(?:\.\d+)+$/i.test(token))
716
+ continue;
717
+ const fromToken = resolveEpicId(token, snapshot);
718
+ if (fromToken)
719
+ return fromToken;
720
+ }
721
+ return null;
722
+ }
723
+ function extractYoloopTargetEpicId(args, snapshot) {
724
+ const fromTarget = extractTargetEpicId(args, snapshot);
725
+ if (fromTarget)
726
+ return fromTarget;
727
+ const yoloop = snapshot.yoloop;
728
+ const sessionEpicId = yoloop?.state?.currentSession?.currentEpicId;
729
+ if (typeof sessionEpicId === 'string' && snapshot.epics[sessionEpicId]) {
730
+ return sessionEpicId;
731
+ }
732
+ const lockEpicId = yoloop?.lock?.currentEpicId ?? yoloop?.lock?.epicId;
733
+ if (typeof lockEpicId === 'string' && snapshot.epics[lockEpicId]) {
734
+ return lockEpicId;
735
+ }
736
+ return null;
737
+ }
738
+ function explicitYoloopEpicCandidate(args) {
739
+ const fromFile = args.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];
740
+ if (fromFile)
741
+ return /^P/i.test(fromFile) ? fromFile.toUpperCase() : `P${fromFile}`;
742
+ for (const token of positionalTokens(args)) {
743
+ if (/^P\d+$/i.test(token))
744
+ return token.toUpperCase();
745
+ if (/^\d+$/.test(token))
746
+ return `P${token}`;
747
+ }
748
+ return null;
749
+ }
750
+ function storyEpicId(story, storyId) {
751
+ if (typeof story.epic_id === 'string' && story.epic_id.length > 0) {
752
+ return story.epic_id;
753
+ }
754
+ const derived = storyId.split('.').slice(0, -1).join('.');
755
+ return derived.length > 0 ? derived : null;
756
+ }
757
+ function isTerminalStoryStatus(status) {
758
+ return typeof status === 'string' && ['done', 'completed', 'merged', 'cancelled', 'canceled', 'abandoned'].includes(status.toLowerCase());
759
+ }
760
+ function addStoryAndDependencies(storyId, snapshot, includedStoryIds) {
761
+ if (includedStoryIds.has(storyId))
762
+ return;
763
+ const story = snapshot.stories[storyId];
764
+ if (!story)
765
+ return;
766
+ includedStoryIds.add(storyId);
767
+ const dependsOn = story.depends_on;
768
+ if (!Array.isArray(dependsOn))
769
+ return;
770
+ for (const dependencyId of dependsOn) {
771
+ if (typeof dependencyId === 'string') {
772
+ addStoryAndDependencies(dependencyId, snapshot, includedStoryIds);
773
+ }
774
+ }
775
+ }
776
+ function buildProjectedStories(targetStoryId, snapshot) {
777
+ const analysis = analyzeDependencyDag(snapshot.stories, [targetStoryId]);
778
+ const projectedStories = {};
779
+ for (const storyId of analysis.orderedIds) {
780
+ const story = snapshot.stories[storyId];
781
+ if (story) {
782
+ projectedStories[storyId] = story;
783
+ }
784
+ }
785
+ return projectedStories;
786
+ }
787
+ function buildProjectedEpics(projectedStories, snapshot, requiredEpicIds = []) {
788
+ const projectedEpics = {};
789
+ for (const epicId of requiredEpicIds) {
790
+ if (snapshot.epics[epicId]) {
791
+ projectedEpics[epicId] = snapshot.epics[epicId];
792
+ }
793
+ }
794
+ for (const [storyId, story] of Object.entries(projectedStories)) {
795
+ const epicId = storyEpicId(story, storyId);
796
+ if (epicId && snapshot.epics[epicId]) {
797
+ projectedEpics[epicId] = snapshot.epics[epicId];
798
+ }
799
+ }
800
+ return projectedEpics;
801
+ }
802
+ function addEpicAndDependencies(epicId, snapshot, includedEpicIds) {
803
+ if (includedEpicIds.has(epicId))
804
+ return;
805
+ const epic = snapshot.epics[epicId];
806
+ if (!epic)
807
+ return;
808
+ includedEpicIds.add(epicId);
809
+ const dependsOn = epic.depends_on;
810
+ if (!Array.isArray(dependsOn))
811
+ return;
812
+ for (const dependencyId of dependsOn) {
813
+ if (typeof dependencyId === 'string' && dependencyId.length > 0) {
814
+ addEpicAndDependencies(dependencyId, snapshot, includedEpicIds);
815
+ }
816
+ }
817
+ }
818
+ function buildProjectedYoloopEpics(targetEpicId, projectedStories, snapshot) {
819
+ const epicAnalysis = analyzeDependencyDag(snapshot.epics, [targetEpicId]);
820
+ const requiredEpicIds = new Set(epicAnalysis.orderedIds);
821
+ for (const [storyId, story] of Object.entries(projectedStories)) {
822
+ const parentEpicId = storyEpicId(story, storyId);
823
+ if (parentEpicId && snapshot.epics[parentEpicId])
824
+ requiredEpicIds.add(parentEpicId);
825
+ }
826
+ const projectedEpics = {};
827
+ for (const epicId of [...requiredEpicIds].sort((left, right) => left.localeCompare(right, 'en'))) {
828
+ const epic = snapshot.epics[epicId];
829
+ if (!epic)
830
+ continue;
831
+ projectedEpics[epicId] = epicId === targetEpicId ? epic : compactStructuralEpic(epicId, epic);
832
+ }
833
+ return projectedEpics;
834
+ }
835
+ function buildProjectedYoloopStories(targetEpicId, targetEpic, snapshot) {
836
+ const storyIds = targetEpic.stories;
837
+ if (!Array.isArray(storyIds)
838
+ || storyIds.some((storyId) => typeof storyId !== 'string' || storyId.length === 0)) {
839
+ throw new StructuralDagError('STRUCTURAL_DEPENDENCY_MISSING', {
840
+ nodes: 0,
841
+ edges: 0,
842
+ malformedStoryMemberships: 1,
843
+ });
844
+ }
845
+ const analysis = analyzeDependencyDag(snapshot.stories, storyIds);
846
+ const projectedStories = {};
847
+ for (const storyId of analysis.orderedIds) {
848
+ const story = snapshot.stories[storyId];
849
+ if (story) {
850
+ projectedStories[storyId] = storyEpicId(story, storyId) === targetEpicId
851
+ ? projectSchedulingLane(storyId, story)
852
+ : compactStructuralStory(storyId, story);
853
+ }
854
+ }
855
+ return projectedStories;
856
+ }
857
+ function buildTargetEpicCoverage(targetEpicId, targetEpic, projectedStories) {
858
+ const declaredStoryIds = [...targetEpic.stories]
859
+ .sort((left, right) => left.localeCompare(right, 'en'));
860
+ const includedStoryIds = Object.entries(projectedStories)
861
+ .filter(([storyId, story]) => storyEpicId(story, storyId) === targetEpicId)
862
+ .map(([storyId]) => storyId)
863
+ .sort((left, right) => left.localeCompare(right, 'en'));
864
+ const membershipSha256 = createHash('sha256')
865
+ .update(`target-epic-coverage-v1\0${JSON.stringify({ targetEpicId, declaredStoryIds, includedStoryIds })}`)
866
+ .digest('hex');
867
+ return {
868
+ schemaVersion: 'TargetEpicCoverage/1.0',
869
+ targetEpicId,
870
+ declaredStoryIds,
871
+ includedStoryIds,
872
+ membershipSha256,
873
+ publicSafe: true,
874
+ };
875
+ }
876
+ function compactStructuralStory(storyId, story) {
877
+ const dependsOn = Array.isArray(story.depends_on)
878
+ ? [...new Set(story.depends_on.filter((value) => typeof value === 'string' && value.length > 0))]
879
+ .sort((left, right) => left.localeCompare(right, 'en'))
880
+ : [];
881
+ const compact = {
882
+ id: safeToken(story.id) ?? storyId,
883
+ ...(safeToken(story.epic_id) ? { epic_id: safeToken(story.epic_id) } : {}),
884
+ ...(safeToken(story.status, 40) ? { status: safeToken(story.status, 40) } : {}),
885
+ depends_on: dependsOn,
886
+ };
887
+ const schedulingEvidence = publicSchedulingCheckpointEvidence(storyId, story);
888
+ if (!isActiveYoloopStory(story.status)) {
889
+ return { ...compact, ...(schedulingEvidence ? { scheduling_checkpoint_evidence: schedulingEvidence } : {}) };
890
+ }
891
+ const source = story.source === 'create-epic' || story.source === 'discovered'
892
+ ? story.source : undefined;
893
+ const branchName = safeGitRef(story.branch_name);
894
+ const lastStep = safeCanonicalToken(story.last_step, 120);
895
+ const steps = Array.isArray(story.steps_completed) && story.steps_completed.length <= 64
896
+ ? story.steps_completed.map((step) => safeCanonicalToken(step, 120))
897
+ : [];
898
+ const validSteps = steps.length > 0 && steps.every((step) => step !== undefined)
899
+ ? steps : undefined;
900
+ const prNumber = typeof story.pr_number === 'number' && Number.isSafeInteger(story.pr_number)
901
+ && story.pr_number > 0 ? story.pr_number : undefined;
902
+ const checkpoint = publicResumeCheckpoint(storyId, story);
903
+ const checkpointVerification = checkpoint ? publicCheckpointVerification(storyId, story) : undefined;
904
+ return {
905
+ ...compact,
906
+ ...(source ? { source } : {}),
907
+ ...(branchName ? { branch_name: branchName } : {}),
908
+ ...(lastStep ? { last_step: lastStep } : {}),
909
+ ...(validSteps ? { steps_completed: validSteps } : {}),
910
+ ...(prNumber ? { pr_number: prNumber } : {}),
911
+ ...(checkpoint ? { checkpoint } : {}),
912
+ ...(checkpointVerification ? { checkpoint_verification: checkpointVerification } : {}),
913
+ ...(schedulingEvidence ? { scheduling_checkpoint_evidence: schedulingEvidence } : {}),
914
+ ...(safeWriteRefs(story.files_to_modify) !== undefined
915
+ ? { files_to_modify: safeWriteRefs(story.files_to_modify) } : {}),
916
+ ...(safeWriteRefs(story.contracts) !== undefined
917
+ ? { contracts: safeWriteRefs(story.contracts) } : {}),
918
+ ...(safeWriteRefs(story.contract_refs) !== undefined
919
+ ? { contract_refs: safeWriteRefs(story.contract_refs) } : {}),
920
+ ...(safeWriteRefs(story.shared_surfaces) !== undefined
921
+ ? { shared_surfaces: safeWriteRefs(story.shared_surfaces) } : {}),
922
+ };
923
+ }
924
+ function compactStructuralEpic(epicId, epic) {
925
+ const stories = Array.isArray(epic.stories)
926
+ ? [...new Set(epic.stories.filter((value) => typeof value === 'string' && value.length > 0))]
927
+ .sort((left, right) => left.localeCompare(right, 'en'))
928
+ : [];
929
+ const dependsOn = Array.isArray(epic.depends_on)
930
+ ? [...new Set(epic.depends_on.filter((value) => typeof value === 'string' && value.length > 0))]
931
+ .sort((left, right) => left.localeCompare(right, 'en'))
932
+ : [];
933
+ return {
934
+ id: safeToken(epic.id) ?? epicId,
935
+ ...(safeToken(epic.status, 40) ? { status: safeToken(epic.status, 40) } : {}),
936
+ ...(safeToken(epic.lifecycle_classification, 40)
937
+ ? { lifecycle_classification: safeToken(epic.lifecycle_classification, 40) }
938
+ : {}),
939
+ stories,
940
+ depends_on: dependsOn,
941
+ };
942
+ }
943
+ function buildYoloopDiscoveryProjection(trigger, snapshot, commandPolicy) {
944
+ const storyAnalysis = analyzeDependencyDag(snapshot.stories);
945
+ const epicAnalysis = analyzeDependencyDag(snapshot.epics);
946
+ const projectedStories = Object.fromEntries(storyAnalysis.orderedIds.map((storyId) => [
947
+ storyId,
948
+ compactStructuralStory(storyId, snapshot.stories[storyId]),
949
+ ]));
950
+ const projectedEpics = Object.fromEntries(epicAnalysis.orderedIds.map((epicId) => [
951
+ epicId,
952
+ compactStructuralEpic(epicId, snapshot.epics[epicId]),
953
+ ]));
954
+ const scope = {
955
+ kind: 'projected',
956
+ commandId: commandPolicy.commandId,
957
+ stateProjectionPolicy: commandPolicy.stateProjectionPolicy,
958
+ projectionMode: 'yoloop-discovery',
959
+ trigger,
960
+ targetEpicId: null,
961
+ targetStoryId: null,
962
+ includedStoryCount: storyAnalysis.orderedIds.length,
963
+ includedEpicCount: epicAnalysis.orderedIds.length,
964
+ omittedStoryCount: 0,
965
+ omittedEpicCount: 0,
966
+ reason: 'targeted-invocation',
967
+ reasonCodes: safeReasonCodes([
968
+ 'structural-required',
969
+ 'yoloop-discovery',
970
+ `structural-edges-${storyAnalysis.edgeCount + epicAnalysis.edgeCount}`,
971
+ 'content-fields-omitted',
972
+ ]),
973
+ };
974
+ return withStateSummary({
975
+ ...snapshot,
976
+ stories: projectedStories,
977
+ epics: projectedEpics,
978
+ scope,
979
+ }, snapshot, scope);
980
+ }
981
+ function buildProjectedTargetEpicStories(targetEpic, snapshot) {
982
+ const includedStoryIds = new Set();
983
+ const storyIds = targetEpic.stories;
984
+ if (Array.isArray(storyIds)) {
985
+ for (const storyId of storyIds) {
986
+ if (typeof storyId === 'string') {
987
+ addStoryAndDependencies(storyId, snapshot, includedStoryIds);
988
+ }
989
+ }
990
+ }
991
+ const projectedStories = {};
992
+ for (const storyId of includedStoryIds) {
993
+ const story = snapshot.stories[storyId];
994
+ if (story) {
995
+ projectedStories[storyId] = story;
996
+ }
997
+ }
998
+ return projectedStories;
999
+ }
1000
+ function buildEpicStubs(snapshot) {
1001
+ const projectedEpics = {};
1002
+ for (const [epicId, epic] of Object.entries(snapshot.epics)) {
1003
+ projectedEpics[epicId] = {
1004
+ id: safeToken(epic.id) ?? epicId,
1005
+ ...(safeToken(epic.status) ? { status: safeToken(epic.status) } : {}),
1006
+ ...(EPIC_LIFECYCLE_CLASSIFICATIONS.includes(epic.lifecycle_classification)
1007
+ ? { lifecycle_classification: epic.lifecycle_classification }
1008
+ : {}),
1009
+ ...(typeof epic.total_stories === 'number' && Number.isFinite(epic.total_stories)
1010
+ ? { total_stories: epic.total_stories }
1011
+ : {}),
1012
+ ...(typeof epic.completed_stories === 'number' && Number.isFinite(epic.completed_stories)
1013
+ ? { completed_stories: epic.completed_stories }
1014
+ : {}),
1015
+ };
1016
+ }
1017
+ return projectedEpics;
1018
+ }
1019
+ function countStatuses(records) {
1020
+ const counts = {};
1021
+ for (const record of Object.values(records)) {
1022
+ const status = safeToken(record.status, 40) ?? 'unknown';
1023
+ counts[status] = (counts[status] ?? 0) + 1;
1024
+ }
1025
+ return counts;
1026
+ }
1027
+ function countEpicLifecycles(records) {
1028
+ const counts = Object.fromEntries(EPIC_LIFECYCLE_CLASSIFICATIONS.map((classification) => [classification, 0]));
1029
+ for (const record of Object.values(records)) {
1030
+ const classification = EPIC_LIFECYCLE_CLASSIFICATIONS.includes(record.lifecycle_classification)
1031
+ ? record.lifecycle_classification
1032
+ : 'active';
1033
+ counts[classification] = (counts[classification] ?? 0) + 1;
1034
+ }
1035
+ return counts;
1036
+ }
1037
+ function isActiveEpicLifecycle(snapshot, epicId) {
1038
+ if (!epicId)
1039
+ return true;
1040
+ const epic = snapshot.epics[epicId];
1041
+ if (!epic)
1042
+ return true;
1043
+ return !EPIC_LIFECYCLE_CLASSIFICATIONS.includes(epic.lifecycle_classification) || epic.lifecycle_classification === 'active';
1044
+ }
1045
+ function sortableStoryTimestamp(story) {
1046
+ for (const key of ['last_updated', 'updated_at', 'completed_at', 'created_at', 'discovered_at']) {
1047
+ const value = story[key];
1048
+ if (typeof value !== 'string')
1049
+ continue;
1050
+ const parsed = Date.parse(value);
1051
+ if (Number.isFinite(parsed))
1052
+ return parsed;
1053
+ }
1054
+ return 0;
1055
+ }
1056
+ function recentStories(snapshot) {
1057
+ return Object.entries(snapshot.stories)
1058
+ .map(([id, story]) => ({ id, story, timestamp: sortableStoryTimestamp(story) }))
1059
+ .sort((left, right) => right.timestamp - left.timestamp || left.id.localeCompare(right.id))
1060
+ .slice(0, RECENT_STORY_LIMIT)
1061
+ .map(({ id, story }) => ({
1062
+ id,
1063
+ ...(safeToken(story.epic_id) ? { epicId: safeToken(story.epic_id) } : {}),
1064
+ ...(safeToken(story.status, 40) ? { status: safeToken(story.status, 40) } : {}),
1065
+ ...(safeToken(story.last_step ?? story.lastStep) ? { lastStep: safeToken(story.last_step ?? story.lastStep) } : {}),
1066
+ ...(safeToken(story.last_updated ?? story.updated_at ?? story.completed_at ?? story.created_at)
1067
+ ? { lastUpdated: safeToken(story.last_updated ?? story.updated_at ?? story.completed_at ?? story.created_at) }
1068
+ : {}),
1069
+ }));
1070
+ }
1071
+ function currentSessionRef(snapshot) {
1072
+ const session = snapshot.current_session;
1073
+ if (!session)
1074
+ return undefined;
1075
+ const ref = {
1076
+ activeEpicId: safeToken(session.active_epic_id) ?? null,
1077
+ activeStoryId: safeToken(session.active_story_id) ?? null,
1078
+ activeStepId: safeToken(session.active_step_id) ?? null,
1079
+ sessionId: safeToken(session.session_id) ?? null,
1080
+ startedAt: safeToken(session.started_at) ?? null,
1081
+ };
1082
+ return Object.values(ref).some((value) => value !== null && value !== undefined) ? ref : undefined;
1083
+ }
1084
+ function yoloopSessionRef(snapshot) {
1085
+ const yoloop = snapshot.yoloop;
1086
+ if (!isRecord(yoloop))
1087
+ return undefined;
1088
+ const state = isRecord(yoloop.state) ? yoloop.state : undefined;
1089
+ const currentSession = isRecord(state?.currentSession) ? state.currentSession : undefined;
1090
+ const lock = isRecord(yoloop.lock) ? yoloop.lock : undefined;
1091
+ const ref = {
1092
+ ...(typeof yoloop.active === 'boolean' ? { active: yoloop.active } : {}),
1093
+ currentEpicId: safeToken(currentSession?.currentEpicId ?? yoloop.currentEpicId) ?? null,
1094
+ currentStoryId: safeToken(currentSession?.currentStoryId ?? yoloop.currentStoryId) ?? null,
1095
+ sessionId: safeToken(currentSession?.sessionId ?? yoloop.sessionId) ?? null,
1096
+ lockEpicId: safeToken(lock?.currentEpicId ?? lock?.epicId) ?? null,
1097
+ };
1098
+ return Object.keys(ref).length > 0 ? ref : undefined;
1099
+ }
1100
+ function continuitySessionRef(snapshot) {
1101
+ const continuity = snapshot.continuity;
1102
+ if (!isRecord(continuity))
1103
+ return undefined;
1104
+ const reasonCodes = Array.isArray(continuity.reasonCodes)
1105
+ ? continuity.reasonCodes.filter((entry) => typeof entry === 'string')
1106
+ : undefined;
1107
+ return {
1108
+ present: true,
1109
+ activeJobId: safeToken(continuity.activeJobId ?? continuity.jobId) ?? null,
1110
+ activeGoalId: safeToken(continuity.activeGoalId ?? continuity.goalId) ?? null,
1111
+ activeLoopId: safeToken(continuity.activeLoopId ?? continuity.loopId) ?? null,
1112
+ ...(reasonCodes && reasonCodes.length > 0 ? { reasonCodes: safeReasonCodes(reasonCodes) } : {}),
1113
+ };
1114
+ }
1115
+ function deriveActiveRef(snapshot, session, yoloop) {
1116
+ const sessionStoryId = safeToken(session?.activeStoryId);
1117
+ const sessionEpicId = safeToken(session?.activeEpicId);
1118
+ const sessionStepId = safeToken(session?.activeStepId);
1119
+ const sessionStoryEpicId = sessionStoryId && snapshot.stories[sessionStoryId]
1120
+ ? storyEpicId(snapshot.stories[sessionStoryId], sessionStoryId)
1121
+ : null;
1122
+ if ((sessionStoryId || sessionEpicId || sessionStepId) && isActiveEpicLifecycle(snapshot, sessionEpicId ?? sessionStoryEpicId)) {
1123
+ return {
1124
+ epicId: sessionEpicId ?? null,
1125
+ storyId: sessionStoryId ?? null,
1126
+ stepId: sessionStepId ?? null,
1127
+ };
1128
+ }
1129
+ const yoloopStoryId = safeToken(yoloop?.currentStoryId);
1130
+ const yoloopEpicId = safeToken(yoloop?.currentEpicId ?? yoloop?.lockEpicId);
1131
+ if ((yoloopStoryId || yoloopEpicId) && isActiveEpicLifecycle(snapshot, yoloopEpicId)) {
1132
+ return {
1133
+ epicId: yoloopEpicId ?? null,
1134
+ storyId: yoloopStoryId ?? null,
1135
+ stepId: null,
1136
+ };
1137
+ }
1138
+ const latestNonTerminal = Object.entries(snapshot.stories)
1139
+ .map(([id, story]) => ({ id, story, timestamp: sortableStoryTimestamp(story) }))
1140
+ .filter(({ id, story }) => !isTerminalStoryStatus(story.status) && isActiveEpicLifecycle(snapshot, storyEpicId(story, id)))
1141
+ .sort((left, right) => right.timestamp - left.timestamp || left.id.localeCompare(right.id))[0];
1142
+ if (latestNonTerminal) {
1143
+ return {
1144
+ epicId: storyEpicId(latestNonTerminal.story, latestNonTerminal.id),
1145
+ storyId: latestNonTerminal.id,
1146
+ stepId: safeToken(latestNonTerminal.story.last_step ?? latestNonTerminal.story.lastStep) ?? null,
1147
+ };
1148
+ }
1149
+ return { epicId: null, storyId: null, stepId: null };
1150
+ }
1151
+ function buildStateSummary(sourceSnapshot, scope) {
1152
+ const storyStatus = countStatuses(sourceSnapshot.stories);
1153
+ const epicStatus = countStatuses(sourceSnapshot.epics);
1154
+ const epicLifecycle = countEpicLifecycles(sourceSnapshot.epics);
1155
+ const activeEpics = Object.values(sourceSnapshot.epics).filter((epic) => {
1156
+ const lifecycle = EPIC_LIFECYCLE_CLASSIFICATIONS.includes(epic.lifecycle_classification)
1157
+ ? epic.lifecycle_classification
1158
+ : 'active';
1159
+ return lifecycle === 'active' && !isTerminalStoryStatus(epic.status);
1160
+ }).length;
1161
+ const session = currentSessionRef(sourceSnapshot);
1162
+ const yoloop = yoloopSessionRef(sourceSnapshot);
1163
+ const continuity = continuitySessionRef(sourceSnapshot);
1164
+ const active = deriveActiveRef(sourceSnapshot, session, yoloop);
1165
+ const recent = recentStories(sourceSnapshot);
1166
+ const reasonCodes = safeReasonCodes(scope.reasonCodes, [
1167
+ 'state-summary-attached',
1168
+ 'state-summary-bounded',
1169
+ `projection-${scope.projectionMode ?? scope.kind}`,
1170
+ scope.stateProjectionPolicy ? `policy-${scope.stateProjectionPolicy}` : 'policy-unknown',
1171
+ recent.length >= RECENT_STORY_LIMIT ? 'recent-stories-capped' : 'recent-stories-bounded',
1172
+ active.storyId || active.epicId ? 'active-ref-derived' : 'active-ref-empty',
1173
+ yoloop ? 'yoloop-session-present' : 'yoloop-session-absent',
1174
+ continuity ? 'continuity-session-present' : 'continuity-session-absent',
1175
+ ]);
1176
+ return {
1177
+ schemaVersion: 1,
1178
+ totals: {
1179
+ stories: Object.keys(sourceSnapshot.stories).length,
1180
+ epics: Object.keys(sourceSnapshot.epics).length,
1181
+ storyStatus,
1182
+ epicStatus,
1183
+ epicLifecycle,
1184
+ activeEpics,
1185
+ blockedStories: storyStatus.blocked ?? 0,
1186
+ },
1187
+ active,
1188
+ blockedCount: storyStatus.blocked ?? 0,
1189
+ recentStories: recent,
1190
+ ...(session ? { currentSession: session } : {}),
1191
+ ...(yoloop ? { currentYoloopSession: yoloop } : {}),
1192
+ ...(continuity ? { currentContinuitySession: continuity } : {}),
1193
+ projection: {
1194
+ commandId: scope.commandId ?? null,
1195
+ stateProjectionPolicy: scope.stateProjectionPolicy ?? null,
1196
+ projectionMode: scope.projectionMode,
1197
+ scopeKind: scope.kind,
1198
+ includedStoryCount: scope.includedStoryCount,
1199
+ includedEpicCount: scope.includedEpicCount ?? Object.keys(sourceSnapshot.epics).length,
1200
+ omittedStoryCount: scope.omittedStoryCount,
1201
+ omittedEpicCount: scope.omittedEpicCount,
1202
+ reason: scope.reason,
1203
+ },
1204
+ reasonCodes,
1205
+ publicSafe: true,
1206
+ };
1207
+ }
1208
+ function withStateSummary(projected, sourceSnapshot, scope) {
1209
+ return {
1210
+ ...projected,
1211
+ stateSummary: buildStateSummary(sourceSnapshot, scope),
1212
+ };
1213
+ }
1214
+ function buildCreateEpicProjection(trigger, snapshot, commandPolicy) {
1215
+ const projectedEpics = {};
1216
+ for (const epicId of Object.keys(snapshot.epics)) {
1217
+ projectedEpics[epicId] = { id: epicId };
1218
+ }
1219
+ const scope = {
1220
+ kind: 'projected',
1221
+ commandId: commandPolicy.commandId,
1222
+ stateProjectionPolicy: commandPolicy.stateProjectionPolicy,
1223
+ projectionMode: 'summary-only',
1224
+ trigger,
1225
+ targetEpicId: null,
1226
+ targetStoryId: null,
1227
+ includedStoryCount: 0,
1228
+ includedEpicCount: Object.keys(projectedEpics).length,
1229
+ omittedStoryCount: Object.keys(snapshot.stories).length,
1230
+ omittedEpicCount: 0,
1231
+ reason: 'epic-summary',
1232
+ reasonCodes: ['epic-summary', 'stories-omitted', 'epic-stubs-only'],
1233
+ };
1234
+ return withStateSummary({
1235
+ ...snapshot,
1236
+ stories: {},
1237
+ epics: projectedEpics,
1238
+ scope,
1239
+ }, snapshot, scope);
1240
+ }
1241
+ function buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, reasonCodes = ['summary-only', 'stories-omitted'], projectionMode = 'summary-only') {
1242
+ const projectedEpics = buildEpicStubs(snapshot);
1243
+ const scope = {
1244
+ kind: 'projected',
1245
+ commandId: commandPolicy.commandId,
1246
+ stateProjectionPolicy: commandPolicy.stateProjectionPolicy,
1247
+ projectionMode,
1248
+ trigger,
1249
+ targetEpicId: null,
1250
+ targetStoryId: null,
1251
+ includedStoryCount: 0,
1252
+ includedEpicCount: Object.keys(projectedEpics).length,
1253
+ omittedStoryCount: Object.keys(snapshot.stories).length,
1254
+ omittedEpicCount: Math.max(0, Object.keys(snapshot.epics).length - Object.keys(projectedEpics).length),
1255
+ reason: 'summary-only',
1256
+ reasonCodes: safeReasonCodes(reasonCodes),
1257
+ };
1258
+ return withStateSummary({
1259
+ ...snapshot,
1260
+ stories: {},
1261
+ epics: projectedEpics,
1262
+ scope,
1263
+ }, snapshot, scope);
1264
+ }
1265
+ function buildStoryProjection(trigger, snapshot, commandPolicy, targetStoryId, projectionMode, reasonCodes) {
1266
+ const targetStory = snapshot.stories[targetStoryId];
1267
+ if (!targetStory) {
1268
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1269
+ stories: Object.keys(snapshot.stories).length,
1270
+ epics: Object.keys(snapshot.epics).length,
1271
+ targetKind: 'story',
1272
+ });
1273
+ }
1274
+ const targetEpicId = storyEpicId(targetStory, targetStoryId);
1275
+ if (!targetEpicId) {
1276
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1277
+ stories: Object.keys(snapshot.stories).length,
1278
+ epics: Object.keys(snapshot.epics).length,
1279
+ targetKind: 'epic',
1280
+ });
1281
+ }
1282
+ const targetEpic = snapshot.epics[targetEpicId];
1283
+ if (!targetEpic) {
1284
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1285
+ stories: Object.keys(snapshot.stories).length,
1286
+ epics: Object.keys(snapshot.epics).length,
1287
+ targetKind: 'epic',
1288
+ });
1289
+ }
1290
+ // Direct *yolo needs the same epic topology seen by *yoloop so a standalone
1291
+ // invocation can bootstrap the canonical P207 graph epoch. Other story
1292
+ // commands remain dependency-scoped. Stories outside the owning epic are
1293
+ // retained only as compact structural dependencies by the yoloop projector.
1294
+ const yoloEpicGraph = projectionMode === 'yolo-story';
1295
+ const projectedStories = yoloEpicGraph
1296
+ ? buildProjectedYoloopStories(targetEpicId, targetEpic, snapshot)
1297
+ : buildProjectedStories(targetStoryId, snapshot);
1298
+ const projectedEpics = yoloEpicGraph
1299
+ ? buildProjectedYoloopEpics(targetEpicId, projectedStories, snapshot)
1300
+ : buildProjectedEpics(projectedStories, snapshot);
1301
+ if (!projectedStories[targetStoryId] || !projectedEpics[targetEpicId]) {
1302
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1303
+ stories: Object.keys(projectedStories).length,
1304
+ epics: Object.keys(projectedEpics).length,
1305
+ targetKind: 'story',
1306
+ });
1307
+ }
1308
+ const scope = {
1309
+ kind: 'projected',
1310
+ commandId: commandPolicy.commandId,
1311
+ stateProjectionPolicy: commandPolicy.stateProjectionPolicy,
1312
+ projectionMode,
1313
+ trigger,
1314
+ targetEpicId,
1315
+ targetStoryId,
1316
+ includedStoryCount: Object.keys(projectedStories).length,
1317
+ includedEpicCount: Object.keys(projectedEpics).length,
1318
+ omittedStoryCount: Math.max(0, Object.keys(snapshot.stories).length - Object.keys(projectedStories).length),
1319
+ omittedEpicCount: Math.max(0, Object.keys(snapshot.epics).length - Object.keys(projectedEpics).length),
1320
+ reason: 'targeted-invocation',
1321
+ reasonCodes: safeReasonCodes(reasonCodes, yoloEpicGraph ? ['epic-graph-authority-complete'] : []),
1322
+ };
1323
+ return withStateSummary({
1324
+ ...snapshot,
1325
+ stories: projectedStories,
1326
+ epics: projectedEpics,
1327
+ scope,
1328
+ }, snapshot, scope);
1329
+ }
1330
+ function buildTargetedEpicProjection(trigger, snapshot, commandPolicy, targetEpicId, projectionMode, reasonCodes) {
1331
+ const targetEpic = snapshot.epics[targetEpicId];
1332
+ if (!targetEpic) {
1333
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1334
+ stories: Object.keys(snapshot.stories).length,
1335
+ epics: Object.keys(snapshot.epics).length,
1336
+ targetKind: 'epic',
1337
+ });
1338
+ }
1339
+ const projectedStories = buildProjectedTargetEpicStories(targetEpic, snapshot);
1340
+ const projectedEpics = buildProjectedEpics(projectedStories, snapshot, [targetEpicId]);
1341
+ if (!projectedEpics[targetEpicId]) {
1342
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1343
+ stories: Object.keys(projectedStories).length,
1344
+ epics: Object.keys(projectedEpics).length,
1345
+ targetKind: 'epic',
1346
+ });
1347
+ }
1348
+ const scope = {
1349
+ kind: 'projected',
1350
+ commandId: commandPolicy.commandId,
1351
+ stateProjectionPolicy: commandPolicy.stateProjectionPolicy,
1352
+ projectionMode,
1353
+ trigger,
1354
+ targetEpicId,
1355
+ targetStoryId: null,
1356
+ includedStoryCount: Object.keys(projectedStories).length,
1357
+ includedEpicCount: Object.keys(projectedEpics).length,
1358
+ omittedStoryCount: Math.max(0, Object.keys(snapshot.stories).length - Object.keys(projectedStories).length),
1359
+ omittedEpicCount: Math.max(0, Object.keys(snapshot.epics).length - Object.keys(projectedEpics).length),
1360
+ reason: 'targeted-invocation',
1361
+ reasonCodes: safeReasonCodes(reasonCodes),
1362
+ };
1363
+ return withStateSummary({
1364
+ ...snapshot,
1365
+ stories: projectedStories,
1366
+ epics: projectedEpics,
1367
+ scope,
1368
+ }, snapshot, scope);
1369
+ }
1370
+ function buildYoloopProjection(trigger, snapshot, commandPolicy) {
1371
+ const explicitCandidate = explicitYoloopEpicCandidate(trigger);
1372
+ const explicitTargetEpicId = extractTargetEpicId(trigger, snapshot);
1373
+ if (explicitCandidate && !explicitTargetEpicId) {
1374
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1375
+ stories: Object.keys(snapshot.stories).length,
1376
+ epics: Object.keys(snapshot.epics).length,
1377
+ targetKind: 'epic',
1378
+ });
1379
+ }
1380
+ const targetEpicId = extractYoloopTargetEpicId(trigger, snapshot);
1381
+ const shape = classifyInvocationShapeV2({
1382
+ commandId: commandPolicy.commandId,
1383
+ explicitYoloopEpicId: explicitTargetEpicId,
1384
+ sessionYoloopEpicId: explicitTargetEpicId ? null : targetEpicId,
1385
+ });
1386
+ if (shape === 'yoloop-discovery')
1387
+ return buildYoloopDiscoveryProjection(trigger, snapshot, commandPolicy);
1388
+ if (!targetEpicId || (shape !== 'yoloop-target' && shape !== 'yoloop-session')) {
1389
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1390
+ stories: Object.keys(snapshot.stories).length,
1391
+ epics: Object.keys(snapshot.epics).length,
1392
+ targetKind: 'epic',
1393
+ });
1394
+ }
1395
+ const targetEpic = snapshot.epics[targetEpicId];
1396
+ if (!targetEpic) {
1397
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1398
+ stories: Object.keys(snapshot.stories).length,
1399
+ epics: Object.keys(snapshot.epics).length,
1400
+ targetKind: 'epic',
1401
+ });
1402
+ }
1403
+ const projectedStories = buildProjectedYoloopStories(targetEpicId, targetEpic, snapshot);
1404
+ const projectedEpics = buildProjectedYoloopEpics(targetEpicId, projectedStories, snapshot);
1405
+ if (!projectedEpics[targetEpicId]) {
1406
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1407
+ stories: Object.keys(projectedStories).length,
1408
+ epics: Object.keys(projectedEpics).length,
1409
+ targetKind: 'epic',
1410
+ });
1411
+ }
1412
+ const projectionMode = shape;
1413
+ const scope = {
1414
+ kind: 'projected',
1415
+ commandId: commandPolicy.commandId,
1416
+ stateProjectionPolicy: commandPolicy.stateProjectionPolicy,
1417
+ projectionMode,
1418
+ trigger,
1419
+ targetEpicId,
1420
+ targetStoryId: null,
1421
+ targetEpicCoverage: buildTargetEpicCoverage(targetEpicId, targetEpic, projectedStories),
1422
+ includedStoryCount: Object.keys(projectedStories).length,
1423
+ includedEpicCount: Object.keys(projectedEpics).length,
1424
+ omittedStoryCount: Math.max(0, Object.keys(snapshot.stories).length - Object.keys(projectedStories).length),
1425
+ omittedEpicCount: Math.max(0, Object.keys(snapshot.epics).length - Object.keys(projectedEpics).length),
1426
+ reason: 'targeted-invocation',
1427
+ reasonCodes: ['structural-required', projectionMode, 'yoloop-targeted'],
1428
+ };
1429
+ return withStateSummary({
1430
+ ...snapshot,
1431
+ stories: projectedStories,
1432
+ epics: projectedEpics,
1433
+ scope,
1434
+ }, snapshot, scope);
1435
+ }
1436
+ function buildPayloadGuardrailEpics(snapshot, retainedStoryIds) {
1437
+ const projectedEpics = {};
1438
+ for (const [epicId, epic] of Object.entries(snapshot.epics)) {
1439
+ const retainedEpicStories = Array.isArray(epic.stories)
1440
+ ? epic.stories.filter((storyId) => typeof storyId === 'string' && retainedStoryIds.has(storyId))
1441
+ : [];
1442
+ projectedEpics[epicId] = {
1443
+ id: safeToken(epic.id) ?? epicId,
1444
+ ...(safeToken(epic.status, 40) ? { status: safeToken(epic.status, 40) } : {}),
1445
+ ...(typeof epic.total_stories === 'number' && Number.isFinite(epic.total_stories)
1446
+ ? { total_stories: epic.total_stories }
1447
+ : {}),
1448
+ ...(typeof epic.completed_stories === 'number' && Number.isFinite(epic.completed_stories)
1449
+ ? { completed_stories: epic.completed_stories }
1450
+ : {}),
1451
+ ...(retainedEpicStories.length > 0 ? { stories: retainedEpicStories } : {}),
1452
+ ...(retainedEpicStories.length > 0 && Array.isArray(epic.depends_on)
1453
+ ? { depends_on: epic.depends_on.filter((value) => typeof value === 'string' && value.length > 0) }
1454
+ : {}),
1455
+ ...(retainedEpicStories.length > 0 && (epic.branch_mode === 'epic' || epic.branch_mode === 'story')
1456
+ ? { branch_mode: epic.branch_mode }
1457
+ : {}),
1458
+ ...(retainedEpicStories.length > 0 && typeof epic.execution_branch === 'string'
1459
+ ? { execution_branch: epic.execution_branch }
1460
+ : {}),
1461
+ ...(retainedEpicStories.length > 0 && typeof epic.origin_branch === 'string'
1462
+ ? { origin_branch: epic.origin_branch }
1463
+ : {}),
1464
+ ...(retainedEpicStories.length > 0 && (epic.branch_lease === null || typeof epic.branch_lease === 'object')
1465
+ ? { branch_lease: epic.branch_lease }
1466
+ : {}),
1467
+ ...(retainedEpicStories.length > 0 && (epic.origin_binding === null || typeof epic.origin_binding === 'object')
1468
+ ? { origin_binding: epic.origin_binding }
1469
+ : {}),
1470
+ ...(retainedEpicStories.length > 0 && (epic.aggregate_qa_receipt === null || typeof epic.aggregate_qa_receipt === 'object')
1471
+ ? { aggregate_qa_receipt: epic.aggregate_qa_receipt }
1472
+ : {}),
1473
+ ...(retainedEpicStories.length > 0 && (epic.head_reconciliation_receipt === null || typeof epic.head_reconciliation_receipt === 'object')
1474
+ ? { head_reconciliation_receipt: epic.head_reconciliation_receipt }
1475
+ : {}),
1476
+ };
1477
+ }
1478
+ return projectedEpics;
1479
+ }
1480
+ function sourceStoryTotal(snapshot) {
1481
+ return snapshot.stateSummary?.totals.stories
1482
+ ?? ((snapshot.scope?.includedStoryCount ?? Object.keys(snapshot.stories).length) + (snapshot.scope?.omittedStoryCount ?? 0));
1483
+ }
1484
+ function sourceEpicTotal(snapshot) {
1485
+ return snapshot.stateSummary?.totals.epics
1486
+ ?? ((snapshot.scope?.includedEpicCount ?? Object.keys(snapshot.epics).length) + (snapshot.scope?.omittedEpicCount ?? 0));
1487
+ }
1488
+ function updateStateSummaryForPayloadGuardrail(snapshot, scope) {
1489
+ if (!snapshot.stateSummary)
1490
+ return undefined;
1491
+ return {
1492
+ ...snapshot.stateSummary,
1493
+ projection: {
1494
+ ...snapshot.stateSummary.projection,
1495
+ scopeKind: 'projected',
1496
+ projectionMode: scope.projectionMode,
1497
+ includedStoryCount: scope.includedStoryCount,
1498
+ includedEpicCount: scope.includedEpicCount ?? snapshot.stateSummary.projection.includedEpicCount,
1499
+ omittedStoryCount: scope.omittedStoryCount,
1500
+ omittedEpicCount: scope.omittedEpicCount,
1501
+ reason: 'body-size',
1502
+ },
1503
+ reasonCodes: safeReasonCodes(snapshot.stateSummary.reasonCodes, ['payload-size-guardrail', 'state-summary-preserved', 'nonessential-state-degraded']),
1504
+ };
1505
+ }
1506
+ /**
1507
+ * P198.04 -- deterministic post-assembly state degradation.
1508
+ *
1509
+ * This helper is intentionally pure and request-only. It removes historical story
1510
+ * bodies that are not structural for the already-projected request, converts the
1511
+ * epic map to public stubs, keeps `stateSummary`, and preserves structural-required
1512
+ * story/yolo/yoloop target state instead of silently corrupting it.
1513
+ */
1514
+ export function degradeStateSnapshotForPayloadLimit(snapshot) {
1515
+ const scope = snapshot.scope;
1516
+ const retainedStoryIds = new Set();
1517
+ const preserveProjectedStructuralStories = scope?.projectionMode === 'structural-required'
1518
+ || scope?.projectionMode === 'yolo-story'
1519
+ || scope?.projectionMode === 'yoloop-target'
1520
+ || scope?.projectionMode === 'yoloop-session'
1521
+ || scope?.projectionMode === 'yoloop-discovery';
1522
+ if (preserveProjectedStructuralStories) {
1523
+ for (const storyId of Object.keys(snapshot.stories)) {
1524
+ retainedStoryIds.add(storyId);
1525
+ }
1526
+ }
1527
+ else if (scope?.targetStoryId) {
1528
+ addStoryAndDependencies(scope.targetStoryId, snapshot, retainedStoryIds);
1529
+ }
1530
+ const projectedStories = {};
1531
+ for (const storyId of retainedStoryIds) {
1532
+ const story = snapshot.stories[storyId];
1533
+ if (story)
1534
+ projectedStories[storyId] = story;
1535
+ }
1536
+ const projectedEpics = buildPayloadGuardrailEpics(snapshot, retainedStoryIds);
1537
+ const includedStoryCount = Object.keys(projectedStories).length;
1538
+ const includedEpicCount = Object.keys(projectedEpics).length;
1539
+ const omittedStoryCount = Math.max(0, sourceStoryTotal(snapshot) - includedStoryCount);
1540
+ const omittedEpicCount = Math.max(0, sourceEpicTotal(snapshot) - includedEpicCount);
1541
+ const projectionMode = preserveProjectedStructuralStories
1542
+ ? scope?.projectionMode ?? 'structural-required'
1543
+ : scope?.projectionMode === 'yolo-story'
1544
+ ? 'yolo-story'
1545
+ : 'summary-only';
1546
+ const nextScope = {
1547
+ kind: 'projected',
1548
+ commandId: scope?.commandId ?? null,
1549
+ stateProjectionPolicy: scope?.stateProjectionPolicy ?? null,
1550
+ projectionMode,
1551
+ targetEpicId: scope?.targetEpicId ?? null,
1552
+ targetStoryId: scope?.targetStoryId ?? null,
1553
+ ...(scope?.targetEpicCoverage ? { targetEpicCoverage: scope.targetEpicCoverage } : {}),
1554
+ includedStoryCount,
1555
+ includedEpicCount,
1556
+ omittedStoryCount,
1557
+ omittedEpicCount,
1558
+ reason: 'body-size',
1559
+ reasonCodes: safeReasonCodes(scope?.reasonCodes, [
1560
+ 'payload-size-guardrail',
1561
+ retainedStoryIds.size > 0 ? 'structural-targets-preserved' : 'stories-omitted',
1562
+ 'epics-stubbed',
1563
+ 'state-summary-preserved',
1564
+ 'redundant-trigger-omitted',
1565
+ ]),
1566
+ };
1567
+ const stateSummary = updateStateSummaryForPayloadGuardrail(snapshot, nextScope);
1568
+ return {
1569
+ ...snapshot,
1570
+ stories: projectedStories,
1571
+ epics: projectedEpics,
1572
+ scope: nextScope,
1573
+ ...(stateSummary ? { stateSummary } : {}),
1574
+ };
1575
+ }
1576
+ /**
1577
+ * Return a request-scoped state snapshot for invoke commands.
1578
+ *
1579
+ * The function is intentionally pure. Structural uncertainty fails closed;
1580
+ * callers must surface the public code instead of sending a full-state fallback.
1581
+ */
1582
+ export function projectStateSnapshotForInvoke(args, snapshot) {
1583
+ const trigger = args.trim();
1584
+ const commandPolicy = resolveCommandProjectionPolicy(trigger);
1585
+ try {
1586
+ if (!commandPolicy) {
1587
+ if (firstTokenIsStoryReference(trigger)) {
1588
+ const storyReferencePolicy = policy('story-reference', 'story-targeted');
1589
+ const targetStoryId = extractStoryId(trigger);
1590
+ if (targetStoryId) {
1591
+ return buildStoryProjection(trigger, snapshot, storyReferencePolicy, targetStoryId, 'targeted-story', ['story-reference-targeted']);
1592
+ }
1593
+ }
1594
+ return buildSummaryOnlyProjection(trigger, snapshot, policy('unknown', 'adaptive-targeted'), ['unknown-command-summary-only']);
1595
+ }
1596
+ if (commandPolicy.stateProjectionPolicy === 'epic-summary') {
1597
+ return buildCreateEpicProjection(trigger, snapshot, commandPolicy);
1598
+ }
1599
+ if (commandPolicy.stateProjectionPolicy === 'yoloop-targeted') {
1600
+ return buildYoloopProjection(trigger, snapshot, commandPolicy);
1601
+ }
1602
+ const targetStoryId = extractStoryId(trigger);
1603
+ if (commandPolicy.stateProjectionPolicy === 'story-targeted') {
1604
+ if (targetStoryId) {
1605
+ const invocationShape = classifyInvocationShapeV2({ commandId: commandPolicy.commandId, targetStoryId });
1606
+ const yoloStory = invocationShape === 'yolo-story';
1607
+ return buildStoryProjection(trigger, snapshot, commandPolicy, targetStoryId, yoloStory ? 'yolo-story' : commandPolicy.structuralRequired ? 'structural-required' : 'targeted-story', [yoloStory ? 'yolo-story' : commandPolicy.structuralRequired ? 'structural-required' : 'targeted-story']);
1608
+ }
1609
+ if (commandPolicy.commandId === 'yolo' || commandPolicy.commandId === 'yolo-inline') {
1610
+ const invocationShape = classifyInvocationShapeV2({ commandId: commandPolicy.commandId });
1611
+ return buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['yolo-inline', 'stories-omitted', 'historical-content-omitted'], invocationShape ?? 'yolo-inline');
1612
+ }
1613
+ // Commit without a story is an exact root working-tree workflow. It
1614
+ // needs no story graph, but a malformed or unknown target must not gain
1615
+ // this summary-only escape from structural target validation.
1616
+ if (commandPolicy.commandId === 'commit' && /^\*?(?:commit|commit-push)$/i.test(trigger)) {
1617
+ return buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['working-tree-commit', 'stories-omitted', 'historical-content-omitted']);
1618
+ }
1619
+ return commandPolicy.structuralRequired
1620
+ ? (() => {
1621
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1622
+ stories: Object.keys(snapshot.stories).length,
1623
+ epics: Object.keys(snapshot.epics).length,
1624
+ targetKind: 'story',
1625
+ });
1626
+ })()
1627
+ : buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['story-target-missing-summary-only']);
1628
+ }
1629
+ if (commandPolicy.stateProjectionPolicy === 'adaptive-targeted') {
1630
+ if (targetStoryId && snapshot.stories[targetStoryId]) {
1631
+ return buildStoryProjection(trigger, snapshot, commandPolicy, targetStoryId, 'targeted-story', ['adaptive-story-targeted']);
1632
+ }
1633
+ const targetEpicId = extractTargetEpicId(trigger, snapshot);
1634
+ if (targetEpicId) {
1635
+ return buildTargetedEpicProjection(trigger, snapshot, commandPolicy, targetEpicId, 'targeted-epic', ['adaptive-epic-targeted']);
1636
+ }
1637
+ return buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['adaptive-summary-only', 'target-unresolved-summary-only']);
1638
+ }
1639
+ if (commandPolicy.stateProjectionPolicy === 'epic-targeted') {
1640
+ // The root *arch-plan pipeline delegates its current stage with the
1641
+ // internal marker `epic-arch`. It has no user-selected epic yet; keep
1642
+ // this exact marker only when the bounded root checkpoint names the
1643
+ // same stage. The server still verifies the accounting receipt.
1644
+ if (commandPolicy.commandId.startsWith('arch-')
1645
+ && /(?:^|\s)epic-arch\s*$/i.test(trigger)
1646
+ && snapshot.archPlan?.execution?.currentStageCommand === commandPolicy.commandId) {
1647
+ return buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['architecture-root-delegated']);
1648
+ }
1649
+ const targetEpicId = extractTargetEpicId(trigger, snapshot);
1650
+ if (targetEpicId) {
1651
+ return buildTargetedEpicProjection(trigger, snapshot, commandPolicy, targetEpicId, commandPolicy.structuralRequired ? 'structural-required' : 'targeted-epic', [commandPolicy.structuralRequired ? 'structural-required' : 'targeted-epic']);
1652
+ }
1653
+ return commandPolicy.structuralRequired
1654
+ ? (() => {
1655
+ throw new StructuralDagError('STRUCTURAL_TARGET_NOT_FOUND', {
1656
+ stories: Object.keys(snapshot.stories).length,
1657
+ epics: Object.keys(snapshot.epics).length,
1658
+ targetKind: 'epic',
1659
+ });
1660
+ })()
1661
+ : buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['epic-target-missing-summary-only']);
1662
+ }
1663
+ if (commandPolicy.stateProjectionPolicy === 'continuity-scoped') {
1664
+ return buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['continuity-scoped-summary-only']);
1665
+ }
1666
+ return buildSummaryOnlyProjection(trigger, snapshot, commandPolicy, ['policy-full-summary-only']);
1667
+ }
1668
+ catch (error) {
1669
+ if (error instanceof StructuralDagError)
1670
+ throw error;
1671
+ if (commandPolicy?.structuralRequired) {
1672
+ throw new StructuralDagError('STRUCTURAL_DEPENDENCY_MISSING', {
1673
+ stories: Object.keys(snapshot.stories).length,
1674
+ epics: Object.keys(snapshot.epics).length,
1675
+ projectionErrors: 1,
1676
+ });
1677
+ }
1678
+ return buildSummaryOnlyProjection(trigger, snapshot, commandPolicy ?? policy('unknown', 'adaptive-targeted'), ['projection-error-summary-only']);
1679
+ }
1680
+ }
1681
+ const V2_INVOCATION_SHAPES = new Set([
1682
+ 'yolo-story',
1683
+ 'yolo-inline',
1684
+ 'yoloop-target',
1685
+ 'yoloop-session',
1686
+ 'yoloop-discovery',
1687
+ ]);
1688
+ function projectedEdgeCount(snapshot) {
1689
+ let edges = 0;
1690
+ for (const collection of [snapshot.stories, snapshot.epics]) {
1691
+ for (const entry of Object.values(collection)) {
1692
+ if (Array.isArray(entry.depends_on)) {
1693
+ edges += entry.depends_on.filter((value) => typeof value === 'string').length;
1694
+ }
1695
+ }
1696
+ }
1697
+ return edges;
1698
+ }
1699
+ /**
1700
+ * Versioned result contract for the five structural YOLO/yoloop shapes.
1701
+ * Other command families retain their existing projection policy and return
1702
+ * null because they are outside StateProjectionV2's closed shape union.
1703
+ */
1704
+ export function projectStateSnapshotResultV2ForInvoke(args, snapshot) {
1705
+ const commandPolicy = resolveCommandProjectionPolicy(args.trim());
1706
+ if (!commandPolicy
1707
+ || !['yolo', 'yolo-inline', 'yoloop'].includes(commandPolicy.commandId)) {
1708
+ return null;
1709
+ }
1710
+ try {
1711
+ const projected = projectStateSnapshotForInvoke(args, snapshot);
1712
+ const shape = projected.scope?.projectionMode;
1713
+ if (!shape || !V2_INVOCATION_SHAPES.has(shape)) {
1714
+ throw new StructuralDagError('STRUCTURAL_DEPENDENCY_MISSING', {
1715
+ stories: Object.keys(projected.stories).length,
1716
+ epics: Object.keys(projected.epics).length,
1717
+ projectionShapeErrors: 1,
1718
+ });
1719
+ }
1720
+ return Object.freeze({
1721
+ ok: true,
1722
+ version: 2,
1723
+ shape,
1724
+ snapshot: projected,
1725
+ included: {
1726
+ epics: projected.scope?.includedEpicCount ?? Object.keys(projected.epics).length,
1727
+ stories: projected.scope?.includedStoryCount ?? Object.keys(projected.stories).length,
1728
+ edges: projectedEdgeCount(projected),
1729
+ },
1730
+ omitted: {
1731
+ epics: projected.scope?.omittedEpicCount ?? 0,
1732
+ stories: projected.scope?.omittedStoryCount ?? 0,
1733
+ },
1734
+ cycleCount: 0,
1735
+ });
1736
+ }
1737
+ catch (error) {
1738
+ if (!(error instanceof StructuralDagError))
1739
+ throw error;
1740
+ return Object.freeze({
1741
+ ok: false,
1742
+ code: error.code,
1743
+ publicDetails: {
1744
+ ...error.publicDetails,
1745
+ ...(error.code === 'STRUCTURAL_CONTEXT_TOO_LARGE'
1746
+ ? {}
1747
+ : { planningCause: planningProjectionCauseForStructuralCode(error.code) }),
1748
+ },
1749
+ });
1750
+ }
1751
+ }