@ornexus/neocortex 4.60.73 → 4.60.74

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 (241) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +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 -212
  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 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -358
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +143 -7200
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -156
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  75. package/packages/client/dist/config/profile-directory.js +1 -13
  76. package/packages/client/dist/config/resolver-selection.js +1 -278
  77. package/packages/client/dist/config/secure-config.js +12 -281
  78. package/packages/client/dist/config.js +2 -223
  79. package/packages/client/dist/constants.js +1 -25
  80. package/packages/client/dist/context/context-collector.js +2 -222
  81. package/packages/client/dist/context/context-sanitizer.js +1 -145
  82. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  83. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  84. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  85. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  86. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  87. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  88. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  90. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  91. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  92. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  93. package/packages/client/dist/continuity/outbox.js +1 -117
  94. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  95. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  96. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  97. package/packages/client/dist/errors/error-messages.js +2 -228
  98. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  99. package/packages/client/dist/evidence/collector.js +1 -347
  100. package/packages/client/dist/evidence/index.js +1 -1
  101. package/packages/client/dist/evidence/types.js +0 -2
  102. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  103. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  104. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  105. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  106. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  107. package/packages/client/dist/git/epic-operational-state.js +2 -672
  108. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  109. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  110. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  113. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  117. package/packages/client/dist/i18n/first-run.js +2 -60
  118. package/packages/client/dist/index.js +1 -47
  119. package/packages/client/dist/invocation/invoke-input.js +1 -24
  120. package/packages/client/dist/license/index.js +1 -5
  121. package/packages/client/dist/license/license-client.js +1 -304
  122. package/packages/client/dist/machine/fingerprint.js +2 -163
  123. package/packages/client/dist/machine/index.js +1 -5
  124. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  125. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  126. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  127. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  128. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  129. package/packages/client/dist/migrations/project-identity.js +7 -493
  130. package/packages/client/dist/migrations/state-json.js +4 -393
  131. package/packages/client/dist/policy/architecture-policy.js +2 -184
  132. package/packages/client/dist/policy/index.js +1 -7
  133. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  134. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  135. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  136. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  137. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  138. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  139. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  140. package/packages/client/dist/private-execution/delivery.js +13 -410
  141. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  142. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  143. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  144. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  145. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  146. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  147. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  148. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  149. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  150. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  151. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  152. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  153. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  154. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  155. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  156. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  157. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  158. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  159. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  160. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  161. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  162. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  163. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  164. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  165. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  166. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  167. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  168. package/packages/client/dist/private-execution/session-lease.js +1 -63
  169. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  170. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  171. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  172. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  173. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  174. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  175. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  176. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  177. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  178. package/packages/client/dist/resilience/index.js +1 -8
  179. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  180. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  181. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  182. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  183. package/packages/client/dist/runner/binary.js +1 -404
  184. package/packages/client/dist/runner/cli.js +17 -1571
  185. package/packages/client/dist/runner/headless/adapters.js +1 -49
  186. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  187. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  188. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  189. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  190. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  191. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  192. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  193. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +18 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  195. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  196. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  197. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  198. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  199. package/packages/client/dist/runner/headless/resolver.js +1 -231
  200. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  201. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  202. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  203. package/packages/client/dist/runner/headless/types.js +2 -574
  204. package/packages/client/dist/runner/local-console.js +13 -396
  205. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  206. package/packages/client/dist/runner/project-identity.js +1 -106
  207. package/packages/client/dist/runner/scheduler.js +7 -995
  208. package/packages/client/dist/runner-cli.js +2 -18
  209. package/packages/client/dist/state/invocation-shape.js +1 -13
  210. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  211. package/packages/client/dist/state/state-json-repair.js +3 -785
  212. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  213. package/packages/client/dist/telemetry/index.js +1 -5
  214. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  215. package/packages/client/dist/tier/index.js +1 -5
  216. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  217. package/packages/client/dist/types/index.js +1 -38
  218. package/packages/client/dist/version.js +1 -27
  219. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  220. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  221. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  222. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  223. package/packages/client/dist/yoloop/index.js +1 -8
  224. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  225. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  226. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  227. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  228. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  229. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  230. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  231. package/targets-stubs/antigravity/gemini.md +1 -1
  232. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  233. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  234. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  235. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex.md +2 -2
  237. package/targets-stubs/codex/AGENTS.md +1 -1
  238. package/targets-stubs/cursor/agent.md +2 -2
  239. package/targets-stubs/gemini-cli/agent.md +2 -2
  240. package/targets-stubs/opencode/neocortex-root.md +1 -1
  241. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,259 +1,9 @@
1
- /** Root-owned, replayable C01 checkpoint for explicitly recorded story branches. */
2
- import { execFileSync } from 'node:child_process';
3
- import { createHash, randomBytes } from 'node:crypto';
4
- import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from 'node:fs';
5
- import { join, resolve } from 'node:path';
6
- import { parseDocument } from 'yaml';
7
- import { resolveBranchUnit } from '../../../shared/dist/yoloop/branch-unit.js';
8
- import { acquireGitLifecyclePhysicalIntegrationLock, assertGitLifecyclePrivateFile, ensureGitLifecyclePrivateChildDirectory, gitLifecycleRuntimeDirectory, releaseGitLifecyclePhysicalIntegrationLock, } from './git-lifecycle-store.js';
9
- import { GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID } from './git-lifecycle-step-ids.js';
10
- import { anchoredAtomicWriteFile, anchoredCompareAndSwapFile } from './secure-filesystem-boundary.js';
11
- import { readCompletedLegacyStoryBranchPlan } from './legacy-story-branch-setup.js';
12
- function fail(reasonCode) { return { ok: false, reasonCode }; }
13
- function digest(value) { return createHash('sha256').update(value).digest('hex'); }
14
- function row(value) {
15
- return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
16
- }
17
- function git(cwd, args) {
18
- return execFileSync('git', [...args], { cwd, encoding: 'utf8',
19
- stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 * 1024 * 1024 }).trim();
20
- }
21
- function gitRaw(cwd, args) {
22
- return execFileSync('git', [...args], { cwd, encoding: 'utf8',
23
- stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 * 1024 * 1024 });
24
- }
25
- function safeRead(path) {
26
- const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
27
- try {
28
- const stat = fstatSync(fd);
29
- if (!stat.isFile() || stat.size > 2 * 1024 * 1024)
30
- throw new Error('legacy-branch-checkpoint-file-unsafe');
31
- return readFileSync(fd, 'utf8');
32
- }
33
- finally {
34
- closeSync(fd);
35
- }
36
- }
37
- function repository(cwd) {
38
- const remote = git(cwd, ['remote', 'get-url', 'origin']);
39
- const match = remote.match(/^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/);
40
- if (!match || match[1].includes('..') || match[2].includes('..')) {
41
- throw new Error('legacy-branch-issue-repository-invalid');
42
- }
43
- return `${match[1]}/${match[2]}`;
44
- }
45
- async function ghIssueVerifier(repo, number) {
46
- const raw = execFileSync('gh', ['issue', 'view', String(number), '--repo', repo,
47
- '--json', 'number,title,state,url'], { encoding: 'utf8', timeout: 15_000,
48
- stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 });
49
- return JSON.parse(raw);
50
- }
51
- function validateIssue(issue, repo, storyId, number, replay) {
52
- if (issue.number !== number || issue.title !== `[YOLO] Story ${storyId} - Workflow Run`
53
- || (issue.state !== 'OPEN' && !(replay && issue.state === 'CLOSED'))
54
- || issue.url.toLowerCase() !== `https://github.com/${repo}/issues/${number}`.toLowerCase()) {
55
- throw new Error('legacy-branch-issue-evidence-invalid');
56
- }
57
- }
58
- function project(plan, number) {
59
- const cwd = plan.worktreePath;
60
- const stateBefore = gitRaw(cwd, ['show', 'HEAD:.neocortex/state.json']);
61
- if (digest(stateBefore) !== plan.stateSha256)
62
- throw new Error('legacy-branch-checkpoint-base-state-mismatch');
63
- const state = row(JSON.parse(stateBefore));
64
- const stories = row(state?.stories);
65
- const epics = row(state?.epics);
66
- const story = row(stories?.[plan.storyId]);
67
- const epic = row(epics?.[plan.epicId]);
68
- const epicStories = Object.entries(stories ?? {}).flatMap(([id, value]) => {
69
- const item = row(value);
70
- return item?.epic_id === plan.epicId ? [{ ...item, id }] : [];
71
- });
72
- if (!epic || epic.id !== plan.epicId || epic.branch_mode === 'epic'
73
- || resolveBranchUnit(epic, epicStories).mode !== 'story'
74
- || !story || story.id !== plan.storyId || story.epic_id !== plan.epicId
75
- || (story.status !== 'backlog' && story.status !== 'ready_to_start')
76
- || !Array.isArray(story.steps_completed) || story.steps_completed.length !== 0
77
- || story.branch_name || story.issue_number || story.last_step) {
78
- throw new Error('legacy-branch-checkpoint-state-conflict');
79
- }
80
- story.status = 'branch-ready';
81
- story.steps_completed = [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID];
82
- story.last_step = GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID;
83
- story.branch_name = plan.branch;
84
- story.issue_number = number;
85
- const stateAfter = `${JSON.stringify(state, null, 2)}\n`;
86
- const storyPath = `docs/stories/${plan.storyId}.story.md`;
87
- const storyBefore = gitRaw(cwd, ['show', `HEAD:${storyPath}`]);
88
- const frontmatter = storyBefore.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
89
- if (!frontmatter)
90
- throw new Error('legacy-branch-checkpoint-frontmatter-invalid');
91
- const document = parseDocument(frontmatter[1], { strict: true, uniqueKeys: true });
92
- if (document.errors.length > 0 || document.get('id') !== plan.storyId
93
- || (document.get('epic_id') ?? document.get('epic')) !== plan.epicId) {
94
- throw new Error('legacy-branch-checkpoint-frontmatter-invalid');
95
- }
96
- const frontmatterData = row(document.toJS());
97
- const stepKeys = ['stepsCompleted', 'steps_completed'].filter((key) => document.has(key));
98
- const branchKeys = ['branchName', 'branch_name'].filter((key) => document.has(key));
99
- const lastKeys = ['lastStep', 'last_step'].filter((key) => document.has(key));
100
- const issueKeys = ['issueNumber', 'issue_number'].filter((key) => document.has(key));
101
- if (stepKeys.length > 1 || branchKeys.length > 1 || lastKeys.length > 1 || issueKeys.length > 1
102
- || (document.has('status') && !['backlog', 'ready', 'ready_to_start'].includes(String(document.get('status'))))
103
- || (document.has('currentStatus')
104
- && !['backlog', 'ready', 'ready_to_start'].includes(String(frontmatterData?.currentStatus)))
105
- || (stepKeys.length === 1 && (!Array.isArray(frontmatterData?.[stepKeys[0]])
106
- || (frontmatterData?.[stepKeys[0]]).length !== 0))
107
- || (branchKeys.length === 1 && frontmatterData?.[branchKeys[0]] != null)
108
- || (lastKeys.length === 1 && frontmatterData?.[lastKeys[0]] != null)
109
- || (issueKeys.length === 1 && frontmatterData?.[issueKeys[0]] != null)) {
110
- throw new Error('legacy-branch-checkpoint-frontmatter-conflict');
111
- }
112
- document.set('status', 'branch-ready');
113
- if (document.has('currentStatus'))
114
- document.set('currentStatus', 'branch-ready');
115
- document.set(stepKeys[0] ?? 'stepsCompleted', [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID]);
116
- document.set(lastKeys[0] ?? 'lastStep', GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID);
117
- document.set(branchKeys[0] ?? 'branchName', plan.branch);
118
- document.set(issueKeys[0] ?? 'issueNumber', number);
119
- const storyAfter = `---\n${document.toString({ lineWidth: 0 })}---\n${storyBefore.slice(frontmatter[0].length)}`;
120
- return { storyPath, stateBefore, stateAfter, storyBefore, storyAfter };
121
- }
122
- function physical(plan, sourceRoot, projection) {
123
- const cwd = realpathSync(plan.worktreePath);
124
- if (plan.epicId !== plan.storyId.split('.')[0]
125
- || plan.branch !== `story/${plan.epicId}/${plan.storyId}`
126
- || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(plan.epicId)
127
- || !git(sourceRoot, ['check-ref-format', '--branch', plan.branch])
128
- || !git(sourceRoot, ['check-ref-format', '--branch', plan.baseBranch])) {
129
- throw new Error('legacy-branch-checkpoint-plan-invalid');
130
- }
131
- const common = (path) => realpathSync(resolve(path, git(path, ['rev-parse', '--git-common-dir'])));
132
- const worktrees = git(sourceRoot, ['worktree', 'list', '--porcelain']).split(/\n\n+/)
133
- .filter((block) => block.split('\n').includes(`branch refs/heads/${plan.branch}`));
134
- if (cwd !== plan.worktreePath || worktrees.length !== 1
135
- || !worktrees[0].split('\n').includes(`worktree ${cwd}`)
136
- || worktrees[0].split('\n').some((line) => line.startsWith('locked') || line.startsWith('prunable'))
137
- || common(cwd) !== common(sourceRoot)
138
- || realpathSync(git(cwd, ['rev-parse', '--show-toplevel'])) !== cwd
139
- || git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== plan.branch
140
- || git(cwd, ['rev-parse', 'HEAD']) !== plan.baseHeadSha
141
- || git(cwd, ['rev-parse', `refs/heads/${plan.branch}`]) !== plan.baseHeadSha
142
- || git(cwd, ['rev-parse', `refs/remotes/origin/${plan.baseBranch}`]) !== plan.baseHeadSha) {
143
- throw new Error('legacy-branch-checkpoint-physical-mismatch');
144
- }
145
- const stateCurrent = safeRead(join(cwd, '.neocortex/state.json'));
146
- const storyCurrent = safeRead(join(cwd, projection.storyPath));
147
- if (![projection.stateBefore, projection.stateAfter].includes(stateCurrent)
148
- || ![projection.storyBefore, projection.storyAfter].includes(storyCurrent)) {
149
- throw new Error('legacy-branch-checkpoint-preimage-conflict');
150
- }
151
- const statuses = gitRaw(cwd, ['status', '--porcelain=v1', '-uall']);
152
- if (statuses.split('\n').filter(Boolean).some((line) => {
153
- if (!line.startsWith(' M '))
154
- return true;
155
- const path = line.slice(3);
156
- return path !== '.neocortex/state.json' && path !== projection.storyPath;
157
- }))
158
- throw new Error('legacy-branch-checkpoint-worktree-dirty');
159
- return { stateCurrent, storyCurrent };
160
- }
161
- async function privateDirectory(projectRoot) {
162
- return ensureGitLifecyclePrivateChildDirectory(await gitLifecycleRuntimeDirectory(projectRoot), 'legacy-story-branch-intents');
163
- }
164
- function journalName(storyId) { return `${digest(storyId)}.c01.json`; }
165
- function acceptedName(storyId) { return `${digest(storyId)}.c01.accepted.json`; }
166
- async function readPrivateJson(directory, name) {
167
- const path = join(directory, name);
168
- if (!existsSync(path))
169
- return null;
170
- await assertGitLifecyclePrivateFile(path, directory);
171
- const raw = safeRead(path);
172
- if (raw.length > 4096)
173
- throw new Error('legacy-branch-checkpoint-journal-invalid');
174
- return JSON.parse(raw);
175
- }
176
- async function writePrivateJson(directory, name, value) {
177
- await anchoredAtomicWriteFile(directory, name, `${JSON.stringify(value)}\n`);
178
- await assertGitLifecyclePrivateFile(join(directory, name), directory);
179
- }
180
- export async function acceptLegacyStoryBranchC01(options) {
181
- if (!Number.isSafeInteger(options.issueNumber) || options.issueNumber <= 0) {
182
- return fail('legacy-branch-issue-number-invalid');
183
- }
184
- const sessionId = `legacy-c01-${randomBytes(16).toString('hex')}`;
185
- const lock = await acquireGitLifecyclePhysicalIntegrationLock(options.projectRoot, {
186
- kind: 'direct', storyId: options.storyId, sessionId, idempotencyKey: sessionId,
187
- expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), persistent: false,
188
- });
189
- if (!lock.ok)
190
- return fail(lock.reasonCode);
191
- try {
192
- const completed = await readCompletedLegacyStoryBranchPlan(options);
193
- if (!completed.ok)
194
- return completed;
195
- const plan = completed.value;
196
- const sourceRoot = realpathSync(options.projectRoot);
197
- const projection = project(plan, options.issueNumber);
198
- const before = physical(plan, sourceRoot, projection);
199
- const repo = repository(sourceRoot);
200
- const directory = await privateDirectory(sourceRoot);
201
- const journal = {
202
- schemaVersion: 1, kind: 'legacy-story-c01-acceptance-intent', storyId: plan.storyId,
203
- planDigest: digest(JSON.stringify(plan)), repository: repo, issueNumber: options.issueNumber,
204
- stateBefore: digest(projection.stateBefore), stateAfter: digest(projection.stateAfter),
205
- storyBefore: digest(projection.storyBefore), storyAfter: digest(projection.storyAfter),
206
- };
207
- const existing = await readPrivateJson(directory, journalName(plan.storyId));
208
- if (existing && JSON.stringify(existing) !== JSON.stringify(journal)) {
209
- return fail('legacy-branch-checkpoint-journal-conflict');
210
- }
211
- if (!existing && (before.stateCurrent !== projection.stateBefore
212
- || before.storyCurrent !== projection.storyBefore)) {
213
- return fail('legacy-branch-checkpoint-unjournaled-drift');
214
- }
215
- const accepted = await readPrivateJson(directory, acceptedName(plan.storyId));
216
- if (accepted && JSON.stringify(accepted) !== JSON.stringify(journal)) {
217
- return fail('legacy-branch-checkpoint-accepted-conflict');
218
- }
219
- const issue = await (options.verifyIssue ?? ghIssueVerifier)(repo, options.issueNumber);
220
- validateIssue(issue, repo, plan.storyId, options.issueNumber, Boolean(accepted));
221
- if (!existing)
222
- await writePrivateJson(directory, journalName(plan.storyId), journal);
223
- const beforeWrite = physical(plan, sourceRoot, projection);
224
- if (accepted && (beforeWrite.stateCurrent !== projection.stateAfter
225
- || beforeWrite.storyCurrent !== projection.storyAfter)) {
226
- return fail('legacy-branch-checkpoint-accepted-physical-mismatch');
227
- }
228
- if (beforeWrite.stateCurrent === projection.stateBefore) {
229
- await anchoredCompareAndSwapFile(join(plan.worktreePath, '.neocortex'), 'state.json', projection.stateAfter, journal.stateBefore);
230
- await options.afterStatePersist?.();
231
- }
232
- const middle = physical(plan, sourceRoot, projection);
233
- if (middle.storyCurrent === projection.storyBefore) {
234
- await anchoredCompareAndSwapFile(join(plan.worktreePath, 'docs/stories'), `${plan.storyId}.story.md`, projection.storyAfter, journal.storyBefore);
235
- await options.afterStoryPersist?.();
236
- }
237
- const after = physical(plan, sourceRoot, projection);
238
- if (after.stateCurrent !== projection.stateAfter || after.storyCurrent !== projection.storyAfter) {
239
- return fail('legacy-branch-checkpoint-post-write-mismatch');
240
- }
241
- if (!accepted)
242
- await writePrivateJson(directory, acceptedName(plan.storyId), journal);
243
- return { ok: true, value: Object.freeze({
244
- schemaVersion: 1, kind: 'legacy-story-c01-checkpoint', storyId: plan.storyId,
245
- epicId: plan.epicId, branch: plan.branch, issueNumber: options.issueNumber,
246
- repository: repo, stateSha256: journal.stateAfter, storySha256: journal.storyAfter,
247
- reused: Boolean(accepted), checkpointAccepted: true, localOnly: true,
248
- }) };
249
- }
250
- catch (error) {
251
- const message = error instanceof Error ? error.message : '';
252
- return fail(message.startsWith('legacy-branch-') ? message
253
- : message.includes('secure-filesystem-cas-conflict') ? 'legacy-branch-checkpoint-write-raced'
254
- : 'legacy-branch-checkpoint-failed');
255
- }
256
- finally {
257
- await releaseGitLifecyclePhysicalIntegrationLock(lock.path, lock.owner).catch(() => undefined);
258
- }
259
- }
1
+ import{execFileSync as O}from"node:child_process";import{createHash as K,randomBytes as R}from"node:crypto";import{closeSync as G,constants as L,existsSync as Z,fstatSync as q,openSync as T,readFileSync as V,realpathSync as B}from"node:fs";import{join as k,resolve as Y}from"node:path";import{parseDocument as M}from"yaml";import{resolveBranchUnit as U}from"../../../shared/dist/yoloop/branch-unit.js";import{acquireGitLifecyclePhysicalIntegrationLock as Q,assertGitLifecyclePrivateFile as j,ensureGitLifecyclePrivateChildDirectory as X,gitLifecycleRuntimeDirectory as tt,releaseGitLifecyclePhysicalIntegrationLock as et}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as v}from"./git-lifecycle-step-ids.js";import{anchoredAtomicWriteFile as rt,anchoredCompareAndSwapFile as D}from"./secure-filesystem-boundary.js";import{readCompletedLegacyStoryBranchPlan as st}from"./legacy-story-branch-setup.js";function p(t){return{ok:!1,reasonCode:t}}function g(t){return K("sha256").update(t).digest("hex")}function S(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function l(t,c){return O("git",[...c],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],maxBuffer:4*1024*1024}).trim()}function C(t,c){return O("git",[...c],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],maxBuffer:4*1024*1024})}function $(t){const c=T(t,L.O_RDONLY|(L.O_NOFOLLOW??0));try{const e=q(c);if(!e.isFile()||e.size>2*1024*1024)throw new Error("legacy-branch-checkpoint-file-unsafe");return V(c,"utf8")}finally{G(c)}}function ct(t){const e=l(t,["remote","get-url","origin"]).match(/^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/);if(!e||e[1].includes("..")||e[2].includes(".."))throw new Error("legacy-branch-issue-repository-invalid");return`${e[1]}/${e[2]}`}async function nt(t,c){const e=O("gh",["issue","view",String(c),"--repo",t,"--json","number,title,state,url"],{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","pipe"],maxBuffer:16384});return JSON.parse(e)}function ot(t,c,e,s,r){if(t.number!==s||t.title!==`[YOLO] Story ${e} - Workflow Run`||t.state!=="OPEN"&&!(r&&t.state==="CLOSED")||t.url.toLowerCase()!==`https://github.com/${c}/issues/${s}`.toLowerCase())throw new Error("legacy-branch-issue-evidence-invalid")}function at(t,c){const e=t.worktreePath,s=C(e,["show","HEAD:.neocortex/state.json"]);if(g(s)!==t.stateSha256)throw new Error("legacy-branch-checkpoint-base-state-mismatch");const r=S(JSON.parse(s)),h=S(r?.stories),o=S(r?.epics),a=S(h?.[t.storyId]),f=S(o?.[t.epicId]),i=Object.entries(h??{}).flatMap(([d,z])=>{const P=S(z);return P?.epic_id===t.epicId?[{...P,id:d}]:[]});if(!f||f.id!==t.epicId||f.branch_mode==="epic"||U(f,i).mode!=="story"||!a||a.id!==t.storyId||a.epic_id!==t.epicId||a.status!=="backlog"&&a.status!=="ready_to_start"||!Array.isArray(a.steps_completed)||a.steps_completed.length!==0||a.branch_name||a.issue_number||a.last_step)throw new Error("legacy-branch-checkpoint-state-conflict");a.status="branch-ready",a.steps_completed=[v],a.last_step=v,a.branch_name=t.branch,a.issue_number=c;const u=`${JSON.stringify(r,null,2)}
2
+ `,b=`docs/stories/${t.storyId}.story.md`,y=C(e,["show",`HEAD:${b}`]),I=y.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);if(!I)throw new Error("legacy-branch-checkpoint-frontmatter-invalid");const n=M(I[1],{strict:!0,uniqueKeys:!0});if(n.errors.length>0||n.get("id")!==t.storyId||(n.get("epic_id")??n.get("epic"))!==t.epicId)throw new Error("legacy-branch-checkpoint-frontmatter-invalid");const w=S(n.toJS()),m=["stepsCompleted","steps_completed"].filter(d=>n.has(d)),A=["branchName","branch_name"].filter(d=>n.has(d)),_=["lastStep","last_step"].filter(d=>n.has(d)),N=["issueNumber","issue_number"].filter(d=>n.has(d));if(m.length>1||A.length>1||_.length>1||N.length>1||n.has("status")&&!["backlog","ready","ready_to_start"].includes(String(n.get("status")))||n.has("currentStatus")&&!["backlog","ready","ready_to_start"].includes(String(w?.currentStatus))||m.length===1&&(!Array.isArray(w?.[m[0]])||(w?.[m[0]]).length!==0)||A.length===1&&w?.[A[0]]!=null||_.length===1&&w?.[_[0]]!=null||N.length===1&&w?.[N[0]]!=null)throw new Error("legacy-branch-checkpoint-frontmatter-conflict");n.set("status","branch-ready"),n.has("currentStatus")&&n.set("currentStatus","branch-ready"),n.set(m[0]??"stepsCompleted",[v]),n.set(_[0]??"lastStep",v),n.set(A[0]??"branchName",t.branch),n.set(N[0]??"issueNumber",c);const F=`---
3
+ ${n.toString({lineWidth:0})}---
4
+ ${y.slice(I[0].length)}`;return{storyPath:b,stateBefore:s,stateAfter:u,storyBefore:y,storyAfter:F}}function E(t,c,e){const s=B(t.worktreePath);if(t.epicId!==t.storyId.split(".")[0]||t.branch!==`story/${t.epicId}/${t.storyId}`||!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(t.epicId)||!l(c,["check-ref-format","--branch",t.branch])||!l(c,["check-ref-format","--branch",t.baseBranch]))throw new Error("legacy-branch-checkpoint-plan-invalid");const r=i=>B(Y(i,l(i,["rev-parse","--git-common-dir"]))),h=l(c,["worktree","list","--porcelain"]).split(/\n\n+/).filter(i=>i.split(`
5
+ `).includes(`branch refs/heads/${t.branch}`));if(s!==t.worktreePath||h.length!==1||!h[0].split(`
6
+ `).includes(`worktree ${s}`)||h[0].split(`
7
+ `).some(i=>i.startsWith("locked")||i.startsWith("prunable"))||r(s)!==r(c)||B(l(s,["rev-parse","--show-toplevel"]))!==s||l(s,["symbolic-ref","--quiet","--short","HEAD"])!==t.branch||l(s,["rev-parse","HEAD"])!==t.baseHeadSha||l(s,["rev-parse",`refs/heads/${t.branch}`])!==t.baseHeadSha||l(s,["rev-parse",`refs/remotes/origin/${t.baseBranch}`])!==t.baseHeadSha)throw new Error("legacy-branch-checkpoint-physical-mismatch");const o=$(k(s,".neocortex/state.json")),a=$(k(s,e.storyPath));if(![e.stateBefore,e.stateAfter].includes(o)||![e.storyBefore,e.storyAfter].includes(a))throw new Error("legacy-branch-checkpoint-preimage-conflict");if(C(s,["status","--porcelain=v1","-uall"]).split(`
8
+ `).filter(Boolean).some(i=>{if(!i.startsWith(" M "))return!0;const u=i.slice(3);return u!==".neocortex/state.json"&&u!==e.storyPath}))throw new Error("legacy-branch-checkpoint-worktree-dirty");return{stateCurrent:o,storyCurrent:a}}async function it(t){return X(await tt(t),"legacy-story-branch-intents")}function x(t){return`${g(t)}.c01.json`}function J(t){return`${g(t)}.c01.accepted.json`}async function H(t,c){const e=k(t,c);if(!Z(e))return null;await j(e,t);const s=$(e);if(s.length>4096)throw new Error("legacy-branch-checkpoint-journal-invalid");return JSON.parse(s)}async function W(t,c,e){await rt(t,c,`${JSON.stringify(e)}
9
+ `),await j(k(t,c),t)}async function wt(t){if(!Number.isSafeInteger(t.issueNumber)||t.issueNumber<=0)return p("legacy-branch-issue-number-invalid");const c=`legacy-c01-${R(16).toString("hex")}`,e=await Q(t.projectRoot,{kind:"direct",storyId:t.storyId,sessionId:c,idempotencyKey:c,expiresAt:new Date(Date.now()+5*6e4).toISOString(),persistent:!1});if(!e.ok)return p(e.reasonCode);try{const s=await st(t);if(!s.ok)return s;const r=s.value,h=B(t.projectRoot),o=at(r,t.issueNumber),a=E(r,h,o),f=ct(h),i=await it(h),u={schemaVersion:1,kind:"legacy-story-c01-acceptance-intent",storyId:r.storyId,planDigest:g(JSON.stringify(r)),repository:f,issueNumber:t.issueNumber,stateBefore:g(o.stateBefore),stateAfter:g(o.stateAfter),storyBefore:g(o.storyBefore),storyAfter:g(o.storyAfter)},b=await H(i,x(r.storyId));if(b&&JSON.stringify(b)!==JSON.stringify(u))return p("legacy-branch-checkpoint-journal-conflict");if(!b&&(a.stateCurrent!==o.stateBefore||a.storyCurrent!==o.storyBefore))return p("legacy-branch-checkpoint-unjournaled-drift");const y=await H(i,J(r.storyId));if(y&&JSON.stringify(y)!==JSON.stringify(u))return p("legacy-branch-checkpoint-accepted-conflict");const I=await(t.verifyIssue??nt)(f,t.issueNumber);ot(I,f,r.storyId,t.issueNumber,!!y),b||await W(i,x(r.storyId),u);const n=E(r,h,o);if(y&&(n.stateCurrent!==o.stateAfter||n.storyCurrent!==o.storyAfter))return p("legacy-branch-checkpoint-accepted-physical-mismatch");n.stateCurrent===o.stateBefore&&(await D(k(r.worktreePath,".neocortex"),"state.json",o.stateAfter,u.stateBefore),await t.afterStatePersist?.()),E(r,h,o).storyCurrent===o.storyBefore&&(await D(k(r.worktreePath,"docs/stories"),`${r.storyId}.story.md`,o.storyAfter,u.storyBefore),await t.afterStoryPersist?.());const m=E(r,h,o);return m.stateCurrent!==o.stateAfter||m.storyCurrent!==o.storyAfter?p("legacy-branch-checkpoint-post-write-mismatch"):(y||await W(i,J(r.storyId),u),{ok:!0,value:Object.freeze({schemaVersion:1,kind:"legacy-story-c01-checkpoint",storyId:r.storyId,epicId:r.epicId,branch:r.branch,issueNumber:t.issueNumber,repository:f,stateSha256:u.stateAfter,storySha256:u.storyAfter,reused:!!y,checkpointAccepted:!0,localOnly:!0})})}catch(s){const r=s instanceof Error?s.message:"";return p(r.startsWith("legacy-branch-")?r:r.includes("secure-filesystem-cas-conflict")?"legacy-branch-checkpoint-write-raced":"legacy-branch-checkpoint-failed")}finally{await et(e.path,e.owner).catch(()=>{})}}export{wt as acceptLegacyStoryBranchC01};