@ornexus/neocortex 4.61.5 → 4.62.0

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 (279) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +1 -1
  5. package/package.json +5 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.d.ts +8 -1
  20. package/packages/client/dist/agent/update-description.js +2 -260
  21. package/packages/client/dist/cache/crypto-utils.js +1 -78
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  23. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  24. package/packages/client/dist/cache/index.js +1 -13
  25. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  26. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  27. package/packages/client/dist/checkpoint/index.js +1 -11
  28. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  29. package/packages/client/dist/cli.js +5 -364
  30. package/packages/client/dist/commands/activate.js +8 -394
  31. package/packages/client/dist/commands/architecture-answers.js +7 -274
  32. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  33. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  34. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  35. package/packages/client/dist/commands/cache-status.js +2 -112
  36. package/packages/client/dist/commands/config.js +1 -88
  37. package/packages/client/dist/commands/doctor.js +2 -635
  38. package/packages/client/dist/commands/invoke.d.ts +17 -0
  39. package/packages/client/dist/commands/invoke.js +148 -7822
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  41. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  42. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  44. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  45. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  46. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  47. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  49. package/packages/client/dist/commands/mutation-qa.js +1 -220
  50. package/packages/client/dist/commands/native-agent.js +2 -136
  51. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  52. package/packages/client/dist/commands/planning-generation.js +1 -53
  53. package/packages/client/dist/commands/planning-memory.js +1 -40
  54. package/packages/client/dist/commands/planning-research.js +1 -42
  55. package/packages/client/dist/commands/private-session.js +1 -75
  56. package/packages/client/dist/commands/property-qa.js +1 -139
  57. package/packages/client/dist/commands/qa-control.js +1 -16
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  60. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  61. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  62. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  68. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  69. package/packages/client/dist/commands/refactor-commit.js +13 -399
  70. package/packages/client/dist/commands/refactor-control.js +3 -142
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  72. package/packages/client/dist/commands/refactor-review.js +5 -283
  73. package/packages/client/dist/commands/refactor-root.js +7 -588
  74. package/packages/client/dist/commands/refresh-memory.js +3 -174
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  77. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  78. package/packages/client/dist/commands/story-worktree.js +5 -258
  79. package/packages/client/dist/config/host-auth-broker.js +1 -60
  80. package/packages/client/dist/config/host-auth-reference.js +1 -93
  81. package/packages/client/dist/config/profile-directory.js +1 -13
  82. package/packages/client/dist/config/resolver-selection.js +1 -278
  83. package/packages/client/dist/config/secure-config.js +12 -281
  84. package/packages/client/dist/config.js +2 -224
  85. package/packages/client/dist/constants.js +1 -25
  86. package/packages/client/dist/context/context-collector.js +2 -222
  87. package/packages/client/dist/context/context-sanitizer.js +1 -145
  88. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  89. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  90. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  91. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  92. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  93. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  94. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  95. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  96. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  97. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  98. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  99. package/packages/client/dist/continuity/outbox.js +1 -117
  100. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  101. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  102. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  103. package/packages/client/dist/errors/error-messages.js +2 -258
  104. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  105. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  106. package/packages/client/dist/evidence/collector.js +1 -347
  107. package/packages/client/dist/evidence/index.js +1 -1
  108. package/packages/client/dist/evidence/types.js +0 -2
  109. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  110. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  111. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  112. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  113. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +94 -9
  114. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -1592
  115. package/packages/client/dist/git/epic-operational-state.js +2 -672
  116. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  117. package/packages/client/dist/git/git-lifecycle-store.d.ts +88 -0
  118. package/packages/client/dist/git/git-lifecycle-store.js +9 -2529
  119. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  120. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  121. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  122. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  123. package/packages/client/dist/git/release-gate-env.d.ts +62 -0
  124. package/packages/client/dist/git/release-gate-env.js +1 -0
  125. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  126. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -186
  127. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  128. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  129. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  130. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  131. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  132. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  133. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  134. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  135. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  136. package/packages/client/dist/i18n/first-run.js +2 -60
  137. package/packages/client/dist/index.js +1 -50
  138. package/packages/client/dist/invocation/invoke-input.js +1 -24
  139. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  140. package/packages/client/dist/license/index.js +1 -5
  141. package/packages/client/dist/license/license-client.js +1 -337
  142. package/packages/client/dist/machine/fingerprint.js +2 -163
  143. package/packages/client/dist/machine/index.js +1 -5
  144. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  145. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  146. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  147. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  148. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  149. package/packages/client/dist/migrations/project-identity.js +7 -493
  150. package/packages/client/dist/migrations/state-json.js +4 -393
  151. package/packages/client/dist/policy/architecture-policy.js +2 -184
  152. package/packages/client/dist/policy/index.js +1 -7
  153. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  154. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  155. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  156. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  157. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  158. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  159. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  160. package/packages/client/dist/private-execution/delivery.js +13 -410
  161. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  162. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  163. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  164. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  165. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  166. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  167. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  168. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  169. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  170. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  171. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  172. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  173. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  174. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  175. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  176. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  177. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  178. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  179. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  180. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  181. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  182. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  183. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  184. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  185. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  186. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  187. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  188. package/packages/client/dist/private-execution/session-lease.js +1 -63
  189. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  190. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  191. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  192. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  193. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  194. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  195. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  196. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  197. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  198. package/packages/client/dist/resilience/index.js +1 -8
  199. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  200. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  201. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  202. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  203. package/packages/client/dist/runner/binary.js +1 -404
  204. package/packages/client/dist/runner/cli.js +17 -1571
  205. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  206. package/packages/client/dist/runner/headless/adapters.js +1 -49
  207. package/packages/client/dist/runner/headless/background-root.js +1 -85
  208. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  209. package/packages/client/dist/runner/headless/child-env.js +1 -0
  210. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  211. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  212. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  213. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  214. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
  215. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  216. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  217. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  218. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  219. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  220. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  221. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  222. package/packages/client/dist/runner/headless/resolver.js +1 -231
  223. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  224. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  225. package/packages/client/dist/runner/headless/types.js +2 -575
  226. package/packages/client/dist/runner/host-capacity.js +1 -59
  227. package/packages/client/dist/runner/local-console.js +13 -396
  228. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  229. package/packages/client/dist/runner/project-identity.js +1 -106
  230. package/packages/client/dist/runner/scheduler.js +7 -995
  231. package/packages/client/dist/runner-cli.js +2 -18
  232. package/packages/client/dist/state/invocation-shape.js +1 -13
  233. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  234. package/packages/client/dist/state/state-json-repair.js +3 -785
  235. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  236. package/packages/client/dist/telemetry/index.js +1 -5
  237. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  238. package/packages/client/dist/tier/index.js +1 -5
  239. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  240. package/packages/client/dist/types/index.js +1 -38
  241. package/packages/client/dist/version.js +1 -27
  242. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  243. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  244. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  245. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  246. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  247. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  248. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  249. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  250. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  251. package/packages/client/dist/yoloop/index.js +1 -8
  252. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  253. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
  254. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  255. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  256. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  257. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  258. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  259. package/packages/shared/dist/project-manifest-projection.js +199 -0
  260. package/packages/shared/dist/project-validation-commands.js +14 -6
  261. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  262. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  263. package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
  264. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  265. package/targets-stubs/antigravity/gemini.md +1 -1
  266. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  267. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  268. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  269. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  270. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  271. package/targets-stubs/claude-code/neocortex.md +5 -5
  272. package/targets-stubs/codex/AGENTS.md +1 -1
  273. package/targets-stubs/cursor/agent.md +2 -2
  274. package/targets-stubs/gemini-cli/agent.md +2 -2
  275. package/targets-stubs/lib/managed-config-merge.js +77 -1
  276. package/targets-stubs/lib/managed-profile.sh +7 -0
  277. package/targets-stubs/opencode/neocortex-root.md +1 -1
  278. package/targets-stubs/vscode/install-vscode.sh +21 -0
  279. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,725 +1,5 @@
1
- /** Durable, root-owned continuation boundary for one private YOLO story. */
2
- import { execFileSync, spawnSync } from 'node:child_process';
3
- import { createCipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';
4
- import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs';
5
- import { homedir } from 'node:os';
6
- import { basename, dirname, join, resolve } from 'node:path';
7
- import { isRootProjectMemoryEffect, rootProjectMemoryPaths } from './shared-root-memory-types.js';
8
- import { readPrivateRootMemoryScope, privateRootMemoryEffect } from './root-memory-scope.js';
9
- import { executeRootMemoryWriter, rootMemoryFileState, verifyRootMemoryWriterExecution } from './root-memory-writer.js';
10
- import { rootMemoryGitFileState, verifyRootMemoryEffectGitEvidence } from './root-memory-git-evidence.js';
11
- import { parsePrivateRootMemoryRequest } from './root-memory-request.js';
12
- import { rootMemoryOperationJournalName, readVerifiedPreparedRootMemory } from './root-memory-recovery.js';
13
- import { assertProjectMemoryPaths } from '../memory/project-memory-path-scope.js';
14
- import { isDeepStrictEqual } from 'node:util';
15
- import { acquireGitLifecyclePhysicalIntegrationLock, applyGitLifecycleRuntimeOverlay, assertGitLifecyclePrivateFile, ensureGitLifecyclePrivateChildDirectory, gitLifecycleRuntimeDirectory, mutateGitLifecycleRuntime, readGitLifecycleRuntimeSync, releaseGitLifecyclePhysicalIntegrationLock, } from '../git/git-lifecycle-store.js';
16
- import { anchoredAtomicWriteFile, anchoredDirectoryIdentity, anchoredExecuteGit } from '../git/secure-filesystem-boundary.js';
17
- import { privateYoloRootOnlySetupReady, readPrivateYoloFrozenWriteSet, readPrivateYoloFrozenWriteSetForTransition } from './clean-baseline.js';
18
- import { admitPrivateYoloFrozenWorkspace, verifyPrivateYoloSnapshotBoundary, verifyPrivateYoloRejectedCandidateOrigin, } from './isolated-admission.js';
19
- import { preparePrivateYoloIsolatedWorkspace } from './isolated-workspace.js';
20
- /** Root-owned C07. The child may propose notes; only this controller runs the writer. */
21
- export async function acceptPrivateYoloProjectMemoryRootReview(projectRoot, request, options = {}) {
22
- const parsed = parsePrivateRootMemoryRequest(request), { directive: d, review: review } = parsed;
23
- const root = resolve(projectRoot), storyId = d.storyId, epicId = storyId.split('.')[0];
24
- const hash = (value) => createHash('sha256').update(value).digest('hex');
25
- let stage = 'session';
26
- const fail = () => { throw new Error(`private-root-memory-acceptance-${stage}-unverified`); };
27
- try {
28
- return await withPhysicalLock(root, storyId, setupSessionId(root, storyId), async () => {
29
- const before = readGitLifecycleRuntimeSync(root, { required: true });
30
- const epic = before.epics[epicId], lease = epic?.branch_lease;
31
- const current = await readSession(root, storyId);
32
- if (!current || epic?.graph_revision !== d.graphRevision || lease?.ownerStoryId !== storyId
33
- || typeof lease.expiresAt !== 'string' || Date.parse(lease.expiresAt) <= Date.now()
34
- || current.workspace.executionBranch !== d.executionBranch)
35
- return fail();
36
- verifySessionBinding(current, root, storyId, d.graphRevision);
37
- const parent = await ensureGitLifecyclePrivateChildDirectory(await gitLifecycleRuntimeDirectory(root), 'private-execution');
38
- const operationName = rootMemoryOperationJournalName(current, parsed);
39
- const prepared = current.rootMemoryEffect === undefined && existsSync(join(parent, operationName));
40
- if (!prepared)
41
- await verifySession(current, root, storyId, d.graphRevision);
42
- const sourceIdentity = await anchoredDirectoryIdentity(root);
43
- stage = 'source-evidence';
44
- assertProjectMemoryPaths(root, ['.neocortex/state.json', `.neocortex/stories/${storyId}/validation-evidence.md`]);
45
- const stateBytes = readFileSync(join(root, '.neocortex/state.json'));
46
- if (hash(stateBytes) !== review.sourceStateSha256)
47
- return fail();
48
- const effective = applyGitLifecycleRuntimeOverlay(JSON.parse(stateBytes.toString('utf8')), before);
49
- const story = effective.stories?.[storyId];
50
- if (!story || story.checkpoint !== undefined || !Array.isArray(story.steps_completed))
51
- return fail();
52
- const completedSteps = [...story.steps_completed];
53
- const proposalPath = `.neocortex/stories/${storyId}/validation-evidence.md`;
54
- const proposalInfo = lstatSync(join(root, proposalPath));
55
- if (!proposalInfo.isFile() || proposalInfo.isSymbolicLink() || proposalInfo.nlink !== 1
56
- || proposalInfo.size < 128 || proposalInfo.size > 256 * 1024
57
- || hash(readFileSync(join(root, proposalPath))) !== review.proposalSha256)
58
- return fail();
59
- const qaPath = join(parent, `qa-review-${review.rootQaReceiptId}.json`);
60
- stage = 'qa-predecessor';
61
- await assertGitLifecyclePrivateFile(qaPath, parent);
62
- const qaBytes = readFileSync(qaPath);
63
- if (qaBytes.length > 16384 || hash(qaBytes) !== review.rootQaReceiptId)
64
- return fail();
65
- const qa = JSON.parse(qaBytes.toString('utf8'));
66
- if (qa.kind !== 'private-qa-root-review' || qa.storyId !== storyId || qa.sourceHeadSha !== current.workspace.baseSha
67
- || qa.precommitQaAccepted !== true || qa.independentStoryQaAccepted !== false || qa.terminalAccepted !== false)
68
- return fail();
69
- const notesSha256 = hash(JSON.stringify(review.notes));
70
- const receiptName = (effect) => `memory-review-${hash(JSON.stringify(effect))}.json`;
71
- const qaPredecessorReady = story.status === 'qa-gate-passed' && typeof story.last_step === 'string'
72
- && hash(story.last_step) === '8721319de90ade506bc9b72a908d8296856b34a11bc640629178bed3fe32e373'
73
- && completedSteps.at(-1) === story.last_step;
74
- const advanceMemoryPhase = async (target) => {
75
- await mutateGitLifecycleRuntime(root, document => {
76
- if (!isDeepStrictEqual(document.epics[epicId], epic) || !isDeepStrictEqual(document.stories[storyId], before.stories[storyId]))
77
- return fail();
78
- document.stories[storyId] = { ...document.stories[storyId], status: 'memory-updated', last_step: review.rawStepId,
79
- steps_completed: [...completedSteps, review.rawStepId] };
80
- }, { expectedRevision: before.revision, preCommit: async () => { await verifySession(target, root, storyId, d.graphRevision); } });
81
- };
82
- if (current.rootMemoryEffect) {
83
- stage = 'replay';
84
- if (current.rootMemoryEffect.sourceSnapshotSha !== review.snapshotSha
85
- || current.rootMemoryEffect.proposalSha256 !== notesSha256
86
- || current.rootMemoryEffect.rootQaReceiptId !== review.rootQaReceiptId)
87
- return fail();
88
- const path = join(parent, receiptName(current.rootMemoryEffect));
89
- await assertGitLifecyclePrivateFile(path, parent);
90
- const bytes = readFileSync(path), receipt = JSON.parse(bytes.toString('utf8'));
91
- if (receipt.proposalSha256 !== review.proposalSha256 || receipt.notesSha256 !== notesSha256
92
- || !isDeepStrictEqual(receipt.rootMemoryEffect, current.rootMemoryEffect))
93
- return fail();
94
- const alreadyAccepted = story.status === 'memory-updated' && story.last_step === review.rawStepId
95
- && completedSteps.at(-1) === review.rawStepId;
96
- if (!alreadyAccepted && !qaPredecessorReady)
97
- return fail();
98
- // The immutable producer receipt and physical pin already prove the
99
- // writer/source effect. Resume only its unaccepted CAS transition.
100
- if (!alreadyAccepted) {
101
- stage = 'phase-recovery';
102
- await advanceMemoryPhase(current);
103
- }
104
- return { schemaVersion: 1, outcome: 'project-memory-root-accepted', storyId, graphRevision: d.graphRevision,
105
- receiptId: hash(bytes), snapshotSha: current.snapshotSha, reused: true, sourceStateUnchanged: true,
106
- phaseRecovered: !alreadyAccepted,
107
- independentStoryQaAccepted: false, terminalAccepted: false, publicSafe: true };
108
- }
109
- if (current.snapshotSha !== review.snapshotSha || !qaPredecessorReady)
110
- return fail();
111
- const clone = current.workspace.workspacePath;
112
- git(clone, ['merge-base', '--is-ancestor', qa.snapshotSha, current.snapshotSha]);
113
- const metadata = [`.neocortex/stories/${storyId}/qa-gate-result.json`, proposalPath,
114
- `.neocortex/stories/${storyId}/tdd-evidence.md`, `docs/stories/${storyId}.rtm.md`];
115
- if (gitRaw(clone, ['diff', '--name-only', '-z', qa.snapshotSha, current.snapshotSha]).toString('utf8')
116
- .split('\0').filter(Boolean).some(path => !metadata.includes(path)))
117
- return fail();
118
- const frozen = await readPrivateYoloFrozenWriteSet(root, storyId, d.executionBranch, d.graphRevision);
119
- if (!gitExitOk(root, ['diff', '--cached', '--quiet']))
120
- return fail();
121
- const sourceStatus = gitRaw(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
122
- let effect, receipt, patch;
123
- let sourceAlreadyApplied = false;
124
- if (prepared) {
125
- stage = 'prepared-recovery';
126
- const recovered = await readVerifiedPreparedRootMemory({ projectRoot: root, parent, current, request: parsed, childPaths: frozen });
127
- effect = recovered.effect;
128
- receipt = recovered.receipt;
129
- patch = recovered.patch;
130
- sourceAlreadyApplied = recovered.sourceAlreadyApplied;
131
- }
132
- else {
133
- for (const path of rootProjectMemoryPaths()) {
134
- if (frozen.includes(path) || !isDeepStrictEqual(rootMemoryFileState(root, path), rootMemoryGitFileState(clone, current.snapshotSha, path)))
135
- return fail();
136
- }
137
- stage = 'writer';
138
- const backups = await ensureGitLifecyclePrivateChildDirectory(parent, 'memory-backups');
139
- const writerAuthority = executeRootMemoryWriter({ snapshotRoot: clone, expectedSnapshotSha: current.snapshotSha,
140
- notes: review.notes, backupDirectory: backups });
141
- const writer = verifyRootMemoryWriterExecution(writerAuthority);
142
- stage = 'writer-snapshot';
143
- if (writer.files.length) {
144
- git(clone, ['add', '-A', '--', ...writer.files.map(file => file.path)]);
145
- git(clone, ['-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false', '-c', 'user.name=Neocortex Private Session',
146
- '-c', 'user.email=private-session@neocortex.invalid', 'commit', '-q', '-m', `private root memory ${storyId} ${current.sequence + 1}`]);
147
- }
148
- const snapshotSha = git(clone, ['rev-parse', 'HEAD']);
149
- effect = { schemaVersion: 'RootProjectMemoryEffect/1', producer: 'root-project-memory',
150
- storyId, epicId, executionBranch: d.executionBranch, sourceHeadSha: current.workspace.baseSha,
151
- sourceSnapshotSha: current.snapshotSha, memorySnapshotSha: snapshotSha, graphRevision: d.graphRevision,
152
- childClaimRevision: hash([...frozen].sort().join('\0')), setupSessionId: current.setupSessionId,
153
- rootQaReceiptId: review.rootQaReceiptId, proposalSha256: writer.notesSha256,
154
- canonicalSha256: writer.verification.canonicalSha256, projectionSha256: writer.verification.projectionSha256,
155
- projectionFileCount: writer.verification.fileCount, files: writer.files, recordedAt: review.reviewedAt, publicSafe: true };
156
- stage = 'git-evidence';
157
- verifyRootMemoryEffectGitEvidence(clone, effect, { storyId, graphRevision: d.graphRevision,
158
- childClaimRevision: effect.childClaimRevision, setupSessionId: current.setupSessionId,
159
- sourceHeadSha: current.workspace.baseSha, executionBranch: d.executionBranch });
160
- patch = gitRaw(clone, ['diff', '--binary', '--full-index', current.snapshotSha, snapshotSha]);
161
- receipt = { schemaVersion: 1, kind: 'private-project-memory-root-review', storyId, graphRevision: d.graphRevision,
162
- sourceHeadSha: current.workspace.baseSha, snapshotSha, proposalSha256: review.proposalSha256, notesSha256,
163
- sourceStateSha256: review.sourceStateSha256, checks: review.checks, reviewedAt: review.reviewedAt,
164
- rootMemoryEffect: effect, independentStoryQaAccepted: false, terminalAccepted: false };
165
- // Retain a prepared journal before source writes. A partial operation fails
166
- // closed with its private clone and journal intact, never an invented pin.
167
- stage = 'prepared-journal';
168
- await anchoredAtomicWriteFile(parent, operationName, JSON.stringify({ schemaVersion: 1, kind: 'prepared-root-memory-effect', previousSession: current, receipt,
169
- patchSha256: hash(patch) }) + '\n');
170
- await options.fault?.('after-prepared-journal');
171
- }
172
- const bytes = JSON.stringify(receipt) + '\n', snapshotSha = effect.memorySnapshotSha;
173
- stage = 'source-admission';
174
- if (!gitRaw(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']).equals(sourceStatus)
175
- || git(root, ['rev-parse', 'HEAD']) !== current.workspace.baseSha
176
- || git(root, ['symbolic-ref', '--short', 'HEAD']) !== d.executionBranch)
177
- return fail();
178
- if (!sourceAlreadyApplied)
179
- for (const file of effect.files)
180
- if (!isDeepStrictEqual(rootMemoryFileState(root, file.path), file.before))
181
- return fail();
182
- // The existing anchored helper sets umask 077 in its child only. Git
183
- // otherwise creates group-writable memory files on hosts with umask 002.
184
- const apply = (check) => anchoredExecuteGit(dirname(root), basename(root), sourceIdentity, ['apply', ...(check ? ['--check'] : []), '--binary', '-'], patch);
185
- if (patch.length && !sourceAlreadyApplied) {
186
- await apply(true);
187
- await apply(false);
188
- }
189
- await options.fault?.('after-source-admission');
190
- if (!readFileSync(join(root, '.neocortex/state.json')).equals(stateBytes))
191
- return fail();
192
- const receiptPath = join(parent, receiptName(effect));
193
- if (existsSync(receiptPath)) {
194
- await assertGitLifecyclePrivateFile(receiptPath, parent);
195
- if (readFileSync(receiptPath, 'utf8') !== bytes)
196
- return fail();
197
- }
198
- else
199
- await anchoredAtomicWriteFile(parent, receiptName(effect), bytes);
200
- const next = Object.freeze({ ...current, snapshotSha,
201
- sequence: current.sequence + (effect.files.length ? 1 : 0), lastPatchSha256: effect.files.length ? hash(patch) : current.lastPatchSha256,
202
- rootMemoryEffect: effect });
203
- stage = 'session-pin';
204
- await options.fault?.('before-session-pin');
205
- await writeSession(root, next);
206
- await verifySession(next, root, storyId, d.graphRevision);
207
- stage = 'phase-transition';
208
- await advanceMemoryPhase(next);
209
- return { schemaVersion: 1, outcome: 'project-memory-root-accepted', storyId, graphRevision: d.graphRevision,
210
- receiptId: hash(bytes), snapshotSha, reused: prepared, sourceStateUnchanged: true,
211
- preparedRecovered: prepared, sourceWriteReused: sourceAlreadyApplied,
212
- independentStoryQaAccepted: false, terminalAccepted: false, publicSafe: true };
213
- });
214
- }
215
- catch (error) {
216
- const reason = error instanceof Error && /^(private-root-memory|private-execution-isolated)-[a-z0-9-]+$/.test(error.message)
217
- ? error.message : undefined;
218
- if (reason)
219
- throw new Error(`private-root-memory-acceptance-${stage}-unverified`, { cause: error });
220
- return fail();
221
- }
222
- }
223
- function git(root, args) {
224
- const env = { ...process.env };
225
- for (const key of [
226
- 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
227
- 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_COMMON_DIR', 'GIT_NAMESPACE', 'GIT_CEILING_DIRECTORIES',
228
- ])
229
- delete env[key];
230
- return execFileSync('git', [...args], {
231
- cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
232
- timeout: 30_000, maxBuffer: 16 * 1024 * 1024,
233
- }).trim();
234
- }
235
- function gitRaw(root, args) {
236
- const env = { ...process.env };
237
- for (const key of [
238
- 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
239
- 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_COMMON_DIR', 'GIT_NAMESPACE', 'GIT_CEILING_DIRECTORIES',
240
- ])
241
- delete env[key];
242
- return execFileSync('git', [...args], {
243
- cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'],
244
- timeout: 30_000, maxBuffer: 16 * 1024 * 1024,
245
- });
246
- }
247
- function gitExitOk(root, args) {
248
- const env = { ...process.env };
249
- for (const key of [
250
- 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
251
- 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_COMMON_DIR', 'GIT_NAMESPACE', 'GIT_CEILING_DIRECTORIES',
252
- ])
253
- delete env[key];
254
- const result = spawnSync('git', [...args], {
255
- cwd: root, env, stdio: 'ignore', timeout: 30_000,
256
- });
257
- if (result.error || result.signal)
258
- throw new Error('git-unverified');
259
- return result.status === 0;
260
- }
261
- async function location(root, storyId) {
262
- const runtime = await gitLifecycleRuntimeDirectory(root);
263
- const parent = await ensureGitLifecyclePrivateChildDirectory(runtime, 'private-execution');
264
- const name = `session-${createHash('sha256').update(storyId).digest('hex')}.json`;
265
- return { parent, name, path: join(parent, name) };
266
- }
267
- function setupSessionId(root, storyId) {
268
- const epicId = storyId.split('.')[0];
269
- const runtime = readGitLifecycleRuntimeSync(root, { required: true });
270
- const value = runtime.epics[epicId]?.branch_lease;
271
- const lease = value && typeof value === 'object' && !Array.isArray(value)
272
- ? value : undefined;
273
- const sessionId = lease?.sessionId;
274
- if (lease?.ownerStoryId !== storyId || typeof sessionId !== 'string'
275
- || !/^setup-[a-f0-9]{64}$/.test(sessionId)
276
- || sessionId !== lease.idempotencyKey) {
277
- throw new Error('session-lease-invalid');
278
- }
279
- return sessionId;
280
- }
281
- function rootOnlySetupReady(root, storyId) {
282
- const story = readGitLifecycleRuntimeSync(root, { required: true }).stories[storyId];
283
- return privateYoloRootOnlySetupReady(story);
284
- }
285
- function parseSession(raw) {
286
- const item = JSON.parse(raw);
287
- if (!item || typeof item !== 'object' || Array.isArray(item))
288
- throw new Error('session-invalid');
289
- const record = item;
290
- const workspace = record.workspace;
291
- if (Object.keys(record).sort().join(',') !== [
292
- 'schemaVersion', 'kind', 'storyId', 'initialGraphRevision', 'graphRevision', 'graphHistory', 'setupSessionId',
293
- 'workspace', 'snapshotSha', 'sequence', 'lastPatchSha256', ...(record.rootMemoryEffect === undefined ? [] : ['rootMemoryEffect']),
294
- ].sort().join(',') || record.schemaVersion !== 1 || record.kind !== 'private-yolo-isolated-session'
295
- || typeof record.storyId !== 'string' || !/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(record.storyId)
296
- || typeof record.initialGraphRevision !== 'string' || !/^[a-f0-9]{64}$/.test(record.initialGraphRevision)
297
- || typeof record.graphRevision !== 'string' || !/^[a-f0-9]{64}$/.test(record.graphRevision)
298
- || !Array.isArray(record.graphHistory) || record.graphHistory.length < 1 || record.graphHistory.length > 65
299
- || record.graphHistory.some((revision) => typeof revision !== 'string' || !/^[a-f0-9]{64}$/.test(revision))
300
- || new Set(record.graphHistory).size !== record.graphHistory.length
301
- || record.graphHistory[0] !== record.initialGraphRevision
302
- || record.graphHistory[record.graphHistory.length - 1] !== record.graphRevision
303
- || typeof record.setupSessionId !== 'string' || !/^setup-[a-f0-9]{64}$/.test(record.setupSessionId)
304
- || typeof record.snapshotSha !== 'string' || !/^[a-f0-9]{40,64}$/.test(record.snapshotSha)
305
- || !Number.isSafeInteger(record.sequence) || Number(record.sequence) < 0 || Number(record.sequence) > 64
306
- || Number(record.sequence) === 0 && record.initialGraphRevision !== record.graphRevision
307
- && record.graphHistory.length !== 2
308
- || Number(record.sequence) === 0 && record.lastPatchSha256 !== null
309
- || Number(record.sequence) > 0 && record.lastPatchSha256 === null
310
- || record.lastPatchSha256 !== null && (typeof record.lastPatchSha256 !== 'string'
311
- || !/^[a-f0-9]{64}$/.test(record.lastPatchSha256))
312
- || record.rootMemoryEffect !== undefined && !isRootProjectMemoryEffect(record.rootMemoryEffect)
313
- || !workspace || typeof workspace !== 'object' || Array.isArray(workspace))
314
- throw new Error('session-invalid');
315
- const candidate = workspace;
316
- if (Object.keys(candidate).sort().join(',') !== [
317
- 'schemaVersion', 'sourceRoot', 'workspacePath', 'baseSha', 'executionBranch',
318
- ].sort().join(',') || candidate.schemaVersion !== 1
319
- || typeof candidate.sourceRoot !== 'string' || typeof candidate.workspacePath !== 'string'
320
- || typeof candidate.baseSha !== 'string' || !/^[a-f0-9]{40,64}$/.test(candidate.baseSha)
321
- || typeof candidate.executionBranch !== 'string' || !candidate.executionBranch) {
322
- throw new Error('session-invalid');
323
- }
324
- return record;
325
- }
326
- async function readSession(root, storyId) {
327
- const target = await location(root, storyId);
328
- if (!existsSync(target.path))
329
- return undefined;
330
- await assertGitLifecyclePrivateFile(target.path, target.parent);
331
- return parseSession(readFileSync(target.path, 'utf8'));
332
- }
333
- async function writeSession(root, record) {
334
- const target = await location(root, record.storyId);
335
- await anchoredAtomicWriteFile(target.parent, target.name, `${JSON.stringify(record)}\n`);
336
- }
337
- async function withPhysicalLock(root, storyId, sessionId, work) {
338
- const lock = await acquireGitLifecyclePhysicalIntegrationLock(root, {
339
- kind: 'direct', storyId, sessionId, idempotencyKey: sessionId,
340
- expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), persistent: false,
341
- });
342
- if (!lock.ok)
343
- throw new Error('private-execution-isolated-session-backpressure');
344
- try {
345
- return await work();
346
- }
347
- finally {
348
- if (!(await releaseGitLifecyclePhysicalIntegrationLock(lock.path, lock.owner))) {
349
- throw new Error('private-execution-isolated-session-lock-unverified');
350
- }
351
- }
352
- }
353
- async function verifySession(record, root, storyId, graphRevision) {
354
- verifySessionBinding(record, root, storyId, graphRevision);
355
- const frozen = await readPrivateYoloFrozenWriteSet(root, storyId, record.workspace.executionBranch, graphRevision);
356
- const scope = await sessionMemoryScope(record, frozen);
357
- verifyPrivateYoloSnapshotBoundary(record.workspace, frozen, record.snapshotSha, scope);
358
- return scope;
359
- }
360
- async function sessionMemoryScope(record, frozen) {
361
- // Ordinary sessions retain the original boundary. Extra scope can only be
362
- // loaded back from the actual private pin, never supplied as a JSON argument.
363
- if (record.rootMemoryEffect === undefined)
364
- return undefined;
365
- const scope = await readPrivateRootMemoryScope({ projectRoot: record.workspace.sourceRoot,
366
- storyId: record.storyId, snapshotRoot: record.workspace.workspacePath, snapshotSha: record.snapshotSha,
367
- sourceHeadSha: record.workspace.baseSha, executionBranch: record.workspace.executionBranch,
368
- graphRevision: record.graphRevision, setupSessionId: record.setupSessionId, childPaths: frozen });
369
- if (!scope || JSON.stringify(privateRootMemoryEffect(scope)) !== JSON.stringify(record.rootMemoryEffect)) {
370
- throw new Error('private-root-memory-scope-unverified');
371
- }
372
- return scope;
373
- }
374
- function verifySessionBinding(record, root, storyId, graphRevision) {
375
- if (record.storyId !== storyId || record.graphRevision !== graphRevision
376
- || record.workspace.sourceRoot !== root
377
- || record.setupSessionId !== setupSessionId(root, storyId)
378
- || record.sequence === 0 && record.snapshotSha !== record.workspace.baseSha
379
- || record.sequence === 0 && record.graphHistory.length > 1 && !rootOnlySetupReady(root, storyId)
380
- || record.sequence > 0 && record.snapshotSha === record.workspace.baseSha) {
381
- throw new Error('session-binding-invalid');
382
- }
383
- }
384
- /** Reserve one clone for the exact C01 session, without launching an agent. */
385
- export async function beginPrivateYoloIsolatedSession(workspace, storyId, graphRevision) {
386
- const root = resolve(workspace.sourceRoot);
387
- try {
388
- const sessionId = setupSessionId(root, storyId);
389
- return await withPhysicalLock(root, storyId, sessionId, async () => {
390
- const existing = await readSession(root, storyId);
391
- if (existing) {
392
- await verifySession(existing, root, storyId, graphRevision);
393
- if (existing.workspace.workspacePath !== workspace.workspacePath)
394
- throw new Error('session-replacement-denied');
395
- return existing;
396
- }
397
- const frozen = await readPrivateYoloFrozenWriteSet(root, storyId, workspace.executionBranch, graphRevision);
398
- verifyPrivateYoloSnapshotBoundary(workspace, frozen, workspace.baseSha);
399
- const record = Object.freeze({
400
- schemaVersion: 1, kind: 'private-yolo-isolated-session', storyId,
401
- initialGraphRevision: graphRevision, graphRevision, graphHistory: [graphRevision],
402
- setupSessionId: sessionId, workspace, snapshotSha: workspace.baseSha,
403
- sequence: 0, lastPatchSha256: null,
404
- });
405
- await writeSession(root, record);
406
- return record;
407
- });
408
- }
409
- catch {
410
- throw new Error('private-execution-isolated-session-unverified');
411
- }
412
- }
413
- async function reconcileSessionGraph(record, root, storyId, graphRevision) {
414
- if (record.graphRevision === graphRevision) {
415
- await verifySession(record, root, storyId, graphRevision);
416
- return record;
417
- }
418
- if (record.storyId !== storyId || record.workspace.sourceRoot !== root
419
- || record.setupSessionId !== setupSessionId(root, storyId)
420
- || record.sequence === 0 && (record.graphHistory.length !== 1
421
- || record.lastPatchSha256 !== null || !rootOnlySetupReady(root, storyId))
422
- || record.sequence > 0 && record.lastPatchSha256 === null
423
- || record.graphHistory.includes(graphRevision) || record.graphHistory.length >= 65) {
424
- throw new Error('session-graph-transition-invalid');
425
- }
426
- const frozen = await readPrivateYoloFrozenWriteSetForTransition(root, storyId, record.workspace.executionBranch, record.initialGraphRevision, graphRevision);
427
- verifyPrivateYoloSnapshotBoundary(record.workspace, frozen, record.snapshotSha, await sessionMemoryScope(record, frozen));
428
- const next = Object.freeze({ ...record, graphRevision,
429
- graphHistory: Object.freeze([...record.graphHistory, graphRevision]) });
430
- await writeSession(root, next);
431
- await verifySession(next, root, storyId, graphRevision);
432
- return next;
433
- }
434
- /** Require a previously admitted patch before accepting a new server graph. */
435
- export async function reconcilePrivateYoloIsolatedSession(projectRoot, storyId, graphRevision) {
436
- const root = resolve(projectRoot);
437
- try {
438
- const sessionId = setupSessionId(root, storyId);
439
- return await withPhysicalLock(root, storyId, sessionId, async () => {
440
- const existing = await readSession(root, storyId);
441
- if (!existing)
442
- throw new Error('session-missing');
443
- return reconcileSessionGraph(existing, root, storyId, graphRevision);
444
- });
445
- }
446
- catch {
447
- throw new Error('private-execution-isolated-session-unverified');
448
- }
449
- }
450
- /** Reuse the pinned clone, or create it once after the physical C01 setup. */
451
- export async function ensurePrivateYoloIsolatedSession(projectRoot, storyId, graphRevision, workspaceParent) {
452
- const root = resolve(projectRoot);
453
- try {
454
- const sessionId = setupSessionId(root, storyId);
455
- return await withPhysicalLock(root, storyId, sessionId, async () => {
456
- const existing = await readSession(root, storyId);
457
- if (existing) {
458
- return reconcileSessionGraph(existing, root, storyId, graphRevision);
459
- }
460
- const parent = workspaceParent ?? join(homedir(), '.local', 'share', 'neocortex', 'private-yolo-workspaces');
461
- if (workspaceParent === undefined)
462
- mkdirSync(parent, { recursive: true, mode: 0o700 });
463
- const workspace = preparePrivateYoloIsolatedWorkspace(root, parent);
464
- const frozen = await readPrivateYoloFrozenWriteSet(root, storyId, workspace.executionBranch, graphRevision);
465
- verifyPrivateYoloSnapshotBoundary(workspace, frozen, workspace.baseSha);
466
- const record = Object.freeze({
467
- schemaVersion: 1, kind: 'private-yolo-isolated-session', storyId,
468
- initialGraphRevision: graphRevision, graphRevision, graphHistory: [graphRevision],
469
- setupSessionId: sessionId, workspace, snapshotSha: workspace.baseSha,
470
- sequence: 0, lastPatchSha256: null,
471
- });
472
- await writeSession(root, record);
473
- return record;
474
- });
475
- }
476
- catch {
477
- throw new Error('private-execution-isolated-session-unverified');
478
- }
479
- }
480
- /** Resume only the same private clone, snapshot and live C01 graph/session. */
481
- export async function resumePrivateYoloIsolatedSession(projectRoot, storyId, graphRevision) {
482
- const root = resolve(projectRoot);
483
- try {
484
- const record = await readSession(root, storyId);
485
- if (!record)
486
- throw new Error('session-missing');
487
- await verifySession(record, root, storyId, graphRevision);
488
- return record;
489
- }
490
- catch {
491
- throw new Error('private-execution-isolated-session-unverified');
492
- }
493
- }
494
- /** Admit one agent delta and durably pin the clone's next root-owned snapshot. */
495
- export async function admitPrivateYoloIsolatedSessionStep(projectRoot, storyId, graphRevision) {
496
- const root = resolve(projectRoot);
497
- try {
498
- const sessionId = setupSessionId(root, storyId);
499
- return await withPhysicalLock(root, storyId, sessionId, async () => {
500
- const current = await readSession(root, storyId);
501
- if (!current)
502
- throw new Error('session-missing');
503
- verifySessionBinding(current, root, storyId, graphRevision);
504
- const frozen = await readPrivateYoloFrozenWriteSet(root, storyId, current.workspace.executionBranch, graphRevision);
505
- const scope = await sessionMemoryScope(current, frozen);
506
- const admission = await admitPrivateYoloFrozenWorkspace(current.workspace, storyId, graphRevision, current.snapshotSha, false, scope);
507
- git(current.workspace.workspacePath, ['add', '-A', '--', ...admission.changedPaths]);
508
- git(current.workspace.workspacePath, [
509
- '-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false',
510
- '-c', 'user.name=Neocortex Private Session',
511
- '-c', 'user.email=private-session@neocortex.invalid',
512
- 'commit', '-q', '-m', `private snapshot ${storyId} ${current.sequence + 1}`,
513
- ]);
514
- const snapshotSha = git(current.workspace.workspacePath, ['rev-parse', 'HEAD']);
515
- verifyPrivateYoloSnapshotBoundary(current.workspace, frozen, snapshotSha, scope);
516
- const next = Object.freeze({
517
- ...current, snapshotSha, sequence: current.sequence + 1,
518
- lastPatchSha256: admission.patchSha256,
519
- });
520
- await writeSession(root, next);
521
- return { session: next, admission };
522
- });
523
- }
524
- catch {
525
- throw new Error('private-execution-isolated-session-unverified');
526
- }
527
- }
528
- /**
529
- * Root-owned C08 staging. The agent never gets index authority: the source
530
- * must still equal the pinned clone, and the staged bytes must equal its
531
- * immutable base-to-snapshot patch. QA and checkpoint remain separate gates.
532
- */
533
- export async function stagePrivateYoloIsolatedSessionBundle(projectRoot, storyId, graphRevision) {
534
- const root = resolve(projectRoot);
535
- try {
536
- const sessionId = setupSessionId(root, storyId);
537
- return await withPhysicalLock(root, storyId, sessionId, async () => {
538
- const session = await readSession(root, storyId);
539
- if (!session || session.sequence < 1)
540
- throw new Error('session-incomplete');
541
- const scope = await verifySession(session, root, storyId, graphRevision);
542
- const frozen = await readPrivateYoloFrozenWriteSet(root, storyId, session.workspace.executionBranch, graphRevision);
543
- const clone = session.workspace.workspacePath;
544
- const changedPaths = gitRaw(clone, [
545
- 'diff', '--name-only', '-z', session.workspace.baseSha, session.snapshotSha,
546
- ]).toString('utf8').split('\0').filter(Boolean).sort();
547
- const required = [
548
- '.neocortex/state.json', `docs/stories/${storyId}.story.md`,
549
- `.neocortex/stories/${storyId}/qa-gate-result.json`,
550
- `.neocortex/stories/${storyId}/validation-evidence.md`,
551
- `.neocortex/stories/${storyId}/review.md`,
552
- ];
553
- if (changedPaths.length === 0 || changedPaths.length > 1024
554
- || new Set(changedPaths).size !== changedPaths.length
555
- || changedPaths.some((path) => !frozen.includes(path) && !(scope && privateRootMemoryEffect(scope).files.some(file => file.path === path)))
556
- || required.some((path) => !changedPaths.includes(path))) {
557
- throw new Error('bundle-incomplete');
558
- }
559
- if (!gitExitOk(root, ['diff', '--cached', '--quiet'])
560
- || gitRaw(root, ['ls-files', '-u', '-z']).byteLength !== 0) {
561
- throw new Error('index-not-clean');
562
- }
563
- const expected = gitRaw(clone, [
564
- 'diff', '--binary', '--full-index', session.workspace.baseSha, session.snapshotSha,
565
- ]);
566
- if (expected.byteLength === 0)
567
- throw new Error('bundle-empty');
568
- git(root, ['add', '-A', '--', ...changedPaths]);
569
- const staged = gitRaw(root, ['diff', '--cached', '--binary', '--full-index']);
570
- const stagedPaths = gitRaw(root, ['diff', '--cached', '--name-only', '-z'])
571
- .toString('utf8').split('\0').filter(Boolean).sort();
572
- if (!staged.equals(expected)
573
- || stagedPaths.length !== changedPaths.length
574
- || stagedPaths.some((path, index) => path !== changedPaths[index])
575
- || !gitExitOk(root, ['diff', '--quiet'])
576
- || git(root, ['rev-parse', 'HEAD']) !== session.workspace.baseSha
577
- || git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== session.workspace.executionBranch) {
578
- throw new Error('bundle-raced');
579
- }
580
- return Object.freeze({
581
- schemaVersion: 1, outcome: 'staged-unverified', snapshotSha: session.snapshotSha,
582
- bundleSha256: createHash('sha256').update(staged).digest('hex'),
583
- changedPaths: Object.freeze(changedPaths),
584
- });
585
- });
586
- }
587
- catch {
588
- // Never unstage on failure: an external writer may have raced the index.
589
- throw new Error('private-execution-root-stage-unverified');
590
- }
591
- }
592
- function rejectedCandidate(record) {
593
- const clone = record.workspace.workspacePath;
594
- const bytes = gitRaw(clone, ['status', '--porcelain=v1', '-z', '-uall']);
595
- const rows = bytes.toString('utf8').split('\0').filter(Boolean);
596
- if (rows.length < 1 || rows.length > 1024)
597
- throw new Error('rejected-candidate-invalid');
598
- let total = 0;
599
- const files = rows.map(row => {
600
- const code = row.slice(0, 2), path = row.slice(3);
601
- if (![' M', ' D', '??'].includes(code) || path.length < 1 || path.length > 1024
602
- || path.startsWith('/') || /[\\\x00-\x1f\x7f]/.test(path)
603
- || path.split('/').some(part => !part || part === '.' || part === '..' || part === '.git')) {
604
- throw new Error('rejected-candidate-path-invalid');
605
- }
606
- const parts = path.split('/');
607
- for (let i = 1; i < parts.length; i++) {
608
- const parent = join(clone, ...parts.slice(0, i));
609
- if (!existsSync(parent))
610
- break;
611
- const entry = lstatSync(parent);
612
- if (!entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.())
613
- throw new Error('rejected-candidate-parent-invalid');
614
- }
615
- const target = join(clone, path);
616
- if (code === ' D') {
617
- if (existsSync(target))
618
- throw new Error('rejected-candidate-raced');
619
- return { path, code, mode: null, sha256: null, content: null };
620
- }
621
- const entry = lstatSync(target);
622
- if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1
623
- || entry.uid !== process.getuid?.() || entry.size > 16 * 1024 * 1024)
624
- throw new Error('rejected-candidate-file-invalid');
625
- const content = readFileSync(target);
626
- total += content.byteLength;
627
- if (total > 16 * 1024 * 1024)
628
- throw new Error('rejected-candidate-too-large');
629
- return { path, code, mode: entry.mode & 0o777, sha256: createHash('sha256').update(content).digest('hex'), content };
630
- });
631
- if (new Set(files.map(f => f.path)).size !== files.length)
632
- throw new Error('rejected-candidate-path-invalid');
633
- const fields = { schemaVersion: 'PrivateYoloRejectedCandidateInspection/1',
634
- storyId: record.storyId, graphRevision: record.graphRevision, snapshotSha: record.snapshotSha,
635
- sourceHead: record.workspace.baseSha, sequence: record.sequence,
636
- statusSha256: createHash('sha256').update(bytes).digest('hex'),
637
- files: files.map(({ content: _content, ...metadata }) => metadata) };
638
- return { files, inspection: { schemaVersion: fields.schemaVersion, storyId: fields.storyId,
639
- graphRevision: fields.graphRevision, snapshotSha: fields.snapshotSha, sourceHead: fields.sourceHead,
640
- sequence: fields.sequence, candidateDigest: createHash('sha256').update(JSON.stringify(fields)).digest('hex'),
641
- changedPaths: files.map(f => f.path), publicSafe: true } };
642
- }
643
- async function checkedRejectedCandidate(root, storyId, graphRevision) {
644
- const record = await readSession(root, storyId);
645
- if (!record)
646
- throw new Error('session-missing');
647
- verifySessionBinding(record, root, storyId, graphRevision);
648
- const frozen = await readPrivateYoloFrozenWriteSet(root, storyId, record.workspace.executionBranch, graphRevision);
649
- verifyPrivateYoloRejectedCandidateOrigin(record.workspace, frozen, record.snapshotSha, await sessionMemoryScope(record, frozen));
650
- return { record, ...rejectedCandidate(record) };
651
- }
652
- /** The parent must first observe executor termination. Never resets a source or changes a pin. */
653
- export async function inspectPrivateYoloRejectedCandidate(projectRoot, storyId, graphRevision, executorStopped) {
654
- if (executorStopped !== true)
655
- throw new Error('private-execution-rejected-candidate-executor-not-stopped');
656
- const root = resolve(projectRoot);
657
- try {
658
- return await withPhysicalLock(root, storyId, setupSessionId(root, storyId), async () => (await checkedRejectedCandidate(root, storyId, graphRevision)).inspection);
659
- }
660
- catch {
661
- throw new Error('private-execution-rejected-candidate-unverified');
662
- }
663
- }
664
- /** Discard only the explicitly inspected unaccepted delta, after encrypted custody. */
665
- export async function discardPrivateYoloRejectedCandidate(projectRoot, storyId, graphRevision, input) {
666
- if (input.executorStopped !== true || input.authorizeDiscard !== true
667
- || !/^[a-f0-9]{64}$/.test(input.expectedCandidateDigest))
668
- throw new Error('private-execution-rejected-candidate-input-invalid');
669
- const root = resolve(projectRoot);
670
- try {
671
- return await withPhysicalLock(root, storyId, setupSessionId(root, storyId), async () => {
672
- const current = await checkedRejectedCandidate(root, storyId, graphRevision);
673
- if (current.inspection.candidateDigest !== input.expectedCandidateDigest)
674
- throw new Error('candidate-review-stale');
675
- const target = await location(root, storyId), pin = readFileSync(target.path);
676
- const archiveId = `rejected-${randomUUID()}`;
677
- const archive = await ensureGitLifecyclePrivateChildDirectory(target.parent, archiveId);
678
- const key = randomBytes(32), iv = randomBytes(12);
679
- const plain = Buffer.from(JSON.stringify({ schemaVersion: 'PrivateYoloRejectedCandidateArchive/1',
680
- inspection: current.inspection, files: current.files.map(({ content, ...metadata }) => ({
681
- ...metadata, contentBase64: content?.toString('base64') ?? null
682
- })) }));
683
- const cipher = createCipheriv('aes-256-gcm', key, iv);
684
- cipher.setAAD(Buffer.from('private-yolo-rejected-candidate-v1'));
685
- const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()]);
686
- plain.fill(0);
687
- const sealed = Buffer.concat([iv, cipher.getAuthTag(), ciphertext]);
688
- try {
689
- await anchoredAtomicWriteFile(archive, 'candidate.key', key);
690
- await anchoredAtomicWriteFile(archive, 'candidate.aesgcm', sealed);
691
- }
692
- finally {
693
- key.fill(0);
694
- }
695
- const recheck = await checkedRejectedCandidate(root, storyId, graphRevision);
696
- if (recheck.inspection.candidateDigest !== input.expectedCandidateDigest || !readFileSync(target.path).equals(pin))
697
- throw new Error('candidate-raced');
698
- const clone = current.record.workspace.workspacePath;
699
- const tracked = current.files.filter(f => f.code !== '??').map(f => f.path);
700
- if (tracked.length)
701
- git(clone, ['restore', '--source', current.record.snapshotSha, '--worktree', '--', ...tracked]);
702
- for (const file of current.files.filter(f => f.code === '??')) {
703
- const path = join(clone, file.path), entry = lstatSync(path);
704
- if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1
705
- || createHash('sha256').update(readFileSync(path)).digest('hex') !== file.sha256)
706
- throw new Error('candidate-raced');
707
- unlinkSync(path);
708
- }
709
- await verifySession(current.record, root, storyId, graphRevision);
710
- if (!readFileSync(target.path).equals(pin))
711
- throw new Error('session-pin-raced');
712
- const receipt = { schemaVersion: 'PrivateYoloRejectedCandidateRecovery/1',
713
- outcome: 'candidate-discarded', archiveId,
714
- archiveSha256: createHash('sha256').update(sealed).digest('hex'),
715
- candidateDigest: input.expectedCandidateDigest, snapshotSha: current.record.snapshotSha,
716
- sourceHead: current.record.workspace.baseSha, sessionPinPreserved: true,
717
- sourcePreserved: true, checkpointAccepted: false, publicSafe: true };
718
- await anchoredAtomicWriteFile(archive, 'recovery.json', `${JSON.stringify(receipt)}\n`);
719
- return receipt;
720
- });
721
- }
722
- catch {
723
- throw new Error('private-execution-rejected-candidate-recovery-unverified');
724
- }
725
- }
1
+ import{execFileSync as ge,spawnSync as _e}from"node:child_process";import{createCipheriv as Ae,createHash as T,randomBytes as Ee,randomUUID as Oe}from"node:crypto";import{existsSync as Y,lstatSync as U,mkdirSync as qe,readFileSync as R,unlinkSync as Te}from"node:fs";import{homedir as De}from"node:os";import{basename as Ge,dirname as Be,join as v,resolve as _}from"node:path";import{isRootProjectMemoryEffect as Ce,rootProjectMemoryPaths as Me}from"./shared-root-memory-types.js";import{readPrivateRootMemoryScope as Ne,privateRootMemoryEffect as xe}from"./root-memory-scope.js";import{executeRootMemoryWriter as ze,rootMemoryFileState as Re,verifyRootMemoryWriterExecution as He}from"./root-memory-writer.js";import{rootMemoryGitFileState as $e,verifyRootMemoryEffectGitEvidence as Le}from"./root-memory-git-evidence.js";import{parsePrivateRootMemoryRequest as Ye}from"./root-memory-request.js";import{rootMemoryOperationJournalName as Je,readVerifiedPreparedRootMemory as Ve}from"./root-memory-recovery.js";import{assertProjectMemoryPaths as Fe}from"../memory/project-memory-path-scope.js";import{isDeepStrictEqual as J}from"node:util";import{acquireGitLifecyclePhysicalIntegrationLock as We,applyGitLifecycleRuntimeOverlay as Qe,assertGitLifecyclePrivateFile as X,ensureGitLifecyclePrivateChildDirectory as Z,gitLifecycleRuntimeDirectory as ke,mutateGitLifecycleRuntime as Ke,readGitLifecycleRuntimeSync as ue,releaseGitLifecyclePhysicalIntegrationLock as Ue}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as z,anchoredDirectoryIdentity as Xe,anchoredExecuteGit as Ze}from"../git/secure-filesystem-boundary.js";import{privateYoloRootOnlySetupReady as et,readPrivateYoloFrozenWriteSet as M,readPrivateYoloFrozenWriteSetForTransition as tt}from"./clean-baseline.js";import{admitPrivateYoloFrozenWorkspace as at,verifyPrivateYoloSnapshotBoundary as V,verifyPrivateYoloRejectedCandidateOrigin as ot}from"./isolated-admission.js";import{preparePrivateYoloIsolatedWorkspace as st}from"./isolated-workspace.js";async function bt(t,a,e={}){const o=Ye(a),{directive:r,review:s}=o,i=_(t),n=r.storyId,f=n.split(".")[0],p=d=>T("sha256").update(d).digest("hex");let h="session";const u=()=>{throw new Error(`private-root-memory-acceptance-${h}-unverified`)};try{return await G(i,n,I(i,n),async()=>{const d=ue(i,{required:!0}),m=d.epics[f],l=m?.branch_lease,c=await D(i,n);if(!c||m?.graph_revision!==r.graphRevision||l?.ownerStoryId!==n||typeof l.expiresAt!="string"||Date.parse(l.expiresAt)<=Date.now()||c.workspace.executionBranch!==r.executionBranch)return u();te(c,i,n,r.graphRevision);const S=await Z(await ke(i),"private-execution"),H=Je(c,o),B=c.rootMemoryEffect===void 0&&Y(v(S,H));B||await A(c,i,n,r.graphRevision);const W=await Xe(i);h="source-evidence",Fe(i,[".neocortex/state.json",`.neocortex/stories/${n}/validation-evidence.md`]);const E=R(v(i,".neocortex/state.json"));if(p(E)!==s.sourceStateSha256)return u();const y=Qe(JSON.parse(E.toString("utf8")),d).stories?.[n];if(!y||y.checkpoint!==void 0||!Array.isArray(y.steps_completed))return u();const ae=[...y.steps_completed],oe=`.neocortex/stories/${n}/validation-evidence.md`,$=U(v(i,oe));if(!$.isFile()||$.isSymbolicLink()||$.nlink!==1||$.size<128||$.size>256*1024||p(R(v(i,oe)))!==s.proposalSha256)return u();const we=v(S,`qa-review-${s.rootQaReceiptId}.json`);h="qa-predecessor",await X(we,S);const se=R(we);if(se.length>16384||p(se)!==s.rootQaReceiptId)return u();const q=JSON.parse(se.toString("utf8"));if(q.kind!=="private-qa-root-review"||q.storyId!==n||q.sourceHeadSha!==c.workspace.baseSha||q.precommitQaAccepted!==!0||q.independentStoryQaAccepted!==!1||q.terminalAccepted!==!1)return u();const re=p(JSON.stringify(s.notes)),ie=w=>`memory-review-${p(JSON.stringify(w))}.json`,me=y.status==="qa-gate-passed"&&typeof y.last_step=="string"&&p(y.last_step)==="8721319de90ade506bc9b72a908d8296856b34a11bc640629178bed3fe32e373"&&ae.at(-1)===y.last_step,Se=async w=>{await Ke(i,j=>{if(!J(j.epics[f],m)||!J(j.stories[n],d.stories[n]))return u();j.stories[n]={...j.stories[n],status:"memory-updated",last_step:s.rawStepId,steps_completed:[...ae,s.rawStepId]}},{expectedRevision:d.revision,preCommit:async()=>{await A(w,i,n,r.graphRevision)}})};if(c.rootMemoryEffect){if(h="replay",c.rootMemoryEffect.sourceSnapshotSha!==s.snapshotSha||c.rootMemoryEffect.proposalSha256!==re||c.rootMemoryEffect.rootQaReceiptId!==s.rootQaReceiptId)return u();const w=v(S,ie(c.rootMemoryEffect));await X(w,S);const j=R(w),k=JSON.parse(j.toString("utf8"));if(k.proposalSha256!==s.proposalSha256||k.notesSha256!==re||!J(k.rootMemoryEffect,c.rootMemoryEffect))return u();const C=y.status==="memory-updated"&&y.last_step===s.rawStepId&&ae.at(-1)===s.rawStepId;return!C&&!me?u():(C||(h="phase-recovery",await Se(c)),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(j),snapshotSha:c.snapshotSha,reused:!0,sourceStateUnchanged:!0,phaseRecovered:!C,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0})}if(c.snapshotSha!==s.snapshotSha||!me)return u();const P=c.workspace.workspacePath;g(P,["merge-base","--is-ancestor",q.snapshotSha,c.snapshotSha]);const Pe=[`.neocortex/stories/${n}/qa-gate-result.json`,oe,`.neocortex/stories/${n}/tdd-evidence.md`,`docs/stories/${n}.rtm.md`];if(b(P,["diff","--name-only","-z",q.snapshotSha,c.snapshotSha]).toString("utf8").split("\0").filter(Boolean).some(w=>!Pe.includes(w)))return u();const ne=await M(i,n,r.executionBranch,r.graphRevision);if(!fe(i,["diff","--cached","--quiet"]))return u();const je=b(i,["status","--porcelain=v1","-z","--untracked-files=all"]);let x,Q,N,K=!1;if(B){h="prepared-recovery";const w=await Ve({projectRoot:i,parent:S,current:c,request:o,childPaths:ne});x=w.effect,Q=w.receipt,N=w.patch,K=w.sourceAlreadyApplied}else{for(const L of Me())if(ne.includes(L)||!J(Re(i,L),$e(P,c.snapshotSha,L)))return u();h="writer";const w=await Z(S,"memory-backups"),j=ze({snapshotRoot:P,expectedSnapshotSha:c.snapshotSha,notes:s.notes,backupDirectory:w}),k=He(j);h="writer-snapshot",k.files.length&&(g(P,["add","-A","--",...k.files.map(L=>L.path)]),g(P,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private root memory ${n} ${c.sequence+1}`]));const C=g(P,["rev-parse","HEAD"]);x={schemaVersion:"RootProjectMemoryEffect/1",producer:"root-project-memory",storyId:n,epicId:f,executionBranch:r.executionBranch,sourceHeadSha:c.workspace.baseSha,sourceSnapshotSha:c.snapshotSha,memorySnapshotSha:C,graphRevision:r.graphRevision,childClaimRevision:p([...ne].sort().join("\0")),setupSessionId:c.setupSessionId,rootQaReceiptId:s.rootQaReceiptId,proposalSha256:k.notesSha256,canonicalSha256:k.verification.canonicalSha256,projectionSha256:k.verification.projectionSha256,projectionFileCount:k.verification.fileCount,files:k.files,recordedAt:s.reviewedAt,publicSafe:!0},h="git-evidence",Le(P,x,{storyId:n,graphRevision:r.graphRevision,childClaimRevision:x.childClaimRevision,setupSessionId:c.setupSessionId,sourceHeadSha:c.workspace.baseSha,executionBranch:r.executionBranch}),N=b(P,["diff","--binary","--full-index",c.snapshotSha,C]),Q={schemaVersion:1,kind:"private-project-memory-root-review",storyId:n,graphRevision:r.graphRevision,sourceHeadSha:c.workspace.baseSha,snapshotSha:C,proposalSha256:s.proposalSha256,notesSha256:re,sourceStateSha256:s.sourceStateSha256,checks:s.checks,reviewedAt:s.reviewedAt,rootMemoryEffect:x,independentStoryQaAccepted:!1,terminalAccepted:!1},h="prepared-journal",await z(S,H,JSON.stringify({schemaVersion:1,kind:"prepared-root-memory-effect",previousSession:c,receipt:Q,patchSha256:p(N)})+`
2
+ `),await e.fault?.("after-prepared-journal")}const ce=JSON.stringify(Q)+`
3
+ `,ye=x.memorySnapshotSha;if(h="source-admission",!b(i,["status","--porcelain=v1","-z","--untracked-files=all"]).equals(je)||g(i,["rev-parse","HEAD"])!==c.workspace.baseSha||g(i,["symbolic-ref","--short","HEAD"])!==r.executionBranch)return u();if(!K){for(const w of x.files)if(!J(Re(i,w.path),w.before))return u()}const ve=w=>Ze(Be(i),Ge(i),W,["apply",...w?["--check"]:[],"--binary","-"],N);if(N.length&&!K&&(await ve(!0),await ve(!1)),await e.fault?.("after-source-admission"),!R(v(i,".neocortex/state.json")).equals(E))return u();const pe=v(S,ie(x));if(Y(pe)){if(await X(pe,S),R(pe,"utf8")!==ce)return u()}else await z(S,ie(x),ce);const he=Object.freeze({...c,snapshotSha:ye,sequence:c.sequence+(x.files.length?1:0),lastPatchSha256:x.files.length?p(N):c.lastPatchSha256,rootMemoryEffect:x});return h="session-pin",await e.fault?.("before-session-pin"),await F(i,he),await A(he,i,n,r.graphRevision),h="phase-transition",await Se(he),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(ce),snapshotSha:ye,reused:B,sourceStateUnchanged:!0,preparedRecovered:B,sourceWriteReused:K,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0}})}catch(d){if(d instanceof Error&&/^(private-root-memory|private-execution-isolated)-[a-z0-9-]+$/.test(d.message)?d.message:void 0)throw new Error(`private-root-memory-acceptance-${h}-unverified`,{cause:d});return u()}}function g(t,a){const e={...process.env};for(const o 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 e[o];return ge("git",[...a],{cwd:t,env:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024}).trim()}function b(t,a){const e={...process.env};for(const o 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 e[o];return ge("git",[...a],{cwd:t,env:e,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function fe(t,a){const e={...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 e[r];const o=_e("git",[...a],{cwd:t,env:e,stdio:"ignore",timeout:3e4});if(o.error||o.signal)throw new Error("git-unverified");return o.status===0}async function de(t,a){const e=await ke(t),o=await Z(e,"private-execution"),r=`session-${T("sha256").update(a).digest("hex")}.json`;return{parent:o,name:r,path:v(o,r)}}function I(t,a){const e=a.split(".")[0],r=ue(t,{required:!0}).epics[e]?.branch_lease,s=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,i=s?.sessionId;if(s?.ownerStoryId!==a||typeof i!="string"||!/^setup-[a-f0-9]{64}$/.test(i)||i!==s.idempotencyKey)throw new Error("session-lease-invalid");return i}function be(t,a){const e=ue(t,{required:!0}).stories[a];return et(e)}function rt(t){const a=JSON.parse(t);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("session-invalid");const e=a,o=e.workspace;if(Object.keys(e).sort().join(",")!==["schemaVersion","kind","storyId","initialGraphRevision","graphRevision","graphHistory","setupSessionId","workspace","snapshotSha","sequence","lastPatchSha256",...e.rootMemoryEffect===void 0?[]:["rootMemoryEffect"]].sort().join(",")||e.schemaVersion!==1||e.kind!=="private-yolo-isolated-session"||typeof e.storyId!="string"||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(e.storyId)||typeof e.initialGraphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.initialGraphRevision)||typeof e.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.graphRevision)||!Array.isArray(e.graphHistory)||e.graphHistory.length<1||e.graphHistory.length>65||e.graphHistory.some(s=>typeof s!="string"||!/^[a-f0-9]{64}$/.test(s))||new Set(e.graphHistory).size!==e.graphHistory.length||e.graphHistory[0]!==e.initialGraphRevision||e.graphHistory[e.graphHistory.length-1]!==e.graphRevision||typeof e.setupSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(e.setupSessionId)||typeof e.snapshotSha!="string"||!/^[a-f0-9]{40,64}$/.test(e.snapshotSha)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<0||Number(e.sequence)>64||Number(e.sequence)===0&&e.initialGraphRevision!==e.graphRevision&&e.graphHistory.length!==2||Number(e.sequence)===0&&e.lastPatchSha256!==null||Number(e.sequence)>0&&e.lastPatchSha256===null||e.lastPatchSha256!==null&&(typeof e.lastPatchSha256!="string"||!/^[a-f0-9]{64}$/.test(e.lastPatchSha256))||e.rootMemoryEffect!==void 0&&!Ce(e.rootMemoryEffect)||!o||typeof o!="object"||Array.isArray(o))throw new Error("session-invalid");const r=o;if(Object.keys(r).sort().join(",")!==["schemaVersion","sourceRoot","workspacePath","baseSha","executionBranch"].sort().join(",")||r.schemaVersion!==1||typeof r.sourceRoot!="string"||typeof r.workspacePath!="string"||typeof r.baseSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.baseSha)||typeof r.executionBranch!="string"||!r.executionBranch)throw new Error("session-invalid");return e}async function D(t,a){const e=await de(t,a);if(Y(e.path))return await X(e.path,e.parent),rt(R(e.path,"utf8"))}async function F(t,a){const e=await de(t,a.storyId);await z(e.parent,e.name,`${JSON.stringify(a)}
4
+ `)}async function G(t,a,e,o){const r=await We(t,{kind:"direct",storyId:a,sessionId:e,idempotencyKey:e,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});if(!r.ok)throw new Error("private-execution-isolated-session-backpressure");try{return await o()}finally{if(!await Ue(r.path,r.owner))throw new Error("private-execution-isolated-session-lock-unverified")}}async function A(t,a,e,o){te(t,a,e,o);const r=await M(a,e,t.workspace.executionBranch,o),s=await ee(t,r);return V(t.workspace,r,t.snapshotSha,s),s}async function ee(t,a){if(t.rootMemoryEffect===void 0)return;const e=await Ne({projectRoot:t.workspace.sourceRoot,storyId:t.storyId,snapshotRoot:t.workspace.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace.baseSha,executionBranch:t.workspace.executionBranch,graphRevision:t.graphRevision,setupSessionId:t.setupSessionId,childPaths:a});if(!e||JSON.stringify(xe(e))!==JSON.stringify(t.rootMemoryEffect))throw new Error("private-root-memory-scope-unverified");return e}function te(t,a,e,o){if(t.storyId!==e||t.graphRevision!==o||t.workspace.sourceRoot!==a||t.setupSessionId!==I(a,e)||t.sequence===0&&t.snapshotSha!==t.workspace.baseSha||t.sequence===0&&t.graphHistory.length>1&&!be(a,e)||t.sequence>0&&t.snapshotSha===t.workspace.baseSha)throw new Error("session-binding-invalid")}async function It(t,a,e){const o=_(t.sourceRoot);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(s){if(await A(s,o,a,e),s.workspace.workspacePath!==t.workspacePath)throw new Error("session-replacement-denied");return s}const i=await M(o,a,t.executionBranch,e);V(t,i,t.baseSha);const n=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:r,workspace:t,snapshotSha:t.baseSha,sequence:0,lastPatchSha256:null});return await F(o,n),n})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function Ie(t,a,e,o){if(t.graphRevision===o)return await A(t,a,e,o),t;if(t.storyId!==e||t.workspace.sourceRoot!==a||t.setupSessionId!==I(a,e)||t.sequence===0&&(t.graphHistory.length!==1||t.lastPatchSha256!==null||!be(a,e))||t.sequence>0&&t.lastPatchSha256===null||t.graphHistory.includes(o)||t.graphHistory.length>=65)throw new Error("session-graph-transition-invalid");const r=await tt(a,e,t.workspace.executionBranch,t.initialGraphRevision,o);V(t.workspace,r,t.snapshotSha,await ee(t,r));const s=Object.freeze({...t,graphRevision:o,graphHistory:Object.freeze([...t.graphHistory,o])});return await F(a,s),await A(s,a,e,o),s}async function Pt(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s)throw new Error("session-missing");return Ie(s,o,a,e)})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function jt(t,a,e,o){const r=_(t);try{const s=I(r,a);return await G(r,a,s,async()=>{const i=await D(r,a);if(i)return Ie(i,r,a,e);const n=o??v(De(),".local","share","neocortex","private-yolo-workspaces");o===void 0&&qe(n,{recursive:!0,mode:448});const f=st(r,n),p=await M(r,a,f.executionBranch,e);V(f,p,f.baseSha);const h=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:s,workspace:f,snapshotSha:f.baseSha,sequence:0,lastPatchSha256:null});return await F(r,h),h})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function _t(t,a,e){const o=_(t);try{const r=await D(o,a);if(!r)throw new Error("session-missing");return await A(r,o,a,e),r}catch{throw new Error("private-execution-isolated-session-unverified")}}async function At(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s)throw new Error("session-missing");te(s,o,a,e);const i=await M(o,a,s.workspace.executionBranch,e),n=await ee(s,i),f=await at(s.workspace,a,e,s.snapshotSha,!1,n);g(s.workspace.workspacePath,["add","-A","--",...f.changedPaths]),g(s.workspace.workspacePath,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private snapshot ${a} ${s.sequence+1}`]);const p=g(s.workspace.workspacePath,["rev-parse","HEAD"]);V(s.workspace,i,p,n);const h=Object.freeze({...s,snapshotSha:p,sequence:s.sequence+1,lastPatchSha256:f.patchSha256});return await F(o,h),{session:h,admission:f}})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function Ot(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s||s.sequence<1)throw new Error("session-incomplete");const i=await A(s,o,a,e),n=await M(o,a,s.workspace.executionBranch,e),f=s.workspace.workspacePath,p=b(f,["diff","--name-only","-z",s.workspace.baseSha,s.snapshotSha]).toString("utf8").split("\0").filter(Boolean).sort(),h=[".neocortex/state.json",`docs/stories/${a}.story.md`,`.neocortex/stories/${a}/qa-gate-result.json`,`.neocortex/stories/${a}/validation-evidence.md`,`.neocortex/stories/${a}/review.md`];if(p.length===0||p.length>1024||new Set(p).size!==p.length||p.some(l=>!n.includes(l)&&!(i&&xe(i).files.some(c=>c.path===l)))||h.some(l=>!p.includes(l)))throw new Error("bundle-incomplete");if(!fe(o,["diff","--cached","--quiet"])||b(o,["ls-files","-u","-z"]).byteLength!==0)throw new Error("index-not-clean");const u=b(f,["diff","--binary","--full-index",s.workspace.baseSha,s.snapshotSha]);if(u.byteLength===0)throw new Error("bundle-empty");g(o,["add","-A","--",...p]);const d=b(o,["diff","--cached","--binary","--full-index"]),m=b(o,["diff","--cached","--name-only","-z"]).toString("utf8").split("\0").filter(Boolean).sort();if(!d.equals(u)||m.length!==p.length||m.some((l,c)=>l!==p[c])||!fe(o,["diff","--quiet"])||g(o,["rev-parse","HEAD"])!==s.workspace.baseSha||g(o,["symbolic-ref","--quiet","--short","HEAD"])!==s.workspace.executionBranch)throw new Error("bundle-raced");return Object.freeze({schemaVersion:1,outcome:"staged-unverified",snapshotSha:s.snapshotSha,bundleSha256:T("sha256").update(d).digest("hex"),changedPaths:Object.freeze(p)})})}catch{throw new Error("private-execution-root-stage-unverified")}}function it(t){const a=t.workspace.workspacePath,e=b(a,["status","--porcelain=v1","-z","-uall"]),o=e.toString("utf8").split("\0").filter(Boolean);if(o.length<1||o.length>1024)throw new Error("rejected-candidate-invalid");let r=0;const s=o.map(n=>{const f=n.slice(0,2),p=n.slice(3);if(![" M"," D","??"].includes(f)||p.length<1||p.length>1024||p.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(p)||p.split("/").some(l=>!l||l==="."||l===".."||l===".git"))throw new Error("rejected-candidate-path-invalid");const h=p.split("/");for(let l=1;l<h.length;l++){const c=v(a,...h.slice(0,l));if(!Y(c))break;const S=U(c);if(!S.isDirectory()||S.isSymbolicLink()||S.uid!==process.getuid?.())throw new Error("rejected-candidate-parent-invalid")}const u=v(a,p);if(f===" D"){if(Y(u))throw new Error("rejected-candidate-raced");return{path:p,code:f,mode:null,sha256:null,content:null}}const d=U(u);if(!d.isFile()||d.isSymbolicLink()||d.nlink!==1||d.uid!==process.getuid?.()||d.size>16*1024*1024)throw new Error("rejected-candidate-file-invalid");const m=R(u);if(r+=m.byteLength,r>16*1024*1024)throw new Error("rejected-candidate-too-large");return{path:p,code:f,mode:d.mode&511,sha256:T("sha256").update(m).digest("hex"),content:m}});if(new Set(s.map(n=>n.path)).size!==s.length)throw new Error("rejected-candidate-path-invalid");const i={schemaVersion:"PrivateYoloRejectedCandidateInspection/1",storyId:t.storyId,graphRevision:t.graphRevision,snapshotSha:t.snapshotSha,sourceHead:t.workspace.baseSha,sequence:t.sequence,statusSha256:T("sha256").update(e).digest("hex"),files:s.map(({content:n,...f})=>f)};return{files:s,inspection:{schemaVersion:i.schemaVersion,storyId:i.storyId,graphRevision:i.graphRevision,snapshotSha:i.snapshotSha,sourceHead:i.sourceHead,sequence:i.sequence,candidateDigest:T("sha256").update(JSON.stringify(i)).digest("hex"),changedPaths:s.map(n=>n.path),publicSafe:!0}}}async function le(t,a,e){const o=await D(t,a);if(!o)throw new Error("session-missing");te(o,t,a,e);const r=await M(t,a,o.workspace.executionBranch,e);return ot(o.workspace,r,o.snapshotSha,await ee(o,r)),{record:o,...it(o)}}async function qt(t,a,e,o){if(o!==!0)throw new Error("private-execution-rejected-candidate-executor-not-stopped");const r=_(t);try{return await G(r,a,I(r,a),async()=>(await le(r,a,e)).inspection)}catch{throw new Error("private-execution-rejected-candidate-unverified")}}async function Tt(t,a,e,o){if(o.executorStopped!==!0||o.authorizeDiscard!==!0||!/^[a-f0-9]{64}$/.test(o.expectedCandidateDigest))throw new Error("private-execution-rejected-candidate-input-invalid");const r=_(t);try{return await G(r,a,I(r,a),async()=>{const s=await le(r,a,e);if(s.inspection.candidateDigest!==o.expectedCandidateDigest)throw new Error("candidate-review-stale");const i=await de(r,a),n=R(i.path),f=`rejected-${Oe()}`,p=await Z(i.parent,f),h=Ee(32),u=Ee(12),d=Buffer.from(JSON.stringify({schemaVersion:"PrivateYoloRejectedCandidateArchive/1",inspection:s.inspection,files:s.files.map(({content:E,...O})=>({...O,contentBase64:E?.toString("base64")??null}))})),m=Ae("aes-256-gcm",h,u);m.setAAD(Buffer.from("private-yolo-rejected-candidate-v1"));const l=Buffer.concat([m.update(d),m.final()]);d.fill(0);const c=Buffer.concat([u,m.getAuthTag(),l]);try{await z(p,"candidate.key",h),await z(p,"candidate.aesgcm",c)}finally{h.fill(0)}if((await le(r,a,e)).inspection.candidateDigest!==o.expectedCandidateDigest||!R(i.path).equals(n))throw new Error("candidate-raced");const H=s.record.workspace.workspacePath,B=s.files.filter(E=>E.code!=="??").map(E=>E.path);B.length&&g(H,["restore","--source",s.record.snapshotSha,"--worktree","--",...B]);for(const E of s.files.filter(O=>O.code==="??")){const O=v(H,E.path),y=U(O);if(!y.isFile()||y.isSymbolicLink()||y.nlink!==1||T("sha256").update(R(O)).digest("hex")!==E.sha256)throw new Error("candidate-raced");Te(O)}if(await A(s.record,r,a,e),!R(i.path).equals(n))throw new Error("session-pin-raced");const W={schemaVersion:"PrivateYoloRejectedCandidateRecovery/1",outcome:"candidate-discarded",archiveId:f,archiveSha256:T("sha256").update(c).digest("hex"),candidateDigest:o.expectedCandidateDigest,snapshotSha:s.record.snapshotSha,sourceHead:s.record.workspace.baseSha,sessionPinPreserved:!0,sourcePreserved:!0,checkpointAccepted:!1,publicSafe:!0};return await z(p,"recovery.json",`${JSON.stringify(W)}
5
+ `),W})}catch{throw new Error("private-execution-rejected-candidate-recovery-unverified")}}export{bt as acceptPrivateYoloProjectMemoryRootReview,At as admitPrivateYoloIsolatedSessionStep,It as beginPrivateYoloIsolatedSession,Tt as discardPrivateYoloRejectedCandidate,jt as ensurePrivateYoloIsolatedSession,qt as inspectPrivateYoloRejectedCandidate,Pt as reconcilePrivateYoloIsolatedSession,_t as resumePrivateYoloIsolatedSession,Ot as stagePrivateYoloIsolatedSessionBundle};