@ornexus/neocortex 4.62.0 → 4.64.1

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 (77) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +28 -5
  5. package/package.json +3 -4
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/commands/invoke.d.ts +7 -0
  9. package/packages/client/dist/commands/invoke.js +50 -50
  10. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  11. package/packages/client/dist/commands/refresh-memory.js +5 -3
  12. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +86 -1
  13. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -3
  14. package/packages/client/dist/git/git-lifecycle-store.d.ts +30 -2
  15. package/packages/client/dist/git/git-lifecycle-store.js +7 -7
  16. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  17. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  18. package/packages/client/dist/git/release-gate-env.d.ts +2 -41
  19. package/packages/client/dist/git/release-gate-env.js +1 -1
  20. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  21. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  22. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  23. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  24. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  25. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  26. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  27. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  28. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  29. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  30. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  31. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  32. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  33. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +30 -0
  34. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -8
  35. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  36. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  37. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  38. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  39. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  40. package/packages/client/dist/runner/headless/types.js +2 -2
  41. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  42. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  43. package/packages/client/dist/state/state-json-repair.js +4 -3
  44. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  45. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  46. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  47. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  48. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  49. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  50. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  51. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  52. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  53. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +46 -1
  54. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  55. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  56. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  57. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +94 -0
  58. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  59. package/packages/shared/dist/compatibility/index.js +6 -0
  60. package/packages/shared/dist/project-manifest-projection.js +6 -3
  61. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  62. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  63. package/packages/shared/dist/yoloop/epic-terminal-git.js +4 -0
  64. package/targets-stubs/antigravity/gemini.md +1 -1
  65. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  66. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  67. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  68. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  69. package/targets-stubs/claude-code/neocortex.md +2 -2
  70. package/targets-stubs/codex/AGENTS.md +1 -1
  71. package/targets-stubs/codex/install-codex.sh +12 -4
  72. package/targets-stubs/cursor/agent.md +2 -2
  73. package/targets-stubs/gemini-cli/agent.md +2 -2
  74. package/targets-stubs/lib/managed-config-merge.js +385 -7
  75. package/targets-stubs/lib/managed-profile.sh +47 -7
  76. package/targets-stubs/opencode/neocortex-root.md +1 -1
  77. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1 +1 @@
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 n=(r,e,t={})=>({commandId:r,stateProjectionPolicy:e,...t}),A=Object.freeze({status:n("status","full"),"arch-plan":n("arch-plan","full"),"arch-prd":n("arch-prd","full"),"arch-architecture":n("arch-architecture","epic-targeted",{structuralRequired:!0}),"arch-api-contracts":n("arch-api-contracts","epic-targeted",{structuralRequired:!0}),"arch-api-integrations":n("arch-api-integrations","epic-targeted",{structuralRequired:!0}),"arch-database":n("arch-database","epic-targeted",{structuralRequired:!0}),"arch-security":n("arch-security","epic-targeted",{structuralRequired:!0}),"arch-design-system":n("arch-design-system","epic-targeted",{structuralRequired:!0}),"arch-ux-design":n("arch-ux-design","epic-targeted",{structuralRequired:!0}),"arch-performance":n("arch-performance","epic-targeted",{structuralRequired:!0}),"arch-testing":n("arch-testing","epic-targeted",{structuralRequired:!0}),"arch-infrastructure":n("arch-infrastructure","epic-targeted",{structuralRequired:!0}),"arch-review":n("arch-review","epic-targeted",{structuralRequired:!0}),"arch-fitness-functions":n("arch-fitness-functions","epic-targeted",{structuralRequired:!0}),"create-epic":n("create-epic","epic-summary"),"idea-diagnose":n("idea-diagnose","full"),"idea-research":n("idea-research","epic-targeted",{structuralRequired:!0}),"generate-epic":n("generate-epic","epic-targeted",{structuralRequired:!0}),exec:n("exec","story-targeted",{structuralRequired:!0}),yolo:n("yolo","story-targeted",{structuralRequired:!0}),"yolo-inline":n("yolo-inline","story-targeted",{structuralRequired:!0}),epic:n("epic","epic-targeted",{structuralRequired:!0}),"setup-branch":n("setup-branch","story-targeted",{structuralRequired:!0}),diagnose:n("diagnose","adaptive-targeted"),"diagnose-inline":n("diagnose-inline","full"),research:n("research","adaptive-targeted"),"research-inline":n("research-inline","full"),"write-spec":n("write-spec","story-targeted",{structuralRequired:!0}),"create-tasks":n("create-tasks","story-targeted",{structuralRequired:!0}),implement:n("implement","story-targeted",{structuralRequired:!0}),commit:n("commit","story-targeted",{structuralRequired:!0}),"commit-push":n("commit","story-targeted",{structuralRequired:!0}),sync:n("sync","story-targeted",{structuralRequired:!0}),"sync-main":n("sync","story-targeted",{structuralRequired:!0}),"create-pr":n("create-pr","story-targeted",{structuralRequired:!0}),review:n("review","story-targeted"),"review-pr":n("review","story-targeted"),merge:n("merge","story-targeted",{structuralRequired:!0}),"merge-pr":n("merge","story-targeted",{structuralRequired:!0}),"fix-blocked":n("fix-blocked","story-targeted"),"finalize-epic":n("finalize-epic","epic-targeted"),"resolve-conflicts":n("resolve-conflicts","story-targeted"),"update-memory":n("update-memory","full"),"update-project-memory":n("update-memory","story-targeted",{structuralRequired:!0}),refactor:n("refactor","adaptive-targeted"),"refactor-suggest":n("refactor","story-targeted",{structuralRequired:!0}),cleanup:n("cleanup","full"),audit:n("audit","full"),"tech-debt":n("tech-debt","full"),menu:n("menu","full"),plans:n("plans","full"),billing:n("billing","full"),subscribe:n("subscribe","full"),"qa-scan":n("qa-scan","full"),yoloop:n("yoloop","yoloop-targeted",{structuralRequired:!0}),"migrate-state":n("migrate-state","full"),"migrate-project-id":n("migrate-project-id","full"),"policy-audit":n("policy-audit","full"),"mutation-test":n("mutation-test","full"),"sync-openapi":n("sync-openapi","full"),"generate-pacts":n("generate-pacts","full"),"verify-pacts":n("verify-pacts","full"),"property-test":n("property-test","full"),"property-tests":n("property-test","story-targeted",{structuralRequired:!0}),"chaos-plan":n("chaos-plan","full"),"ui-ux-review":n("ui-ux-review","adaptive-targeted"),"solyd-system":n("solyd-system","adaptive-targeted"),goal:n("goal","continuity-scoped"),loop:n("loop","continuity-scoped"),jobs:n("jobs","continuity-scoped"),runner:n("runner","continuity-scoped"),"goal-tick":n("goal-tick","continuity-scoped"),"loop-tick":n("loop-tick","continuity-scoped"),"validate-tests":n("validate-tests","story-targeted",{structuralRequired:!0}),"qa-gate":n("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 w(r,e=120){if(typeof r!="string")return;const t=r.trim(),i=d(r,e);return i===t?i:void 0}function T(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(o=>typeof o=="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||!T(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||!w(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 oe(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||!T(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 ne(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 o=d(c,80);if(!(!o||e.has(o))&&(e.add(o),t.push(o),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 o=de(r,e,t,i,c);return I({...e,scope:o},e,o)}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(o=>typeof o=="string"&&o.length>0);for(const o of c)if(e.epics[o])return o;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 o=P(c,e);if(o)return o}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 o=i?.lock?.currentEpicId??i?.lock?.epicId;return typeof o=="string"&&e.epics[o]?o: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 o of c)typeof o=="string"&&x(o,e,t)}function me(r,e){const t=C(e.stories,[r]),i={};for(const c of t.orderedIds){const o=e.stories[c];o&&(i[c]=o)}return i}function $(r,e,t=[]){const i={};for(const c of t)e.epics[c]&&(i[c]=e.epics[c]);for(const[c,o]of Object.entries(r)){const s=j(o,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 o of c)typeof o=="string"&&o.length>0&&ge(o,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 o={};for(const s of[...c].sort((a,u)=>a.localeCompare(u,"en"))){const a=t.epics[s];a&&(o[s]=s===r?a:H(s,a))}return o}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),o={};for(const s of c.orderedIds){const a=t.stories[s];a&&(o[s]=j(a,s)===r?ne(s,a):Y(s,a))}return o}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")),o=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:o,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 o=e.source==="create-epic"||e.source==="discovered"?e.source:void 0,s=T(e.branch_name),a=w(e.last_step,120),u=Array.isArray(e.steps_completed)&&e.steps_completed.length<=64?e.steps_completed.map(m=>w(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?oe(r,e):void 0;return{...i,...o?{source:o}:{},...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,o)=>c.localeCompare(o,"en")):[],i=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(c=>typeof c=="string"&&c.length>0))].sort((c,o)=>c.localeCompare(o,"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),o=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:o,epics:s,scope:a},e,a)}function _e(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const o of i)typeof o=="string"&&x(o,e,t);const c={};for(const o of t){const s=e.stories[o];s&&(c[o]=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,o={...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(o).length>0?o: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),o=d(e?.activeStepId),s=i&&r.stories[i]?j(r.stories[i],i):null;if((i||c||o)&&N(r,c??s))return{epicId:c??null,storyId:i??null,stepId:o??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),o=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:o,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 o of Object.keys(e.epics))i[o]={id:o};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 o=Se(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(o).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(o).length),reason:"summary-only",reasonCodes:_(i)};return I({...e,stories:{},epics:o,scope:s},e,s)}function D(r,e,t,i,c,o){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:_(o,l?["epic-graph-authority-complete"]:[])};return I({...e,stories:f,epics:p,scope:g},e,g)}function W(r,e,t,i,c,o){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:_(o)};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 o=fe(r,e),s=O({commandId:t.commandId,explicitYoloopEpicId:c,sessionYoloopEpicId:c?null:o});if(s==="yoloop-discovery")return be(r,e,t);if(!o||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[o];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(o,a,e),l=V(o,u,e);if(!l[o])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:o,targetStoryId:null,targetEpicCoverage:he(o,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 we(r,e){const t={};for(const[i,c]of Object.entries(r.epics)){const o=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}:{},...o.length>0?{stories:o}:{},...o.length>0&&Array.isArray(c.depends_on)?{depends_on:c.depends_on.filter(s=>typeof s=="string"&&s.length>0)}:{},...o.length>0&&(c.branch_mode==="epic"||c.branch_mode==="story")?{branch_mode:c.branch_mode}:{},...o.length>0&&typeof c.execution_branch=="string"?{execution_branch:c.execution_branch}:{},...o.length>0&&typeof c.origin_branch=="string"?{origin_branch:c.origin_branch}:{},...o.length>0&&(c.branch_lease===null||typeof c.branch_lease=="object")?{branch_lease:c.branch_lease}:{},...o.length>0&&(c.origin_binding===null||typeof c.origin_binding=="object")?{origin_binding:c.origin_binding}:{},...o.length>0&&(c.aggregate_qa_receipt===null||typeof c.aggregate_qa_receipt=="object")?{aggregate_qa_receipt:c.aggregate_qa_receipt}:{},...o.length>0&&(c.head_reconciliation_receipt===null||typeof c.head_reconciliation_receipt=="object")?{head_reconciliation_receipt:c.head_reconciliation_receipt}:{},...o.length>0&&c.story_worktree_evidence!==null&&typeof c.story_worktree_evidence=="object"?{story_worktree_evidence:c.story_worktree_evidence}:{}}}return t}function Te(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 o=we(r,t),s=Object.keys(c).length,a=Object.keys(o).length,u=Math.max(0,Te(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:o,scope:p,...g?{stateSummary:g}:{}}}function xe(r,e){const t=r.trim(),i=z(t);try{if(!i){if(ue(t)){const o=n("story-reference","story-targeted"),s=F(t);if(s)return D(t,e,o,s,"targeted-story",["story-reference-targeted"])}return b(t,e,n("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 o=O({commandId:i.commandId});return b(t,e,i,["yolo-inline","stories-omitted","historical-content-omitted"],o??"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 o=R(t,e);return o?W(t,e,i,o,"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 o=R(t,e);return o?W(t,e,i,o,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??n("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
+ 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 w(r,e=120){if(typeof r!="string")return;const t=r.trim(),i=d(r,e);return i===t?i:void 0}function T(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||!T(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||!w(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||!T(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")):void 0,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)}:{},...t?{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=T(e.branch_name),a=w(e.last_step,120),u=Array.isArray(e.steps_completed)&&e.steps_completed.length<=64?e.steps_completed.map(m=>w(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 we(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}:{},...n.length>0&&c.story_worktree_evidence!==null&&typeof c.story_worktree_evidence=="object"?{story_worktree_evidence:c.story_worktree_evidence}:{},...n.length>0&&c.branch_mode_conversion_receipt!==null&&typeof c.branch_mode_conversion_receipt=="object"&&!Array.isArray(c.branch_mode_conversion_receipt)?{branch_mode_conversion_receipt:c.branch_mode_conversion_receipt}:{}}}return t}function Te(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=we(r,t),s=Object.keys(c).length,a=Object.keys(n).length,u=Math.max(0,Te(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};
@@ -13,11 +13,22 @@ export interface StateRepairAuditSummary {
13
13
  readonly reasonCodes: readonly string[];
14
14
  readonly backupPath?: string;
15
15
  readonly changes: readonly string[];
16
+ /** P227.02: set when a story worktree suppressed the repair write. */
17
+ readonly skipped?: 'story-worktree';
18
+ /** P227.02: number of in-memory repair changes that were not written. */
19
+ readonly divergenceCount?: number;
20
+ /** P227.02: whether a shared state migration would have been applied. */
21
+ readonly migrationPending?: boolean;
16
22
  }
23
+ /** P227.02: checkout in which the pre-invoke repair runs. */
24
+ export type StateRepairCheckoutKind = 'main' | 'story-worktree';
25
+ export declare const STATE_REPAIR_SKIPPED_STORY_WORKTREE: "state-repair-skipped-story-worktree";
17
26
  export interface StateJsonPreInvokeRepairOptions {
18
27
  readonly args?: string;
19
28
  readonly canonicalCommandId?: string;
20
29
  readonly nowIso?: string;
30
+ /** P227.02: `story-worktree` makes the repair read-only; absent means detected (DEC-09). */
31
+ readonly checkoutKind?: StateRepairCheckoutKind;
21
32
  /** Internal, physically verified completion overlay; never persisted as story state. */
22
33
  readonly effectiveDoneStoryIds?: readonly string[];
23
34
  }
@@ -80,4 +91,16 @@ export interface EpicAggregateReconciliationResult<TState extends Record<string,
80
91
  export declare function isInlineYoloMaterialization(args: unknown, canonicalCommandId?: string | null): boolean;
81
92
  export declare function isP189DoneLikeStoryStatus(value: unknown): boolean;
82
93
  export declare function reconcileEpicAggregatesInState<TState extends Record<string, unknown>>(input: unknown, options?: EpicAggregateReconciliationOptions): EpicAggregateReconciliationResult<TState>;
94
+ /**
95
+ * P227.02 (ADR-1, narrowed by DEC-08): a linked Git worktree (git-dir differs
96
+ * from the common dir) is a story worktree only when it carries a Neocortex
97
+ * story signal: the adopted/managed `NEOCORTEX_STORY_WORKTREE_ID` or a
98
+ * managed story-worktree path. Other linked worktrees (integration or gate
99
+ * workspaces, test fixtures) keep the main-checkout repair. Any detection
100
+ * failure keeps the main-checkout behavior.
101
+ */
102
+ export declare function detectStateRepairCheckoutKind(projectRoot: string, env?: NodeJS.ProcessEnv): StateRepairCheckoutKind;
103
+ /** Returns a private copy of the in-memory overlay when it matches `sourceSha256`. */
104
+ export declare function readStoryWorktreeRepairOverlay(projectRoot: string, sourceSha256: string | undefined): Record<string, unknown> | undefined;
105
+ export declare function __resetStoryWorktreeRepairOverlaysForTests(): void;
83
106
  export declare function maybeRepairStateJsonBeforeInvoke(projectRoot: string, options?: StateJsonPreInvokeRepairOptions): StateRepairAuditSummary;
@@ -1,3 +1,4 @@
1
- import{existsSync as F,mkdirSync as J,readFileSync as q,renameSync as B,writeFileSync as H,copyFileSync as W}from"node:fs";import{join as x}from"node:path";import{randomBytes as V}from"node:crypto";import{planStateMigration as Z,StateMigrationHardStopError as U}from"../../../shared/dist/state/index.js";import{applyStateMigration as K,previewStateMigration as Y,StateMigrationApplyError as Q}from"../migrations/state-json.js";import{readGitLifecycleRuntimeSync as X,verifyAcceptedGitLifecycleStoryCheckpointSync as ee}from"../git/git-lifecycle-store.js";class S extends Error{reasonCode;constructor(t,o){super(t),this.reasonCode=o,this.name="StateRepairHardStopError"}}const te="P189-GAP-STATE-SHAPE",f={reconciled:"epic_aggregate_reconciled",totalRecounted:"epic_total_stories_recounted",completedRecounted:"epic_completed_stories_recounted",statusPromotedDone:"epic_status_promoted_done",completedAtSet:"epic_completed_at_set",stateNotObject:"epic_aggregate_state_not_object",epicsNotObject:"epic_aggregate_epics_not_object",storiesNotObject:"epic_aggregate_stories_not_object",scopeProjected:"epic_aggregate_scope_projected",epicNotObject:"epic_aggregate_epic_not_object",epicIdConflict:"epic_aggregate_epic_id_conflict",storyListNotArray:"epic_aggregate_story_list_not_array",storyRefInvalid:"epic_aggregate_story_ref_invalid",storyRefDuplicate:"epic_aggregate_story_ref_duplicate",storyMissing:"epic_aggregate_story_missing",storyNotObject:"epic_aggregate_story_not_object",storyIdConflict:"epic_aggregate_story_id_conflict",storyEpicConflict:"epic_aggregate_story_epic_conflict",terminalIncompleteConflict:"epic_aggregate_terminal_incomplete_conflict"},oe=new Set(["yolo","implement","diagnose","research","write-spec","create-tasks","refactor-suggest","property-tests","validate-tests","qa-gate","update-project-memory","commit-push","sync-main","create-pr","review-pr","merge-pr","review"]),re=new Set(["yoloop","auto-yolo","epic-runner","story-runner","loop-yolo","auto-epic"]);function d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j(){return new Date().toISOString()}function ne(){return j().replace(/[:.]/g,"-")}function ie(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function k(e){const[t]=e.trim().split(/\s+/,1);return t?t.replace(/^@?\*/,"").replace(/^@/,"").toLowerCase():null}function se(e){const[t]=e.trim().split(/\s+/,1);if(!t)return!1;const o=t.replace(/^@/,"");return/^[A-Z]?\d+(?:\.\d+)+$/i.test(o)||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(o)}function R(e){const t=e.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return t?.[1]?t[1]:e.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function I(e,t){if(typeof e!="string")return!1;const o=t??k(e);return(o==="yolo"||o==="yolo-inline")&&$(e).length>0&&R(e)===null}function $(e){const t=e.trim(),o=t.search(/\s/);return o===-1?"":t.slice(o).trim()}function ce(e){const t=$(e).split(/\s+/).find(o=>o.length>0&&!o.startsWith("-"));return t?t.replace(/^@/,"").replace(/^['"]|['"]$/g,""):null}function O(e,t){const r=e.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),s=[r,r.toUpperCase(),/^p\d+$/i.test(r)?`P${r.replace(/^p/i,"")}`:null,/^\d+$/.test(r)?`P${r}`:null].filter(c=>typeof c=="string"&&c.length>0);for(const c of s)if(d(t[c]))return c;return null}function ae(e,t){const o=e.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return o?.[1]?O(o[1],t):null}function P(e,t,o){if(typeof t!="string"||t.trim().length===0||!d(e.epics)||!d(e.stories))return;const r=t.trim(),s=o??k(r);if(s!==null&&oe.has(s)||se(r)){const l=R(r),a=l?e.stories[l]:void 0;if(d(a)&&typeof a.epic_id=="string"&&d(e.epics[a.epic_id]))return a.epic_id;const n=l?.split(".")[0];if(n&&d(e.epics[n]))return n}if(s!==null&&re.has(s)){const l=ae(r,e.epics);if(l)return l;const a=ce(r);if(a){const n=O(a,e.epics);if(n)return n}}}const E="pr_merged_issue_closed_reconciled",pe="invalid_workflow_issue_removed";function b(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}const le=new Set(["done","completed","merged"]),de=new Set(["done","completed","merged"]);function T(e){return le.has(b(e))}function M(e){return de.has(b(e))}function h(e,t){throw new S(`${t} (${te} if this shape is intentionally new).`,e)}function ue(e){return JSON.parse(JSON.stringify(e))}function fe(e,t){const o=t.scope??e.scope;if(!d(o))return;const r=typeof o.kind=="string"?o.kind:null,s=typeof o.omittedStoryCount=="number"?o.omittedStoryCount:0,c=typeof o.omittedEpicCount=="number"?o.omittedEpicCount:0;(r==="projected"||s>0||c>0)&&h(f.scopeProjected,"[Neocortex] state.json aggregate reconciliation stopped: projected or partial state coverage cannot prove epic aggregates.")}function ge(e,t){const o=[],r=new Set;for(const s of t)(typeof s!="string"||s.length===0)&&h(f.storyRefInvalid,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" has a non-string or empty story reference.`),r.has(s)&&h(f.storyRefDuplicate,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" lists story "${u(s)}" more than once.`),r.add(s),o.push(s);return o}function _e(e,t,o){const r=o[t];return r===void 0&&h(f.storyMissing,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" references missing story "${u(t)}".`),d(r)||h(f.storyNotObject,`[Neocortex] state.json aggregate reconciliation stopped: story "${u(t)}" is not an object.`),r.id!==t&&h(f.storyIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: story key "${u(t)}" conflicts with its id field.`),r.epic_id!==e&&h(f.storyEpicConflict,`[Neocortex] state.json aggregate reconciliation stopped: story "${u(t)}" does not belong to epic "${u(e)}".`),r}function v(e,t){e.includes(t)||e.push(t)}function me(e,t={}){d(e)||h(f.stateNotObject,"[Neocortex] state.json aggregate reconciliation stopped: top-level state must be an object."),d(e.epics)||h(f.epicsNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `epics` must be an object before counts are authoritative."),d(e.stories)||h(f.storiesNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `stories` must be an object before counts are authoritative."),fe(e,t);const o=ue(e),r=o.epics,s=o.stories,c=[],l=[],a=new Set(t.effectiveDoneStoryIds??[]);for(const[n,i]of Object.entries(r)){if(t.targetEpicId&&n!==t.targetEpicId)continue;d(i)||h(f.epicNotObject,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(n)}" is not an object.`),i.id!==n&&h(f.epicIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: epic key "${u(n)}" conflicts with its id field.`),Array.isArray(i.stories)||h(f.storyListNotArray,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(n)}" has non-array stories.`);const p=ge(n,i.stories),g=p.length,m=p.filter(A=>{const z=_e(n,A,s);return T(z.status)||a.has(A)}).length,_=g>0&&m===g;if(M(i.status)&&!_&&g>0&&h(f.terminalIncompleteConflict,`[Neocortex] state.json aggregate reconciliation stopped: terminal epic "${u(n)}" has incomplete listed stories.`),t.preserveGitLifecycleAggregates&&(i.branch_mode==="epic"||typeof i.execution_branch=="string"))continue;const y=[],N={total_stories:i.total_stories,completed_stories:i.completed_stories,status:i.status,completed_at:i.completed_at};if(i.total_stories!==g&&(i.total_stories=g,v(y,f.totalRecounted)),i.completed_stories!==m&&(i.completed_stories=m,v(y,f.completedRecounted)),!M(i.status)&&_&&(i.status="done",v(y,f.statusPromotedDone),(i.completed_at===void 0||i.completed_at===null)&&(i.completed_at=t.nowIso??j(),v(y,f.completedAtSet))),y.length>0){v(y,f.reconciled);for(const A of y)v(c,A);l.push({epicId:n,reasonCodes:y,previous:N,next:{total_stories:g,completed_stories:m,status:i.status,completed_at:i.completed_at}})}}return{mutated:JSON.stringify(o)!==JSON.stringify(e),state:o,reasonCodes:c,changes:l}}function w(e,t){const o=e[t];return d(o)?o:null}function ye(e){const t=w(e,"issueCloseAudit")??w(e,"issue_close_audit");if(t){const s=b(t.event).replace(/-/g,"_"),c=t.publicSafe===!0||t.public_safe===!0,l=t.rawLogStorage==="forbidden"||t.raw_log_storage==="forbidden";if(s==="story_issue_closed"&&c&&l)return!0}const o=w(e,"completionEvidence")??w(e,"completion_evidence"),r=b(o?.issueState??o?.issue_state??o?.state);return e.issue_closed===!0||b(e.issue_state??e.issueState??e.workflow_issue_state)==="closed"||r==="closed"}function D(e){const t=w(e,"completionEvidence")??w(e,"completion_evidence"),o=w(e,"scopedCiEvidence")??w(e,"scoped_ci_evidence"),r=[e.physicalMergeStatus,e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState,o?.prState].map(b);return e.merged===!0||r.includes("merged")||b(o?.finalState)==="can-merge"&&e.merged===!0}function he(e){const t=w(e,"completionEvidence")??w(e,"completion_evidence"),o=[e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState].map(b),r=D(e),s=["denied-external-gate","denied-local-or-repo","not-attempted"].includes(b(e.physicalMergeStatus)),c=o.includes("closed")||o.includes("closed-unmerged");return r&&(e.merged===!1||s||c)||e.merged===!0&&s}function Se(e,t,o){const r=`state-completion-reconciliation:${u(t)}`,s=e.filter(d).map(n=>({...n})),c={id:r,status:"open",reason:"stale_state_completion_evidence_observed",reason_codes:[E],category:"state/completion-reconciliation",story_id:u(t),public_safe:!0,raw_log_storage:"forbidden",created_at:o,last_seen_at:o,occurrences:1},l=s.findIndex(n=>n.id===r);if(l<0)return[...s,c];const a=s[l];return s[l]={...a,...c,created_at:typeof a.created_at=="string"?a.created_at:o,occurrences:Math.max(1,typeof a.occurrences=="number"?a.occurrences:1)+1},s}function be(e,t,o,r){const s=d(e.stories)?e.stories:null;if(!s)return;const c=[],l=j();for(const[a,n]of Object.entries(s)){if(!d(n))continue;const i=typeof n.epic_id=="string"?n.epic_id:a.split(".")[0];if(r&&i!==r)continue;const p=b(n.status);if(he(n))throw new S(`[Neocortex] state.json repair stopped: story "${a}" has conflicting PR merge completion evidence. Resolve .neocortex/state.json manually before invoking Neocortex.`,"conflicting_completion_evidence");if(p!=="pr-reviewed"||!D(n)||!ye(n))continue;const g=typeof n.status=="string"?n.status:p,m=ie(n.steps_completed);n.status="done",n.last_step="step-c-12-merge-pr",n.steps_completed=Array.from(new Set([...m,"step-c-12-merge-pr"])),n.merged=!0,n.physicalMergeStatus="merged",n.completion_reconciled_at=l,t.push(`reconciled completion evidence for story ${a}`),o.push(E),c.push({schemaVersion:1,publicSafe:!0,rawLogStorage:"forbidden",storyId:u(a),previousStatus:g,nextStatus:"done",reasonCodes:[E],reconciledAt:l}),e.state_repair_debt=Se(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],a,l)}c.length>0&&(e.state_completion_reconciliations=[...Array.isArray(e.state_completion_reconciliations)?e.state_completion_reconciliations.filter(d):[],...c])}function we(e,t,o){const r=d(e.stories)?e.stories:null;if(r)for(const[s,c]of Object.entries(r))!d(c)||!Object.prototype.hasOwnProperty.call(c,"workflow_issue")||typeof c.workflow_issue=="number"&&Number.isFinite(c.workflow_issue)||(delete c.workflow_issue,t.push(`removed invalid workflow_issue from story ${u(s)}`),o.push(pe))}function ve(e,t={}){if(Array.isArray(e.stories))throw new S("[Neocortex] state.json repair stopped: `stories` is an Array. Convert it to an object keyed by story ID or run `*migrate-state --preview` for guidance.","stories_array_ambiguous");if(d(e.epics)){for(const[i,p]of Object.entries(e.epics))if(d(p)&&p.stories!==void 0&&!Array.isArray(p.stories))throw new S(`[Neocortex] state.json repair stopped: epic "${i}" has non-array \`stories\`. Repair this ambiguous shape manually before invoking Neocortex.`,"epic_stories_not_array")}if(e.schema_version!==void 0&&e.schema_version!==0&&e.schema_version!==1)throw new S(`[Neocortex] state.json repair stopped: schema_version=${String(e.schema_version)} is not a safe automatic downgrade target. Run \`*migrate-state --preview\` or repair the schema version manually.`,"unsupported_schema_version");if(I(t.args,t.canonicalCommandId)){for(const i of["epics","stories"]){const p=e[i];if(p!==void 0){if(!d(p))throw new S("[Neocortex] inline materialization stopped: invalid state collection.","inline_state_collection_invalid");for(const[g,m]of Object.entries(p)){if(!d(m))throw new S("[Neocortex] inline materialization stopped: invalid state record.","inline_state_record_invalid");if(m.id!==void 0&&m.id!==g)throw new S("[Neocortex] inline materialization stopped: conflicting state identity.","inline_state_identity_conflict")}}}return{mutated:!1,state:e,reasonCodes:[],changes:[]}}let o;try{o=Z(e)}catch(i){throw i instanceof U?new S(`[Neocortex] state.json repair stopped by shared migration planner: ${i.message}`,i.reasonCode):i}let r=JSON.parse(JSON.stringify(o.kind==="migrate"?o.plan.targetState:e));const s=o.kind==="migrate"?o.plan.steps.map(i=>`shared migration ${i.kind}: ${i.target}`):[],c=o.kind==="migrate"?["state_migration_shared_plan"]:[];let l=[];const a=P(r,t.args,t.canonicalCommandId);if(we(r,s,c),be(r,s,c,a),typeof t.args=="string"){const i=me(r,{nowIso:t.nowIso,targetEpicId:a,effectiveDoneStoryIds:t.effectiveDoneStoryIds,preserveGitLifecycleAggregates:!0});if(i.mutated){r=i.state,l=i.changes;for(const p of i.reasonCodes)c.push(p);for(const p of i.changes)s.push(`reconciled aggregate for epic ${u(p.epicId)}`)}}const n=JSON.stringify(r)!==JSON.stringify(e);if(n){const i=t.nowIso??j(),p=Array.from(new Set(c));l.length>0&&je(r,l,i),r.last_updated=i,r.state_migration_repairs=[...Array.isArray(r.state_migration_repairs)?r.state_migration_repairs:[],{schemaVersion:1,action:"client_auto_repair",reasonCodes:p,repairedAt:i}],r.state_repair_debt=Ce(Array.isArray(r.state_repair_debt)?r.state_repair_debt:[],p,i)}return{mutated:n,state:r,reasonCodes:Array.from(new Set(c)),changes:s}}function G(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function L(e){const t=b(e);return t.length>0?C(t).slice(0,80):null}function Ae(e,t){return{schemaVersion:1,publicSafe:!0,epicId:u(e.epicId),reasonCodes:e.reasonCodes.map(C).filter(Boolean),previous:{total_stories:G(e.previous.total_stories),completed_stories:G(e.previous.completed_stories),status:L(e.previous.status),completed_at_present:typeof e.previous.completed_at=="string"&&e.previous.completed_at.length>0},next:{total_stories:e.next.total_stories,completed_stories:e.next.completed_stories,status:L(e.next.status),completed_at_present:typeof e.next.completed_at=="string"&&e.next.completed_at.length>0},repairedAt:t}}function xe(e,t,o){let r=e.filter(d).map(s=>({...s}));for(const s of t){const c=u(s.epicId),l=Array.from(new Set(s.reasonCodes.map(C).filter(Boolean))).sort(),a=`state-aggregate-reconciliation:${c}`,n={id:a,status:"open",reason:"epic_aggregate_reconciled",reason_codes:l,category:"state/epic-aggregate-reconciliation",epic_id:c,created_at:o,last_seen_at:o,occurrences:1},i=r.findIndex(g=>g.id===a);if(i<0){r=[...r,n];continue}const p=r[i];r[i]={...p,...n,created_at:typeof p.created_at=="string"?p.created_at:o,occurrences:Math.max(1,typeof p.occurrences=="number"?p.occurrences:1)+1}}return r}function je(e,t,o){e.state_aggregate_reconciliations=[...Array.isArray(e.state_aggregate_reconciliations)?e.state_aggregate_reconciliations.filter(d):[],...t.map(r=>Ae(r,o))],e.state_repair_debt=xe(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],t,o)}function Ce(e,t,o){const r=Array.from(new Set(t.map(C).filter(Boolean))).sort(),s=`state-drift-repair:${r.join("+")||"unknown"}`,c=e.filter(d).map(i=>({...i})),l={id:s,status:"open",reason:"state_json_drift_repaired",reason_codes:r,category:"state/drift-repair",created_at:o,last_seen_at:o,occurrences:1},a=c.findIndex(i=>i.id===s);if(a<0)return[...c,l];const n=c[a];return c[a]={...n,...l,created_at:typeof n.created_at=="string"?n.created_at:o,occurrences:Math.max(1,typeof n.occurrences=="number"?n.occurrences:1)+1},c}function C(e){return e.replace(/\b(sk|ghp|gho|github_pat|xoxb|AKIA)[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^,\s)]+/gi,"$1=[redacted]").replace(/https?:\/\/[^\s)]+/gi,"[url-redacted]").replace(/[^a-z0-9_+-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)}function u(e){return e.replace(/[^a-z0-9_.:-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)||"unknown"}function Te(e,t={}){const o=x(e,".neocortex"),r=x(o,"state.json");if(!F(r))return{repaired:!1,reasonCodes:[],changes:[]};let s;if(!I(t.args,t.canonicalCommandId))try{const _=Y(e);_&&(s=K(e,_))}catch(_){const y=_ instanceof Q?_.reasonCode:"state_migration_apply_failed";throw new S(`[Neocortex] state.json migration stopped before invoke: ${_ instanceof Error?_.message:String(_)}. No unverified state was used.`,y)}let c;try{c=JSON.parse(q(r,"utf8"))}catch(_){const y=_ instanceof Error?_.message:String(_);throw new S(`[Neocortex] state.json repair stopped: invalid JSON in .neocortex/state.json (${y}). No files were overwritten. Fix the JSON or restore a backup, then rerun.`,"invalid_json")}if(!d(c))throw new S("[Neocortex] state.json repair stopped: top-level state must be a JSON object. Restore a valid .neocortex/state.json before invoking Neocortex.","state_not_object");const l=P(c,t.args,t.canonicalCommandId),a=I(t.args,t.canonicalCommandId)?[]:Ie(e,c,l),n=ve(c,{...t,effectiveDoneStoryIds:a});if(!n.mutated)return s?{repaired:!0,reasonCodes:["state_migration_transaction_applied"],backupPath:s.backupHash?`.neocortex/state.json.migration-backup-${s.operationId}`:void 0,changes:[`shared state migration ${s.outcome}`]}:{repaired:!1,reasonCodes:[],changes:[]};J(o,{recursive:!0});const i=ne(),p=x(o,`state.json.backup-${i}`),g=x(o,`state.json.tmp.${V(6).toString("hex")}`);W(r,p),H(g,`${JSON.stringify(n.state,null,2)}
2
- `,"utf8"),B(g,r);const m=`.neocortex/state.json.backup-${i}`;return process.stderr.write(`[Neocortex P156.05] state.json auto-repaired before invoke; backup=${m}; reasonCodes=${n.reasonCodes.join(",")}; changes=${n.changes.join("; ")}
3
- `),{repaired:!0,reasonCodes:n.reasonCodes,backupPath:m,changes:n.changes}}function Ie(e,t,o){const r=X(e),s=d(t.epics)?t.epics:{},c=d(t.stories)?t.stories:{},l=[];for(const[a,n]of Object.entries(r.stories)){if(!d(n)||!T(n.status)||!n.checkpoint)continue;const i=d(c[a])?c[a]:null,p=typeof i?.epic_id=="string"?i.epic_id:a.split(".")[0];if(!p||o&&p!==o)continue;const g=d(s[p])?s[p]:null,m=d(r.epics[p])?r.epics[p]:null,_=m?.branch_mode??g?.branch_mode,y=m?.execution_branch??g?.execution_branch;if(_!=="epic"||typeof y!="string")continue;ee(e,n.checkpoint,a,p,y).verdict==="verified"&&l.push(a)}return l.sort()}export{f as EPIC_AGGREGATE_REASON_CODES,te as P189_STATE_SHAPE_GAP_CODE,S as StateRepairHardStopError,I as isInlineYoloMaterialization,T as isP189DoneLikeStoryStatus,Te as maybeRepairStateJsonBeforeInvoke,me as reconcileEpicAggregatesInState};
1
+ import{existsSync as te,lstatSync as oe,mkdirSync as re,readFileSync as R,realpathSync as C,renameSync as ne,writeFileSync as ie,copyFileSync as se}from"node:fs";import{execFileSync as ae}from"node:child_process";import{join as E,resolve as j}from"node:path";import{createHash as ce,randomBytes as pe}from"node:crypto";import{planStateMigration as le,StateMigrationHardStopError as de}from"../../../shared/dist/state/index.js";import{applyStateMigration as ue,previewStateMigration as G,StateMigrationApplyError as fe}from"../migrations/state-json.js";import{readGitLifecycleRuntimeSync as ge,verifyAcceptedGitLifecycleStoryCheckpointSync as _e}from"../git/git-lifecycle-store.js";class S extends Error{reasonCode;constructor(t,o){super(t),this.reasonCode=o,this.name="StateRepairHardStopError"}}const L="state-repair-skipped-story-worktree",me="P189-GAP-STATE-SHAPE",_={reconciled:"epic_aggregate_reconciled",totalRecounted:"epic_total_stories_recounted",completedRecounted:"epic_completed_stories_recounted",statusPromotedDone:"epic_status_promoted_done",completedAtSet:"epic_completed_at_set",stateNotObject:"epic_aggregate_state_not_object",epicsNotObject:"epic_aggregate_epics_not_object",storiesNotObject:"epic_aggregate_stories_not_object",scopeProjected:"epic_aggregate_scope_projected",epicNotObject:"epic_aggregate_epic_not_object",epicIdConflict:"epic_aggregate_epic_id_conflict",storyListNotArray:"epic_aggregate_story_list_not_array",storyRefInvalid:"epic_aggregate_story_ref_invalid",storyRefDuplicate:"epic_aggregate_story_ref_duplicate",storyMissing:"epic_aggregate_story_missing",storyNotObject:"epic_aggregate_story_not_object",storyIdConflict:"epic_aggregate_story_id_conflict",storyEpicConflict:"epic_aggregate_story_epic_conflict",terminalIncompleteConflict:"epic_aggregate_terminal_incomplete_conflict"},ye=new Set(["yolo","implement","diagnose","research","write-spec","create-tasks","refactor-suggest","property-tests","validate-tests","qa-gate","update-project-memory","commit-push","sync-main","create-pr","review-pr","merge-pr","review"]),he=new Set(["yoloop","auto-yolo","epic-runner","story-runner","loop-yolo","auto-epic"]);function d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function I(){return new Date().toISOString()}function Se(){return I().replace(/[:.]/g,"-")}function be(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function W(e){const[t]=e.trim().split(/\s+/,1);return t?t.replace(/^@?\*/,"").replace(/^@/,"").toLowerCase():null}function we(e){const[t]=e.trim().split(/\s+/,1);if(!t)return!1;const o=t.replace(/^@/,"");return/^[A-Z]?\d+(?:\.\d+)+$/i.test(o)||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(o)}function z(e){const t=e.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return t?.[1]?t[1]:e.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function N(e,t){if(typeof e!="string")return!1;const o=t??W(e);return(o==="yolo"||o==="yolo-inline")&&F(e).length>0&&z(e)===null}function F(e){const t=e.trim(),o=t.search(/\s/);return o===-1?"":t.slice(o).trim()}function ve(e){const t=F(e).split(/\s+/).find(o=>o.length>0&&!o.startsWith("-"));return t?t.replace(/^@/,"").replace(/^['"]|['"]$/g,""):null}function J(e,t){const r=e.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),s=[r,r.toUpperCase(),/^p\d+$/i.test(r)?`P${r.replace(/^p/i,"")}`:null,/^\d+$/.test(r)?`P${r}`:null].filter(a=>typeof a=="string"&&a.length>0);for(const a of s)if(d(t[a]))return a;return null}function Ee(e,t){const o=e.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return o?.[1]?J(o[1],t):null}function $(e,t,o){if(typeof t!="string"||t.trim().length===0||!d(e.epics)||!d(e.stories))return;const r=t.trim(),s=o??W(r);if(s!==null&&ye.has(s)||we(r)){const l=z(r),c=l?e.stories[l]:void 0;if(d(c)&&typeof c.epic_id=="string"&&d(e.epics[c.epic_id]))return c.epic_id;const i=l?.split(".")[0];if(i&&d(e.epics[i]))return i}if(s!==null&&he.has(s)){const l=Ee(r,e.epics);if(l)return l;const c=ve(r);if(c){const i=J(c,e.epics);if(i)return i}}}const T="pr_merged_issue_closed_reconciled",Ae="invalid_workflow_issue_removed";function b(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}const xe=new Set(["done","completed","merged"]),Ce=new Set(["done","completed","merged"]);function K(e){return xe.has(b(e))}function H(e){return Ce.has(b(e))}function h(e,t){throw new S(`${t} (${me} if this shape is intentionally new).`,e)}function P(e){return JSON.parse(JSON.stringify(e))}function Ie(e,t){const o=t.scope??e.scope;if(!d(o))return;const r=typeof o.kind=="string"?o.kind:null,s=typeof o.omittedStoryCount=="number"?o.omittedStoryCount:0,a=typeof o.omittedEpicCount=="number"?o.omittedEpicCount:0;(r==="projected"||s>0||a>0)&&h(_.scopeProjected,"[Neocortex] state.json aggregate reconciliation stopped: projected or partial state coverage cannot prove epic aggregates.")}function Ne(e,t){const o=[],r=new Set;for(const s of t)(typeof s!="string"||s.length===0)&&h(_.storyRefInvalid,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" has a non-string or empty story reference.`),r.has(s)&&h(_.storyRefDuplicate,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" lists story "${u(s)}" more than once.`),r.add(s),o.push(s);return o}function ke(e,t,o){const r=o[t];return r===void 0&&h(_.storyMissing,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(e)}" references missing story "${u(t)}".`),d(r)||h(_.storyNotObject,`[Neocortex] state.json aggregate reconciliation stopped: story "${u(t)}" is not an object.`),r.id!==t&&h(_.storyIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: story key "${u(t)}" conflicts with its id field.`),r.epic_id!==e&&h(_.storyEpicConflict,`[Neocortex] state.json aggregate reconciliation stopped: story "${u(t)}" does not belong to epic "${u(e)}".`),r}function v(e,t){e.includes(t)||e.push(t)}function Oe(e,t={}){d(e)||h(_.stateNotObject,"[Neocortex] state.json aggregate reconciliation stopped: top-level state must be an object."),d(e.epics)||h(_.epicsNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `epics` must be an object before counts are authoritative."),d(e.stories)||h(_.storiesNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `stories` must be an object before counts are authoritative."),Ie(e,t);const o=P(e),r=o.epics,s=o.stories,a=[],l=[],c=new Set(t.effectiveDoneStoryIds??[]);for(const[i,n]of Object.entries(r)){if(t.targetEpicId&&i!==t.targetEpicId)continue;d(n)||h(_.epicNotObject,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(i)}" is not an object.`),n.id!==i&&h(_.epicIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: epic key "${u(i)}" conflicts with its id field.`),Array.isArray(n.stories)||h(_.storyListNotArray,`[Neocortex] state.json aggregate reconciliation stopped: epic "${u(i)}" has non-array stories.`);const p=Ne(i,n.stories),f=p.length,m=p.filter(x=>{const ee=ke(i,x,s);return K(ee.status)||c.has(x)}).length,y=f>0&&m===f;if(H(n.status)&&!y&&f>0&&h(_.terminalIncompleteConflict,`[Neocortex] state.json aggregate reconciliation stopped: terminal epic "${u(i)}" has incomplete listed stories.`),t.preserveGitLifecycleAggregates&&(n.branch_mode==="epic"||typeof n.execution_branch=="string"))continue;const g=[],A={total_stories:n.total_stories,completed_stories:n.completed_stories,status:n.status,completed_at:n.completed_at};if(n.total_stories!==f&&(n.total_stories=f,v(g,_.totalRecounted)),n.completed_stories!==m&&(n.completed_stories=m,v(g,_.completedRecounted)),!H(n.status)&&y&&(n.status="done",v(g,_.statusPromotedDone),(n.completed_at===void 0||n.completed_at===null)&&(n.completed_at=t.nowIso??I(),v(g,_.completedAtSet))),g.length>0){v(g,_.reconciled);for(const x of g)v(a,x);l.push({epicId:i,reasonCodes:g,previous:A,next:{total_stories:f,completed_stories:m,status:n.status,completed_at:n.completed_at}})}}return{mutated:JSON.stringify(o)!==JSON.stringify(e),state:o,reasonCodes:a,changes:l}}function w(e,t){const o=e[t];return d(o)?o:null}function Re(e){const t=w(e,"issueCloseAudit")??w(e,"issue_close_audit");if(t){const s=b(t.event).replace(/-/g,"_"),a=t.publicSafe===!0||t.public_safe===!0,l=t.rawLogStorage==="forbidden"||t.raw_log_storage==="forbidden";if(s==="story_issue_closed"&&a&&l)return!0}const o=w(e,"completionEvidence")??w(e,"completion_evidence"),r=b(o?.issueState??o?.issue_state??o?.state);return e.issue_closed===!0||b(e.issue_state??e.issueState??e.workflow_issue_state)==="closed"||r==="closed"}function B(e){const t=w(e,"completionEvidence")??w(e,"completion_evidence"),o=w(e,"scopedCiEvidence")??w(e,"scoped_ci_evidence"),r=[e.physicalMergeStatus,e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState,o?.prState].map(b);return e.merged===!0||r.includes("merged")||b(o?.finalState)==="can-merge"&&e.merged===!0}function je(e){const t=w(e,"completionEvidence")??w(e,"completion_evidence"),o=[e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState].map(b),r=B(e),s=["denied-external-gate","denied-local-or-repo","not-attempted"].includes(b(e.physicalMergeStatus)),a=o.includes("closed")||o.includes("closed-unmerged");return r&&(e.merged===!1||s||a)||e.merged===!0&&s}function $e(e,t,o){const r=`state-completion-reconciliation:${u(t)}`,s=e.filter(d).map(i=>({...i})),a={id:r,status:"open",reason:"stale_state_completion_evidence_observed",reason_codes:[T],category:"state/completion-reconciliation",story_id:u(t),public_safe:!0,raw_log_storage:"forbidden",created_at:o,last_seen_at:o,occurrences:1},l=s.findIndex(i=>i.id===r);if(l<0)return[...s,a];const c=s[l];return s[l]={...c,...a,created_at:typeof c.created_at=="string"?c.created_at:o,occurrences:Math.max(1,typeof c.occurrences=="number"?c.occurrences:1)+1},s}function Te(e,t,o,r){const s=d(e.stories)?e.stories:null;if(!s)return;const a=[],l=I();for(const[c,i]of Object.entries(s)){if(!d(i))continue;const n=typeof i.epic_id=="string"?i.epic_id:c.split(".")[0];if(r&&n!==r)continue;const p=b(i.status);if(je(i))throw new S(`[Neocortex] state.json repair stopped: story "${c}" has conflicting PR merge completion evidence. Resolve .neocortex/state.json manually before invoking Neocortex.`,"conflicting_completion_evidence");if(p!=="pr-reviewed"||!B(i)||!Re(i))continue;const f=typeof i.status=="string"?i.status:p,m=be(i.steps_completed);i.status="done",i.last_step="step-c-12-merge-pr",i.steps_completed=Array.from(new Set([...m,"step-c-12-merge-pr"])),i.merged=!0,i.physicalMergeStatus="merged",i.completion_reconciled_at=l,t.push(`reconciled completion evidence for story ${c}`),o.push(T),a.push({schemaVersion:1,publicSafe:!0,rawLogStorage:"forbidden",storyId:u(c),previousStatus:f,nextStatus:"done",reasonCodes:[T],reconciledAt:l}),e.state_repair_debt=$e(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],c,l)}a.length>0&&(e.state_completion_reconciliations=[...Array.isArray(e.state_completion_reconciliations)?e.state_completion_reconciliations.filter(d):[],...a])}function Pe(e,t,o){const r=d(e.stories)?e.stories:null;if(r)for(const[s,a]of Object.entries(r))!d(a)||!Object.prototype.hasOwnProperty.call(a,"workflow_issue")||typeof a.workflow_issue=="number"&&Number.isFinite(a.workflow_issue)||(delete a.workflow_issue,t.push(`removed invalid workflow_issue from story ${u(s)}`),o.push(Ae))}function q(e,t={}){if(Array.isArray(e.stories))throw new S("[Neocortex] state.json repair stopped: `stories` is an Array. Convert it to an object keyed by story ID or run `*migrate-state --preview` for guidance.","stories_array_ambiguous");if(d(e.epics)){for(const[n,p]of Object.entries(e.epics))if(d(p)&&p.stories!==void 0&&!Array.isArray(p.stories))throw new S(`[Neocortex] state.json repair stopped: epic "${n}" has non-array \`stories\`. Repair this ambiguous shape manually before invoking Neocortex.`,"epic_stories_not_array")}if(e.schema_version!==void 0&&e.schema_version!==0&&e.schema_version!==1)throw new S(`[Neocortex] state.json repair stopped: schema_version=${String(e.schema_version)} is not a safe automatic downgrade target. Run \`*migrate-state --preview\` or repair the schema version manually.`,"unsupported_schema_version");if(N(t.args,t.canonicalCommandId)){for(const n of["epics","stories"]){const p=e[n];if(p!==void 0){if(!d(p))throw new S("[Neocortex] inline materialization stopped: invalid state collection.","inline_state_collection_invalid");for(const[f,m]of Object.entries(p)){if(!d(m))throw new S("[Neocortex] inline materialization stopped: invalid state record.","inline_state_record_invalid");if(m.id!==void 0&&m.id!==f)throw new S("[Neocortex] inline materialization stopped: conflicting state identity.","inline_state_identity_conflict")}}}return{mutated:!1,state:e,reasonCodes:[],changes:[]}}let o;try{o=le(e)}catch(n){throw n instanceof de?new S(`[Neocortex] state.json repair stopped by shared migration planner: ${n.message}`,n.reasonCode):n}let r=JSON.parse(JSON.stringify(o.kind==="migrate"?o.plan.targetState:e));const s=o.kind==="migrate"?o.plan.steps.map(n=>`shared migration ${n.kind}: ${n.target}`):[],a=o.kind==="migrate"?["state_migration_shared_plan"]:[];let l=[];const c=$(r,t.args,t.canonicalCommandId);if(Pe(r,s,a),Te(r,s,a,c),typeof t.args=="string"){const n=Oe(r,{nowIso:t.nowIso,targetEpicId:c,effectiveDoneStoryIds:t.effectiveDoneStoryIds,preserveGitLifecycleAggregates:!0});if(n.mutated){r=n.state,l=n.changes;for(const p of n.reasonCodes)a.push(p);for(const p of n.changes)s.push(`reconciled aggregate for epic ${u(p.epicId)}`)}}const i=JSON.stringify(r)!==JSON.stringify(e);if(i){const n=t.nowIso??I(),p=Array.from(new Set(a));l.length>0&&Ge(r,l,n),r.last_updated=n,r.state_migration_repairs=[...Array.isArray(r.state_migration_repairs)?r.state_migration_repairs:[],{schemaVersion:1,action:"client_auto_repair",reasonCodes:p,repairedAt:n}],r.state_repair_debt=Le(Array.isArray(r.state_repair_debt)?r.state_repair_debt:[],p,n)}return{mutated:i,state:r,reasonCodes:Array.from(new Set(a)),changes:s}}function Y(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Z(e){const t=b(e);return t.length>0?k(t).slice(0,80):null}function Me(e,t){return{schemaVersion:1,publicSafe:!0,epicId:u(e.epicId),reasonCodes:e.reasonCodes.map(k).filter(Boolean),previous:{total_stories:Y(e.previous.total_stories),completed_stories:Y(e.previous.completed_stories),status:Z(e.previous.status),completed_at_present:typeof e.previous.completed_at=="string"&&e.previous.completed_at.length>0},next:{total_stories:e.next.total_stories,completed_stories:e.next.completed_stories,status:Z(e.next.status),completed_at_present:typeof e.next.completed_at=="string"&&e.next.completed_at.length>0},repairedAt:t}}function De(e,t,o){let r=e.filter(d).map(s=>({...s}));for(const s of t){const a=u(s.epicId),l=Array.from(new Set(s.reasonCodes.map(k).filter(Boolean))).sort(),c=`state-aggregate-reconciliation:${a}`,i={id:c,status:"open",reason:"epic_aggregate_reconciled",reason_codes:l,category:"state/epic-aggregate-reconciliation",epic_id:a,created_at:o,last_seen_at:o,occurrences:1},n=r.findIndex(f=>f.id===c);if(n<0){r=[...r,i];continue}const p=r[n];r[n]={...p,...i,created_at:typeof p.created_at=="string"?p.created_at:o,occurrences:Math.max(1,typeof p.occurrences=="number"?p.occurrences:1)+1}}return r}function Ge(e,t,o){e.state_aggregate_reconciliations=[...Array.isArray(e.state_aggregate_reconciliations)?e.state_aggregate_reconciliations.filter(d):[],...t.map(r=>Me(r,o))],e.state_repair_debt=De(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],t,o)}function Le(e,t,o){const r=Array.from(new Set(t.map(k).filter(Boolean))).sort(),s=`state-drift-repair:${r.join("+")||"unknown"}`,a=e.filter(d).map(n=>({...n})),l={id:s,status:"open",reason:"state_json_drift_repaired",reason_codes:r,category:"state/drift-repair",created_at:o,last_seen_at:o,occurrences:1},c=a.findIndex(n=>n.id===s);if(c<0)return[...a,l];const i=a[c];return a[c]={...i,...l,created_at:typeof i.created_at=="string"?i.created_at:o,occurrences:Math.max(1,typeof i.occurrences=="number"?i.occurrences:1)+1},a}function k(e){return e.replace(/\b(sk|ghp|gho|github_pat|xoxb|AKIA)[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^,\s)]+/gi,"$1=[redacted]").replace(/https?:\/\/[^\s)]+/gi,"[url-redacted]").replace(/[^a-z0-9_+-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)}function u(e){return e.replace(/[^a-z0-9_.:-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)||"unknown"}const We=2e3,ze="NEOCORTEX_STORY_WORKTREE_ID",Fe=/^[A-Za-z0-9][A-Za-z0-9_-]{3,63}$/,Je=/(?:^|\/)(?:\.claude\/worktrees|\.neocortex\/worktrees|nx\/wt)\/[^/]+\/?$/;function Ke(e){let t;try{t=C(e)}catch{t=j(e)}return Je.test(t.replace(/\\/g,"/"))}function He(e){const t=e[ze];return typeof t=="string"&&Fe.test(t)}function U(e,t){return He(t)||Ke(e)?"story-worktree":"main"}function Be(e,t){const o=E(e,".git");try{const r=oe(o);if(r.isDirectory())return"main";if(!r.isFile()||r.size>4096)return null;const s=/^gitdir:\s*(.+?)\s*$/m.exec(R(o,"utf8"));if(!s)return null;const a=j(e,s[1]).replace(/\\/g,"/");return/\/worktrees\/[^/]+\/?$/.test(a)?U(e,t):null}catch{return null}}function qe(e,t=process.env){const o=Be(e,t);if(o)return o;try{const r=ae("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:We}).split(/\r?\n/).map(s=>s.trim()).filter(Boolean);return r.length!==3||C(r[0])===C(r[1])?"main":U(r[2],t)}catch{return"main"}}const O=new Map;function M(e){try{return C(e)}catch{return j(e)}}function ot(e,t){const o=O.get(M(e));if(!(!o||!t||o.sourceSha256!==t))return structuredClone(o.state)}function rt(){O.clear()}function V(e,t){let o;try{o=JSON.parse(t??R(e,"utf8"))}catch(r){const s=r instanceof Error?r.message:String(r);throw new S(`[Neocortex] state.json repair stopped: invalid JSON in .neocortex/state.json (${s}). No files were overwritten. Fix the JSON or restore a backup, then rerun.`,"invalid_json")}if(!d(o))throw new S("[Neocortex] state.json repair stopped: top-level state must be a JSON object. Restore a valid .neocortex/state.json before invoking Neocortex.","state_not_object");return o}function X(e){const t=e instanceof fe?e.reasonCode:"state_migration_apply_failed";return new S(`[Neocortex] state.json migration stopped before invoke: ${e instanceof Error?e.message:String(e)}. No unverified state was used.`,t)}function Ye(e,t,o){const r=M(e),s=R(t),a=ce("sha256").update(s).digest("hex"),l=V(t,s.toString("utf8")),c=N(o.args,o.canonicalCommandId);let i=null;if(!c)try{i=G(e)}catch(D){throw X(D)}const n=!!i,p=i?P(i.targetState):l,f=$(p,o.args,o.canonicalCommandId),m=c?[]:Q(e,p,f),y=q(p,{...o,effectiveDoneStoryIds:m});if(!y.mutated&&!n)return{repaired:!1,reasonCodes:[],changes:[]};O.set(r,{sourceSha256:a,state:P(y.mutated?y.state:p)});const g=y.mutated?y.changes.length:0,A=y.mutated?y.reasonCodes:[];return process.stderr.write(`[Neocortex P227.02] ${L}; divergences=${g}; migrationPending=${n}; snapshot=in-memory-overlay; reasonCodes=${A.join(",")}
2
+ `),{repaired:!1,skipped:"story-worktree",reasonCodes:[L],changes:[],divergenceCount:g,migrationPending:n}}function nt(e,t={}){const o=E(e,".neocortex"),r=E(o,"state.json");if(O.delete(M(e)),!te(r))return{repaired:!1,reasonCodes:[],changes:[]};if((t.checkoutKind??qe(e))==="story-worktree")return Ye(e,r,t);let a;if(!N(t.args,t.canonicalCommandId))try{const g=G(e);g&&(a=ue(e,g))}catch(g){throw X(g)}const l=V(r),c=$(l,t.args,t.canonicalCommandId),i=N(t.args,t.canonicalCommandId)?[]:Q(e,l,c),n=q(l,{...t,effectiveDoneStoryIds:i});if(!n.mutated)return a?{repaired:!0,reasonCodes:["state_migration_transaction_applied"],backupPath:a.backupHash?`.neocortex/state.json.migration-backup-${a.operationId}`:void 0,changes:[`shared state migration ${a.outcome}`]}:{repaired:!1,reasonCodes:[],changes:[]};re(o,{recursive:!0});const p=Se(),f=E(o,`state.json.backup-${p}`),m=E(o,`state.json.tmp.${pe(6).toString("hex")}`);se(r,f),ie(m,`${JSON.stringify(n.state,null,2)}
3
+ `,"utf8"),ne(m,r);const y=`.neocortex/state.json.backup-${p}`;return process.stderr.write(`[Neocortex P156.05] state.json auto-repaired before invoke; backup=${y}; reasonCodes=${n.reasonCodes.join(",")}; changes=${n.changes.join("; ")}
4
+ `),{repaired:!0,reasonCodes:n.reasonCodes,backupPath:y,changes:n.changes}}function Q(e,t,o){const r=ge(e),s=d(t.epics)?t.epics:{},a=d(t.stories)?t.stories:{},l=[];for(const[c,i]of Object.entries(r.stories)){if(!d(i)||!K(i.status)||!i.checkpoint)continue;const n=d(a[c])?a[c]:null,p=typeof n?.epic_id=="string"?n.epic_id:c.split(".")[0];if(!p||o&&p!==o)continue;const f=d(s[p])?s[p]:null,m=d(r.epics[p])?r.epics[p]:null,y=m?.branch_mode??f?.branch_mode,g=m?.execution_branch??f?.execution_branch;if(y!=="epic"||typeof g!="string")continue;_e(e,i.checkpoint,c,p,g).verdict==="verified"&&l.push(c)}return l.sort()}export{_ as EPIC_AGGREGATE_REASON_CODES,me as P189_STATE_SHAPE_GAP_CODE,L as STATE_REPAIR_SKIPPED_STORY_WORKTREE,S as StateRepairHardStopError,rt as __resetStoryWorktreeRepairOverlaysForTests,qe as detectStateRepairCheckoutKind,N as isInlineYoloMaterialization,K as isP189DoneLikeStoryStatus,nt as maybeRepairStateJsonBeforeInvoke,ot as readStoryWorktreeRepairOverlay,Oe as reconcileEpicAggregatesInState};
@@ -1 +1 @@
1
- import{execFileSync as w,spawnSync as m}from"node:child_process";import{realpathSync as I}from"node:fs";import{createYoloChangeEvidence as A}from"../../../shared/dist/yolo/change-evidence.js";import{readGitLifecycleRuntimeSync as R}from"../git/git-lifecycle-store.js";class E extends Error{diagnostic;constructor(t){super("yolo-change-evidence-unavailable"),this.name="YoloChangeEvidenceUnavailableError",this.diagnostic=Object.freeze({...t})}}function P(e){return e instanceof E?e.diagnostic:void 0}const u=Object.freeze({repair:"not-attempted",recollectionCount:0});function _(e){return e==="lease-owner-mismatch"||e==="lease-invalid-or-nonsetup"||e==="direct-yolo-writer-active"?"resolve-lease-conflict":e==="base-ref-missing"||e==="base-observation-unavailable"||e==="base-observation-timeout"||e==="base-object-missing"||e==="base-not-ancestor"||e==="diff-read-unavailable"?"restore-verified-base-evidence":e==="execution-branch-mismatch"||e.startsWith("direct-yolo-")?"inspect-repository-binding":"none"}function i(e,t,n=u,r=n.repair){throw new E({reason:e,baseSource:t,repair:r,recollectionCount:n.recollectionCount,fallbackAction:_(e),publicSafe:!0})}async function $(e){let t;try{t=R(e.projectRoot,{required:!0})}catch(d){if(d instanceof Error&&d.message==="git-lifecycle-runtime-missing")return u;i("runtime-state-unavailable","none")}const n=await T(e.projectRoot,t,e.storyId,e.epicId);if(n)return Object.freeze({...u,storyWorktree:n});const r=t.epics[e.epicId]?.branch_lease;if(r==null)return u;(typeof r!="object"||Array.isArray(r))&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),r.ownerStoryId!==e.storyId&&i("lease-owner-mismatch","active-story-lease",u,"not-eligible"),typeof r.expiresAt!="string"&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const a=Date.parse(r.expiresAt);if(Number.isFinite(a)||i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),a>Date.now())return u;(typeof r.sessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.sessionId)||r.idempotencyKey!==r.sessionId)&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const{prepareDirectYoloSetup:o}=await import("../git/direct-yolo-checkpoint.js"),s=await o({...e,expiredSetupRecovery:{schemaVersion:1,expectedRuntimeRevision:t.revision,expectedLease:Object.freeze({...r})}});return s.ok||i(s.reasonCode,"active-story-lease",u,"not-eligible"),(s.value.storyId!==e.storyId||s.value.epicId!==e.epicId||Date.parse(s.value.leaseExpiresAt)<=Date.now())&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),Object.freeze({repair:"applied",recollectionCount:1})}function h(e,t,n,r,a){try{return w("git",["-C",e,...t],{encoding:"utf8",timeout:3e3,maxBuffer:1024*1024,stdio:["ignore","pipe","ignore"]})}catch{i(n,r,a)}}const C=15e3,O=2;function k(e,t,n,r){let a=!1;for(let o=0;o<O;o+=1)try{return w("git",["-C",e,...t],{encoding:"utf8",timeout:C,maxBuffer:1024*1024,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(s){const d=s.code,b=s.signal;a=d==="ETIMEDOUT"||b==="SIGTERM"}i(a?"base-observation-timeout":"base-observation-unavailable",n,r)}function x(e,t,n){const r=m("git",["-C",e,"show-ref","--verify","--quiet",t],{timeout:3e3,stdio:"ignore"});if(r.status===0)return!0;if(r.status===1)return!1;i("base-observation-unavailable","none",n)}function D(e,t,n,r){const a=m("git",["-C",e,"cat-file","-e",`${t}^{commit}`],{timeout:3e3,stdio:"ignore"});if(a.status===0)return!0;if(a.status===1||a.status===128)return!1;i("base-observation-unavailable",n,r)}function L(e){const t=e.reconciliation??u;(!/^[A-Za-z0-9][A-Za-z0-9_./-]{0,119}$/.test(e.defaultBranch)||e.defaultBranch.includes(".."))&&i("invalid-default-branch","none",t);let n;try{n=h(e.projectRoot,["rev-parse","--show-toplevel"],"repository-root-mismatch","none",t).trim(),I(n)!==I(e.projectRoot)&&i("repository-root-mismatch","none",t)}catch(f){if(f instanceof E)throw f;i("repository-root-mismatch","none",t)}const r=h(e.projectRoot,["rev-parse","HEAD"],"base-observation-unavailable","none",t).trim();if(r!==e.expectedHeadSha)throw new Error("yolo-change-evidence-stale");let a,o="none",s=!1,d,b=null;if(e.storyId&&e.epicId&&t.storyWorktree){let f;try{f=R(e.projectRoot,{required:!0})}catch{i("runtime-state-unavailable","none",t)}const c=t.storyWorktree,l=f.storyWorktrees?.entries[c.leaseId];(!l||l.storyId!==e.storyId||l.epicId!==e.epicId||l.state!=="active"||l.worktreePath!==S(e.projectRoot)||(l.syncedSha??l.baseSha)!==c.baseSha)&&i("lease-invalid-or-nonsetup","active-story-lease",t,"not-eligible"),m("git",["-C",e.projectRoot,"merge-base","--is-ancestor",c.baseSha,"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor","active-story-lease",t,"not-eligible"),d=c.baseSha}else if(e.storyId&&e.epicId){let f;try{f=R(e.projectRoot)}catch{i("runtime-state-unavailable","none",t)}const c=f.epics[e.epicId],l=B(e.projectRoot,f,e.storyId)?void 0:c?.branch_lease,v=h(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"],"execution-branch-mismatch","none",t).trim();if(c?.branch_mode==="epic"&&c.execution_branch===v&&(b=v),l&&typeof l=="object"&&!Array.isArray(l)){const g=l;g.ownerStoryId!==e.storyId&&i("lease-owner-mismatch","active-story-lease",t,"not-eligible"),(typeof g.expiresAt!="string"||!Number.isFinite(Date.parse(g.expiresAt))||Date.parse(g.expiresAt)<=Date.now())&&i("lease-invalid-or-nonsetup","active-story-lease",t,"not-eligible"),b===null&&i("execution-branch-mismatch","active-story-lease",t,"not-eligible"),s=!0}}if(d)a=d,o="active-story-lease";else if(s)a=r,o="active-story-lease";else{const f=b===null?"":k(e.projectRoot,["ls-remote","--heads","origin",`refs/heads/${b}`],"published-execution-branch",t).trim();if(f){o="published-execution-branch";const c=/^([a-f0-9]{40})\trefs\/heads\/([^\n]+)$/.exec(f);(!c||c[2]!==b)&&i("base-observation-unavailable",o,t),D(e.projectRoot,c[1],o,t)||i("base-object-missing",o,t),m("git",["-C",e.projectRoot,"merge-base","--is-ancestor",c[1],"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor",o,t),a=c[1]}else{const c=`refs/heads/${e.defaultBranch}`,l=`refs/remotes/origin/${e.defaultBranch}`,v=x(e.projectRoot,c,t)?c:x(e.projectRoot,l,t)?l:null;v||i("base-ref-missing","none",t),o=v===c?"local-default-branch":"remote-default-branch",a=h(e.projectRoot,["merge-base","HEAD",v],"base-not-ancestor",o,t).trim()}}const y=h(e.projectRoot,["diff","--name-only","-z",a,"--"],"diff-read-unavailable",o,t).split("\0").filter(Boolean),j=h(e.projectRoot,["ls-files","--others","--exclude-standard","-z"],"diff-read-unavailable",o,t).split("\0").filter(Boolean),p=A({baseSha:a,headSha:r,changedPaths:[...y,...j]});if(h(e.projectRoot,["rev-parse","HEAD"],"base-observation-unavailable",o,t).trim()!==r)throw new Error("yolo-change-evidence-stale");return p}function S(e){const t=m("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:3e3});if(t.status===0)try{return I(t.stdout.trim())}catch{return}}async function T(e,t,n,r){const a=S(e);if(!a)return;const o=Object.values(t.storyWorktrees?.entries??{}).filter(p=>p.storyId===n&&p.worktreePath===a);if(o.length===0)return;const s=o[0];(o.length>1||s.state!=="active"||s.epicId!==r)&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const{StoryWorktreeManager:d}=await import("../git/story-worktree-manager.js"),b=await new d({projectRoot:e}).probe(s.leaseId);(!b.ok||b.value.ownership!=="proven")&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const y=s.syncedSha??s.baseSha;return m("git",["-C",e,"merge-base","--is-ancestor",y,"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor","active-story-lease",u,"not-eligible"),Object.freeze({leaseId:s.leaseId,baseSha:y})}function B(e,t,n){const r=m("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:3e3});if(r.status!==0)return!1;let a;try{a=I(r.stdout.trim())}catch{return!1}return Object.values(t.storyWorktrees?.entries??{}).some(o=>o.storyId===n&&o.state==="active"&&o.worktreePath===a)}export{E as YoloChangeEvidenceUnavailableError,L as collectYoloChangeEvidence,$ as reconcileYoloChangeEvidenceLease,P as yoloChangeEvidenceDiagnostic};
1
+ import{execFileSync as x,spawnSync as m}from"node:child_process";import{createHash as _}from"node:crypto";import{readFileSync as k,realpathSync as R}from"node:fs";import{join as O}from"node:path";import{createYoloChangeEvidence as C}from"../../../shared/dist/yolo/change-evidence.js";import{readGitLifecycleRuntimeSync as E}from"../git/git-lifecycle-store.js";class S extends Error{diagnostic;constructor(t){super("yolo-change-evidence-unavailable"),this.name="YoloChangeEvidenceUnavailableError",this.diagnostic=Object.freeze({...t})}}function G(e){return e instanceof S?e.diagnostic:void 0}const u=Object.freeze({repair:"not-attempted",recollectionCount:0});function D(e){return e==="lease-owner-mismatch"||e==="lease-invalid-or-nonsetup"||e==="direct-yolo-writer-active"?"resolve-lease-conflict":e==="base-ref-missing"||e==="base-observation-unavailable"||e==="base-observation-timeout"||e==="base-object-missing"||e==="base-not-ancestor"||e==="diff-read-unavailable"?"restore-verified-base-evidence":e==="execution-branch-mismatch"||e.startsWith("direct-yolo-")?"inspect-repository-binding":"none"}function i(e,t,n=u,r=n.repair){throw new S({reason:e,baseSource:t,repair:r,recollectionCount:n.recollectionCount,fallbackAction:D(e),publicSafe:!0})}async function K(e){let t;try{t=E(e.projectRoot,{required:!0})}catch(l){if(l instanceof Error&&l.message==="git-lifecycle-runtime-missing")return u;i("runtime-state-unavailable","none")}const n=await z(e.projectRoot,t,e.storyId,e.epicId);if(n)return Object.freeze({...u,storyWorktree:n});const r=t.epics[e.epicId]?.branch_lease;if(r==null)return u;(typeof r!="object"||Array.isArray(r))&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),r.ownerStoryId!==e.storyId&&i("lease-owner-mismatch","active-story-lease",u,"not-eligible"),typeof r.expiresAt!="string"&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const o=Date.parse(r.expiresAt);if(Number.isFinite(o)||i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),o>Date.now())return u;(typeof r.sessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.sessionId)||r.idempotencyKey!==r.sessionId)&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const{prepareDirectYoloSetup:a}=await import("../git/direct-yolo-checkpoint.js"),s=await a({...e,expiredSetupRecovery:{schemaVersion:1,expectedRuntimeRevision:t.revision,expectedLease:Object.freeze({...r})}});return s.ok||i(s.reasonCode,"active-story-lease",u,"not-eligible"),(s.value.storyId!==e.storyId||s.value.epicId!==e.epicId||Date.parse(s.value.leaseExpiresAt)<=Date.now())&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible"),Object.freeze({repair:"applied",recollectionCount:1})}function h(e,t,n,r,o){try{return x("git",["-C",e,...t],{encoding:"utf8",timeout:3e3,maxBuffer:1024*1024,stdio:["ignore","pipe","ignore"]})}catch{i(n,r,o)}}const T=15e3,W=2;function B(e,t,n,r){let o=!1;for(let a=0;a<W;a+=1)try{return x("git",["-C",e,...t],{encoding:"utf8",timeout:T,maxBuffer:1024*1024,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(s){const l=s.code,d=s.signal;o=l==="ETIMEDOUT"||d==="SIGTERM"}i(o?"base-observation-timeout":"base-observation-unavailable",n,r)}function A(e,t,n){const r=m("git",["-C",e,"show-ref","--verify","--quiet",t],{timeout:3e3,stdio:"ignore"});if(r.status===0)return!0;if(r.status===1)return!1;i("base-observation-unavailable","none",n)}function M(e,t,n,r){const o=m("git",["-C",e,"cat-file","-e",`${t}^{commit}`],{timeout:3e3,stdio:"ignore"});if(o.status===0)return!0;if(o.status===1||o.status===128)return!1;i("base-observation-unavailable",n,r)}function Z(e){const t=e.reconciliation??u;(!/^[A-Za-z0-9][A-Za-z0-9_./-]{0,119}$/.test(e.defaultBranch)||e.defaultBranch.includes(".."))&&i("invalid-default-branch","none",t);let n;try{n=h(e.projectRoot,["rev-parse","--show-toplevel"],"repository-root-mismatch","none",t).trim(),R(n)!==R(e.projectRoot)&&i("repository-root-mismatch","none",t)}catch(b){if(b instanceof S)throw b;i("repository-root-mismatch","none",t)}const r=h(e.projectRoot,["rev-parse","HEAD"],"base-observation-unavailable","none",t).trim();if(r!==e.expectedHeadSha)throw new Error("yolo-change-evidence-stale");let o,a="none",s=!1,l,d=null;if(e.storyId&&e.epicId&&t.storyWorktree){let b;try{b=E(e.projectRoot,{required:!0})}catch{i("runtime-state-unavailable","none",t)}const c=t.storyWorktree,f=b.storyWorktrees?.entries[c.leaseId];(!f||f.storyId!==e.storyId||f.epicId!==e.epicId||f.state!=="active"||f.worktreePath!==w(e.projectRoot)||(f.syncedSha??f.baseSha)!==c.baseSha)&&i("lease-invalid-or-nonsetup","active-story-lease",t,"not-eligible"),m("git",["-C",e.projectRoot,"merge-base","--is-ancestor",c.baseSha,"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor","active-story-lease",t,"not-eligible"),l=c.baseSha}else if(e.storyId&&e.epicId){let b;try{b=E(e.projectRoot)}catch{i("runtime-state-unavailable","none",t)}const c=b.epics[e.epicId],f=Y(e.projectRoot,b,e.storyId),v=f?void 0:c?.branch_lease;f&&(l=H(e.projectRoot,b,e.storyId,e.epicId,t));const j=h(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"],"execution-branch-mismatch","none",t).trim();if(c?.branch_mode==="epic"&&c.execution_branch===j&&(d=j),v&&typeof v=="object"&&!Array.isArray(v)){const I=v;I.ownerStoryId!==e.storyId&&i("lease-owner-mismatch","active-story-lease",t,"not-eligible"),(typeof I.expiresAt!="string"||!Number.isFinite(Date.parse(I.expiresAt))||Date.parse(I.expiresAt)<=Date.now())&&i("lease-invalid-or-nonsetup","active-story-lease",t,"not-eligible"),d===null&&i("execution-branch-mismatch","active-story-lease",t,"not-eligible"),s=!0}}if(l)o=l,a="active-story-lease";else if(s)o=r,a="active-story-lease";else{const b=d===null?"":B(e.projectRoot,["ls-remote","--heads","origin",`refs/heads/${d}`],"published-execution-branch",t).trim();if(b){a="published-execution-branch";const c=/^([a-f0-9]{40})\trefs\/heads\/([^\n]+)$/.exec(b);(!c||c[2]!==d)&&i("base-observation-unavailable",a,t),M(e.projectRoot,c[1],a,t)||i("base-object-missing",a,t),m("git",["-C",e.projectRoot,"merge-base","--is-ancestor",c[1],"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor",a,t),o=c[1]}else{const c=`refs/heads/${e.defaultBranch}`,f=`refs/remotes/origin/${e.defaultBranch}`,v=A(e.projectRoot,c,t)?c:A(e.projectRoot,f,t)?f:null;v||i("base-ref-missing","none",t),a=v===c?"local-default-branch":"remote-default-branch",o=h(e.projectRoot,["merge-base","HEAD",v],"base-not-ancestor",a,t).trim()}}const g=h(e.projectRoot,["diff","--name-only","-z",o,"--"],"diff-read-unavailable",a,t).split("\0").filter(Boolean),y=h(e.projectRoot,["ls-files","--others","--exclude-standard","-z"],"diff-read-unavailable",a,t).split("\0").filter(Boolean),p=C({baseSha:o,headSha:r,changedPaths:[...g,...y]});if(h(e.projectRoot,["rev-parse","HEAD"],"base-observation-unavailable",a,t).trim()!==r)throw new Error("yolo-change-evidence-stale");return p}function w(e){const t=m("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:3e3});if(t.status===0)try{return R(t.stdout.trim())}catch{return}}async function z(e,t,n,r){const o=w(e);if(!o)return;const a=Object.values(t.storyWorktrees?.entries??{}).filter(p=>p.storyId===n&&p.worktreePath===o);if(a.length===0)return;const s=a[0];(a.length>1||s.state!=="active"||s.epicId!==r)&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const{StoryWorktreeManager:l}=await import("../git/story-worktree-manager.js"),d=await new l({projectRoot:e}).probe(s.leaseId);(!d.ok||d.value.ownership!=="proven")&&i("lease-invalid-or-nonsetup","active-story-lease",u,"not-eligible");const g=s.syncedSha??s.baseSha;return m("git",["-C",e,"merge-base","--is-ancestor",g,"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor","active-story-lease",u,"not-eligible"),Object.freeze({leaseId:s.leaseId,baseSha:g})}function H(e,t,n,r,o){const a=w(e),s=Object.values(t.storyWorktrees?.entries??{}).filter(y=>y.storyId===n&&y.state==="active"&&y.worktreePath===a),l=s[0];(!l||s.length>1||l.epicId!==r||!N(e,l))&&i("lease-invalid-or-nonsetup","active-story-lease",o,"not-eligible");const d=l.syncedSha??l.baseSha;return m("git",["-C",e,"merge-base","--is-ancestor",d,"HEAD"],{timeout:3e3,stdio:"ignore"}).status!==0&&i("base-not-ancestor","active-story-lease",o,"not-eligible"),d}const P="nx-owner";function N(e,t){const n=m("git",["-C",e,"rev-parse","--absolute-git-dir"],{encoding:"utf8",timeout:3e3});if(n.status!==0)return!1;try{const r=JSON.parse(k(O(n.stdout.trim(),P),"utf8"));return r.schemaVersion===1&&r.leaseId===t.leaseId&&typeof r.nonce=="string"&&_("sha256").update(r.nonce).digest("hex")===t.nonceDigest}catch{return!1}}function Y(e,t,n){const r=m("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:3e3});if(r.status!==0)return!1;let o;try{o=R(r.stdout.trim())}catch{return!1}return Object.values(t.storyWorktrees?.entries??{}).some(a=>a.storyId===n&&a.state==="active"&&a.worktreePath===o)}export{S as YoloChangeEvidenceUnavailableError,Z as collectYoloChangeEvidence,K as reconcileYoloChangeEvidenceLease,G as yoloChangeEvidenceDiagnostic};
@@ -56,6 +56,8 @@ export interface DiscoveryHookResult {
56
56
  /** Reason hook was a no-op (only present if !applied). */
57
57
  readonly reason?: string;
58
58
  }
59
+ /** P227.17 DEC-05: discovery backup of `.neocortex/state.json` (git-ignored). */
60
+ export declare const DISCOVERY_STATE_BACKUP_SUFFIX = "backup-discovery";
59
61
  /**
60
62
  * Run discovery + merge if hook conditions are met.
61
63
  *
@@ -1,2 +1,2 @@
1
- import{existsSync as f,readFileSync as h,renameSync as m,statSync as y,writeFileSync as j}from"node:fs";import{basename as p,dirname as b,resolve as l,isAbsolute as O}from"node:path";import{discoverEpicsFromDir as w,mergeDiscoveredIntoState as g,buildDefaultDiscoveryFs as k}from"./shared-discover-epics.js";import{extractYoloopTargetPath as z,isYoloopInvocation as S}from"./target-normalization.js";function v(e,o){return O(e)?e:l(o,e)}function $(e,o,t){if(o.epics.length===0)return;const s=l(e,".neocortex","state.json");if(f(s))try{const i=h(s,"utf8"),r=JSON.parse(i),n=g(r,o);if(n.added.length===0&&n.storiesAdded===0)return;r.last_updated=new Date().toISOString();const a=`${s}.tmp.${process.pid}.${Date.now()}`;j(a,`${JSON.stringify(r,null,2)}
2
- `,"utf8"),m(a,s)}catch(i){const r=i instanceof Error?i.message:String(i);t?.warn?.(`[neocortex] discovery hook: failed to persist .neocortex/state.json: ${r}. Proceeding with request snapshot only.`)}}function A(e,o){const t=p(o),s=e.epics.filter(r=>r.path===o||r.filename===t),i=new Set(s.map(r=>r.id));return{epics:Object.freeze(s),warnings:Object.freeze([...e.warnings,...s.length===0?[`single-file discovery found no matching epic descriptor for ${t}`]:[]]),skipped:Object.freeze([...e.skipped,...e.epics.filter(r=>!i.has(r.id)).map(r=>`${r.filename}: skipped (not requested file)`)])}}async function D(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};if(!S(e.args))return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"not a yoloop trigger"};const o=z(e.args,e.projectRoot);if(!o)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"no path arg"};let t;try{t=v(o,e.projectRoot)}catch(r){const n=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] discovery hook: path resolution failed: ${n}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path resolution failed"}}let s=!1,i=!1;try{if(f(t)){const r=y(t);s=r.isDirectory(),i=r.isFile()}}catch{s=!1,i=!1}if(!s&&!i)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path not found"};try{const r=await k(),n=s?t:b(t),a=w(n,r),c=i?A(a,t):a,d=g(e.stateSnapshot,c);$(e.projectRoot,c,e.logger),(d.added.length>0||d.storiesAdded>0)&&e.logger?.info?.(`[neocortex] discovered ${d.added.length} epic(s), ${d.storiesAdded} story-ies from ${s?t:p(t)}`);for(const u of c.warnings)e.logger?.warn?.(`[neocortex] discovery: ${u}`);return{applied:!0,added:d.added,skipped:d.skipped,storiesAdded:d.storiesAdded}}catch(r){const n=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] discovery hook failed: ${n}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`error: ${n}`}}}async function I(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await D(e)}catch(o){const t=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook (outer) failed: ${t}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`outer error: ${t}`}}}export{I as maybeRunDiscoveryHook,D as runDiscoveryHook};
1
+ import{closeSync as k,existsSync as u,fchmodSync as O,fsyncSync as $,openSync as z,readFileSync as y,renameSync as h,statSync as m,unlinkSync as A,writeSync as v}from"node:fs";import{basename as S,dirname as D,resolve as p,isAbsolute as g,relative as F,sep as E}from"node:path";import{discoverEpicsFromDir as P,mergeDiscoveredIntoState as j,buildDefaultDiscoveryFs as R}from"./shared-discover-epics.js";import{createLegacyStoryScopeExtractor as I}from"./legacy-story-scope.js";import{extractYoloopTargetPath as T,isYoloopInvocation as x}from"./target-normalization.js";function B(e,s){return g(e)?e:p(s,e)}function _(e,s,t){if(s.epics.length===0)return;const r=p(e,".neocortex","state.json");if(u(r))try{const n=y(r,"utf8"),o=JSON.parse(n),i=j(o,s);if(i.added.length===0&&i.storiesAdded===0&&i.storiesFilled===0)return;o.last_updated=new Date().toISOString();const f=`tmp.${process.pid}.${Date.now()}`,c=`${r}.${f}`,a=`${r}.${Y}`,d=`${a}.${f}`;b(c,Buffer.from(`${JSON.stringify(o,null,2)}
2
+ `,"utf8"),J(r));try{if(b(d,Buffer.from(n,"utf8"),384),y(r,"utf8")!==n){l(c),l(d),t?.warn?.("[neocortex] discovery hook: legacy-scope-state-cas-mismatch; state.json left unchanged.");return}h(d,a),h(c,r)}catch(w){throw l(c),l(d),w}}catch(n){t?.warn?.(`[neocortex] discovery hook: failed to persist .neocortex/state.json (${C(n)}). Proceeding with request snapshot only.`)}}function C(e){const s=e?.code;return typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,31}$/.test(s)?s:e instanceof SyntaxError?"state-json-invalid":"discovery-state-persist-failed"}function l(e){try{A(e)}catch{}}function J(e){try{return m(e).mode&511}catch{return 420}}function b(e,s,t){const r=z(e,"w",t);try{O(r,t),v(r,s),$(r)}finally{k(r)}}const Y="backup-discovery";function q(e){const s=p(e);return t=>{if(typeof t!="string"||t.length===0||g(t))return!1;const r=p(s,t.endsWith("/")?t.slice(0,-1):t),n=F(s,r);return n.length===0||n===".."||n.startsWith(`..${E}`)||g(n)?!1:u(r)}}function H(e,s){const t=S(s),r=e.epics.filter(o=>o.path===s||o.filename===t),n=new Set(r.map(o=>o.id));return{epics:Object.freeze(r),warnings:Object.freeze([...e.warnings,...r.length===0?[`single-file discovery found no matching epic descriptor for ${t}`]:[]]),skipped:Object.freeze([...e.skipped,...e.epics.filter(o=>!n.has(o.id)).map(o=>`${o.filename}: skipped (not requested file)`)])}}async function N(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};if(!x(e.args))return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"not a yoloop trigger"};const s=T(e.args,e.projectRoot);if(!s)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"no path arg"};let t;try{t=B(s,e.projectRoot)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook: path resolution failed: ${i}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path resolution failed"}}let r=!1,n=!1;try{if(u(t)){const o=m(t);r=o.isDirectory(),n=o.isFile()}}catch{r=!1,n=!1}if(!r&&!n)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path not found"};try{const o=await R(),i=r?t:D(t),f=P(i,o,{legacyStoryScope:I(q(e.projectRoot))}),c=n?H(f,t):f,a=j(e.stateSnapshot,c);_(e.projectRoot,c,e.logger),(a.added.length>0||a.storiesAdded>0)&&e.logger?.info?.(`[neocortex] discovered ${a.added.length} epic(s), ${a.storiesAdded} story-ies from ${r?t:S(t)}`);for(const d of c.warnings)e.logger?.warn?.(`[neocortex] discovery: ${d}`);return{applied:!0,added:a.added,skipped:a.skipped,storiesAdded:a.storiesAdded}}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook failed: ${i}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`error: ${i}`}}}async function M(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await N(e)}catch(s){const t=s instanceof Error?s.message:String(s);return e.logger?.warn?.(`[neocortex] discovery hook (outer) failed: ${t}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`outer error: ${t}`}}}export{Y as DISCOVERY_STATE_BACKUP_SUFFIX,M as maybeRunDiscoveryHook,N as runDiscoveryHook};
@@ -84,6 +84,23 @@ export declare function maybeAutoResolveYoloopArgs(ctx: AutoResolveYoloopContext
84
84
  * reinterpret corrupt/unavailable persisted state as a fresh session.
85
85
  */
86
86
  export declare function readYoloopForRequest(args: string, projectRoot: string, nowIso?: string): Promise<YoloopPersistedState | undefined>;
87
+ /**
88
+ * P227.21 (R8, DEC-06, DEC-15): `*yoloop` start hook, run by `invoke.ts` before the
89
+ * state snapshot is projected. It runs the P227.20 branch-mode conversion and
90
+ * then the origin-binding capture for the resolved target epic. The order of the start adaptations is: policy (P227.16),
91
+ * then branch-mode conversion (P227.20), then the origin binding (this hook), then the plan
92
+ * request. Only yoloop triggers do I/O. The hook never throws and never aborts
93
+ * the request: it reports one public stderr line (outcome and reason code only)
94
+ * and returns the receipt.
95
+ */
96
+ export declare function maybeCaptureYoloopStartOriginBinding(args: string, projectRoot: string, options?: {
97
+ readonly nowIso?: string;
98
+ readonly fetchTimeoutMs?: number;
99
+ readonly quiet?: boolean;
100
+ /** DEC-15 test seams forwarded to the P227.20 conversion. */
101
+ readonly prProvider?: import('../git/legacy-branch-mode-conversion.js').LegacyBranchModeConversionPrProvider;
102
+ readonly repository?: string;
103
+ }): Promise<import('./yoloop-start-origin-binding.js').OriginBindingStartReceipt | undefined>;
87
104
  /**
88
105
  * Post-response hook: apply server-provided operations to local state.
89
106
  * Safe to call for any response — no-op if no yoloopStateUpdate present.