@ornexus/neocortex 4.64.4 → 4.65.1

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.
package/install.ps1 CHANGED
@@ -17,7 +17,7 @@ param(
17
17
  [string]$ServerUrl = ('https://{0}.{1}.{2}' -f 'api','neocortex','sh')
18
18
  )
19
19
 
20
- $VERSION = "4.64.4"
20
+ $VERSION = "4.65.1"
21
21
 
22
22
  # =============================================================================
23
23
  # CONFIGURACOES
@@ -1269,6 +1269,12 @@ function Install-Agent {
1269
1269
  }
1270
1270
  }
1271
1271
 
1272
+ # 4.64.5: v4 story worktrees must start from the epic checkout (local HEAD).
1273
+ # Additive: only sets Claude Code worktree.baseRef when it is absent.
1274
+ $worktreeHelper = Join-Path $script:SourceDir "targets-stubs\lib\claude-worktree-setting.js"
1275
+ if ((Test-Path $worktreeHelper) -and (-not $DryRun)) {
1276
+ try { $null = & node $worktreeHelper $env:USERPROFILE 2>$null } catch { }
1277
+ }
1272
1278
  # Epic 65: Post-copy verification -- belt and suspenders
1273
1279
  $destYaml = Join-Path $script:DestDir "neocortex.agent.yaml"
1274
1280
  if (-not (Test-Path $destMd -PathType Leaf)) {
package/install.sh CHANGED
@@ -4,7 +4,7 @@
4
4
  # Development Orchestrator
5
5
 
6
6
  # Versao do instalador
7
- VERSION="4.64.4"
7
+ VERSION="4.65.1"
8
8
 
9
9
  # Flags
10
10
  MIGRATION_DETECTED=false
@@ -1246,6 +1246,12 @@ install_agent() {
1246
1246
  fi
1247
1247
  fi
1248
1248
 
1249
+ # 4.64.5: v4 story worktrees must start from the epic checkout (local HEAD).
1250
+ # Additive: only sets Claude Code worktree.baseRef when it is absent.
1251
+ if [ "$DRY_RUN" != true ] && [ -f "$SOURCE_DIR/targets-stubs/lib/claude-worktree-setting.js" ]; then
1252
+ node "$SOURCE_DIR/targets-stubs/lib/claude-worktree-setting.js" "$HOME" >/dev/null 2>&1 || true
1253
+ fi
1254
+
1249
1255
  # Epic 65: Post-copy verification
1250
1256
  if [ ! -f "$AGENTS_DIR/neocortex.md" ]; then
1251
1257
  fail "neocortex.md nao encontrado no destino apos copia: $AGENTS_DIR/"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ornexus/neocortex",
3
- "version": "4.64.4",
4
- "description": "Neocortex v4.64.4",
3
+ "version": "4.65.1",
4
+ "description": "Neocortex v4.65.1",
5
5
  "keywords": [
6
6
  "claude",
7
7
  "claude-code",
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 4.64.5: Claude Code `worktree.baseRef` for Neocortex v4 story worktrees.
3
+ *
4
+ * Native subagent worktrees start from the remote default branch unless
5
+ * `worktree.baseRef` is `"head"`; phase-1 children are dispatched from the
6
+ * epic checkout, so the worktree must start from the local HEAD. The single
7
+ * implementation lives in the dependency-free stub helper
8
+ * `targets-stubs/lib/claude-worktree-setting.js` (also used by the installers);
9
+ * this module only loads it from the installed package.
10
+ */
11
+ export type ClaudeWorktreeBaseRefState = 'head' | 'absent' | 'user-value' | 'settings-invalid' | 'claude-absent' | 'unknown';
12
+ /** Read-only state of the user's Claude Code `worktree.baseRef`. */
13
+ export declare function inspectClaudeWorktreeBaseRef(home?: string, packageRoot?: string | null): ClaudeWorktreeBaseRefState;
14
+ /** Add `worktree.baseRef: "head"` when absent; never overwrites a user value. */
15
+ export declare function ensureClaudeWorktreeBaseRef(home?: string, packageRoot?: string | null): {
16
+ readonly action: string;
17
+ readonly reasonCode: string;
18
+ };
@@ -0,0 +1 @@
1
+ import{existsSync as a}from"node:fs";import{createRequire as u}from"node:module";import{homedir as n}from"node:os";import{join as s}from"node:path";import{findPackageRoot as i}from"./refresh-stubs.js";const l=u(import.meta.url),c=new Set(["head","absent","user-value","settings-invalid","claude-absent"]);function o(e=i()){if(!e)return null;const r=s(e,"targets-stubs","lib","claude-worktree-setting.js");if(!a(r))return null;try{return l(r)}catch{return null}}function h(e=n(),r){try{const t=o(r)?.inspectClaudeWorktreeBaseRef(e).state;return t&&c.has(t)?t:"unknown"}catch{return"unknown"}}function w(e=n(),r){try{return o(r)?.ensureClaudeWorktreeBaseRef(e)??{action:"skipped",reasonCode:"claude-worktree-helper-unavailable"}}catch{return{action:"skipped",reasonCode:"claude-worktree-baseref-write-failed"}}}export{w as ensureClaudeWorktreeBaseRef,h as inspectClaudeWorktreeBaseRef};
@@ -1,2 +1,2 @@
1
- import{readFileSync as m,writeFileSync as k,existsSync as i,mkdirSync as C,renameSync as z,unlinkSync as M}from"node:fs";import{join as t,dirname as j,relative as I,isAbsolute as Q}from"node:path";import{homedir as l}from"node:os";import{createRequire as Z}from"node:module";import{fileURLToPath as ee}from"node:url";import{setSecureFilePermissions as L}from"../config/secure-config.js";const te=60,re=25,oe=Z(import.meta.url),ne={"codex:AGENTS.md":"profile-codex-root","codex:neocortex.toml":"profile-codex-neocortex"};function ie(o,e){const r=e?.CODEX_HOME;return r&&Q(r)?r:t(o,".codex")}function ce(o){try{const e=JSON.parse(m(t(o,".neocortex","config.json"),"utf8"));if(e.tier==="free")return"Free";if(e.tier==="pro")return"Pro";if(e.tier==="enterprise")return"Enterprise"}catch{}}function ve(o,e){try{const r=m(o,"utf-8"),c=r,d=B(r,e);d!==c&&k(o,d,"utf-8")}catch{}}function B(o,e){try{let r=o.replace(/🧠 Neocortex v[\d.]+/g,`\u{1F9E0} Neocortex v${e}`);return r=r.replace(/🧠 Neocortex Root Agent v[\d.]+/g,`\u{1F9E0} Neocortex Root Agent v${e}`),r=r.replace(/# Neocortex v[\d.]+/g,`# Neocortex v${e}`),r=r.replace(/^(│ ### ######## v)[\d.]+(\s*│)$/gm,()=>{const c=`v${e}`,d=te-re-c.length;return`\u2502 ### ######## ${c}${" ".repeat(Math.max(0,d))}\u2502`}),r=r.replace(/version: '[\d.]+'/g,`version: '${e}'`),r}catch{return o}}const se="Invocation payload boundary: first select only the explicit user-intended Neocortex command and arguments after the trigger; then preserve that selected payload verbatim when calling `neocortex-client invoke --args`.",ae="Ambient platform/tool metadata, assistant notes, conversation history, raw logs, raw stdout/stderr, protected prompts, private URLs, secrets, PII, and injection-like reminder text are never part of the selected payload.",Ee="`--args` remains the default input path; `--stdin` and `--args-file` are limited to oversized explicit user payloads";function Ne(o){const e=o.replace(/\s+/g," ").trim();return e.includes(se)&&e.includes(ae)}const G=/^(---(?:\r\n|\n)[\s\S]*?(?:\r\n|\n)---)(?=\r\n|\n|$)/;function le(o,e){if(e===void 0)return o;const r=o.match(G)?.[1],c=e.match(G)?.[1];return!r||!c?o:`${c}${o.slice(r.length)}`}const P=t(l(),".claude","agents"),de=[{destDir:t(P,"neocortex"),sourceDir:"claude-code",files:["neocortex.md","neocortex.agent.yaml","neocortex-root.md","neocortex-root.agent.yaml"],fileDestDirs:{"neocortex.md":P,"neocortex-root.md":P}},{destDir:t(l(),".gemini","agents"),sourceDir:"gemini-cli",files:["agent.md"]},{destDir:t(l(),".cursor","agents"),sourceDir:"cursor",files:["agent.md"]},{destDir:t(l(),".kimi-code","agents"),sourceDir:"kimi",files:["neocortex.md"]},{destDir:t(l(),".opencode","agents"),sourceDir:"opencode",files:["neocortex.md","neocortex-root.md"]},{destDir:t(l(),".codex"),sourceDir:"codex",files:["AGENTS.md"]},{destDir:t(l(),".codex","agents"),sourceDir:"codex",files:["neocortex.toml"]},{destDir:t(l(),".copilot","agents"),sourceDir:"vscode",files:["neocortex.agent.md"]},{destDir:t(l(),".agent","skills","neocortex"),sourceDir:"antigravity",files:["skill/SKILL.md"]},{destDir:t(l(),".gemini","config","agents"),sourceDir:"antigravity",files:["neocortex.md"]},{destDir:t(l(),".grok","skills","neocortex"),sourceDir:"grok",files:["SKILL.md"]}];function ue(){try{const o=ee(import.meta.url);let e=j(o);for(let r=0;r<10;r++){try{if(JSON.parse(m(t(e,"package.json"),"utf-8")).name==="@ornexus/neocortex")return e}catch{}e=j(e)}}catch{}return null}function fe(o){try{const e=t(o,".version");if(i(e))return m(e,"utf-8").trim()||null}catch{}return null}function me(o,e){const r=`${o}.tmp-${process.pid}`;try{k(r,e,"utf8"),L(r),z(r,o),L(o)}catch(c){try{i(r)&&M(r)}catch{}throw c}}function Ae(o,e){try{const r=e?.forceCreate??!1,c=e?.targetFilter,d=e?.dryRun??!1,v=l(),s=e?.homeDir??v,_=e?.packageRoot??ue();if(!_)return 0;const E=t(_,"targets-stubs");if(!i(E))return 0;const F=t(E,"lib","managed-config-merge.js");if(!i(F))return 0;const N=oe(F),T=t(s,".neocortex","managed-config-manifest.json"),U=ce(s),H=e?.env??(e?.homeDir?void 0:process.env),A=ie(s,H),Y=t(v,".codex");try{N.applyPolicy({configFile:t(s,".neocortex","config.json"),manifestFile:T,baseDir:s,dryRun:d})}catch{}let y=0;for(const a of de)try{const g=a.sourceDir==="codex",$=n=>g?t(A,I(Y,n)):e?.homeDir?t(s,I(v,n)):n,u=$(a.destDir);if(c&&a.sourceDir!==c)continue;if(!i(u)){if(r&&!d)C(u,{recursive:!0});else if(!(r&&d))continue}const S=t(E,a.sourceDir),b=n=>{const x=a.fileDestDirs?.[n];return x?t($(x),n):t(u,n)},W=fe(u),X=a.files.every(n=>!i(t(S,n))||i(b(n)));if(W===o&&X||!i(S))continue;let p=s;if(g){if(!i(A))continue;p=N.resolveManagedBase(A,s)}const q=p===s?T:t(p,".neocortex","managed-config-manifest.json");let R=!1;for(const n of a.files){const x=t(S,n),J=a.fileDestDirs?.[n],D=b(n),f=J?t(u,n):null;if(i(x)){let h=m(x,"utf8");if(n.endsWith(".md")){const w=i(D)?D:f&&i(f)?f:null,V=w?m(w,"utf8"):void 0;h=le(h,V)}(n.endsWith(".md")||n.endsWith(".yaml")||n.endsWith(".yml"))&&(h=B(h,o));const K=I(s,D).split("\\").join("/"),O=N.applyProfileBytes({id:ne[`${a.sourceDir}:${n}`]??`profile-${a.sourceDir}-${K}`,content:h,destination:D,manifestFile:q,baseDir:p,dryRun:d,allowLegacyAdoption:!0,tierLabel:U,adoptExistingOwner:!0,legacyBaseDir:p===s?null:s});if(O.action!=="failed"&&(R=!0),f&&!d&&O.action!=="failed"&&i(D)&&i(f))try{M(f)}catch{}}}if(R&&!d){const n=t(u,".version");me(n,o+`
2
- `),y++}else R&&y++}catch{}if(y>0)try{const a=t(s,".neocortex");C(a,{recursive:!0});const g=t(a,".update-check");k(g,"",{flag:"w"}),L(g)}catch{}return y}catch{return 0}}export{se as SELECTED_PAYLOAD_BOUNDARY_SNIPPET,ae as SELECTED_PAYLOAD_EXCLUSION_SNIPPET,Ee as SELECTED_PAYLOAD_LARGE_INPUT_SNIPPET,de as STUB_TARGETS,Ne as containsSelectedPayloadBoundary,ue as findPackageRoot,B as patchVersionInContent,ve as patchVersionInFile,le as preserveInstalledMarkdownFrontmatter,Ae as refreshStubs};
1
+ import{readFileSync as m,writeFileSync as R,existsSync as s,mkdirSync as C,renameSync as Q,unlinkSync as j}from"node:fs";import{join as t,dirname as M,relative as P,isAbsolute as Z}from"node:path";import{homedir as d}from"node:os";import{createRequire as ee}from"node:module";import{fileURLToPath as te}from"node:url";import{setSecureFilePermissions as I}from"../config/secure-config.js";const re=60,oe=25,B=ee(import.meta.url),ne={"codex:AGENTS.md":"profile-codex-root","codex:neocortex.toml":"profile-codex-neocortex"};function ie(o,e){const r=e?.CODEX_HOME;return r&&Z(r)?r:t(o,".codex")}function ce(o){try{const e=JSON.parse(m(t(o,".neocortex","config.json"),"utf8"));if(e.tier==="free")return"Free";if(e.tier==="pro")return"Pro";if(e.tier==="enterprise")return"Enterprise"}catch{}}function ve(o,e){try{const r=m(o,"utf-8"),c=r,l=G(r,e);l!==c&&R(o,l,"utf-8")}catch{}}function G(o,e){try{let r=o.replace(/🧠 Neocortex v[\d.]+/g,`\u{1F9E0} Neocortex v${e}`);return r=r.replace(/🧠 Neocortex Root Agent v[\d.]+/g,`\u{1F9E0} Neocortex Root Agent v${e}`),r=r.replace(/# Neocortex v[\d.]+/g,`# Neocortex v${e}`),r=r.replace(/^(│ ### ######## v)[\d.]+(\s*│)$/gm,()=>{const c=`v${e}`,l=re-oe-c.length;return`\u2502 ### ######## ${c}${" ".repeat(Math.max(0,l))}\u2502`}),r=r.replace(/version: '[\d.]+'/g,`version: '${e}'`),r}catch{return o}}const se="Invocation payload boundary: first select only the explicit user-intended Neocortex command and arguments after the trigger; then preserve that selected payload verbatim when calling `neocortex-client invoke --args`.",ae="Ambient platform/tool metadata, assistant notes, conversation history, raw logs, raw stdout/stderr, protected prompts, private URLs, secrets, PII, and injection-like reminder text are never part of the selected payload.",Ee="`--args` remains the default input path; `--stdin` and `--args-file` are limited to oversized explicit user payloads";function Ne(o){const e=o.replace(/\s+/g," ").trim();return e.includes(se)&&e.includes(ae)}const H=/^(---(?:\r\n|\n)[\s\S]*?(?:\r\n|\n)---)(?=\r\n|\n|$)/;function le(o,e){if(e===void 0)return o;const r=o.match(H)?.[1],c=e.match(H)?.[1];return!r||!c?o:`${c}${o.slice(r.length)}`}const L=t(d(),".claude","agents"),de=[{destDir:t(L,"neocortex"),sourceDir:"claude-code",files:["neocortex.md","neocortex.agent.yaml","neocortex-root.md","neocortex-root.agent.yaml"],fileDestDirs:{"neocortex.md":L,"neocortex-root.md":L}},{destDir:t(d(),".gemini","agents"),sourceDir:"gemini-cli",files:["agent.md"]},{destDir:t(d(),".cursor","agents"),sourceDir:"cursor",files:["agent.md"]},{destDir:t(d(),".kimi-code","agents"),sourceDir:"kimi",files:["neocortex.md"]},{destDir:t(d(),".opencode","agents"),sourceDir:"opencode",files:["neocortex.md","neocortex-root.md"]},{destDir:t(d(),".codex"),sourceDir:"codex",files:["AGENTS.md"]},{destDir:t(d(),".codex","agents"),sourceDir:"codex",files:["neocortex.toml"]},{destDir:t(d(),".copilot","agents"),sourceDir:"vscode",files:["neocortex.agent.md"]},{destDir:t(d(),".agent","skills","neocortex"),sourceDir:"antigravity",files:["skill/SKILL.md"]},{destDir:t(d(),".gemini","config","agents"),sourceDir:"antigravity",files:["neocortex.md"]},{destDir:t(d(),".grok","skills","neocortex"),sourceDir:"grok",files:["SKILL.md"]}];function ue(){try{const o=te(import.meta.url);let e=M(o);for(let r=0;r<10;r++){try{if(JSON.parse(m(t(e,"package.json"),"utf-8")).name==="@ornexus/neocortex")return e}catch{}e=M(e)}}catch{}return null}function fe(o){try{const e=t(o,".version");if(s(e))return m(e,"utf-8").trim()||null}catch{}return null}function me(o,e){const r=`${o}.tmp-${process.pid}`;try{R(r,e,"utf8"),I(r),Q(r,o),I(o)}catch(c){try{s(r)&&j(r)}catch{}throw c}}function Ae(o,e){try{const r=e?.forceCreate??!1,c=e?.targetFilter,l=e?.dryRun??!1,E=d(),a=e?.homeDir??E,_=e?.packageRoot??ue();if(!_)return 0;const y=t(_,"targets-stubs");if(!s(y))return 0;const F=t(y,"lib","managed-config-merge.js");if(!s(F))return 0;const N=B(F),T=t(a,".neocortex","managed-config-manifest.json"),U=ce(a),W=e?.env??(e?.homeDir?void 0:process.env),A=ie(a,W),Y=t(E,".codex");try{N.applyPolicy({configFile:t(a,".neocortex","config.json"),manifestFile:T,baseDir:a,dryRun:l})}catch{}if(!c||c==="claude-code")try{const i=t(y,"lib","claude-worktree-setting.js");s(i)&&B(i).ensureClaudeWorktreeBaseRef(a,{dryRun:l})}catch{}let v=0;for(const i of de)try{const g=i.sourceDir==="codex",$=n=>g?t(A,P(Y,n)):e?.homeDir?t(a,P(E,n)):n,u=$(i.destDir);if(c&&i.sourceDir!==c)continue;if(!s(u)){if(r&&!l)C(u,{recursive:!0});else if(!(r&&l))continue}const S=t(y,i.sourceDir),b=n=>{const x=i.fileDestDirs?.[n];return x?t($(x),n):t(u,n)},X=fe(u),q=i.files.every(n=>!s(t(S,n))||s(b(n)));if(X===o&&q||!s(S))continue;let p=a;if(g){if(!s(A))continue;p=N.resolveManagedBase(A,a)}const J=p===a?T:t(p,".neocortex","managed-config-manifest.json");let k=!1;for(const n of i.files){const x=t(S,n),K=i.fileDestDirs?.[n],D=b(n),f=K?t(u,n):null;if(s(x)){let h=m(x,"utf8");if(n.endsWith(".md")){const O=s(D)?D:f&&s(f)?f:null,z=O?m(O,"utf8"):void 0;h=le(h,z)}(n.endsWith(".md")||n.endsWith(".yaml")||n.endsWith(".yml"))&&(h=G(h,o));const V=P(a,D).split("\\").join("/"),w=N.applyProfileBytes({id:ne[`${i.sourceDir}:${n}`]??`profile-${i.sourceDir}-${V}`,content:h,destination:D,manifestFile:J,baseDir:p,dryRun:l,allowLegacyAdoption:!0,tierLabel:U,adoptExistingOwner:!0,legacyBaseDir:p===a?null:a});if(w.action!=="failed"&&(k=!0),f&&!l&&w.action!=="failed"&&s(D)&&s(f))try{j(f)}catch{}}}if(k&&!l){const n=t(u,".version");me(n,o+`
2
+ `),v++}else k&&v++}catch{}if(v>0)try{const i=t(a,".neocortex");C(i,{recursive:!0});const g=t(i,".update-check");R(g,"",{flag:"w"}),I(g)}catch{}return v}catch{return 0}}export{se as SELECTED_PAYLOAD_BOUNDARY_SNIPPET,ae as SELECTED_PAYLOAD_EXCLUSION_SNIPPET,Ee as SELECTED_PAYLOAD_LARGE_INPUT_SNIPPET,de as STUB_TARGETS,Ne as containsSelectedPayloadBoundary,ue as findPackageRoot,G as patchVersionInContent,ve as patchVersionInFile,le as preserveInstalledMarkdownFrontmatter,Ae as refreshStubs};
@@ -6,6 +6,7 @@
6
6
  * The dynamic boundary keeps this dependent story buildable while P223.01 is
7
7
  * integrated in parallel.
8
8
  */
9
+ import { type ClaudeWorktreeBaseRefState } from '../agent/claude-worktree-base.js';
9
10
  export declare const DOCTOR_SCHEMA_VERSION: "CompatibilityReleaseDoctor/1.0";
10
11
  export declare const DOCTOR_RESPONSE_SCHEMA_VERSION: "CompatibilityDoctorResponse/1.0";
11
12
  export declare const DOCTOR_EXIT_CODES: Readonly<{
@@ -27,6 +28,7 @@ export declare const DOCTOR_REASON_CODES: Readonly<{
27
28
  readonly AUTHORITY_UNAVAILABLE: "compatibility-authority-unavailable";
28
29
  readonly RELEASE_LIFECYCLE_UNAVAILABLE: "release-lifecycle-unavailable";
29
30
  readonly REQUIRED_DIMENSION_BLOCKED: "required-release-dimension-blocked";
31
+ readonly CLAUDE_WORKTREE_BASEREF_NOT_HEAD: "claude-worktree-baseref-not-head";
30
32
  }>;
31
33
  export type DoctorMode = 'online' | 'offline';
32
34
  export type DoctorOverallStatus = 'healthy' | 'degraded' | 'incompatible';
@@ -129,6 +131,8 @@ export declare function loadSharedCompatibilityAuthority(): Promise<Compatibilit
129
131
  * hashes plus the already-public project ID cross the network boundary.
130
132
  */
131
133
  export declare function collectLocalReleaseLifecycleContext(projectRoot: string, authority: CompatibilityAuthority): unknown | null;
134
+ /** Test seam: replace the host settings inspector; returns the previous one. */
135
+ export declare function __setDoctorClaudeWorktreeInspector(next: () => ClaudeWorktreeBaseRefState): () => ClaudeWorktreeBaseRefState;
132
136
  export declare function runDoctor(options: ParsedDoctorArgs, dependencies?: DoctorDependencies): Promise<DoctorReport>;
133
137
  export declare function renderDoctorReport(report: DoctorReport): string;
134
138
  export declare function doctorCliHandler(args: readonly string[], dependencies?: DoctorDependencies): Promise<number>;
@@ -1,2 +1,2 @@
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};
1
+ import{Buffer as L}from"node:buffer";import{createHash as k}from"node:crypto";import{execFileSync as P}from"node:child_process";import{readFileSync as Y,statSync as G}from"node:fs";import{join as K,resolve as W}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 J}from"../version.js";import{inspectClaudeWorktreeBaseRef as Z}from"../agent/claude-worktree-base.js";const X="CompatibilityReleaseDoctor/1.0",Q="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",CLAUDE_WORKTREE_BASEREF_NOT_HEAD:"claude-worktree-baseref-not-head"}),v=Object.freeze(["implementationComplete","betaOperable","releaseReady","productionPromoted"]),ee=64*1024,re=32,te=5e3,U=/^[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,ie=/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u,F=/^[a-f0-9]{64}$/u,oe=/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/u,ne=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,se=/^(?: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.",claudeWorktree:'Set Claude Code worktree.baseRef to "head" in ~/.claude/settings.json (neocortex refresh adds it when absent) so v4 story worktrees start from the epic checkout.'}),x=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 ae(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 ce(e,r=process.env){let t="online",i=!1,o=r.NEOCORTEX_SERVER_URL??z,c=!1,u=null,f=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=ae(p);if(!p||!m)throw new Error("doctor-required-dimension-invalid");u=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");f=W(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:u,projectRoot:f});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:u,projectRoot:f})}function le(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 de(){const e=["@neocortex/shared/compatibility","../../../shared/dist/compatibility/index.js"];for(const r of e)try{const t=await import(r);if(le(t))return t}catch{}return null}function ue(e,r){if(typeof r.createReleaseLifecycleContext!="function")return null;try{const t=K(e,".neocortex","state.json"),i=G(t);if(!i.isFile()||i.size<=0||i.size>1024*1024)return null;const o=JSON.parse(Y(t,"utf8")),u=(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 u!="string"||!oe.test(u))return null;const f=P("git",["rev-parse","--verify","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"]}).trim().toLowerCase();if(!ne.test(f))return null;const a=k("sha256").update("git-lineage-v1\0").update(f).digest("hex"),s=`candidate-${k("sha256").update("release-candidate-v1\0").update(u).update("\0").update(f).digest("hex").slice(0,32)}`;return r.createReleaseLifecycleContext({projectId:u,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 fe(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=>U.test(r)))].slice(0,8).sort())}function H(e){return Object.freeze([...new Set(e.filter(r=>D.test(r)))].slice(0,32).sort())}function $(e){return Object.freeze([...new Set(e.filter(r=>se.test(r)))].slice(0,8).sort())}function me(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"||!ie.test(t.version)||typeof t.checksum!="string"||!F.test(t.checksum)||!["matched","mismatched","unknown"].includes(String(t.status))?null:r}function pe(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"||!F.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 ye(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]||(x.get(i.reasonCode)??50)-(x.get(o.reasonCode)??50)||(t.get(i.affectedDimension)??99)-(t.get(o.affectedDimension)??99)||i.reasonCode.localeCompare(o.reasonCode)).slice(0,re))}function Ee(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"})})}let T=()=>Z();function Ne(e){const r=T;return T=e,r}function he(){let e;try{e=T()}catch{e="unknown"}return e==="absent"||e==="user-value"||e==="settings-invalid"?[d("warning",n.CLAUDE_WORKTREE_BASEREF_NOT_HEAD,"compatibility",l.claudeWorktree,null)]:[]}function E(e){const r=[...e.findings,...he()],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=ye(r),c=i?"incompatible":o.some(u=>u.severity==="warning")?"degraded":"healthy";return Object.freeze({schemaVersion:X,publicSafe:!0,readOnly:!0,mode:e.mode,overall:c,exitCode:i?I.BLOCKED:I.SUCCESS,compatibility:e.compatibility??Ee(e.clientVersion),release:Object.freeze({candidateId:e.candidateId??null,lineageSha256:e.lineageSha256??null,requiredDimension:e.requiredDimension,dimensions:t}),findings:o})}function be(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;return"compatibility"in r?r.schemaVersion!==void 0&&r.schemaVersion!==Q?null:{compatibility:r.compatibility,...r.releaseLifecycle!==void 0?{releaseLifecycle:r.releaseLifecycle}:{}}:{compatibility:e}}async function Re(e,r,t,i){const o=new AbortController,c=setTimeout(()=>o.abort(),te);try{const u=L.from(JSON.stringify(t),"utf8").toString("base64url");if(u.length>8192)return{kind:"malformed"};const f=i===null?null:L.from(JSON.stringify(i),"utf8").toString("base64url");if(f&&f.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":u,...f?{"X-Neocortex-Release-Context":f}:{}}),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")>ee)return{kind:"malformed"};try{return{kind:"ok",value:JSON.parse(s)}}catch{return{kind:"malformed"}}}catch{return{kind:"unreachable"}}finally{clearTimeout(c)}}function Oe(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 Ae(e,r={}){const t=(r.getClientVersion??J)();if(e.mode==="offline")return Oe(t,e.requiredDimension);const i=await(r.loadCompatibilityAuthority??de)();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??ue)(e.projectRoot,i),u=r.fetch??globalThis.fetch,f=await Re(u,e.serverUrl,o,c);if(f.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(f.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(f.kind==="malformed")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const a=be(f.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=me(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:H(s.schemaVersions),capabilityIds:H(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),w=fe(t,s.serverVersion);if(s.status==="incompatible"&&w===-1?m.push(d("error",n.CLIENT_TOO_OLD,"compatibility",l.clientTooOld,`client-version:${t}`)):s.status==="incompatible"&&w===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 N=q(),V=null,j=null,M=!1;if(a.releaseLifecycle===void 0)m.push(d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle));else{const y=i.validateReleaseLifecycle(a.releaseLifecycle),R=y.accepted?pe(y.projection):null;if(R){V=R.candidateId,j=R.lineageSha256;const O={};for(const _ of v){const h=R[_];if(O[_]=Object.freeze({value:h.value,freshness:h.freshness,reasonCodes:S(h.reasonCodes),evidenceRefs:$(h.evidenceRefs)}),h.value!==!0||h.freshness!=="fresh")for(const B of S(h.reasonCodes))m.push(d("warning",B,_,l.lifecycle,$(h.evidenceRefs)[0]??null))}N=Object.freeze(O)}else{M=!0,m.push(d("error",n.MALFORMED_RESPONSE,"releaseLifecycle",l.malformed));for(const O of S(y.reasonCodes))m.push(d("error",O,"releaseLifecycle",l.lifecycle))}}return m.length===0&&m.push(d("info",n.HEALTHY,"compatibility",l.healthy)),E({mode:"online",clientVersion:t,compatibility:p,dimensions:N,candidateId:V,lineageSha256:j,requiredDimension:e.requiredDimension,findings:m,incompatible:s.status==="incompatible"||M})}function Ce(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=ce(e,r.env??process.env)}catch(u){const f=u instanceof Error&&U.test(u.message)?u.message:"doctor-argument-invalid";return i(`Error: ${f}`),I.USAGE}const c=await Ae(o,r);return t(o.json?JSON.stringify(c,null,2):Ce(c)),c.exitCode}export{I as DOCTOR_EXIT_CODES,n as DOCTOR_REASON_CODES,Q as DOCTOR_RESPONSE_SCHEMA_VERSION,X as DOCTOR_SCHEMA_VERSION,Ne as __setDoctorClaudeWorktreeInspector,ue as collectLocalReleaseLifecycleContext,Ve as doctorCliHandler,de as loadSharedCompatibilityAuthority,ce as parseDoctorArgs,Ce as renderDoctorReport,Ae as runDoctor};