@ornexus/neocortex 4.60.66 → 4.60.68

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 (236) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1598 -1640
  3. package/install.ps1 +1 -1
  4. package/install.sh +2 -1
  5. package/package.json +10 -7
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +212 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +417 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +251 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +108 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +303 -3
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.d.ts +135 -0
  37. package/packages/client/dist/commands/doctor.js +635 -0
  38. package/packages/client/dist/commands/invoke.d.ts +18 -0
  39. package/packages/client/dist/commands/invoke.js +7140 -142
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  41. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  42. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  44. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  45. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  46. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  47. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  49. package/packages/client/dist/commands/mutation-qa.js +220 -1
  50. package/packages/client/dist/commands/native-agent.js +136 -2
  51. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  52. package/packages/client/dist/commands/planning-generation.js +53 -1
  53. package/packages/client/dist/commands/planning-memory.js +40 -1
  54. package/packages/client/dist/commands/planning-research.js +42 -1
  55. package/packages/client/dist/commands/private-session.js +75 -1
  56. package/packages/client/dist/commands/property-qa.js +139 -1
  57. package/packages/client/dist/commands/qa-control.js +16 -1
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  60. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  61. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  62. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  68. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  69. package/packages/client/dist/commands/refactor-commit.js +399 -13
  70. package/packages/client/dist/commands/refactor-control.js +142 -3
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  72. package/packages/client/dist/commands/refactor-review.js +283 -5
  73. package/packages/client/dist/commands/refactor-root.js +588 -7
  74. package/packages/client/dist/commands/refresh-memory.js +156 -3
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  76. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  77. package/packages/client/dist/config/profile-directory.js +13 -1
  78. package/packages/client/dist/config/resolver-selection.js +278 -1
  79. package/packages/client/dist/config/secure-config.js +281 -12
  80. package/packages/client/dist/config.js +223 -2
  81. package/packages/client/dist/constants.js +25 -1
  82. package/packages/client/dist/context/context-collector.js +222 -2
  83. package/packages/client/dist/context/context-sanitizer.js +145 -1
  84. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  85. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  86. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  87. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  88. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  89. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  90. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  91. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  92. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  93. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  94. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  95. package/packages/client/dist/continuity/outbox.js +117 -1
  96. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  97. package/packages/client/dist/continuity/sqlite-store.js +2536 -81
  98. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  99. package/packages/client/dist/errors/error-messages.js +228 -2
  100. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  101. package/packages/client/dist/evidence/collector.js +347 -1
  102. package/packages/client/dist/evidence/index.js +1 -1
  103. package/packages/client/dist/evidence/types.js +2 -0
  104. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  105. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  106. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  107. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  108. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  109. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  110. package/packages/client/dist/git/git-lifecycle-store.js +1938 -9
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  113. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  117. package/packages/client/dist/i18n/first-run.js +60 -2
  118. package/packages/client/dist/index.js +47 -1
  119. package/packages/client/dist/invocation/invoke-input.js +24 -1
  120. package/packages/client/dist/license/index.js +5 -1
  121. package/packages/client/dist/license/license-client.js +304 -1
  122. package/packages/client/dist/machine/fingerprint.js +163 -2
  123. package/packages/client/dist/machine/index.js +5 -1
  124. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  125. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  126. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  127. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  128. package/packages/client/dist/migrations/project-identity.js +493 -7
  129. package/packages/client/dist/migrations/state-json.js +344 -4
  130. package/packages/client/dist/policy/architecture-policy.js +184 -2
  131. package/packages/client/dist/policy/index.js +7 -1
  132. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  133. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  134. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  135. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  136. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  137. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  138. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  139. package/packages/client/dist/private-execution/delivery.js +410 -13
  140. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  141. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  142. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  143. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  144. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  145. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  146. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  147. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  148. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  149. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  150. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  151. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  152. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  153. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  154. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  155. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  156. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  157. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  158. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  159. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  160. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  161. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  162. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  163. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  164. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  165. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  166. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  167. package/packages/client/dist/private-execution/session-lease.js +63 -1
  168. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  169. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  170. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  171. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  172. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  173. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  174. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  175. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  176. package/packages/client/dist/resilience/index.js +8 -1
  177. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  178. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  179. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  180. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  181. package/packages/client/dist/runner/binary.js +404 -1
  182. package/packages/client/dist/runner/cli.js +1571 -17
  183. package/packages/client/dist/runner/headless/adapters.js +49 -1
  184. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  185. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  186. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  187. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  188. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  189. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  190. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  191. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  192. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  193. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  194. package/packages/client/dist/runner/headless/resolver.js +231 -1
  195. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  196. package/packages/client/dist/runner/headless/run-yoloop.d.ts +4 -1
  197. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  198. package/packages/client/dist/runner/headless/types.js +574 -2
  199. package/packages/client/dist/runner/local-console.js +396 -13
  200. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  201. package/packages/client/dist/runner/project-identity.js +106 -1
  202. package/packages/client/dist/runner/scheduler.js +995 -7
  203. package/packages/client/dist/runner-cli.js +18 -2
  204. package/packages/client/dist/state/invocation-shape.js +13 -1
  205. package/packages/client/dist/state/project-state-snapshot.js +1677 -1
  206. package/packages/client/dist/state/state-json-repair.js +785 -3
  207. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  208. package/packages/client/dist/telemetry/index.js +5 -1
  209. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  210. package/packages/client/dist/tier/index.js +5 -1
  211. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  212. package/packages/client/dist/types/index.js +38 -1
  213. package/packages/client/dist/version.js +27 -1
  214. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  215. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  216. package/packages/client/dist/yolo/spec-envelope-collector.js +185 -5
  217. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  218. package/packages/client/dist/yoloop/index.js +8 -1
  219. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  220. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  221. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  222. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  223. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1723 -1
  224. package/packages/shared/dist/compatibility/index.js +476 -0
  225. package/packages/shared/dist/yoloop/release-blocked.js +653 -0
  226. package/targets-stubs/antigravity/gemini.md +1 -1
  227. package/targets-stubs/antigravity/skill/SKILL.md +3 -2
  228. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  229. package/targets-stubs/claude-code/neocortex-root.md +5 -5
  230. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  231. package/targets-stubs/claude-code/neocortex.md +8 -9
  232. package/targets-stubs/codex/AGENTS.md +3 -3
  233. package/targets-stubs/cursor/agent.md +4 -3
  234. package/targets-stubs/gemini-cli/agent.md +5 -4
  235. package/targets-stubs/opencode/neocortex-root.md +3 -3
  236. package/targets-stubs/vscode/neocortex.agent.md +5 -4
@@ -0,0 +1,635 @@
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
+ }