@ornexus/neocortex 4.66.7 → 4.66.9

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 (45) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +2 -2
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/commands/doctor.d.ts +9 -0
  9. package/packages/client/dist/commands/doctor.js +2 -2
  10. package/packages/client/dist/commands/invoke.d.ts +7 -1
  11. package/packages/client/dist/commands/invoke.js +98 -96
  12. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +1 -1
  13. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  14. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  15. package/packages/client/dist/git/git-lifecycle-store.js +9 -9
  16. package/packages/client/dist/git/published-story-reconciliation.d.ts +13 -0
  17. package/packages/client/dist/git/published-story-reconciliation.js +2 -0
  18. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  19. package/packages/client/dist/yoloop/target-normalization.d.ts +8 -2
  20. package/packages/client/dist/yoloop/target-normalization.js +1 -1
  21. package/packages/shared/dist/compatibility/index.js +3 -0
  22. package/packages/shared/dist/invocation/diagnose-degraded-continuation.d.ts +13 -1
  23. package/packages/shared/dist/invocation/diagnose-degraded-continuation.js +20 -12
  24. package/packages/shared/dist/invocation/diagnose-degraded-continuation.test.js +30 -1
  25. package/targets-stubs/antigravity/gemini.md +1 -1
  26. package/targets-stubs/antigravity/neocortex.md +7 -13
  27. package/targets-stubs/antigravity/skill/SKILL.md +7 -13
  28. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  29. package/targets-stubs/claude-code/neocortex-root.md +8 -8
  30. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  31. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  32. package/targets-stubs/claude-code/neocortex.md +8 -8
  33. package/targets-stubs/codex/AGENTS.md +7 -11
  34. package/targets-stubs/codex/neocortex.toml +7 -13
  35. package/targets-stubs/cursor/agent.md +8 -14
  36. package/targets-stubs/deepseek-harness/SKILL.md +7 -13
  37. package/targets-stubs/gemini-cli/agent.md +8 -14
  38. package/targets-stubs/gemini-cli/agents/neocortex.md +8 -14
  39. package/targets-stubs/grok/SKILL.md +7 -13
  40. package/targets-stubs/kimi/neocortex.md +7 -13
  41. package/targets-stubs/lib/managed-config-merge.js +16 -3
  42. package/targets-stubs/openclaw/SKILL.md +7 -13
  43. package/targets-stubs/opencode/neocortex-root.md +8 -13
  44. package/targets-stubs/opencode/neocortex.md +8 -13
  45. package/targets-stubs/vscode/neocortex.agent.md +8 -14
package/install.ps1 CHANGED
@@ -19,7 +19,7 @@ param(
19
19
  [string]$ServerUrl = ('https://{0}.{1}.{2}' -f 'api','neocortex','sh')
20
20
  )
21
21
 
22
- $VERSION = "4.66.7"
22
+ $VERSION = "4.66.9"
23
23
 
24
24
  # =============================================================================
25
25
  # CONFIGURACOES
package/install.sh CHANGED
@@ -4,7 +4,7 @@
4
4
  # Development Orchestrator
5
5
 
6
6
  # Versao do instalador
7
- VERSION="4.66.7"
7
+ VERSION="4.66.9"
8
8
 
9
9
  # Flags
10
10
  MIGRATION_DETECTED=false
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ornexus/neocortex",
3
- "version": "4.66.7",
4
- "description": "Neocortex v4.66.7",
3
+ "version": "4.66.9",
4
+ "description": "Neocortex v4.66.9",
5
5
  "keywords": [
6
6
  "claude",
7
7
  "claude-code",
@@ -42,7 +42,7 @@ export declare const AGENT_ROLE_IDS: Readonly<Record<string, string>>;
42
42
  * Replace all version strings in a stub file with the given version.
43
43
  * Handles 4 patterns:
44
44
  * 1. Emoji description: 🧠 Neocortex vX.Y.Z
45
- * 2. Plain markdown header: # Neocortex vX.Y.Z
45
+ * 2. Plain Markdown header or YAML description: Neocortex vX.Y.Z
46
46
  * 3. Banner line: │ ### ######## vX.Y.Z ...│
47
47
  * 4. YAML version field: version: 'X.Y.Z'
48
48
  *
@@ -62,7 +62,7 @@ export declare const SELECTED_PAYLOAD_EXCLUSION_SNIPPET = "Ambient platform/tool
62
62
  export declare const SELECTED_PAYLOAD_LARGE_INPUT_SNIPPET = "`--args` remains the default input path; `--stdin` and `--args-file` are limited to oversized explicit user payloads";
63
63
  export declare function containsSelectedPayloadBoundary(content: string): boolean;
64
64
  /**
65
- * Refresh a managed Markdown body without replacing host-owned frontmatter.
65
+ * Refresh a managed Markdown body and migrate the exact prior descriptions.
66
66
  * Preservation is intentionally limited to files whose packaged source also
67
67
  * declares YAML frontmatter, avoiding accidental treatment of body separators
68
68
  * in plain wrappers such as Codex AGENTS.md.
@@ -1,2 +1,2 @@
1
- import{readFileSync as F,writeFileSync as X,existsSync as a,mkdirSync as te,renameSync as ge,unlinkSync as xe,realpathSync as oe}from"node:fs";import{join as o,dirname as ne,relative as T,isAbsolute as re}from"node:path";import{homedir as x}from"node:os";import{createRequire as pe}from"node:module";import{fileURLToPath as De}from"node:url";import{setSecureFilePermissions as Y}from"../config/secure-config.js";const he=60,ye=25,ce=pe(import.meta.url),Se={"codex:AGENTS.md":"profile-codex-root","codex:neocortex-sentinel.toml":"profile-codex-neocortex-sentinel","codex:neocortex.toml":"profile-codex-neocortex","claude-code:neocortex-sentinel.md":"profile-claude-neocortex-sentinel-agent","claude-code:neocortex.md":"profile-claude-neocortex-agent","claude-code:neocortex-root.md":"profile-claude-neocortex-root-agent","gemini-cli:neocortex-sentinel.md":"profile-gemini-neocortex-sentinel","gemini-cli:neocortex.md":"profile-gemini-neocortex","gemini-cli:neocortex-root.md":"profile-gemini-neocortex-root","grok:neocortex-sentinel.md":"profile-grok-agent-neocortex-sentinel"},be={"codex:neocortex-sentinel.toml":"profile-codex-neocortex-sentinel","codex:neocortex.toml":"profile-codex-neocortex","claude-code:neocortex-sentinel.md":"profile-claude-neocortex-sentinel-agent","claude-code:neocortex.md":"profile-claude-neocortex-agent","claude-code:neocortex-root.md":"profile-claude-neocortex-root-agent","opencode:neocortex-sentinel.md":"profile-opencode-neocortex-sentinel","opencode:neocortex.md":"profile-opencode-neocortex","opencode:neocortex-root.md":"profile-opencode-neocortex-root"},ie={"claude-code":"neocortex-sentinel.md","gemini-cli":"agents/neocortex-sentinel.md",grok:"agents/neocortex-sentinel.md",opencode:"neocortex-sentinel.md",codex:"neocortex-sentinel.toml"},Ee=["b3efacd202482c4fe0ff18cd6c115dfb1ea7252b5bddcfc1401f84a13f0943af","79e3b721e9d330239ccc166b75b98f3dac2cad91958e850c9c6226dbb5d0f330","e5de92b4bbe73fec1abc8f027de9f5765b251bdd52846c6b6be8b9a8e6fa68c6"];function Re(t,e){return t?.installSentinel!==void 0?t.installSentinel:e?.NEOCORTEX_INSTALL_SENTINEL==="1"}function ve(t){return/^neocortex-sentinel\.(?:md|toml)$/.test(t)}function ke(t){return/^neocortex-root\.(?:md|toml|agent\.yaml)$/.test(t)}function se(t,e){return ke(t)?!1:ve(t)?e:!0}function Ne(t,e){const n=e?.CODEX_HOME;return n&&re(n)?n:o(t,".codex")}function Ae(t){try{const e=JSON.parse(F(o(t,".neocortex","config.json"),"utf8"));if(e.tier==="free")return"Free";if(e.tier==="pro")return"Pro";if(e.tier==="enterprise")return"Enterprise"}catch{}}function Xe(t,e){try{const n=F(t,"utf-8"),i=n,l=ae(n,e);l!==i&&X(t,l,"utf-8")}catch{}}function ae(t,e){try{let n=t.replace(/🧠 Neocortex v[\d.]+/g,`\u{1F9E0} Neocortex v${e}`);return n=n.replace(/🧠 Neocortex Root Agent v[\d.]+/g,`\u{1F9E0} Neocortex Root Agent v${e}`),n=n.replace(/🧠 Neocortex Sentinel v[\d.]+/g,`\u{1F9E0} Neocortex Sentinel v${e}`),n=n.replace(/# Neocortex v[\d.]+/g,`# Neocortex v${e}`),n=n.replace(/^(│ ### ######## v)[\d.]+(\s*│)$/gm,()=>{const i=`v${e}`,l=he-ye-i.length;return`\u2502 ### ######## ${i}${" ".repeat(Math.max(0,l))}\u2502`}),n=n.replace(/version: '[\d.]+'/g,`version: '${e}'`),n}catch{return t}}const Fe="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`.",Pe="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.",Ye="`--args` remains the default input path; `--stdin` and `--args-file` are limited to oversized explicit user payloads";function Ke(t){const e=t.replace(/\s+/g," ").trim();return e.includes(Fe)&&e.includes(Pe)}const le=/^(---(?:\r\n|\n)[\s\S]*?(?:\r\n|\n)---)(?=\r\n|\n|$)/;function je(t,e){if(e===void 0)return t;const n=t.match(le)?.[1],i=e.match(le)?.[1];return!n||!i?t:`${i}${t.slice(n.length)}`}const H=o(x(),".claude","agents"),_e=[{destDir:o(H,"neocortex"),sourceDir:"claude-code",files:["neocortex-sentinel.md","neocortex.md","neocortex-root.md","neocortex.agent.yaml","neocortex-root.agent.yaml"],fileDestDirs:{"neocortex-sentinel.md":H,"neocortex.md":H,"neocortex-root.md":H}},{destDir:o(x(),".gemini","agents"),sourceDir:"gemini-cli",files:["neocortex-sentinel.md","neocortex.md","neocortex-root.md"],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md","neocortex.md":"agents/neocortex.md","neocortex-root.md":"agent.md"}},{destDir:o(x(),".cursor","agents"),sourceDir:"cursor",files:["agent.md"]},{destDir:o(x(),".kimi-code","agents"),sourceDir:"kimi",files:["neocortex.md"]},{destDir:o(x(),".opencode","agents"),sourceDir:"opencode",files:["neocortex-sentinel.md","neocortex.md","neocortex-root.md"]},{destDir:o(x(),".codex"),sourceDir:"codex",files:["AGENTS.md"]},{destDir:o(x(),".codex","agents"),sourceDir:"codex",files:["neocortex-sentinel.toml","neocortex.toml"]},{destDir:o(x(),".copilot","agents"),sourceDir:"vscode",files:["neocortex.agent.md"]},{destDir:o(x(),".agent","skills","neocortex"),sourceDir:"antigravity",files:["skill/SKILL.md"]},{destDir:o(x(),".gemini","config","agents"),sourceDir:"antigravity",files:["neocortex.md"]},{destDir:o(x(),".grok","skills","neocortex"),sourceDir:"grok",files:["SKILL.md"]},{destDir:o(x(),".grok","agents"),sourceDir:"grok",files:["neocortex-sentinel.md"],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md"}}],Le=[{stubDir:"gemini-cli",agentsDir:o(".gemini","agents"),roleFiles:[["neocortex-sentinel.md","project-gemini-neocortex-sentinel",!0],["neocortex.md","project-gemini-neocortex",!0],["neocortex-root.md","project-gemini-neocortex-root",!1]],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md","neocortex.md":"agents/neocortex.md","neocortex-root.md":"agent.md"}},{stubDir:"grok",agentsDir:o(".grok","agents"),roleFiles:[["neocortex-sentinel.md","project-grok-agent-neocortex-sentinel",!0]],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md"}},{stubDir:"claude-code",agentsDir:o(".claude","agents"),roleFiles:[["neocortex-sentinel.md","project-claude-neocortex-sentinel-agent",!0],["neocortex.md","project-claude-neocortex-agent",!0]],legacyDir:o(".claude","agents","neocortex")},{stubDir:"opencode",agentsDir:o(".opencode","agents"),roleFiles:[["neocortex-sentinel.md","project-opencode-neocortex-sentinel",!0],["neocortex.md","project-opencode-neocortex",!0],["neocortex-root.md","project-opencode-neocortex-root",!1]]},{stubDir:"codex",agentsDir:o(".codex","agents"),roleFiles:[["neocortex-sentinel.toml","project-codex-neocortex-sentinel",!0],["neocortex.toml","project-codex-neocortex",!0]]}];function Ie(){try{const t=De(import.meta.url);let e=ne(t);for(let n=0;n<10;n++){try{if(JSON.parse(F(o(e,"package.json"),"utf-8")).name==="@ornexus/neocortex")return e}catch{}e=ne(e)}}catch{}return null}function Ce(t){try{const e=o(t,".version");if(a(e))return F(e,"utf-8").trim()||null}catch{}return null}function Te(t,e){const n=`${t}.tmp-${process.pid}`;try{X(n,e,"utf8"),Y(n),ge(n,t),Y(t)}catch(i){try{a(n)&&xe(n)}catch{}throw i}}function Je(t,e){return we(t,e).refreshed}function de(t,e,n,i,l,s=!0){let f=F(t,"utf8");if(e.endsWith(".md")&&s){const c=a(n)?n:i&&a(i)?i:null,S=c?F(c,"utf8"):void 0;f=je(f,S)}return(e.endsWith(".md")||e.endsWith(".yaml")||e.endsWith(".yml"))&&(f=ae(f,l)),f}function K(t,e,n){return{id:t.id??e,scope:n,relativePath:t.relativePath??"",action:t.action,reasonCode:t.reasonCode,...t.nextStep?{nextStep:t.nextStep}:{}}}function Oe(t,e){try{return oe.native(t)===oe.native(e)}catch{return!1}}function P(t){const{managed:e,destination:n,manifestFile:i,baseDir:l,id:s,scope:f,dryRun:c,results:S,knownHashes:h}=t;try{const p=e.retireLegacy({destination:n,manifestFile:i,baseDir:l,id:s,dryRun:c,...h?{knownHashes:h}:{}});p.action!=="none"&&S.push(K(p,s,f))}catch(p){const u=p?.reasonCode;S.push({id:s,scope:f,relativePath:T(l,n).split("\\").join("/"),action:"failed",reasonCode:typeof u=="string"?u:"managed-retirement-failed"})}}function $e(t){const{projectRoot:e,home:n,stubsRoot:i,managed:l,cliVersion:s,dryRun:f,tierLabel:c,targetFilter:S,installSentinel:h,results:p}=t;if(!re(e)||!a(e)||Oe(e,n))return;const u=o(e,".neocortex","managed-config-manifest.json");for(const g of Le)if(!(S&&g.stubDir!==S))try{const j=o(i,g.stubDir),k=o(e,g.agentsDir),R=g.stubDir==="gemini-cli"?o(k,"agent.md"):null;if(!(g.roleFiles.slice(0,2).some(([r])=>a(o(k,r)))||!!(R&&a(R))))continue;const $=ie[g.stubDir],N=h&&!!($&&a(o(j,$)));for(const[r,y,w]of g.roleFiles){const D=o(j,g.fileSources?.[r]??r),b=o(k,r);if(!se(r,h)){P({managed:l,destination:b,manifestFile:u,baseDir:e,id:y,scope:"project",dryRun:f,results:p});continue}if(!a(D)||!w&&!a(b))continue;const A=g.legacyDir?o(e,g.legacyDir,r):null,G=N&&l.agentRoleMigrationPending?.({id:y,destination:b,manifestFile:u,baseDir:e})===!0,U=de(D,r,b,A,s,!G);try{const m=l.applyProfileBytes({id:y,content:U,destination:b,manifestFile:u,baseDir:e,dryRun:f,allowLegacyAdoption:!0,tierLabel:c,adoptExistingOwner:!0,agentRoles:N,legacyCopyPath:A&&a(A)?A:null,contentVersion:s});p.push(K(m,y,"project"))}catch(m){const E=m?.reasonCode;p.push({id:y,scope:"project",relativePath:T(e,b).split("\\").join("/"),action:"failed",reasonCode:typeof E=="string"?E:"managed-operation-failed"})}}R&&a(o(k,"neocortex.md"))&&P({managed:l,destination:R,manifestFile:u,baseDir:e,id:"project-gemini-cli-.gemini-agents-agent.md",scope:"project",dryRun:f,results:p})}catch{}}function we(t,e){const n=[];try{const i=e?.forceCreate??!1,l=e?.targetFilter,s=e?.dryRun??!1,f=x(),c=e?.homeDir??f,S=e?.packageRoot??Ie();if(!S)return{refreshed:0,results:n};const h=o(S,"targets-stubs");if(!a(h))return{refreshed:0,results:n};const p=o(h,"lib","managed-config-merge.js");if(!a(p))return{refreshed:0,results:n};const u=ce(p),g=o(c,".neocortex","managed-config-manifest.json"),j=Ae(c),k=e?.env??(e?.homeDir?void 0:process.env),R=Re(e,k),O=Ne(c,k),$=o(f,".codex");try{u.applyPolicy({configFile:o(c,".neocortex","config.json"),manifestFile:g,baseDir:c,dryRun:s})}catch{}if(e?.projectRoot&&$e({projectRoot:e.projectRoot,home:c,stubsRoot:h,managed:u,cliVersion:t,dryRun:s,tierLabel:j,targetFilter:l,installSentinel:R,results:n}),!l||l==="claude-code")try{const r=o(h,"lib","claude-worktree-setting.js");a(r)&&ce(r).ensureClaudeWorktreeBaseRef(c,{dryRun:s})}catch{}let N=0;for(const r of _e)try{const y=r.sourceDir==="codex",w=d=>y?o(O,T($,d)):e?.homeDir?o(c,T(f,d)):d,D=w(r.destDir);if(l&&r.sourceDir!==l)continue;if(!a(D)){if(i&&!s)te(D,{recursive:!0});else if(!(i&&s))continue}const b=o(h,r.sourceDir),A=d=>o(b,r.fileSources?.[d]??d),G=d=>{const L=r.fileDestDirs?.[d];return L?o(w(L),d):o(D,d)},U=Ce(D);if(!a(b))continue;let m=c;if(y){if(!a(O))continue;m=u.resolveManagedBase(O,c)}const E=m===c?g:o(m,".neocortex","managed-config-manifest.json"),J=ie[r.sourceDir],V=R&&!!(J&&a(o(b,J)));r.sourceDir==="codex"&&r.files.includes("neocortex.toml")&&P({managed:u,destination:o(D,"neocortex-worker.toml"),manifestFile:E,baseDir:m,id:"profile-codex-neocortex-worker-retired",scope:"user",dryRun:s,results:n,knownHashes:Ee});let W=!1,q=!1,_=!1;for(const d of r.files){const L=A(d),ue=r.fileDestDirs?.[d],I=G(d),B=ue?o(D,d):null,Q=T(c,I).split("\\").join("/"),Z=`${r.sourceDir}:${d}`,C=Se[Z]??`profile-${r.sourceDir}-${Q}`;if(!se(d,R)){P({managed:u,destination:I,manifestFile:E,baseDir:m,id:C,scope:"user",dryRun:s,results:n});continue}if(a(L)){const M=be[Z],fe=!!M&&V&&u.agentRoleMigrationPending?.({id:C,agentRoleId:M,destination:I,manifestFile:E,baseDir:m})===!0,me=de(L,d,I,B,t,!fe);try{const v=u.applyProfileBytes({id:C,content:me,destination:I,manifestFile:E,baseDir:m,dryRun:s,allowLegacyAdoption:!0,tierLabel:j,adoptExistingOwner:!0,legacyBaseDir:m===c?null:c,...M?{agentRoles:V,agentRoleId:M}:{},legacyCopyPath:B&&a(B)?B:null,contentVersion:t});n.push(K(v,C,"user")),v.action==="skipped"||v.action==="failed"?_=!0:(W=!0,v.action!=="noop"&&v.action!=="planned-noop"&&(q=!0))}catch(v){const ee=v?.reasonCode;throw n.push({id:C,scope:"user",relativePath:Q,action:"failed",reasonCode:typeof ee=="string"?ee:"managed-operation-failed"}),_=!0,v}}}!_&&W&&r.sourceDir==="gemini-cli"&&P({managed:u,destination:o(D,"agent.md"),manifestFile:E,baseDir:m,id:"profile-gemini-cli-.gemini-agents-agent.md",scope:"user",dryRun:s,results:n}),!_&&r.sourceDir==="grok"&&r.files.includes("neocortex-sentinel.md")&&P({managed:u,destination:o(D,"neocortex.md"),manifestFile:E,baseDir:m,id:"profile-grok-agent-neocortex",scope:"user",dryRun:s,results:n});const z=W&&!_&&(q||U!==t);if(z&&!s){const d=o(D,".version");Te(d,t+`
2
- `),N++}else z&&N++}catch{}if(N>0&&!s)try{const r=o(c,".neocortex");te(r,{recursive:!0});const y=o(r,".update-check");X(y,"",{flag:"w"}),Y(y)}catch{}return{refreshed:N,results:n}}catch{return{refreshed:0,results:n}}}export{be as AGENT_ROLE_IDS,Se as CANONICAL_MANAGED_IDS,Le as PROJECT_ROLE_TARGETS,Fe as SELECTED_PAYLOAD_BOUNDARY_SNIPPET,Pe as SELECTED_PAYLOAD_EXCLUSION_SNIPPET,Ye as SELECTED_PAYLOAD_LARGE_INPUT_SNIPPET,_e as STUB_TARGETS,Ke as containsSelectedPayloadBoundary,Ie as findPackageRoot,ae as patchVersionInContent,Xe as patchVersionInFile,je as preserveInstalledMarkdownFrontmatter,Je as refreshStubs,we as refreshStubsReport};
1
+ import{readFileSync as k,writeFileSync as Y,existsSync as d,mkdirSync as te,renameSync as ge,unlinkSync as xe,realpathSync as oe}from"node:fs";import{join as n,dirname as ne,relative as T,isAbsolute as re}from"node:path";import{homedir as D}from"node:os";import{createRequire as he}from"node:module";import{fileURLToPath as De}from"node:url";import{setSecureFilePermissions as X}from"../config/secure-config.js";const ye=60,Se=25,ce=he(import.meta.url),Ee={"codex:AGENTS.md":"profile-codex-root","codex:neocortex-sentinel.toml":"profile-codex-neocortex-sentinel","codex:neocortex.toml":"profile-codex-neocortex","claude-code:neocortex-sentinel.md":"profile-claude-neocortex-sentinel-agent","claude-code:neocortex.md":"profile-claude-neocortex-agent","claude-code:neocortex-root.md":"profile-claude-neocortex-root-agent","gemini-cli:neocortex-sentinel.md":"profile-gemini-neocortex-sentinel","gemini-cli:neocortex.md":"profile-gemini-neocortex","gemini-cli:neocortex-root.md":"profile-gemini-neocortex-root","grok:neocortex-sentinel.md":"profile-grok-agent-neocortex-sentinel"},be={"codex:neocortex-sentinel.toml":"profile-codex-neocortex-sentinel","codex:neocortex.toml":"profile-codex-neocortex","claude-code:neocortex-sentinel.md":"profile-claude-neocortex-sentinel-agent","claude-code:neocortex.md":"profile-claude-neocortex-agent","claude-code:neocortex-root.md":"profile-claude-neocortex-root-agent","opencode:neocortex-sentinel.md":"profile-opencode-neocortex-sentinel","opencode:neocortex.md":"profile-opencode-neocortex","opencode:neocortex-root.md":"profile-opencode-neocortex-root"},ie={"claude-code":"neocortex-sentinel.md","gemini-cli":"agents/neocortex-sentinel.md",grok:"agents/neocortex-sentinel.md",opencode:"neocortex-sentinel.md",codex:"neocortex-sentinel.toml"},Re=["b3efacd202482c4fe0ff18cd6c115dfb1ea7252b5bddcfc1401f84a13f0943af","79e3b721e9d330239ccc166b75b98f3dac2cad91958e850c9c6226dbb5d0f330","e5de92b4bbe73fec1abc8f027de9f5765b251bdd52846c6b6be8b9a8e6fa68c6"];function ve(t,e){return t?.installSentinel!==void 0?t.installSentinel:e?.NEOCORTEX_INSTALL_SENTINEL==="1"}function Ne(t){return/^neocortex-sentinel\.(?:md|toml)$/.test(t)}function Pe(t){return/^neocortex-root\.(?:md|toml|agent\.yaml)$/.test(t)}function se(t,e){return Pe(t)?!1:Ne(t)?e:!0}function Ae(t,e){const o=e?.CODEX_HOME;return o&&re(o)?o:n(t,".codex")}function ke(t){try{const e=JSON.parse(k(n(t,".neocortex","config.json"),"utf8"));if(e.tier==="free")return"Free";if(e.tier==="pro")return"Pro";if(e.tier==="enterprise")return"Enterprise"}catch{}}function Ke(t,e){try{const o=k(t,"utf-8"),i=o,c=ae(o,e);c!==i&&Y(t,c,"utf-8")}catch{}}function ae(t,e){try{let o=t.replace(/🧠 Neocortex v[\d.]+/g,`\u{1F9E0} Neocortex v${e}`);return o=o.replace(/🧠 Neocortex Root Agent v[\d.]+/g,`\u{1F9E0} Neocortex Root Agent v${e}`),o=o.replace(/🧠 Neocortex Sentinel v[\d.]+/g,`\u{1F9E0} Neocortex Sentinel v${e}`),o=o.replace(/# Neocortex v[\d.]+/g,`# Neocortex v${e}`),o=o.replace(/^(description:[ \t]*"Neocortex v)\d+(?:\.\d+)+(?=(?: \((?:Free|Pro|Enterprise)\))? \| OrNexus Team"[ \t]*$)/gm,(i,c)=>`${c}${e}`),o=o.replace(/^(│ ### ######## v)[\d.]+(\s*│)$/gm,()=>{const i=`v${e}`,c=ye-Se-i.length;return`\u2502 ### ######## ${i}${" ".repeat(Math.max(0,c))}\u2502`}),o=o.replace(/version: '[\d.]+'/g,`version: '${e}'`),o}catch{return t}}const Fe="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`.",Ie="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.",Je="`--args` remains the default input path; `--stdin` and `--args-file` are limited to oversized explicit user payloads";function Ve(t){const e=t.replace(/\s+/g," ").trim();return e.includes(Fe)&&e.includes(Ie)}const le=/^(---(?:\r\n|\n)[\s\S]*?(?:\r\n|\n)---)(?=\r\n|\n|$)/,de=/^description:[ \t]*(?:"([^"\r\n]+)"|([^\r\n]+))[ \t]*(?=\r?$)/gm,_e=new Map([["Neocortex orchestrator \u2014 owns *yoloop","Development orchestrator for *yoloop."],["Neocortex root agent \u2014 owns *yoloop","Development orchestrator for *yoloop."],["Neocortex orchestrator custom agent candidate (native-needs-validation)","Development orchestrator candidate (native-needs-validation)."],["Run Neocortex development orchestration commands through the public thin client.","Run development orchestration commands through the public thin client."]]);function Le(t,e){if(e===void 0)return t;const o=t.match(le)?.[1],i=e.match(le)?.[1];if(!o||!i)return t;const[c,...a]=o.matchAll(de),[l,...s]=i.matchAll(de);let g=i;if(c?.[1]&&l&&a.length===0&&s.length===0){const x=(l[1]??l[2]).trim().replace(/ \((?:Free|Pro|Enterprise)\)(?= — owns \*yoloop$)/,""),m=_e.get(x);m&&c[1].endsWith(` | OrNexus Team \u2014 ${m}`)&&(g=i.replace(l[0],()=>c[0]))}return`${g}${t.slice(o.length)}`}const G=n(D(),".claude","agents"),je=[{destDir:n(G,"neocortex"),sourceDir:"claude-code",files:["neocortex-sentinel.md","neocortex.md","neocortex-root.md","neocortex.agent.yaml","neocortex-root.agent.yaml"],fileDestDirs:{"neocortex-sentinel.md":G,"neocortex.md":G,"neocortex-root.md":G}},{destDir:n(D(),".gemini","agents"),sourceDir:"gemini-cli",files:["neocortex-sentinel.md","neocortex.md","neocortex-root.md"],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md","neocortex.md":"agents/neocortex.md","neocortex-root.md":"agent.md"}},{destDir:n(D(),".cursor","agents"),sourceDir:"cursor",files:["agent.md"]},{destDir:n(D(),".kimi-code","agents"),sourceDir:"kimi",files:["neocortex.md"]},{destDir:n(D(),".opencode","agents"),sourceDir:"opencode",files:["neocortex-sentinel.md","neocortex.md","neocortex-root.md"]},{destDir:n(D(),".codex"),sourceDir:"codex",files:["AGENTS.md"]},{destDir:n(D(),".codex","agents"),sourceDir:"codex",files:["neocortex-sentinel.toml","neocortex.toml"]},{destDir:n(D(),".copilot","agents"),sourceDir:"vscode",files:["neocortex.agent.md"]},{destDir:n(D(),".agent","skills","neocortex"),sourceDir:"antigravity",files:["skill/SKILL.md"]},{destDir:n(D(),".gemini","config","agents"),sourceDir:"antigravity",files:["neocortex.md"]},{destDir:n(D(),".grok","skills","neocortex"),sourceDir:"grok",files:["SKILL.md"]},{destDir:n(D(),".grok","agents"),sourceDir:"grok",files:["neocortex-sentinel.md"],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md"}}],Ce=[{stubDir:"gemini-cli",agentsDir:n(".gemini","agents"),roleFiles:[["neocortex-sentinel.md","project-gemini-neocortex-sentinel",!0],["neocortex.md","project-gemini-neocortex",!0],["neocortex-root.md","project-gemini-neocortex-root",!1]],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md","neocortex.md":"agents/neocortex.md","neocortex-root.md":"agent.md"}},{stubDir:"grok",agentsDir:n(".grok","agents"),roleFiles:[["neocortex-sentinel.md","project-grok-agent-neocortex-sentinel",!0]],fileSources:{"neocortex-sentinel.md":"agents/neocortex-sentinel.md"}},{stubDir:"claude-code",agentsDir:n(".claude","agents"),roleFiles:[["neocortex-sentinel.md","project-claude-neocortex-sentinel-agent",!0],["neocortex.md","project-claude-neocortex-agent",!0]],legacyDir:n(".claude","agents","neocortex")},{stubDir:"opencode",agentsDir:n(".opencode","agents"),roleFiles:[["neocortex-sentinel.md","project-opencode-neocortex-sentinel",!0],["neocortex.md","project-opencode-neocortex",!0],["neocortex-root.md","project-opencode-neocortex-root",!1]]},{stubDir:"codex",agentsDir:n(".codex","agents"),roleFiles:[["neocortex-sentinel.toml","project-codex-neocortex-sentinel",!0],["neocortex.toml","project-codex-neocortex",!0]]}];function Te(){try{const t=De(import.meta.url);let e=ne(t);for(let o=0;o<10;o++){try{if(JSON.parse(k(n(e,"package.json"),"utf-8")).name==="@ornexus/neocortex")return e}catch{}e=ne(e)}}catch{}return null}function Oe(t){try{const e=n(t,".version");if(d(e))return k(e,"utf-8").trim()||null}catch{}return null}function $e(t,e){const o=`${t}.tmp-${process.pid}`;try{Y(o,e,"utf8"),X(o),ge(o,t),X(t)}catch(i){try{d(o)&&xe(o)}catch{}throw i}}function qe(t,e){return Me(t,e).refreshed}function ue(t,e,o,i,c,a=!0){let l=k(t,"utf8");if(e.endsWith(".md")&&a){const s=d(o)?o:i&&d(i)?i:null,g=s?k(s,"utf8"):void 0;l=Le(l,g)}return(e.endsWith(".md")||e.endsWith(".yaml")||e.endsWith(".yml")||e.endsWith(".toml"))&&(l=ae(l,c)),l}function K(t,e,o){return{id:t.id??e,scope:o,relativePath:t.relativePath??"",action:t.action,reasonCode:t.reasonCode,...t.nextStep?{nextStep:t.nextStep}:{}}}function we(t,e){try{return oe.native(t)===oe.native(e)}catch{return!1}}function F(t){const{managed:e,destination:o,manifestFile:i,baseDir:c,id:a,scope:l,dryRun:s,results:g,knownHashes:x}=t;try{const m=e.retireLegacy({destination:o,manifestFile:i,baseDir:c,id:a,dryRun:s,...x?{knownHashes:x}:{}});m.action!=="none"&&g.push(K(m,a,l))}catch(m){const f=m?.reasonCode;g.push({id:a,scope:l,relativePath:T(c,o).split("\\").join("/"),action:"failed",reasonCode:typeof f=="string"?f:"managed-retirement-failed"})}}function Be(t){const{projectRoot:e,home:o,stubsRoot:i,managed:c,cliVersion:a,dryRun:l,tierLabel:s,targetFilter:g,installSentinel:x,results:m}=t;if(!re(e)||!d(e)||we(e,o))return;const f=n(e,".neocortex","managed-config-manifest.json");for(const h of Ce)if(!(g&&h.stubDir!==g))try{const I=n(i,h.stubDir),N=n(e,h.agentsDir),R=h.stubDir==="gemini-cli"?n(N,"agent.md"):null;if(!(h.roleFiles.slice(0,2).some(([r])=>d(n(N,r)))||!!(R&&d(R))))continue;const $=ie[h.stubDir],P=x&&!!($&&d(n(I,$)));for(const[r,S,w]of h.roleFiles){const y=n(I,h.fileSources?.[r]??r),E=n(N,r);if(!se(r,x)){F({managed:c,destination:E,manifestFile:f,baseDir:e,id:S,scope:"project",dryRun:l,results:m});continue}if(!d(y)||!w&&!d(E))continue;const A=h.legacyDir?n(e,h.legacyDir,r):null,H=P&&c.agentRoleMigrationPending?.({id:S,destination:E,manifestFile:f,baseDir:e})===!0,U=ue(y,r,E,A,a,!H);try{const p=c.applyProfileBytes({id:S,content:U,destination:E,manifestFile:f,baseDir:e,dryRun:l,allowLegacyAdoption:!0,tierLabel:s,adoptExistingOwner:!0,agentRoles:P,legacyCopyPath:A&&d(A)?A:null,contentVersion:a});m.push(K(p,S,"project"))}catch(p){const b=p?.reasonCode;m.push({id:S,scope:"project",relativePath:T(e,E).split("\\").join("/"),action:"failed",reasonCode:typeof b=="string"?b:"managed-operation-failed"})}}R&&d(n(N,"neocortex.md"))&&F({managed:c,destination:R,manifestFile:f,baseDir:e,id:"project-gemini-cli-.gemini-agents-agent.md",scope:"project",dryRun:l,results:m})}catch{}}function Me(t,e){const o=[];try{const i=e?.forceCreate??!1,c=e?.targetFilter,a=e?.dryRun??!1,l=D(),s=e?.homeDir??l,g=e?.packageRoot??Te();if(!g)return{refreshed:0,results:o};const x=n(g,"targets-stubs");if(!d(x))return{refreshed:0,results:o};const m=n(x,"lib","managed-config-merge.js");if(!d(m))return{refreshed:0,results:o};const f=ce(m),h=n(s,".neocortex","managed-config-manifest.json"),I=ke(s),N=e?.env??(e?.homeDir?void 0:process.env),R=ve(e,N),O=Ae(s,N),$=n(l,".codex");try{f.applyPolicy({configFile:n(s,".neocortex","config.json"),manifestFile:h,baseDir:s,dryRun:a})}catch{}if(e?.projectRoot&&Be({projectRoot:e.projectRoot,home:s,stubsRoot:x,managed:f,cliVersion:t,dryRun:a,tierLabel:I,targetFilter:c,installSentinel:R,results:o}),!c||c==="claude-code")try{const r=n(x,"lib","claude-worktree-setting.js");d(r)&&ce(r).ensureClaudeWorktreeBaseRef(s,{dryRun:a})}catch{}let P=0;for(const r of je)try{const S=r.sourceDir==="codex",w=u=>S?n(O,T($,u)):e?.homeDir?n(s,T(l,u)):u,y=w(r.destDir);if(c&&r.sourceDir!==c)continue;if(!d(y)){if(i&&!a)te(y,{recursive:!0});else if(!(i&&a))continue}const E=n(x,r.sourceDir),A=u=>n(E,r.fileSources?.[u]??u),H=u=>{const L=r.fileDestDirs?.[u];return L?n(w(L),u):n(y,u)},U=Oe(y);if(!d(E))continue;let p=s;if(S){if(!d(O))continue;p=f.resolveManagedBase(O,s)}const b=p===s?h:n(p,".neocortex","managed-config-manifest.json"),J=ie[r.sourceDir],V=R&&!!(J&&d(n(E,J)));r.sourceDir==="codex"&&r.files.includes("neocortex.toml")&&F({managed:f,destination:n(y,"neocortex-worker.toml"),manifestFile:b,baseDir:p,id:"profile-codex-neocortex-worker-retired",scope:"user",dryRun:a,results:o,knownHashes:Re});let W=!1,q=!1,_=!1;for(const u of r.files){const L=A(u),fe=r.fileDestDirs?.[u],j=H(u),B=fe?n(y,u):null,Q=T(s,j).split("\\").join("/"),Z=`${r.sourceDir}:${u}`,C=Ee[Z]??`profile-${r.sourceDir}-${Q}`;if(!se(u,R)){F({managed:f,destination:j,manifestFile:b,baseDir:p,id:C,scope:"user",dryRun:a,results:o});continue}if(d(L)){const M=be[Z],me=!!M&&V&&f.agentRoleMigrationPending?.({id:C,agentRoleId:M,destination:j,manifestFile:b,baseDir:p})===!0,pe=ue(L,u,j,B,t,!me);try{const v=f.applyProfileBytes({id:C,content:pe,destination:j,manifestFile:b,baseDir:p,dryRun:a,allowLegacyAdoption:!0,tierLabel:I,adoptExistingOwner:!0,legacyBaseDir:p===s?null:s,...M?{agentRoles:V,agentRoleId:M}:{},legacyCopyPath:B&&d(B)?B:null,contentVersion:t});o.push(K(v,C,"user")),v.action==="skipped"||v.action==="failed"?_=!0:(W=!0,v.action!=="noop"&&v.action!=="planned-noop"&&(q=!0))}catch(v){const ee=v?.reasonCode;throw o.push({id:C,scope:"user",relativePath:Q,action:"failed",reasonCode:typeof ee=="string"?ee:"managed-operation-failed"}),_=!0,v}}}!_&&W&&r.sourceDir==="gemini-cli"&&F({managed:f,destination:n(y,"agent.md"),manifestFile:b,baseDir:p,id:"profile-gemini-cli-.gemini-agents-agent.md",scope:"user",dryRun:a,results:o}),!_&&r.sourceDir==="grok"&&r.files.includes("neocortex-sentinel.md")&&F({managed:f,destination:n(y,"neocortex.md"),manifestFile:b,baseDir:p,id:"profile-grok-agent-neocortex",scope:"user",dryRun:a,results:o});const z=W&&!_&&(q||U!==t);if(z&&!a){const u=n(y,".version");$e(u,t+`
2
+ `),P++}else z&&P++}catch{}if(P>0&&!a)try{const r=n(s,".neocortex");te(r,{recursive:!0});const S=n(r,".update-check");Y(S,"",{flag:"w"}),X(S)}catch{}return{refreshed:P,results:o}}catch{return{refreshed:0,results:o}}}export{be as AGENT_ROLE_IDS,Ee as CANONICAL_MANAGED_IDS,Ce as PROJECT_ROLE_TARGETS,Fe as SELECTED_PAYLOAD_BOUNDARY_SNIPPET,Ie as SELECTED_PAYLOAD_EXCLUSION_SNIPPET,Je as SELECTED_PAYLOAD_LARGE_INPUT_SNIPPET,je as STUB_TARGETS,Ve as containsSelectedPayloadBoundary,Te as findPackageRoot,ae as patchVersionInContent,Ke as patchVersionInFile,Le as preserveInstalledMarkdownFrontmatter,qe as refreshStubs,Me as refreshStubsReport};
@@ -29,6 +29,7 @@ export declare const DOCTOR_REASON_CODES: Readonly<{
29
29
  readonly MALFORMED_RESPONSE: "malformed-response";
30
30
  readonly AUTHORITY_UNAVAILABLE: "compatibility-authority-unavailable";
31
31
  readonly RELEASE_LIFECYCLE_UNAVAILABLE: "release-lifecycle-unavailable";
32
+ readonly ACTIVE_PRODUCTION_VERIFIED: "active-production-verified";
32
33
  readonly REQUIRED_DIMENSION_BLOCKED: "required-release-dimension-blocked";
33
34
  readonly CLAUDE_WORKTREE_BASEREF_NOT_HEAD: "claude-worktree-baseref-not-head";
34
35
  }>;
@@ -53,6 +54,12 @@ export interface DoctorReleaseDimension {
53
54
  readonly reasonCodes: readonly string[];
54
55
  readonly evidenceRefs: readonly string[];
55
56
  }
57
+ export interface DoctorActiveProduction {
58
+ readonly version: string;
59
+ readonly sourceRevision: string;
60
+ readonly imageDigest: string;
61
+ readonly releaseBindingDigest: string;
62
+ }
56
63
  export interface DoctorReport {
57
64
  readonly schemaVersion: typeof DOCTOR_SCHEMA_VERSION;
58
65
  readonly publicSafe: true;
@@ -80,6 +87,8 @@ export interface DoctorReport {
80
87
  readonly lineageSha256: string | null;
81
88
  readonly requiredDimension: ReleaseDimensionName | null;
82
89
  readonly dimensions: Readonly<Record<ReleaseDimensionName, DoctorReleaseDimension>>;
90
+ /** Current OCI runtime evidence, separate from project candidate receipts. */
91
+ readonly activeProduction?: DoctorActiveProduction;
83
92
  };
84
93
  readonly findings: readonly DoctorFinding[];
85
94
  /** P229.03 (CON-P229.03-DOCTOR): additive; never affects `overall`/`exitCode`. */
@@ -1,2 +1,2 @@
1
- import{Buffer as I}from"node:buffer";import{createHash as x}from"node:crypto";import{execFileSync as J}from"node:child_process";import{readFileSync as Z,statSync as K}from"node:fs";import{join as Q,resolve as ee}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 U}from"../constants.js";import{getClientVersion as re}from"../version.js";import{inspectClaudeWorktreeBaseRef as te}from"../agent/claude-worktree-base.js";import{PRIVATE_EXECUTION_HOST_KINDS as oe}from"../../../shared/dist/compatibility/index.js";import{createPrivateHarnessExecutorPort as ie,resolvePrivateHarnessDecision as P}from"../private-execution/harness-adapters/index.js";const ne="CompatibilityReleaseDoctor/1.0",se="CompatibilityDoctorResponse/1.0",L=Object.freeze({SUCCESS:0,BLOCKED:1,USAGE:2}),s=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"}),D=Object.freeze(["implementationComplete","betaOperable","releaseReady","productionPromoted"]),ae=64*1024,ce=32,le=5e3,T=/^[a-z][a-z0-9-]{0,63}$/u,V=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/u,v=/^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][A-Za-z0-9.-]{1,40})?$/u,ue=/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u,F=/^[a-f0-9]{64}$/u,de=/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/u,fe=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,me=/^(?: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.'}),H=new Map([[s.MALFORMED_RESPONSE,0],[s.AUTHORITY_UNAVAILABLE,1],[s.CLIENT_TOO_OLD,2],[s.SERVER_TOO_OLD,3],[s.PROTOCOL_MISMATCH,4],[s.SCHEMA_MISMATCH,5],[s.CAPABILITY_MISMATCH,6],[s.REGISTRY_DRIFT,7],[s.SERVER_UNREACHABLE,8],[s.OFFLINE,9],[s.RELEASE_LIFECYCLE_UNAVAILABLE,10],[s.REQUIRED_DIMENSION_BLOCKED,11],[s.HEALTHY,100]]);function $(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 pe(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 ye(e,r=process.env){let t="online",o=!1,i=r.NEOCORTEX_SERVER_URL??U,c=!1,m=null,d=process.cwd();for(let n=0;n<e.length;n+=1){const a=e[n];if(a==="--offline")t="offline";else if(a==="--json")o=!0;else if(a==="--server-url"){const p=e[n+1];if(!p)throw new Error("doctor-server-url-required");i=p,c=!0,n+=1}else if(a==="--require"){const p=e[n+1],f=pe(p);if(!p||!f)throw new Error("doctor-required-dimension-invalid");m=f,n+=1}else if(a==="--project-root"){const p=e[n+1];if(!p||p.length>4096||p.includes("\0"))throw new Error("doctor-project-root-invalid");d=ee(p),n+=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:o,serverUrl:U,requiredDimension:m,projectRoot:d});if(i.length>2048)throw new Error("doctor-server-url-invalid");try{const n=new URL(i);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||n.search||n.hash)throw new Error("url")}catch{throw new Error("doctor-server-url-invalid")}return Object.freeze({mode:t,json:o,serverUrl:i.replace(/\/+$/u,""),requiredDimension:m,projectRoot:d})}function Ee(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 be(){const e=["@neocortex/shared/compatibility","../../../shared/dist/compatibility/index.js"];for(const r of e)try{const t=await import(r);if(Ee(t))return t}catch{}return null}function he(e,r){if(typeof r.createReleaseLifecycleContext!="function")return null;try{const t=Q(e,".neocortex","state.json"),o=K(t);if(!o.isFile()||o.size<=0||o.size>1024*1024)return null;const i=JSON.parse(Z(t,"utf8")),m=(i.config&&typeof i.config=="object"&&!Array.isArray(i.config)?i.config:i.project&&typeof i.project=="object"&&!Array.isArray(i.project)?i.project:null)?.project_id;if(typeof m!="string"||!de.test(m))return null;const d=J("git",["rev-parse","--verify","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"]}).trim().toLowerCase();if(!fe.test(d))return null;const n=x("sha256").update("git-lineage-v1\0").update(d).digest("hex"),a=`candidate-${x("sha256").update("release-candidate-v1\0").update(m).update("\0").update(d).digest("hex").slice(0,32)}`;return r.createReleaseLifecycleContext({projectId:m,candidateId:a,lineageSha256:n})}catch{return null}}function u(e,r,t,o,i=null){return Object.freeze({severity:e,reasonCode:r,affectedDimension:t,evidenceRef:i,remediation:o})}function Re(e,r){if(!v.test(e)||!v.test(r))return null;const t=c=>c.split(/[-+]/u,1)[0].split(".").map(Number),o=t(e),i=t(r);for(let c=0;c<3;c+=1)if(o[c]!==i[c])return o[c]<i[c]?-1:1;return 0}function g(e){return Object.freeze([...new Set(e.filter(r=>T.test(r)))].slice(0,8).sort())}function q(e){return Object.freeze([...new Set(e.filter(r=>V.test(r)))].slice(0,32).sort())}function B(e){return Object.freeze([...new Set(e.filter(r=>me.test(r)))].slice(0,8).sort())}function Oe(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"||!v.test(r.clientVersion)||typeof r.serverVersion!="string"||!v.test(r.serverVersion)||!(r.protocolVersion===null||typeof r.protocolVersion=="string"&&V.test(r.protocolVersion))||!Array.isArray(r.schemaVersions)||!r.schemaVersions.every(o=>typeof o=="string")||!Array.isArray(r.capabilityIds)||!r.capabilityIds.every(o=>typeof o=="string")||!Array.isArray(r.reasonCodes)||!r.reasonCodes.every(o=>typeof o=="string")||!t||typeof t.version!="string"||!ue.test(t.version)||typeof t.checksum!="string"||!F.test(t.checksum)||!["matched","mismatched","unknown"].includes(String(t.status))?null:r}function Ae(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;if(typeof r.candidateId!="string"||!V.test(r.candidateId)||typeof r.lineageSha256!="string"||!F.test(r.lineageSha256))return null;for(const t of D){const o=r[t];if(!o||typeof o!="object"||Array.isArray(o))return null;const i=o;if(!(typeof i.value=="boolean"||i.value==="unknown")||!["fresh","stale","unknown"].includes(String(i.freshness))||!Array.isArray(i.reasonCodes)||!i.reasonCodes.every(c=>typeof c=="string")||!Array.isArray(i.evidenceRefs)||!i.evidenceRefs.every(c=>typeof c=="string"))return null}return r}function Ce(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((o,i)=>r[o.severity]-r[i.severity]||(H.get(o.reasonCode)??50)-(H.get(i.reasonCode)??50)||(t.get(o.affectedDimension)??99)-(t.get(i.affectedDimension)??99)||o.reasonCode.localeCompare(i.reasonCode)).slice(0,ce))}function ve(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 w=()=>te();function Be(e){const r=w;return w=e,r}function ge(){let e;try{e=w()}catch{e="unknown"}return e==="absent"||e==="user-value"||e==="settings-invalid"?[u("warning",s.CLAUDE_WORKTREE_BASEREF_NOT_HEAD,"compatibility",l.claudeWorktree,null)]:[]}function E(e){const r=[...e.findings,...ge()],t=e.dimensions??$();let o=e.incompatible;e.requiredDimension&&t[e.requiredDimension].value!==!0&&(o=!0,r.push(u("error",s.REQUIRED_DIMENSION_BLOCKED,e.requiredDimension,l.required,t[e.requiredDimension].evidenceRefs[0]??null)));const i=Ce(r),c=o?"incompatible":i.some(m=>m.severity==="warning")?"degraded":"healthy";return Object.freeze({schemaVersion:ne,publicSafe:!0,readOnly:!0,mode:e.mode,overall:c,exitCode:o?L.BLOCKED:L.SUCCESS,compatibility:e.compatibility??ve(e.clientVersion),release:Object.freeze({candidateId:e.candidateId??null,lineageSha256:e.lineageSha256??null,requiredDimension:e.requiredDimension,dimensions:t}),findings:i})}function Se(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;return"compatibility"in r?r.schemaVersion!==void 0&&r.schemaVersion!==se?null:{compatibility:r.compatibility,...r.releaseLifecycle!==void 0?{releaseLifecycle:r.releaseLifecycle}:{}}:{compatibility:e}}async function _e(e,r,t,o){const i=new AbortController,c=setTimeout(()=>i.abort(),le);try{const m=I.from(JSON.stringify(t),"utf8").toString("base64url");if(m.length>8192)return{kind:"malformed"};const d=o===null?null:I.from(JSON.stringify(o),"utf8").toString("base64url");if(d&&d.length>2048)return{kind:"malformed"};const n=await e(`${r}/api/v1/compatibility`,{method:"GET",headers:Object.freeze({Accept:"application/json","Cache-Control":"no-store","X-Neocortex-Compatibility-Offer":m,...d?{"X-Neocortex-Release-Context":d}:{}}),signal:i.signal});if(n.status===404||n.status===405||n.status===426)return{kind:"server-too-old"};if(!n.ok)return n.status>=500?{kind:"unreachable"}:{kind:"malformed"};const a=await n.text();if(I.byteLength(a,"utf8")>ae)return{kind:"malformed"};try{return{kind:"ok",value:JSON.parse(a)}}catch{return{kind:"malformed"}}}catch{return{kind:"unreachable"}}finally{clearTimeout(c)}}function Ie(e,r){return E({mode:"offline",clientVersion:e,requiredDimension:r,incompatible:!1,findings:[u("warning",s.OFFLINE,"compatibility",l.offline),u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]})}const Y="private-executor-headless-unavailable",G="private-executor-version-unsupported",X=/^\d{1,9}\.\d{1,9}\.\d{1,9}$/u,S=Object.freeze({availability:"absent",version:null,refusalReasonCode:null});async function Le(e,r={}){try{const o=P(e)?.kind==="adapter"?ie(e,r):void 0;if(o===void 0)return Object.freeze({availability:"refused",version:null,refusalReasonCode:Y});const i=await o.preflight();return X.test(i.hostVersion)?Object.freeze({availability:"available",version:i.hostVersion,refusalReasonCode:null}):S}catch(t){return t instanceof Error&&t.message===G?Object.freeze({availability:"refused",version:null,refusalReasonCode:G}):S}}function De(e){if(!e||typeof e!="object"||Array.isArray(e))return S;const r=e,t=r.version,o=r.refusalReasonCode;return r.availability==="available"&&typeof t=="string"&&X.test(t)&&o===null?Object.freeze({availability:"available",version:t,refusalReasonCode:null}):r.availability==="refused"&&t===null&&typeof o=="string"&&T.test(o)?Object.freeze({availability:"refused",version:null,refusalReasonCode:o}):S}async function Te(e,r){const t=r.probePrivateExecutor,o=await Promise.all(oe.map(async i=>{if(t===void 0)return Object.freeze({hostKind:i,...P(i)?.kind==="refusal"?{availability:"refused",version:null,refusalReasonCode:Y}:{availability:"not-probed",version:null,refusalReasonCode:null}});let c;try{c=await t(i)}catch{c=void 0}return Object.freeze({hostKind:i,...De(c)})}));return Object.freeze(o)}async function Ve(e,r={}){const[t,o]=await Promise.all([we(e,r),Te(e.projectRoot,r)]);return Object.freeze({...t,privateExecutors:o})}async function we(e,r){const t=(r.getClientVersion??re)();if(e.mode==="offline")return Ie(t,e.requiredDimension);const o=await(r.loadCompatibilityAuthority??be)();if(!o)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]});let i;try{i=o.createCompatibilityOffer({clientVersion:t,registryVersion:C,registryChecksum:A})}catch{return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]})}const c=(r.collectReleaseContext??he)(e.projectRoot,o),m=r.fetch??globalThis.fetch,d=await _e(m,e.serverUrl,i,c);if(d.kind==="unreachable")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!1,findings:[u("warning",s.SERVER_UNREACHABLE,"compatibility",l.unreachable),u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(d.kind==="server-too-old")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.SERVER_TOO_OLD,"compatibility",l.serverTooOld),u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(d.kind==="malformed")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const n=Se(d.value);if(!n||!o.isCompatibilityResultV1(n.compatibility))return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const a=Oe(n.compatibility);if(!a||a.clientVersion!==t)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const p=Object.freeze({status:a.status,clientVersion:t,serverVersion:a.serverVersion,protocolVersion:a.protocolVersion,schemaVersions:q(a.schemaVersions),capabilityIds:q(a.capabilityIds),registry:Object.freeze({localVersion:C,localChecksum:A,remoteVersion:a.commandRegistry.version,remoteChecksum:a.commandRegistry.checksum,status:a.commandRegistry.status})}),f=[],h=g(a.reasonCodes),j=Re(t,a.serverVersion);if(a.status==="incompatible"&&j===-1?f.push(u("error",s.CLIENT_TOO_OLD,"compatibility",l.clientTooOld,`client-version:${t}`)):a.status==="incompatible"&&j===1&&f.push(u("error",s.SERVER_TOO_OLD,"compatibility",l.serverTooOld,`server-version:${a.serverVersion}`)),h.some(y=>y.includes("protocol"))&&f.push(u("error",s.PROTOCOL_MISMATCH,"compatibility",l.protocol)),h.some(y=>y.includes("schema"))&&f.push(u("error",s.SCHEMA_MISMATCH,"compatibility",l.schema)),h.some(y=>y.includes("capability"))&&f.push(u("error",s.CAPABILITY_MISMATCH,"compatibility",l.capability)),(a.commandRegistry.status==="mismatched"||a.commandRegistry.version!==C||a.commandRegistry.checksum!==A)&&f.push(u("error",s.REGISTRY_DRIFT,"compatibility",l.registry,`sha256:${a.commandRegistry.checksum}`)),a.status==="incompatible"&&f.length===0)f.push(u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed));else if(a.status==="degraded")for(const y of h)f.push(u("warning",y,"compatibility",l.lifecycle));let N=$(),M=null,z=null,k=!1;if(n.releaseLifecycle===void 0)f.push(u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle));else{const y=o.validateReleaseLifecycle(n.releaseLifecycle),R=y.accepted?Ae(y.projection):null;if(R){M=R.candidateId,z=R.lineageSha256;const O={};for(const _ of D){const b=R[_];if(O[_]=Object.freeze({value:b.value,freshness:b.freshness,reasonCodes:g(b.reasonCodes),evidenceRefs:B(b.evidenceRefs)}),b.value!==!0||b.freshness!=="fresh")for(const W of g(b.reasonCodes))f.push(u("warning",W,_,l.lifecycle,B(b.evidenceRefs)[0]??null))}N=Object.freeze(O)}else{k=!0,f.push(u("error",s.MALFORMED_RESPONSE,"releaseLifecycle",l.malformed));for(const O of g(y.reasonCodes))f.push(u("error",O,"releaseLifecycle",l.lifecycle))}}return f.length===0&&f.push(u("info",s.HEALTHY,"compatibility",l.healthy)),E({mode:"online",clientVersion:t,compatibility:p,dimensions:N,candidateId:M,lineageSha256:z,requiredDimension:e.requiredDimension,findings:f,incompatible:a.status==="incompatible"||k})}function je(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 D){const o=e.release.dimensions[t];r.push(` ${t}: ${String(o.value)} (${o.freshness}) [${o.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}`);r.push("","Private executors:");for(const t of e.privateExecutors)r.push(` ${t.hostKind}: ${t.availability} version=${t.version??"unknown"} refusal=${t.refusalReasonCode??"none"}`);return r.push("","Doctor made no repairs or state changes."),r.join(`
2
- `)}async function Ye(e,r){const t=r??{},o=t.stdout??console.log,i=t.stderr??console.error;let c;try{c=ye(e,t.env??process.env)}catch(n){const a=n instanceof Error&&T.test(n.message)?n.message:"doctor-argument-invalid";return i(`Error: ${a}`),L.USAGE}const m=c.projectRoot,d=await Ve(c,r===void 0?{...t,probePrivateExecutor:n=>Le(n,{cwd:m})}:t);return o(c.json?JSON.stringify(d,null,2):je(d)),d.exitCode}export{L as DOCTOR_EXIT_CODES,s as DOCTOR_REASON_CODES,se as DOCTOR_RESPONSE_SCHEMA_VERSION,ne as DOCTOR_SCHEMA_VERSION,Be as __setDoctorClaudeWorktreeInspector,he as collectLocalReleaseLifecycleContext,Le as defaultProbePrivateExecutor,Ye as doctorCliHandler,be as loadSharedCompatibilityAuthority,ye as parseDoctorArgs,je as renderDoctorReport,Ve as runDoctor};
1
+ import{Buffer as A}from"node:buffer";import{createHash as U}from"node:crypto";import{execFileSync as Q}from"node:child_process";import{readFileSync as ee,statSync as re}from"node:fs";import{join as te,resolve as ie}from"node:path";import{COMMAND_REGISTRY_CHECKSUM as _,COMMAND_REGISTRY_VERSION as C}from"../generated/command-registry.generated.js";import{DEFAULT_SERVER_URL as h}from"../constants.js";import{getClientVersion as oe}from"../version.js";import{inspectClaudeWorktreeBaseRef as ne}from"../agent/claude-worktree-base.js";import{PRIVATE_EXECUTION_HOST_KINDS as se}from"../../../shared/dist/compatibility/index.js";import{createPrivateHarnessExecutorPort as ae,resolvePrivateHarnessDecision as F}from"../private-execution/harness-adapters/index.js";const ce="CompatibilityReleaseDoctor/1.0",le="CompatibilityDoctorResponse/1.0",T=Object.freeze({SUCCESS:0,BLOCKED:1,USAGE:2}),a=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",ACTIVE_PRODUCTION_VERIFIED:"active-production-verified",REQUIRED_DIMENSION_BLOCKED:"required-release-dimension-blocked",CLAUDE_WORKTREE_BASEREF_NOT_HEAD:"claude-worktree-baseref-not-head"}),V=Object.freeze(["implementationComplete","betaOperable","releaseReady","productionPromoted"]),$=64*1024,ue=32,q=5e3,w=/^[a-z][a-z0-9-]{0,63}$/u,j=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/u,S=/^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][A-Za-z0-9.-]{1,40})?$/u,de=/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u,H=/^[a-f0-9]{64}$/u,fe=/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/u,me=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,pe=/^(?:local-gate|beta-receipt|release-gate|promotion-receipt|sha256):[a-f0-9]{64}$/u,d=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.'}),B=new Map([[a.MALFORMED_RESPONSE,0],[a.AUTHORITY_UNAVAILABLE,1],[a.CLIENT_TOO_OLD,2],[a.SERVER_TOO_OLD,3],[a.PROTOCOL_MISMATCH,4],[a.SCHEMA_MISMATCH,5],[a.CAPABILITY_MISMATCH,6],[a.REGISTRY_DRIFT,7],[a.SERVER_UNREACHABLE,8],[a.OFFLINE,9],[a.RELEASE_LIFECYCLE_UNAVAILABLE,10],[a.REQUIRED_DIMENSION_BLOCKED,11],[a.HEALTHY,100]]);function Y(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 ye(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 Ee(e,r=process.env){let t="online",i=!1,o=r.NEOCORTEX_SERVER_URL??h,c=!1,f=null,l=process.cwd();for(let n=0;n<e.length;n+=1){const s=e[n];if(s==="--offline")t="offline";else if(s==="--json")i=!0;else if(s==="--server-url"){const y=e[n+1];if(!y)throw new Error("doctor-server-url-required");o=y,c=!0,n+=1}else if(s==="--require"){const y=e[n+1],m=ye(y);if(!y||!m)throw new Error("doctor-required-dimension-invalid");f=m,n+=1}else if(s==="--project-root"){const y=e[n+1];if(!y||y.length>4096||y.includes("\0"))throw new Error("doctor-project-root-invalid");l=ie(y),n+=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:h,requiredDimension:f,projectRoot:l});if(o.length>2048)throw new Error("doctor-server-url-invalid");try{const n=new URL(o);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||n.search||n.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:l})}function be(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 he(){const e=["@neocortex/shared/compatibility","../../../shared/dist/compatibility/index.js"];for(const r of e)try{const t=await import(r);if(be(t))return t}catch{}return null}function Re(e,r){if(typeof r.createReleaseLifecycleContext!="function")return null;try{const t=te(e,".neocortex","state.json"),i=re(t);if(!i.isFile()||i.size<=0||i.size>1024*1024)return null;const o=JSON.parse(ee(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"||!fe.test(f))return null;const l=Q("git",["rev-parse","--verify","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"]}).trim().toLowerCase();if(!me.test(l))return null;const n=U("sha256").update("git-lineage-v1\0").update(l).digest("hex"),s=`candidate-${U("sha256").update("release-candidate-v1\0").update(f).update("\0").update(l).digest("hex").slice(0,32)}`;return r.createReleaseLifecycleContext({projectId:f,candidateId:s,lineageSha256:n})}catch{return null}}function u(e,r,t,i,o=null){return Object.freeze({severity:e,reasonCode:r,affectedDimension:t,evidenceRef:o,remediation:i})}function Oe(e,r){if(!S.test(e)||!S.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 I(e){return Object.freeze([...new Set(e.filter(r=>w.test(r)))].slice(0,8).sort())}function G(e){return Object.freeze([...new Set(e.filter(r=>j.test(r)))].slice(0,32).sort())}function X(e){return Object.freeze([...new Set(e.filter(r=>pe.test(r)))].slice(0,8).sort())}function ve(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"||!S.test(r.clientVersion)||typeof r.serverVersion!="string"||!S.test(r.serverVersion)||!(r.protocolVersion===null||typeof r.protocolVersion=="string"&&j.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"||!de.test(t.version)||typeof t.checksum!="string"||!H.test(t.checksum)||!["matched","mismatched","unknown"].includes(String(t.status))?null:r}function ge(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;if(typeof r.candidateId!="string"||!j.test(r.candidateId)||typeof r.lineageSha256!="string"||!H.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 Ae(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]||(B.get(i.reasonCode)??50)-(B.get(o.reasonCode)??50)||(t.get(i.affectedDimension)??99)-(t.get(o.affectedDimension)??99)||i.reasonCode.localeCompare(o.reasonCode)).slice(0,ue))}function _e(e){return Object.freeze({status:"unknown",clientVersion:e,serverVersion:null,protocolVersion:null,schemaVersions:Object.freeze([]),capabilityIds:Object.freeze([]),registry:Object.freeze({localVersion:C,localChecksum:_,remoteVersion:null,remoteChecksum:null,status:"unknown"})})}let N=()=>ne();function Ge(e){const r=N;return N=e,r}function Ce(){let e;try{e=N()}catch{e="unknown"}return e==="absent"||e==="user-value"||e==="settings-invalid"?[u("warning",a.CLAUDE_WORKTREE_BASEREF_NOT_HEAD,"compatibility",d.claudeWorktree,null)]:[]}function E(e){const r=[...e.findings,...Ce()],t=e.dimensions??Y();let i=e.incompatible;const o=e.requiredDimension==="productionPromoted"&&e.activeProduction!==void 0;e.requiredDimension&&t[e.requiredDimension].value!==!0&&!o&&(i=!0,r.push(u("error",a.REQUIRED_DIMENSION_BLOCKED,e.requiredDimension,d.required,t[e.requiredDimension].evidenceRefs[0]??null)));const c=Ae(r),f=i?"incompatible":c.some(l=>l.severity==="warning")?"degraded":"healthy";return Object.freeze({schemaVersion:ce,publicSafe:!0,readOnly:!0,mode:e.mode,overall:f,exitCode:i?T.BLOCKED:T.SUCCESS,compatibility:e.compatibility??_e(e.clientVersion),release:Object.freeze({candidateId:e.candidateId??null,lineageSha256:e.lineageSha256??null,requiredDimension:e.requiredDimension,dimensions:t,...e.activeProduction?{activeProduction:e.activeProduction}:{}}),findings:c})}function Se(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;return"compatibility"in r?r.schemaVersion!==void 0&&r.schemaVersion!==le?null:{compatibility:r.compatibility,...r.releaseLifecycle!==void 0?{releaseLifecycle:r.releaseLifecycle}:{}}:{compatibility:e}}async function Ie(e,r,t,i){const o=new AbortController,c=setTimeout(()=>o.abort(),q);try{const f=A.from(JSON.stringify(t),"utf8").toString("base64url");if(f.length>8192)return{kind:"malformed"};const l=i===null?null:A.from(JSON.stringify(i),"utf8").toString("base64url");if(l&&l.length>2048)return{kind:"malformed"};const n=await e(`${r}/api/v1/compatibility`,{method:"GET",headers:Object.freeze({Accept:"application/json","Cache-Control":"no-store","X-Neocortex-Compatibility-Offer":f,...l?{"X-Neocortex-Release-Context":l}:{}}),signal:o.signal,...r===h?{redirect:"error"}:{}});if(n.status===404||n.status===405||n.status===426)return{kind:"server-too-old"};if(!n.ok)return n.status>=500?{kind:"unreachable"}:{kind:"malformed"};const s=await n.text();if(A.byteLength(s,"utf8")>$)return{kind:"malformed"};try{return{kind:"ok",value:JSON.parse(s)}}catch{return{kind:"malformed"}}}catch{return{kind:"unreachable"}}finally{clearTimeout(c)}}async function Le(e,r){const t=/^sha256:[a-f0-9]{64}$/u,i=o=>typeof o=="string"&&t.test(o);try{const o=await e(`${h}/health?deep=true`,{method:"GET",headers:{Accept:"application/json","Cache-Control":"no-store"},cache:"no-store",redirect:"error",signal:AbortSignal.timeout(q)});if(!o.ok)return;const c=await o.text();if(A.byteLength(c,"utf8")>$)return;const f=JSON.parse(c),l=f?.supply_chain,n=f?.asset_authority,s=f?.asset_canary;return f?.status!=="ok"||f.version!==r||l?.verification_enabled!==!0||l.provenance_verified!==!0||l.release_binding_complete!==!0||l.sbom_present!==!0||typeof l.source_revision!="string"||!/^[a-f0-9]{40}$/u.test(l.source_revision)||!i(l.image_digest)||!i(l.sbom_digest)||!i(l.release_binding_digest)||n?.schema_version!==1||n.public_safe!==!0||n.release_generation_compatible!==!0||!i(n.generation)||s?.schema_version!==1||s.public_safe!==!0||s.outcome!=="passed"||s.generation!==n.generation?void 0:Object.freeze({version:r,sourceRevision:l.source_revision,imageDigest:l.image_digest,releaseBindingDigest:l.release_binding_digest})}catch{return}}function De(e,r){return E({mode:"offline",clientVersion:e,requiredDimension:r,incompatible:!1,findings:[u("warning",a.OFFLINE,"compatibility",d.offline),u("warning",a.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",d.lifecycle)]})}const J="private-executor-headless-unavailable",W="private-executor-version-unsupported",Z=/^\d{1,9}\.\d{1,9}\.\d{1,9}$/u,L=Object.freeze({availability:"absent",version:null,refusalReasonCode:null});async function Te(e,r={}){try{const i=F(e)?.kind==="adapter"?ae(e,r):void 0;if(i===void 0)return Object.freeze({availability:"refused",version:null,refusalReasonCode:J});const o=await i.preflight();return Z.test(o.hostVersion)?Object.freeze({availability:"available",version:o.hostVersion,refusalReasonCode:null}):L}catch(t){return t instanceof Error&&t.message===W?Object.freeze({availability:"refused",version:null,refusalReasonCode:W}):L}}function Ve(e){if(!e||typeof e!="object"||Array.isArray(e))return L;const r=e,t=r.version,i=r.refusalReasonCode;return r.availability==="available"&&typeof t=="string"&&Z.test(t)&&i===null?Object.freeze({availability:"available",version:t,refusalReasonCode:null}):r.availability==="refused"&&t===null&&typeof i=="string"&&w.test(i)?Object.freeze({availability:"refused",version:null,refusalReasonCode:i}):L}async function we(e,r){const t=r.probePrivateExecutor,i=await Promise.all(se.map(async o=>{if(t===void 0)return Object.freeze({hostKind:o,...F(o)?.kind==="refusal"?{availability:"refused",version:null,refusalReasonCode:J}:{availability:"not-probed",version:null,refusalReasonCode:null}});let c;try{c=await t(o)}catch{c=void 0}return Object.freeze({hostKind:o,...Ve(c)})}));return Object.freeze(i)}async function je(e,r={}){const[t,i]=await Promise.all([Ne(e,r),we(e.projectRoot,r)]);return Object.freeze({...t,privateExecutors:i})}async function Ne(e,r){const t=(r.getClientVersion??oe)();if(e.mode==="offline")return De(t,e.requiredDimension);const i=await(r.loadCompatibilityAuthority??he)();if(!i)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",a.AUTHORITY_UNAVAILABLE,"compatibility",d.authority)]});let o;try{o=i.createCompatibilityOffer({clientVersion:t,registryVersion:C,registryChecksum:_})}catch{return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",a.AUTHORITY_UNAVAILABLE,"compatibility",d.authority)]})}const c=(r.collectReleaseContext??Re)(e.projectRoot,i),f=r.fetch??globalThis.fetch,l=await Ie(f,e.serverUrl,o,c);if(l.kind==="unreachable")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!1,findings:[u("warning",a.SERVER_UNREACHABLE,"compatibility",d.unreachable),u("warning",a.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",d.lifecycle)]});if(l.kind==="server-too-old")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",a.SERVER_TOO_OLD,"compatibility",d.serverTooOld),u("warning",a.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",d.lifecycle)]});if(l.kind==="malformed")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",a.MALFORMED_RESPONSE,"compatibility",d.malformed)]});const n=Se(l.value);if(!n||!i.isCompatibilityResultV1(n.compatibility))return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",a.MALFORMED_RESPONSE,"compatibility",d.malformed)]});const s=ve(n.compatibility);if(!s||s.clientVersion!==t)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",a.MALFORMED_RESPONSE,"compatibility",d.malformed)]});const y=Object.freeze({status:s.status,clientVersion:t,serverVersion:s.serverVersion,protocolVersion:s.protocolVersion,schemaVersions:G(s.schemaVersions),capabilityIds:G(s.capabilityIds),registry:Object.freeze({localVersion:C,localChecksum:_,remoteVersion:s.commandRegistry.version,remoteChecksum:s.commandRegistry.checksum,status:s.commandRegistry.status})}),m=[],R=I(s.reasonCodes),P=Oe(t,s.serverVersion);if(s.status==="incompatible"&&P===-1?m.push(u("error",a.CLIENT_TOO_OLD,"compatibility",d.clientTooOld,`client-version:${t}`)):s.status==="incompatible"&&P===1&&m.push(u("error",a.SERVER_TOO_OLD,"compatibility",d.serverTooOld,`server-version:${s.serverVersion}`)),R.some(p=>p.includes("protocol"))&&m.push(u("error",a.PROTOCOL_MISMATCH,"compatibility",d.protocol)),R.some(p=>p.includes("schema"))&&m.push(u("error",a.SCHEMA_MISMATCH,"compatibility",d.schema)),R.some(p=>p.includes("capability"))&&m.push(u("error",a.CAPABILITY_MISMATCH,"compatibility",d.capability)),(s.commandRegistry.status==="mismatched"||s.commandRegistry.version!==C||s.commandRegistry.checksum!==_)&&m.push(u("error",a.REGISTRY_DRIFT,"compatibility",d.registry,`sha256:${s.commandRegistry.checksum}`)),s.status==="incompatible"&&m.length===0)m.push(u("error",a.MALFORMED_RESPONSE,"compatibility",d.malformed));else if(s.status==="degraded")for(const p of R)m.push(u("warning",p,"compatibility",d.lifecycle));let M=Y(),k=null,z=null,x=!1,O;if(n.releaseLifecycle===void 0)c===null&&e.serverUrl===h&&(e.requiredDimension===null||e.requiredDimension==="productionPromoted")&&s.status==="compatible"&&m.every(p=>p.severity!=="error")&&(O=await Le(f,s.serverVersion)),O?m.push(u("info",a.ACTIVE_PRODUCTION_VERIFIED,"productionPromoted","The active OCI release reports verified provenance and a complete deployment binding.",O.releaseBindingDigest)):m.push(u("warning",a.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",d.lifecycle));else{const p=i.validateReleaseLifecycle(n.releaseLifecycle),v=p.accepted?ge(p.projection):null;if(v){k=v.candidateId,z=v.lineageSha256;const g={};for(const D of V){const b=v[D];if(g[D]=Object.freeze({value:b.value,freshness:b.freshness,reasonCodes:I(b.reasonCodes),evidenceRefs:X(b.evidenceRefs)}),b.value!==!0||b.freshness!=="fresh")for(const K of I(b.reasonCodes))m.push(u("warning",K,D,d.lifecycle,X(b.evidenceRefs)[0]??null))}M=Object.freeze(g)}else{x=!0,m.push(u("error",a.MALFORMED_RESPONSE,"releaseLifecycle",d.malformed));for(const g of I(p.reasonCodes))m.push(u("error",g,"releaseLifecycle",d.lifecycle))}}return m.length===0&&m.push(u("info",a.HEALTHY,"compatibility",d.healthy)),E({mode:"online",clientVersion:t,compatibility:y,dimensions:M,candidateId:k,lineageSha256:z,activeProduction:O,requiredDimension:e.requiredDimension,findings:m,incompatible:s.status==="incompatible"||x})}function Pe(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}`,"","Project candidate lifecycle:"];for(const t of V){const i=e.release.dimensions[t];r.push(` ${t}: ${String(i.value)} (${i.freshness}) [${i.reasonCodes.join(",")||"none"}]`)}if(e.release.activeProduction){const t=e.release.activeProduction;r.push(` Active production: v${t.version} at ${t.sourceRevision} [${t.releaseBindingDigest}]`)}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}`);r.push("","Private executors:");for(const t of e.privateExecutors)r.push(` ${t.hostKind}: ${t.availability} version=${t.version??"unknown"} refusal=${t.refusalReasonCode??"none"}`);return r.push("","Doctor made no repairs or state changes."),r.join(`
2
+ `)}async function Xe(e,r){const t=r??{},i=t.stdout??console.log,o=t.stderr??console.error;let c;try{c=Ee(e,t.env??process.env)}catch(n){const s=n instanceof Error&&w.test(n.message)?n.message:"doctor-argument-invalid";return o(`Error: ${s}`),T.USAGE}const f=c.projectRoot,l=await je(c,r===void 0?{...t,probePrivateExecutor:n=>Te(n,{cwd:f})}:t);return i(c.json?JSON.stringify(l,null,2):Pe(l)),l.exitCode}export{T as DOCTOR_EXIT_CODES,a as DOCTOR_REASON_CODES,le as DOCTOR_RESPONSE_SCHEMA_VERSION,ce as DOCTOR_SCHEMA_VERSION,Ge as __setDoctorClaudeWorktreeInspector,Re as collectLocalReleaseLifecycleContext,Te as defaultProbePrivateExecutor,Xe as doctorCliHandler,he as loadSharedCompatibilityAuthority,Ee as parseDoctorArgs,Pe as renderDoctorReport,je as runDoctor};
@@ -16,6 +16,7 @@ import { type InvokeEffectContext, type StrictReadOnlyInvokeEnvelope } from '../
16
16
  import { type ExplicitIntentRecoveryBindingV1, type ExplicitIntentRecoveryResultV1, type InvokeInputEvidenceV1, type InvokeInputEnvelopeV2, type InvokeInputSourceV2, type InvocationMalformedInputReasonV1, type InvocationAdmissionResultV1, type ProjectIdentityMigrationRequestV1 } from '../../../shared/dist/invocation/index.js';
17
17
  import { COMPATIBILITY_CAPABILITIES, type CompatibilityOfferV1, type CompatibilityResultV1, type PrivateExecutionHostKind } from '../../../shared/dist/compatibility/index.js';
18
18
  import { type P205TransientExecutionAuthority } from '../git/git-lifecycle-store.js';
19
+ import type { PublishedStoryReconciliation } from '../git/published-story-reconciliation.js';
19
20
  /**
20
21
  * P226.04: the collector may fail with the bounded per-field frontmatter code
21
22
  * (`frontmatter-list-too-long:<field>:<n>><limit>`); surface it verbatim instead
@@ -65,6 +66,8 @@ export interface InvokeOptions {
65
66
  readonly environment?: NodeJS.ProcessEnv;
66
67
  /** P205.05 exact outer transport policy; never inferred from response metadata. */
67
68
  readonly strictReadOnly?: boolean;
69
+ /** Explicit opt-in from a wrapper that can consume the scoped diagnose receipt. */
70
+ readonly diagnoseScopedContinuation?: boolean;
68
71
  /** Explicit P222.16 beta; never inferred from Codex being installed. */
69
72
  readonly privateExecutionBeta?: boolean;
70
73
  /** Explicit local subscription model override; never part of server args or a fallback. */
@@ -345,6 +348,7 @@ export interface InvokeCliParsedOptions {
345
348
  readonly serverUrl?: string;
346
349
  readonly platformTarget?: string;
347
350
  readonly strictReadOnly: boolean;
351
+ readonly diagnoseScopedContinuation?: true;
348
352
  readonly privateExecutionBeta: boolean;
349
353
  readonly privateExecutionModel?: string;
350
354
  }
@@ -667,7 +671,7 @@ export type InvokeRequestBody = InvokeRequestBodyBase & ({
667
671
  readonly args?: never;
668
672
  readonly argsRef: InvokeArgsRef;
669
673
  });
670
- export declare function buildInvokeCompatibilityOffer(): CompatibilityOfferV1;
674
+ export declare function buildInvokeCompatibilityOffer(diagnoseScopedContinuation?: boolean): CompatibilityOfferV1;
671
675
  export interface InvokePayloadTelemetry {
672
676
  readonly schemaVersion: 1;
673
677
  readonly payloadBytes: number;
@@ -758,6 +762,8 @@ export interface StateSnapshotCollectionOptions {
758
762
  readonly p205Authorities?: Readonly<Record<string, P205TransientExecutionAuthority>>;
759
763
  /** P230.07: count-only P205 order diagnostics projected on the affected epic. */
760
764
  readonly p205AuthorityDiagnostics?: readonly P205AuthorityEpicDiagnostic[];
765
+ /** Public scheduling proof revalidated against the remote for this request. */
766
+ readonly publishedStoryReconciliations?: readonly PublishedStoryReconciliation[];
761
767
  }
762
768
  export declare class StateSnapshotIntegrityError extends Error {
763
769
  readonly reasonCode: string;