@ornexus/neocortex 4.61.4 → 4.61.6

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 (254) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +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 -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.js +1 -260
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  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 -364
  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 +148 -7822
  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 -174
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  76. package/packages/client/dist/commands/story-worktree.js +5 -258
  77. package/packages/client/dist/config/host-auth-broker.js +1 -60
  78. package/packages/client/dist/config/host-auth-reference.js +1 -93
  79. package/packages/client/dist/config/profile-directory.js +1 -13
  80. package/packages/client/dist/config/resolver-selection.js +1 -278
  81. package/packages/client/dist/config/secure-config.js +12 -281
  82. package/packages/client/dist/config.js +2 -224
  83. package/packages/client/dist/constants.js +1 -25
  84. package/packages/client/dist/context/context-collector.js +2 -222
  85. package/packages/client/dist/context/context-sanitizer.js +1 -145
  86. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  87. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  88. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  89. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  90. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  91. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  92. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  93. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  94. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  95. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  96. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  97. package/packages/client/dist/continuity/outbox.js +1 -117
  98. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  99. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  100. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  101. package/packages/client/dist/errors/error-messages.js +2 -258
  102. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  103. package/packages/client/dist/evidence/collector.js +1 -347
  104. package/packages/client/dist/evidence/index.js +1 -1
  105. package/packages/client/dist/evidence/types.js +0 -2
  106. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  107. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  108. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  109. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  110. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
  111. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
  112. package/packages/client/dist/git/epic-operational-state.js +2 -672
  113. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  114. package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
  115. package/packages/client/dist/git/git-lifecycle-store.js +8 -2500
  116. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  117. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  118. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  119. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  120. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  121. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  122. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  123. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  124. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  125. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  126. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  127. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  128. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  129. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  130. package/packages/client/dist/i18n/first-run.js +2 -60
  131. package/packages/client/dist/index.js +1 -50
  132. package/packages/client/dist/invocation/invoke-input.js +1 -24
  133. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  134. package/packages/client/dist/license/index.js +1 -5
  135. package/packages/client/dist/license/license-client.js +1 -337
  136. package/packages/client/dist/machine/fingerprint.js +2 -163
  137. package/packages/client/dist/machine/index.js +1 -5
  138. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  139. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  140. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  141. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  142. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  143. package/packages/client/dist/migrations/project-identity.js +7 -493
  144. package/packages/client/dist/migrations/state-json.js +4 -393
  145. package/packages/client/dist/policy/architecture-policy.js +2 -184
  146. package/packages/client/dist/policy/index.js +1 -7
  147. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  148. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  149. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  150. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  151. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  152. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  153. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  154. package/packages/client/dist/private-execution/delivery.js +13 -410
  155. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  156. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  157. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  158. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  159. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  160. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  161. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  162. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  163. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  164. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  165. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  166. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  167. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  168. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  169. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  170. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  171. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  172. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  173. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  174. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  175. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  176. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  177. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  178. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  179. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  180. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  181. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  182. package/packages/client/dist/private-execution/session-lease.js +1 -63
  183. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  184. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  185. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  186. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  187. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  188. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  189. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  190. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  191. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  192. package/packages/client/dist/resilience/index.js +1 -8
  193. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  194. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  195. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  196. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  197. package/packages/client/dist/runner/binary.js +1 -404
  198. package/packages/client/dist/runner/cli.js +17 -1571
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.js +1 -85
  202. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  203. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  204. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  205. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  206. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  207. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  208. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  209. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  210. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  211. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  212. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  213. package/packages/client/dist/runner/headless/resolver.js +1 -231
  214. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  215. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  216. package/packages/client/dist/runner/headless/types.js +2 -575
  217. package/packages/client/dist/runner/host-capacity.js +1 -59
  218. package/packages/client/dist/runner/local-console.js +13 -396
  219. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  220. package/packages/client/dist/runner/project-identity.js +1 -106
  221. package/packages/client/dist/runner/scheduler.js +7 -995
  222. package/packages/client/dist/runner-cli.js +2 -18
  223. package/packages/client/dist/state/invocation-shape.js +1 -13
  224. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  225. package/packages/client/dist/state/state-json-repair.js +3 -785
  226. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  227. package/packages/client/dist/telemetry/index.js +1 -5
  228. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  229. package/packages/client/dist/tier/index.js +1 -5
  230. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  231. package/packages/client/dist/types/index.js +1 -38
  232. package/packages/client/dist/version.js +1 -27
  233. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  234. package/packages/client/dist/yolo/change-evidence-collector.js +1 -245
  235. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  236. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  237. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  238. package/packages/client/dist/yoloop/index.js +1 -8
  239. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  240. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  241. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  242. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  243. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  244. package/targets-stubs/antigravity/gemini.md +1 -1
  245. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  246. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  247. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  248. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  249. package/targets-stubs/claude-code/neocortex.md +2 -2
  250. package/targets-stubs/codex/AGENTS.md +1 -1
  251. package/targets-stubs/cursor/agent.md +2 -2
  252. package/targets-stubs/gemini-cli/agent.md +2 -2
  253. package/targets-stubs/opencode/neocortex-root.md +1 -1
  254. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,393 +1,4 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, unlinkSync, } from 'node:fs';
3
- import { dirname, join, resolve } from 'node:path';
4
- import { assertStateMigrationPlanV1, assertStateMigrationReceiptV1, planStateMigration, stateMigrationDigest, STATE_MIGRATION_RECEIPT_SCHEMA, StateMigrationHardStopError, } from '../../../shared/dist/state/index.js';
5
- import { atomicReplaceUtf8, durableCreateUtf8, fsyncDirectoryBestEffort, recoverAtomicReplaceUtf8, } from '../fs/atomic-state-replace.js';
6
- const STATE_RELATIVE_PATH = join('.neocortex', 'state.json');
7
- const MANIFEST_RELATIVE_PATH = join('.neocortex', 'state-migration.json');
8
- const LOCK_RELATIVE_PATH = join('.neocortex', 'state-migration.lock');
9
- export const STATE_MIGRATION_INPUT_LIMIT_BYTES = 4 * 1024 * 1024;
10
- export class StateMigrationApplyError extends Error {
11
- reasonCode;
12
- receipt;
13
- constructor(reasonCode, message = reasonCode, receipt) {
14
- super(message);
15
- this.reasonCode = reasonCode;
16
- this.receipt = receipt;
17
- this.name = 'StateMigrationApplyError';
18
- }
19
- }
20
- const sha256Bytes = (value) => createHash('sha256').update(value).digest('hex');
21
- const stateRaw = (state) => `${JSON.stringify(state, null, 2)}\n`;
22
- function safeRoot(projectRoot) {
23
- let root;
24
- try {
25
- root = realpathSync(resolve(projectRoot));
26
- }
27
- catch {
28
- throw new StateMigrationApplyError('state_migration_root_invalid');
29
- }
30
- if (!statSync(root).isDirectory())
31
- throw new StateMigrationApplyError('state_migration_root_invalid');
32
- for (const relative of ['.neocortex', STATE_RELATIVE_PATH, MANIFEST_RELATIVE_PATH]) {
33
- const path = join(root, relative);
34
- if (!existsSync(path))
35
- continue;
36
- const stat = lstatSync(path);
37
- if (stat.isSymbolicLink() || (relative !== '.neocortex' && !stat.isFile()) || (relative === '.neocortex' && !stat.isDirectory())) {
38
- throw new StateMigrationApplyError('state_migration_symlink_or_type_rejected');
39
- }
40
- }
41
- return root;
42
- }
43
- function parseState(raw) {
44
- try {
45
- const parsed = JSON.parse(raw);
46
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
47
- return parsed;
48
- }
49
- catch { /* normalized below */ }
50
- throw new StateMigrationApplyError('state_migration_state_corrupt');
51
- }
52
- function readBoundedState(root) {
53
- const statePath = join(root, STATE_RELATIVE_PATH);
54
- if (!existsSync(statePath))
55
- throw new StateMigrationApplyError('state_migration_state_missing');
56
- const size = statSync(statePath).size;
57
- if (size > STATE_MIGRATION_INPUT_LIMIT_BYTES)
58
- throw new StateMigrationApplyError('state_migration_input_too_large');
59
- const raw = readFileSync(statePath, 'utf8');
60
- const bytes = Buffer.byteLength(raw, 'utf8');
61
- if (bytes !== size || bytes > STATE_MIGRATION_INPUT_LIMIT_BYTES) {
62
- throw new StateMigrationApplyError('state_migration_source_changed');
63
- }
64
- return { state: parseState(raw), raw, digest: sha256Bytes(raw), bytes };
65
- }
66
- export function collectStateMigrationAuthority(projectRoot) {
67
- const source = readBoundedState(safeRoot(projectRoot));
68
- let decision;
69
- try {
70
- decision = planStateMigration(source.state);
71
- }
72
- catch (error) {
73
- if (error instanceof StateMigrationHardStopError)
74
- throw new StateMigrationApplyError(error.reasonCode, error.message);
75
- throw error;
76
- }
77
- const target = decision.kind === 'migrate' ? decision.plan.targetState : source.state;
78
- const count = (record, key) => {
79
- const value = record[key];
80
- return value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value).length : 0;
81
- };
82
- const plan = decision.kind === 'migrate'
83
- ? (({ targetState: _privateTargetState, ...publicPlan }) => publicPlan)(decision.plan)
84
- : null;
85
- return Object.freeze({
86
- schemaVersion: 'StateMigrationAuthority/1.0',
87
- sourceByteDigest: source.digest,
88
- sourceCanonicalHash: decision.kind === 'migrate' ? decision.plan.sourceCanonicalHash : decision.sourceCanonicalHash,
89
- sourceByteLength: source.bytes,
90
- before: { epics: count(source.state, 'epics'), stories: count(source.state, 'stories') },
91
- after: { epics: count(target, 'epics'), stories: count(target, 'stories') },
92
- outcome: decision.kind,
93
- plan,
94
- publicSafe: true,
95
- });
96
- }
97
- export function readStateMigrationSourceSnapshot(projectRoot) {
98
- const source = readBoundedState(safeRoot(projectRoot));
99
- return Object.freeze({
100
- state: source.state,
101
- raw: source.raw,
102
- byteDigest: source.digest,
103
- byteLength: source.bytes,
104
- });
105
- }
106
- /**
107
- * Restore one migration preimage only while both current postimage and backup
108
- * bytes remain exact. This is intentionally narrower than a general reset and
109
- * never removes the backup or migration history.
110
- */
111
- export function restoreStateMigrationPreimage(input) {
112
- if (!/^smig_[a-f0-9]{32}$/.test(input.operationId)
113
- || !/^[a-f0-9]{64}$/.test(input.expectedCurrentDigest)
114
- || !/^[a-f0-9]{64}$/.test(input.expectedBackupDigest)) {
115
- throw new StateMigrationApplyError('state_migration_rollback_binding_invalid');
116
- }
117
- const root = safeRoot(input.projectRoot);
118
- const release = claimLock(root);
119
- try {
120
- const statePath = join(root, STATE_RELATIVE_PATH);
121
- const backupPath = join(root, '.neocortex', `state.json.migration-backup-${input.operationId}`);
122
- if (!existsSync(backupPath))
123
- throw new StateMigrationApplyError('state_migration_backup_missing');
124
- const backupInfo = lstatSync(backupPath);
125
- if (!backupInfo.isFile() || backupInfo.isSymbolicLink()) {
126
- throw new StateMigrationApplyError('state_migration_backup_conflict');
127
- }
128
- const currentRaw = readFileSync(statePath, 'utf8');
129
- const backupRaw = readFileSync(backupPath, 'utf8');
130
- if (sha256Bytes(currentRaw) !== input.expectedCurrentDigest) {
131
- throw new StateMigrationApplyError('state_migration_rollback_postimage_conflict');
132
- }
133
- if (sha256Bytes(backupRaw) !== input.expectedBackupDigest) {
134
- throw new StateMigrationApplyError('state_migration_backup_conflict');
135
- }
136
- atomicReplaceUtf8(statePath, backupRaw);
137
- if (sha256Bytes(readFileSync(statePath)) !== input.expectedBackupDigest) {
138
- throw new StateMigrationApplyError('state_migration_rollback_failed');
139
- }
140
- return { restoredDigest: input.expectedBackupDigest, backupPreserved: true };
141
- }
142
- finally {
143
- release();
144
- }
145
- }
146
- function claimLock(root) {
147
- const lockPath = join(root, LOCK_RELATIVE_PATH);
148
- mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
149
- const ownerToken = randomUUID();
150
- const ownerContents = `${process.pid}:${ownerToken}\n`;
151
- const acquire = () => {
152
- const ownerPath = `${lockPath}.${process.pid}.${randomUUID()}.owner`;
153
- durableCreateUtf8(ownerPath, ownerContents);
154
- try {
155
- linkSync(ownerPath, lockPath);
156
- }
157
- finally {
158
- try {
159
- unlinkSync(ownerPath);
160
- }
161
- catch { /* orphan owners have no authority */ }
162
- fsyncDirectoryBestEffort(dirname(lockPath));
163
- }
164
- };
165
- try {
166
- acquire();
167
- }
168
- catch (error) {
169
- if (error.code !== 'EEXIST')
170
- throw new StateMigrationApplyError('state_migration_lock_failed');
171
- const stat = lstatSync(lockPath);
172
- if (stat.isSymbolicLink() || !stat.isFile())
173
- throw new StateMigrationApplyError('state_migration_lock_corrupt');
174
- const owner = readFileSync(lockPath, 'utf8');
175
- const ownerMatch = owner.match(/^([1-9][0-9]*):([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\n$/i);
176
- if (!ownerMatch || owner.length > 64)
177
- throw new StateMigrationApplyError('state_migration_lock_corrupt');
178
- let alive = true;
179
- try {
180
- process.kill(Number(ownerMatch[1]), 0);
181
- }
182
- catch (probe) {
183
- alive = probe.code !== 'ESRCH';
184
- }
185
- if (alive)
186
- throw new StateMigrationApplyError('state_migration_locked');
187
- try {
188
- unlinkSync(lockPath);
189
- acquire();
190
- }
191
- catch {
192
- throw new StateMigrationApplyError('state_migration_locked');
193
- }
194
- }
195
- return () => {
196
- try {
197
- if (readFileSync(lockPath, 'utf8') !== ownerContents)
198
- return;
199
- unlinkSync(lockPath);
200
- fsyncDirectoryBestEffort(dirname(lockPath));
201
- }
202
- catch { /* cleanup is best effort; never delete an unproven foreign lock */ }
203
- };
204
- }
205
- function parseManifest(root) {
206
- const path = join(root, MANIFEST_RELATIVE_PATH);
207
- recoverAtomicReplaceUtf8(path);
208
- if (!existsSync(path))
209
- return null;
210
- let parsed;
211
- try {
212
- parsed = JSON.parse(readFileSync(path, 'utf8'));
213
- }
214
- catch {
215
- throw new StateMigrationApplyError('state_migration_manifest_corrupt');
216
- }
217
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
218
- throw new StateMigrationApplyError('state_migration_manifest_corrupt');
219
- const value = parsed;
220
- if (value.schemaVersion !== 1
221
- || typeof value.operationId !== 'string' || !/^smig_[a-f0-9]{32}$/.test(value.operationId)
222
- || !['prepared', 'applied', 'rolled-back'].includes(String(value.phase))
223
- || typeof value.sourceCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.sourceCanonicalHash)
224
- || typeof value.sourceByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(value.sourceByteDigest)
225
- || typeof value.targetCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.targetCanonicalHash)
226
- || typeof value.targetByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(value.targetByteDigest)
227
- || !Number.isSafeInteger(value.migratedEpicCount) || (value.migratedEpicCount ?? -1) < 0
228
- || !Number.isSafeInteger(value.migratedStoryCount) || (value.migratedStoryCount ?? -1) < 0
229
- || !Number.isSafeInteger(value.preservedUnknownFieldCount) || (value.preservedUnknownFieldCount ?? -1) < 0
230
- || typeof value.backupPath !== 'string'
231
- || value.backupPath !== join('.neocortex', `state.json.migration-backup-${value.operationId}`)) {
232
- throw new StateMigrationApplyError('state_migration_manifest_corrupt');
233
- }
234
- return value;
235
- }
236
- function writeManifest(root, manifest) {
237
- atomicReplaceUtf8(join(root, MANIFEST_RELATIVE_PATH), `${JSON.stringify(manifest, null, 2)}\n`);
238
- }
239
- function receipt(outcome, operationId, sourceBytesHash, targetBytesHash, sourceCanonicalHash, targetCanonicalHash, backupHash, rollbackStatus, migratedEpicCount, migratedStoryCount, preservedUnknownFieldCount, reasonCodes) {
240
- const value = {
241
- schemaVersion: STATE_MIGRATION_RECEIPT_SCHEMA,
242
- operationId,
243
- outcome,
244
- sourceBytesHash,
245
- targetBytesHash,
246
- sourceCanonicalHash,
247
- targetCanonicalHash,
248
- backupHash,
249
- rollbackStatus,
250
- migratedEpicCount,
251
- migratedStoryCount,
252
- preservedUnknownFieldCount,
253
- reasonCodes,
254
- publicSafe: true,
255
- };
256
- assertStateMigrationReceiptV1(value);
257
- return value;
258
- }
259
- export function previewStateMigration(projectRoot) {
260
- const root = safeRoot(projectRoot);
261
- let decision;
262
- try {
263
- decision = planStateMigration(readBoundedState(root).state);
264
- }
265
- catch (error) {
266
- if (error instanceof StateMigrationHardStopError)
267
- throw new StateMigrationApplyError(error.reasonCode, error.message);
268
- throw error;
269
- }
270
- return decision.kind === 'migrate' ? decision.plan : null;
271
- }
272
- /** Apply one shared plan under a client-owned lock, byte CAS and durable backup. */
273
- export function applyStateMigration(projectRoot, expectedPlan, hooks = {}) {
274
- const root = safeRoot(projectRoot);
275
- const release = claimLock(root);
276
- try {
277
- const statePath = join(root, STATE_RELATIVE_PATH);
278
- try {
279
- recoverAtomicReplaceUtf8(statePath);
280
- }
281
- catch {
282
- throw new StateMigrationApplyError('state_migration_atomic_recovery_failed');
283
- }
284
- if (!existsSync(statePath))
285
- throw new StateMigrationApplyError('state_migration_state_missing');
286
- const initialRaw = readBoundedState(root).raw;
287
- if (expectedPlan?.sourceByteDigest && sha256Bytes(initialRaw) !== expectedPlan.sourceByteDigest) {
288
- throw new StateMigrationApplyError('state_migration_expected_bytes_conflict');
289
- }
290
- let decision;
291
- try {
292
- decision = planStateMigration(parseState(initialRaw));
293
- }
294
- catch (error) {
295
- if (error instanceof StateMigrationHardStopError)
296
- throw new StateMigrationApplyError(error.reasonCode, error.message);
297
- throw error;
298
- }
299
- const existing = parseManifest(root);
300
- const currentBytesHash = sha256Bytes(initialRaw);
301
- if (decision.kind === 'unchanged') {
302
- if (expectedPlan && decision.sourceCanonicalHash !== expectedPlan.targetCanonicalHash) {
303
- throw new StateMigrationApplyError('state_migration_expected_plan_conflict');
304
- }
305
- if (existing && existing.targetCanonicalHash === decision.sourceCanonicalHash) {
306
- if (existing.targetByteDigest !== currentBytesHash) {
307
- throw new StateMigrationApplyError('state_migration_state_drift');
308
- }
309
- if (existing.phase === 'prepared')
310
- writeManifest(root, { ...existing, phase: 'applied' });
311
- if (existing.phase === 'rolled-back')
312
- throw new StateMigrationApplyError('state_migration_state_drift');
313
- return receipt('already-applied', existing.operationId, existing.sourceByteDigest, existing.targetByteDigest, existing.sourceCanonicalHash, existing.targetCanonicalHash, existing.sourceByteDigest, 'not-required', existing.migratedEpicCount, existing.migratedStoryCount, existing.preservedUnknownFieldCount, ['migration_replay_verified']);
314
- }
315
- if (existing)
316
- throw new StateMigrationApplyError('state_migration_state_drift');
317
- return receipt('already-applied', expectedPlan?.operationId ?? 'smig_00000000000000000000000000000000', currentBytesHash, currentBytesHash, decision.sourceCanonicalHash, decision.sourceCanonicalHash, null, 'not-required', 0, 0, 0, ['canonical_state_unchanged']);
318
- }
319
- const plan = decision.plan;
320
- assertStateMigrationPlanV1(plan);
321
- if (expectedPlan && (expectedPlan.operationId !== plan.operationId
322
- || expectedPlan.sourceCanonicalHash !== plan.sourceCanonicalHash
323
- || expectedPlan.targetCanonicalHash !== plan.targetCanonicalHash)) {
324
- throw new StateMigrationApplyError('state_migration_expected_plan_conflict');
325
- }
326
- if (existing && existing.operationId !== plan.operationId) {
327
- throw new StateMigrationApplyError('state_migration_operation_conflict');
328
- }
329
- const sourceByteDigest = currentBytesHash;
330
- const targetRaw = stateRaw(plan.targetState);
331
- const targetByteDigest = sha256Bytes(targetRaw);
332
- const backupPath = join('.neocortex', `state.json.migration-backup-${plan.operationId}`);
333
- const backupAbsolute = join(root, backupPath);
334
- if (existsSync(backupAbsolute)) {
335
- const backupStat = lstatSync(backupAbsolute);
336
- if (backupStat.isSymbolicLink() || !backupStat.isFile() || sha256Bytes(readFileSync(backupAbsolute)) !== sourceByteDigest) {
337
- throw new StateMigrationApplyError('state_migration_backup_conflict');
338
- }
339
- }
340
- else {
341
- durableCreateUtf8(backupAbsolute, initialRaw);
342
- }
343
- const manifest = {
344
- schemaVersion: 1,
345
- operationId: plan.operationId,
346
- phase: 'prepared',
347
- sourceCanonicalHash: plan.sourceCanonicalHash,
348
- sourceByteDigest,
349
- targetCanonicalHash: plan.targetCanonicalHash,
350
- targetByteDigest,
351
- migratedEpicCount: plan.migratedEpicIds.length,
352
- migratedStoryCount: plan.migratedStoryIds.length,
353
- preservedUnknownFieldCount: plan.preservedUnknownFieldCount,
354
- backupPath,
355
- };
356
- writeManifest(root, manifest);
357
- hooks.afterPrepared?.(statePath);
358
- if (sha256Bytes(readFileSync(statePath)) !== sourceByteDigest) {
359
- throw new StateMigrationApplyError('state_migration_source_cas_conflict');
360
- }
361
- try {
362
- atomicReplaceUtf8(statePath, targetRaw);
363
- hooks.afterReplace?.(statePath);
364
- const installedRaw = readFileSync(statePath, 'utf8');
365
- const installed = parseState(installedRaw);
366
- if (sha256Bytes(installedRaw) !== targetByteDigest || stateMigrationDigest(installed) !== plan.targetCanonicalHash) {
367
- throw new Error('readback-digest-mismatch');
368
- }
369
- writeManifest(root, { ...manifest, phase: 'applied' });
370
- }
371
- catch (error) {
372
- try {
373
- const backupRaw = readFileSync(backupAbsolute, 'utf8');
374
- if (sha256Bytes(backupRaw) !== sourceByteDigest)
375
- throw new Error('rollback-backup-digest-mismatch');
376
- atomicReplaceUtf8(statePath, backupRaw);
377
- if (sha256Bytes(readFileSync(statePath)) !== sourceByteDigest)
378
- throw new Error('rollback-digest-mismatch');
379
- writeManifest(root, { ...manifest, phase: 'rolled-back' });
380
- }
381
- catch {
382
- const unverified = receipt('blocked', plan.operationId, sourceByteDigest, targetByteDigest, plan.sourceCanonicalHash, plan.targetCanonicalHash, sourceByteDigest, 'unverified', plan.migratedEpicIds.length, plan.migratedStoryIds.length, plan.preservedUnknownFieldCount, ['apply_failed', 'rollback_unverified']);
383
- throw new StateMigrationApplyError('state_migration_rollback_failed', String(error), unverified);
384
- }
385
- const rolledBack = receipt('blocked', plan.operationId, sourceByteDigest, targetByteDigest, plan.sourceCanonicalHash, plan.targetCanonicalHash, sourceByteDigest, 'restored', plan.migratedEpicIds.length, plan.migratedStoryIds.length, plan.preservedUnknownFieldCount, ['apply_failed', 'rollback_verified']);
386
- throw new StateMigrationApplyError('state_migration_apply_rolled_back', String(error), rolledBack);
387
- }
388
- return receipt('applied', plan.operationId, sourceByteDigest, targetByteDigest, plan.sourceCanonicalHash, plan.targetCanonicalHash, sourceByteDigest, 'not-required', plan.migratedEpicIds.length, plan.migratedStoryIds.length, plan.preservedUnknownFieldCount, ['lock_acquired', 'source_cas_verified', 'backup_verified', 'atomic_replace_verified']);
389
- }
390
- finally {
391
- release();
392
- }
393
- }
1
+ import{createHash as z,randomUUID as U}from"node:crypto";import{existsSync as m,linkSync as J,lstatSync as I,mkdirSync as G,readFileSync as f,realpathSync as K,statSync as L,unlinkSync as T}from"node:fs";import{dirname as x,join as p,resolve as X}from"node:path";import{assertStateMigrationPlanV1 as Y,assertStateMigrationReceiptV1 as Q,planStateMigration as M,stateMigrationDigest as W,STATE_MIGRATION_RECEIPT_SCHEMA as Z,StateMigrationHardStopError as R}from"../../../shared/dist/state/index.js";import{atomicReplaceUtf8 as H,durableCreateUtf8 as N,fsyncDirectoryBestEffort as O,recoverAtomicReplaceUtf8 as P}from"../fs/atomic-state-replace.js";const E=p(".neocortex","state.json"),$=p(".neocortex","state-migration.json"),tt=p(".neocortex","state-migration.lock"),V=4*1024*1024;class a extends Error{reasonCode;receipt;constructor(t,r=t,e){super(r),this.reasonCode=t,this.receipt=e,this.name="StateMigrationApplyError"}}const _=o=>z("sha256").update(o).digest("hex"),et=o=>`${JSON.stringify(o,null,2)}
2
+ `;function b(o){let t;try{t=K(X(o))}catch{throw new a("state_migration_root_invalid")}if(!L(t).isDirectory())throw new a("state_migration_root_invalid");for(const r of[".neocortex",E,$]){const e=p(t,r);if(!m(e))continue;const s=I(e);if(s.isSymbolicLink()||r!==".neocortex"&&!s.isFile()||r===".neocortex"&&!s.isDirectory())throw new a("state_migration_symlink_or_type_rejected")}return t}function j(o){try{const t=JSON.parse(o);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}throw new a("state_migration_state_corrupt")}function v(o){const t=p(o,E);if(!m(t))throw new a("state_migration_state_missing");const r=L(t).size;if(r>V)throw new a("state_migration_input_too_large");const e=f(t,"utf8"),s=Buffer.byteLength(e,"utf8");if(s!==r||s>V)throw new a("state_migration_source_changed");return{state:j(e),raw:e,digest:_(e),bytes:s}}function ct(o){const t=v(b(o));let r;try{r=M(t.state)}catch(l){throw l instanceof R?new a(l.reasonCode,l.message):l}const e=r.kind==="migrate"?r.plan.targetState:t.state,s=(l,g)=>{const i=l[g];return i&&typeof i=="object"&&!Array.isArray(i)?Object.keys(i).length:0},c=r.kind==="migrate"?(({targetState:l,...g})=>g)(r.plan):null;return Object.freeze({schemaVersion:"StateMigrationAuthority/1.0",sourceByteDigest:t.digest,sourceCanonicalHash:r.kind==="migrate"?r.plan.sourceCanonicalHash:r.sourceCanonicalHash,sourceByteLength:t.bytes,before:{epics:s(t.state,"epics"),stories:s(t.state,"stories")},after:{epics:s(e,"epics"),stories:s(e,"stories")},outcome:r.kind,plan:c,publicSafe:!0})}function lt(o){const t=v(b(o));return Object.freeze({state:t.state,raw:t.raw,byteDigest:t.digest,byteLength:t.bytes})}function gt(o){if(!/^smig_[a-f0-9]{32}$/.test(o.operationId)||!/^[a-f0-9]{64}$/.test(o.expectedCurrentDigest)||!/^[a-f0-9]{64}$/.test(o.expectedBackupDigest))throw new a("state_migration_rollback_binding_invalid");const t=b(o.projectRoot),r=q(t);try{const e=p(t,E),s=p(t,".neocortex",`state.json.migration-backup-${o.operationId}`);if(!m(s))throw new a("state_migration_backup_missing");const c=I(s);if(!c.isFile()||c.isSymbolicLink())throw new a("state_migration_backup_conflict");const l=f(e,"utf8"),g=f(s,"utf8");if(_(l)!==o.expectedCurrentDigest)throw new a("state_migration_rollback_postimage_conflict");if(_(g)!==o.expectedBackupDigest)throw new a("state_migration_backup_conflict");if(H(e,g),_(f(e))!==o.expectedBackupDigest)throw new a("state_migration_rollback_failed");return{restoredDigest:o.expectedBackupDigest,backupPreserved:!0}}finally{r()}}function q(o){const t=p(o,tt);G(x(t),{recursive:!0,mode:448});const r=U(),e=`${process.pid}:${r}
3
+ `,s=()=>{const c=`${t}.${process.pid}.${U()}.owner`;N(c,e);try{J(c,t)}finally{try{T(c)}catch{}O(x(t))}};try{s()}catch(c){if(c.code!=="EEXIST")throw new a("state_migration_lock_failed");const l=I(t);if(l.isSymbolicLink()||!l.isFile())throw new a("state_migration_lock_corrupt");const g=f(t,"utf8"),i=g.match(/^([1-9][0-9]*):([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\n$/i);if(!i||g.length>64)throw new a("state_migration_lock_corrupt");let h=!0;try{process.kill(Number(i[1]),0)}catch(n){h=n.code!=="ESRCH"}if(h)throw new a("state_migration_locked");try{T(t),s()}catch{throw new a("state_migration_locked")}}return()=>{try{if(f(t,"utf8")!==e)return;T(t),O(x(t))}catch{}}}function rt(o){const t=p(o,$);if(P(t),!m(t))return null;let r;try{r=JSON.parse(f(t,"utf8"))}catch{throw new a("state_migration_manifest_corrupt")}if(!r||typeof r!="object"||Array.isArray(r))throw new a("state_migration_manifest_corrupt");const e=r;if(e.schemaVersion!==1||typeof e.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(e.operationId)||!["prepared","applied","rolled-back"].includes(String(e.phase))||typeof e.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(e.sourceCanonicalHash)||typeof e.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(e.sourceByteDigest)||typeof e.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(e.targetCanonicalHash)||typeof e.targetByteDigest!="string"||!/^[a-f0-9]{64}$/.test(e.targetByteDigest)||!Number.isSafeInteger(e.migratedEpicCount)||(e.migratedEpicCount??-1)<0||!Number.isSafeInteger(e.migratedStoryCount)||(e.migratedStoryCount??-1)<0||!Number.isSafeInteger(e.preservedUnknownFieldCount)||(e.preservedUnknownFieldCount??-1)<0||typeof e.backupPath!="string"||e.backupPath!==p(".neocortex",`state.json.migration-backup-${e.operationId}`))throw new a("state_migration_manifest_corrupt");return e}function D(o,t){H(p(o,$),`${JSON.stringify(t,null,2)}
4
+ `)}function S(o,t,r,e,s,c,l,g,i,h,n,u){const w={schemaVersion:Z,operationId:t,outcome:o,sourceBytesHash:r,targetBytesHash:e,sourceCanonicalHash:s,targetCanonicalHash:c,backupHash:l,rollbackStatus:g,migratedEpicCount:i,migratedStoryCount:h,preservedUnknownFieldCount:n,reasonCodes:u,publicSafe:!0};return Q(w),w}function pt(o){const t=b(o);let r;try{r=M(v(t).state)}catch(e){throw e instanceof R?new a(e.reasonCode,e.message):e}return r.kind==="migrate"?r.plan:null}function ut(o,t,r={}){const e=b(o),s=q(e);try{const c=p(e,E);try{P(c)}catch{throw new a("state_migration_atomic_recovery_failed")}if(!m(c))throw new a("state_migration_state_missing");const l=v(e).raw;if(t?.sourceByteDigest&&_(l)!==t.sourceByteDigest)throw new a("state_migration_expected_bytes_conflict");let g;try{g=M(j(l))}catch(d){throw d instanceof R?new a(d.reasonCode,d.message):d}const i=rt(e),h=_(l);if(g.kind==="unchanged"){if(t&&g.sourceCanonicalHash!==t.targetCanonicalHash)throw new a("state_migration_expected_plan_conflict");if(i&&i.targetCanonicalHash===g.sourceCanonicalHash){if(i.targetByteDigest!==h)throw new a("state_migration_state_drift");if(i.phase==="prepared"&&D(e,{...i,phase:"applied"}),i.phase==="rolled-back")throw new a("state_migration_state_drift");return S("already-applied",i.operationId,i.sourceByteDigest,i.targetByteDigest,i.sourceCanonicalHash,i.targetCanonicalHash,i.sourceByteDigest,"not-required",i.migratedEpicCount,i.migratedStoryCount,i.preservedUnknownFieldCount,["migration_replay_verified"])}if(i)throw new a("state_migration_state_drift");return S("already-applied",t?.operationId??"smig_00000000000000000000000000000000",h,h,g.sourceCanonicalHash,g.sourceCanonicalHash,null,"not-required",0,0,0,["canonical_state_unchanged"])}const n=g.plan;if(Y(n),t&&(t.operationId!==n.operationId||t.sourceCanonicalHash!==n.sourceCanonicalHash||t.targetCanonicalHash!==n.targetCanonicalHash))throw new a("state_migration_expected_plan_conflict");if(i&&i.operationId!==n.operationId)throw new a("state_migration_operation_conflict");const u=h,w=et(n.targetState),y=_(w),F=p(".neocortex",`state.json.migration-backup-${n.operationId}`),k=p(e,F);if(m(k)){const d=I(k);if(d.isSymbolicLink()||!d.isFile()||_(f(k))!==u)throw new a("state_migration_backup_conflict")}else N(k,l);const A={schemaVersion:1,operationId:n.operationId,phase:"prepared",sourceCanonicalHash:n.sourceCanonicalHash,sourceByteDigest:u,targetCanonicalHash:n.targetCanonicalHash,targetByteDigest:y,migratedEpicCount:n.migratedEpicIds.length,migratedStoryCount:n.migratedStoryIds.length,preservedUnknownFieldCount:n.preservedUnknownFieldCount,backupPath:F};if(D(e,A),r.afterPrepared?.(c),_(f(c))!==u)throw new a("state_migration_source_cas_conflict");try{H(c,w),r.afterReplace?.(c);const d=f(c,"utf8"),B=j(d);if(_(d)!==y||W(B)!==n.targetCanonicalHash)throw new Error("readback-digest-mismatch");D(e,{...A,phase:"applied"})}catch(d){try{const C=f(k,"utf8");if(_(C)!==u)throw new Error("rollback-backup-digest-mismatch");if(H(c,C),_(f(c))!==u)throw new Error("rollback-digest-mismatch");D(e,{...A,phase:"rolled-back"})}catch{const C=S("blocked",n.operationId,u,y,n.sourceCanonicalHash,n.targetCanonicalHash,u,"unverified",n.migratedEpicIds.length,n.migratedStoryIds.length,n.preservedUnknownFieldCount,["apply_failed","rollback_unverified"]);throw new a("state_migration_rollback_failed",String(d),C)}const B=S("blocked",n.operationId,u,y,n.sourceCanonicalHash,n.targetCanonicalHash,u,"restored",n.migratedEpicIds.length,n.migratedStoryIds.length,n.preservedUnknownFieldCount,["apply_failed","rollback_verified"]);throw new a("state_migration_apply_rolled_back",String(d),B)}return S("applied",n.operationId,u,y,n.sourceCanonicalHash,n.targetCanonicalHash,u,"not-required",n.migratedEpicIds.length,n.migratedStoryIds.length,n.preservedUnknownFieldCount,["lock_acquired","source_cas_verified","backup_verified","atomic_replace_verified"])}finally{s()}}export{V as STATE_MIGRATION_INPUT_LIMIT_BYTES,a as StateMigrationApplyError,ut as applyStateMigration,ct as collectStateMigrationAuthority,pt as previewStateMigration,lt as readStateMigrationSourceSnapshot,gt as restoreStateMigrationPreimage};
@@ -1,184 +1,2 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * This file is part of Neocortex CLI, licensed under the
6
- * Functional Source License, Version 1.1 (FSL-1.1).
7
- *
8
- * Change Date: February 20, 2029
9
- * Change License: MIT
10
- *
11
- * See the LICENSE file in the project root for full license text.
12
- */
13
- /**
14
- * Epic P107.02: Client-side Policy Reader
15
- *
16
- * Reads `.neocortex/architecture-policy.json` from consumer project root,
17
- * validates structure against P107.01 wire-format types, and exposes to
18
- * `collectStateSnapshot` hook so the server receives it via request body.
19
- *
20
- * Fail-soft by design -- NEVER throws. File absent / malformed / invalid
21
- * schema all return `undefined` (warning to stderr when non-trivial).
22
- *
23
- * Pattern reference:
24
- * - P101.06/07 (client-side file reader + hook pattern)
25
- * - P63.01 (UTF-8 BOM defense)
26
- * - P103.06 (CRLF normalization)
27
- */
28
- import { readFile } from 'node:fs/promises';
29
- import { join } from 'node:path';
30
- /**
31
- * Relative path from project root to consumer policy file.
32
- * Consumer copies `architecture-policy.template.json` (from repo root) to
33
- * this path and edits.
34
- */
35
- export const POLICY_FILE_PATH = '.neocortex/architecture-policy.json';
36
- // Frozen canonical enum sets mirroring JSON Schema (core/data/architecture-policy-schema.json).
37
- // Kept in sync with SSoT types in @neocortex/shared/types/architecture-policy.ts.
38
- const VALID_MODES = Object.freeze([
39
- 'interactive',
40
- 'yoloop_friendly',
41
- 'fully_automated',
42
- ]);
43
- const VALID_CLOUD_PROVIDERS = Object.freeze(['aws', 'gcp', 'oci', 'azure', 'any']);
44
- const VALID_API_STYLES = Object.freeze(['REST', 'GraphQL', 'tRPC']);
45
- const VALID_INTEGRATION_STYLES = Object.freeze(['sync', 'async', 'hybrid']);
46
- const VALID_UI_PRIORITIES = Object.freeze(['mobile-first', 'desktop-first', 'responsive']);
47
- const VALID_REFACTOR_AGGRESSIVENESS = Object.freeze(['conservative', 'balanced', 'aggressive']);
48
- const VALID_TEST_WORKFLOWS = Object.freeze(['TDD', 'test-after', 'BDD']);
49
- /** Known optional default field names per ArchitectureDefaults interface. */
50
- const KNOWN_DEFAULT_FIELDS = new Set([
51
- 'primary_persona',
52
- 'cloud_provider',
53
- 'api_style',
54
- 'integration_style',
55
- 'ui_priority',
56
- 'refactor_aggressiveness',
57
- 'test_workflow',
58
- ]);
59
- /**
60
- * Pure function validator. Zero I/O. Deterministic.
61
- *
62
- * Returns `ArchitecturePolicyValidationResult` with:
63
- * - `valid: true` iff all required fields correct and no hard errors
64
- * - `errors`: hard failures (schema version mismatch, bad mode, type errors)
65
- * - `warnings`: soft issues (unknown optional fields -- forward-compat)
66
- */
67
- export function validatePolicy(candidate) {
68
- const errors = [];
69
- const warnings = [];
70
- if (typeof candidate !== 'object' || candidate === null || Array.isArray(candidate)) {
71
- return {
72
- valid: false,
73
- errors: Object.freeze(['Policy must be a plain object']),
74
- warnings: Object.freeze([]),
75
- };
76
- }
77
- const c = candidate;
78
- // schema_version: must be literal 1
79
- if (c.schema_version !== 1) {
80
- errors.push(`schema_version must be 1, got ${JSON.stringify(c.schema_version)}`);
81
- }
82
- // mode: must be one of 3 valid values
83
- if (typeof c.mode !== 'string' || !VALID_MODES.includes(c.mode)) {
84
- errors.push(`mode must be one of [${VALID_MODES.join(', ')}], got ${JSON.stringify(c.mode)}`);
85
- }
86
- // defaults: optional object, each field must match its enum (or null/undefined)
87
- if (c.defaults !== undefined && c.defaults !== null) {
88
- if (typeof c.defaults !== 'object' || Array.isArray(c.defaults)) {
89
- errors.push('defaults must be an object');
90
- }
91
- else {
92
- const defaults = c.defaults;
93
- // Unknown-field warnings (forward-compat: future versions may add fields)
94
- for (const key of Object.keys(defaults)) {
95
- if (!KNOWN_DEFAULT_FIELDS.has(key)) {
96
- warnings.push(`defaults.${key}: unknown field (ignored)`);
97
- }
98
- }
99
- // Per-field value validation (null is allowed -- means "unset", asks human)
100
- if (defaults.primary_persona !== undefined &&
101
- defaults.primary_persona !== null &&
102
- typeof defaults.primary_persona !== 'string') {
103
- errors.push(`defaults.primary_persona must be string or null`);
104
- }
105
- validateEnumField(defaults, 'cloud_provider', VALID_CLOUD_PROVIDERS, errors);
106
- validateEnumField(defaults, 'api_style', VALID_API_STYLES, errors);
107
- validateEnumField(defaults, 'integration_style', VALID_INTEGRATION_STYLES, errors);
108
- validateEnumField(defaults, 'ui_priority', VALID_UI_PRIORITIES, errors);
109
- validateEnumField(defaults, 'refactor_aggressiveness', VALID_REFACTOR_AGGRESSIVENESS, errors);
110
- validateEnumField(defaults, 'test_workflow', VALID_TEST_WORKFLOWS, errors);
111
- }
112
- }
113
- // preserved_interactions: optional array of strings
114
- if (c.preserved_interactions !== undefined && c.preserved_interactions !== null) {
115
- if (!Array.isArray(c.preserved_interactions) ||
116
- !c.preserved_interactions.every((s) => typeof s === 'string')) {
117
- errors.push('preserved_interactions must be array of strings');
118
- }
119
- }
120
- return {
121
- valid: errors.length === 0,
122
- errors: Object.freeze(errors),
123
- warnings: Object.freeze(warnings),
124
- };
125
- }
126
- /**
127
- * Async reader. NEVER throws.
128
- *
129
- * Returns `undefined` when:
130
- * - file does not exist (ENOENT; silent, expected default)
131
- * - permission denied (EACCES; warns stderr)
132
- * - malformed JSON (warns stderr with path)
133
- * - schema invalid (warns stderr with error list)
134
- *
135
- * Returns typed `ArchitecturePolicy` on full success.
136
- */
137
- export async function readArchitecturePolicy(projectRoot) {
138
- const absPath = join(projectRoot, POLICY_FILE_PATH);
139
- let raw;
140
- try {
141
- raw = await readFile(absPath, 'utf8');
142
- }
143
- catch (err) {
144
- const code = err.code;
145
- if (code === 'ENOENT') {
146
- // Silent: file absent is the expected default.
147
- return undefined;
148
- }
149
- const msg = err.message ?? String(err);
150
- // Defensive warn -- operational issue (permission, etc).
151
- // eslint-disable-next-line no-console
152
- console.warn(`[Neocortex] architecture-policy read failed (${absPath}): ${msg}`);
153
- return undefined;
154
- }
155
- // Encoding normalization (P63 BOM + P103 CRLF patterns).
156
- // eslint-disable-next-line no-misleading-character-class
157
- const normalized = raw.replace(/^/, '').replace(/\r\n/g, '\n');
158
- let parsed;
159
- try {
160
- parsed = JSON.parse(normalized);
161
- }
162
- catch (err) {
163
- const msg = err.message ?? String(err);
164
- // eslint-disable-next-line no-console
165
- console.warn(`[Neocortex] architecture-policy malformed JSON (${absPath}): ${msg}. Proceeding without policy.`);
166
- return undefined;
167
- }
168
- const result = validatePolicy(parsed);
169
- if (!result.valid) {
170
- // eslint-disable-next-line no-console
171
- console.warn(`[Neocortex] architecture-policy schema invalid (${absPath}): ${result.errors.join('; ')}. Proceeding without policy.`);
172
- return undefined;
173
- }
174
- return parsed;
175
- }
176
- // ── Internal helpers ──────────────────────────────────────────────────────
177
- function validateEnumField(defaults, field, validValues, errors) {
178
- const val = defaults[field];
179
- if (val === undefined || val === null)
180
- return; // unset is OK
181
- if (typeof val !== 'string' || !validValues.includes(val)) {
182
- errors.push(`defaults.${field} must be one of [${validValues.join(', ')}] or null, got ${JSON.stringify(val)}`);
183
- }
184
- }
1
+ import{readFile as u}from"node:fs/promises";import{join as d}from"node:path";const p=".neocortex/architecture-policy.json",f=Object.freeze(["interactive","yoloop_friendly","fully_automated"]),y=Object.freeze(["aws","gcp","oci","azure","any"]),_=Object.freeze(["REST","GraphQL","tRPC"]),g=Object.freeze(["sync","async","hybrid"]),m=Object.freeze(["mobile-first","desktop-first","responsive"]),O=Object.freeze(["conservative","balanced","aggressive"]),b=Object.freeze(["TDD","test-after","BDD"]),h=new Set(["primary_persona","cloud_provider","api_style","integration_style","ui_priority","refactor_aggressiveness","test_workflow"]);function v(n){const r=[],o=[];if(typeof n!="object"||n===null||Array.isArray(n))return{valid:!1,errors:Object.freeze(["Policy must be a plain object"]),warnings:Object.freeze([])};const t=n;if(t.schema_version!==1&&r.push(`schema_version must be 1, got ${JSON.stringify(t.schema_version)}`),(typeof t.mode!="string"||!f.includes(t.mode))&&r.push(`mode must be one of [${f.join(", ")}], got ${JSON.stringify(t.mode)}`),t.defaults!==void 0&&t.defaults!==null)if(typeof t.defaults!="object"||Array.isArray(t.defaults))r.push("defaults must be an object");else{const e=t.defaults;for(const c of Object.keys(e))h.has(c)||o.push(`defaults.${c}: unknown field (ignored)`);e.primary_persona!==void 0&&e.primary_persona!==null&&typeof e.primary_persona!="string"&&r.push("defaults.primary_persona must be string or null"),i(e,"cloud_provider",y,r),i(e,"api_style",_,r),i(e,"integration_style",g,r),i(e,"ui_priority",m,r),i(e,"refactor_aggressiveness",O,r),i(e,"test_workflow",b,r)}return t.preserved_interactions!==void 0&&t.preserved_interactions!==null&&(!Array.isArray(t.preserved_interactions)||!t.preserved_interactions.every(e=>typeof e=="string"))&&r.push("preserved_interactions must be array of strings"),{valid:r.length===0,errors:Object.freeze(r),warnings:Object.freeze(o)}}async function A(n){const r=d(n,p);let o;try{o=await u(r,"utf8")}catch(s){if(s.code==="ENOENT")return;const l=s.message??String(s);console.warn(`[Neocortex] architecture-policy read failed (${r}): ${l}`);return}const t=o.replace(/^/,"").replace(/\r\n/g,`
2
+ `);let e;try{e=JSON.parse(t)}catch(s){const a=s.message??String(s);console.warn(`[Neocortex] architecture-policy malformed JSON (${r}): ${a}. Proceeding without policy.`);return}const c=v(e);if(!c.valid){console.warn(`[Neocortex] architecture-policy schema invalid (${r}): ${c.errors.join("; ")}. Proceeding without policy.`);return}return e}function i(n,r,o,t){const e=n[r];e!=null&&(typeof e!="string"||!o.includes(e))&&t.push(`defaults.${r} must be one of [${o.join(", ")}] or null, got ${JSON.stringify(e)}`)}export{p as POLICY_FILE_PATH,A as readArchitecturePolicy,v as validatePolicy};
@@ -1,7 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * Barrel export for Epic P107.02 policy reader module.
6
- */
7
- export { readArchitecturePolicy, validatePolicy, POLICY_FILE_PATH, } from './architecture-policy.js';
1
+ import{readArchitecturePolicy as c,validatePolicy as i,POLICY_FILE_PATH as o}from"./architecture-policy.js";export{o as POLICY_FILE_PATH,c as readArchitecturePolicy,i as validatePolicy};
@@ -1,38 +0,0 @@
1
- /**
2
- * P119.02: Inlined byte-identical types from
3
- * `@neocortex/shared/types/architecture-policy`.
4
- *
5
- * SSoT-Shadow pattern (P92.01 server precedent extended by P117.01 to client
6
- * checkpoint dist + P117.07 to client yoloop dist). Client tarball is published
7
- * standalone via `@ornexus/neocortex` and does NOT include `@neocortex/shared`
8
- * as a runtime dependency (workspace package, excluded from tarball per
9
- * `.npmignore` + `tsconfig.build.json`). Any non-erased import of
10
- * `@neocortex/shared` in `packages/client/dist/**` causes runtime
11
- * `ERR_MODULE_NOT_FOUND` on globally installed `@ornexus/neocortex`.
12
- *
13
- * Pre-P119.02, three files leaked `import type` statements from
14
- * `@neocortex/shared` in the published v4.19.1 tarball:
15
- * - dist/policy/architecture-policy.d.ts
16
- * - dist/policy/index.d.ts
17
- * - dist/commands/invoke.d.ts (imported `YoloopPersistedState`)
18
- *
19
- * Type-only `import type` is erased at runtime (no module resolution attempt),
20
- * but produces TS2307 in consumer projects that try to use the types via
21
- * globally-installed CLI (`npm install -g @ornexus/neocortex`).
22
- *
23
- * Sync responsibility: `policy-shared-sync.test.ts` (client-side drift test,
24
- * mirror of `checkpoint-shared-sync.test.ts` P117.01). Drift test fails CI
25
- * if these diverge from SSoT canonical at
26
- * `packages/shared/src/types/architecture-policy.ts`.
27
- *
28
- * Defense-in-depth: `validate-pre-publish.js` ships
29
- * `validateClientNoSharedImport()` (P117.01) scanning client dist for
30
- * `@neocortex/shared` runtime references. P119.02 expands its scope to also
31
- * walk `dist/policy/` and `dist/commands/` (in addition to checkpoint + yoloop
32
- * coverage from P117).
33
- *
34
- * DO NOT EDIT WITHOUT also editing
35
- * `packages/shared/src/types/architecture-policy.ts`.
36
- */
37
- export {};
38
- // === END P119.02 ===