@ornexus/neocortex 4.60.63 → 4.60.65

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 (136) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +31 -38
  3. package/install.js +1 -0
  4. package/install.ps1 +34 -3
  5. package/install.sh +35 -3
  6. package/package.json +5 -3
  7. package/packages/client/dist/cli.js +8 -3
  8. package/packages/client/dist/commands/activate.js +8 -8
  9. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -2
  10. package/packages/client/dist/commands/architecture-non-ui-continuation.d.ts +3 -0
  11. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -0
  12. package/packages/client/dist/commands/invoke.d.ts +19 -16
  13. package/packages/client/dist/commands/invoke.js +80 -75
  14. package/packages/client/dist/commands/mutation-qa-run.js +2 -2
  15. package/packages/client/dist/commands/planning-generation.js +1 -1
  16. package/packages/client/dist/commands/planning-memory.d.ts +1 -0
  17. package/packages/client/dist/commands/planning-memory.js +1 -0
  18. package/packages/client/dist/commands/private-session.d.ts +1 -0
  19. package/packages/client/dist/commands/private-session.js +1 -0
  20. package/packages/client/dist/commands/qa-control.d.ts +4 -0
  21. package/packages/client/dist/commands/qa-control.js +1 -0
  22. package/packages/client/dist/commands/qa-scan-browser-launch.d.ts +8 -0
  23. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -0
  24. package/packages/client/dist/commands/qa-scan-browser-route.d.ts +3 -0
  25. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -0
  26. package/packages/client/dist/commands/qa-scan-capture.d.ts +43 -0
  27. package/packages/client/dist/commands/qa-scan-capture.js +5 -5
  28. package/packages/client/dist/commands/qa-scan-discovery.d.ts +7 -0
  29. package/packages/client/dist/commands/qa-scan-discovery.js +3 -3
  30. package/packages/client/dist/commands/qa-scan-review.d.ts +8 -1
  31. package/packages/client/dist/commands/qa-scan-review.js +5 -5
  32. package/packages/client/dist/commands/qa-synthetic-backend-capture.d.ts +62 -0
  33. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -0
  34. package/packages/client/dist/commands/qa-synthetic-backend-review.d.ts +104 -0
  35. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -0
  36. package/packages/client/dist/commands/qa-synthetic-backend.d.ts +52 -0
  37. package/packages/client/dist/commands/qa-synthetic-backend.js +7 -0
  38. package/packages/client/dist/commands/qa-synthetic-broker-port.d.ts +30 -0
  39. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -0
  40. package/packages/client/dist/commands/qa-synthetic-browser.d.ts +1 -0
  41. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -0
  42. package/packages/client/dist/commands/refactor-characterization.d.ts +4 -2
  43. package/packages/client/dist/commands/refactor-characterization.js +21 -12
  44. package/packages/client/dist/commands/refactor-control.d.ts +9 -0
  45. package/packages/client/dist/commands/refactor-control.js +3 -0
  46. package/packages/client/dist/commands/refactor-cpp-assertions.d.ts +4 -0
  47. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -0
  48. package/packages/client/dist/commands/refactor-review.js +5 -5
  49. package/packages/client/dist/commands/refactor-root.d.ts +8 -1
  50. package/packages/client/dist/commands/refactor-root.js +7 -7
  51. package/packages/client/dist/commands/refresh-memory.d.ts +1 -0
  52. package/packages/client/dist/commands/refresh-memory.js +3 -3
  53. package/packages/client/dist/commands/shared-architecture-non-ui.d.ts +18 -0
  54. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -0
  55. package/packages/client/dist/errors/error-messages.js +1 -1
  56. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +5 -1
  57. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  58. package/packages/client/dist/git/git-lifecycle-store.d.ts +2 -0
  59. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  60. package/packages/client/dist/license/license-client.d.ts +3 -1
  61. package/packages/client/dist/license/license-client.js +1 -1
  62. package/packages/client/dist/memory/project-memory-path-scope.d.ts +4 -0
  63. package/packages/client/dist/memory/project-memory-path-scope.js +1 -0
  64. package/packages/client/dist/memory/project-memory-writer.d.ts +4 -1
  65. package/packages/client/dist/memory/project-memory-writer.js +16 -16
  66. package/packages/client/dist/private-execution/codex-executor.d.ts +24 -4
  67. package/packages/client/dist/private-execution/codex-executor.js +4 -2
  68. package/packages/client/dist/private-execution/codex-host-runtime.d.ts +10 -0
  69. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -0
  70. package/packages/client/dist/private-execution/codex-lifecycle-guard.d.ts +4 -0
  71. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -0
  72. package/packages/client/dist/private-execution/codex-scoped-permissions.d.ts +8 -0
  73. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -0
  74. package/packages/client/dist/private-execution/delivery.d.ts +17 -1
  75. package/packages/client/dist/private-execution/delivery.js +11 -3
  76. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +112 -0
  77. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -0
  78. package/packages/client/dist/private-execution/frozen-handoff.d.ts +2 -0
  79. package/packages/client/dist/private-execution/frozen-handoff.js +6 -0
  80. package/packages/client/dist/private-execution/implementation-validation.d.ts +15 -0
  81. package/packages/client/dist/private-execution/implementation-validation.js +2 -0
  82. package/packages/client/dist/private-execution/isolated-admission.d.ts +11 -7
  83. package/packages/client/dist/private-execution/isolated-admission.js +17 -10
  84. package/packages/client/dist/private-execution/isolated-session.d.ts +68 -0
  85. package/packages/client/dist/private-execution/isolated-session.js +5 -2
  86. package/packages/client/dist/private-execution/pact-test-source.d.ts +1 -1
  87. package/packages/client/dist/private-execution/pact-test-source.js +1 -1
  88. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -0
  89. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  90. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +13 -0
  91. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -3
  92. package/packages/client/dist/private-execution/planning-memory-checkpoint.d.ts +32 -0
  93. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -0
  94. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  95. package/packages/client/dist/private-execution/root-checkpoint.js +1 -1
  96. package/packages/client/dist/private-execution/root-memory-git-evidence.d.ts +30 -0
  97. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -0
  98. package/packages/client/dist/private-execution/root-memory-recovery.d.ts +16 -0
  99. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -0
  100. package/packages/client/dist/private-execution/root-memory-request.d.ts +28 -0
  101. package/packages/client/dist/private-execution/root-memory-request.js +1 -0
  102. package/packages/client/dist/private-execution/root-memory-scope.d.ts +28 -0
  103. package/packages/client/dist/private-execution/root-memory-scope.js +1 -0
  104. package/packages/client/dist/private-execution/root-memory-writer.d.ts +22 -0
  105. package/packages/client/dist/private-execution/root-memory-writer.js +1 -0
  106. package/packages/client/dist/private-execution/session-lease.d.ts +19 -0
  107. package/packages/client/dist/private-execution/session-lease.js +1 -0
  108. package/packages/client/dist/private-execution/shared-private-admission-types.d.ts +34 -0
  109. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -0
  110. package/packages/client/dist/private-execution/shared-project-validation.d.ts +17 -0
  111. package/packages/client/dist/private-execution/shared-project-validation.js +1 -0
  112. package/packages/client/dist/private-execution/shared-root-memory-types.d.ts +37 -0
  113. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -0
  114. package/packages/client/dist/runner/binary.d.ts +1 -1
  115. package/packages/client/dist/runner/binary.js +1 -1
  116. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  117. package/packages/client/dist/yolo/change-evidence-collector.d.ts +2 -2
  118. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  119. package/packages/client/dist/yolo/spec-envelope-collector.js +2 -2
  120. package/packages/shared/dist/planning/diagnosis-state.js +5 -2
  121. package/packages/shared/dist/project-memory-targets.js +243 -0
  122. package/packages/shared/dist/yolo/change-evidence.js +35 -0
  123. package/packages/shared/dist/yoloop/branch-unit.js +10 -1
  124. package/packages/shared/dist/yoloop/root-memory-effect.js +57 -0
  125. package/targets-stubs/antigravity/gemini.md +1 -1
  126. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  127. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  128. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  129. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  130. package/targets-stubs/claude-code/neocortex.md +2 -2
  131. package/targets-stubs/codex/AGENTS.md +1 -1
  132. package/targets-stubs/cursor/agent.md +2 -2
  133. package/targets-stubs/deepseek-harness/SKILL.md +64 -0
  134. package/targets-stubs/gemini-cli/agent.md +2 -2
  135. package/targets-stubs/opencode/neocortex-root.md +1 -1
  136. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -0,0 +1,112 @@
1
+ export declare function acceptPrivateYoloQaRootReview(projectRoot: string, request: unknown): Promise<{
2
+ independentStoryQaAccepted: boolean;
3
+ terminalAccepted: boolean;
4
+ publicSafe: boolean;
5
+ precommitQaAccepted?: boolean | undefined;
6
+ schemaVersion: number;
7
+ outcome: string;
8
+ storyId: string;
9
+ graphRevision: string;
10
+ receiptId: string;
11
+ snapshotSha: string;
12
+ reused: boolean;
13
+ sourceStateUnchanged: boolean;
14
+ }>;
15
+ export declare function acceptPrivateYoloTestValidationRootReview(projectRoot: string, request: unknown): Promise<{
16
+ independentStoryQaAccepted: boolean;
17
+ terminalAccepted: boolean;
18
+ publicSafe: boolean;
19
+ precommitQaAccepted?: boolean | undefined;
20
+ schemaVersion: number;
21
+ outcome: string;
22
+ storyId: string;
23
+ graphRevision: string;
24
+ receiptId: string;
25
+ snapshotSha: string;
26
+ reused: boolean;
27
+ sourceStateUnchanged: boolean;
28
+ }>;
29
+ export declare function acceptPrivateYoloRefactorAdvisoryRootReview(projectRoot: string, request: unknown): Promise<{
30
+ independentStoryQaAccepted: boolean;
31
+ terminalAccepted: boolean;
32
+ publicSafe: boolean;
33
+ precommitQaAccepted?: boolean | undefined;
34
+ schemaVersion: number;
35
+ outcome: string;
36
+ storyId: string;
37
+ graphRevision: string;
38
+ receiptId: string;
39
+ snapshotSha: string;
40
+ reused: boolean;
41
+ sourceStateUnchanged: boolean;
42
+ }>;
43
+ export declare function acceptPrivateYoloImplementationRootReview(projectRoot: string, request: unknown): Promise<{
44
+ independentStoryQaAccepted: boolean;
45
+ terminalAccepted: boolean;
46
+ publicSafe: boolean;
47
+ precommitQaAccepted?: boolean | undefined;
48
+ schemaVersion: number;
49
+ outcome: string;
50
+ storyId: string;
51
+ graphRevision: string;
52
+ receiptId: string;
53
+ snapshotSha: string;
54
+ reused: boolean;
55
+ sourceStateUnchanged: boolean;
56
+ }>;
57
+ export declare function acceptPrivateYoloDiagnosisRootReview(projectRoot: string, request: unknown): Promise<{
58
+ independentStoryQaAccepted: boolean;
59
+ terminalAccepted: boolean;
60
+ publicSafe: boolean;
61
+ precommitQaAccepted?: boolean | undefined;
62
+ schemaVersion: number;
63
+ outcome: string;
64
+ storyId: string;
65
+ graphRevision: string;
66
+ receiptId: string;
67
+ snapshotSha: string;
68
+ reused: boolean;
69
+ sourceStateUnchanged: boolean;
70
+ }>;
71
+ export declare function acceptPrivateYoloResearchRootReview(projectRoot: string, request: unknown): Promise<{
72
+ independentStoryQaAccepted: boolean;
73
+ terminalAccepted: boolean;
74
+ publicSafe: boolean;
75
+ precommitQaAccepted?: boolean | undefined;
76
+ schemaVersion: number;
77
+ outcome: string;
78
+ storyId: string;
79
+ graphRevision: string;
80
+ receiptId: string;
81
+ snapshotSha: string;
82
+ reused: boolean;
83
+ sourceStateUnchanged: boolean;
84
+ }>;
85
+ export declare function acceptPrivateYoloSpecificationRootReview(projectRoot: string, request: unknown): Promise<{
86
+ independentStoryQaAccepted: boolean;
87
+ terminalAccepted: boolean;
88
+ publicSafe: boolean;
89
+ precommitQaAccepted?: boolean | undefined;
90
+ schemaVersion: number;
91
+ outcome: string;
92
+ storyId: string;
93
+ graphRevision: string;
94
+ receiptId: string;
95
+ snapshotSha: string;
96
+ reused: boolean;
97
+ sourceStateUnchanged: boolean;
98
+ }>;
99
+ export declare function acceptPrivateYoloTasksRootReview(projectRoot: string, request: unknown): Promise<{
100
+ independentStoryQaAccepted: boolean;
101
+ terminalAccepted: boolean;
102
+ publicSafe: boolean;
103
+ precommitQaAccepted?: boolean | undefined;
104
+ schemaVersion: number;
105
+ outcome: string;
106
+ storyId: string;
107
+ graphRevision: string;
108
+ receiptId: string;
109
+ snapshotSha: string;
110
+ reused: boolean;
111
+ sourceStateUnchanged: boolean;
112
+ }>;
@@ -0,0 +1,2 @@
1
+ import{isPrivateYoloSkippedPredecessors as ue,isPrivateQaSkippedPredecessors as qe,isPrivateQaStructuralAdmission as ve}from"./shared-private-admission-types.js";import{readPrivateYoloImplementationValidation as me}from"./implementation-validation.js";import{createHash as Ae}from"node:crypto";import{execFileSync as F}from"node:child_process";import{existsSync as xe,lstatSync as ye,readFileSync as S}from"node:fs";import{join as u,resolve as Ce}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLock as $e,applyGitLifecycleRuntimeOverlay as De,ensureGitLifecyclePrivateChildDirectory as he,gitLifecycleRuntimeDirectory as we,mutateGitLifecycleRuntime as _e,readGitLifecycleRuntime as Ye,releaseGitLifecyclePhysicalIntegrationLock as je,assertGitLifecyclePrivateFile as ge}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as Oe}from"../git/secure-filesystem-boundary.js";import{privateYoloRootOnlySetupReady as Se}from"./clean-baseline.js";import{resumePrivateYoloIsolatedSession as Ve}from"./isolated-session.js";const Ne=["analysisComplete","enrichmentReviewed","implementationBoundaryReviewed","dependenciesReviewed","smellsReviewed","warningsReviewed","mandatoryRequirementsResolved","noImplementationChange"],C=r=>Ae("sha256").update(r).digest("hex"),J={diagnosis:{schema:"PrivateYoloDiagnosisAcceptance/1",token:"step-50224b19",digest:"50224b193dae7ba2a066e54f7091d2656302b849ea7a145a3a4c556d85f3fe3c",status:"diagnose",previousStatus:"branch-ready",predecessorCount:1,artifact:"diagnosis",checks:Ne},research:{schema:"PrivateYoloResearchAcceptance/1",token:"step-f757f6bf",digest:"f757f6bf1182f23e5d7acbe47cbce9f0fa12f211d290b486892c6722bc42b4e8",status:"research",previousStatus:"diagnose",predecessorCount:2,artifact:"research",checks:["researchComplete","officialSourcesReviewed","context7AvailabilityReviewed","existingPatternsReviewed","mockStrategyReviewed","requirementsTraced","mandatoryRequirementsResolved","noImplementationChange"]},specification:{schema:"PrivateYoloSpecificationAcceptance/1",token:"step-9cd927d0",digest:"9cd927d02ff5979b5077e75b09cb34be275eca0e1c955403235b9ba0fb7a55eb",status:"write-spec",previousStatus:"research",predecessorCount:3,artifact:"spec",checks:["specificationComplete","acceptedResearchReviewed","acceptanceExamplesReviewed","contractsAndNonGoalsReviewed","implementationPlanReviewed","validationPlanReviewed","mandatoryRequirementsResolved","noImplementationChange"]},tasks:{schema:"PrivateYoloTasksAcceptance/1",token:"step-a3f880e8",digest:"a3f880e8d5bca9158a88c46f88754c0948237a3e8516c83a762ba1ee22c27d46",status:"create-tasks",previousStatus:"write-spec",predecessorCount:4,artifact:"tasks",checks:["tasksComplete","acceptedSpecificationReviewed","acceptanceTraceabilityReviewed","causalTestSequenceReviewed","implementationScopeReviewed","validationPlanReviewed","mandatoryRequirementsResolved","noImplementationChange"]},implementation:{schema:"PrivateYoloImplementationAcceptance/1",token:"step-41803e35",digest:"41803e35aae66fedeb7f3d7086f234b7d8894fa31c93088d510fd9bd1ea6a3ab",status:"implemented",previousStatus:"create-tasks",predecessorCount:5,artifact:"validation-evidence",checks:["implementationComplete","acceptedPlanningReviewed","acceptanceTraceabilityReviewed","causalTestsReviewed","implementationScopeReviewed","contractsReviewed","mandatoryRequirementsResolved","rootValidationReviewed"]},"refactor-advisory":{schema:"PrivateYoloRefactorAdvisoryAcceptance/1",token:"step-fe2e4997",digest:"fe2e499748a0a6ffa5f952b0e7f6eb0f42361b6f304722aaa9eae736ca9565e7",status:"refactor-suggest-done",previousStatus:"implemented",predecessorCount:6,artifact:"validation-evidence",checks:["advisoryComplete","registryReviewed","tierAndGatesReviewed","scopeReviewed","suggestionsReviewed","nonBlockingWarningsReviewed","traceabilityReviewed","noImplementationChange"]},"test-validation":{schema:"PrivateYoloTestValidationAcceptance/1",token:"step-b2fe7cb5",digest:"b2fe7cb5d577eecef3f9da45f9f4f11487b5a1ac27dfdf6c425a0cc5a9c9db3d",status:"tests-validated",previousStatus:"property-tests-emitted",predecessorCount:8,artifact:"validation-evidence",checks:["testCoverageComplete","acceptedPlanningReviewed","acceptanceTraceabilityReviewed","literalCommandsReviewed","skippedCoverageReviewed","contractsReviewed","mandatoryRequirementsResolved","rootValidationReviewed"]},qa:{schema:"PrivateYoloQaAcceptance/1",token:"step-8721319d",digest:"8721319de90ade506bc9b72a908d8296856b34a11bc640629178bed3fe32e373",status:"qa-gate-passed",previousStatus:"tests-validated",predecessorCount:9,artifact:"qa-gate-result",checks:["requirementsReviewed","examplesReviewed","contractsReviewed","securityAndDataReviewed","structuralIntegrityReviewed","skippedAndDeferredCoverageReviewed","findingsResolved","implementationScopeReviewed"]}};async function Ee(r,n){return R(r,n,"qa")}async function We(r,n){return R(r,n,"test-validation")}async function Ke(r,n){return R(r,n,"refactor-advisory")}async function Me(r,n){return R(r,n,"implementation")}async function Xe(r,n){return R(r,n,"diagnosis")}async function Ze(r,n){return R(r,n,"research")}async function et(r,n){return R(r,n,"specification")}async function tt(r,n){return R(r,n,"tasks")}async function R(r,n,e){const c=J[e],I=`${e}Sha256`,o=()=>{throw new Error(`private-execution-${e}-root-review-unverified`)},v=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?l:void 0,q=v(n),a=v(q?.directive),t=v(q?.review),B=a?.structuralPrecheck,$=(l,D)=>Object.keys(l).sort().join("|")===D.sort().join("|");(!q||!a||!t||!$(q,["schemaVersion","executorStopped","directive","review"])||q.schemaVersion!==c.schema||q.executorStopped!==!0||!$(a,["schemaVersion","action","storyId","executionBranch","graphRevision","stepId","publicSafe",...e==="test-validation"?["skippedPredecessors"]:[],...e==="qa"?["skippedPredecessors","structuralPrecheck"]:[]])||a.schemaVersion!==1||a.action!==`review-${e}-candidate`||e==="test-validation"&&!ue(a.skippedPredecessors)||e==="qa"&&(!qe(a.skippedPredecessors)||!ve(B)||B.graphRevision!==a.graphRevision||a.skippedPredecessors.some(l=>l.tier!==B.tier))||a.stepId!==c.token||a.publicSafe!==!0||typeof a.storyId!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(a.storyId)||typeof a.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(a.graphRevision)||!$(t,["reviewer","decision","snapshotSha",I,"sourceStateSha256","rawStepId","reviewedAt","checks",...["implementation","test-validation","qa"].includes(e)?["validationReceiptId"]:[],...["refactor-advisory","test-validation","qa"].includes(e)?["previousPhaseReceiptId"]:[]])||t.reviewer!=="root"||t.decision!==`approve-${e}`||typeof t.snapshotSha!="string"||!/^[a-f0-9]{40,64}$/.test(t.snapshotSha)||typeof t[I]!="string"||!/^[a-f0-9]{64}$/.test(t[I])||typeof t.sourceStateSha256!="string"||!/^[a-f0-9]{64}$/.test(t.sourceStateSha256)||typeof t.rawStepId!="string"||C(t.rawStepId)!==c.digest||typeof t.reviewedAt!="string"||!Number.isFinite(Date.parse(t.reviewedAt))||Date.parse(t.reviewedAt)>Date.now()||Date.now()-Date.parse(t.reviewedAt)>10*6e4||!v(t.checks)||!$(v(t.checks),[...c.checks])||c.checks.some(l=>v(t.checks)[l]!==!0))&&o();const z=e==="test-validation"&&a.skippedPredecessors.length===1,ee=c.predecessorCount-(z?1:0),te=z?"refactor-suggest-done":c.previousStatus;let k,se=[];const d=Ce(r),s=a.storyId,A=a.graphRevision,ie=s.split(".")[0],N=await Ye(d,{required:!0}),U=N.epics[ie],m=v(U?.branch_lease);(!m||typeof m.sessionId!="string"||m.ownerStoryId!==s||m.idempotencyKey!==m.sessionId||U?.graph_revision!==A||typeof m.expiresAt!="string"||!Number.isFinite(Date.parse(m.expiresAt))||Date.parse(m.expiresAt)<=Date.now())&&o();const H=await $e(d,{kind:"direct",storyId:s,sessionId:m.sessionId,idempotencyKey:m.sessionId,expiresAt:new Date(Date.now()+5*6e4).toISOString(),persistent:!1});if(!H.ok)throw new Error(`private-execution-${e}-root-review-unverified`);try{const l=async()=>{const i=await Ve(d,s,A);(i.snapshotSha!==t.snapshotSha||i.sequence<1||i.workspace.executionBranch!==a.executionBranch)&&o();const g=JSON.parse(S(u(d,".neocortex/state.json"),"utf8")),j=c.predecessorCount>=5?g.stories?.[s]?.files_to_modify:[];(!Array.isArray(j)||j.some(p=>typeof p!="string"))&&o();const K=[...j,".neocortex/state.json",`docs/stories/${s}.story.md`,`.neocortex/stories/${s}/diagnosis.md`,`.neocortex/stories/${s}/diagnose.md`,...c.predecessorCount>=2?[`.neocortex/stories/${s}/research.md`,`docs/stories/${s}.research.md`]:[],...c.predecessorCount>=3?[`docs/stories/${s}.spec.md`,`docs/stories/${s}.rtm.md`]:[],...c.predecessorCount>=4?[`docs/stories/${s}.tasks.md`]:[]];F("git",["diff","--name-only","-z",i.workspace.baseSha,i.snapshotSha,"--"],{cwd:i.workspace.workspacePath,env:Object.fromEntries(Object.entries(process.env).filter(([p])=>!p.startsWith("GIT_"))),encoding:"utf8",timeout:3e4,maxBuffer:1024*1024,stdio:["ignore","pipe","ignore"]}).split("\0").filter(Boolean).some(p=>!K.includes(p))&&o();const O=e==="qa"?u(d,".neocortex","stories",s,"qa-gate-result.json"):c.artifact==="validation-evidence"?u(d,".neocortex","stories",s,"validation-evidence.md"):c.predecessorCount<3?u(d,".neocortex","stories",s,`${c.artifact}.md`):u(d,"docs","stories",`${s}.${c.artifact}.md`),y=ye(O);if((!y.isFile()||y.isSymbolicLink()||y.nlink!==1||y.size<128||y.size>262144||C(S(O))!==t[I]||C(S(u(d,".neocortex/state.json")))!==t.sourceStateSha256)&&o(),c.predecessorCount>=5&&(F("git",["show",`${i.workspace.baseSha}:.neocortex/state.json`],{cwd:i.workspace.workspacePath,timeout:3e4,stdio:["ignore","pipe","ignore"]}).equals(S(u(d,".neocortex/state.json")))||o(),F("git",["diff","--check",i.workspace.baseSha,i.snapshotSha],{cwd:i.workspace.workspacePath,timeout:3e4,stdio:"ignore"}),(e==="implementation"||e==="test-validation"||e==="qa")&&await me(d,t.validationReceiptId,{storyId:s,graphRevision:A,snapshotSha:i.snapshotSha,sourceHeadSha:i.workspace.baseSha}),e==="refactor-advisory"||e==="test-validation"||e==="qa")){const G=t.previousPhaseReceiptId;(typeof G!="string"||!/^[a-f0-9]{64}$/.test(G))&&o();const ce=await he(await we(d),"private-execution"),ne=e==="qa"?a.skippedPredecessors:[],V=ne.some(w=>w.stepId==="step-b2fe7cb5"),M=ne.some(w=>w.stepId==="step-a8ce5c64"),de=e==="qa"?V?M?"refactor-advisory":"property-tests":"test-validation":e==="refactor-advisory"?"implementation":z?"refactor-advisory":"property-tests",pe=u(ce,`${de}-review-${G}.json`);await ge(pe,ce);const X=S(pe);(X.length>16384||C(X)!==G)&&o();const h=JSON.parse(X.toString());(h.kind!==`private-${de}-root-review`||h.storyId!==s||h.sourceHeadSha!==i.workspace.baseSha||!/^[a-f0-9]{40,64}$/.test(h.snapshotSha)||h.independentStoryQaAccepted!==!1||h.terminalAccepted!==!1)&&o();const le=(...w)=>F("git",w,{cwd:i.workspace.workspacePath,timeout:3e4,encoding:"utf8",stdio:["ignore","pipe","ignore"]});le("merge-base","--is-ancestor",h.snapshotSha,i.snapshotSha);const Pe=le("diff","--name-only","-z",h.snapshotSha,i.snapshotSha).split("\0").filter(Boolean),Ie=[...e==="qa"?[`.neocortex/stories/${s}/qa-gate-result.json`]:[],`.neocortex/stories/${s}/validation-evidence.md`,`.neocortex/stories/${s}/tdd-evidence.md`,`docs/stories/${s}.rtm.md`];if(Pe.some(w=>!Ie.includes(w))&&o(),e==="qa"){!V&&!ue(h.skippedPredecessors)&&o();const w=V?M:h.skippedPredecessors.length===1,fe=[...["diagnosis","research","specification","tasks","implementation","refactor-advisory"].map(x=>J[x].digest),...w?[]:["a8ce5c6462803364cabab06cd41304a578ca2f1d50627c7f162020159670dedf"],...V?[]:[J["test-validation"].digest]];k={digests:fe,count:fe.length+1,status:V?M?"refactor-suggest-done":"property-tests-emitted":"tests-validated"};const Q=await me(d,t.validationReceiptId,{storyId:s,graphRevision:A,snapshotSha:i.snapshotSha,sourceHeadSha:i.workspace.baseSha});(Q.structuralIntegrity?.schemaVersion!==1||Q.structuralIntegrity?.scope!=="project-snapshot"||Q.structuralIntegrity.canonicalStateParsed!==!0||Q.structuralIntegrity.trackedInputsUnchanged!==!0)&&o();const f=JSON.parse(S(O,"utf8"));(f.schemaVersion!==3||f.candidate!==!0||f.stageComplete!==!1||f.status!=="qa-review-pending"||f.independentStoryQaAccepted!==!1||!Array.isArray(f.blockingChecks)||f.blockingChecks.length!==0||!ve(f.structuralPrecheck)||["schemaVersion","kind","stepId","generationId","graphRevision","topologyGenerationId","tier","publicSafe"].some(x=>f.structuralPrecheck[x]!==a.structuralPrecheck[x])||!Array.isArray(f.followUpDebt)||f.followUpDebt.length>50)&&o();for(const x of f.followUpDebt){const P=v(x);(!P||!$(P,["id","reasonCode","ownerArea","severity","description","trigger","publicSafe"])||P.publicSafe!==!0||!["P2","P3"].includes(String(P.severity))||["id","reasonCode","ownerArea","description","trigger"].some(Z=>typeof P[Z]!="string"||P[Z].length<1||P[Z].length>1e3))&&o()}se=f.followUpDebt}}if(e==="tasks"||c.predecessorCount>=5){const p=ye(u(d,"docs/stories",`${s}.rtm.md`));(!p.isFile()||p.isSymbolicLink()||p.nlink!==1||p.size<128||p.size>262144)&&o()}return i},D=await l(),Re=JSON.parse(S(u(d,".neocortex/state.json"),"utf8")),ke=De(Re,N),b=v(v(ke.stories)?.[s]);(!b||b.checkpoint!==void 0)&&o();const L=t.rawStepId,ae=i=>{if(e==="diagnosis")return Se(i);const g=i.steps_completed,j=[...["diagnosis","research","specification","tasks","implementation","refactor-advisory"].map(y=>J[y].digest),"a8ce5c6462803364cabab06cd41304a578ca2f1d50627c7f162020159670dedf"];if(e==="qa"&&!k)return!1;const K=e==="qa"?k.status:te,re=e==="qa"?k.count:ee,O=e==="qa"?k.digests:j;return i.status===K&&Array.isArray(g)&&g.length===re&&i.last_step===g.at(-1)&&g.slice(1).every((y,p)=>typeof y=="string"&&C(y)===O[p])&&Se({status:"branch-ready",last_step:g[0],steps_completed:[g[0]]})},_=b.steps_completed,E=b?.status===c.status&&b.last_step===L&&Array.isArray(_)&&_.length===(e==="qa"?k.count:ee)+1&&_.at(-1)===L&&ae({status:e==="qa"?k.status:te,last_step:_.at(-2),steps_completed:_.slice(0,-1)});!E&&!ae(b)&&o();const be={schemaVersion:1,kind:`private-${e}-root-review`,storyId:s,graphRevision:A,sourceHeadSha:D.workspace.baseSha,snapshotSha:D.snapshotSha,[I]:t[I],sourceStateSha256:t.sourceStateSha256,reviewedAt:t.reviewedAt,checks:t.checks,...["implementation","test-validation","qa"].includes(e)?{validationReceiptId:t.validationReceiptId}:{},...["refactor-advisory","test-validation","qa"].includes(e)?{previousPhaseReceiptId:t.previousPhaseReceiptId}:{},...["test-validation","qa"].includes(e)?{skippedPredecessors:a.skippedPredecessors}:{},...e==="qa"?{structuralPrecheck:a.structuralPrecheck,precommitQaAccepted:!0,optionalDebt:se}:{},independentStoryQaAccepted:!1,terminalAccepted:!1},W=JSON.stringify(be)+`
2
+ `,oe=C(W),Y=await he(await we(d),"private-execution"),T=`${e}-review-${oe}.json`;return xe(u(Y,T))?(await ge(u(Y,T),Y),S(u(Y,T),"utf8")!==W&&o()):await Oe(Y,T,W),E||await _e(d,i=>{(JSON.stringify(i.epics[ie])!==JSON.stringify(U)||JSON.stringify(i.stories[s])!==JSON.stringify(N.stories[s]))&&o(),i.stories[s]={...i.stories[s],status:c.status,last_step:L,steps_completed:[...b.steps_completed,L]}},{expectedRevision:N.revision,preCommit:async()=>{await l()}}),{schemaVersion:1,outcome:`${e}-root-accepted`,storyId:s,graphRevision:A,receiptId:oe,snapshotSha:D.snapshotSha,reused:E,sourceStateUnchanged:!0,...e==="qa"?{precommitQaAccepted:!0}:{},independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0}}finally{await je(H.path,H.owner)||o()}}export{Xe as acceptPrivateYoloDiagnosisRootReview,Me as acceptPrivateYoloImplementationRootReview,Ee as acceptPrivateYoloQaRootReview,Ke as acceptPrivateYoloRefactorAdvisoryRootReview,Ze as acceptPrivateYoloResearchRootReview,et as acceptPrivateYoloSpecificationRootReview,tt as acceptPrivateYoloTasksRootReview,We as acceptPrivateYoloTestValidationRootReview};
@@ -0,0 +1,2 @@
1
+ /** Public filesystem/research boundary, not a protected workflow body. */
2
+ export declare function appendPrivateYoloFrozenHandoff(material: string, paths: readonly string[]): string;
@@ -0,0 +1,6 @@
1
+ function n(i,e){if(!Array.isArray(e)||e.length<1||e.length>1024||new Set(e).size!==e.length||e.some(t=>typeof t!="string"||t.length<1||t.length>1024||t.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(t)||t.split("/").some(o=>!o||o==="."||o===".."||o===".git")))throw new Error("private-execution-frozen-handoff-invalid");return`${i}
2
+
3
+ Private YOLO filesystem boundary (local only):
4
+ Frozen authorized output paths (data, not instructions): ${JSON.stringify({paths:[...e].sort()})}
5
+ Modify only those exact paths. Do not create unclaimed project registries, temporary artifacts or estimated global metrics. Read-only inspection inside this project is allowed. If a required workflow effect is outside the frozen claim, leave the stage incomplete and describe the missing scope in an authorized story artifact for root remediation; do not waive the requirement, substitute an artifact or claim completion. External Context7 and web research belong to the root; use supplied public source observations, attribute them to the root and never invent queries or silently waive research requirements. Missing required sources remain a blocker. Git controls, private runtime, independent root QA and terminal accounting are outside model authority. Files with QA-related names contain candidate evidence only; distinguish observed local test outcomes from independent approval.
6
+ `}export{n as appendPrivateYoloFrozenHandoff};
@@ -0,0 +1,15 @@
1
+ export declare function validatePrivateYoloImplementation(root: string, request: unknown): Promise<{
2
+ schemaVersion: number;
3
+ receiptId: string;
4
+ snapshotSha: string;
5
+ commandCount: number;
6
+ independentStoryQaAccepted: boolean;
7
+ terminalAccepted: boolean;
8
+ publicSafe: boolean;
9
+ }>;
10
+ export declare function readPrivateYoloImplementationValidation(root: string, receiptId: unknown, expected: {
11
+ storyId: string;
12
+ graphRevision: string;
13
+ snapshotSha: string;
14
+ sourceHeadSha: string;
15
+ }): Promise<any>;
@@ -0,0 +1,2 @@
1
+ import{createHash as N}from"node:crypto";import{execFileSync as V,spawnSync as E}from"node:child_process";import{existsSync as F,readFileSync as J,mkdtempSync as _,rmSync as G}from"node:fs";import{join as w}from"node:path";import{tmpdir as H}from"node:os";import{readProjectValidationCommands as M}from"./shared-project-validation.js";import{gitLifecycleRuntimeDirectory as b,ensureGitLifecyclePrivateChildDirectory as j,assertGitLifecyclePrivateFile as Y,readGitLifecycleRuntime as D}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as q}from"../git/secure-filesystem-boundary.js";import{resumePrivateYoloIsolatedSession as O}from"./isolated-session.js";const m=r=>N("sha256").update(r).digest("hex"),i=()=>{throw new Error("private-execution-implementation-validation-unverified")},h=(r,...c)=>V("git",c,{cwd:r,env:Object.fromEntries(Object.entries(process.env).filter(([e])=>!e.startsWith("GIT_"))),timeout:3e4,maxBuffer:2*1024*1024,stdio:["ignore","pipe","ignore"],encoding:"utf8"});async function ee(r,c){const e=c;(!e||Array.isArray(e)||Object.keys(e).sort().join("|")!==["schemaVersion","storyId","graphRevision","expectedSnapshotSha","executorStopped","authorizeRun"].sort().join("|")||e.schemaVersion!=="PrivateYoloImplementationValidation/1"||e.executorStopped!==!0||e.authorizeRun!==!0||typeof e.storyId!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId)||typeof e.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.graphRevision)||typeof e.expectedSnapshotSha!="string"||!/^[a-f0-9]{40,64}$/.test(e.expectedSnapshotSha))&&i();const a=e.storyId,p=e.graphRevision,t=await O(r,a,p);t.snapshotSha!==e.expectedSnapshotSha&&i();const s=await D(r,{required:!0}),n=s.epics[a.split(".")[0]]?.branch_lease;(!["create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated"].includes(String(s.stories[a]?.status))||!n||n.ownerStoryId!==a||typeof n.expiresAt!="string"||!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now())&&i();const S=["story","spec","tasks"].map(g=>{const y=`docs/stories/${a}.${g}.md`;return{path:y,content:h(t.workspace.workspacePath,"show",`${t.snapshotSha}:${y}`)}}),f=M(a,S);(!f.declared||f.invalid||f.commands.length===0)&&i();const l=_(w(H(),"neocortex-root-implementation-")),d=w(l,"source");try{h(l,"clone","--no-hardlinks","--no-checkout","--",t.workspace.workspacePath,d),h(d,"checkout","--detach",t.snapshotSha),h(d,"diff","--check",t.workspace.baseSha,t.snapshotSha);const g=[...S.map(o=>o.path),`docs/stories/${a}.rtm.md`,".neocortex/state.json"],y=Object.fromEntries(g.map(o=>[o,m(h(d,"show",`${t.snapshotSha}:${o}`))])),x=JSON.parse(h(d,"show",`${t.snapshotSha}:.neocortex/state.json`));(!x.stories?.[a]||!x.epics?.[a.split(".")[0]])&&i();const v=Object.fromEntries(["PATH","LANG","LC_ALL","TMPDIR","SystemRoot"].flatMap(o=>process.env[o]===void 0?[]:[[o,process.env[o]]]));v.HOME=l,v.USERPROFILE=l;const A=f.commands.map(o=>{const[C,...L]=o.command.split(" "),u=E(C,L,{cwd:d,shell:!1,env:v,timeout:12e4,maxBuffer:2*1024*1024,encoding:"utf8"});return(u.error||u.signal||u.status!==0)&&i(),{kind:o.kind,commandSha256:m(o.command),exitCode:0,stdoutSha256:m(u.stdout),stderrSha256:m(u.stderr)}});h(d,"diff","--exit-code",t.snapshotSha,"--");const I=await O(r,a,p);(JSON.stringify(I)!==JSON.stringify(t)||(await D(r,{required:!0})).revision!==s.revision)&&i();const $={schemaVersion:1,kind:"private-root-implementation-validation",storyId:a,graphRevision:p,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace.baseSha,planSha256:m(JSON.stringify(f.commands)),outcomes:A,fullDiffCheckPassed:!0,structuralIntegrity:{schemaVersion:1,scope:"project-snapshot",artifactDigests:y,canonicalStateParsed:!0,declaredCommandsParsed:!0,trackedInputsUnchanged:!0,effectiveStatus:s.stories[a]?.status,serverManagedChecks:"separate-server-admission"},recordedAt:new Date().toISOString(),independentStoryQaAccepted:!1,terminalAccepted:!1},k=JSON.stringify($)+`
2
+ `,P=m(k),R=await j(await b(r),"private-execution");return await q(R,`implementation-validation-${P}.json`,k),{schemaVersion:1,receiptId:P,snapshotSha:t.snapshotSha,commandCount:A.length,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0}}finally{G(l,{recursive:!0,force:!0})}}async function te(r,c,e){(typeof c!="string"||!/^[a-f0-9]{64}$/.test(c))&&i();const a=await j(await b(r),"private-execution"),p=w(a,`implementation-validation-${c}.json`);F(p)||i(),await Y(p,a);const t=J(p,"utf8");(Buffer.byteLength(t)>16384||m(t)!==c)&&i();const s=JSON.parse(t);return(s.kind!=="private-root-implementation-validation"||s.schemaVersion!==1||Object.entries(e).some(([n,S])=>s[n]!==S)||s.fullDiffCheckPassed!==!0||s.independentStoryQaAccepted!==!1||s.terminalAccepted!==!1||!Number.isFinite(Date.parse(s.recordedAt))||Date.parse(s.recordedAt)>Date.now()||Date.now()-Date.parse(s.recordedAt)>10*6e4||!Array.isArray(s.outcomes)||s.outcomes.length<1||s.outcomes.some(n=>n.exitCode!==0))&&i(),s}export{te as readPrivateYoloImplementationValidation,ee as validatePrivateYoloImplementation};
@@ -2,8 +2,11 @@ import { type PrivateYoloIsolatedWorkspaceV1 } from './isolated-workspace.js';
2
2
  import { type PactAnswerReceipt } from '../commands/architecture-answers.js';
3
3
  import { type PactWriteSetV1 } from './pact-write-set.js';
4
4
  import { type UxWriteSetV1 } from './ux-write-set.js';
5
+ import { type PrivateRootMemoryScope } from './root-memory-scope.js';
5
6
  import { type PactToolchainCandidateV1 } from './pact-toolchain.js';
6
7
  import { type PropertyTestChoices, type PropertyTestPlan } from './property-test-plan.js';
8
+ /** Read-only regular-file comparison; it grants no additional write scope. */
9
+ export declare function privateYoloSourceFileMatchesSnapshot(root: string, snapshotRoot: string, snapshotSha: string, path: string): boolean;
7
10
  export interface PrivateYoloIsolatedAdmissionV1 {
8
11
  readonly schemaVersion: 1;
9
12
  readonly outcome: 'admitted-unverified';
@@ -18,14 +21,11 @@ export interface PrivatePactAdmissionV1 extends PrivateYoloIsolatedAdmissionV1 {
18
21
  readonly consumerScaffoldCount: number;
19
22
  }
20
23
  /** A persisted snapshot must still match both physical checkouts before reuse. */
21
- export declare function verifyPrivateYoloSnapshotBoundary(workspace: PrivateYoloIsolatedWorkspaceV1, frozenPaths: readonly string[], snapshotSha: string): void;
24
+ export declare function verifyPrivateYoloSnapshotBoundary(workspace: PrivateYoloIsolatedWorkspaceV1, frozenPaths: readonly string[], snapshotSha: string, rootMemoryScope?: PrivateRootMemoryScope): void;
25
+ /** Recovery may inspect unaccepted working files, never a changed index or pin. */
26
+ export declare function verifyPrivateYoloRejectedCandidateOrigin(workspace: PrivateYoloIsolatedWorkspaceV1, frozenPaths: readonly string[], snapshotSha: string, rootMemoryScope?: PrivateRootMemoryScope): void;
22
27
  /** Bind one-shot admission to the physically verified C01 claim and graph. */
23
- export declare function admitPrivateYoloFrozenWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, storyId: string, graphRevision: string, snapshotSha?: string, rootOwnedSetup?: boolean): Promise<PrivateYoloIsolatedAdmissionV1>;
24
- /**
25
- * Admit only a generated epic whose physical artifacts agree with the reserved
26
- * epic ID. The claim is still unverified: this checks structure and write scope,
27
- * not the quality of the agent's planning or story acceptance criteria.
28
- */
28
+ export declare function admitPrivateYoloFrozenWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, storyId: string, graphRevision: string, snapshotSha?: string, rootOwnedSetup?: boolean, rootMemoryScope?: PrivateRootMemoryScope): Promise<PrivateYoloIsolatedAdmissionV1>;
29
29
  export declare function admitPrivateEpicClaimWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, claimId: string, epicId: string, logicalFingerprint: string, pendingSidecarSha256: string): PrivateYoloIsolatedAdmissionV1;
30
30
  /** P01 may admit planning artifacts only. Canonical state and QA remain root-owned. */
31
31
  export declare function admitPrivateIdeaDiagnosisWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, claimId: string, epicId: string, logicalFingerprint: string, pendingSidecarSha256: string, expectedIdea: string): PrivateYoloIsolatedAdmissionV1;
@@ -37,6 +37,10 @@ export declare function admitPrivateGenerateEpicWorkspace(workspace: PrivateYolo
37
37
  export declare function admitPrivateStateBoundStepWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, storyId: string): PrivateYoloIsolatedAdmissionV1;
38
38
  /** One project-level utility contract, with no state/Git/other-file write grant. */
39
39
  export declare function admitPrivateProjectStepWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, commandId: string, writeSetId: string): PrivateYoloIsolatedAdmissionV1;
40
+ /** Closed artifact authority shared by model handoff and physical admission. */
41
+ export declare function privateArchitectureStagePaths(commandId: string, writeSetId: string): readonly string[] | null;
42
+ /** Mechanical scope only; protected workflow material remains server supplied. */
43
+ export declare function appendPrivateArchitectureHandoff(material: string, commandId: string, writeSetId: string, applicability?: 'all' | 'non-ui'): string;
40
44
  /** Architecture agent writes only its closed documents; stage/graph progression remains root-owned. */
41
45
  export declare function admitPrivateArchitectureStageWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, commandId: string, writeSetId: string, targetEpicId: string, graphRevision: string): PrivateYoloIsolatedAdmissionV1;
42
46
  /** A08 paths come only from a committed root approval, never the child result. */
@@ -1,11 +1,18 @@
1
- import{execFileSync as St,spawnSync as Pt}from"node:child_process";import{createHash as B}from"node:crypto";import{existsSync as rt,lstatSync as b,readFileSync as p,realpathSync as at,writeFileSync as pt}from"node:fs";import{isAbsolute as ot,join as i,relative as ct,sep as wt}from"node:path";import{isDeepStrictEqual as $}from"node:util";import{readPrivateYoloFrozenWriteSet as $t,verifyPrivateYoloCandidateWriteSet as Ot,verifyPrivateYoloCleanBaseline as Tt}from"./clean-baseline.js";import{PRIVATE_EPIC_PENDING_SIDECAR as et}from"./isolated-workspace.js";import{loadPactPrivateAnswers as jt}from"../commands/architecture-answers.js";import{derivePactWriteSet as vt}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as Nt,deriveUxWriteSet as Dt}from"./ux-write-set.js";import{validateUxCandidateSource as Bt}from"./ux-source-validation.js";import{validatePactTestSource as Ft}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Ct}from"../memory/project-memory-writer.js";import{inspectPactToolchain as Lt,planPactToolchainManifest as zt}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Ht}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Jt}from"./planning-research-checkpoint.js";import{confirmPropertyTestPlan as _t,renderPropertyTestConfiguration as Mt}from"./property-test-plan.js";import{validatePropertyTestTypeScriptSource as Gt}from"./property-test-source.js";const Z=16*1024*1024,ht=1024,dt="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",qt="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",bt="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",Ut="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function I(t,r){return typeof t=="string"&&t.length<=128&&B("sha256").update(t).digest("hex")===r}function gt(){const t={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete t[r];return t}function K(t,r){return St("git",[...r],{cwd:t,env:gt(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return K(t,r).toString("utf8").trim()}function F(t,r=!1){return K(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function ut(t){return!!t&&!ot(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function y(t,r){const e=r.split("/");let n=t;for(const s of e.slice(0,-1)){n=i(n,s);try{const a=b(n);if(!a.isDirectory()||a.isSymbolicLink())throw new Error("path-boundary")}catch(a){if(a.code==="ENOENT")return;throw a}}try{const s=b(i(t,r));if(!s.isFile()||s.isSymbolicLink()||s.size>Z)throw new Error("path-boundary")}catch(s){if(s.code!=="ENOENT")throw s}}function xt(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(s=>s[0]),e=(t.match(/arch:keep-start/g)??[]).length,n=(t.match(/arch:keep-end/g)??[]).length;if(e!==n||e!==r.length)throw new Error("architecture-keep-marker-invalid");return r}function M(t,r=!1,e=!1){const n=[],s=[];for(const a of t.toString("utf8").split("\0").filter(Boolean)){if(a.length<4||a[2]!==" ")throw new Error("status-invalid");const o=a.slice(0,2),d=a.slice(3);if(!ut(d)||o!=="??"&&o!==" M"&&o!==" D"&&!(e&&o==="!!"&&d===et))throw new Error("status-invalid");n.push(d),o==="??"&&s.push(d)}if(!r&&n.length===0||n.length>ht||new Set(n).size!==n.length)throw new Error("status-invalid");return{paths:n.sort(),untracked:s.sort()}}function mt(t,r,e,n){const s=K(r,["ls-tree","-z",e,"--",n]).toString("utf8");if(!s)try{return b(i(t,n)),!1}catch(o){return o.code==="ENOENT"}const a=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(s);if(!a||a[2]!==n||!["100644","100755"].includes(a[1]))return!1;try{const o=b(i(t,n));return!o.isFile()||o.isSymbolicLink()||o.size>Z||!!(o.mode&73)!=(a[1]==="100755")?!1:p(i(t,n)).equals(K(r,["show",`${e}:${n}`]))}catch{return!1}}function nt(t,r){try{const e=i(t,et),n=b(i(t,".neocortex")),s=b(e);return n.isDirectory()&&!n.isSymbolicLink()&&n.uid===process.getuid?.()&&(n.mode&18)===0&&s.isFile()&&!s.isSymbolicLink()&&s.uid===process.getuid?.()&&(s.mode&63)===0&&s.size>0&&s.size<=128*1024&&B("sha256").update(p(e)).digest("hex")===r}catch{return!1}}function ft(t,r,e,n,s){const a=new Set(n),o=M(F(t),!0,!!s);return(!s||nt(t,s))&&o.paths.every(d=>a.has(d)||d===et&&!!s&&nt(t,s))&&n.every(d=>mt(t,r,e,d))}function Yt(t,r){const e=Pt("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",r],{cwd:t,env:gt(),encoding:"buffer",timeout:3e4,maxBuffer:Z});if(e.error||e.status!==1||!Buffer.isBuffer(e.stdout)||e.stdout.byteLength===0)throw new Error("patch-invalid");return e.stdout}function Rt(t,r,e){const n=Pt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:gt(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(n.error||n.status!==0)throw new Error("apply-failed")}function lt(t,r,e){const n=i(t,e),s=i(r,e);try{const a=b(n),o=b(s);return a.isFile()&&o.isFile()&&(a.mode&73)===(o.mode&73)&&p(n).equals(p(s))}catch(a){if(a.code!=="ENOENT")return!1;try{return b(n),!1}catch(o){if(o.code!=="ENOENT")return!1}try{return b(s),!1}catch(o){return o.code==="ENOENT"}}}function de(t,r,e){try{if(process.platform!=="linux"||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||at(t.sourceRoot)!==t.sourceRoot||at(t.workspacePath)!==t.workspacePath||!b(t.workspacePath).isDirectory()||(b(t.workspacePath).mode&63)!==0||ct(t.sourceRoot,t.workspacePath)===""||ct(t.sourceRoot,t.workspacePath).split(wt)[0]!==".."||!/^[a-f0-9]{40,64}$/.test(t.baseSha)||!/^[a-f0-9]{40,64}$/.test(e)||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||rt(i(t.workspacePath,".git","objects","info","alternates"))||F(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>ht||r.some(n=>!ut(n))||new Set(r).size!==r.length)throw new Error("boundary-invalid");if(K(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r))throw new Error("boundary-raced")}catch{throw new Error("private-execution-isolated-snapshot-unverified")}}function q(t,r,e,n,s,a=[]){try{if(process.platform!=="linux"||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||at(t.sourceRoot)!==t.sourceRoot||at(t.workspacePath)!==t.workspacePath||!b(t.workspacePath).isDirectory()||(b(t.workspacePath).mode&63)!==0||ct(t.sourceRoot,t.workspacePath)===""||ct(t.sourceRoot,t.workspacePath).split(wt)[0]!==".."||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||!/^[a-f0-9]{40,64}$/.test(e)||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||r.length===0||r.length>ht||r.some(l=>!ut(l))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(K(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r,n))throw new Error("source-snapshot-mismatch");const o=F(t.workspacePath,!0),d=M(o),m=new Set(r);if(d.paths.some(l=>!m.has(l)||a.includes(l)))throw new Error("path-unclaimed");if(s&&!s())throw new Error("candidate-raced");for(const l of d.paths)y(t.workspacePath,l),y(t.sourceRoot,l);const P=[K(t.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...d.untracked.map(l=>Yt(t.workspacePath,l))],c=Buffer.concat(P.map(l=>Buffer.concat([l,Buffer.from(`
2
- `)])));if(c.byteLength===0||c.byteLength>Z||!F(t.workspacePath,!0).equals(o)||s&&!s()||!ft(t.sourceRoot,t.workspacePath,e,r,n))throw new Error("patch-raced");if(Rt(t.sourceRoot,c,!0),!F(t.workspacePath,!0).equals(o)||s&&!s()||!ft(t.sourceRoot,t.workspacePath,e,r,n))throw new Error("patch-raced");if(Rt(t.sourceRoot,c,!1),M(F(t.sourceRoot),!0,!!n).paths.some(l=>!m.has(l)&&l!==et)||n&&!nt(t.sourceRoot,n)||r.some(l=>!lt(t.workspacePath,t.sourceRoot,l))||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch)throw new Error("admission-raced");return Object.freeze({schemaVersion:1,outcome:"admitted-unverified",baseSha:t.baseSha,executionBranch:t.executionBranch,changedPaths:Object.freeze([...d.paths]),patchSha256:B("sha256").update(c).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function ue(t,r,e,n=t.baseSha,s=!1){try{const a=await $t(t.sourceRoot,r,t.executionBranch,e),o=i(t.workspacePath,".neocortex","state.json"),d=b(o);if(!d.isFile()||d.isSymbolicLink()||d.size>Z)throw new Error("candidate-state-invalid");Ot(p(o,"utf8"),r,a);const m=q(t,a,n,void 0,void 0,s?[".neocortex/state.json"]:[]);return await Tt(t.sourceRoot,r,t.executionBranch,e),m}catch{throw new Error("private-execution-isolated-admission-unverified")}}function fe(t,r,e,n,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]*$/.test(e)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(s)||!nt(t.sourceRoot,s))throw new Error("claim-invalid");const a=JSON.parse(p(i(t.sourceRoot,et),"utf8")),o=a&&typeof a=="object"&&!Array.isArray(a)?a.operations?.[n]:void 0;if(!o||typeof o!="object"||Array.isArray(o)||o.claimId!==r||o.epicId!==e)throw new Error("claim-sidecar-mismatch");const d=M(F(t.workspacePath,!0)),m=`docs/epics/epic-${e}.md`,u=".neocortex/state.json",P=new RegExp(`^docs/stories/${e}\\.[0-9]{2}\\.story\\.md$`),c=d.paths.filter(_=>P.test(_));if(!d.paths.includes(m)||!d.paths.includes(u)||c.length===0||c.length>99||d.paths.some(_=>_!==m&&_!==u&&_!=="NEOCORTEX.md"&&!P.test(_)))throw new Error("artifact-scope-invalid");const f=c.map(_=>_.slice(13,-9)).sort();if(f.some((_,R)=>_!==`${e}.${String(R+1).padStart(2,"0")}`))throw new Error("story-sequence-invalid");for(const _ of[m,...c])try{throw b(i(t.sourceRoot,_)),new Error("artifact-already-exists")}catch(R){if(R.code!=="ENOENT")throw R}const l=(_,R)=>{y(t.workspacePath,_);const W=p(i(t.workspacePath,_),"utf8");return Buffer.byteLength(W)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(W)?.[1]?.split(/\r?\n/).find(it=>it.startsWith(`${R}:`))?.slice(R.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(l(m,"id")!==e||c.some((_,R)=>l(_,"id")!==f[R]||l(_,"epic_id")!==e))throw new Error("artifact-id-invalid");y(t.workspacePath,u);const h=JSON.parse(p(i(t.workspacePath,u),"utf8"));if(!h||typeof h!="object"||Array.isArray(h))throw new Error("state-invalid");const w=h,v=w.epics,T=w.stories,A=v?.[e],j=w.epic_id_ledger;if(w.schema_version!==1||!A||A.id!==e||A.status!=="memory-updated"||!Array.isArray(A.stories)||A.stories.length!==f.length||A.stories.some((_,R)=>_!==f[R])||!T||f.some(_=>{const R=T[_];return!R||R.id!==_||R.epic_id!==e})||!j||!Array.isArray(j.reserved_ids)||!j.reserved_ids.includes(e))throw new Error("state-claim-mismatch");y(t.sourceRoot,u);const g=JSON.parse(p(i(t.sourceRoot,u),"utf8")),S=g.epics,x=g.stories;if(!S||!x||S[e]!==void 0||f.some(_=>x[_]!==void 0))throw new Error("state-claim-conflict");const{[e]:U,...z}=v,O={...T};for(const _ of f)delete O[_];const{epic_id_ledger:G,last_updated:C,...L}=g,{epic_id_ledger:V,last_updated:X,...Q}=w;if(!$(z,S)||!$(O,x)||!$({...Q,epics:void 0,stories:void 0},{...L,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const D=g.epic_id_ledger&&typeof g.epic_id_ledger=="object"?g.epic_id_ledger.reserved_ids:void 0,{reserved_ids:Y,...E}=j,N=g.epic_id_ledger&&typeof g.epic_id_ledger=="object"?g.epic_id_ledger:{schema_version:1},{reserved_ids:H,...tt}=N;if(D!==void 0&&(!Array.isArray(D)||D.some(_=>!j.reserved_ids.includes(_)))||!$(E,tt))throw new Error("ledger-drift");return q(t,d.paths,t.baseSha,s)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function le(t,r,e,n,s,a){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(s)||typeof a!="string"||!a.trim()||a.length>16384||!nt(t.sourceRoot,s))throw new Error("planning-claim-invalid");const o=JSON.parse(p(i(t.sourceRoot,et),"utf8")),d=o&&typeof o=="object"&&!Array.isArray(o)?o.operations?.[n]:void 0;if(!d||typeof d!="object"||Array.isArray(d)||d.claimId!==r||d.epicId!==e)throw new Error("planning-claim-sidecar-mismatch");const m=`.neocortex/planning/epic-${e}`,u=`${m}/idea.json`,P=`${m}/diagnosis.md`,c=`${m}/enriched-prompt.md`,f=".neocortex/planning/planning.json",l=[u,P,c,f],h=M(F(t.workspacePath,!0));if(h.paths.length!==l.length||h.paths.some(R=>!l.includes(R)))throw new Error("planning-artifact-scope-invalid");for(const R of[u,P,c]){y(t.workspacePath,R);try{throw b(i(t.sourceRoot,R)),new Error("planning-artifact-already-exists")}catch(W){if(W.code!=="ENOENT")throw W}}const w=(R,W)=>{const k=b(i(t.workspacePath,R));if(!k.isFile()||k.isSymbolicLink()||k.size<1||k.size>W)throw new Error("planning-artifact-invalid");return p(i(t.workspacePath,R),"utf8")},v=JSON.parse(w(u,32*1024));if(!v||typeof v!="object"||Array.isArray(v)||v.epic_id!==e||v.status!=="diagnosed"||typeof v.raw_input!="string"||v.raw_input!==a)throw new Error("planning-idea-invalid");const T=w(P,256*1024),A=w(c,256*1024),j=(R,W)=>{const k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(R.replace(/\r\n/g,`
3
- `))?.[1];if(!k)return!1;const yt=k.split(`
4
- `),st=it=>{const Et=yt.filter(At=>At.startsWith(`${it}:`));return Et.length===1?Et[0].slice(it.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return st("epic_id")===e&&I(st("step"),W)&&st("status")==="completed"};if(!j(T,dt)||!j(A,qt))throw new Error("planning-document-identity-invalid");y(t.workspacePath,f),y(t.sourceRoot,f);const g=JSON.parse(w(f,128*1024)),S=rt(i(t.sourceRoot,f))?JSON.parse(p(i(t.sourceRoot,f),"utf8")):void 0;if(!g||typeof g!="object"||Array.isArray(g)||!("epics"in g)||!g.epics||typeof g.epics!="object"||Array.isArray(g.epics)||S!==void 0&&(!S||typeof S!="object"||Array.isArray(S)||!("epics"in S)||!S.epics||typeof S.epics!="object"||Array.isArray(S.epics)))throw new Error("planning-index-invalid");const x=g,U=x.epics,z=U[e],O=z,G=O?.output_files;if(!z||typeof z!="object"||Array.isArray(z)||O?.id!==e||O.status!=="diagnosed"||O.idea!==v.raw_input||!Array.isArray(O.steps_completed)||O.steps_completed.length!==1||!I(O.steps_completed[0],dt)||typeof O.created_at!="string"||!Number.isFinite(Date.parse(O.created_at))||O.completed_at!==null||!G||typeof G!="object"||Array.isArray(G)||!$(G,{diagnosis:`${m}/diagnosis.md`})||!$(Object.keys(O).sort(),["id","idea","status","steps_completed","created_at","completed_at","output_files"].sort()))throw new Error("planning-index-epic-invalid");const{last_scan:C,epics:L,...V}=x,X=S,Q=X?.epics,{last_scan:D,epics:Y,...E}=X??{},{[e]:N,...H}=U;if(Q?.[e]!==void 0||!$(H,Q??{})||X!==void 0&&!$(V,E)||X===void 0&&(Object.keys(U).length!==1||!$(Object.keys(x).sort(),["version","next_epic_id","last_scan","existing_epics_discovered","epics"].sort())||x.version!=="1.0.0"||x.next_epic_id!==1||!$(x.existing_epics_discovered,[]))||typeof x.last_scan!="string"||!Number.isFinite(Date.parse(x.last_scan)))throw new Error("planning-index-drift");const tt=l.map(R=>B("sha256").update(p(i(t.workspacePath,R))).digest("hex")),_=()=>l.every((R,W)=>{try{return y(t.workspacePath,R),B("sha256").update(p(i(t.workspacePath,R))).digest("hex")===tt[W]}catch{return!1}});return q(t,l,t.baseSha,s,_)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function pe(t,r,e,n,s,a){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(a))throw new Error("planning-research-binding-invalid");const o=".neocortex/state.json",d=".neocortex/planning/planning.json",m=`.neocortex/planning/epic-${e}`,u=`${m}/research.md`;if(y(t.sourceRoot,o),y(t.workspacePath,o),y(t.sourceRoot,d),y(t.workspacePath,d),y(t.sourceRoot,u),y(t.workspacePath,u),b(i(t.sourceRoot,o)).size>8*1024*1024||b(i(t.workspacePath,o)).size>8*1024*1024||b(i(t.sourceRoot,d)).size>128*1024||b(i(t.workspacePath,d)).size>128*1024)throw new Error("planning-research-source-size-invalid");const P=p(i(t.sourceRoot,o));if(B("sha256").update(P).digest("hex")!==a||!P.equals(p(i(t.workspacePath,o))))throw new Error("planning-research-state-drift");const c=JSON.parse(P.toString("utf8")),f=Ht(c,r,e);if(f.diagnosisReceiptId!==n||f.intakeRevision!==s)throw new Error("planning-research-predecessor-mismatch");const h=c.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[D,Y]of Object.entries({idea:`${m}/idea.json`,diagnosis:`${m}/diagnosis.md`,enrichment:`${m}/enriched-prompt.md`,index:d}))if(y(t.sourceRoot,Y),B("sha256").update(p(i(t.sourceRoot,Y))).digest("hex")!==h[D])throw new Error("planning-research-source-artifact-drift");try{throw b(i(t.sourceRoot,u)),new Error("planning-research-already-exists")}catch(D){if(D.code!=="ENOENT")throw D}const w=[u,d],v=M(F(t.workspacePath,!0));if(v.paths.length!==w.length||v.paths.some(D=>!w.includes(D)))throw new Error("planning-research-write-scope-invalid");const T=b(i(t.workspacePath,u));if(!T.isFile()||T.isSymbolicLink()||T.size<64||T.size>256*1024)throw new Error("planning-research-document-invalid");const A=p(i(t.workspacePath,u),"utf8"),j=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(A.replace(/\r\n/g,`
5
- `))?.[1],g=D=>{const Y=j?.split(`
6
- `).filter(E=>E.startsWith(`${D}:`))??[];return Y.length===1?Y[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!j||g("epic_id")!==e||g("status")!=="completed"||!I(g("step"),bt)||!A.slice(j.length+8).trim())throw new Error("planning-research-document-identity-invalid");const S=JSON.parse(p(i(t.sourceRoot,d),"utf8")),x=JSON.parse(p(i(t.workspacePath,d),"utf8"));if(!S||typeof S!="object"||Array.isArray(S)||!x||typeof x!="object"||Array.isArray(x))throw new Error("planning-research-index-invalid");const U=S,z=x,O=U.epics,G=z.epics,C=O?.[e];if(!O||Array.isArray(O)||!G||Array.isArray(G)||!C||Array.isArray(C)||C.id!==e||C.idea!==f.rawIntent||C.status!=="diagnosed"||!Array.isArray(C.steps_completed)||C.steps_completed.length!==1||!I(C.steps_completed[0],dt)||!$(C.output_files,{diagnosis:`${m}/diagnosis.md`})||typeof z.last_scan!="string"||!Number.isFinite(Date.parse(z.last_scan)))throw new Error("planning-research-index-predecessor-invalid");const L={...C,status:"researched",steps_completed:[...C.steps_completed,g("step")],output_files:{diagnosis:`${m}/diagnosis.md`,research:u}},V={...U,last_scan:z.last_scan,epics:{...O,[e]:L}};if(!$(z,V))throw new Error("planning-research-index-drift");const X=w.map(D=>B("sha256").update(p(i(t.workspacePath,D))).digest("hex")),Q=()=>w.every((D,Y)=>{try{return y(t.workspacePath,D),B("sha256").update(p(i(t.workspacePath,D))).digest("hex")===X[Y]}catch{return!1}});return q(t,w,t.baseSha,void 0,Q)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function ge(t,r,e,n,s,a,o){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||[n,s,a,o].some(E=>!/^[a-f0-9]{64}$/.test(E)))throw new Error("planning-generation-binding-invalid");const d=".neocortex/state.json",m=".neocortex/planning/planning.json",u=`.neocortex/planning/epic-${e}`,P=`docs/epics/epic-${e}.md`;for(const E of[d,m,`${u}/idea.json`,`${u}/diagnosis.md`,`${u}/enriched-prompt.md`,`${u}/research.md`]){y(t.sourceRoot,E),y(t.workspacePath,E);const N=p(i(t.sourceRoot,E));if(E!==m&&!N.equals(p(i(t.workspacePath,E)))||!N.equals(K(t.sourceRoot,["show",`HEAD:${E}`])))throw new Error("planning-generation-predecessor-uncommitted")}const c=p(i(t.sourceRoot,d));if(c.byteLength>8*1024*1024||B("sha256").update(c).digest("hex")!==o)throw new Error("planning-generation-state-drift");const f=JSON.parse(c.toString("utf8")),l=Jt(f,r,e);if(l.diagnosisReceiptId!==n||l.researchReceiptId!==s||l.intakeRevision!==a)throw new Error("planning-generation-predecessor-mismatch");const h=f.epics[e],w=h.createEpicPlanningPhysical.artifactDigests,v=h.createEpicPlanningResearchPhysical.artifactDigests,T={idea:`${u}/idea.json`,diagnosis:`${u}/diagnosis.md`,enrichment:`${u}/enriched-prompt.md`,research:`${u}/research.md`};for(const[E,N]of Object.entries(T)){const H=E==="research"?v.research:w[E];if(B("sha256").update(p(i(t.sourceRoot,N))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(B("sha256").update(p(i(t.sourceRoot,m))).digest("hex")!==v.index)throw new Error("planning-generation-index-drift");const A=M(F(t.workspacePath,!0)),j=new RegExp(`^docs/stories/${e}\\.([0-9]{2})\\.story\\.md$`),g=A.paths.filter(E=>j.test(E)).sort((E,N)=>Number(j.exec(E)[1])-Number(j.exec(N)[1]));if(g.length<1||g.length>24||g.some((E,N)=>j.exec(E)[1]!==String(N+1).padStart(2,"0"))||A.paths.length!==g.length+2||A.paths.some(E=>E!==P&&E!==m&&!j.test(E)))throw new Error("planning-generation-write-scope-invalid");const S=[P,m,...g];for(const E of[P,...g]){y(t.sourceRoot,E),y(t.workspacePath,E);try{throw b(i(t.sourceRoot,E)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const N=b(i(t.workspacePath,E));if(!N.isFile()||N.isSymbolicLink()||N.size<128||N.size>(E===P?512:128)*1024)throw new Error("planning-generation-document-invalid")}const x=(E,N)=>{const tt=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(E.replace(/\r\n/g,`
1
+ import{execFileSync as Nt,spawnSync as wt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as rt,lstatSync as x,readFileSync as g,realpathSync as ct,writeFileSync as mt}from"node:fs";import{isAbsolute as nt,join as a,relative as ht,sep as vt}from"node:path";import{isDeepStrictEqual as S}from"node:util";import{readPrivateYoloFrozenWriteSet as Dt,verifyPrivateYoloCandidateWriteSet as Ft,verifyPrivateYoloCleanBaseline as Ct}from"./clean-baseline.js";import{PRIVATE_EPIC_PENDING_SIDECAR as et}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Bt}from"../commands/architecture-answers.js";import{derivePactWriteSet as _t}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as zt,deriveUxWriteSet as Lt}from"./ux-write-set.js";import{validateUxCandidateSource as Ht}from"./ux-source-validation.js";import{validatePactTestSource as Jt}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Mt}from"../memory/project-memory-writer.js";import{privateRootMemoryEffect as yt,privateRootMemorySourceMatches as Gt,privateRootMemorySourceMatchReason as Yt}from"./root-memory-scope.js";import{inspectPactToolchain as qt,planPactToolchainManifest as Ut}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Vt,planningPendingSidecarDigest as bt}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Wt}from"./planning-research-checkpoint.js";import{confirmPropertyTestPlan as xt,renderPropertyTestConfiguration as Xt}from"./property-test-plan.js";import{validatePropertyTestTypeScriptSource as Kt}from"./property-test-source.js";const Z=16*1024*1024,dt=1024,ut="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",Zt="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",Rt="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",Qt="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function tt(t,r){return typeof t=="string"&&t.length<=128&&F("sha256").update(t).digest("hex")===r}function Et(){const t={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete t[r];return t}function Y(t,r){return Nt("git",[...r],{cwd:t,env:Et(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return Y(t,r).toString("utf8").trim()}function C(t,r=!1){return Y(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function ot(t){return!!t&&!nt(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function P(t,r){const e=r.split("/");let s=t;for(const n of e.slice(0,-1)){s=a(s,n);try{const i=x(s);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("path-boundary")}catch(i){if(i.code==="ENOENT")return;throw i}}try{const n=x(a(t,r));if(!n.isFile()||n.isSymbolicLink()||n.size>Z)throw new Error("path-boundary")}catch(n){if(n.code!=="ENOENT")throw n}}function At(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(n=>n[0]),e=(t.match(/arch:keep-start/g)??[]).length,s=(t.match(/arch:keep-end/g)??[]).length;if(e!==s||e!==r.length)throw new Error("architecture-keep-marker-invalid");return r}function M(t,r=!1,e=!1,s=[]){const n=[],i=[];for(const o of t.toString("utf8").split("\0").filter(Boolean)){if(o.length<4||o[2]!==" ")throw new Error("status-invalid");const f=o.slice(0,2),l=o.slice(3);if(!ot(l)||f!=="??"&&f!==" M"&&f!==" D"&&!(f===" T"&&s.includes(l))&&!(e&&f==="!!"&&l===et))throw new Error("status-invalid");n.push(l),f==="??"&&i.push(l)}if(!r&&n.length===0||n.length>dt||new Set(n).size!==n.length)throw new Error("status-invalid");return{paths:n.sort(),untracked:i.sort()}}function ft(t,r,e,s){const n=Y(r,["ls-tree","-z",e,"--",s]).toString("utf8");if(!n)try{return x(a(t,s)),!1}catch(o){return o.code==="ENOENT"}const i=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(n);if(!i||i[2]!==s||!["100644","100755"].includes(i[1]))return!1;try{const o=x(a(t,s));return!o.isFile()||o.isSymbolicLink()||o.size>Z||!!(o.mode&73)!=(i[1]==="100755")?!1:g(a(t,s)).equals(Y(r,["show",`${e}:${s}`]))}catch{return!1}}function ve(t,r,e,s){return ot(s)&&/^[a-f0-9]{40,64}$/.test(e)&&ft(t,r,e,s)}function st(t,r){try{const e=a(t,et),s=x(a(t,".neocortex")),n=x(e);return s.isDirectory()&&!s.isSymbolicLink()&&s.uid===process.getuid?.()&&(s.mode&18)===0&&n.isFile()&&!n.isSymbolicLink()&&n.uid===process.getuid?.()&&(n.mode&63)===0&&n.size>0&&n.size<=128*1024&&F("sha256").update(g(e)).digest("hex")===r}catch{return!1}}function lt(t,r,e,s,n,i){const o=new Set(s),f=i?yt(i).files.map(m=>m.path):[],l=M(C(t),!0,!!n,f),c=i?Yt(i,t,r,e):"matched";if(c!=="matched")throw new Error(`root-memory-${c}`);if(!l.paths.every(m=>o.has(m)||f.includes(m)||m===et&&!!n&&st(t,n)))throw new Error("source-unclaimed-delta");if(!s.every(m=>ft(t,r,e,m)))throw new Error("source-frozen-mismatch");return!n||st(t,n)}function kt(t,r){const e=wt("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",r],{cwd:t,env:Et(),encoding:"buffer",timeout:3e4,maxBuffer:Z});if(e.error||e.status!==1||!Buffer.isBuffer(e.stdout)||e.stdout.byteLength===0)throw new Error("patch-invalid");return e.stdout}function St(t,r,e){const s=wt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:Et(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(s.error||s.status!==0)throw new Error("apply-failed")}function pt(t,r,e){const s=a(t,e),n=a(r,e);try{const i=x(s),o=x(n);return i.isFile()&&o.isFile()&&(i.mode&73)===(o.mode&73)&&g(s).equals(g(n))}catch(i){if(i.code!=="ENOENT")return!1;try{return x(s),!1}catch(o){if(o.code!=="ENOENT")return!1}try{return x(n),!1}catch(o){return o.code==="ENOENT"}}}function _e(t,r,e,s){$t(t,r,e,!0,s)}function be(t,r,e,s){if($t(t,r,e,!1,s),Y(t.workspacePath,["diff","--cached","--name-only"]).byteLength!==0)throw new Error("private-execution-isolated-snapshot-unverified")}function $t(t,r,e,s,n){try{if(process.platform!=="linux"||t.schemaVersion!==1||!nt(t.sourceRoot)||!nt(t.workspacePath)||ct(t.sourceRoot)!==t.sourceRoot||ct(t.workspacePath)!==t.workspacePath||!x(t.workspacePath).isDirectory()||(x(t.workspacePath).mode&63)!==0||ht(t.sourceRoot,t.workspacePath)===""||ht(t.sourceRoot,t.workspacePath).split(vt)[0]!==".."||!/^[a-f0-9]{40,64}$/.test(t.baseSha)||!/^[a-f0-9]{40,64}$/.test(e)||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||rt(a(t.workspacePath,".git","objects","info","alternates"))||s&&C(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>dt||r.some(i=>!ot(i))||new Set(r).size!==r.length)throw new Error("boundary-invalid");if(Y(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!lt(t.sourceRoot,t.workspacePath,e,r,void 0,n))throw new Error("boundary-raced")}catch(i){const o=i instanceof Error&&(["boundary-invalid","boundary-raced","status-invalid","source-unclaimed-delta","source-frozen-mismatch"].includes(i.message)||/^root-memory-(scope-binding|snapshot-ancestry|snapshot-content|source-content|source-projection)(-unsafe)?$/.test(i.message))?i.message:"physical-inspection-failed";throw new Error("private-execution-isolated-snapshot-unverified",{cause:new Error(o)})}}function q(t,r,e,s,n,i=[],o){try{if(process.platform!=="linux"||t.schemaVersion!==1||!nt(t.sourceRoot)||!nt(t.workspacePath)||ct(t.sourceRoot)!==t.sourceRoot||ct(t.workspacePath)!==t.workspacePath||!x(t.workspacePath).isDirectory()||(x(t.workspacePath).mode&63)!==0||ht(t.sourceRoot,t.workspacePath)===""||ht(t.sourceRoot,t.workspacePath).split(vt)[0]!==".."||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||!/^[a-f0-9]{40,64}$/.test(e)||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||r.length===0||r.length>dt||r.some(p=>!ot(p))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(Y(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!lt(t.sourceRoot,t.workspacePath,e,r,s,o))throw new Error("source-snapshot-mismatch");const f=C(t.workspacePath,!0),l=M(f),c=new Set(r);if(l.paths.some(p=>!c.has(p)||i.includes(p)))throw new Error("path-unclaimed");if(n&&!n())throw new Error("candidate-raced");for(const p of l.paths)P(t.workspacePath,p),P(t.sourceRoot,p);const h=[Y(t.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...l.untracked.map(p=>kt(t.workspacePath,p))],u=Buffer.concat(h.map(p=>Buffer.concat([p,Buffer.from(`
2
+ `)])));if(u.byteLength===0||u.byteLength>Z||!C(t.workspacePath,!0).equals(f)||n&&!n()||!lt(t.sourceRoot,t.workspacePath,e,r,s,o))throw new Error("patch-raced");if(St(t.sourceRoot,u,!0),!C(t.workspacePath,!0).equals(f)||n&&!n()||!lt(t.sourceRoot,t.workspacePath,e,r,s,o))throw new Error("patch-raced");St(t.sourceRoot,u,!1);const v=o?yt(o).files.map(p=>p.path):[];if(M(C(t.sourceRoot),!0,!!s,v).paths.some(p=>!c.has(p)&&!v.includes(p)&&p!==et)||o&&!Gt(o,t.sourceRoot)||s&&!st(t.sourceRoot,s)||r.some(p=>!pt(t.workspacePath,t.sourceRoot,p))||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch)throw new Error("admission-raced");return Object.freeze({schemaVersion:1,outcome:"admitted-unverified",baseSha:t.baseSha,executionBranch:t.executionBranch,changedPaths:Object.freeze([...l.paths]),patchSha256:F("sha256").update(u).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function xe(t,r,e,s=t.baseSha,n=!1,i){try{const o=await Dt(t.sourceRoot,r,t.executionBranch,e);if(i){const m=yt(i);if(m.storyId!==r||m.childClaimRevision!==F("sha256").update([...o].sort().join("\0")).digest("hex"))throw new Error("root-memory-claim-mismatch")}const f=a(t.workspacePath,".neocortex","state.json"),l=x(f);if(!l.isFile()||l.isSymbolicLink()||l.size>Z)throw new Error("candidate-state-invalid");Ft(g(f,"utf8"),r,o);const c=q(t,o,s,void 0,void 0,n?[".neocortex/state.json"]:[],i);return await Ct(t.sourceRoot,r,t.executionBranch,e),c}catch{throw new Error("private-execution-isolated-admission-unverified")}}const It=new Set(["id","epic_id","title","description","status","steps_completed","last_step","branch_name","estimated_hours","complexity","priority","type","depends_on","created_at","updated_at","acceptance_criteria"]),te=new Set(["id","title","description","status","stories","total_stories","completed_stories","estimated_hours","complexity","priority","created_at","updated_at","last_updated","source","tags"]);function Ot(t){return["title","description","complexity","priority","type","created_at","updated_at","last_updated","source"].some(e=>t[e]!==void 0&&typeof t[e]!="string")||t.estimated_hours!==void 0&&(typeof t.estimated_hours!="number"||!Number.isFinite(t.estimated_hours)||t.estimated_hours<0)?!1:["depends_on","acceptance_criteria","tags"].every(e=>t[e]===void 0||Array.isArray(t[e])&&t[e].length<=256&&t[e].every(s=>typeof s=="string"))}function ee(t){return Object.keys(t).every(r=>It.has(r))&&t.status==="backlog"&&Ot(t)&&(t.steps_completed===void 0||Array.isArray(t.steps_completed)&&t.steps_completed.length===0)&&(t.last_step===void 0||t.last_step===null)&&(t.branch_name===void 0||t.branch_name===null)}function Re(t,r,e,s,n){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]*$/.test(e)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(n)||!st(t.sourceRoot,n))throw new Error("claim-invalid");const i=JSON.parse(g(a(t.sourceRoot,et),"utf8")),o=i&&typeof i=="object"&&!Array.isArray(i)?i.operations?.[s]:void 0;if(!o||typeof o!="object"||Array.isArray(o)||o.claimId!==r||o.epicId!==e)throw new Error("claim-sidecar-mismatch");const f=M(C(t.workspacePath,!0)),l=`docs/epics/epic-${e}.md`,c=".neocortex/state.json",m=new RegExp(`^docs/stories/${e}\\.[0-9]{2}\\.story\\.md$`),h=f.paths.filter(E=>m.test(E));if(!f.paths.includes(l)||!f.paths.includes(c)||h.length===0||h.length>99||f.paths.some(E=>E!==l&&E!==c&&E!=="NEOCORTEX.md"&&!m.test(E)))throw new Error("artifact-scope-invalid");const u=h.map(E=>E.slice(13,-9)).sort();if(u.some((E,T)=>E!==`${e}.${String(T+1).padStart(2,"0")}`))throw new Error("story-sequence-invalid");for(const E of[l,...h])try{throw x(a(t.sourceRoot,E)),new Error("artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}const v=(E,T)=>{P(t.workspacePath,E);const K=g(a(t.workspacePath,E),"utf8");return Buffer.byteLength(K)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(K)?.[1]?.split(/\r?\n/).find(at=>at.startsWith(`${T}:`))?.slice(T.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(v(l,"id")!==e||h.some((E,T)=>v(E,"id")!==u[T]||v(E,"epic_id")!==e))throw new Error("artifact-id-invalid");P(t.workspacePath,c);const d=JSON.parse(g(a(t.workspacePath,c),"utf8"));if(!d||typeof d!="object"||Array.isArray(d))throw new Error("state-invalid");const p=d,_=p.epics,j=p.stories,b=_?.[e],N=p.epic_id_ledger;if(p.schema_version!==1||!b||b.id!==e||b.status!=="memory-updated"||Object.keys(b).some(E=>!te.has(E))||!Ot(b)||b.completed_stories!==void 0&&b.completed_stories!==0||b.total_stories!==void 0&&b.total_stories!==u.length||!Array.isArray(b.stories)||b.stories.length!==u.length||b.stories.some((E,T)=>E!==u[T])||!j||u.some(E=>{const T=j[E];return!T||T.id!==E||T.epic_id!==e||!ee(T)})||!N||!Array.isArray(N.reserved_ids)||!N.reserved_ids.includes(e))throw new Error("state-claim-mismatch");P(t.sourceRoot,c);const y=JSON.parse(g(a(t.sourceRoot,c),"utf8")),A=y.epics,R=y.stories;if(!A||!R||A[e]!==void 0||u.some(E=>R[E]!==void 0))throw new Error("state-claim-conflict");const{[e]:U,...L}=_,$={...j};for(const E of u)delete $[E];const{epic_id_ledger:G,last_updated:B,...z}=y,{epic_id_ledger:W,last_updated:X,...Q}=p;if(!S(L,A)||!S($,R)||!S({...Q,epics:void 0,stories:void 0},{...z,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const O=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger.reserved_ids:void 0,{reserved_ids:V,...w}=N,D=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger:{schema_version:1},{reserved_ids:H,...k}=D;if(O!==void 0&&(!Array.isArray(O)||O.some(E=>typeof E!="string"||!/^P[1-9][0-9]*$/.test(E))||new Set(O).size!==O.length))throw new Error("ledger-drift");const I=[...Array.isArray(O)?O:[]];if(I.includes(e)||I.push(e),!S(N.reserved_ids,I)||!S(w,k))throw new Error("ledger-drift");return q(t,f.paths,t.baseSha,n)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function Ae(t,r,e,s,n,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(n)||typeof i!="string"||!i.trim()||i.length>16384||!st(t.sourceRoot,n))throw new Error("planning-claim-invalid");const o=JSON.parse(g(a(t.sourceRoot,et),"utf8")),f=o&&typeof o=="object"&&!Array.isArray(o)?o.operations?.[s]:void 0;if(!f||typeof f!="object"||Array.isArray(f)||f.claimId!==r||f.epicId!==e)throw new Error("planning-claim-sidecar-mismatch");const l=`.neocortex/planning/epic-${e}`,c=`${l}/idea.json`,m=`${l}/diagnosis.md`,h=`${l}/enriched-prompt.md`,u=".neocortex/planning/planning.json",v=[c,m,h,u],d=M(C(t.workspacePath,!0));if(d.paths.length!==v.length||d.paths.some(E=>!v.includes(E)))throw new Error("planning-artifact-scope-invalid");for(const E of[c,m,h]){P(t.workspacePath,E);try{throw x(a(t.sourceRoot,E)),new Error("planning-artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}}const p=(E,T)=>{const K=x(a(t.workspacePath,E));if(!K.isFile()||K.isSymbolicLink()||K.size<1||K.size>T)throw new Error("planning-artifact-invalid");return g(a(t.workspacePath,E),"utf8")},_=JSON.parse(p(c,32*1024));if(!_||typeof _!="object"||Array.isArray(_)||_.epic_id!==e||_.status!=="diagnosed"||typeof _.raw_input!="string"||_.raw_input!==i)throw new Error("planning-idea-invalid");const j=p(m,256*1024),b=p(h,256*1024),N=(E,T)=>{const K=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(E.replace(/\r\n/g,`
3
+ `))?.[1];if(!K)return!1;const Pt=K.split(`
4
+ `),it=gt=>{const at=Pt.filter(jt=>jt.startsWith(`${gt}:`));return at.length===1?at[0].slice(gt.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return it("epic_id")===e&&tt(it("step"),T)&&it("status")==="completed"};if(!N(j,ut)||!N(b,Zt))throw new Error("planning-document-identity-invalid");P(t.workspacePath,u),P(t.sourceRoot,u);const y=JSON.parse(p(u,128*1024)),A=rt(a(t.sourceRoot,u))?JSON.parse(g(a(t.sourceRoot,u),"utf8")):void 0;if(!y||typeof y!="object"||Array.isArray(y)||!("epics"in y)||!y.epics||typeof y.epics!="object"||Array.isArray(y.epics)||A!==void 0&&(!A||typeof A!="object"||Array.isArray(A)||!("epics"in A)||!A.epics||typeof A.epics!="object"||Array.isArray(A.epics)))throw new Error("planning-index-invalid");const R=y,U=R.epics,L=U[e],$=L,G=$?.output_files;if(!L||typeof L!="object"||Array.isArray(L)||$?.id!==e||$.status!=="diagnosed"||$.idea!==_.raw_input||!Array.isArray($.steps_completed)||$.steps_completed.length!==1||!tt($.steps_completed[0],ut)||typeof $.created_at!="string"||!Number.isFinite(Date.parse($.created_at))||$.completed_at!==null||!G||typeof G!="object"||Array.isArray(G)||!S(G,{diagnosis:`${l}/diagnosis.md`})||!S(Object.keys($).sort(),["id","idea","status","steps_completed","created_at","completed_at","output_files"].sort()))throw new Error("planning-index-epic-invalid");const{last_scan:B,epics:z,...W}=R,X=A,Q=X?.epics,{last_scan:O,epics:V,...w}=X??{},{[e]:D,...H}=U;if(Q?.[e]!==void 0||!S(H,Q??{})||X!==void 0&&!S(W,w)||X===void 0&&(Object.keys(U).length!==1||!S(Object.keys(R).sort(),["version","next_epic_id","last_scan","existing_epics_discovered","epics"].sort())||R.version!=="1.0.0"||R.next_epic_id!==1||!S(R.existing_epics_discovered,[]))||typeof R.last_scan!="string"||!Number.isFinite(Date.parse(R.last_scan)))throw new Error("planning-index-drift");const k=v.map(E=>F("sha256").update(g(a(t.workspacePath,E))).digest("hex")),I=()=>v.every((E,T)=>{try{return P(t.workspacePath,E),F("sha256").update(g(a(t.workspacePath,E))).digest("hex")===k[T]}catch{return!1}});return q(t,v,t.baseSha,n,I)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function Se(t,r,e,s,n,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(i))throw new Error("planning-research-binding-invalid");const o=".neocortex/state.json",f=".neocortex/planning/planning.json",l=`.neocortex/planning/epic-${e}`,c=`${l}/research.md`;if(P(t.sourceRoot,o),P(t.workspacePath,o),P(t.sourceRoot,f),P(t.workspacePath,f),P(t.sourceRoot,c),P(t.workspacePath,c),x(a(t.sourceRoot,o)).size>8*1024*1024||x(a(t.workspacePath,o)).size>8*1024*1024||x(a(t.sourceRoot,f)).size>128*1024||x(a(t.workspacePath,f)).size>128*1024)throw new Error("planning-research-source-size-invalid");const m=g(a(t.sourceRoot,o));if(F("sha256").update(m).digest("hex")!==i||!m.equals(g(a(t.workspacePath,o))))throw new Error("planning-research-state-drift");const h=JSON.parse(m.toString("utf8")),u=Vt(h,r,e);if(u.diagnosisReceiptId!==s||u.intakeRevision!==n)throw new Error("planning-research-predecessor-mismatch");const d=h.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[O,V]of Object.entries({idea:`${l}/idea.json`,diagnosis:`${l}/diagnosis.md`,enrichment:`${l}/enriched-prompt.md`,index:f}))if(P(t.sourceRoot,V),F("sha256").update(g(a(t.sourceRoot,V))).digest("hex")!==d[O])throw new Error("planning-research-source-artifact-drift");try{throw x(a(t.sourceRoot,c)),new Error("planning-research-already-exists")}catch(O){if(O.code!=="ENOENT")throw O}const p=[c,f],_=M(C(t.workspacePath,!0));if(_.paths.length!==p.length||_.paths.some(O=>!p.includes(O)))throw new Error("planning-research-write-scope-invalid");const j=x(a(t.workspacePath,c));if(!j.isFile()||j.isSymbolicLink()||j.size<64||j.size>256*1024)throw new Error("planning-research-document-invalid");const b=g(a(t.workspacePath,c),"utf8"),N=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(b.replace(/\r\n/g,`
5
+ `))?.[1],y=O=>{const V=N?.split(`
6
+ `).filter(w=>w.startsWith(`${O}:`))??[];return V.length===1?V[0].slice(O.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!N||y("epic_id")!==e||y("status")!=="completed"||!tt(y("step"),Rt)||!b.slice(N.length+8).trim())throw new Error("planning-research-document-identity-invalid");const A=JSON.parse(g(a(t.sourceRoot,f),"utf8")),R=JSON.parse(g(a(t.workspacePath,f),"utf8"));if(!A||typeof A!="object"||Array.isArray(A)||!R||typeof R!="object"||Array.isArray(R))throw new Error("planning-research-index-invalid");const U=A,L=R,$=U.epics,G=L.epics,B=$?.[e];if(!$||Array.isArray($)||!G||Array.isArray(G)||!B||Array.isArray(B)||B.id!==e||B.idea!==u.rawIntent||B.status!=="diagnosed"||!Array.isArray(B.steps_completed)||B.steps_completed.length!==1||!tt(B.steps_completed[0],ut)||!S(B.output_files,{diagnosis:`${l}/diagnosis.md`})||typeof L.last_scan!="string"||!Number.isFinite(Date.parse(L.last_scan)))throw new Error("planning-research-index-predecessor-invalid");const z={...B,status:"researched",steps_completed:[...B.steps_completed,y("step")],output_files:{diagnosis:`${l}/diagnosis.md`,research:c}},W={...U,last_scan:L.last_scan,epics:{...$,[e]:z}};if(!S(L,W))throw new Error("planning-research-index-drift");const X=p.map(O=>F("sha256").update(g(a(t.workspacePath,O))).digest("hex")),Q=()=>p.every((O,V)=>{try{return P(t.workspacePath,O),F("sha256").update(g(a(t.workspacePath,O))).digest("hex")===X[V]}catch{return!1}});return q(t,p,t.baseSha,bt(t.sourceRoot),Q)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function $e(t,r,e,s,n,i,o){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||[s,n,i,o].some(w=>!/^[a-f0-9]{64}$/.test(w)))throw new Error("planning-generation-binding-invalid");const f=".neocortex/state.json",l=".neocortex/planning/planning.json",c=`.neocortex/planning/epic-${e}`,m=`docs/epics/epic-${e}.md`;for(const w of[f,l,`${c}/idea.json`,`${c}/diagnosis.md`,`${c}/enriched-prompt.md`,`${c}/research.md`]){P(t.sourceRoot,w),P(t.workspacePath,w);const D=g(a(t.sourceRoot,w));if(w!==l&&!D.equals(g(a(t.workspacePath,w)))||!D.equals(Y(t.sourceRoot,["show",`HEAD:${w}`])))throw new Error("planning-generation-predecessor-uncommitted")}const h=g(a(t.sourceRoot,f));if(h.byteLength>8*1024*1024||F("sha256").update(h).digest("hex")!==o)throw new Error("planning-generation-state-drift");const u=JSON.parse(h.toString("utf8")),v=Wt(u,r,e);if(v.diagnosisReceiptId!==s||v.researchReceiptId!==n||v.intakeRevision!==i)throw new Error("planning-generation-predecessor-mismatch");const d=u.epics[e],p=d.createEpicPlanningPhysical.artifactDigests,_=d.createEpicPlanningResearchPhysical.artifactDigests,j={idea:`${c}/idea.json`,diagnosis:`${c}/diagnosis.md`,enrichment:`${c}/enriched-prompt.md`,research:`${c}/research.md`};for(const[w,D]of Object.entries(j)){const H=w==="research"?_.research:p[w];if(F("sha256").update(g(a(t.sourceRoot,D))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(F("sha256").update(g(a(t.sourceRoot,l))).digest("hex")!==_.index)throw new Error("planning-generation-index-drift");const b=M(C(t.workspacePath,!0)),N=new RegExp(`^docs/stories/${e}\\.([0-9]{2})\\.story\\.md$`),y=b.paths.filter(w=>N.test(w)).sort((w,D)=>Number(N.exec(w)[1])-Number(N.exec(D)[1]));if(y.length<1||y.length>24||y.some((w,D)=>N.exec(w)[1]!==String(D+1).padStart(2,"0"))||b.paths.length!==y.length+2||b.paths.some(w=>w!==m&&w!==l&&!N.test(w)))throw new Error("planning-generation-write-scope-invalid");const A=[m,l,...y];for(const w of[m,...y]){P(t.sourceRoot,w),P(t.workspacePath,w);try{throw x(a(t.sourceRoot,w)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const D=x(a(t.workspacePath,w));if(!D.isFile()||D.isSymbolicLink()||D.size<128||D.size>(w===m?512:128)*1024)throw new Error("planning-generation-document-invalid")}const R=(w,D)=>{const k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(w.replace(/\r\n/g,`
7
7
  `))?.[1]?.split(`
8
- `).filter(_=>_.startsWith(`${N}:`))??[];return tt.length===1?tt[0].slice(N.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},U=p(i(t.workspacePath,P),"utf8");if(x(U,"id")!==e||x(U,"stories_count")!==String(g.length)||!U.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[E,N]of g.entries()){const H=p(i(t.workspacePath,N),"utf8");if(x(H,"id")!==`${e}.${String(E+1).padStart(2,"0")}`||x(H,"epic")!==e||x(H,"status")!=="backlog"||!H.includes("## Acceptance Criteria")||!/\bGiven\b[\s\S]*\bWhen\b[\s\S]*\bThen\b/.test(H))throw new Error("planning-generation-story-invalid")}const z=JSON.parse(p(i(t.sourceRoot,m),"utf8")),O=JSON.parse(p(i(t.workspacePath,m),"utf8")),G=z.epics,C=O.epics,L=G?.[e],V=C?.[e];if(!G||!C||!L||!V||L.id!==e||L.status!=="researched"||!Array.isArray(L.steps_completed)||L.steps_completed.length!==2||!I(L.steps_completed[0],dt)||!I(L.steps_completed[1],bt)||!$(L.output_files,{diagnosis:`${u}/diagnosis.md`,research:`${u}/research.md`})||typeof O.last_scan!="string"||!Number.isFinite(Date.parse(O.last_scan))||typeof V.completed_at!="string"||!Number.isFinite(Date.parse(V.completed_at)))throw new Error("planning-generation-index-predecessor-invalid");const X=V.steps_completed?.[2];if(!I(X,Ut))throw new Error("planning-generation-index-transition-invalid");const Q={...z,last_scan:O.last_scan,epics:{...G,[e]:{...L,status:"generated",steps_completed:[...L.steps_completed,X],completed_at:V.completed_at,output_files:{...L.output_files,epic:P,stories:g}}}};if(!$(O,Q))throw new Error("planning-generation-index-transition-invalid");const D=S.map(E=>B("sha256").update(p(i(t.workspacePath,E))).digest("hex")),Y=()=>S.every((E,N)=>{try{return y(t.workspacePath,E),B("sha256").update(p(i(t.workspacePath,E))).digest("hex")===D[N]}catch{return!1}});return q(t,S,t.baseSha,void 0,Y)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function me(t,r){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(r))throw new Error("story-id-invalid");const e=".neocortex/state.json";y(t.sourceRoot,e),y(t.workspacePath,e);const n=JSON.parse(p(i(t.sourceRoot,e),"utf8")),s=JSON.parse(p(i(t.workspacePath,e),"utf8"));if(!n||typeof n!="object"||Array.isArray(n)||!s||typeof s!="object"||Array.isArray(s))throw new Error("state-invalid");const a=n,o=s,d=a.stories,m=o.stories,u=d?.[r],P=m?.[r],c=u?.files_to_modify;if(a.schema_version!==1||o.schema_version!==1||!d||!m||!u||!P||u.id!==r||P.id!==r||P.epic_id!==u.epic_id||!Array.isArray(c)||c.length===0||c.length>ht||c.some(x=>typeof x!="string"||!ut(x)||x.length>1024)||new Set(c).size!==c.length||!$(P.files_to_modify,c))throw new Error("write-set-invalid");const{[r]:f,...l}=d,{[r]:h,...w}=m,{stories:v,last_updated:T,...A}=a,{stories:j,last_updated:g,...S}=o;if(!$(w,l)||!$(S,A))throw new Error("state-unrelated-drift");return q(t,[...c].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function ye(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const s=new Date,a=`Q${Math.floor(s.getUTCMonth()/3)+1}-${s.getUTCFullYear()}`,o=M(F(t.workspacePath,!0)).paths,d=`tools/chaos/${a}-plan.md`,m=`.neocortex/chaos-history/${a}.md`,u=o.filter(h=>h.startsWith("tools/chaos/experiments/")),P=u.map(h=>/^tools\/chaos\/experiments\/(chaos-mesh|litmus|aws-fis)-(?:PodKill|NetworkChaos|IOChaos|StressChaos|TimeChaos|pod-kill|network-chaos|io-chaos|stress-chaos|time-chaos)-([a-z0-9]+(?:-[a-z0-9]+)*)\.yaml$/.exec(h));if(!o.includes(d)||!o.includes(m)||u.length<5||u.length>10||o.length!==u.length+2||P.some(h=>!h)||new Set(P.map(h=>h[1])).size!==1)throw new Error("chaos-write-set-invalid");for(const h of o)if(y(t.workspacePath,h),b(i(t.workspacePath,h)).size===0)throw new Error("chaos-empty-artifact");const c=p(i(t.workspacePath,m),"utf8");if(!c.includes(a)||!/\bPLANNED\b/.test(c))throw new Error("chaos-history-invalid");const l=K(t.workspacePath,["ls-tree","-z","HEAD","--",m]).length>0?K(t.workspacePath,["show",`HEAD:${m}`]).toString("utf8"):"";if(l&&!c.startsWith(l))throw new Error("chaos-history-not-append-only");return q(t,o,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}const n=r==="sync-openapi"&&e==="sync-openapi-contract-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:r==="tech-debt"&&e==="tech-debt-registry-v1"?[".neocortex/tech-debt-registry.json"]:void 0;if(!n)throw new Error("private-execution-project-step-admission-unverified");try{if(r==="tech-debt"){const s=".neocortex/tech-debt-registry.json";y(t.workspacePath,s);const a=JSON.parse(p(i(t.workspacePath,s),"utf8"));if(!a||typeof a!="object"||Array.isArray(a))throw new Error("registry-invalid");const o=a;if(o.schema_version!==2||o.version!==void 0&&o.version!==2||!Array.isArray(o.items))throw new Error("registry-invalid")}return q(t,n,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function Ee(t,r,e,n,s){const a=r==="arch-prd"&&e==="arch-prd-docs-v1"?["docs/architecture/prd.md","docs/architecture/product-experience.md"]:r==="arch-architecture"&&e==="arch-architecture-doc-v1"?["docs/architecture/architecture.md"]:r==="arch-fitness-functions"&&e==="arch-fitness-tools-v1"?["tools/architecture/dependency-cruiser.config.js","tools/architecture/archunit-test.ts","tools/architecture/.eslintrc.boundaries.js"]:r==="arch-api-contracts"&&e==="arch-api-contracts-docs-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:r==="arch-api-integrations"&&e==="arch-api-integrations-doc-v1"?["docs/architecture/api-integrations.md"]:r==="arch-database"&&e==="arch-database-doc-v1"?["docs/architecture/database-schema.md"]:r==="arch-security"&&e==="arch-security-doc-v1"?["docs/architecture/cyber-security.md"]:r==="arch-design-system"&&e==="arch-design-system-doc-v1"?["docs/architecture/atomic-design-system.md"]:r==="arch-performance"&&e==="arch-performance-doc-v1"?["docs/architecture/performance-strategy.md"]:r==="arch-testing"&&e==="arch-testing-doc-v1"?["docs/architecture/testing-strategy.md"]:r==="arch-infrastructure"&&e==="arch-infrastructure-doc-v1"?["docs/architecture/infrastructure-deploy.md"]:r==="arch-review"&&e==="arch-review-doc-v1"?["docs/architecture/review-consolidation.md"]:r==="update-memory"&&e==="arch-memory-canonical-v1"?["NEOCORTEX.md"]:null;if(!a||!/^P[1-9][0-9]{0,11}$/.test(n)||!/^[a-f0-9]{64}$/.test(s))throw new Error("private-execution-architecture-admission-unverified");try{y(t.workspacePath,".neocortex/state.json");const o=JSON.parse(p(i(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const d=o,u=d.archPlan?.execution,P=d.epics;if(!u||u.currentStageCommand!==r||u.targetEpicId!==n||u.graphRevision!==s||!P||!Object.hasOwn(P,n))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(u.continuationState!=="delegate"||u.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const c="NEOCORTEX.md";if(!M(F(t.workspacePath,!0)).paths.includes(c))throw new Error("memory-effect-missing");y(t.sourceRoot,c),y(t.workspacePath,c);const f=p(i(t.sourceRoot,c),"utf8"),l=p(i(t.workspacePath,c),"utf8"),h="<!-- NEOCORTEX-MEMORY-START -->",w="<!-- NEOCORTEX-MEMORY-END -->",v=g=>{if(g.split(h).length!==2||g.split(w).length!==2||g.indexOf(h)>=g.indexOf(w))throw new Error("memory-markers-invalid");const S=g.indexOf(h)+h.length,x=g.indexOf(w);return{before:g.slice(0,S),body:g.slice(S,x),after:g.slice(x)}},T=v(f),A=v(l);if(T.before!==A.before||T.after!==A.after||T.body===A.body||Buffer.byteLength(l,"utf8")>32768||l.split(`
9
- `).length>240)throw new Error("memory-managed-block-invalid");const j=new Set(T.body.split(`
10
- `));for(const g of A.body.split(`
11
- `))j.has(g)||Ct(g)}if(r==="arch-prd"){const c="docs/architecture/prd.md";if(!M(F(t.workspacePath,!0)).paths.includes(c))throw new Error("prd-effect-missing");if(y(t.workspacePath,c),b(i(t.workspacePath,c)).size===0)throw new Error("prd-empty")}if(r==="arch-api-contracts"||r==="arch-fitness-functions"||r==="arch-api-integrations"||r==="arch-database"||r==="arch-security"||r==="arch-design-system"||r==="arch-performance"||r==="arch-testing"||r==="arch-infrastructure"||r==="arch-review"){const c=M(F(t.workspacePath,!0)).paths;for(const f of a){if(!c.includes(f))throw new Error("architecture-required-effect-missing");if(y(t.workspacePath,f),b(i(t.workspacePath,f)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){y(t.sourceRoot,f);const l=rt(i(t.sourceRoot,f))?p(i(t.sourceRoot,f),"utf8"):"",h=p(i(t.workspacePath,f),"utf8"),w=xt(l),v=xt(h);if(!$(v,w))throw new Error("architecture-keep-marker-changed")}}}return q(t,a,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function Pe(t,r,e,n){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||n.schemaVersion!==1||n.targetEpicId!==r)throw new Error("binding-invalid");const s=Dt(t.sourceRoot,r),a=Nt(t.workspacePath,r);if(!$(s,n)||!$(a,n))throw new Error("write-set-invalid");y(t.workspacePath,".neocortex/state.json");const o=JSON.parse(p(i(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const d=o,u=d.archPlan?.execution,P=d.epics;if(!u||u.currentStageCommand!=="arch-ux-design"||u.continuationState!=="delegate"||u.targetEpicId!==r||u.graphRevision!==e||!P||!Object.hasOwn(P,r))throw new Error("stage-invalid");const c=M(F(t.workspacePath,!0)).paths;if(c.length!==n.pathCount||c.some(f=>!n.paths.includes(f)))throw new Error("agent-path-unclaimed");for(const f of n.paths){y(t.sourceRoot,f),y(t.workspacePath,f);const l=b(i(t.workspacePath,f));if(!l.isFile()||l.isSymbolicLink()||l.size<1)throw new Error("effect-empty");const h=new TextDecoder("utf-8",{fatal:!0}).decode(p(i(t.workspacePath,f)));if(!h.trim()||h.includes("\0"))throw new Error("effect-invalid")}return Bt(t.workspacePath,n),q(t,n.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function we(t,r,e,n,s,a){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||n.targetEpicId!==r||n.graphRevision!==e||s.schemaVersion!==1)throw new Error("binding-invalid");const o=jt(t.sourceRoot);if(!o||!$(o.receipt,n))throw new Error("answers-invalid");const d=vt(t.sourceRoot,o.answers.generateProvider),m=vt(t.workspacePath,o.answers.generateProvider);if(d.outcome!=="ready"||m.outcome!=="ready"||!$(d.writeSet,s)||!$(m.writeSet,s))throw new Error("write-set-invalid");const u=M(F(t.workspacePath,!0)).paths;if(u.some(h=>!s.paths.includes(h)))throw new Error("agent-path-unclaimed");let P=0,c=0;for(const h of s.paths){if(y(t.sourceRoot,h),rt(i(t.sourceRoot,h))||!u.includes(h))throw new Error("effect-missing-or-overwrite");y(t.workspacePath,h);const w=b(i(t.workspacePath,h));if(!w.isFile()||w.size<1)throw new Error("effect-empty");const v=new TextDecoder("utf-8",{fatal:!0}).decode(p(i(t.workspacePath,h))),T=s.interactions.find(j=>j.filePath===h);if(h!==s.providerPath&&!T)throw new Error("private-execution-pact-interaction-missing");const A=Ft(h,v,o.answers.brokerUrl,T,t.workspacePath);A.consumerBinding==="app-import-candidate"&&P++,A.consumerBinding==="mock-only-scaffold"&&c++}let f=s.paths;if(a){const h=zt(t.sourceRoot,o.answers.generateProvider),w=v=>B("sha256").update(v).digest("hex");if(a.schemaVersion!==1||a.outcome!=="candidate-unverified"||a.executionVerified!==!1||a.sourceManifestSha256!==w(h.sourceText)||a.sourceLockSha256!==(h.sourceLockText===null?null:w(h.sourceLockText))||a.manifestText!==h.candidateText||!mt(t.sourceRoot,t.workspacePath,t.baseSha,"package.json")||!mt(t.sourceRoot,t.workspacePath,t.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const v of["package.json","package-lock.json"]){y(t.sourceRoot,v),y(t.workspacePath,v);const T=v==="package.json"?h.sourceText:h.sourceLockText,A=rt(i(t.workspacePath,v))?p(i(t.workspacePath,v),"utf8"):null;if(T!==A)throw new Error("toolchain-clone-raced")}if(pt(i(t.workspacePath,"package.json"),a.manifestText),pt(i(t.workspacePath,"package-lock.json"),a.lockText),Lt(t.workspacePath,o.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");f=[...s.paths,"package.json","package-lock.json"]}const l=q(t,f,t.baseSha);return Object.freeze({...l,consumerBindingCandidateCount:P,consumerScaffoldCount:c})}catch{throw new Error("private-execution-pact-admission-unverified")}}function ve(t,r,e,n=new Date().toISOString()){try{const s=_t(t.sourceRoot,r);if(!$(s,e)||!lt(t.sourceRoot,t.workspacePath,e.prdPath)||e.aggregates.some(c=>!lt(t.sourceRoot,t.workspacePath,c.implementationFile))||e.writeSet.length===0)throw new Error("plan-drift");const a=M(F(t.workspacePath,!0)).paths;if(!$(a,e.writeSet))throw new Error("agent-path-unclaimed");const o=new Map;for(const c of e.aggregates){y(t.sourceRoot,c.testFile),y(t.workspacePath,c.testFile);const f=b(i(t.workspacePath,c.testFile));if(!f.isFile()||f.isSymbolicLink()||f.size<1||f.size>Z)throw new Error("test-invalid");const l=p(i(t.workspacePath,c.testFile)),h=new TextDecoder("utf-8",{fatal:!0}).decode(l),w=e.language==="typescript"?(h.match(/\b(?:it|test)\s*\(/g)??[]).length:(h.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!h.trim()||h.includes("\0")||w<c.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(h)||!h.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&Gt({source:h,testFile:c.testFile,implementationFile:c.implementationFile,invariantCount:c.invariantCount,numRuns:e.numRuns}),o.set(c.testFile,B("sha256").update(l).digest("hex"))}y(t.sourceRoot,e.prdPath),y(t.workspacePath,e.prdPath);const d=p(i(t.workspacePath,e.prdPath)),m=new TextDecoder("utf-8",{fatal:!0}).decode(d),u=Mt(m,e,n);pt(i(t.workspacePath,e.prdPath),u);const P=B("sha256").update(u).digest("hex");return q(t,[...e.writeSet,e.prdPath],t.baseSha,void 0,()=>{try{return!$(_t(t.sourceRoot,r),e)||e.aggregates.some(c=>!lt(t.sourceRoot,t.workspacePath,c.implementationFile))||B("sha256").update(p(i(t.workspacePath,e.prdPath))).digest("hex")!==P?!1:[...o].every(([c,f])=>B("sha256").update(p(i(t.workspacePath,c))).digest("hex")===f)}catch{return!1}})}catch{throw new Error("private-execution-property-admission-unverified")}}export{Ee as admitPrivateArchitectureStageWorkspace,fe as admitPrivateEpicClaimWorkspace,ge as admitPrivateGenerateEpicWorkspace,le as admitPrivateIdeaDiagnosisWorkspace,pe as admitPrivateIdeaResearchWorkspace,we as admitPrivatePactWorkspace,ye as admitPrivateProjectStepWorkspace,ve as admitPrivatePropertyTestWorkspace,me as admitPrivateStateBoundStepWorkspace,Pe as admitPrivateUxWorkspace,ue as admitPrivateYoloFrozenWorkspace,de as verifyPrivateYoloSnapshotBoundary};
8
+ `).filter(I=>I.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},U=g(a(t.workspacePath,m),"utf8");if(R(U,"id")!==e||R(U,"stories_count")!==String(y.length)||!U.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[w,D]of y.entries()){const H=g(a(t.workspacePath,D),"utf8"),k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(H.replace(/\r\n/g,`
9
+ `))?.[1]??"";if(R(H,"id")!==`${e}.${String(w+1).padStart(2,"0")}`||R(H,"epic_id")!==e||/^\s*epic\s*:/m.test(k)||R(H,"status")!=="backlog"||!H.includes("## Acceptance Criteria")||!/\bGiven\b[\s\S]*\bWhen\b[\s\S]*\bThen\b/.test(H))throw new Error("planning-generation-story-invalid")}const L=JSON.parse(g(a(t.sourceRoot,l),"utf8")),$=JSON.parse(g(a(t.workspacePath,l),"utf8")),G=L.epics,B=$.epics,z=G?.[e],W=B?.[e];if(!G||!B||!z||!W||z.id!==e||z.status!=="researched"||!Array.isArray(z.steps_completed)||z.steps_completed.length!==2||!tt(z.steps_completed[0],ut)||!tt(z.steps_completed[1],Rt)||!S(z.output_files,{diagnosis:`${c}/diagnosis.md`,research:`${c}/research.md`})||typeof $.last_scan!="string"||!Number.isFinite(Date.parse($.last_scan))||typeof W.completed_at!="string"||!Number.isFinite(Date.parse(W.completed_at)))throw new Error("planning-generation-index-predecessor-invalid");const X=W.steps_completed?.[2];if(!tt(X,Qt))throw new Error("planning-generation-index-transition-invalid");const Q={...L,last_scan:$.last_scan,epics:{...G,[e]:{...z,status:"generated",steps_completed:[...z.steps_completed,X],completed_at:W.completed_at,output_files:{...z.output_files,epic:m,stories:y}}}};if(!S($,Q))throw new Error("planning-generation-index-transition-invalid");const O=A.map(w=>F("sha256").update(g(a(t.workspacePath,w))).digest("hex")),V=()=>A.every((w,D)=>{try{return P(t.workspacePath,w),F("sha256").update(g(a(t.workspacePath,w))).digest("hex")===O[D]}catch{return!1}});return q(t,A,t.baseSha,bt(t.sourceRoot),V)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function Oe(t,r){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(r))throw new Error("story-id-invalid");const e=".neocortex/state.json";P(t.sourceRoot,e),P(t.workspacePath,e);const s=JSON.parse(g(a(t.sourceRoot,e),"utf8")),n=JSON.parse(g(a(t.workspacePath,e),"utf8"));if(!s||typeof s!="object"||Array.isArray(s)||!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const i=s,o=n,f=i.stories,l=o.stories,c=f?.[r],m=l?.[r],h=c?.files_to_modify;if(i.schema_version!==1||o.schema_version!==1||!f||!l||!c||!m||c.id!==r||m.id!==r||m.epic_id!==c.epic_id||!Array.isArray(h)||h.length===0||h.length>dt||h.some(R=>typeof R!="string"||!ot(R)||R.length>1024)||new Set(h).size!==h.length||!S(m.files_to_modify,h))throw new Error("write-set-invalid");const{[r]:u,...v}=f,{[r]:d,...p}=l,{stories:_,last_updated:j,...b}=i,{stories:N,last_updated:y,...A}=o;if(!S(p,v)||!S(A,b))throw new Error("state-unrelated-drift");return q(t,[...h].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function Te(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const n=new Date,i=`Q${Math.floor(n.getUTCMonth()/3)+1}-${n.getUTCFullYear()}`,o=M(C(t.workspacePath,!0)).paths,f=`tools/chaos/${i}-plan.md`,l=`.neocortex/chaos-history/${i}.md`,c=o.filter(d=>d.startsWith("tools/chaos/experiments/")),m=c.map(d=>/^tools\/chaos\/experiments\/(chaos-mesh|litmus|aws-fis)-(?:PodKill|NetworkChaos|IOChaos|StressChaos|TimeChaos|pod-kill|network-chaos|io-chaos|stress-chaos|time-chaos)-([a-z0-9]+(?:-[a-z0-9]+)*)\.yaml$/.exec(d));if(!o.includes(f)||!o.includes(l)||c.length<5||c.length>10||o.length!==c.length+2||m.some(d=>!d)||new Set(m.map(d=>d[1])).size!==1)throw new Error("chaos-write-set-invalid");for(const d of o)if(P(t.workspacePath,d),x(a(t.workspacePath,d)).size===0)throw new Error("chaos-empty-artifact");const h=g(a(t.workspacePath,l),"utf8");if(!h.includes(i)||!/\bPLANNED\b/.test(h))throw new Error("chaos-history-invalid");const v=Y(t.workspacePath,["ls-tree","-z","HEAD","--",l]).length>0?Y(t.workspacePath,["show",`HEAD:${l}`]).toString("utf8"):"";if(v&&!h.startsWith(v))throw new Error("chaos-history-not-append-only");return q(t,o,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}const s=r==="sync-openapi"&&e==="sync-openapi-contract-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:r==="tech-debt"&&e==="tech-debt-registry-v1"?[".neocortex/tech-debt-registry.json"]:void 0;if(!s)throw new Error("private-execution-project-step-admission-unverified");try{if(r==="tech-debt"){const n=".neocortex/tech-debt-registry.json";P(t.workspacePath,n);const i=JSON.parse(g(a(t.workspacePath,n),"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("registry-invalid");const o=i;if(o.schema_version!==2||o.version!==void 0&&o.version!==2||!Array.isArray(o.items))throw new Error("registry-invalid")}return q(t,s,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function Tt(t,r){const e=t==="arch-prd"&&r==="arch-prd-docs-v1"?["docs/architecture/prd.md","docs/architecture/product-experience.md"]:t==="arch-architecture"&&r==="arch-architecture-doc-v1"?["docs/architecture/architecture.md"]:t==="arch-fitness-functions"&&r==="arch-fitness-tools-v1"?["tools/architecture/dependency-cruiser.config.js","tools/architecture/archunit-test.ts","tools/architecture/.eslintrc.boundaries.js"]:t==="arch-api-contracts"&&r==="arch-api-contracts-docs-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:t==="arch-api-integrations"&&r==="arch-api-integrations-doc-v1"?["docs/architecture/api-integrations.md"]:t==="arch-database"&&r==="arch-database-doc-v1"?["docs/architecture/database-schema.md"]:t==="arch-security"&&r==="arch-security-doc-v1"?["docs/architecture/cyber-security.md"]:t==="arch-design-system"&&r==="arch-design-system-doc-v1"?["docs/architecture/atomic-design-system.md"]:t==="arch-performance"&&r==="arch-performance-doc-v1"?["docs/architecture/performance-strategy.md"]:t==="arch-testing"&&r==="arch-testing-doc-v1"?["docs/architecture/testing-strategy.md"]:t==="arch-infrastructure"&&r==="arch-infrastructure-doc-v1"?["docs/architecture/infrastructure-deploy.md"]:t==="arch-review"&&r==="arch-review-doc-v1"?["docs/architecture/review-consolidation.md"]:t==="update-memory"&&r==="arch-memory-canonical-v1"?["NEOCORTEX.md"]:null;return e===null?null:Object.freeze(e)}function je(t,r,e,s="all"){const n=Tt(r,e);if(!n)throw new Error("private-execution-architecture-admission-unverified");return`${t}
10
+
11
+ Private architecture handoff (local only):
12
+ ${JSON.stringify({allowedPaths:n})}
13
+ ${s==="non-ui"?`The server admitted a signed non-UI scope for this snapshot. Preserve the backend-only scope: design-system and UX phases are not applicable. Do not require or generate interface artifacts.
14
+ `:""}Write exactly the listed nonempty artifacts inside this isolated clone. Existing compliant listed artifacts may remain unchanged; all listed artifacts must exist after execution. Place any necessary scope notes inside those artifacts. Do not edit README, package files, other documents, state, Git, QA records or configuration outside the listed paths. Do not install dependencies, use network, deploy or continue to another stage. Preserve existing arch:keep blocks byte-for-byte. Do not add new arch:keep markers. For managed memory, preserve all bytes outside its existing managed block. Root independently reviews artifacts and owns continuation, Git and acceptance.
15
+ `}function Ne(t,r,e,s,n){const i=Tt(r,e);if(!i||!/^P[1-9][0-9]{0,11}$/.test(s)||!/^[a-f0-9]{64}$/.test(n))throw new Error("private-execution-architecture-admission-unverified");try{P(t.workspacePath,".neocortex/state.json");const o=JSON.parse(g(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const f=o,c=f.archPlan?.execution,m=f.epics;if(!c||c.currentStageCommand!==r||c.targetEpicId!==s||c.graphRevision!==n||!m||!Object.hasOwn(m,s))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(c.continuationState!=="delegate"||c.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const h="NEOCORTEX.md";if(!M(C(t.workspacePath,!0)).paths.includes(h))throw new Error("memory-effect-missing");P(t.sourceRoot,h),P(t.workspacePath,h);const u=g(a(t.sourceRoot,h),"utf8"),v=g(a(t.workspacePath,h),"utf8"),d="<!-- NEOCORTEX-MEMORY-START -->",p="<!-- NEOCORTEX-MEMORY-END -->",_=y=>{if(y.split(d).length!==2||y.split(p).length!==2||y.indexOf(d)>=y.indexOf(p))throw new Error("memory-markers-invalid");const A=y.indexOf(d)+d.length,R=y.indexOf(p);return{before:y.slice(0,A),body:y.slice(A,R),after:y.slice(R)}},j=_(u),b=_(v);if(j.before!==b.before||j.after!==b.after||j.body===b.body||Buffer.byteLength(v,"utf8")>32768||v.split(`
16
+ `).length>240)throw new Error("memory-managed-block-invalid");const N=new Set(j.body.split(`
17
+ `));for(const y of b.body.split(`
18
+ `))N.has(y)||Mt(y)}if(r==="arch-prd"){const h="docs/architecture/prd.md";if(!M(C(t.workspacePath,!0)).paths.includes(h))throw new Error("prd-effect-missing");if(P(t.workspacePath,h),x(a(t.workspacePath,h)).size===0)throw new Error("prd-empty")}if(r==="arch-api-contracts"||r==="arch-fitness-functions"||r==="arch-api-integrations"||r==="arch-database"||r==="arch-security"||r==="arch-design-system"||r==="arch-performance"||r==="arch-testing"||r==="arch-infrastructure"||r==="arch-review"){const h=M(C(t.workspacePath,!0)).paths;for(const u of i){if(!h.includes(u)&&Y(t.workspacePath,["cat-file","-t",`${t.baseSha}:${u}`]).toString("utf8").trim()!=="blob")throw new Error("architecture-required-effect-missing");if(P(t.workspacePath,u),x(a(t.workspacePath,u)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){P(t.sourceRoot,u);const v=rt(a(t.sourceRoot,u))?g(a(t.sourceRoot,u),"utf8"):"",d=g(a(t.workspacePath,u),"utf8"),p=At(v),_=At(d);if(!S(_,p))throw new Error("architecture-keep-marker-changed")}}}return q(t,i,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function De(t,r,e,s){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||s.schemaVersion!==1||s.targetEpicId!==r)throw new Error("binding-invalid");const n=Lt(t.sourceRoot,r),i=zt(t.workspacePath,r);if(!S(n,s)||!S(i,s))throw new Error("write-set-invalid");P(t.workspacePath,".neocortex/state.json");const o=JSON.parse(g(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const f=o,c=f.archPlan?.execution,m=f.epics;if(!c||c.currentStageCommand!=="arch-ux-design"||c.continuationState!=="delegate"||c.targetEpicId!==r||c.graphRevision!==e||!m||!Object.hasOwn(m,r))throw new Error("stage-invalid");const h=M(C(t.workspacePath,!0)).paths;if(h.length!==s.pathCount||h.some(u=>!s.paths.includes(u)))throw new Error("agent-path-unclaimed");for(const u of s.paths){P(t.sourceRoot,u),P(t.workspacePath,u);const v=x(a(t.workspacePath,u));if(!v.isFile()||v.isSymbolicLink()||v.size<1)throw new Error("effect-empty");const d=new TextDecoder("utf-8",{fatal:!0}).decode(g(a(t.workspacePath,u)));if(!d.trim()||d.includes("\0"))throw new Error("effect-invalid")}return Ht(t.workspacePath,s),q(t,s.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function Fe(t,r,e,s,n,i){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||s.targetEpicId!==r||s.graphRevision!==e||n.schemaVersion!==1)throw new Error("binding-invalid");const o=Bt(t.sourceRoot);if(!o||!S(o.receipt,s))throw new Error("answers-invalid");const f=_t(t.sourceRoot,o.answers.generateProvider),l=_t(t.workspacePath,o.answers.generateProvider);if(f.outcome!=="ready"||l.outcome!=="ready"||!S(f.writeSet,n)||!S(l.writeSet,n))throw new Error("write-set-invalid");const c=M(C(t.workspacePath,!0)).paths;if(c.some(d=>!n.paths.includes(d)))throw new Error("agent-path-unclaimed");let m=0,h=0;for(const d of n.paths){if(P(t.sourceRoot,d),rt(a(t.sourceRoot,d))||!c.includes(d))throw new Error("effect-missing-or-overwrite");P(t.workspacePath,d);const p=x(a(t.workspacePath,d));if(!p.isFile()||p.size<1)throw new Error("effect-empty");const _=new TextDecoder("utf-8",{fatal:!0}).decode(g(a(t.workspacePath,d))),j=n.interactions.find(N=>N.filePath===d);if(d!==n.providerPath&&!j)throw new Error("private-execution-pact-interaction-missing");const b=Jt(d,_,o.answers.brokerUrl,j,t.workspacePath,o.answers.matchersAggressive);b.consumerBinding==="app-import-candidate"&&m++,b.consumerBinding==="mock-only-scaffold"&&h++}let u=n.paths;if(i){const d=Ut(t.sourceRoot,o.answers.generateProvider),p=_=>F("sha256").update(_).digest("hex");if(i.schemaVersion!==1||i.outcome!=="candidate-unverified"||i.executionVerified!==!1||i.sourceManifestSha256!==p(d.sourceText)||i.sourceLockSha256!==(d.sourceLockText===null?null:p(d.sourceLockText))||i.manifestText!==d.candidateText||!ft(t.sourceRoot,t.workspacePath,t.baseSha,"package.json")||!ft(t.sourceRoot,t.workspacePath,t.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const _ of["package.json","package-lock.json"]){P(t.sourceRoot,_),P(t.workspacePath,_);const j=_==="package.json"?d.sourceText:d.sourceLockText,b=rt(a(t.workspacePath,_))?g(a(t.workspacePath,_),"utf8"):null;if(j!==b)throw new Error("toolchain-clone-raced")}if(mt(a(t.workspacePath,"package.json"),i.manifestText),mt(a(t.workspacePath,"package-lock.json"),i.lockText),qt(t.workspacePath,o.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");u=[...n.paths,"package.json","package-lock.json"]}const v=q(t,u,t.baseSha);return Object.freeze({...v,consumerBindingCandidateCount:m,consumerScaffoldCount:h})}catch{throw new Error("private-execution-pact-admission-unverified")}}function Ce(t,r,e,s=new Date().toISOString()){try{const n=xt(t.sourceRoot,r);if(!S(n,e)||!pt(t.sourceRoot,t.workspacePath,e.prdPath)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||e.writeSet.length===0)throw new Error("plan-drift");const i=M(C(t.workspacePath,!0)).paths;if(!S(i,e.writeSet))throw new Error("agent-path-unclaimed");const o=new Map;for(const h of e.aggregates){P(t.sourceRoot,h.testFile),P(t.workspacePath,h.testFile);const u=x(a(t.workspacePath,h.testFile));if(!u.isFile()||u.isSymbolicLink()||u.size<1||u.size>Z)throw new Error("test-invalid");const v=g(a(t.workspacePath,h.testFile)),d=new TextDecoder("utf-8",{fatal:!0}).decode(v),p=e.language==="typescript"?(d.match(/\b(?:it|test)\s*\(/g)??[]).length:(d.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!d.trim()||d.includes("\0")||p<h.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(d)||!d.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&Kt({source:d,testFile:h.testFile,implementationFile:h.implementationFile,invariantCount:h.invariantCount,numRuns:e.numRuns}),o.set(h.testFile,F("sha256").update(v).digest("hex"))}P(t.sourceRoot,e.prdPath),P(t.workspacePath,e.prdPath);const f=g(a(t.workspacePath,e.prdPath)),l=new TextDecoder("utf-8",{fatal:!0}).decode(f),c=Xt(l,e,s);mt(a(t.workspacePath,e.prdPath),c);const m=F("sha256").update(c).digest("hex");return q(t,[...e.writeSet,e.prdPath],t.baseSha,void 0,()=>{try{return!S(xt(t.sourceRoot,r),e)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||F("sha256").update(g(a(t.workspacePath,e.prdPath))).digest("hex")!==m?!1:[...o].every(([h,u])=>F("sha256").update(g(a(t.workspacePath,h))).digest("hex")===u)}catch{return!1}})}catch{throw new Error("private-execution-property-admission-unverified")}}export{Ne as admitPrivateArchitectureStageWorkspace,Re as admitPrivateEpicClaimWorkspace,$e as admitPrivateGenerateEpicWorkspace,Ae as admitPrivateIdeaDiagnosisWorkspace,Se as admitPrivateIdeaResearchWorkspace,Fe as admitPrivatePactWorkspace,Te as admitPrivateProjectStepWorkspace,Ce as admitPrivatePropertyTestWorkspace,Oe as admitPrivateStateBoundStepWorkspace,De as admitPrivateUxWorkspace,xe as admitPrivateYoloFrozenWorkspace,je as appendPrivateArchitectureHandoff,Tt as privateArchitectureStagePaths,ve as privateYoloSourceFileMatchesSnapshot,be as verifyPrivateYoloRejectedCandidateOrigin,_e as verifyPrivateYoloSnapshotBoundary};