@ornexus/neocortex 4.60.68 → 4.60.69

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 (232) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  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 +3 -290
  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.d.ts +6 -0
  38. package/packages/client/dist/commands/invoke.js +142 -7140
  39. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  40. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  41. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  42. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  43. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  44. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  45. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  46. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  47. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  48. package/packages/client/dist/commands/mutation-qa.js +1 -220
  49. package/packages/client/dist/commands/native-agent.js +2 -136
  50. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  51. package/packages/client/dist/commands/planning-generation.js +1 -53
  52. package/packages/client/dist/commands/planning-memory.js +1 -40
  53. package/packages/client/dist/commands/planning-research.js +1 -42
  54. package/packages/client/dist/commands/private-session.js +1 -75
  55. package/packages/client/dist/commands/property-qa.js +1 -139
  56. package/packages/client/dist/commands/qa-control.js +1 -16
  57. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  58. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  59. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  60. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  61. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  62. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  63. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  64. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  65. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  66. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  67. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  68. package/packages/client/dist/commands/refactor-commit.js +13 -399
  69. package/packages/client/dist/commands/refactor-control.js +3 -142
  70. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  71. package/packages/client/dist/commands/refactor-review.js +5 -283
  72. package/packages/client/dist/commands/refactor-root.js +7 -588
  73. package/packages/client/dist/commands/refresh-memory.js +3 -156
  74. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  76. package/packages/client/dist/config/profile-directory.js +1 -13
  77. package/packages/client/dist/config/resolver-selection.js +1 -278
  78. package/packages/client/dist/config/secure-config.js +12 -281
  79. package/packages/client/dist/config.js +2 -223
  80. package/packages/client/dist/constants.js +1 -25
  81. package/packages/client/dist/context/context-collector.js +2 -222
  82. package/packages/client/dist/context/context-sanitizer.js +1 -145
  83. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  84. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  85. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  86. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  87. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  88. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  89. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  90. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  91. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  92. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  93. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  94. package/packages/client/dist/continuity/outbox.js +1 -117
  95. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  96. package/packages/client/dist/continuity/sqlite-store.js +81 -2536
  97. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  98. package/packages/client/dist/errors/error-messages.js +2 -228
  99. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  100. package/packages/client/dist/evidence/collector.js +1 -347
  101. package/packages/client/dist/evidence/index.js +1 -1
  102. package/packages/client/dist/evidence/types.js +0 -2
  103. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  104. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  105. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  106. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  107. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  108. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  109. package/packages/client/dist/git/git-lifecycle-store.js +9 -1938
  110. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  111. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  112. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  113. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  114. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  115. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  116. package/packages/client/dist/i18n/first-run.js +2 -60
  117. package/packages/client/dist/index.js +1 -47
  118. package/packages/client/dist/invocation/invoke-input.js +1 -24
  119. package/packages/client/dist/license/index.js +1 -5
  120. package/packages/client/dist/license/license-client.js +1 -304
  121. package/packages/client/dist/machine/fingerprint.js +2 -163
  122. package/packages/client/dist/machine/index.js +1 -5
  123. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  124. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  125. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  126. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  127. package/packages/client/dist/migrations/project-identity.js +7 -493
  128. package/packages/client/dist/migrations/state-json.js +4 -344
  129. package/packages/client/dist/policy/architecture-policy.js +2 -184
  130. package/packages/client/dist/policy/index.js +1 -7
  131. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  132. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  133. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  134. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  135. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  136. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  137. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  138. package/packages/client/dist/private-execution/delivery.js +13 -410
  139. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  140. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  141. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  142. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  143. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  144. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  145. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  146. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  147. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  148. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  149. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  150. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  151. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  152. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  153. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  154. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  155. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  156. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  157. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  158. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  159. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  160. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  161. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  162. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  163. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  164. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  165. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  166. package/packages/client/dist/private-execution/session-lease.js +1 -63
  167. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  168. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  169. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  170. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  171. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  172. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  173. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  174. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  175. package/packages/client/dist/resilience/index.js +1 -8
  176. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  177. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  178. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  179. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  180. package/packages/client/dist/runner/binary.js +1 -404
  181. package/packages/client/dist/runner/cli.js +17 -1571
  182. package/packages/client/dist/runner/headless/adapters.js +1 -49
  183. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  184. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  185. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  186. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  187. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -1236
  188. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  189. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  190. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  191. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  192. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  193. package/packages/client/dist/runner/headless/resolver.js +1 -231
  194. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  195. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  196. package/packages/client/dist/runner/headless/types.js +2 -574
  197. package/packages/client/dist/runner/local-console.js +13 -396
  198. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  199. package/packages/client/dist/runner/project-identity.js +1 -106
  200. package/packages/client/dist/runner/scheduler.js +7 -995
  201. package/packages/client/dist/runner-cli.js +2 -18
  202. package/packages/client/dist/state/invocation-shape.js +1 -13
  203. package/packages/client/dist/state/project-state-snapshot.js +1 -1677
  204. package/packages/client/dist/state/state-json-repair.js +3 -785
  205. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  206. package/packages/client/dist/telemetry/index.js +1 -5
  207. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  208. package/packages/client/dist/tier/index.js +1 -5
  209. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  210. package/packages/client/dist/types/index.js +1 -38
  211. package/packages/client/dist/version.js +1 -27
  212. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  213. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  214. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -185
  215. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  216. package/packages/client/dist/yoloop/index.js +1 -8
  217. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  218. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  219. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  220. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  221. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1723
  222. package/targets-stubs/antigravity/gemini.md +1 -1
  223. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  224. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  225. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  226. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  227. package/targets-stubs/claude-code/neocortex.md +2 -2
  228. package/targets-stubs/codex/AGENTS.md +1 -1
  229. package/targets-stubs/cursor/agent.md +2 -2
  230. package/targets-stubs/gemini-cli/agent.md +2 -2
  231. package/targets-stubs/opencode/neocortex-root.md +1 -1
  232. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,344 +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
- function claimLock(root) {
98
- const lockPath = join(root, LOCK_RELATIVE_PATH);
99
- mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
100
- const ownerToken = randomUUID();
101
- const ownerContents = `${process.pid}:${ownerToken}\n`;
102
- const acquire = () => {
103
- const ownerPath = `${lockPath}.${process.pid}.${randomUUID()}.owner`;
104
- durableCreateUtf8(ownerPath, ownerContents);
105
- try {
106
- linkSync(ownerPath, lockPath);
107
- }
108
- finally {
109
- try {
110
- unlinkSync(ownerPath);
111
- }
112
- catch { /* orphan owners have no authority */ }
113
- fsyncDirectoryBestEffort(dirname(lockPath));
114
- }
115
- };
116
- try {
117
- acquire();
118
- }
119
- catch (error) {
120
- if (error.code !== 'EEXIST')
121
- throw new StateMigrationApplyError('state_migration_lock_failed');
122
- const stat = lstatSync(lockPath);
123
- if (stat.isSymbolicLink() || !stat.isFile())
124
- throw new StateMigrationApplyError('state_migration_lock_corrupt');
125
- const owner = readFileSync(lockPath, 'utf8');
126
- 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);
127
- if (!ownerMatch || owner.length > 64)
128
- throw new StateMigrationApplyError('state_migration_lock_corrupt');
129
- let alive = true;
130
- try {
131
- process.kill(Number(ownerMatch[1]), 0);
132
- }
133
- catch (probe) {
134
- alive = probe.code !== 'ESRCH';
135
- }
136
- if (alive)
137
- throw new StateMigrationApplyError('state_migration_locked');
138
- try {
139
- unlinkSync(lockPath);
140
- acquire();
141
- }
142
- catch {
143
- throw new StateMigrationApplyError('state_migration_locked');
144
- }
145
- }
146
- return () => {
147
- try {
148
- if (readFileSync(lockPath, 'utf8') !== ownerContents)
149
- return;
150
- unlinkSync(lockPath);
151
- fsyncDirectoryBestEffort(dirname(lockPath));
152
- }
153
- catch { /* cleanup is best effort; never delete an unproven foreign lock */ }
154
- };
155
- }
156
- function parseManifest(root) {
157
- const path = join(root, MANIFEST_RELATIVE_PATH);
158
- recoverAtomicReplaceUtf8(path);
159
- if (!existsSync(path))
160
- return null;
161
- let parsed;
162
- try {
163
- parsed = JSON.parse(readFileSync(path, 'utf8'));
164
- }
165
- catch {
166
- throw new StateMigrationApplyError('state_migration_manifest_corrupt');
167
- }
168
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
169
- throw new StateMigrationApplyError('state_migration_manifest_corrupt');
170
- const value = parsed;
171
- if (value.schemaVersion !== 1
172
- || typeof value.operationId !== 'string' || !/^smig_[a-f0-9]{32}$/.test(value.operationId)
173
- || !['prepared', 'applied', 'rolled-back'].includes(String(value.phase))
174
- || typeof value.sourceCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.sourceCanonicalHash)
175
- || typeof value.sourceByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(value.sourceByteDigest)
176
- || typeof value.targetCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.targetCanonicalHash)
177
- || typeof value.targetByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(value.targetByteDigest)
178
- || !Number.isSafeInteger(value.migratedEpicCount) || (value.migratedEpicCount ?? -1) < 0
179
- || !Number.isSafeInteger(value.migratedStoryCount) || (value.migratedStoryCount ?? -1) < 0
180
- || !Number.isSafeInteger(value.preservedUnknownFieldCount) || (value.preservedUnknownFieldCount ?? -1) < 0
181
- || typeof value.backupPath !== 'string'
182
- || value.backupPath !== join('.neocortex', `state.json.migration-backup-${value.operationId}`)) {
183
- throw new StateMigrationApplyError('state_migration_manifest_corrupt');
184
- }
185
- return value;
186
- }
187
- function writeManifest(root, manifest) {
188
- atomicReplaceUtf8(join(root, MANIFEST_RELATIVE_PATH), `${JSON.stringify(manifest, null, 2)}\n`);
189
- }
190
- function receipt(outcome, operationId, sourceBytesHash, targetBytesHash, sourceCanonicalHash, targetCanonicalHash, backupHash, rollbackStatus, migratedEpicCount, migratedStoryCount, preservedUnknownFieldCount, reasonCodes) {
191
- const value = {
192
- schemaVersion: STATE_MIGRATION_RECEIPT_SCHEMA,
193
- operationId,
194
- outcome,
195
- sourceBytesHash,
196
- targetBytesHash,
197
- sourceCanonicalHash,
198
- targetCanonicalHash,
199
- backupHash,
200
- rollbackStatus,
201
- migratedEpicCount,
202
- migratedStoryCount,
203
- preservedUnknownFieldCount,
204
- reasonCodes,
205
- publicSafe: true,
206
- };
207
- assertStateMigrationReceiptV1(value);
208
- return value;
209
- }
210
- export function previewStateMigration(projectRoot) {
211
- const root = safeRoot(projectRoot);
212
- let decision;
213
- try {
214
- decision = planStateMigration(readBoundedState(root).state);
215
- }
216
- catch (error) {
217
- if (error instanceof StateMigrationHardStopError)
218
- throw new StateMigrationApplyError(error.reasonCode, error.message);
219
- throw error;
220
- }
221
- return decision.kind === 'migrate' ? decision.plan : null;
222
- }
223
- /** Apply one shared plan under a client-owned lock, byte CAS and durable backup. */
224
- export function applyStateMigration(projectRoot, expectedPlan, hooks = {}) {
225
- const root = safeRoot(projectRoot);
226
- const release = claimLock(root);
227
- try {
228
- const statePath = join(root, STATE_RELATIVE_PATH);
229
- try {
230
- recoverAtomicReplaceUtf8(statePath);
231
- }
232
- catch {
233
- throw new StateMigrationApplyError('state_migration_atomic_recovery_failed');
234
- }
235
- if (!existsSync(statePath))
236
- throw new StateMigrationApplyError('state_migration_state_missing');
237
- const initialRaw = readBoundedState(root).raw;
238
- if (expectedPlan?.sourceByteDigest && sha256Bytes(initialRaw) !== expectedPlan.sourceByteDigest) {
239
- throw new StateMigrationApplyError('state_migration_expected_bytes_conflict');
240
- }
241
- let decision;
242
- try {
243
- decision = planStateMigration(parseState(initialRaw));
244
- }
245
- catch (error) {
246
- if (error instanceof StateMigrationHardStopError)
247
- throw new StateMigrationApplyError(error.reasonCode, error.message);
248
- throw error;
249
- }
250
- const existing = parseManifest(root);
251
- const currentBytesHash = sha256Bytes(initialRaw);
252
- if (decision.kind === 'unchanged') {
253
- if (expectedPlan && decision.sourceCanonicalHash !== expectedPlan.targetCanonicalHash) {
254
- throw new StateMigrationApplyError('state_migration_expected_plan_conflict');
255
- }
256
- if (existing && existing.targetCanonicalHash === decision.sourceCanonicalHash) {
257
- if (existing.targetByteDigest !== currentBytesHash) {
258
- throw new StateMigrationApplyError('state_migration_state_drift');
259
- }
260
- if (existing.phase === 'prepared')
261
- writeManifest(root, { ...existing, phase: 'applied' });
262
- if (existing.phase === 'rolled-back')
263
- throw new StateMigrationApplyError('state_migration_state_drift');
264
- 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']);
265
- }
266
- if (existing)
267
- throw new StateMigrationApplyError('state_migration_state_drift');
268
- return receipt('already-applied', expectedPlan?.operationId ?? 'smig_00000000000000000000000000000000', currentBytesHash, currentBytesHash, decision.sourceCanonicalHash, decision.sourceCanonicalHash, null, 'not-required', 0, 0, 0, ['canonical_state_unchanged']);
269
- }
270
- const plan = decision.plan;
271
- assertStateMigrationPlanV1(plan);
272
- if (expectedPlan && (expectedPlan.operationId !== plan.operationId
273
- || expectedPlan.sourceCanonicalHash !== plan.sourceCanonicalHash
274
- || expectedPlan.targetCanonicalHash !== plan.targetCanonicalHash)) {
275
- throw new StateMigrationApplyError('state_migration_expected_plan_conflict');
276
- }
277
- if (existing && existing.operationId !== plan.operationId) {
278
- throw new StateMigrationApplyError('state_migration_operation_conflict');
279
- }
280
- const sourceByteDigest = currentBytesHash;
281
- const targetRaw = stateRaw(plan.targetState);
282
- const targetByteDigest = sha256Bytes(targetRaw);
283
- const backupPath = join('.neocortex', `state.json.migration-backup-${plan.operationId}`);
284
- const backupAbsolute = join(root, backupPath);
285
- if (existsSync(backupAbsolute)) {
286
- const backupStat = lstatSync(backupAbsolute);
287
- if (backupStat.isSymbolicLink() || !backupStat.isFile() || sha256Bytes(readFileSync(backupAbsolute)) !== sourceByteDigest) {
288
- throw new StateMigrationApplyError('state_migration_backup_conflict');
289
- }
290
- }
291
- else {
292
- durableCreateUtf8(backupAbsolute, initialRaw);
293
- }
294
- const manifest = {
295
- schemaVersion: 1,
296
- operationId: plan.operationId,
297
- phase: 'prepared',
298
- sourceCanonicalHash: plan.sourceCanonicalHash,
299
- sourceByteDigest,
300
- targetCanonicalHash: plan.targetCanonicalHash,
301
- targetByteDigest,
302
- migratedEpicCount: plan.migratedEpicIds.length,
303
- migratedStoryCount: plan.migratedStoryIds.length,
304
- preservedUnknownFieldCount: plan.preservedUnknownFieldCount,
305
- backupPath,
306
- };
307
- writeManifest(root, manifest);
308
- hooks.afterPrepared?.(statePath);
309
- if (sha256Bytes(readFileSync(statePath)) !== sourceByteDigest) {
310
- throw new StateMigrationApplyError('state_migration_source_cas_conflict');
311
- }
312
- try {
313
- atomicReplaceUtf8(statePath, targetRaw);
314
- hooks.afterReplace?.(statePath);
315
- const installedRaw = readFileSync(statePath, 'utf8');
316
- const installed = parseState(installedRaw);
317
- if (sha256Bytes(installedRaw) !== targetByteDigest || stateMigrationDigest(installed) !== plan.targetCanonicalHash) {
318
- throw new Error('readback-digest-mismatch');
319
- }
320
- writeManifest(root, { ...manifest, phase: 'applied' });
321
- }
322
- catch (error) {
323
- try {
324
- const backupRaw = readFileSync(backupAbsolute, 'utf8');
325
- if (sha256Bytes(backupRaw) !== sourceByteDigest)
326
- throw new Error('rollback-backup-digest-mismatch');
327
- atomicReplaceUtf8(statePath, backupRaw);
328
- if (sha256Bytes(readFileSync(statePath)) !== sourceByteDigest)
329
- throw new Error('rollback-digest-mismatch');
330
- writeManifest(root, { ...manifest, phase: 'rolled-back' });
331
- }
332
- catch {
333
- 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']);
334
- throw new StateMigrationApplyError('state_migration_rollback_failed', String(error), unverified);
335
- }
336
- 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']);
337
- throw new StateMigrationApplyError('state_migration_apply_rolled_back', String(error), rolledBack);
338
- }
339
- 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']);
340
- }
341
- finally {
342
- release();
343
- }
344
- }
1
+ import{createHash as q,randomUUID as N}from"node:crypto";import{existsSync as S,linkSync as J,lstatSync as E,mkdirSync as z,readFileSync as h,realpathSync as G,statSync as j,unlinkSync as v}from"node:fs";import{dirname as A,join as d,resolve as K}from"node:path";import{assertStateMigrationPlanV1 as X,assertStateMigrationReceiptV1 as Y,planStateMigration as T,stateMigrationDigest as Q,STATE_MIGRATION_RECEIPT_SCHEMA as W,StateMigrationHardStopError as B}from"../../../shared/dist/state/index.js";import{atomicReplaceUtf8 as M,durableCreateUtf8 as L,fsyncDirectoryBestEffort as O,recoverAtomicReplaceUtf8 as V}from"../fs/atomic-state-replace.js";const D=d(".neocortex","state.json"),R=d(".neocortex","state-migration.json"),Z=d(".neocortex","state-migration.lock"),P=4*1024*1024;class o extends Error{reasonCode;receipt;constructor(e,a=e,t){super(a),this.reasonCode=e,this.receipt=t,this.name="StateMigrationApplyError"}}const _=i=>q("sha256").update(i).digest("hex"),tt=i=>`${JSON.stringify(i,null,2)}
2
+ `;function $(i){let e;try{e=G(K(i))}catch{throw new o("state_migration_root_invalid")}if(!j(e).isDirectory())throw new o("state_migration_root_invalid");for(const a of[".neocortex",D,R]){const t=d(e,a);if(!S(t))continue;const s=E(t);if(s.isSymbolicLink()||a!==".neocortex"&&!s.isFile()||a===".neocortex"&&!s.isDirectory())throw new o("state_migration_symlink_or_type_rejected")}return e}function U(i){try{const e=JSON.parse(i);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}throw new o("state_migration_state_corrupt")}function F(i){const e=d(i,D);if(!S(e))throw new o("state_migration_state_missing");const a=j(e).size;if(a>P)throw new o("state_migration_input_too_large");const t=h(e,"utf8"),s=Buffer.byteLength(t,"utf8");if(s!==a||s>P)throw new o("state_migration_source_changed");return{state:U(t),raw:t,digest:_(t),bytes:s}}function ct(i){const e=F($(i));let a;try{a=T(e.state)}catch(l){throw l instanceof B?new o(l.reasonCode,l.message):l}const t=a.kind==="migrate"?a.plan.targetState:e.state,s=(l,p)=>{const n=l[p];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).length:0},c=a.kind==="migrate"?(({targetState:l,...p})=>p)(a.plan):null;return Object.freeze({schemaVersion:"StateMigrationAuthority/1.0",sourceByteDigest:e.digest,sourceCanonicalHash:a.kind==="migrate"?a.plan.sourceCanonicalHash:a.sourceCanonicalHash,sourceByteLength:e.bytes,before:{epics:s(e.state,"epics"),stories:s(e.state,"stories")},after:{epics:s(t,"epics"),stories:s(t,"stories")},outcome:a.kind,plan:c,publicSafe:!0})}function et(i){const e=d(i,Z);z(A(e),{recursive:!0,mode:448});const a=N(),t=`${process.pid}:${a}
3
+ `,s=()=>{const c=`${e}.${process.pid}.${N()}.owner`;L(c,t);try{J(c,e)}finally{try{v(c)}catch{}O(A(e))}};try{s()}catch(c){if(c.code!=="EEXIST")throw new o("state_migration_lock_failed");const l=E(e);if(l.isSymbolicLink()||!l.isFile())throw new o("state_migration_lock_corrupt");const p=h(e,"utf8"),n=p.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(!n||p.length>64)throw new o("state_migration_lock_corrupt");let f=!0;try{process.kill(Number(n[1]),0)}catch(r){f=r.code!=="ESRCH"}if(f)throw new o("state_migration_locked");try{v(e),s()}catch{throw new o("state_migration_locked")}}return()=>{try{if(h(e,"utf8")!==t)return;v(e),O(A(e))}catch{}}}function rt(i){const e=d(i,R);if(V(e),!S(e))return null;let a;try{a=JSON.parse(h(e,"utf8"))}catch{throw new o("state_migration_manifest_corrupt")}if(!a||typeof a!="object"||Array.isArray(a))throw new o("state_migration_manifest_corrupt");const t=a;if(t.schemaVersion!==1||typeof t.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(t.operationId)||!["prepared","applied","rolled-back"].includes(String(t.phase))||typeof t.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(t.sourceCanonicalHash)||typeof t.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(t.sourceByteDigest)||typeof t.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(t.targetCanonicalHash)||typeof t.targetByteDigest!="string"||!/^[a-f0-9]{64}$/.test(t.targetByteDigest)||!Number.isSafeInteger(t.migratedEpicCount)||(t.migratedEpicCount??-1)<0||!Number.isSafeInteger(t.migratedStoryCount)||(t.migratedStoryCount??-1)<0||!Number.isSafeInteger(t.preservedUnknownFieldCount)||(t.preservedUnknownFieldCount??-1)<0||typeof t.backupPath!="string"||t.backupPath!==d(".neocortex",`state.json.migration-backup-${t.operationId}`))throw new o("state_migration_manifest_corrupt");return t}function b(i,e){M(d(i,R),`${JSON.stringify(e,null,2)}
4
+ `)}function k(i,e,a,t,s,c,l,p,n,f,r,g){const m={schemaVersion:W,operationId:e,outcome:i,sourceBytesHash:a,targetBytesHash:t,sourceCanonicalHash:s,targetCanonicalHash:c,backupHash:l,rollbackStatus:p,migratedEpicCount:n,migratedStoryCount:f,preservedUnknownFieldCount:r,reasonCodes:g,publicSafe:!0};return Y(m),m}function lt(i){const e=$(i);let a;try{a=T(F(e).state)}catch(t){throw t instanceof B?new o(t.reasonCode,t.message):t}return a.kind==="migrate"?a.plan:null}function pt(i,e,a={}){const t=$(i),s=et(t);try{const c=d(t,D);try{V(c)}catch{throw new o("state_migration_atomic_recovery_failed")}if(!S(c))throw new o("state_migration_state_missing");const l=F(t).raw;if(e?.sourceByteDigest&&_(l)!==e.sourceByteDigest)throw new o("state_migration_expected_bytes_conflict");let p;try{p=T(U(l))}catch(u){throw u instanceof B?new o(u.reasonCode,u.message):u}const n=rt(t),f=_(l);if(p.kind==="unchanged"){if(e&&p.sourceCanonicalHash!==e.targetCanonicalHash)throw new o("state_migration_expected_plan_conflict");if(n&&n.targetCanonicalHash===p.sourceCanonicalHash){if(n.targetByteDigest!==f)throw new o("state_migration_state_drift");if(n.phase==="prepared"&&b(t,{...n,phase:"applied"}),n.phase==="rolled-back")throw new o("state_migration_state_drift");return k("already-applied",n.operationId,n.sourceByteDigest,n.targetByteDigest,n.sourceCanonicalHash,n.targetCanonicalHash,n.sourceByteDigest,"not-required",n.migratedEpicCount,n.migratedStoryCount,n.preservedUnknownFieldCount,["migration_replay_verified"])}if(n)throw new o("state_migration_state_drift");return k("already-applied",e?.operationId??"smig_00000000000000000000000000000000",f,f,p.sourceCanonicalHash,p.sourceCanonicalHash,null,"not-required",0,0,0,["canonical_state_unchanged"])}const r=p.plan;if(X(r),e&&(e.operationId!==r.operationId||e.sourceCanonicalHash!==r.sourceCanonicalHash||e.targetCanonicalHash!==r.targetCanonicalHash))throw new o("state_migration_expected_plan_conflict");if(n&&n.operationId!==r.operationId)throw new o("state_migration_operation_conflict");const g=f,m=tt(r.targetState),w=_(m),x=d(".neocortex",`state.json.migration-backup-${r.operationId}`),y=d(t,x);if(S(y)){const u=E(y);if(u.isSymbolicLink()||!u.isFile()||_(h(y))!==g)throw new o("state_migration_backup_conflict")}else L(y,l);const I={schemaVersion:1,operationId:r.operationId,phase:"prepared",sourceCanonicalHash:r.sourceCanonicalHash,sourceByteDigest:g,targetCanonicalHash:r.targetCanonicalHash,targetByteDigest:w,migratedEpicCount:r.migratedEpicIds.length,migratedStoryCount:r.migratedStoryIds.length,preservedUnknownFieldCount:r.preservedUnknownFieldCount,backupPath:x};if(b(t,I),a.afterPrepared?.(c),_(h(c))!==g)throw new o("state_migration_source_cas_conflict");try{M(c,m),a.afterReplace?.(c);const u=h(c,"utf8"),H=U(u);if(_(u)!==w||Q(H)!==r.targetCanonicalHash)throw new Error("readback-digest-mismatch");b(t,{...I,phase:"applied"})}catch(u){try{const C=h(y,"utf8");if(_(C)!==g)throw new Error("rollback-backup-digest-mismatch");if(M(c,C),_(h(c))!==g)throw new Error("rollback-digest-mismatch");b(t,{...I,phase:"rolled-back"})}catch{const C=k("blocked",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"unverified",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["apply_failed","rollback_unverified"]);throw new o("state_migration_rollback_failed",String(u),C)}const H=k("blocked",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"restored",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["apply_failed","rollback_verified"]);throw new o("state_migration_apply_rolled_back",String(u),H)}return k("applied",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"not-required",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["lock_acquired","source_cas_verified","backup_verified","atomic_replace_verified"])}finally{s()}}export{P as STATE_MIGRATION_INPUT_LIMIT_BYTES,o as StateMigrationApplyError,pt as applyStateMigration,ct as collectStateMigrationAuthority,lt as previewStateMigration};
@@ -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 ===