@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,635 +1,2 @@
1
- /**
2
- * Read-only compatibility and release doctor (P223.02).
3
- *
4
- * The release contract is owned by P223.01. This command intentionally loads
5
- * that authority through a narrow adapter instead of copying its validator.
6
- * The dynamic boundary keeps this dependent story buildable while P223.01 is
7
- * integrated in parallel.
8
- */
9
- import { Buffer } from 'node:buffer';
10
- import { createHash } from 'node:crypto';
11
- import { execFileSync } from 'node:child_process';
12
- import { readFileSync, statSync } from 'node:fs';
13
- import { join, resolve } from 'node:path';
14
- import { COMMAND_REGISTRY_CHECKSUM, COMMAND_REGISTRY_VERSION, } from '../generated/command-registry.generated.js';
15
- import { DEFAULT_SERVER_URL } from '../constants.js';
16
- import { getClientVersion } from '../version.js';
17
- export const DOCTOR_SCHEMA_VERSION = 'CompatibilityReleaseDoctor/1.0';
18
- export const DOCTOR_RESPONSE_SCHEMA_VERSION = 'CompatibilityDoctorResponse/1.0';
19
- export const DOCTOR_EXIT_CODES = Object.freeze({
20
- SUCCESS: 0,
21
- BLOCKED: 1,
22
- USAGE: 2,
23
- });
24
- export const DOCTOR_REASON_CODES = Object.freeze({
25
- HEALTHY: 'doctor-healthy',
26
- OFFLINE: 'doctor-offline',
27
- SERVER_UNREACHABLE: 'server-unreachable',
28
- CLIENT_TOO_OLD: 'client-too-old',
29
- SERVER_TOO_OLD: 'server-too-old',
30
- PROTOCOL_MISMATCH: 'protocol-mismatch',
31
- SCHEMA_MISMATCH: 'schema-mismatch',
32
- CAPABILITY_MISMATCH: 'capability-mismatch',
33
- REGISTRY_DRIFT: 'registry-drift',
34
- MALFORMED_RESPONSE: 'malformed-response',
35
- AUTHORITY_UNAVAILABLE: 'compatibility-authority-unavailable',
36
- RELEASE_LIFECYCLE_UNAVAILABLE: 'release-lifecycle-unavailable',
37
- REQUIRED_DIMENSION_BLOCKED: 'required-release-dimension-blocked',
38
- });
39
- const DIMENSIONS = Object.freeze([
40
- 'implementationComplete',
41
- 'betaOperable',
42
- 'releaseReady',
43
- 'productionPromoted',
44
- ]);
45
- const MAX_RESPONSE_BYTES = 64 * 1024;
46
- const MAX_FINDINGS = 32;
47
- const DEFAULT_TIMEOUT_MS = 5_000;
48
- const SAFE_REASON = /^[a-z][a-z0-9-]{0,63}$/u;
49
- const SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/u;
50
- const SAFE_VERSION = /^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][A-Za-z0-9.-]{1,40})?$/u;
51
- const SAFE_REGISTRY_VERSION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u;
52
- const SHA256 = /^[a-f0-9]{64}$/u;
53
- const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/u;
54
- const GIT_OBJECT_ID = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
55
- const SAFE_EVIDENCE_REF = /^(?:local-gate|beta-receipt|release-gate|promotion-receipt|sha256):[a-f0-9]{64}$/u;
56
- const REMEDIATION = Object.freeze({
57
- healthy: 'No compatibility remediation is required.',
58
- offline: 'Rerun without --offline when read-only server evidence is available.',
59
- unreachable: 'Check read-only server reachability, then rerun doctor.',
60
- clientTooOld: 'Run a separately authorized client update, then rerun doctor.',
61
- serverTooOld: 'Ask an authorized server operator to update the server, then rerun doctor.',
62
- protocol: 'Align client and server protocol releases before invoking protected operations.',
63
- schema: 'Use a client and server pair that supports the required public schemas.',
64
- capability: 'Enable no feature here; use a release pair with the required capability set.',
65
- registry: 'Install an exact release pair with the same command-registry checksum.',
66
- malformed: 'Contact support with the reason code only; do not attach raw response data.',
67
- authority: 'Integrate the P223.01 shared compatibility authority, then rerun doctor.',
68
- lifecycle: 'Obtain bounded physical release evidence through separately authorized operations.',
69
- required: 'Satisfy and verify the required physical release dimension through a separately authorized operation.',
70
- });
71
- const REASON_ORDER = new Map([
72
- [DOCTOR_REASON_CODES.MALFORMED_RESPONSE, 0],
73
- [DOCTOR_REASON_CODES.AUTHORITY_UNAVAILABLE, 1],
74
- [DOCTOR_REASON_CODES.CLIENT_TOO_OLD, 2],
75
- [DOCTOR_REASON_CODES.SERVER_TOO_OLD, 3],
76
- [DOCTOR_REASON_CODES.PROTOCOL_MISMATCH, 4],
77
- [DOCTOR_REASON_CODES.SCHEMA_MISMATCH, 5],
78
- [DOCTOR_REASON_CODES.CAPABILITY_MISMATCH, 6],
79
- [DOCTOR_REASON_CODES.REGISTRY_DRIFT, 7],
80
- [DOCTOR_REASON_CODES.SERVER_UNREACHABLE, 8],
81
- [DOCTOR_REASON_CODES.OFFLINE, 9],
82
- [DOCTOR_REASON_CODES.RELEASE_LIFECYCLE_UNAVAILABLE, 10],
83
- [DOCTOR_REASON_CODES.REQUIRED_DIMENSION_BLOCKED, 11],
84
- [DOCTOR_REASON_CODES.HEALTHY, 100],
85
- ]);
86
- function unknownDimensions(reasonCode = 'release-evidence-unavailable') {
87
- const dimension = () => Object.freeze({
88
- value: 'unknown',
89
- freshness: 'unknown',
90
- reasonCodes: Object.freeze([reasonCode]),
91
- evidenceRefs: Object.freeze([]),
92
- });
93
- return Object.freeze({
94
- implementationComplete: dimension(),
95
- betaOperable: dimension(),
96
- releaseReady: dimension(),
97
- productionPromoted: dimension(),
98
- });
99
- }
100
- function parseRequiredDimension(value) {
101
- const aliases = Object.freeze({
102
- implementation: 'implementationComplete',
103
- 'implementation-complete': 'implementationComplete',
104
- beta: 'betaOperable',
105
- 'beta-operable': 'betaOperable',
106
- release: 'releaseReady',
107
- 'release-ready': 'releaseReady',
108
- production: 'productionPromoted',
109
- 'production-promoted': 'productionPromoted',
110
- });
111
- return value ? aliases[value] ?? null : null;
112
- }
113
- export function parseDoctorArgs(args, env = process.env) {
114
- let mode = 'online';
115
- let json = false;
116
- let serverUrl = env.NEOCORTEX_SERVER_URL ?? DEFAULT_SERVER_URL;
117
- let serverUrlExplicit = false;
118
- let requiredDimension = null;
119
- let projectRoot = process.cwd();
120
- for (let index = 0; index < args.length; index += 1) {
121
- const arg = args[index];
122
- if (arg === '--offline') {
123
- mode = 'offline';
124
- }
125
- else if (arg === '--json') {
126
- json = true;
127
- }
128
- else if (arg === '--server-url') {
129
- const value = args[index + 1];
130
- if (!value)
131
- throw new Error('doctor-server-url-required');
132
- serverUrl = value;
133
- serverUrlExplicit = true;
134
- index += 1;
135
- }
136
- else if (arg === '--require') {
137
- const value = args[index + 1];
138
- const parsed = parseRequiredDimension(value);
139
- if (!value || !parsed)
140
- throw new Error('doctor-required-dimension-invalid');
141
- requiredDimension = parsed;
142
- index += 1;
143
- }
144
- else if (arg === '--project-root') {
145
- const value = args[index + 1];
146
- if (!value || value.length > 4_096 || value.includes('\0'))
147
- throw new Error('doctor-project-root-invalid');
148
- projectRoot = resolve(value);
149
- index += 1;
150
- }
151
- else {
152
- throw new Error('doctor-argument-invalid');
153
- }
154
- }
155
- if (mode === 'offline' && serverUrlExplicit)
156
- throw new Error('doctor-offline-server-url-conflict');
157
- if (mode === 'offline') {
158
- return Object.freeze({ mode, json, serverUrl: DEFAULT_SERVER_URL, requiredDimension, projectRoot });
159
- }
160
- if (serverUrl.length > 2_048)
161
- throw new Error('doctor-server-url-invalid');
162
- try {
163
- const parsed = new URL(serverUrl);
164
- if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
165
- || parsed.username || parsed.password || parsed.search || parsed.hash)
166
- throw new Error('url');
167
- }
168
- catch {
169
- throw new Error('doctor-server-url-invalid');
170
- }
171
- return Object.freeze({ mode, json, serverUrl: serverUrl.replace(/\/+$/u, ''), requiredDimension, projectRoot });
172
- }
173
- function isCompatibilityAuthority(value) {
174
- if (!value || typeof value !== 'object')
175
- return false;
176
- const candidate = value;
177
- return typeof candidate.createCompatibilityOffer === 'function'
178
- && typeof candidate.isCompatibilityResultV1 === 'function'
179
- && typeof candidate.validateReleaseLifecycle === 'function';
180
- }
181
- /** P223.01 integration seam. No fallback validator is maintained here. */
182
- export async function loadSharedCompatibilityAuthority() {
183
- const candidates = [
184
- '@neocortex/shared/compatibility',
185
- '../../../shared/dist/compatibility/index.js',
186
- ];
187
- for (const specifier of candidates) {
188
- try {
189
- const moduleValue = await import(specifier);
190
- if (isCompatibilityAuthority(moduleValue))
191
- return moduleValue;
192
- }
193
- catch {
194
- // P223.02 can be built before P223.01 lands. Online diagnosis fails closed;
195
- // offline diagnosis remains useful and reports all remote truth as unknown.
196
- }
197
- }
198
- return null;
199
- }
200
- /**
201
- * Resolve the current project to an opaque selector without repairing or
202
- * writing state. Git output is consumed locally and only domain-separated
203
- * hashes plus the already-public project ID cross the network boundary.
204
- */
205
- export function collectLocalReleaseLifecycleContext(projectRoot, authority) {
206
- if (typeof authority.createReleaseLifecycleContext !== 'function')
207
- return null;
208
- try {
209
- const statePath = join(projectRoot, '.neocortex', 'state.json');
210
- const stat = statSync(statePath);
211
- if (!stat.isFile() || stat.size <= 0 || stat.size > 1024 * 1024)
212
- return null;
213
- const state = JSON.parse(readFileSync(statePath, 'utf8'));
214
- const config = state.config && typeof state.config === 'object' && !Array.isArray(state.config)
215
- ? state.config
216
- : state.project && typeof state.project === 'object' && !Array.isArray(state.project)
217
- ? state.project
218
- : null;
219
- const projectId = config?.project_id;
220
- if (typeof projectId !== 'string' || !PROJECT_ID.test(projectId))
221
- return null;
222
- const head = execFileSync('git', ['rev-parse', '--verify', 'HEAD'], {
223
- cwd: projectRoot,
224
- encoding: 'utf8',
225
- timeout: 2_000,
226
- maxBuffer: 1_024,
227
- stdio: ['ignore', 'pipe', 'ignore'],
228
- }).trim().toLowerCase();
229
- if (!GIT_OBJECT_ID.test(head))
230
- return null;
231
- const lineageSha256 = createHash('sha256').update('git-lineage-v1\0').update(head).digest('hex');
232
- const candidateId = `candidate-${createHash('sha256')
233
- .update('release-candidate-v1\0').update(projectId).update('\0').update(head).digest('hex').slice(0, 32)}`;
234
- return authority.createReleaseLifecycleContext({ projectId, candidateId, lineageSha256 });
235
- }
236
- catch {
237
- return null;
238
- }
239
- }
240
- function finding(severity, reasonCode, affectedDimension, remediation, evidenceRef = null) {
241
- return Object.freeze({ severity, reasonCode, affectedDimension, evidenceRef, remediation });
242
- }
243
- function compareVersions(left, right) {
244
- if (!SAFE_VERSION.test(left) || !SAFE_VERSION.test(right))
245
- return null;
246
- const numeric = (value) => value
247
- .split(/[-+]/u, 1)[0]
248
- .split('.')
249
- .map(Number);
250
- const leftParts = numeric(left);
251
- const rightParts = numeric(right);
252
- for (let index = 0; index < 3; index += 1) {
253
- if (leftParts[index] === rightParts[index])
254
- continue;
255
- return leftParts[index] < rightParts[index] ? -1 : 1;
256
- }
257
- return 0;
258
- }
259
- function safeReasons(value) {
260
- return Object.freeze([...new Set(value.filter((reason) => SAFE_REASON.test(reason)))].slice(0, 8).sort());
261
- }
262
- function safeIdentifiers(value) {
263
- return Object.freeze([...new Set(value.filter((item) => SAFE_IDENTIFIER.test(item)))].slice(0, 32).sort());
264
- }
265
- function safeEvidenceRefs(value) {
266
- return Object.freeze([...new Set(value.filter((item) => SAFE_EVIDENCE_REF.test(item)))].slice(0, 8).sort());
267
- }
268
- function asCompatibilityBoundary(value) {
269
- if (!value || typeof value !== 'object' || Array.isArray(value))
270
- return null;
271
- const candidate = value;
272
- const registry = candidate.commandRegistry;
273
- if (!['compatible', 'degraded', 'incompatible'].includes(String(candidate.status))
274
- || typeof candidate.clientVersion !== 'string' || !SAFE_VERSION.test(candidate.clientVersion)
275
- || typeof candidate.serverVersion !== 'string' || !SAFE_VERSION.test(candidate.serverVersion)
276
- || !(candidate.protocolVersion === null || typeof candidate.protocolVersion === 'string' && SAFE_IDENTIFIER.test(candidate.protocolVersion))
277
- || !Array.isArray(candidate.schemaVersions) || !candidate.schemaVersions.every((item) => typeof item === 'string')
278
- || !Array.isArray(candidate.capabilityIds) || !candidate.capabilityIds.every((item) => typeof item === 'string')
279
- || !Array.isArray(candidate.reasonCodes) || !candidate.reasonCodes.every((item) => typeof item === 'string')
280
- || !registry || typeof registry.version !== 'string' || !SAFE_REGISTRY_VERSION.test(registry.version)
281
- || typeof registry.checksum !== 'string' || !SHA256.test(registry.checksum)
282
- || !['matched', 'mismatched', 'unknown'].includes(String(registry.status)))
283
- return null;
284
- return candidate;
285
- }
286
- function asLifecycleProjection(value) {
287
- if (!value || typeof value !== 'object' || Array.isArray(value))
288
- return null;
289
- const candidate = value;
290
- if (typeof candidate.candidateId !== 'string' || !SAFE_IDENTIFIER.test(candidate.candidateId)
291
- || typeof candidate.lineageSha256 !== 'string' || !SHA256.test(candidate.lineageSha256))
292
- return null;
293
- for (const name of DIMENSIONS) {
294
- const dimension = candidate[name];
295
- if (!dimension || typeof dimension !== 'object' || Array.isArray(dimension))
296
- return null;
297
- const record = dimension;
298
- if (!(typeof record.value === 'boolean' || record.value === 'unknown')
299
- || !['fresh', 'stale', 'unknown'].includes(String(record.freshness))
300
- || !Array.isArray(record.reasonCodes) || !record.reasonCodes.every((item) => typeof item === 'string')
301
- || !Array.isArray(record.evidenceRefs) || !record.evidenceRefs.every((item) => typeof item === 'string'))
302
- return null;
303
- }
304
- return candidate;
305
- }
306
- function sortedFindings(findings) {
307
- const severityOrder = { error: 0, warning: 1, info: 2 };
308
- const dimensionOrder = new Map([
309
- ['compatibility', 0], ['releaseLifecycle', 1],
310
- ['implementationComplete', 2], ['betaOperable', 3], ['releaseReady', 4], ['productionPromoted', 5],
311
- ]);
312
- return Object.freeze([...findings]
313
- .sort((left, right) => severityOrder[left.severity] - severityOrder[right.severity]
314
- || (REASON_ORDER.get(left.reasonCode) ?? 50) - (REASON_ORDER.get(right.reasonCode) ?? 50)
315
- || (dimensionOrder.get(left.affectedDimension) ?? 99) - (dimensionOrder.get(right.affectedDimension) ?? 99)
316
- || left.reasonCode.localeCompare(right.reasonCode))
317
- .slice(0, MAX_FINDINGS));
318
- }
319
- function compatibilityShell(clientVersion) {
320
- return Object.freeze({
321
- status: 'unknown',
322
- clientVersion,
323
- serverVersion: null,
324
- protocolVersion: null,
325
- schemaVersions: Object.freeze([]),
326
- capabilityIds: Object.freeze([]),
327
- registry: Object.freeze({
328
- localVersion: COMMAND_REGISTRY_VERSION,
329
- localChecksum: COMMAND_REGISTRY_CHECKSUM,
330
- remoteVersion: null,
331
- remoteChecksum: null,
332
- status: 'unknown',
333
- }),
334
- });
335
- }
336
- function finalizeReport(input) {
337
- const findings = [...input.findings];
338
- const dimensions = input.dimensions ?? unknownDimensions();
339
- let blocked = input.incompatible;
340
- if (input.requiredDimension && dimensions[input.requiredDimension].value !== true) {
341
- blocked = true;
342
- findings.push(finding('error', DOCTOR_REASON_CODES.REQUIRED_DIMENSION_BLOCKED, input.requiredDimension, REMEDIATION.required, dimensions[input.requiredDimension].evidenceRefs[0] ?? null));
343
- }
344
- const ordered = sortedFindings(findings);
345
- const overall = blocked
346
- ? 'incompatible'
347
- : ordered.some((item) => item.severity === 'warning') ? 'degraded' : 'healthy';
348
- return Object.freeze({
349
- schemaVersion: DOCTOR_SCHEMA_VERSION,
350
- publicSafe: true,
351
- readOnly: true,
352
- mode: input.mode,
353
- overall,
354
- exitCode: blocked ? DOCTOR_EXIT_CODES.BLOCKED : DOCTOR_EXIT_CODES.SUCCESS,
355
- compatibility: input.compatibility ?? compatibilityShell(input.clientVersion),
356
- release: Object.freeze({
357
- candidateId: input.candidateId ?? null,
358
- lineageSha256: input.lineageSha256 ?? null,
359
- requiredDimension: input.requiredDimension,
360
- dimensions,
361
- }),
362
- findings: ordered,
363
- });
364
- }
365
- function responseEnvelope(value) {
366
- if (!value || typeof value !== 'object' || Array.isArray(value))
367
- return null;
368
- const candidate = value;
369
- if ('compatibility' in candidate) {
370
- if (candidate.schemaVersion !== undefined && candidate.schemaVersion !== DOCTOR_RESPONSE_SCHEMA_VERSION)
371
- return null;
372
- return { compatibility: candidate.compatibility, ...(candidate.releaseLifecycle !== undefined ? { releaseLifecycle: candidate.releaseLifecycle } : {}) };
373
- }
374
- // A bare P223.01 compatibility result is accepted as a reduced projection.
375
- return { compatibility: value };
376
- }
377
- async function fetchDoctorResponse(fetcher, serverUrl, offer, releaseContext) {
378
- const controller = new AbortController();
379
- const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
380
- try {
381
- const encodedOffer = Buffer.from(JSON.stringify(offer), 'utf8').toString('base64url');
382
- if (encodedOffer.length > 8_192)
383
- return { kind: 'malformed' };
384
- const encodedContext = releaseContext === null
385
- ? null
386
- : Buffer.from(JSON.stringify(releaseContext), 'utf8').toString('base64url');
387
- if (encodedContext && encodedContext.length > 2_048)
388
- return { kind: 'malformed' };
389
- const response = await fetcher(`${serverUrl}/api/v1/compatibility`, {
390
- method: 'GET',
391
- headers: Object.freeze({
392
- Accept: 'application/json',
393
- 'Cache-Control': 'no-store',
394
- 'X-Neocortex-Compatibility-Offer': encodedOffer,
395
- ...(encodedContext ? { 'X-Neocortex-Release-Context': encodedContext } : {}),
396
- }),
397
- signal: controller.signal,
398
- });
399
- if (response.status === 404 || response.status === 405 || response.status === 426)
400
- return { kind: 'server-too-old' };
401
- if (!response.ok)
402
- return response.status >= 500 ? { kind: 'unreachable' } : { kind: 'malformed' };
403
- const body = await response.text();
404
- if (Buffer.byteLength(body, 'utf8') > MAX_RESPONSE_BYTES)
405
- return { kind: 'malformed' };
406
- try {
407
- return { kind: 'ok', value: JSON.parse(body) };
408
- }
409
- catch {
410
- return { kind: 'malformed' };
411
- }
412
- }
413
- catch {
414
- return { kind: 'unreachable' };
415
- }
416
- finally {
417
- clearTimeout(timeout);
418
- }
419
- }
420
- function offlineReport(clientVersion, requiredDimension) {
421
- return finalizeReport({
422
- mode: 'offline',
423
- clientVersion,
424
- requiredDimension,
425
- incompatible: false,
426
- findings: [
427
- finding('warning', DOCTOR_REASON_CODES.OFFLINE, 'compatibility', REMEDIATION.offline),
428
- finding('warning', DOCTOR_REASON_CODES.RELEASE_LIFECYCLE_UNAVAILABLE, 'releaseLifecycle', REMEDIATION.lifecycle),
429
- ],
430
- });
431
- }
432
- export async function runDoctor(options, dependencies = {}) {
433
- const clientVersion = (dependencies.getClientVersion ?? getClientVersion)();
434
- if (options.mode === 'offline')
435
- return offlineReport(clientVersion, options.requiredDimension);
436
- const authority = await (dependencies.loadCompatibilityAuthority ?? loadSharedCompatibilityAuthority)();
437
- if (!authority) {
438
- return finalizeReport({
439
- mode: 'online', clientVersion, requiredDimension: options.requiredDimension, incompatible: true,
440
- findings: [finding('error', DOCTOR_REASON_CODES.AUTHORITY_UNAVAILABLE, 'compatibility', REMEDIATION.authority)],
441
- });
442
- }
443
- let offer;
444
- try {
445
- offer = authority.createCompatibilityOffer({
446
- clientVersion,
447
- registryVersion: COMMAND_REGISTRY_VERSION,
448
- registryChecksum: COMMAND_REGISTRY_CHECKSUM,
449
- });
450
- }
451
- catch {
452
- return finalizeReport({
453
- mode: 'online', clientVersion, requiredDimension: options.requiredDimension, incompatible: true,
454
- findings: [finding('error', DOCTOR_REASON_CODES.AUTHORITY_UNAVAILABLE, 'compatibility', REMEDIATION.authority)],
455
- });
456
- }
457
- const releaseContext = (dependencies.collectReleaseContext ?? collectLocalReleaseLifecycleContext)(options.projectRoot, authority);
458
- const fetcher = dependencies.fetch ?? globalThis.fetch;
459
- const remote = await fetchDoctorResponse(fetcher, options.serverUrl, offer, releaseContext);
460
- if (remote.kind === 'unreachable') {
461
- return finalizeReport({
462
- mode: 'online', clientVersion, requiredDimension: options.requiredDimension, incompatible: false,
463
- findings: [
464
- finding('warning', DOCTOR_REASON_CODES.SERVER_UNREACHABLE, 'compatibility', REMEDIATION.unreachable),
465
- finding('warning', DOCTOR_REASON_CODES.RELEASE_LIFECYCLE_UNAVAILABLE, 'releaseLifecycle', REMEDIATION.lifecycle),
466
- ],
467
- });
468
- }
469
- if (remote.kind === 'server-too-old') {
470
- return finalizeReport({
471
- mode: 'online', clientVersion, requiredDimension: options.requiredDimension, incompatible: true,
472
- findings: [
473
- finding('error', DOCTOR_REASON_CODES.SERVER_TOO_OLD, 'compatibility', REMEDIATION.serverTooOld),
474
- finding('warning', DOCTOR_REASON_CODES.RELEASE_LIFECYCLE_UNAVAILABLE, 'releaseLifecycle', REMEDIATION.lifecycle),
475
- ],
476
- });
477
- }
478
- if (remote.kind === 'malformed') {
479
- return finalizeReport({
480
- mode: 'online', clientVersion, requiredDimension: options.requiredDimension, incompatible: true,
481
- findings: [finding('error', DOCTOR_REASON_CODES.MALFORMED_RESPONSE, 'compatibility', REMEDIATION.malformed)],
482
- });
483
- }
484
- const envelope = responseEnvelope(remote.value);
485
- if (!envelope || !authority.isCompatibilityResultV1(envelope.compatibility)) {
486
- return finalizeReport({
487
- mode: 'online', clientVersion, requiredDimension: options.requiredDimension, incompatible: true,
488
- findings: [finding('error', DOCTOR_REASON_CODES.MALFORMED_RESPONSE, 'compatibility', REMEDIATION.malformed)],
489
- });
490
- }
491
- const result = asCompatibilityBoundary(envelope.compatibility);
492
- if (!result || result.clientVersion !== clientVersion) {
493
- return finalizeReport({
494
- mode: 'online', clientVersion, requiredDimension: options.requiredDimension, incompatible: true,
495
- findings: [finding('error', DOCTOR_REASON_CODES.MALFORMED_RESPONSE, 'compatibility', REMEDIATION.malformed)],
496
- });
497
- }
498
- const compatibility = Object.freeze({
499
- status: result.status,
500
- clientVersion,
501
- serverVersion: result.serverVersion,
502
- protocolVersion: result.protocolVersion,
503
- schemaVersions: safeIdentifiers(result.schemaVersions),
504
- capabilityIds: safeIdentifiers(result.capabilityIds),
505
- registry: Object.freeze({
506
- localVersion: COMMAND_REGISTRY_VERSION,
507
- localChecksum: COMMAND_REGISTRY_CHECKSUM,
508
- remoteVersion: result.commandRegistry.version,
509
- remoteChecksum: result.commandRegistry.checksum,
510
- status: result.commandRegistry.status,
511
- }),
512
- });
513
- const findings = [];
514
- const resultReasons = safeReasons(result.reasonCodes);
515
- const versionOrder = compareVersions(clientVersion, result.serverVersion);
516
- if (result.status === 'incompatible' && versionOrder === -1) {
517
- findings.push(finding('error', DOCTOR_REASON_CODES.CLIENT_TOO_OLD, 'compatibility', REMEDIATION.clientTooOld, `client-version:${clientVersion}`));
518
- }
519
- else if (result.status === 'incompatible' && versionOrder === 1) {
520
- findings.push(finding('error', DOCTOR_REASON_CODES.SERVER_TOO_OLD, 'compatibility', REMEDIATION.serverTooOld, `server-version:${result.serverVersion}`));
521
- }
522
- if (resultReasons.some((reason) => reason.includes('protocol'))) {
523
- findings.push(finding('error', DOCTOR_REASON_CODES.PROTOCOL_MISMATCH, 'compatibility', REMEDIATION.protocol));
524
- }
525
- if (resultReasons.some((reason) => reason.includes('schema'))) {
526
- findings.push(finding('error', DOCTOR_REASON_CODES.SCHEMA_MISMATCH, 'compatibility', REMEDIATION.schema));
527
- }
528
- if (resultReasons.some((reason) => reason.includes('capability'))) {
529
- findings.push(finding('error', DOCTOR_REASON_CODES.CAPABILITY_MISMATCH, 'compatibility', REMEDIATION.capability));
530
- }
531
- if (result.commandRegistry.status === 'mismatched'
532
- || result.commandRegistry.version !== COMMAND_REGISTRY_VERSION
533
- || result.commandRegistry.checksum !== COMMAND_REGISTRY_CHECKSUM) {
534
- findings.push(finding('error', DOCTOR_REASON_CODES.REGISTRY_DRIFT, 'compatibility', REMEDIATION.registry, `sha256:${result.commandRegistry.checksum}`));
535
- }
536
- if (result.status === 'incompatible' && findings.length === 0) {
537
- findings.push(finding('error', DOCTOR_REASON_CODES.MALFORMED_RESPONSE, 'compatibility', REMEDIATION.malformed));
538
- }
539
- else if (result.status === 'degraded') {
540
- for (const reason of resultReasons)
541
- findings.push(finding('warning', reason, 'compatibility', REMEDIATION.lifecycle));
542
- }
543
- let dimensions = unknownDimensions();
544
- let candidateId = null;
545
- let lineageSha256 = null;
546
- let lifecycleMalformed = false;
547
- if (envelope.releaseLifecycle === undefined) {
548
- findings.push(finding('warning', DOCTOR_REASON_CODES.RELEASE_LIFECYCLE_UNAVAILABLE, 'releaseLifecycle', REMEDIATION.lifecycle));
549
- }
550
- else {
551
- const validation = authority.validateReleaseLifecycle(envelope.releaseLifecycle);
552
- const projection = validation.accepted ? asLifecycleProjection(validation.projection) : null;
553
- if (!projection) {
554
- lifecycleMalformed = true;
555
- findings.push(finding('error', DOCTOR_REASON_CODES.MALFORMED_RESPONSE, 'releaseLifecycle', REMEDIATION.malformed));
556
- for (const reason of safeReasons(validation.reasonCodes)) {
557
- findings.push(finding('error', reason, 'releaseLifecycle', REMEDIATION.lifecycle));
558
- }
559
- }
560
- else {
561
- candidateId = projection.candidateId;
562
- lineageSha256 = projection.lineageSha256;
563
- const mapped = {};
564
- for (const name of DIMENSIONS) {
565
- const source = projection[name];
566
- mapped[name] = Object.freeze({
567
- value: source.value,
568
- freshness: source.freshness,
569
- reasonCodes: safeReasons(source.reasonCodes),
570
- evidenceRefs: safeEvidenceRefs(source.evidenceRefs),
571
- });
572
- if (source.value !== true || source.freshness !== 'fresh') {
573
- for (const reason of safeReasons(source.reasonCodes)) {
574
- findings.push(finding('warning', reason, name, REMEDIATION.lifecycle, safeEvidenceRefs(source.evidenceRefs)[0] ?? null));
575
- }
576
- }
577
- }
578
- dimensions = Object.freeze(mapped);
579
- }
580
- }
581
- if (findings.length === 0)
582
- findings.push(finding('info', DOCTOR_REASON_CODES.HEALTHY, 'compatibility', REMEDIATION.healthy));
583
- return finalizeReport({
584
- mode: 'online',
585
- clientVersion,
586
- compatibility,
587
- dimensions,
588
- candidateId,
589
- lineageSha256,
590
- requiredDimension: options.requiredDimension,
591
- findings,
592
- incompatible: result.status === 'incompatible' || lifecycleMalformed,
593
- });
594
- }
595
- export function renderDoctorReport(report) {
596
- const lines = [
597
- 'Neocortex compatibility and release doctor (read-only)',
598
- `Result: ${report.overall} (exit ${report.exitCode})`,
599
- `Mode: ${report.mode}`,
600
- `Compatibility: ${report.compatibility.status}`,
601
- `Client: ${report.compatibility.clientVersion}`,
602
- `Server: ${report.compatibility.serverVersion ?? 'unknown'}`,
603
- `Registry: ${report.compatibility.registry.status}`,
604
- '',
605
- 'Release lifecycle:',
606
- ];
607
- for (const name of DIMENSIONS) {
608
- const dimension = report.release.dimensions[name];
609
- lines.push(` ${name}: ${String(dimension.value)} (${dimension.freshness}) [${dimension.reasonCodes.join(',') || 'none'}]`);
610
- }
611
- lines.push('', 'Ordered findings:');
612
- for (const item of report.findings) {
613
- lines.push(` ${item.severity.toUpperCase()} ${item.reasonCode} dimension=${item.affectedDimension} evidence=${item.evidenceRef ?? 'none'}`);
614
- lines.push(` ${item.remediation}`);
615
- }
616
- lines.push('', 'Doctor made no repairs or state changes.');
617
- return lines.join('\n');
618
- }
619
- export async function doctorCliHandler(args, dependencies = {}) {
620
- const stdout = dependencies.stdout ?? console.log;
621
- const stderr = dependencies.stderr ?? console.error;
622
- let options;
623
- try {
624
- options = parseDoctorArgs(args, dependencies.env ?? process.env);
625
- }
626
- catch (error) {
627
- const reasonCode = error instanceof Error && SAFE_REASON.test(error.message)
628
- ? error.message : 'doctor-argument-invalid';
629
- stderr(`Error: ${reasonCode}`);
630
- return DOCTOR_EXIT_CODES.USAGE;
631
- }
632
- const report = await runDoctor(options, dependencies);
633
- stdout(options.json ? JSON.stringify(report, null, 2) : renderDoctorReport(report));
634
- return report.exitCode;
635
- }
1
+ import{Buffer as L}from"node:buffer";import{createHash as M}from"node:crypto";import{execFileSync as B}from"node:child_process";import{readFileSync as P,statSync as Y}from"node:fs";import{join as G,resolve as J}from"node:path";import{COMMAND_REGISTRY_CHECKSUM as A,COMMAND_REGISTRY_VERSION as C}from"../generated/command-registry.generated.js";import{DEFAULT_SERVER_URL as z}from"../constants.js";import{getClientVersion as Z}from"../version.js";const K="CompatibilityReleaseDoctor/1.0",X="CompatibilityDoctorResponse/1.0",I=Object.freeze({SUCCESS:0,BLOCKED:1,USAGE:2}),n=Object.freeze({HEALTHY:"doctor-healthy",OFFLINE:"doctor-offline",SERVER_UNREACHABLE:"server-unreachable",CLIENT_TOO_OLD:"client-too-old",SERVER_TOO_OLD:"server-too-old",PROTOCOL_MISMATCH:"protocol-mismatch",SCHEMA_MISMATCH:"schema-mismatch",CAPABILITY_MISMATCH:"capability-mismatch",REGISTRY_DRIFT:"registry-drift",MALFORMED_RESPONSE:"malformed-response",AUTHORITY_UNAVAILABLE:"compatibility-authority-unavailable",RELEASE_LIFECYCLE_UNAVAILABLE:"release-lifecycle-unavailable",REQUIRED_DIMENSION_BLOCKED:"required-release-dimension-blocked"}),v=Object.freeze(["implementationComplete","betaOperable","releaseReady","productionPromoted"]),Q=64*1024,W=32,ee=5e3,k=/^[a-z][a-z0-9-]{0,63}$/u,D=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/u,g=/^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][A-Za-z0-9.-]{1,40})?$/u,re=/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u,U=/^[a-f0-9]{64}$/u,te=/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/u,ie=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,oe=/^(?:local-gate|beta-receipt|release-gate|promotion-receipt|sha256):[a-f0-9]{64}$/u,l=Object.freeze({healthy:"No compatibility remediation is required.",offline:"Rerun without --offline when read-only server evidence is available.",unreachable:"Check read-only server reachability, then rerun doctor.",clientTooOld:"Run a separately authorized client update, then rerun doctor.",serverTooOld:"Ask an authorized server operator to update the server, then rerun doctor.",protocol:"Align client and server protocol releases before invoking protected operations.",schema:"Use a client and server pair that supports the required public schemas.",capability:"Enable no feature here; use a release pair with the required capability set.",registry:"Install an exact release pair with the same command-registry checksum.",malformed:"Contact support with the reason code only; do not attach raw response data.",authority:"Integrate the P223.01 shared compatibility authority, then rerun doctor.",lifecycle:"Obtain bounded physical release evidence through separately authorized operations.",required:"Satisfy and verify the required physical release dimension through a separately authorized operation."}),F=new Map([[n.MALFORMED_RESPONSE,0],[n.AUTHORITY_UNAVAILABLE,1],[n.CLIENT_TOO_OLD,2],[n.SERVER_TOO_OLD,3],[n.PROTOCOL_MISMATCH,4],[n.SCHEMA_MISMATCH,5],[n.CAPABILITY_MISMATCH,6],[n.REGISTRY_DRIFT,7],[n.SERVER_UNREACHABLE,8],[n.OFFLINE,9],[n.RELEASE_LIFECYCLE_UNAVAILABLE,10],[n.REQUIRED_DIMENSION_BLOCKED,11],[n.HEALTHY,100]]);function q(e="release-evidence-unavailable"){const r=()=>Object.freeze({value:"unknown",freshness:"unknown",reasonCodes:Object.freeze([e]),evidenceRefs:Object.freeze([])});return Object.freeze({implementationComplete:r(),betaOperable:r(),releaseReady:r(),productionPromoted:r()})}function ne(e){const r=Object.freeze({implementation:"implementationComplete","implementation-complete":"implementationComplete",beta:"betaOperable","beta-operable":"betaOperable",release:"releaseReady","release-ready":"releaseReady",production:"productionPromoted","production-promoted":"productionPromoted"});return e?r[e]??null:null}function se(e,r=process.env){let t="online",i=!1,o=r.NEOCORTEX_SERVER_URL??z,c=!1,f=null,u=process.cwd();for(let a=0;a<e.length;a+=1){const s=e[a];if(s==="--offline")t="offline";else if(s==="--json")i=!0;else if(s==="--server-url"){const p=e[a+1];if(!p)throw new Error("doctor-server-url-required");o=p,c=!0,a+=1}else if(s==="--require"){const p=e[a+1],m=ne(p);if(!p||!m)throw new Error("doctor-required-dimension-invalid");f=m,a+=1}else if(s==="--project-root"){const p=e[a+1];if(!p||p.length>4096||p.includes("\0"))throw new Error("doctor-project-root-invalid");u=J(p),a+=1}else throw new Error("doctor-argument-invalid")}if(t==="offline"&&c)throw new Error("doctor-offline-server-url-conflict");if(t==="offline")return Object.freeze({mode:t,json:i,serverUrl:z,requiredDimension:f,projectRoot:u});if(o.length>2048)throw new Error("doctor-server-url-invalid");try{const a=new URL(o);if(a.protocol!=="http:"&&a.protocol!=="https:"||a.username||a.password||a.search||a.hash)throw new Error("url")}catch{throw new Error("doctor-server-url-invalid")}return Object.freeze({mode:t,json:i,serverUrl:o.replace(/\/+$/u,""),requiredDimension:f,projectRoot:u})}function ae(e){if(!e||typeof e!="object")return!1;const r=e;return typeof r.createCompatibilityOffer=="function"&&typeof r.isCompatibilityResultV1=="function"&&typeof r.validateReleaseLifecycle=="function"}async function ce(){const e=["@neocortex/shared/compatibility","../../../shared/dist/compatibility/index.js"];for(const r of e)try{const t=await import(r);if(ae(t))return t}catch{}return null}function le(e,r){if(typeof r.createReleaseLifecycleContext!="function")return null;try{const t=G(e,".neocortex","state.json"),i=Y(t);if(!i.isFile()||i.size<=0||i.size>1024*1024)return null;const o=JSON.parse(P(t,"utf8")),f=(o.config&&typeof o.config=="object"&&!Array.isArray(o.config)?o.config:o.project&&typeof o.project=="object"&&!Array.isArray(o.project)?o.project:null)?.project_id;if(typeof f!="string"||!te.test(f))return null;const u=B("git",["rev-parse","--verify","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"]}).trim().toLowerCase();if(!ie.test(u))return null;const a=M("sha256").update("git-lineage-v1\0").update(u).digest("hex"),s=`candidate-${M("sha256").update("release-candidate-v1\0").update(f).update("\0").update(u).digest("hex").slice(0,32)}`;return r.createReleaseLifecycleContext({projectId:f,candidateId:s,lineageSha256:a})}catch{return null}}function d(e,r,t,i,o=null){return Object.freeze({severity:e,reasonCode:r,affectedDimension:t,evidenceRef:o,remediation:i})}function de(e,r){if(!g.test(e)||!g.test(r))return null;const t=c=>c.split(/[-+]/u,1)[0].split(".").map(Number),i=t(e),o=t(r);for(let c=0;c<3;c+=1)if(i[c]!==o[c])return i[c]<o[c]?-1:1;return 0}function S(e){return Object.freeze([...new Set(e.filter(r=>k.test(r)))].slice(0,8).sort())}function x(e){return Object.freeze([...new Set(e.filter(r=>D.test(r)))].slice(0,32).sort())}function H(e){return Object.freeze([...new Set(e.filter(r=>oe.test(r)))].slice(0,8).sort())}function fe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,t=r.commandRegistry;return!["compatible","degraded","incompatible"].includes(String(r.status))||typeof r.clientVersion!="string"||!g.test(r.clientVersion)||typeof r.serverVersion!="string"||!g.test(r.serverVersion)||!(r.protocolVersion===null||typeof r.protocolVersion=="string"&&D.test(r.protocolVersion))||!Array.isArray(r.schemaVersions)||!r.schemaVersions.every(i=>typeof i=="string")||!Array.isArray(r.capabilityIds)||!r.capabilityIds.every(i=>typeof i=="string")||!Array.isArray(r.reasonCodes)||!r.reasonCodes.every(i=>typeof i=="string")||!t||typeof t.version!="string"||!re.test(t.version)||typeof t.checksum!="string"||!U.test(t.checksum)||!["matched","mismatched","unknown"].includes(String(t.status))?null:r}function ue(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;if(typeof r.candidateId!="string"||!D.test(r.candidateId)||typeof r.lineageSha256!="string"||!U.test(r.lineageSha256))return null;for(const t of v){const i=r[t];if(!i||typeof i!="object"||Array.isArray(i))return null;const o=i;if(!(typeof o.value=="boolean"||o.value==="unknown")||!["fresh","stale","unknown"].includes(String(o.freshness))||!Array.isArray(o.reasonCodes)||!o.reasonCodes.every(c=>typeof c=="string")||!Array.isArray(o.evidenceRefs)||!o.evidenceRefs.every(c=>typeof c=="string"))return null}return r}function me(e){const r={error:0,warning:1,info:2},t=new Map([["compatibility",0],["releaseLifecycle",1],["implementationComplete",2],["betaOperable",3],["releaseReady",4],["productionPromoted",5]]);return Object.freeze([...e].sort((i,o)=>r[i.severity]-r[o.severity]||(F.get(i.reasonCode)??50)-(F.get(o.reasonCode)??50)||(t.get(i.affectedDimension)??99)-(t.get(o.affectedDimension)??99)||i.reasonCode.localeCompare(o.reasonCode)).slice(0,W))}function pe(e){return Object.freeze({status:"unknown",clientVersion:e,serverVersion:null,protocolVersion:null,schemaVersions:Object.freeze([]),capabilityIds:Object.freeze([]),registry:Object.freeze({localVersion:C,localChecksum:A,remoteVersion:null,remoteChecksum:null,status:"unknown"})})}function E(e){const r=[...e.findings],t=e.dimensions??q();let i=e.incompatible;e.requiredDimension&&t[e.requiredDimension].value!==!0&&(i=!0,r.push(d("error",n.REQUIRED_DIMENSION_BLOCKED,e.requiredDimension,l.required,t[e.requiredDimension].evidenceRefs[0]??null)));const o=me(r),c=i?"incompatible":o.some(f=>f.severity==="warning")?"degraded":"healthy";return Object.freeze({schemaVersion:K,publicSafe:!0,readOnly:!0,mode:e.mode,overall:c,exitCode:i?I.BLOCKED:I.SUCCESS,compatibility:e.compatibility??pe(e.clientVersion),release:Object.freeze({candidateId:e.candidateId??null,lineageSha256:e.lineageSha256??null,requiredDimension:e.requiredDimension,dimensions:t}),findings:o})}function ye(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;return"compatibility"in r?r.schemaVersion!==void 0&&r.schemaVersion!==X?null:{compatibility:r.compatibility,...r.releaseLifecycle!==void 0?{releaseLifecycle:r.releaseLifecycle}:{}}:{compatibility:e}}async function Ee(e,r,t,i){const o=new AbortController,c=setTimeout(()=>o.abort(),ee);try{const f=L.from(JSON.stringify(t),"utf8").toString("base64url");if(f.length>8192)return{kind:"malformed"};const u=i===null?null:L.from(JSON.stringify(i),"utf8").toString("base64url");if(u&&u.length>2048)return{kind:"malformed"};const a=await e(`${r}/api/v1/compatibility`,{method:"GET",headers:Object.freeze({Accept:"application/json","Cache-Control":"no-store","X-Neocortex-Compatibility-Offer":f,...u?{"X-Neocortex-Release-Context":u}:{}}),signal:o.signal});if(a.status===404||a.status===405||a.status===426)return{kind:"server-too-old"};if(!a.ok)return a.status>=500?{kind:"unreachable"}:{kind:"malformed"};const s=await a.text();if(L.byteLength(s,"utf8")>Q)return{kind:"malformed"};try{return{kind:"ok",value:JSON.parse(s)}}catch{return{kind:"malformed"}}}catch{return{kind:"unreachable"}}finally{clearTimeout(c)}}function he(e,r){return E({mode:"offline",clientVersion:e,requiredDimension:r,incompatible:!1,findings:[d("warning",n.OFFLINE,"compatibility",l.offline),d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]})}async function be(e,r={}){const t=(r.getClientVersion??Z)();if(e.mode==="offline")return he(t,e.requiredDimension);const i=await(r.loadCompatibilityAuthority??ce)();if(!i)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]});let o;try{o=i.createCompatibilityOffer({clientVersion:t,registryVersion:C,registryChecksum:A})}catch{return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]})}const c=(r.collectReleaseContext??le)(e.projectRoot,i),f=r.fetch??globalThis.fetch,u=await Ee(f,e.serverUrl,o,c);if(u.kind==="unreachable")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!1,findings:[d("warning",n.SERVER_UNREACHABLE,"compatibility",l.unreachable),d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(u.kind==="server-too-old")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.SERVER_TOO_OLD,"compatibility",l.serverTooOld),d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(u.kind==="malformed")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const a=ye(u.value);if(!a||!i.isCompatibilityResultV1(a.compatibility))return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const s=fe(a.compatibility);if(!s||s.clientVersion!==t)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const p=Object.freeze({status:s.status,clientVersion:t,serverVersion:s.serverVersion,protocolVersion:s.protocolVersion,schemaVersions:x(s.schemaVersions),capabilityIds:x(s.capabilityIds),registry:Object.freeze({localVersion:C,localChecksum:A,remoteVersion:s.commandRegistry.version,remoteChecksum:s.commandRegistry.checksum,status:s.commandRegistry.status})}),m=[],b=S(s.reasonCodes),T=de(t,s.serverVersion);if(s.status==="incompatible"&&T===-1?m.push(d("error",n.CLIENT_TOO_OLD,"compatibility",l.clientTooOld,`client-version:${t}`)):s.status==="incompatible"&&T===1&&m.push(d("error",n.SERVER_TOO_OLD,"compatibility",l.serverTooOld,`server-version:${s.serverVersion}`)),b.some(y=>y.includes("protocol"))&&m.push(d("error",n.PROTOCOL_MISMATCH,"compatibility",l.protocol)),b.some(y=>y.includes("schema"))&&m.push(d("error",n.SCHEMA_MISMATCH,"compatibility",l.schema)),b.some(y=>y.includes("capability"))&&m.push(d("error",n.CAPABILITY_MISMATCH,"compatibility",l.capability)),(s.commandRegistry.status==="mismatched"||s.commandRegistry.version!==C||s.commandRegistry.checksum!==A)&&m.push(d("error",n.REGISTRY_DRIFT,"compatibility",l.registry,`sha256:${s.commandRegistry.checksum}`)),s.status==="incompatible"&&m.length===0)m.push(d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed));else if(s.status==="degraded")for(const y of b)m.push(d("warning",y,"compatibility",l.lifecycle));let V=q(),N=null,w=null,j=!1;if(a.releaseLifecycle===void 0)m.push(d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle));else{const y=i.validateReleaseLifecycle(a.releaseLifecycle),O=y.accepted?ue(y.projection):null;if(O){N=O.candidateId,w=O.lineageSha256;const R={};for(const _ of v){const h=O[_];if(R[_]=Object.freeze({value:h.value,freshness:h.freshness,reasonCodes:S(h.reasonCodes),evidenceRefs:H(h.evidenceRefs)}),h.value!==!0||h.freshness!=="fresh")for(const $ of S(h.reasonCodes))m.push(d("warning",$,_,l.lifecycle,H(h.evidenceRefs)[0]??null))}V=Object.freeze(R)}else{j=!0,m.push(d("error",n.MALFORMED_RESPONSE,"releaseLifecycle",l.malformed));for(const R of S(y.reasonCodes))m.push(d("error",R,"releaseLifecycle",l.lifecycle))}}return m.length===0&&m.push(d("info",n.HEALTHY,"compatibility",l.healthy)),E({mode:"online",clientVersion:t,compatibility:p,dimensions:V,candidateId:N,lineageSha256:w,requiredDimension:e.requiredDimension,findings:m,incompatible:s.status==="incompatible"||j})}function Oe(e){const r=["Neocortex compatibility and release doctor (read-only)",`Result: ${e.overall} (exit ${e.exitCode})`,`Mode: ${e.mode}`,`Compatibility: ${e.compatibility.status}`,`Client: ${e.compatibility.clientVersion}`,`Server: ${e.compatibility.serverVersion??"unknown"}`,`Registry: ${e.compatibility.registry.status}`,"","Release lifecycle:"];for(const t of v){const i=e.release.dimensions[t];r.push(` ${t}: ${String(i.value)} (${i.freshness}) [${i.reasonCodes.join(",")||"none"}]`)}r.push("","Ordered findings:");for(const t of e.findings)r.push(` ${t.severity.toUpperCase()} ${t.reasonCode} dimension=${t.affectedDimension} evidence=${t.evidenceRef??"none"}`),r.push(` ${t.remediation}`);return r.push("","Doctor made no repairs or state changes."),r.join(`
2
+ `)}async function ve(e,r={}){const t=r.stdout??console.log,i=r.stderr??console.error;let o;try{o=se(e,r.env??process.env)}catch(f){const u=f instanceof Error&&k.test(f.message)?f.message:"doctor-argument-invalid";return i(`Error: ${u}`),I.USAGE}const c=await be(o,r);return t(o.json?JSON.stringify(c,null,2):Oe(c)),c.exitCode}export{I as DOCTOR_EXIT_CODES,n as DOCTOR_REASON_CODES,X as DOCTOR_RESPONSE_SCHEMA_VERSION,K as DOCTOR_SCHEMA_VERSION,le as collectLocalReleaseLifecycleContext,ve as doctorCliHandler,ce as loadSharedCompatibilityAuthority,se as parseDoctorArgs,Oe as renderDoctorReport,be as runDoctor};