@ornexus/neocortex 4.60.63 → 4.60.65

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 (136) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +31 -38
  3. package/install.js +1 -0
  4. package/install.ps1 +34 -3
  5. package/install.sh +35 -3
  6. package/package.json +5 -3
  7. package/packages/client/dist/cli.js +8 -3
  8. package/packages/client/dist/commands/activate.js +8 -8
  9. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -2
  10. package/packages/client/dist/commands/architecture-non-ui-continuation.d.ts +3 -0
  11. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -0
  12. package/packages/client/dist/commands/invoke.d.ts +19 -16
  13. package/packages/client/dist/commands/invoke.js +80 -75
  14. package/packages/client/dist/commands/mutation-qa-run.js +2 -2
  15. package/packages/client/dist/commands/planning-generation.js +1 -1
  16. package/packages/client/dist/commands/planning-memory.d.ts +1 -0
  17. package/packages/client/dist/commands/planning-memory.js +1 -0
  18. package/packages/client/dist/commands/private-session.d.ts +1 -0
  19. package/packages/client/dist/commands/private-session.js +1 -0
  20. package/packages/client/dist/commands/qa-control.d.ts +4 -0
  21. package/packages/client/dist/commands/qa-control.js +1 -0
  22. package/packages/client/dist/commands/qa-scan-browser-launch.d.ts +8 -0
  23. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -0
  24. package/packages/client/dist/commands/qa-scan-browser-route.d.ts +3 -0
  25. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -0
  26. package/packages/client/dist/commands/qa-scan-capture.d.ts +43 -0
  27. package/packages/client/dist/commands/qa-scan-capture.js +5 -5
  28. package/packages/client/dist/commands/qa-scan-discovery.d.ts +7 -0
  29. package/packages/client/dist/commands/qa-scan-discovery.js +3 -3
  30. package/packages/client/dist/commands/qa-scan-review.d.ts +8 -1
  31. package/packages/client/dist/commands/qa-scan-review.js +5 -5
  32. package/packages/client/dist/commands/qa-synthetic-backend-capture.d.ts +62 -0
  33. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -0
  34. package/packages/client/dist/commands/qa-synthetic-backend-review.d.ts +104 -0
  35. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -0
  36. package/packages/client/dist/commands/qa-synthetic-backend.d.ts +52 -0
  37. package/packages/client/dist/commands/qa-synthetic-backend.js +7 -0
  38. package/packages/client/dist/commands/qa-synthetic-broker-port.d.ts +30 -0
  39. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -0
  40. package/packages/client/dist/commands/qa-synthetic-browser.d.ts +1 -0
  41. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -0
  42. package/packages/client/dist/commands/refactor-characterization.d.ts +4 -2
  43. package/packages/client/dist/commands/refactor-characterization.js +21 -12
  44. package/packages/client/dist/commands/refactor-control.d.ts +9 -0
  45. package/packages/client/dist/commands/refactor-control.js +3 -0
  46. package/packages/client/dist/commands/refactor-cpp-assertions.d.ts +4 -0
  47. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -0
  48. package/packages/client/dist/commands/refactor-review.js +5 -5
  49. package/packages/client/dist/commands/refactor-root.d.ts +8 -1
  50. package/packages/client/dist/commands/refactor-root.js +7 -7
  51. package/packages/client/dist/commands/refresh-memory.d.ts +1 -0
  52. package/packages/client/dist/commands/refresh-memory.js +3 -3
  53. package/packages/client/dist/commands/shared-architecture-non-ui.d.ts +18 -0
  54. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -0
  55. package/packages/client/dist/errors/error-messages.js +1 -1
  56. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +5 -1
  57. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  58. package/packages/client/dist/git/git-lifecycle-store.d.ts +2 -0
  59. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  60. package/packages/client/dist/license/license-client.d.ts +3 -1
  61. package/packages/client/dist/license/license-client.js +1 -1
  62. package/packages/client/dist/memory/project-memory-path-scope.d.ts +4 -0
  63. package/packages/client/dist/memory/project-memory-path-scope.js +1 -0
  64. package/packages/client/dist/memory/project-memory-writer.d.ts +4 -1
  65. package/packages/client/dist/memory/project-memory-writer.js +16 -16
  66. package/packages/client/dist/private-execution/codex-executor.d.ts +24 -4
  67. package/packages/client/dist/private-execution/codex-executor.js +4 -2
  68. package/packages/client/dist/private-execution/codex-host-runtime.d.ts +10 -0
  69. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -0
  70. package/packages/client/dist/private-execution/codex-lifecycle-guard.d.ts +4 -0
  71. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -0
  72. package/packages/client/dist/private-execution/codex-scoped-permissions.d.ts +8 -0
  73. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -0
  74. package/packages/client/dist/private-execution/delivery.d.ts +17 -1
  75. package/packages/client/dist/private-execution/delivery.js +11 -3
  76. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +112 -0
  77. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -0
  78. package/packages/client/dist/private-execution/frozen-handoff.d.ts +2 -0
  79. package/packages/client/dist/private-execution/frozen-handoff.js +6 -0
  80. package/packages/client/dist/private-execution/implementation-validation.d.ts +15 -0
  81. package/packages/client/dist/private-execution/implementation-validation.js +2 -0
  82. package/packages/client/dist/private-execution/isolated-admission.d.ts +11 -7
  83. package/packages/client/dist/private-execution/isolated-admission.js +17 -10
  84. package/packages/client/dist/private-execution/isolated-session.d.ts +68 -0
  85. package/packages/client/dist/private-execution/isolated-session.js +5 -2
  86. package/packages/client/dist/private-execution/pact-test-source.d.ts +1 -1
  87. package/packages/client/dist/private-execution/pact-test-source.js +1 -1
  88. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -0
  89. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  90. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +13 -0
  91. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -3
  92. package/packages/client/dist/private-execution/planning-memory-checkpoint.d.ts +32 -0
  93. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -0
  94. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  95. package/packages/client/dist/private-execution/root-checkpoint.js +1 -1
  96. package/packages/client/dist/private-execution/root-memory-git-evidence.d.ts +30 -0
  97. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -0
  98. package/packages/client/dist/private-execution/root-memory-recovery.d.ts +16 -0
  99. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -0
  100. package/packages/client/dist/private-execution/root-memory-request.d.ts +28 -0
  101. package/packages/client/dist/private-execution/root-memory-request.js +1 -0
  102. package/packages/client/dist/private-execution/root-memory-scope.d.ts +28 -0
  103. package/packages/client/dist/private-execution/root-memory-scope.js +1 -0
  104. package/packages/client/dist/private-execution/root-memory-writer.d.ts +22 -0
  105. package/packages/client/dist/private-execution/root-memory-writer.js +1 -0
  106. package/packages/client/dist/private-execution/session-lease.d.ts +19 -0
  107. package/packages/client/dist/private-execution/session-lease.js +1 -0
  108. package/packages/client/dist/private-execution/shared-private-admission-types.d.ts +34 -0
  109. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -0
  110. package/packages/client/dist/private-execution/shared-project-validation.d.ts +17 -0
  111. package/packages/client/dist/private-execution/shared-project-validation.js +1 -0
  112. package/packages/client/dist/private-execution/shared-root-memory-types.d.ts +37 -0
  113. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -0
  114. package/packages/client/dist/runner/binary.d.ts +1 -1
  115. package/packages/client/dist/runner/binary.js +1 -1
  116. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  117. package/packages/client/dist/yolo/change-evidence-collector.d.ts +2 -2
  118. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  119. package/packages/client/dist/yolo/spec-envelope-collector.js +2 -2
  120. package/packages/shared/dist/planning/diagnosis-state.js +5 -2
  121. package/packages/shared/dist/project-memory-targets.js +243 -0
  122. package/packages/shared/dist/yolo/change-evidence.js +35 -0
  123. package/packages/shared/dist/yoloop/branch-unit.js +10 -1
  124. package/packages/shared/dist/yoloop/root-memory-effect.js +57 -0
  125. package/targets-stubs/antigravity/gemini.md +1 -1
  126. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  127. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  128. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  129. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  130. package/targets-stubs/claude-code/neocortex.md +2 -2
  131. package/targets-stubs/codex/AGENTS.md +1 -1
  132. package/targets-stubs/cursor/agent.md +2 -2
  133. package/targets-stubs/deepseek-harness/SKILL.md +64 -0
  134. package/targets-stubs/gemini-cli/agent.md +2 -2
  135. package/targets-stubs/opencode/neocortex-root.md +1 -1
  136. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,24 +1,24 @@
1
- import{randomUUID as B}from"node:crypto";import{constants as ee,existsSync as g,lstatSync as $,mkdirSync as j,copyFileSync as M,readdirSync as te,readFileSync as R,readlinkSync as q,realpathSync as Ce,renameSync as re,rmSync as A,statSync as $e,symlinkSync as W,unlinkSync as ne,writeFileSync as F}from"node:fs";import{platform as I}from"node:os";import{dirname as T,isAbsolute as oe,join as p,relative as se,resolve as ae,sep as Pe,win32 as Te}from"node:path";import{CANONICAL_PROJECT_MEMORY_SOURCE as y,getProjectMemoryTarget as X,renderArchitectureReferenceTable as ve}from"./shared-project-memory-types.js";function ie(e){return(e.memoryNotes?.length??0)>0||(e.architectureReferences?.length??0)>0||e.bootstrapArchitecture!==void 0}const z="<!-- NEOCORTEX-REFRESH-UPDATES-START -->",G="<!-- NEOCORTEX-REFRESH-UPDATES-END -->";function L(e,t){return e.split(t).length-1}function Oe(e){me(e.memoryNotes??[],e.architectureReferences??[],e.bootstrapArchitecture);const t=H(e.memoryNotes??[]).map(s=>`- [${s.reasonCode}] ${s.summary} (layer: ${s.layer})`),r=(e.architectureReferences??[]).map(s=>`- [architecture-reference] \`${s.path}\`: ${s.title}; ${s.purpose}; use: ${s.suggestedUsage}`),o=e.bootstrapArchitecture,n=o===void 0?[]:[...(o.universalLaws??[]).map(s=>`- [bootstrap-law] ${s}`),...(o.businessContext??[]).map(s=>`- [bootstrap-business] ${s}`),...(o.activeContext??[]).map(s=>`- [bootstrap-context] ${s}`),...(o.repositoryMap??[]).map(s=>`- [bootstrap-repository] ${s}`),...(o.environmentPractices??[]).map(s=>`- [bootstrap-environment] ${s}`),...(o.platformMemoryContract??[]).map(s=>`- [bootstrap-platform] ${s}`),...(o.maintenanceRules??[]).map(s=>`- [bootstrap-maintenance] ${s}`),...(o.heuristics??[]).map(s=>`- [bootstrap-heuristic] ${s}`)];return w([...t,...r,...n])}function xe(e,t){if(t.split(`
2
- `).length>e.budget.maxLines||Buffer.byteLength(t,"utf8")>e.budget.maxBytes)throw new Error("Canonical project memory update exceeds its context budget; refusing to truncate existing content.")}function ce(e,t,r){const o=Oe(r);if(o.length===0)return t;const n=t.includes(`\r
1
+ import{randomUUID as U}from"node:crypto";import{constants as V,existsSync as g,lstatSync as C,mkdirSync as O,copyFileSync as j,readdirSync as Q,readFileSync as E,readlinkSync as ee,realpathSync as we,renameSync as te,rmSync as N,statSync as Ee,symlinkSync as B,unlinkSync as re,writeFileSync as q}from"node:fs";import{platform as M}from"node:os";import{basename as Re,dirname as I,join as p,relative as Se,resolve as Ce}from"node:path";import{CANONICAL_PROJECT_MEMORY_SOURCE as b,getProjectMemoryTarget as W,renderArchitectureReferenceTable as Pe}from"./shared-project-memory-types.js";import{assertProjectMemoryPaths as F,invalidProjectMemoryPath as $e,isValidScopedRelativePath as Te}from"./project-memory-path-scope.js";function ne(e){return(e.memoryNotes?.length??0)>0||(e.architectureReferences?.length??0)>0||e.bootstrapArchitecture!==void 0}const X="<!-- NEOCORTEX-REFRESH-UPDATES-START -->",z="<!-- NEOCORTEX-REFRESH-UPDATES-END -->";function A(e,t){return e.split(t).length-1}function ve(e){ce(e.memoryNotes??[],e.architectureReferences??[],e.bootstrapArchitecture);const t=G(e.memoryNotes??[]).map(r=>`- [${r.reasonCode}] ${r.summary} (layer: ${r.layer})`),n=(e.architectureReferences??[]).map(r=>`- [architecture-reference] \`${r.path}\`: ${r.title}; ${r.purpose}; use: ${r.suggestedUsage}`),o=e.bootstrapArchitecture,s=o===void 0?[]:[...(o.universalLaws??[]).map(r=>`- [bootstrap-law] ${r}`),...(o.businessContext??[]).map(r=>`- [bootstrap-business] ${r}`),...(o.activeContext??[]).map(r=>`- [bootstrap-context] ${r}`),...(o.repositoryMap??[]).map(r=>`- [bootstrap-repository] ${r}`),...(o.environmentPractices??[]).map(r=>`- [bootstrap-environment] ${r}`),...(o.platformMemoryContract??[]).map(r=>`- [bootstrap-platform] ${r}`),...(o.maintenanceRules??[]).map(r=>`- [bootstrap-maintenance] ${r}`),...(o.heuristics??[]).map(r=>`- [bootstrap-heuristic] ${r}`)];return w([...t,...n,...s])}function xe(e,t){if(t.split(`
2
+ `).length>e.budget.maxLines||Buffer.byteLength(t,"utf8")>e.budget.maxBytes)throw new Error("Canonical project memory update exceeds its context budget; refusing to truncate existing content.")}function oe(e,t,n){const o=ve(n);if(o.length===0)return t;const s=t.includes(`\r
3
3
  `)?`\r
4
4
  `:`
5
- `,s=v(e),a=_(e),u=L(t,s),c=L(t,a);if(u!==1||c!==1||t.indexOf(a)<t.indexOf(s))throw new Error("Canonical project memory has ambiguous managed-block markers; refusing refresh.");const l=L(t,z),i=L(t,G);if(l!==i||l>1)throw new Error("Canonical project memory has ambiguous refresh-update markers; refusing refresh.");let d;if(l===0){const m=t.indexOf(a),b=t.slice(0,m),k=[z,"## Durable Refresh Updates",...o,G,""].join(n);d=`${b}${b.endsWith(n)?"":n}${k}${t.slice(m)}`}else{const m=t.indexOf(z),b=t.indexOf(G),k=t.indexOf(s),S=t.indexOf(a);if(m<k||b>S||b<m)throw new Error("Canonical refresh-update block is outside the managed block; refusing refresh.");const D=t.slice(m,b),U=new Set(D.split(/\r?\n/).map(C=>C.trim().toLowerCase())),f=o.filter(C=>!U.has(C.trim().toLowerCase()));if(f.length===0)return t;const N=t.slice(0,b);d=`${N}${N.endsWith(n)?"":n}${f.join(n)}${n}${t.slice(b)}`}return xe(e,d),d}function Ne(){return{readFile(e){try{return R(e,"utf8")}catch{return}},writeFileAtomic(e,t){j(T(e),{recursive:!0});const r=B(),o=`${e}.tmp-${r}`,n=g(e)?`${e}.bak-${r}`:void 0;try{return F(o,t,{encoding:"utf8",flag:"wx",mode:384}),n!==void 0&&M(e,n,ee.COPYFILE_EXCL),re(o,e),{backupPath:n}}catch(s){if(A(o,{force:!0}),n!==void 0&&g(n))try{M(n,e)}catch{}throw s}},join(...e){return p(...e)}}}function v(e){return`<!-- ${e.ownedBlockName}-START -->`}function _(e){return`<!-- ${e.ownedBlockName}-END -->`}function w(e){const t=new Set,r=[];for(const o of e){const n=o.trim().replace(/\s+/g," ");n.length===0||t.has(n.toLowerCase())||(t.add(n.toLowerCase()),r.push(n))}return r}function je(e){const t=new Set,r=[];for(const o of e)t.has(o.path)||(t.add(o.path),r.push(o));return r}function Me(e){switch(e.templateKind){case"neocortex-md":return"# NEOCORTEX.md Project Memory";case"claude-md":return"# CLAUDE.md Project Memory";case"agents-md":return"# AGENTS.md Project Instructions";case"gemini-md":return"# GEMINI.md Project Memory";case"copilot-instructions":return"# GitHub Copilot Repository Instructions";case"cursor-rule":return`---
5
+ `,r=$(e),a=L(e),c=A(t,r),u=A(t,a);if(c!==1||u!==1||t.indexOf(a)<t.indexOf(r))throw new Error("Canonical project memory has ambiguous managed-block markers; refusing refresh.");const l=A(t,X),i=A(t,z);if(l!==i||l>1)throw new Error("Canonical project memory has ambiguous refresh-update markers; refusing refresh.");let d;if(l===0){const m=t.indexOf(a),h=t.slice(0,m),k=[X,"## Durable Refresh Updates",...o,z,""].join(s);d=`${h}${h.endsWith(s)?"":s}${k}${t.slice(m)}`}else{const m=t.indexOf(X),h=t.indexOf(z),k=t.indexOf(r),R=t.indexOf(a);if(m<k||h>R||h<m)throw new Error("Canonical refresh-update block is outside the managed block; refusing refresh.");const _=t.slice(m,h),D=new Set(_.split(/\r?\n/).map(S=>S.trim().toLowerCase())),f=o.filter(S=>!D.has(S.trim().toLowerCase()));if(f.length===0)return t;const x=t.slice(0,h);d=`${x}${x.endsWith(s)?"":s}${f.join(s)}${s}${t.slice(h)}`}return xe(e,d),d}function Oe(e){return{readFile(t){try{return E(t,"utf8")}catch{return}},writeFileAtomic(t,n){O(I(t),{recursive:!0});const o=U(),s=`${t}.tmp-${o}`,r=g(t)?fe(t,o,e):void 0;try{return q(s,n,{encoding:"utf8",flag:"wx",mode:384}),r!==void 0&&j(t,r,V.COPYFILE_EXCL),te(s,t),{backupPath:r}}catch(a){if(N(s,{force:!0}),r!==void 0&&g(r))try{j(r,t)}catch{}throw a}},join(...t){return p(...t)}}}function $(e){return`<!-- ${e.ownedBlockName}-START -->`}function L(e){return`<!-- ${e.ownedBlockName}-END -->`}function w(e){const t=new Set,n=[];for(const o of e){const s=o.trim().replace(/\s+/g," ");s.length===0||t.has(s.toLowerCase())||(t.add(s.toLowerCase()),n.push(s))}return n}function je(e){const t=new Set,n=[];for(const o of e)t.has(o.path)||(t.add(o.path),n.push(o));return n}function Ne(e){switch(e.templateKind){case"neocortex-md":return"# NEOCORTEX.md Project Memory";case"claude-md":return"# CLAUDE.md Project Memory";case"agents-md":return"# AGENTS.md Project Instructions";case"gemini-md":return"# GEMINI.md Project Memory";case"copilot-instructions":return"# GitHub Copilot Repository Instructions";case"cursor-rule":return`---
6
6
  description: Neocortex project memory
7
7
  alwaysApply: true
8
8
  ---
9
9
 
10
- # Cursor Project Memory`}}const Ae=["Keep always-loaded memory compact: laws, active context, and references only.","Preserve human-authored instructions outside this owned block.","Prefer repository SSoT docs over duplicating architecture details here."],Ie=["Consult `docs/architecture/` before changes that affect architecture, contracts, data, security, performance, UX, or infrastructure.","Reference architecture documents by repository path, such as `docs/architecture/architecture.md`, before changing related implementation.","Summarize decisions and trade-offs in NEOCORTEX.md; do not paste complete architecture documents into memory.","Update memory for durable cross-layer changes across skills/agents, frontend, backend, API, DB, schemas, envs, DevOps, cyber security, testing/QA, observability, product, docs, and platform contracts.","Prioritize compact summaries of durable decisions, public contracts, operational risks, debts, command behavior, and repository paths; skip transient logs, raw payloads, secrets, private prompts, long documents, and duplicated canonical sources.","Keep platform memory files symlink-backed or include-backed to NEOCORTEX.md when supported."],it=["skills-agents","frontend","backend","api","db","schemas","envs","devops","cyber-security","testing-qa","observability","product-business","docs-architecture","platform-memory","command-behavior","generic"],Le=360,ue={feature:"Features",rule:"Rules/Policies",flag:"Flags",route:"Routes",api:"APIs/Contracts","db-schema":"DB/Schema",architecture:"Architecture",debt:"Debts",decision:"Decisions",generic:"General Updates"},_e=/\b(private|proprietary|server[- ]only|system)\s+prompt\b|\b(api[-_ ]?key|license[-_ ]?key|password|authorization|bearer|token|secret)\s*[:=]|\b(ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[baprs]-[A-Za-z0-9-]+)\b|\b(customer|cliente)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s*[:=]|\braw\s+payload\b/i;function De(e){const t=e.toLowerCase();return/\b(project memory|canonical memory|memory heuristic|neocortex\.md|\*update-memory)\b/.test(t)?"decision":/\b(feature|capability|funcionalidade|release)\b/.test(t)?"feature":/\b(rule|policy|guardrail|regra|lei|must|never)\b/.test(t)?"rule":/\b(flag|feature[- ]?flag|toggle|env var|environment variable)\b/.test(t)?"flag":/\b(api|contract|schema contract|graphql|rest|rpc|webhook)\b/.test(t)?"api":/\b(db|database|schema|migration|table|column|prisma|sql)\b/.test(t)?"db-schema":/\b(decision|decisão|decisao|accepted|rejected|trade[- ]?off)\b/.test(t)?"decision":/\b(route|endpoint route|url path|pathname)\b|\/(api|admin|portal|v\d+)\//.test(t)?"route":/\b(architecture|arquitetura|adr|topology|infra|boundary)\b/.test(t)?"architecture":/\b(debt|follow[- ]?up|todo|tech[- ]?debt|dívida|divida)\b/.test(t)?"debt":"generic"}function Ue(e){const t=e.toLowerCase();return/\b(neocortex\.md|project memory|canonical memory|memory wrapper|symlink|owned block|memory heuristic)\b/.test(t)?"platform-memory":/\b(command|cli|\*update-memory|\*create-epic|\*arch-plan|workflow behavior)\b/.test(t)?"command-behavior":/\b(skill|agent|subagent|orchestrator|opencode|codex|claude|gemini|cursor)\b/.test(t)?"skills-agents":/\b(frontend|ui|ux|react|component|design[- ]?system|css|accessibility|a11y)\b/.test(t)?"frontend":/\b(backend|server|service|worker|job|queue)\b/.test(t)?"backend":/\b(api|endpoint|rest|graphql|rpc|webhook|contract)\b/.test(t)?"api":/\b(db|database|table|column|migration|sql|prisma)\b/.test(t)?"db":/\b(schema|schemas|zod|json schema|protobuf|openapi)\b/.test(t)?"schemas":/\b(env|environment|\.env\.example|config|configuration|feature[- ]?flag)\b/.test(t)?"envs":/\b(devops|deploy|deployment|ci|cd|docker|container|kubernetes|infra|terraform|rollback)\b/.test(t)?"devops":/\b(security|cyber|auth|authorization|permission|compliance|vulnerability|secret|token redaction)\b/.test(t)?"cyber-security":/\b(test|testing|qa|e2e|unit|integration|snapshot|property[- ]?based|flaky)\b/.test(t)?"testing-qa":/\b(observability|metric|metrics|log|logging|trace|tracing|alert|monitoring|slo)\b/.test(t)?"observability":/\b(product|business|user journey|onboarding|pricing|tenant|customer-facing)\b/.test(t)?"product-business":/\b(docs|documentation|architecture|arquitetura|adr|runbook|decision record)\b/.test(t)?"docs-architecture":"generic"}function de(e){const t=e.trim().replace(/\s+/g," ");if(Buffer.byteLength(t,"utf8")<=Le)return t;const r=t.match(/(?:^|\s)([\w.-]+(?:\/[\w.@-]+)+(?:\.[A-Za-z0-9]+)?)/)?.[1],o=t.slice(0,220).replace(/\s+\S*$/,"").trim();return r?`${o}\u2026 See ${r} for details.`:`${o}\u2026 Details omitted from always-loaded memory; keep source content in repository docs.`}function Be(e){h(e);const t=De(e),r=Ue(e);return{kind:t,layer:r,sectionTitle:ue[t],summary:de(e),reasonCode:`memory_update_${t.replace("-","_")}`}}function H(e){const t=new Set,r=[];for(const o of e){const n=Be(o),s=`${n.kind}:${n.summary.toLowerCase()}`;t.has(s)||(t.add(s),r.push(n))}return r}function h(e){if(_e.test(e))throw new Error("Project memory input violates IP boundary guardrails.")}function le(e,t){const r=(e??"").split(`
10
+ # Cursor Project Memory`}}const Me=["Keep always-loaded memory compact: laws, active context, and references only.","Preserve human-authored instructions outside this owned block.","Prefer repository SSoT docs over duplicating architecture details here."],Ie=["Consult `docs/architecture/` before changes that affect architecture, contracts, data, security, performance, UX, or infrastructure.","Reference architecture documents by repository path, such as `docs/architecture/architecture.md`, before changing related implementation.","Summarize decisions and trade-offs in NEOCORTEX.md; do not paste complete architecture documents into memory.","Update memory for durable cross-layer changes across skills/agents, frontend, backend, API, DB, schemas, envs, DevOps, cyber security, testing/QA, observability, product, docs, and platform contracts.","Prioritize compact summaries of durable decisions, public contracts, operational risks, debts, command behavior, and repository paths; skip transient logs, raw payloads, secrets, private prompts, long documents, and duplicated canonical sources.","Keep platform memory files symlink-backed or include-backed to NEOCORTEX.md when supported."],it=["skills-agents","frontend","backend","api","db","schemas","envs","devops","cyber-security","testing-qa","observability","product-business","docs-architecture","platform-memory","command-behavior","generic"],Ae=360,se={feature:"Features",rule:"Rules/Policies",flag:"Flags",route:"Routes",api:"APIs/Contracts","db-schema":"DB/Schema",architecture:"Architecture",debt:"Debts",decision:"Decisions",generic:"General Updates"},Le=/\b(private|proprietary|server[- ]only|system)\s+prompt\b|\b(api[-_ ]?key|license[-_ ]?key|password|authorization|bearer|token|secret)\s*[:=]|\b(ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[baprs]-[A-Za-z0-9-]+)\b|\b(customer|cliente)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s*[:=]|\braw\s+payload\b/i;function _e(e){const t=e.toLowerCase();return/\b(project memory|canonical memory|memory heuristic|neocortex\.md|\*update-memory)\b/.test(t)?"decision":/\b(feature|capability|funcionalidade|release)\b/.test(t)?"feature":/\b(rule|policy|guardrail|regra|lei|must|never)\b/.test(t)?"rule":/\b(flag|feature[- ]?flag|toggle|env var|environment variable)\b/.test(t)?"flag":/\b(api|contract|schema contract|graphql|rest|rpc|webhook)\b/.test(t)?"api":/\b(db|database|schema|migration|table|column|prisma|sql)\b/.test(t)?"db-schema":/\b(decision|decisão|decisao|accepted|rejected|trade[- ]?off)\b/.test(t)?"decision":/\b(route|endpoint route|url path|pathname)\b|\/(api|admin|portal|v\d+)\//.test(t)?"route":/\b(architecture|arquitetura|adr|topology|infra|boundary)\b/.test(t)?"architecture":/\b(debt|follow[- ]?up|todo|tech[- ]?debt|dívida|divida)\b/.test(t)?"debt":"generic"}function De(e){const t=e.toLowerCase();return/\b(neocortex\.md|project memory|canonical memory|memory wrapper|symlink|owned block|memory heuristic)\b/.test(t)?"platform-memory":/\b(command|cli|\*update-memory|\*create-epic|\*arch-plan|workflow behavior)\b/.test(t)?"command-behavior":/\b(skill|agent|subagent|orchestrator|opencode|codex|claude|gemini|cursor)\b/.test(t)?"skills-agents":/\b(frontend|ui|ux|react|component|design[- ]?system|css|accessibility|a11y)\b/.test(t)?"frontend":/\b(backend|server|service|worker|job|queue)\b/.test(t)?"backend":/\b(api|endpoint|rest|graphql|rpc|webhook|contract)\b/.test(t)?"api":/\b(db|database|table|column|migration|sql|prisma)\b/.test(t)?"db":/\b(schema|schemas|zod|json schema|protobuf|openapi)\b/.test(t)?"schemas":/\b(env|environment|\.env\.example|config|configuration|feature[- ]?flag)\b/.test(t)?"envs":/\b(devops|deploy|deployment|ci|cd|docker|container|kubernetes|infra|terraform|rollback)\b/.test(t)?"devops":/\b(security|cyber|auth|authorization|permission|compliance|vulnerability|secret|token redaction)\b/.test(t)?"cyber-security":/\b(test|testing|qa|e2e|unit|integration|snapshot|property[- ]?based|flaky)\b/.test(t)?"testing-qa":/\b(observability|metric|metrics|log|logging|trace|tracing|alert|monitoring|slo)\b/.test(t)?"observability":/\b(product|business|user journey|onboarding|pricing|tenant|customer-facing)\b/.test(t)?"product-business":/\b(docs|documentation|architecture|arquitetura|adr|runbook|decision record)\b/.test(t)?"docs-architecture":"generic"}function ae(e){const t=e.trim().replace(/\s+/g," ");if(Buffer.byteLength(t,"utf8")<=Ae)return t;const n=t.match(/(?:^|\s)([\w.-]+(?:\/[\w.@-]+)+(?:\.[A-Za-z0-9]+)?)/)?.[1],o=t.slice(0,220).replace(/\s+\S*$/,"").trim();return n?`${o}\u2026 See ${n} for details.`:`${o}\u2026 Details omitted from always-loaded memory; keep source content in repository docs.`}function Ue(e){y(e);const t=_e(e),n=De(e);return{kind:t,layer:n,sectionTitle:se[t],summary:ae(e),reasonCode:`memory_update_${t.replace("-","_")}`}}function G(e){const t=new Set,n=[];for(const o of e){const s=Ue(o),r=`${s.kind}:${s.summary.toLowerCase()}`;t.has(r)||(t.add(r),n.push(s))}return n}function y(e){if(Le.test(e))throw new Error("Project memory input violates IP boundary guardrails.")}function ie(e,t){const n=(e??"").split(`
11
11
  `),o=t.split(`
12
- `),n=[],s=Math.max(r.length,o.length);for(let u=0;u<s;u++){const c=r[u],l=o[u];if(c!==l&&(c!==void 0&&n.push(`- ${c}`),l!==void 0&&n.push(`+ ${l}`),n.length>=80)){n.push("\u2026 diff truncated; inspect repository diff for full context.");break}}const a=n.join(`
13
- `);return h(a),a}function Y(e){h(e.path),h(e.title),h(e.purpose),h(e.suggestedUsage)}function me(e,t,r){e.forEach(h),t.forEach(Y),r?.universalLaws?.forEach(h),r?.businessContext?.forEach(h),r?.activeContext?.forEach(h),r?.repositoryMap?.forEach(h),r?.environmentPractices?.forEach(h),r?.platformMemoryContract?.forEach(h),r?.maintenanceRules?.forEach(h),r?.heuristics?.forEach(h),r?.importantReferences?.forEach(Y),r?.architectureReferences?.forEach(Y)}function fe(e){return[Me(e),"","This file contains compact, always-loaded project memory. Keep detailed architecture in referenced docs.",""].join(`
14
- `)}function pe(e,t,r,o){me(t,r,o);const n=w([...Ae,...o?.universalLaws??[]]),s=w([...o?.activeContext??[],...t.map(de)]),a=H(t),u=w(o?.businessContext??["Product/business context was not explicitly documented during bootstrap; treat conclusions as repository-inferred until a human updates this section."]),c=w(o?.repositoryMap??["Source, tests, package/build files, docs, CI, and runtime manifests are the permitted bootstrap sources for repository orientation."]),l=w(o?.environmentPractices??["Use `.env.example` for configuration shape only; do not read real environment files or credential-bearing files into always-loaded memory."]),i=w(o?.platformMemoryContract??["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Platform wrapper/frontmatter must be preserved via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."]),d=w(o?.maintenanceRules??["Keep NEOCORTEX.md deterministic, compact, objective, and direct; store only summaries, indexes, and links to detailed docs.","Do not copy protected prompt bodies, proprietary wrappers, server-side internals, customer data, license keys, or long document bodies into always-loaded memory."]),m=je([...o?.importantReferences??[],...o?.architectureReferences??[],...r]),b=w([...Ie,...o?.heuristics??[]]),k=n.map(f=>`- ${f}`),S=s.length>0?s.map(f=>`- ${f}`):["- No active project notes recorded."],D=m.length>0?ve(m):"No architecture references discovered.",U=a.length>0?Object.entries(ue).flatMap(([f,N])=>{const C=a.filter(P=>P.kind===f);return C.length>0?[`### ${N}`,...C.map(P=>`- [${P.reasonCode}] ${P.summary} (layer: ${P.layer})`)]:[]}):["- No durable change feedback recorded."];return[v(e),"## Universal Project Laws",...k,"","## Business/Product Context",...u.map(f=>`- ${f}`),"","## Active Context",...S,"","## Durable Change Feedback",...U,"","## Architecture References",D,"","## Repository Map",...c.map(f=>`- ${f}`),"","## Environment/Container/Production/Security/Dev Practices",...l.map(f=>`- ${f}`),"","## Platform Memory Contract",...i.map(f=>`- ${f}`),`- NEOCORTEX.md is the canonical project memory source for every platform target; run \`${e.bidirectionalReference.feedbackTrigger}\` when durable context discovered in a platform wrapper should be fed back into canonical memory.`,"","## Maintenance Rules",...d.map(f=>`- ${f}`),"","## Architecture Heuristics",...b.map(f=>`- ${f}`),_(e)].join(`
15
- `)}const ye=["docs/architecture","docs/arquitetura-software"],qe=["README.md","readme.md","architecture.md","docs/architecture.md"],We=["package.json","pnpm-lock.yaml","package-lock.json","yarn.lock","tsconfig.json","vite.config.ts","turbo.json"],Fe=["Dockerfile","docker-compose.yml","compose.yml",".env.example","fly.toml"],Xe=["AGENTS.md","CLAUDE.md","GEMINI.md",".opencode/AGENTS.md",".cursor/rules/neocortex.mdc"];function he(e,t,r=24e3){const o=p(e,t);try{if(!g(o)||$(o).isDirectory())return;const n=R(o,"utf8");return n.length<=r?n:n.slice(0,r)}catch{return}}function K(e,t){j(T(e),{recursive:!0});const r=B(),o=`${e}.tmp-${r}`,n=g(e)?`${e}.bak-${r}`:void 0;try{return F(o,t,{encoding:"utf8",flag:"wx",mode:384}),n!==void 0&&M(e,n,ee.COPYFILE_EXCL),re(o,e),n}catch(s){if(A(o,{force:!0}),n!==void 0&&g(n))try{M(n,e)}catch{}throw s}}function E(e){throw new Error(`project-memory-path-${e}`)}function be(e){return typeof e=="string"&&e.length>0&&!e.startsWith("~")&&!e.includes("\\")&&!e.includes("\0")&&!oe(e)&&!Te.isAbsolute(e)&&!/^[a-zA-Z]:/.test(e)&&!e.split("/").some(t=>t===""||t==="."||t==="..")}function Z(e,t){let r;try{r=Ce(e)}catch{E("out-of-scope")}const o=p(r,y);for(const n of t){be(n)||E("invalid");const s=ae(r,n),a=se(r,s);(a===""||a===".."||a.startsWith(`..${Pe}`)||oe(a))&&E("out-of-scope");const u=n.split("/");for(let c=0;c<u.length;c++){const l=p(r,...u.slice(0,c+1));let i;try{i=$(l)}catch(m){if(m.code==="ENOENT")continue;E("out-of-scope")}if(!i.isSymbolicLink())continue;(c!==u.length-1||n===y)&&E("out-of-scope");let d;try{d=q(l)}catch{E("out-of-scope")}ae(T(l),d)!==o&&E("out-of-scope")}}}function J(e){return Array.from(new Set(H(e).map(t=>t.reasonCode)))}function O(e,t){try{return g(p(e,t))}catch{return!1}}function ze(e,t){try{return te(p(e,t),{withFileTypes:!0}).filter(r=>!r.name.startsWith(".")&&!r.name.toLowerCase().includes("secret")).sort((r,o)=>r.name.localeCompare(o.name)).slice(0,8).map(r=>`${t}/${r.name}${r.isDirectory()?"/":""}`)}catch{return[]}}function ge(e,t,r=16){try{const o=te(p(e,t),{withFileTypes:!0}).filter(s=>!s.name.startsWith(".")&&!s.name.startsWith("_")).sort((s,a)=>s.name.localeCompare(a.name)),n=[];for(const s of o){const a=`${t}/${s.name}`;if(s.isDirectory()?n.push(...ge(e,a,r-n.length)):/\.(md|markdown)$/i.test(s.name)&&n.push(a),n.length>=r)break}return n}catch{return[]}}function Ge(e,t){const r=t.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim();return r?r.replace(/[`*_#]/g,""):e.split("/").pop()?.replace(/\.(md|markdown)$/i,"").replace(/[-_]+/g," ")??e}function He(e,t){const r=/\b(stale|deprecated|outdated|incerto|uncertain)\b/i.test(`${e}
16
- ${t.slice(0,2e3)}`),o=t.replace(/^---[\s\S]*?---\s*/,"").split(/\n{2,}/).map(s=>s.replace(/^#+\s+.+$/gm,"").replace(/[`*_>#]/g,"").replace(/\s+/g," ").trim()).find(s=>s.length>0&&!s.startsWith("|"));return`${r?"[stale/uncertain evidence] ":""}${(o??"Architecture reference for this project.").slice(0,180)}`}function Ye(e){const t=e.toLowerCase();return/deploy|infra|docker|production|runbook/.test(t)?"Use before changing deployment, runtime, containers, or production operations.":/security|auth|compliance/.test(t)?"Use before changing auth, compliance, or security-sensitive behavior.":/api|contract|state|schema/.test(t)?"Use before changing contracts, APIs, schemas, or persisted state.":"Use before implementation in this area; verify freshness when marked stale or uncertain."}function ke(e){const t=We.filter(i=>O(e,i)),r=Fe.filter(i=>O(e,i)),o=Xe.filter(i=>O(e,i)),n=["packages","src","apps","tests","__tests__"].filter(i=>O(e,i)),a=[...ye.flatMap(i=>ge(e,i)),...qe.filter(i=>O(e,i))].slice(0,24).flatMap(i=>{const d=he(e,i,48e3);return d?[{path:i,title:Ge(i,d),purpose:He(i,d),suggestedUsage:Ye(i),source:ye.some(m=>i.startsWith(`${m}/`))?"architecture-root":"fallback-file"}]:[]}),u=he(e,"package.json"),c=u?.match(/"name"\s*:\s*"([^"]+)"/)?.[1],l=[...u?.matchAll(/"(test|build|lint|typecheck|dev)"\s*:/g)??[]].map(i=>i[1]);return{universalLaws:["Bootstrap canonical memory before creating or repairing platform memory wrappers when NEOCORTEX.md is absent.","Use only permitted repository sources for bootstrap: package/build files, architecture docs, README/deploy docs, .env.example, runtime manifests, CI, source/test layout, and platform memory wrappers."],businessContext:[c?`Repository package name: ${c}.`:"Repository product name was not declared in package metadata.","Business/product conclusions are bootstrap-inferred and must be refined from canonical docs or human input."],activeContext:[`Bootstrap scanned ${t.length} package/build files, ${a.length} architecture/readme docs, ${r.length} runtime/config templates, and ${o.length} platform memory wrappers.`,l.length>0?`Detected quality scripts: ${l.sort().join(", ")}.`:"No standard quality scripts were detected in package metadata."],repositoryMap:[t.length>0?`Package/build files: ${t.join(", ")}.`:"No package/build files detected in permitted bootstrap set.",n.length>0?`Source/test roots: ${n.flatMap(i=>ze(e,i)).slice(0,16).join(", ")}.`:"Source/test roots were not detected in standard locations.",o.length>0?`Platform memory/wrappers: ${o.join(", ")}.`:"No platform memory wrappers detected before bootstrap."],environmentPractices:[r.length>0?`Runtime/config templates: ${r.join(", ")}.`:"No Docker/compose/.env.example/runtime manifest detected in permitted bootstrap set.","Read `.env.example` only for configuration shape; never ingest real .env files, credentials, customer data, or license keys into memory.","Run repository quality scripts before commit and keep CI/deploy evidence referenced by path or URL rather than copied verbatim."],platformMemoryContract:["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Preserve wrappers/frontmatter via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."],maintenanceRules:["Generated memory must be deterministic, objective, direct, compact, and inside the target always-loaded context budget.","Cite long architecture docs by path with usage guidance; mark stale or uncertain docs when repository evidence indicates that status.","Do not copy protected prompt bodies, proprietary wrappers, server internals, secrets, customer data, license keys, or complete long documents."],architectureReferences:a,heuristics:["Before processing a story, consult the cited Architecture References whose path or suggested usage intersects the change.","When a referenced doc is marked stale/uncertain, validate against current package/runtime/source evidence before relying on it."]}}function V(e,t,r){const o=v(t),n=_(t),s=e.indexOf(o),a=e.indexOf(n);if(s>=0&&a>=s){const c=a+n.length;return`${e.slice(0,s)}${r}${e.slice(c)}`}const u=e.endsWith(`
12
+ `),s=[],r=Math.max(n.length,o.length);for(let c=0;c<r;c++){const u=n[c],l=o[c];if(u!==l&&(u!==void 0&&s.push(`- ${u}`),l!==void 0&&s.push(`+ ${l}`),s.length>=80)){s.push("\u2026 diff truncated; inspect repository diff for full context.");break}}const a=s.join(`
13
+ `);return y(a),a}function H(e){y(e.path),y(e.title),y(e.purpose),y(e.suggestedUsage)}function ce(e,t,n){e.forEach(y),t.forEach(H),n?.universalLaws?.forEach(y),n?.businessContext?.forEach(y),n?.activeContext?.forEach(y),n?.repositoryMap?.forEach(y),n?.environmentPractices?.forEach(y),n?.platformMemoryContract?.forEach(y),n?.maintenanceRules?.forEach(y),n?.heuristics?.forEach(y),n?.importantReferences?.forEach(H),n?.architectureReferences?.forEach(H)}function ue(e){return[Ne(e),"","This file contains compact, always-loaded project memory. Keep detailed architecture in referenced docs.",""].join(`
14
+ `)}function de(e,t,n,o){ce(t,n,o);const s=w([...Me,...o?.universalLaws??[]]),r=w([...o?.activeContext??[],...t.map(ae)]),a=G(t),c=w(o?.businessContext??["Product/business context was not explicitly documented during bootstrap; treat conclusions as repository-inferred until a human updates this section."]),u=w(o?.repositoryMap??["Source, tests, package/build files, docs, CI, and runtime manifests are the permitted bootstrap sources for repository orientation."]),l=w(o?.environmentPractices??["Use `.env.example` for configuration shape only; do not read real environment files or credential-bearing files into always-loaded memory."]),i=w(o?.platformMemoryContract??["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Platform wrapper/frontmatter must be preserved via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."]),d=w(o?.maintenanceRules??["Keep NEOCORTEX.md deterministic, compact, objective, and direct; store only summaries, indexes, and links to detailed docs.","Do not copy protected prompt bodies, proprietary wrappers, server-side internals, customer data, license keys, or long document bodies into always-loaded memory."]),m=je([...o?.importantReferences??[],...o?.architectureReferences??[],...n]),h=w([...Ie,...o?.heuristics??[]]),k=s.map(f=>`- ${f}`),R=r.length>0?r.map(f=>`- ${f}`):["- No active project notes recorded."],_=m.length>0?Pe(m):"No architecture references discovered.",D=a.length>0?Object.entries(se).flatMap(([f,x])=>{const S=a.filter(P=>P.kind===f);return S.length>0?[`### ${x}`,...S.map(P=>`- [${P.reasonCode}] ${P.summary} (layer: ${P.layer})`)]:[]}):["- No durable change feedback recorded."];return[$(e),"## Universal Project Laws",...k,"","## Business/Product Context",...c.map(f=>`- ${f}`),"","## Active Context",...R,"","## Durable Change Feedback",...D,"","## Architecture References",_,"","## Repository Map",...u.map(f=>`- ${f}`),"","## Environment/Container/Production/Security/Dev Practices",...l.map(f=>`- ${f}`),"","## Platform Memory Contract",...i.map(f=>`- ${f}`),`- NEOCORTEX.md is the canonical project memory source for every platform target; run \`${e.bidirectionalReference.feedbackTrigger}\` when durable context discovered in a platform wrapper should be fed back into canonical memory.`,"","## Maintenance Rules",...d.map(f=>`- ${f}`),"","## Architecture Heuristics",...h.map(f=>`- ${f}`),L(e)].join(`
15
+ `)}const le=["docs/architecture","docs/arquitetura-software"],Be=["README.md","readme.md","architecture.md","docs/architecture.md"],qe=["package.json","pnpm-lock.yaml","package-lock.json","yarn.lock","tsconfig.json","vite.config.ts","turbo.json"],We=["Dockerfile","docker-compose.yml","compose.yml",".env.example","fly.toml"],Fe=["AGENTS.md","CLAUDE.md","GEMINI.md",".opencode/AGENTS.md",".cursor/rules/neocortex.mdc"];function me(e,t,n=24e3){const o=p(e,t);try{if(!g(o)||C(o).isDirectory())return;const s=E(o,"utf8");return s.length<=n?s:s.slice(0,n)}catch{return}}function fe(e,t,n){if(!n)return`${e}.bak-${t}`;const o=Ce(n),s=C(o);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&63)!==0||we(o)!==o)throw new Error("project-memory-backup-directory-unsafe");return p(o,`${Re(e)}.bak-${t}`)}function Y(e,t,n){O(I(e),{recursive:!0});const o=U(),s=`${e}.tmp-${o}`,r=g(e)?fe(e,o,n):void 0;try{return q(s,t,{encoding:"utf8",flag:"wx",mode:384}),r!==void 0&&j(e,r,V.COPYFILE_EXCL),te(s,e),r}catch(a){if(N(s,{force:!0}),r!==void 0&&g(r))try{j(r,e)}catch{}throw a}}function K(e){return Array.from(new Set(G(e).map(t=>t.reasonCode)))}function T(e,t){try{return g(p(e,t))}catch{return!1}}function Xe(e,t){try{return Q(p(e,t),{withFileTypes:!0}).filter(n=>!n.name.startsWith(".")&&!n.name.toLowerCase().includes("secret")).sort((n,o)=>n.name.localeCompare(o.name)).slice(0,8).map(n=>`${t}/${n.name}${n.isDirectory()?"/":""}`)}catch{return[]}}function pe(e,t,n=16){try{const o=Q(p(e,t),{withFileTypes:!0}).filter(r=>!r.name.startsWith(".")&&!r.name.startsWith("_")).sort((r,a)=>r.name.localeCompare(a.name)),s=[];for(const r of o){const a=`${t}/${r.name}`;if(r.isDirectory()?s.push(...pe(e,a,n-s.length)):/\.(md|markdown)$/i.test(r.name)&&s.push(a),s.length>=n)break}return s}catch{return[]}}function ze(e,t){const n=t.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim();return n?n.replace(/[`*_#]/g,""):e.split("/").pop()?.replace(/\.(md|markdown)$/i,"").replace(/[-_]+/g," ")??e}function Ge(e,t){const n=/\b(stale|deprecated|outdated|incerto|uncertain)\b/i.test(`${e}
16
+ ${t.slice(0,2e3)}`),o=t.replace(/^---[\s\S]*?---\s*/,"").split(/\n{2,}/).map(r=>r.replace(/^#+\s+.+$/gm,"").replace(/[`*_>#]/g,"").replace(/\s+/g," ").trim()).find(r=>r.length>0&&!r.startsWith("|"));return`${n?"[stale/uncertain evidence] ":""}${(o??"Architecture reference for this project.").slice(0,180)}`}function He(e){const t=e.toLowerCase();return/deploy|infra|docker|production|runbook/.test(t)?"Use before changing deployment, runtime, containers, or production operations.":/security|auth|compliance/.test(t)?"Use before changing auth, compliance, or security-sensitive behavior.":/api|contract|state|schema/.test(t)?"Use before changing contracts, APIs, schemas, or persisted state.":"Use before implementation in this area; verify freshness when marked stale or uncertain."}function ye(e){const t=qe.filter(i=>T(e,i)),n=We.filter(i=>T(e,i)),o=Fe.filter(i=>T(e,i)),s=["packages","src","apps","tests","__tests__"].filter(i=>T(e,i)),a=[...le.flatMap(i=>pe(e,i)),...Be.filter(i=>T(e,i))].slice(0,24).flatMap(i=>{const d=me(e,i,48e3);return d?[{path:i,title:ze(i,d),purpose:Ge(i,d),suggestedUsage:He(i),source:le.some(m=>i.startsWith(`${m}/`))?"architecture-root":"fallback-file"}]:[]}),c=me(e,"package.json"),u=c?.match(/"name"\s*:\s*"([^"]+)"/)?.[1],l=[...c?.matchAll(/"(test|build|lint|typecheck|dev)"\s*:/g)??[]].map(i=>i[1]);return{universalLaws:["Bootstrap canonical memory before creating or repairing platform memory wrappers when NEOCORTEX.md is absent.","Use only permitted repository sources for bootstrap: package/build files, architecture docs, README/deploy docs, .env.example, runtime manifests, CI, source/test layout, and platform memory wrappers."],businessContext:[u?`Repository package name: ${u}.`:"Repository product name was not declared in package metadata.","Business/product conclusions are bootstrap-inferred and must be refined from canonical docs or human input."],activeContext:[`Bootstrap scanned ${t.length} package/build files, ${a.length} architecture/readme docs, ${n.length} runtime/config templates, and ${o.length} platform memory wrappers.`,l.length>0?`Detected quality scripts: ${l.sort().join(", ")}.`:"No standard quality scripts were detected in package metadata."],repositoryMap:[t.length>0?`Package/build files: ${t.join(", ")}.`:"No package/build files detected in permitted bootstrap set.",s.length>0?`Source/test roots: ${s.flatMap(i=>Xe(e,i)).slice(0,16).join(", ")}.`:"Source/test roots were not detected in standard locations.",o.length>0?`Platform memory/wrappers: ${o.join(", ")}.`:"No platform memory wrappers detected before bootstrap."],environmentPractices:[n.length>0?`Runtime/config templates: ${n.join(", ")}.`:"No Docker/compose/.env.example/runtime manifest detected in permitted bootstrap set.","Read `.env.example` only for configuration shape; never ingest real .env files, credentials, customer data, or license keys into memory.","Run repository quality scripts before commit and keep CI/deploy evidence referenced by path or URL rather than copied verbatim."],platformMemoryContract:["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Preserve wrappers/frontmatter via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."],maintenanceRules:["Generated memory must be deterministic, objective, direct, compact, and inside the target always-loaded context budget.","Cite long architecture docs by path with usage guidance; mark stale or uncertain docs when repository evidence indicates that status.","Do not copy protected prompt bodies, proprietary wrappers, server internals, secrets, customer data, license keys, or complete long documents."],architectureReferences:a,heuristics:["Before processing a story, consult the cited Architecture References whose path or suggested usage intersects the change.","When a referenced doc is marked stale/uncertain, validate against current package/runtime/source evidence before relying on it."]}}function J(e,t,n){const o=$(t),s=L(t),r=e.indexOf(o),a=e.indexOf(s);if(r>=0&&a>=r){const u=a+s.length;return`${e.slice(0,r)}${n}${e.slice(u)}`}const c=e.endsWith(`
17
17
  `)?`
18
18
  `:`
19
19
 
20
- `;return`${e}${u}${r}
21
- `}function Ke(e){return e.endsWith(".mdc")?`---
20
+ `;return`${e}${c}${n}
21
+ `}function Ye(e){return e.endsWith(".mdc")?`---
22
22
  description: Neocortex project memory
23
23
  alwaysApply: true
24
24
  ---
@@ -32,9 +32,9 @@ name: neocortex
32
32
  description: Neocortex project memory wrapper
33
33
  ---
34
34
 
35
- `:""}function we(e,t){const r=T(p(e,t)),o=p(e,y),n=se(r,o);return n.length>0?n:y}function x(e,t){return!!(e.targetId==="canonical"||e.requiresWrapperPreservation||e.linkRequirement.requiresWrapperPreservation||e.linkRequirement.wrapperAllowed||t==="AGENTS.md"||t.includes("/agents/")||t.includes("/skills/")||t.endsWith(".toml")||t.endsWith(".mdc")||t.endsWith(".agent.md")||t.endsWith(".instructions.md"))}function Ze(e){return e.linkRequirement.symlinkBacked&&e.linkRequirement.semanticFileRequired}function Q(e){return/EPERM|EACCES|operation not permitted|permission/i.test(e)?"EPERM: symlink permission denied":/ENOSYS|ENOTSUP|EOPNOTSUPP|not supported/i.test(e)?"symlink filesystem unsupported":"symlink capability unavailable"}function Ee(e,t,r,o,n=!1){if(o!==void 0)return o;const s=Ze(t);if(!s)return{os:I(),supported:!1,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:`target policy ${t.linkRequirement.policy} does not allow semantic symlink orchestration`};if(n)return{os:I(),supported:!0,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:"dry-run does not probe filesystem symlink support"};const a=p(e,".neocortex","tmp"),u=B(),c=p(a,`symlink-capability-source-${u}`),l=p(a,`symlink-capability-link-${u}`);try{j(a,{recursive:!0}),F(c,"probe",{encoding:"utf8",flag:"wx",mode:384}),W(c,l);const i=$(l).isSymbolicLink()&&$e(l).isFile();return{os:I(),supported:i,permission:i?"ok":"unknown",filesystem:i?"supports-symlink":"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:i?void 0:"filesystem probe did not create a resolvable symbolic link"}}catch(i){const d=i instanceof Error?i.message:String(i),m=/EPERM|EACCES|operation not permitted|permission/i.test(d);return{os:I(),supported:!1,permission:m?"denied":"unknown",filesystem:"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:Q(d)}}finally{A(l,{force:!0}),A(c,{force:!0})}}function Je(e,t,r,o){const n=we(o,t),s=r??`${Ke(t)}# ${e.platformName} Neocortex Memory Wrapper
35
+ `:""}function be(e,t){const n=I(p(e,t)),o=p(e,b),s=Se(n,o);return s.length>0?s:b}function v(e,t){return!!(e.targetId==="canonical"||e.requiresWrapperPreservation||e.linkRequirement.requiresWrapperPreservation||e.linkRequirement.wrapperAllowed||t==="AGENTS.md"||t.includes("/agents/")||t.includes("/skills/")||t.endsWith(".toml")||t.endsWith(".mdc")||t.endsWith(".agent.md")||t.endsWith(".instructions.md"))}function Ke(e){return e.linkRequirement.symlinkBacked&&e.linkRequirement.semanticFileRequired}function Z(e){return/EPERM|EACCES|operation not permitted|permission/i.test(e)?"EPERM: symlink permission denied":/ENOSYS|ENOTSUP|EOPNOTSUPP|not supported/i.test(e)?"symlink filesystem unsupported":"symlink capability unavailable"}function he(e,t,n,o,s=!1){if(o!==void 0)return o;const r=Ke(t);if(!r)return{os:M(),supported:!1,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:v(t,n),reason:`target policy ${t.linkRequirement.policy} does not allow semantic symlink orchestration`};if(s)return{os:M(),supported:!0,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:v(t,n),reason:"dry-run does not probe filesystem symlink support"};const a=p(e,".neocortex","tmp"),c=U(),u=p(a,`symlink-capability-source-${c}`),l=p(a,`symlink-capability-link-${c}`);try{O(a,{recursive:!0}),q(u,"probe",{encoding:"utf8",flag:"wx",mode:384}),B(u,l);const i=C(l).isSymbolicLink()&&Ee(l).isFile();return{os:M(),supported:i,permission:i?"ok":"unknown",filesystem:i?"supports-symlink":"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:v(t,n),reason:i?void 0:"filesystem probe did not create a resolvable symbolic link"}}catch(i){const d=i instanceof Error?i.message:String(i),m=/EPERM|EACCES|operation not permitted|permission/i.test(d);return{os:M(),supported:!1,permission:m?"denied":"unknown",filesystem:"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:v(t,n),reason:Z(d)}}finally{N(l,{force:!0}),N(u,{force:!0})}}function Je(e,t,n,o){const s=be(o,t),r=n??`${Ye(t)}# ${e.platformName} Neocortex Memory Wrapper
36
36
 
37
- `,a=[v(e),"## Canonical Project Memory Source","",`This platform wrapper preserves host-specific frontmatter/instructions while resolving project memory to \`${n}\`.`,"",`- Canonical source: \`${y}\``,`- Symlink-backed/source-of-truth file: \`${n}\``,`- Feedback loop: read \`${n}\` for shared context and run \`${e.bidirectionalReference.feedbackTrigger}\` when durable platform findings should update \`${y}\`.`,"- Human-authored content outside this managed block is preserved byte-for-byte.",_(e)].join(`
38
- `);return V(s,e,a)}function Re(e,t,r,o,n,s=!1){const a=p(e,t),u=Q(n),l=`${["[NEOCORTEX COMPATIBILITY REMEDIATION]","Materialized project memory fallback because semantic symlink orchestration failed.","This is not product mode; repair host permissions/filesystem support and restore the symlink to NEOCORTEX.md.","WARNING: materialized fallback is remediation debt, not a silent mode; run *update-memory for durable context and repair this file back to canonical NEOCORTEX.md resolution.",`Fallback reason: ${u}`,""].join(`
39
- `)}${r}`,d=(g(a)?R(a,"utf8"):void 0)!==l;return d&&!s&&(g(a)&&$(a).isSymbolicLink()&&ne(a),K(a,l)),{filePath:a,relativeFile:t,changed:d,content:l,mode:"compatibility-materialized-fallback",canonicalSource:y,symlinkCapability:o,fallbackReason:u,remediationDebt:`Repair ${t} so it is a symlink to ${y}; fallback is compatibility remediation only.`}}function Ve(e,t,r,o,n,s=!1){const a=p(e,t),u=we(e,t);s||j(T(a),{recursive:!0});const c=Ee(e,r,t,n,s);if(!c.supported)return Re(e,t,o,c,c.reason??"symlink capability detection reported unsupported host",s);if(s){let i=!0;try{i=!(g(a)&&$(a).isSymbolicLink()&&q(a)===u)}catch{i=!0}return{filePath:a,relativeFile:t,changed:i,content:o,mode:"semantic-symlink",canonicalSource:y,symlinkCapability:c}}let l=!1;try{return g(a)?$(a).isSymbolicLink()&&q(a)===u?l=!1:(ne(a),W(u,a),l=!0):(W(u,a),l=!0),{filePath:a,relativeFile:t,changed:l,content:R(a,"utf8"),mode:"semantic-symlink",canonicalSource:y,symlinkCapability:c}}catch(i){const d=i instanceof Error?i.message:String(i),m=Q(d);return Re(e,t,o,{...c,supported:!1,permission:/EPERM|EACCES|operation not permitted|permission/i.test(d)?"denied":c.permission,filesystem:"no-symlink-support",reason:m},m,s)}}function Qe(e,t,r,o,n){const s=c=>c.split(`
40
- `).length<=e.budget.maxLines&&Buffer.byteLength(c,"utf8")<=e.budget.maxBytes;if(s(t))return t;const a=pe(e,r.slice(0,8),o.slice(0,12),n),u=V(t.includes(v(e))?t:fe(e),e,a);return s(u)?u:u.slice(0,e.budget.maxBytes)}function Se(e,t,r=[],o=[],n){const s=t??fe(e),a=pe(e,r,o,n),u=V(s,e,a);return Qe(e,u,r,o,n)}function et(e){const t=X(e.targetId),r=e.fs??Ne(),o=r.join(e.projectRoot,t.primaryFile);if(e.fs===void 0&&t.targetId==="canonical"&&Z(e.projectRoot,[y]),t.targetId!=="canonical"&&e.fs===void 0){const c=tt(e).files.find(l=>l.relativeFile===t.primaryFile);if(c===void 0)throw new Error(`Primary project memory file was not written for ${t.targetId}.`);return{filePath:c.filePath,changed:c.changed,content:c.content}}const n=r.readFile(o),s=e.bootstrapArchitecture??(e.fs===void 0&&t.targetId==="canonical"&&n===void 0?ke(e.projectRoot):void 0),a=t.targetId==="canonical"&&n!==void 0?ie(e)?ce(t,n,e):n:Se(t,n,e.memoryNotes,e.architectureReferences,s);if(n===a)return{filePath:o,changed:!1,content:a};const u=e.dryRun?void 0:r.writeFileAtomic(o,a);return{filePath:o,changed:!0,content:a,safeDiff:le(n,a),backupPath:u?.backupPath,reasonCodes:J(e.memoryNotes??[])}}function ct(e){return et({...e,targetId:"canonical"})}function tt(e){if(e.fs!==void 0)throw new Error("writeProjectMemoryTargetFiles requires the node filesystem to manage symlinks safely.");const t=X(e.targetId),r=X("canonical");t.secondaryFiles.some(d=>d===null||d.scope!=="project"&&d.scope!=="user"||!be(d.path))&&E("invalid");const o=Array.from(new Set([t.primaryFile,...t.targetId==="canonical"?[]:t.secondaryFiles.filter(d=>d.scope==="project").map(d=>d.path)]));Z(e.projectRoot,[y,...o,".neocortex/tmp"]);const n=p(e.projectRoot,y),s=g(n)?R(n,"utf8"):void 0,a=e.bootstrapArchitecture??(s===void 0?ke(e.projectRoot):void 0),u=s!==void 0?ie(e)?ce(r,s,e):s:Se(r,s,e.memoryNotes,e.architectureReferences,a),c=!g(n)||R(n,"utf8")!==u;let l;if(c&&!e.dryRun&&(l=K(n,u)),t.targetId==="canonical")return{targetId:t.targetId,canonicalFilePath:n,changed:c,files:[{filePath:n,relativeFile:y,changed:c,content:u,mode:"canonical",canonicalSource:y,safeDiff:le(s,u),backupPath:l,reasonCodes:J(e.memoryNotes??[])}]};const i=o.map(d=>{if(Z(e.projectRoot,[d,".neocortex/tmp"]),!x(t,d))return Ve(e.projectRoot,d,t,u,e.symlinkCapability,e.dryRun);const m=p(e.projectRoot,d),b=g(m)?R(m,"utf8"):void 0,k=Je(t,d,b,e.projectRoot),S=b!==k;return S&&!e.dryRun&&K(m,k),{filePath:m,relativeFile:d,changed:S,content:k,mode:"managed-wrapper",canonicalSource:y,symlinkCapability:Ee(e.projectRoot,t,d,e.symlinkCapability,e.dryRun),reasonCodes:J(e.memoryNotes??[])}});return{targetId:t.targetId,canonicalFilePath:n,files:i,changed:c||i.some(d=>d.changed)}}export{it as PROJECT_MEMORY_LAYER_CATEGORIES,ke as bootstrapArchitectureMemory,Se as buildProjectMemoryContent,Be as classifyProjectMemoryUpdate,Ne as createNodeProjectMemoryFs,le as createSafeProjectMemoryDiff,ct as writeCanonicalProjectMemory,et as writeProjectMemory,tt as writeProjectMemoryTargetFiles};
37
+ `,a=[$(e),"## Canonical Project Memory Source","",`This platform wrapper preserves host-specific frontmatter/instructions while resolving project memory to \`${s}\`.`,"",`- Canonical source: \`${b}\``,`- Symlink-backed/source-of-truth file: \`${s}\``,`- Feedback loop: read \`${s}\` for shared context and run \`${e.bidirectionalReference.feedbackTrigger}\` when durable platform findings should update \`${b}\`.`,"- Human-authored content outside this managed block is preserved byte-for-byte.",L(e)].join(`
38
+ `);return J(r,e,a)}function ge(e,t,n,o,s,r=!1){const a=p(e,t),c=Z(s),l=`${["[NEOCORTEX COMPATIBILITY REMEDIATION]","Materialized project memory fallback because semantic symlink orchestration failed.","This is not product mode; repair host permissions/filesystem support and restore the symlink to NEOCORTEX.md.","WARNING: materialized fallback is remediation debt, not a silent mode; run *update-memory for durable context and repair this file back to canonical NEOCORTEX.md resolution.",`Fallback reason: ${c}`,""].join(`
39
+ `)}${n}`,d=(g(a)?E(a,"utf8"):void 0)!==l;return d&&!r&&(g(a)&&C(a).isSymbolicLink()&&re(a),Y(a,l)),{filePath:a,relativeFile:t,changed:d,content:l,mode:"compatibility-materialized-fallback",canonicalSource:b,symlinkCapability:o,fallbackReason:c,remediationDebt:`Repair ${t} so it is a symlink to ${b}; fallback is compatibility remediation only.`}}function Ze(e,t,n,o,s,r=!1){const a=p(e,t),c=be(e,t);r||O(I(a),{recursive:!0});const u=he(e,n,t,s,r);if(!u.supported)return ge(e,t,o,u,u.reason??"symlink capability detection reported unsupported host",r);if(r){let i=!0;try{i=!(g(a)&&C(a).isSymbolicLink()&&ee(a)===c)}catch{i=!0}return{filePath:a,relativeFile:t,changed:i,content:o,mode:"semantic-symlink",canonicalSource:b,symlinkCapability:u}}let l=!1;try{return g(a)?C(a).isSymbolicLink()&&ee(a)===c?l=!1:(re(a),B(c,a),l=!0):(B(c,a),l=!0),{filePath:a,relativeFile:t,changed:l,content:E(a,"utf8"),mode:"semantic-symlink",canonicalSource:b,symlinkCapability:u}}catch(i){const d=i instanceof Error?i.message:String(i),m=Z(d);return ge(e,t,o,{...u,supported:!1,permission:/EPERM|EACCES|operation not permitted|permission/i.test(d)?"denied":u.permission,filesystem:"no-symlink-support",reason:m},m,r)}}function Ve(e,t,n,o,s){const r=u=>u.split(`
40
+ `).length<=e.budget.maxLines&&Buffer.byteLength(u,"utf8")<=e.budget.maxBytes;if(r(t))return t;const a=de(e,n.slice(0,8),o.slice(0,12),s),c=J(t.includes($(e))?t:ue(e),e,a);return r(c)?c:c.slice(0,e.budget.maxBytes)}function ke(e,t,n=[],o=[],s){const r=t??ue(e),a=de(e,n,o,s),c=J(r,e,a);return Ve(e,c,n,o,s)}function Qe(e){const t=W(e.targetId),n=e.fs??Oe(e.backupDirectory),o=n.join(e.projectRoot,t.primaryFile);if(e.fs===void 0&&t.targetId==="canonical"&&F(e.projectRoot,[b]),t.targetId!=="canonical"&&e.fs===void 0){const u=et(e).files.find(l=>l.relativeFile===t.primaryFile);if(u===void 0)throw new Error(`Primary project memory file was not written for ${t.targetId}.`);return{filePath:u.filePath,changed:u.changed,content:u.content}}const s=n.readFile(o),r=e.bootstrapArchitecture??(e.fs===void 0&&t.targetId==="canonical"&&s===void 0?ye(e.projectRoot):void 0),a=t.targetId==="canonical"&&s!==void 0?ne(e)?oe(t,s,e):s:ke(t,s,e.memoryNotes,e.architectureReferences,r);if(s===a)return{filePath:o,changed:!1,content:a};const c=e.dryRun?void 0:n.writeFileAtomic(o,a);return{filePath:o,changed:!0,content:a,safeDiff:ie(s,a),backupPath:c?.backupPath,reasonCodes:K(e.memoryNotes??[])}}function ct(e){return Qe({...e,targetId:"canonical"})}function et(e){if(e.fs!==void 0)throw new Error("writeProjectMemoryTargetFiles requires the node filesystem to manage symlinks safely.");const t=W(e.targetId),n=W("canonical");t.secondaryFiles.some(d=>d===null||d.scope!=="project"&&d.scope!=="user"||!Te(d.path))&&$e("invalid");const o=Array.from(new Set([t.primaryFile,...t.targetId==="canonical"?[]:t.secondaryFiles.filter(d=>d.scope==="project").map(d=>d.path)]));F(e.projectRoot,[b,...o,".neocortex/tmp"]);const s=p(e.projectRoot,b),r=g(s)?E(s,"utf8"):void 0,a=e.bootstrapArchitecture??(r===void 0?ye(e.projectRoot):void 0),c=r!==void 0?ne(e)?oe(n,r,e):r:ke(n,r,e.memoryNotes,e.architectureReferences,a),u=!g(s)||E(s,"utf8")!==c;let l;if(u&&!e.dryRun&&(l=Y(s,c,e.backupDirectory)),t.targetId==="canonical")return{targetId:t.targetId,canonicalFilePath:s,changed:u,files:[{filePath:s,relativeFile:b,changed:u,content:c,mode:"canonical",canonicalSource:b,safeDiff:ie(r,c),backupPath:l,reasonCodes:K(e.memoryNotes??[])}]};const i=o.map(d=>{if(F(e.projectRoot,[d,".neocortex/tmp"]),!v(t,d))return Ze(e.projectRoot,d,t,c,e.symlinkCapability,e.dryRun);const m=p(e.projectRoot,d),h=g(m)?E(m,"utf8"):void 0,k=Je(t,d,h,e.projectRoot),R=h!==k;return R&&!e.dryRun&&Y(m,k,e.backupDirectory),{filePath:m,relativeFile:d,changed:R,content:k,mode:"managed-wrapper",canonicalSource:b,symlinkCapability:he(e.projectRoot,t,d,e.symlinkCapability,e.dryRun),reasonCodes:K(e.memoryNotes??[])}});return{targetId:t.targetId,canonicalFilePath:s,files:i,changed:u||i.some(d=>d.changed)}}export{it as PROJECT_MEMORY_LAYER_CATEGORIES,ye as bootstrapArchitectureMemory,ke as buildProjectMemoryContent,Ue as classifyProjectMemoryUpdate,Oe as createNodeProjectMemoryFs,ie as createSafeProjectMemoryDiff,v as shouldUseManagedWrapper,ct as writeCanonicalProjectMemory,Qe as writeProjectMemory,et as writeProjectMemoryTargetFiles};
@@ -1,5 +1,5 @@
1
- export interface PrivateCodexPreflightV5 {
2
- readonly schemaVersion: 5;
1
+ export interface PrivateCodexPreflightV6 {
2
+ readonly schemaVersion: 6;
3
3
  readonly hostKind: 'codex-cli';
4
4
  readonly hostVersion: string;
5
5
  readonly projectRoot: string;
@@ -11,6 +11,7 @@ export interface PrivateCodexPreflightV5 {
11
11
  readonly mcpIsolation: 'passed';
12
12
  readonly environmentIsolation: 'passed';
13
13
  readonly networkDenied: 'passed';
14
+ readonly webSearchDisabled: 'passed';
14
15
  readonly credentialKind: 'chatgpt-subscription';
15
16
  }
16
17
  export interface PrivateCodexExecutionReceiptV1 {
@@ -23,6 +24,18 @@ export interface PrivateCodexExecutionReceiptV1 {
23
24
  readonly stderrBytes: number;
24
25
  readonly publicSafe: true;
25
26
  }
27
+ /** Host-only failure telemetry. No material, output text, path, ID or effect verdict. */
28
+ export type PrivateCodexWorkspaceEffectFailureV1 = Readonly<{
29
+ schemaVersion: 1;
30
+ kind: 'PrivateCodexWorkspaceEffectFailure/1';
31
+ phase: 'before-capture' | 'branch-before' | 'after-capture' | 'identity-after' | 'no-payload-change';
32
+ agentReturnedSuccessfully: boolean;
33
+ stdoutSha256?: string;
34
+ stderrSha256?: string;
35
+ stdoutBytes?: number;
36
+ stderrBytes?: number;
37
+ publicSafe: true;
38
+ }>;
26
39
  interface BoundedProcessResult {
27
40
  readonly exitCode: number | null;
28
41
  readonly stdout: Buffer;
@@ -35,6 +48,7 @@ export type PrivateCodexRunner = (args: readonly string[], options: {
35
48
  readonly stdin?: string;
36
49
  readonly timeoutMs: number;
37
50
  readonly maxOutputBytes: number;
51
+ readonly configReadProbe?: true;
38
52
  }) => Promise<BoundedProcessResult>;
39
53
  /** The CLI needs its login location and executable path, not host secrets. */
40
54
  export declare function privateCodexEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
@@ -43,6 +57,8 @@ export declare function runBoundedCodexProcess(args: readonly string[], options:
43
57
  readonly stdin?: string;
44
58
  readonly timeoutMs: number;
45
59
  readonly maxOutputBytes: number;
60
+ readonly codexHome?: string;
61
+ readonly configReadProbe?: true;
46
62
  }): Promise<BoundedProcessResult>;
47
63
  /**
48
64
  * Probe the exact default sandbox configuration used by `codex exec`. This
@@ -55,11 +71,15 @@ export declare function preflightPrivateCodexExecutor(projectRoot: string, optio
55
71
  readonly userHome?: string;
56
72
  readonly now?: () => number;
57
73
  readonly networkProbe?: (root: string, runner: PrivateCodexRunner) => Promise<boolean>;
58
- }): Promise<PrivateCodexPreflightV5>;
59
- export declare function runPrivateCodexStep(material: string, preflight: PrivateCodexPreflightV5, options?: {
74
+ }): Promise<PrivateCodexPreflightV6>;
75
+ export declare function runPrivateCodexStep(material: string, preflight: PrivateCodexPreflightV6, options?: {
60
76
  readonly runner?: PrivateCodexRunner;
61
77
  readonly now?: () => number;
62
78
  readonly requireWorkspaceEffect?: boolean;
63
79
  readonly expectedExecutionBranch?: string;
80
+ /** Root observer only; its return value never authorizes an effect. */
81
+ readonly onWorkspaceEffectFailure?: (observation: PrivateCodexWorkspaceEffectFailureV1) => void;
82
+ /** Operator-selected subscription model; no global configuration mutation. */
83
+ readonly model?: string;
64
84
  }): Promise<PrivateCodexExecutionReceiptV1>;
65
85
  export {};
@@ -1,2 +1,4 @@
1
- import{execFileSync as P,spawn as A}from"node:child_process";import{createHash as _,randomBytes as C}from"node:crypto";import{connect as N,createServer as G}from"node:net";import{accessSync as O,lstatSync as x,mkdtempSync as j,readFileSync as H,realpathSync as K,rmdirSync as g,unlinkSync as T,constants as I}from"node:fs";import{homedir as V}from"node:os";import{join as w,resolve as S}from"node:path";import{gitLifecycleRuntimeDirectory as $}from"../git/git-lifecycle-store.js";import{captureDirectYoloCheckoutEvidence as R}from"../git/direct-yolo-checkpoint.js";const W=3e4,u=16*1024,F=1024*1024,X=256*1024,b=/^codex-cli\s+(\d+\.\d+\.\d+)\s*$/,p="p222-isolated",Y=["PATH","HOME","LANG","LC_ALL","TERM","CODEX_HOME"],q=["-c","features.hooks=false","-c","analytics.enabled=false","-c",'history.persistence="none"',"-c",'otel.exporter="none"',"-c",'otel.metrics_exporter="none"',"-c",'otel.trace_exporter="none"',"-c","otel.log_user_prompt=false","-c","notify=[]"];function J(r){const e={};for(const t of Y)typeof r[t]=="string"&&(e[t]=r[t]);return e}async function k(r,e){return new Promise((t,o)=>{const n=J(process.env),s=A("codex",[...r],{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:n}),i=[],c=[];let a=0,d=0,y=!1,m=!1;const h=setTimeout(()=>{y=!0,s.kill("SIGKILL")},e.timeoutMs);s.stdout.on("data",l=>{a+=l.byteLength,a+d>e.maxOutputBytes?(m=!0,s.kill("SIGKILL")):i.push(l)}),s.stderr.on("data",l=>{d+=l.byteLength,a+d>e.maxOutputBytes?(m=!0,s.kill("SIGKILL")):c.push(l)}),s.on("error",l=>{clearTimeout(h),o(l)}),s.on("close",l=>{clearTimeout(h),t({exitCode:l,stdout:Buffer.concat(i),stderr:Buffer.concat(c),timedOut:y,outputExceeded:m})}),s.stdin.on("error",()=>{}),s.stdin.end(e.stdin)})}function f(r){return r.exitCode===0&&!r.timedOut&&!r.outputExceeded}async function B(r,e){const t=await e(["-c","features.plugins=false","plugin","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:u}),o=await e(["mcp","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:u});if(!f(t)||!f(o))return!1;try{const n=JSON.parse(t.stdout.toString("utf8")),s=JSON.parse(o.stdout.toString("utf8"));return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Array.isArray(n.installed)&&n.installed.length===0&&Array.isArray(s)&&s.length===0)}catch{return!1}}async function D(r,e){const t=await e(["-c","features.hooks=false","features","list"],{cwd:r,timeoutMs:1e4,maxOutputBytes:u});if(!f(t))return!1;const o=t.stdout.toString("utf8").split(/\r?\n/).filter(n=>/^hooks\s+\S+\s+(?:true|false)\s*$/.test(n));return o.length===1&&/^hooks\s+\S+\s+false\s*$/.test(o[0])}function U(r){const e=x(r);if(!e.isFile()||e.isSymbolicLink())throw new Error("private-codex-auth-unavailable");O(r,I.R_OK)}function z(r){const e={...process.env};for(const t of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[t];try{const t=n=>P("git",[...n],{cwd:r,env:e,encoding:"utf8",timeout:5e3,maxBuffer:u,stdio:["ignore","pipe","ignore"]}).trim(),o=[t(["rev-parse","--git-dir"]),t(["rev-parse","--git-common-dir"])].map(n=>K(S(r,n)));if(o.some(n=>!x(n).isDirectory()))throw new Error("git-control-invalid");return[...new Set(o)]}catch{throw new Error("private-codex-git-control-unavailable")}}async function Q(r,e){const t=await e(["sandbox","-P",p,"--","git","rev-parse","--git-dir"],{cwd:r,timeoutMs:1e4,maxOutputBytes:u});if(!f(t))return!1;for(const o of z(r)){const n=w(o,`.neocortex-git-probe-${C(16).toString("hex")}`),s=await e(["sandbox","-P",p,"--","sh","-c",'mkdir "$1"',"sh",n],{cwd:r,timeoutMs:1e4,maxOutputBytes:u});let i=!1,c=!1;try{const a=x(n);i=!0,c=a.isDirectory()}catch(a){if(a.code!=="ENOENT")return!1}if(i&&(c?g(n):T(n)),s.exitCode!==1||s.timedOut||s.outputExceeded||i)return!1}return!0}async function Z(r,e,t){if(!x(e).isDirectory())return!1;O(e,I.R_OK);const o=await t(["sandbox","-P",p,"--","sh","-c",'if test -r "$1"; then exit 42; else exit 43; fi',"sh",e],{cwd:r,timeoutMs:1e4,maxOutputBytes:u});return o.exitCode===43&&!o.timedOut&&!o.outputExceeded}async function ee(r,e){const t=G(o=>o.end());await new Promise((o,n)=>{t.once("error",n),t.listen(0,"127.0.0.1",()=>o())});try{const o=t.address();if(!o||typeof o=="string")return!1;const n='const s=require("node:net").connect(Number(process.argv[1]),"127.0.0.1");s.setTimeout(1500);s.on("connect",()=>{s.end();process.exit(0)});s.on("error",()=>process.exit(1));s.on("timeout",()=>process.exit(1))';if(!await new Promise(a=>{const d=N(o.port,"127.0.0.1");d.setTimeout(1500),d.once("connect",()=>{d.end(),a(!0)}),d.once("error",()=>a(!1)),d.once("timeout",()=>{d.destroy(),a(!1)})}))return!1;const i=await e(["sandbox","-P",p,"--","node","--version"],{cwd:r,timeoutMs:5e3,maxOutputBytes:u});if(!f(i))return!1;const c=await e(["sandbox","-P",p,"--","node","-e",n,String(o.port)],{cwd:r,timeoutMs:5e3,maxOutputBytes:u});return c.exitCode===1&&!c.timedOut&&!c.outputExceeded}finally{t.close()}}async function fe(r,e={}){if((e.platform??process.platform)!=="linux")throw new Error("private-codex-platform-unsupported");const t=S(r),o=e.runner??k,n=e.userHome??V(),s=e.codexHome??process.env.CODEX_HOME??w(n,".codex"),i=w(s,"auth.json");try{U(i)}catch{throw new Error("private-codex-auth-unavailable")}const c=await o(["--version"],{cwd:t,timeoutMs:5e3,maxOutputBytes:u}),a=f(c)?b.exec(c.stdout.toString("utf8").trim()):null;if(!a)throw new Error("private-codex-version-unavailable");const d=await o(["login","status"],{cwd:t,timeoutMs:5e3,maxOutputBytes:u});if(!f(d)||!/Logged in using ChatGPT/i.test(Buffer.concat([d.stdout,d.stderr]).toString("utf8")))throw new Error("private-codex-subscription-required");if(!await B(t,o).catch(()=>!1))throw new Error("private-codex-mcp-isolation-unproven");if(!await D(t,o).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");const h=await $(t).catch(()=>{throw new Error("private-codex-git-lifecycle-read-isolation-unproven")}),l=w(n,".ssh"),L=await o(["sandbox","-P",p,"--","sh","-c",'test ! -r "$1" && test ! -r "$2"',"sh",i,l],{cwd:t,timeoutMs:1e4,maxOutputBytes:u});if(!f(L))throw new Error("private-codex-auth-isolation-unproven");const v=j(w(t,".private-codex-probe-")),E=w(v,"receipt");try{const M=await o(["sandbox","-P",p,"--","sh","-c",'printf "P222_PROBE\\n" > "$1"',"sh",E],{cwd:t,timeoutMs:1e4,maxOutputBytes:u});if(!f(M)||H(E,"utf8")!==`P222_PROBE
2
- `)throw new Error("private-codex-workspace-write-unproven")}catch{throw new Error("private-codex-workspace-write-unproven")}finally{try{T(E)}catch{}g(v)}if(!await Q(t,o).catch(()=>!1))throw new Error("private-codex-git-control-isolation-unproven");if(!await Z(t,h,o).catch(()=>!1))throw new Error("private-codex-git-lifecycle-read-isolation-unproven");if(!await(e.networkProbe??ee)(t,o))throw new Error("private-codex-network-isolation-unproven");return Object.freeze({schemaVersion:5,hostKind:"codex-cli",hostVersion:a[1],projectRoot:t,observedAtMs:(e.now??Date.now)(),authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",credentialKind:"chatgpt-subscription"})}async function pe(r,e,t={}){const o=(t.now??Date.now)();if(e.schemaVersion!==5||e.hostKind!=="codex-cli"||e.authIsolation!=="passed"||e.workspaceWrite!=="passed"||e.gitControlWriteDenied!=="passed"||e.gitLifecycleReadDenied!=="passed"||e.mcpIsolation!=="passed"||e.environmentIsolation!=="passed"||e.networkDenied!=="passed"||e.credentialKind!=="chatgpt-subscription"||o<e.observedAtMs||o-e.observedAtMs>W||typeof r!="string"||Buffer.byteLength(r,"utf8")<1||Buffer.byteLength(r,"utf8")>X)throw new Error("private-codex-preflight-stale");const n=t.runner??k,s=await n(["--version"],{cwd:e.projectRoot,timeoutMs:5e3,maxOutputBytes:u});if(!f(s)||b.exec(s.stdout.toString("utf8").trim())?.[1]!==e.hostVersion)throw new Error("private-codex-version-drift");const i=t.requireWorkspaceEffect?await R(e.projectRoot).catch(()=>{throw new Error("private-codex-workspace-effect-unverified")}):void 0;if(i&&t.expectedExecutionBranch!==void 0&&i.branch!==t.expectedExecutionBranch)throw new Error("private-codex-workspace-effect-unverified");if(!await D(e.projectRoot,n).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");if(!await B(e.projectRoot,n).catch(()=>!1))throw new Error("private-codex-mcp-isolation-unproven");const c=await n(["exec","--ephemeral","--json","--strict-config","-c","features.plugins=false",...q,"-c","shell_environment_policy.ignore_default_excludes=false","-c",'shell_environment_policy.include_only=["PATH","HOME","LANG","LC_ALL","TERM"]',"-c",`default_permissions="${p}"`,"-C",e.projectRoot,"-"],{cwd:e.projectRoot,stdin:r,timeoutMs:10*6e4,maxOutputBytes:F});if(!f(c))throw new Error("private-codex-execution-unverified");if(i){const a=await R(e.projectRoot).catch(()=>{throw new Error("private-codex-workspace-effect-unverified")});if(a.headSha!==i.headSha||a.branch!==i.branch||a.payloadDigest===i.payloadDigest)throw new Error("private-codex-workspace-effect-unverified")}return Object.freeze({schemaVersion:1,outcome:"executor-returned-unverified",exitCode:0,stdoutSha256:_("sha256").update(c.stdout).digest("hex"),stderrSha256:_("sha256").update(c.stderr).digest("hex"),stdoutBytes:c.stdout.byteLength,stderrBytes:c.stderr.byteLength,publicSafe:!0})}export{fe as preflightPrivateCodexExecutor,J as privateCodexEnvironment,k as runBoundedCodexProcess,pe as runPrivateCodexStep};
1
+ import{codexLifecycleGuardPath as J}from"./codex-lifecycle-guard.js";import{execFileSync as X,spawn as Y}from"node:child_process";import{createHash as T,randomBytes as q}from"node:crypto";import{connect as U,createServer as Z}from"node:net";import{accessSync as k,lstatSync as B,mkdtempSync as Q,readFileSync as ee,realpathSync as te,rmdirSync as M,unlinkSync as A,constants as C}from"node:fs";import{homedir as re}from"node:os";import{join as v,resolve as L}from"node:path";import{gitLifecycleRuntimeDirectory as oe}from"../git/git-lifecycle-store.js";import{captureDirectYoloCheckoutEvidence as H}from"../git/direct-yolo-checkpoint.js";import{createPrivateCodexScopedRunner as ne}from"./codex-scoped-permissions.js";import{createPrivateCodexHostRuntime as se}from"./codex-host-runtime.js";const N=3e4,m=16*1024,ie=1024*1024,ae=256*1024,j=/^codex-cli\s+(\d+\.\d+\.\d+)\s*$/,x="p222-isolated",ce=["PATH","HOME","LANG","LC_ALL","TERM","CODEX_HOME"],G=["-c",'web_search="disabled"',"-c","features.hooks=false","-c","analytics.enabled=false","-c",'history.persistence="none"',"-c",'otel.exporter="none"',"-c",'otel.metrics_exporter="none"',"-c",'otel.trace_exporter="none"',"-c","otel.log_user_prompt=false","-c","notify=[]"],I=new WeakMap,P=new WeakMap;function de(r){const e={};for(const t of ce)typeof r[t]=="string"&&(e[t]=r[t]);return e}async function $(r,e){if(e.configReadProbe&&(e.stdin!==void 0||r.at(-1)!=="app-server"))throw new Error("private-codex-web-search-isolation-unproven");return new Promise((t,o)=>{const s=de(process.env);e.codexHome!==void 0&&(s.CODEX_HOME=e.codexHome);const n=process.platform==="linux",a=Y(n?process.execPath:e.codexHome===void 0?"codex":"/bin/sh",n?[J,"process"]:e.codexHome===void 0?[...r]:["-c",'umask 077; exec codex "$@"',"neocortex-private-codex",...r],{cwd:e.cwd,stdio:n?["pipe","pipe","pipe","ipc"]:["pipe","pipe","pipe"],env:s,detached:n}),d=()=>{if(process.platform==="linux"&&a.pid!==void 0)try{process.kill(-a.pid,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}else a.kill("SIGKILL")},i=[],u=[];let f=0,p=0,c=!1,w=!1,E="",S=!1;const b=l=>a.stdin.write(`${JSON.stringify(l)}
2
+ `),_=setTimeout(()=>{c=!0,d()},e.timeoutMs);a.stdout.on("data",l=>{if(f+=l.byteLength,f+p>e.maxOutputBytes)w=!0,d();else if(i.push(l),e.configReadProbe){E+=l.toString("utf8");let y;for(;(y=E.indexOf(`
3
+ `))>=0;){const D=E.slice(0,y);E=E.slice(y+1);try{const R=JSON.parse(D);R.id===1&&R.result&&!S?(S=!0,b({method:"initialized",params:{}}),b({id:2,method:"config/read",params:{includeLayers:!1,cwd:e.cwd}})):R.id===2&&a.stdin.end()}catch{}}}}),a.stderr.on("data",l=>{p+=l.byteLength,f+p>e.maxOutputBytes?(w=!0,d()):u.push(l)}),a.on("error",l=>{clearTimeout(_),o(l)}),a.on("close",l=>{clearTimeout(_),t({exitCode:l,stdout:Buffer.concat(i),stderr:Buffer.concat(u),timedOut:c,outputExceeded:w})}),a.stdin.on("error",()=>{}),n&&a.send({kind:"private-codex-launch",args:[...r],codexHome:e.codexHome},l=>{l&&(clearTimeout(_),d(),o(new Error("private-codex-process-guard-unavailable")))}),e.configReadProbe?b({id:1,method:"initialize",params:{clientInfo:{name:"p222-isolation-probe",version:"1"},capabilities:{}}}):a.stdin.end(e.stdin)})}function h(r){return r.exitCode===0&&!r.timedOut&&!r.outputExceeded}async function W(r,e){const t=await e(["-c","features.plugins=false","plugin","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m}),o=await e(["mcp","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t)||!h(o))return null;try{const s=JSON.parse(t.stdout.toString("utf8")),n=JSON.parse(o.stdout.toString("utf8"));if(!!!(s&&typeof s=="object"&&!Array.isArray(s)&&Array.isArray(s.installed)&&s.installed.length===0)||!Array.isArray(n)||n.length>64)return null;const d=n.map(c=>{if(!c||typeof c!="object"||Array.isArray(c))throw new Error("invalid catalog");const w=c;if(typeof w.name!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(w.name)||typeof w.enabled!="boolean")throw new Error("invalid catalog");return w.name});if(new Set(d).size!==d.length)return null;if(d.length===0)return[];const i=[...d].sort().flatMap(c=>["-c",`mcp_servers.${c}.enabled=false`]),u=await e([...i,"mcp","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(u))return null;const f=JSON.parse(u.stdout.toString("utf8"));if(!Array.isArray(f)||f.length!==d.length)return null;const p=new Set;for(const c of f){if(!c||typeof c!="object"||Array.isArray(c)||typeof c.name!="string"||!d.includes(c.name)||c.enabled!==!1||p.has(c.name))return null;p.add(c.name)}return Object.freeze(i)}catch{return null}}async function z(r,e){const t=await e(["-c","features.hooks=false","features","list"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t))return!1;const o=t.stdout.toString("utf8").split(/\r?\n/).filter(s=>/^hooks\s+\S+\s+(?:true|false)\s*$/.test(s));return o.length===1&&/^hooks\s+\S+\s+false\s*$/.test(o[0])}async function V(r,e,t){const o=await e(["-c","features.plugins=false",...t,...G,"--strict-config","app-server"],{cwd:r,configReadProbe:!0,timeoutMs:1e4,maxOutputBytes:262144});try{if(!h(o))return!1;const n=o.stdout.toString("utf8").split(/\r?\n/).filter(Boolean).map(a=>JSON.parse(a)).filter(a=>a&&a.id===2);return n.length===1&&!n[0].error&&n[0].result?.config?.web_search==="disabled"}catch{return!1}finally{o.stdout.fill(0),o.stderr.fill(0)}}function ue(r){const e=B(r);if(!e.isFile()||e.isSymbolicLink())throw new Error("private-codex-auth-unavailable");k(r,C.R_OK)}function F(r){const e={...process.env};for(const t of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[t];try{const t=s=>X("git",[...s],{cwd:r,env:e,encoding:"utf8",timeout:5e3,maxBuffer:m,stdio:["ignore","pipe","ignore"]}).trim(),o=[t(["rev-parse","--git-dir"]),t(["rev-parse","--git-common-dir"])].map(s=>te(L(r,s)));if(o.some(s=>!B(s).isDirectory()))throw new Error("git-control-invalid");return[...new Set(o)]}catch{throw new Error("private-codex-git-control-unavailable")}}async function le(r,e){const t=await e(["sandbox","-P",x,"--","git","rev-parse","--git-dir"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t))return!1;for(const o of F(r)){const s=v(o,`.neocortex-git-probe-${q(16).toString("hex")}`),n=await e(["sandbox","-P",x,"--","sh","-c",'mkdir "$1"',"sh",s],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});let a=!1,d=!1;try{const i=B(s);a=!0,d=i.isDirectory()}catch(i){if(i.code!=="ENOENT")return!1}if(a&&(d?M(s):A(s)),n.exitCode!==1||n.timedOut||n.outputExceeded||a)return!1}return!0}async function fe(r,e,t){if(!B(e).isDirectory())return!1;k(e,C.R_OK);const o=await t(["sandbox","-P",x,"--","sh","-c",'if test -r "$1"; then exit 42; else exit 43; fi',"sh",e],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});return o.exitCode===43&&!o.timedOut&&!o.outputExceeded}async function pe(r,e){const t=Z(o=>o.end());await new Promise((o,s)=>{t.once("error",s),t.listen(0,"127.0.0.1",()=>o())});try{const o=t.address();if(!o||typeof o=="string")return!1;const s='const s=require("node:net").connect(Number(process.argv[1]),"127.0.0.1");s.setTimeout(1500);s.on("connect",()=>{s.end();process.exit(0)});s.on("error",()=>process.exit(1));s.on("timeout",()=>process.exit(1))';if(!await new Promise(i=>{const u=U(o.port,"127.0.0.1");u.setTimeout(1500),u.once("connect",()=>{u.end(),i(!0)}),u.once("error",()=>i(!1)),u.once("timeout",()=>{u.destroy(),i(!1)})}))return!1;const a=await e(["sandbox","-P",x,"--","node","--version"],{cwd:r,timeoutMs:5e3,maxOutputBytes:m});if(!h(a))return!1;const d=await e(["sandbox","-P",x,"--","node","-e",s,String(o.port)],{cwd:r,timeoutMs:5e3,maxOutputBytes:m});return d.exitCode===1&&!d.timedOut&&!d.outputExceeded}finally{t.close()}}async function Re(r,e={}){if((e.platform??process.platform)!=="linux")throw new Error("private-codex-platform-unsupported");const t=L(r),o=e.userHome??re(),s=e.codexHome??process.env.CODEX_HOME??v(o,".codex"),n=e.runner?void 0:se(t,s);try{const a=n?async(g,K)=>(n.verify(),$(g,{...K,codexHome:n.home})):$,d=n?.home??s,i=e.runner??await ne(t,a,{...e,codexHome:d,credentialSourceHome:n?.sourceHome??s,gitControlDirectories:F(t)}),u=v(d,"auth.json");try{ue(u)}catch{throw new Error("private-codex-auth-unavailable")}const f=await i(["--version"],{cwd:t,timeoutMs:5e3,maxOutputBytes:m}),p=h(f)?j.exec(f.stdout.toString("utf8").trim()):null;if(!p)throw new Error("private-codex-version-unavailable");const c=await i(["login","status"],{cwd:t,timeoutMs:5e3,maxOutputBytes:m});if(!h(c)||!/Logged in using ChatGPT/i.test(Buffer.concat([c.stdout,c.stderr]).toString("utf8")))throw new Error("private-codex-subscription-required");const w=await W(t,i).catch(()=>null);if(w===null)throw new Error("private-codex-mcp-isolation-unproven");if(!await z(t,i).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");if(!await V(t,i,w).catch(()=>!1))throw new Error("private-codex-web-search-isolation-unproven");const S=await oe(t).catch(()=>{throw new Error("private-codex-git-lifecycle-read-isolation-unproven")}),b=v(o,".ssh"),_=await i(["sandbox","-P",x,"--","sh","-c",...n?['test ! -r "$1" && test ! -r "$2" && test ! -r "$3"',"sh",u,b,v(s,"auth.json")]:['test ! -r "$1" && test ! -r "$2"',"sh",u,b]],{cwd:t,timeoutMs:1e4,maxOutputBytes:m});if(!h(_))throw new Error("private-codex-auth-isolation-unproven");const l=Q(v(t,".private-codex-probe-")),y=v(l,"receipt");try{const g=await i(["sandbox","-P",x,"--","sh","-c",'printf "P222_PROBE\\n" > "$1"',"sh",y],{cwd:t,timeoutMs:1e4,maxOutputBytes:m});if(!h(g)||ee(y,"utf8")!==`P222_PROBE
4
+ `)throw new Error("private-codex-workspace-write-unproven")}catch{throw new Error("private-codex-workspace-write-unproven")}finally{try{A(y)}catch{}M(l)}if(!await le(t,i).catch(()=>!1))throw new Error("private-codex-git-control-isolation-unproven");if(!await fe(t,S,i).catch(()=>!1))throw new Error("private-codex-git-lifecycle-read-isolation-unproven");if(!await(e.networkProbe??pe)(t,i))throw new Error("private-codex-network-isolation-unproven");const O=Object.freeze({schemaVersion:6,hostKind:"codex-cli",hostVersion:p[1],projectRoot:t,observedAtMs:(e.now??Date.now)(),authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",credentialKind:"chatgpt-subscription"});if(I.set(O,i),n){const g=setTimeout(()=>{P.delete(O),I.delete(O);try{n.close()}catch{}},N);g.unref(),P.set(O,{runtime:n,timer:g})}return O}catch(a){throw n?.close(),a}}async function Te(r,e,t={}){const o=P.get(e);o&&(clearTimeout(o.timer),P.delete(e));try{const s=(t.now??Date.now)();if(t.model!==void 0&&!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(t.model))throw new Error("private-codex-model-invalid");if(e.schemaVersion!==6||e.hostKind!=="codex-cli"||e.authIsolation!=="passed"||e.workspaceWrite!=="passed"||e.gitControlWriteDenied!=="passed"||e.gitLifecycleReadDenied!=="passed"||e.mcpIsolation!=="passed"||e.environmentIsolation!=="passed"||e.webSearchDisabled!=="passed"||e.networkDenied!=="passed"||e.credentialKind!=="chatgpt-subscription"||s<e.observedAtMs||s-e.observedAtMs>N||typeof r!="string"||Buffer.byteLength(r,"utf8")<1||Buffer.byteLength(r,"utf8")>ae)throw new Error("private-codex-preflight-stale");const n=t.runner??I.get(e);if(!n)throw new Error("private-codex-preflight-stale");const a=await n(["--version"],{cwd:e.projectRoot,timeoutMs:5e3,maxOutputBytes:m});if(!h(a)||j.exec(a.stdout.toString("utf8").trim())?.[1]!==e.hostVersion)throw new Error("private-codex-version-drift");const d=(p,c)=>{const w=Object.freeze({schemaVersion:1,kind:"PrivateCodexWorkspaceEffectFailure/1",phase:p,agentReturnedSuccessfully:c!==void 0,...c===void 0?{}:{stdoutSha256:T("sha256").update(c.stdout).digest("hex"),stderrSha256:T("sha256").update(c.stderr).digest("hex"),stdoutBytes:c.stdout.length,stderrBytes:c.stderr.length},publicSafe:!0});try{Promise.resolve(t.onWorkspaceEffectFailure?.(w)).catch(()=>{})}catch{}return new Error("private-codex-workspace-effect-unverified")},i=t.requireWorkspaceEffect?await H(e.projectRoot).catch(()=>{throw d("before-capture")}):void 0;if(i&&t.expectedExecutionBranch!==void 0&&i.branch!==t.expectedExecutionBranch)throw d("branch-before");if(!await z(e.projectRoot,n).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");const u=await W(e.projectRoot,n).catch(()=>null);if(u===null)throw new Error("private-codex-mcp-isolation-unproven");if(!await V(e.projectRoot,n,u).catch(()=>!1))throw new Error("private-codex-web-search-isolation-unproven");const f=await n(["exec","--ephemeral","--json","--strict-config","-c","features.plugins=false",...t.model===void 0?[]:["--model",t.model],...u,...G,"-c","shell_environment_policy.ignore_default_excludes=false","-c",'shell_environment_policy.include_only=["PATH","HOME","LANG","LC_ALL","TERM"]',"-c",`default_permissions="${x}"`,"-C",e.projectRoot,"-"],{cwd:e.projectRoot,stdin:r,timeoutMs:10*6e4,maxOutputBytes:ie});if(!h(f))throw new Error("private-codex-execution-unverified");if(o?.runtime.verify(),i){const p=await H(e.projectRoot).catch(()=>{throw d("after-capture",f)});if(p.headSha!==i.headSha||p.branch!==i.branch)throw d("identity-after",f);if(p.payloadDigest===i.payloadDigest)throw d("no-payload-change",f)}return Object.freeze({schemaVersion:1,outcome:"executor-returned-unverified",exitCode:0,stdoutSha256:T("sha256").update(f.stdout).digest("hex"),stderrSha256:T("sha256").update(f.stderr).digest("hex"),stdoutBytes:f.stdout.byteLength,stderrBytes:f.stderr.byteLength,publicSafe:!0})}finally{o&&(I.delete(e),o.runtime.close())}}export{Re as preflightPrivateCodexExecutor,de as privateCodexEnvironment,$ as runBoundedCodexProcess,Te as runPrivateCodexStep};
@@ -0,0 +1,10 @@
1
+ export interface PrivateCodexHostRuntime {
2
+ readonly home: string;
3
+ readonly sourceHome: string;
4
+ verify(): void;
5
+ close(): void;
6
+ }
7
+ /** The CLI may record project trust in its own configuration. Keep that write in
8
+ * short-lived, owner-private host control storage using the existing account.
9
+ * No credential is placed in, mounted into or passed to the model checkout. */
10
+ export declare function createPrivateCodexHostRuntime(projectRoot: string, sourceHome: string): PrivateCodexHostRuntime;
@@ -0,0 +1 @@
1
+ import{startPrivateCodexHomeGuard as L}from"./codex-lifecycle-guard.js";import{createHash as k}from"node:crypto";import{closeSync as H,constants as O,fstatSync as z,lstatSync as g,mkdtempSync as M,openSync as R,readFileSync as T,realpathSync as S,rmSync as _,writeFileSync as C}from"node:fs";import{isAbsolute as P,join as c,relative as W}from"node:path";const p=d=>k("sha256").update(d).digest("hex"),w=new Set;let b=!1;function r(){throw new Error("private-codex-host-runtime-unverified")}function a(d,v){const f=R(d,O.O_RDONLY|O.O_NOFOLLOW|O.O_NONBLOCK);try{const e=z(f);(!e.isFile()||e.uid!==process.getuid?.()||e.nlink!==1||e.mode&18||v&&(e.mode&511)!==384||e.size<1||e.size>1048576)&&r();const l=T(f),s=z(f),m=g(d);return(l.length!==e.size||[s,m].some(t=>t.dev!==e.dev||t.ino!==e.ino||t.size!==e.size||t.mtimeMs!==e.mtimeMs||t.ctimeMs!==e.ctimeMs||t.mode!==e.mode||t.nlink!==1))&&r(),l}finally{H(f)}}function K(d,v){try{const f=S(d),e=S(v),l=W(f,e),s=g(e);(!l||!l.startsWith("..")&&!P(l)||!s.isDirectory()||s.uid!==process.getuid?.()||s.mode&18)&&r();const m=a(c(e,"auth.json"),!0);let t;try{t=a(c(e,"config.toml"),!1)}catch(o){if(o.code!=="ENOENT")throw o}const D=p(m),F=t?p(t):void 0,n=M(c(e,".neocortex-executor-")),N=g(n),u=process.platform==="linux"?L(n):void 0;let x=!1;const E=()=>{const o=g(n),i=g(e);(S(e)!==e||i.dev!==s.dev||i.ino!==s.ino||i.uid!==s.uid||i.mode&18||o.dev!==N.dev||o.ino!==N.ino||o.uid!==process.getuid?.()||(o.mode&511)!==448||!o.isDirectory()||o.isSymbolicLink())&&r()};let y;const j=()=>{if(!x)try{E(),_(n,{recursive:!0}),x=!0,y&&w.delete(y),u?.connected&&u.disconnect()}catch{r()}};try{C(c(n,"auth.json"),m,{mode:384,flag:"wx"}),t&&C(c(n,"config.toml"),t,{mode:384,flag:"wx"}),m.fill(0),t?.fill(0);const o=()=>{try{(x||u&&(!u.connected||u.exitCode!==null||u.signalCode!==null))&&r(),E(),p(a(c(e,"auth.json"),!0))!==D&&r();let i;try{i=a(c(e,"config.toml"),!1)}catch(h){if(h.code!=="ENOENT")throw h}(i?p(i):void 0)!==F&&r(),a(c(n,"auth.json"),!0);try{a(c(n,"config.toml"),!0)}catch(h){if(h.code!=="ENOENT")throw h}}catch{r()}};return o(),y=Object.freeze({home:n,sourceHome:e,verify:o,close:j}),w.add(y),b||(b=!0,process.once("exit",()=>{for(const i of w)try{i.close()}catch{}})),y}catch(o){throw j(),o}}catch{r()}}export{K as createPrivateCodexHostRuntime};
@@ -0,0 +1,4 @@
1
+ /** Mechanical Linux process/custody lifetime; no workflow material or authority. */
2
+ import { type ChildProcess } from 'node:child_process';
3
+ export declare const codexLifecycleGuardPath: string;
4
+ export declare function startPrivateCodexHomeGuard(home: string): ChildProcess;
@@ -0,0 +1 @@
1
+ import{spawn as i}from"node:child_process";import{lstatSync as d,realpathSync as a,rmSync as u}from"node:fs";import{basename as f}from"node:path";import{fileURLToPath as m}from"node:url";const p=m(new URL(import.meta.url.endsWith(".ts")?"../../dist/private-execution/codex-lifecycle-guard.js":"./codex-lifecycle-guard.js",import.meta.url));function L(r){const e=d(r),c=i(process.execPath,[p,"home",r,String(e.dev),String(e.ino)],{detached:!0,env:{},stdio:["ignore","ignore","ignore","ipc"]});return c.on("error",()=>{}),c.unref(),c.channel?.unref(),c}function n(){process.kill(-process.pid,"SIGKILL"),process.exit(1)}function l(){const[r,e,c]=process.argv.slice(3);let s=!1;const o=()=>{if(!s){s=!0;try{if(!r||!f(r).startsWith(".neocortex-executor-"))throw new Error;const t=d(r);if(a(r)!==r||!t.isDirectory()||t.isSymbolicLink()||t.uid!==process.getuid?.()||(t.mode&511)!==448||String(t.dev)!==e||String(t.ino)!==c)throw new Error;u(r,{recursive:!0}),process.exit(0)}catch(t){process.exit(t.code==="ENOENT"?0:1)}}};process.on("disconnect",o),process.connected||o()}function x(){process.on("disconnect",n),process.on("SIGTERM",n),process.on("SIGINT",n),process.stdout.on("error",n),process.stderr.on("error",n),process.connected||n(),process.once("message",r=>{const e=r;(!e||e.kind!=="private-codex-launch"||!Array.isArray(e.args)||e.args.some(o=>typeof o!="string")||e.codexHome!==void 0&&typeof e.codexHome!="string")&&n();const c=e.args,s=i(e.codexHome===void 0?"codex":"/bin/sh",e.codexHome===void 0?c:["-c",'umask 077; exec codex "$@"',"neocortex-private-codex",...c],{cwd:process.cwd(),env:Object.fromEntries(["PATH","HOME","LANG","LC_ALL","TERM","CODEX_HOME"].filter(o=>process.env[o]!==void 0).map(o=>[o,process.env[o]])),detached:!1,stdio:["pipe","pipe","pipe"]});process.stdin.pipe(s.stdin),s.stdin.on("error",()=>{}),s.stdout.pipe(process.stdout),s.stderr.pipe(process.stderr),s.on("error",n),s.on("close",o=>{process.stdin.unpipe(s.stdin),process.stdin.pause(),process.removeListener("disconnect",n),process.connected&&process.disconnect?.(),process.exitCode=typeof o=="number"?o:1})})}process.argv[1]===p&&process.platform==="linux"&&(process.argv[2]==="home"?l():process.argv[2]==="process"?x():process.exit(1));export{p as codexLifecycleGuardPath,L as startPrivateCodexHomeGuard};
@@ -0,0 +1,8 @@
1
+ import type { PrivateCodexRunner } from './codex-executor.js';
2
+ /** Per-invocation permissions; never modifies the operator's configuration. */
3
+ export declare function createPrivateCodexScopedRunner(projectRoot: string, base: PrivateCodexRunner, options: {
4
+ readonly userHome?: string;
5
+ readonly codexHome?: string;
6
+ readonly credentialSourceHome?: string;
7
+ readonly gitControlDirectories: readonly string[];
8
+ }): Promise<PrivateCodexRunner>;
@@ -0,0 +1 @@
1
+ import{randomBytes as g}from"node:crypto";import{accessSync as D,constants as J,lstatSync as S,readdirSync as N,realpathSync as u}from"node:fs";import{homedir as R}from"node:os";import{createRequire as k}from"node:module";import{basename as $,delimiter as P,dirname as x,join as a,resolve as l,sep as b}from"node:path";import{gitLifecycleRuntimeDirectory as _}from"../git/git-lifecycle-store.js";function E(p){const o=new Set;for(const t of p){const r=S(t);if(!r.isDirectory()||r.isSymbolicLink()||u(t)!==t)throw new Error("private-codex-root-state-isolation-unproven");for(const s of N(t)){if(!s.startsWith("neocortex-"))continue;const d=a(t,s),c=S(d);if(!/^[A-Za-z0-9._-]{1,128}$/.test(s)||c.isSymbolicLink()||!c.isDirectory()&&!c.isFile())throw new Error("private-codex-root-state-isolation-unproven");if(o.add(d),o.size>64)throw new Error("private-codex-root-state-isolation-unproven")}}return[...o].sort()}function C(){for(const p of(process.env.PATH??"").split(P).filter(Boolean))try{const o=u(a(p,"codex"));if(D(o,J.X_OK),!S(o).isFile())continue;if($(o)!=="codex.js"||$(x(o))!=="bin")return[x(o)];const t=[x(x(o))],r=process.arch==="x64"?"@openai/codex-linux-x64":process.arch==="arm64"?"@openai/codex-linux-arm64":void 0;if(r)try{t.push(u(x(k(o).resolve(`${r}/package.json`))))}catch{}return[...new Set(t)]}catch{}throw new Error("private-codex-version-unavailable")}async function M(p,o,t){const r=u(l(p)),s=Object.freeze([...t.gitControlDirectories]),d=t.userHome??R(),c=t.codexHome??process.env.CODEX_HOME??a(d,".codex"),O=C();if(O.some(e=>[b,l(d),l(c),r].includes(e)||e.startsWith(r+b)))throw new Error("private-codex-executable-scope-unsafe");const j=await _(r),y=E(s),i={":root":"deny",":minimal":"read",[r]:"write",[a(d,".ssh")]:"deny",[a(c,"auth.json")]:"deny"};if(t.credentialSourceHome){const e=l(t.credentialSourceHome),n=l(c);i[e]="deny",n!==e&&!n.startsWith(e+b)&&(i[n]="deny"),delete i[a(c,"auth.json")]}for(const e of O)i[e]="read";for(const e of s)i[e]="read";i[a(r,".git")]="read",i[j]="deny";for(const e of y)i[e]="deny";const h=`p222-isolated-${g(16).toString("hex")}`,w=`permissions.${h}={filesystem={${Object.entries(i).map(([e,n])=>`${JSON.stringify(e)}=${JSON.stringify(n)}`).join(",")}},network={enabled=false}}`;return async(e,n)=>{if(u(l(n.cwd))!==r)throw new Error("private-codex-execution-root-drift");if(JSON.stringify(E(s))!==JSON.stringify(y))throw new Error("private-codex-root-state-isolation-unproven");if(e[0]!=="sandbox"&&e[0]!=="exec")return o(e,n);const f=[...e];if(e[0]==="sandbox"){if(e[1]!=="-P"||e[2]!=="p222-isolated")throw new Error("private-codex-permission-profile-invalid");f[2]=h}else{const H=f.findIndex((v,m)=>v==='default_permissions="p222-isolated"'&&f[m-1]==="-c");if(H<0)throw new Error("private-codex-permission-profile-invalid");f[H]=`default_permissions="${h}"`;for(const v of y){const m=await o(["-c",w,"sandbox","-P",h,"--","sh","-c",'test ! -r "$1"',"sh",v],{cwd:r,timeoutMs:1e4,maxOutputBytes:16384});if(m.exitCode!==0||m.timedOut||m.outputExceeded||JSON.stringify(E(s))!==JSON.stringify(y))throw new Error("private-codex-root-state-isolation-unproven")}}return o(e[0]==="exec"?["exec","-c",w,...f.slice(1)]:["-c",w,...f],n)}}export{M as createPrivateCodexScopedRunner};
@@ -1,3 +1,4 @@
1
+ import { type PrivateYoloSkippedPredecessor, type PrivateQaSkippedPredecessor, type PrivateQaStructuralAdmission } from './shared-private-admission-types.js';
1
2
  export declare const PRIVATE_EXECUTION_PUBLIC_INSTRUCTION_V1 = "# Neocortex private execution pending\n\nThe authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.";
2
3
  export declare const PRIVATE_REPORT_PUBLIC_INSTRUCTION_V1 = "# Private review report ready\n\nThe compatible local client must consume the one-time report and save it in owner-private storage. No report content is included in this public response.";
3
4
  /** Public token only; the protected QA step identifier never ships in the client. */
@@ -19,7 +20,22 @@ export interface PrivateExecutionCheckpointRootActionV1 {
19
20
  readonly stepId: string;
20
21
  readonly publicSafe: true;
21
22
  }
22
- export type PrivateExecutionRootActionV1 = PrivateExecutionSetupRootActionV1 | PrivateExecutionCheckpointRootActionV1;
23
+ export type PrivateExecutionRootActionV1 = PrivateExecutionSetupRootActionV1 | PrivateExecutionCheckpointRootActionV1 | (Omit<PrivateExecutionCheckpointRootActionV1, 'action'> & {
24
+ readonly action: 'review-qa-candidate';
25
+ readonly skippedPredecessors: readonly PrivateQaSkippedPredecessor[];
26
+ readonly structuralPrecheck: PrivateQaStructuralAdmission;
27
+ }) | (Omit<PrivateExecutionCheckpointRootActionV1, 'action'> & {
28
+ readonly action: 'review-test-validation-candidate';
29
+ readonly skippedPredecessors: readonly PrivateYoloSkippedPredecessor[];
30
+ }) | (Omit<PrivateExecutionCheckpointRootActionV1, 'action'> & {
31
+ readonly action: 'review-diagnosis-candidate' | 'review-research-candidate' | 'review-specification-candidate' | 'review-tasks-candidate' | 'review-implementation-candidate' | 'review-refactor-advisory-candidate' | 'review-project-memory-candidate';
32
+ });
33
+ /** A closed public selector is not an executable private stage or its receipt. */
34
+ export declare function isPrivatePlanningRootPublicEnvelope(value: unknown, expected: {
35
+ readonly claimId: string;
36
+ readonly epicId: string;
37
+ readonly memoryReceiptId?: string;
38
+ }): boolean;
23
39
  /** Reject a prompt-shaped server regression before any CLI output or writeback. */
24
40
  export declare function isPrivateExecutionPublicEnvelope(value: unknown): boolean;
25
41
  export interface PrivateExecutionPublicBindingV1 {
@@ -1,5 +1,13 @@
1
- import{createHash as u}from"node:crypto";const v=`# Neocortex private execution pending
1
+ import{isPrivateYoloSkippedPredecessors as b,isPrivateQaSkippedPredecessors as S,isPrivateQaStructuralAdmission as w}from"./shared-private-admission-types.js";import{createHash as I}from"node:crypto";const l=`# Neocortex private execution pending
2
2
 
3
- The authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.`,y=`# Private review report ready
3
+ The authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.`,v=`# Private review report ready
4
4
 
5
- The compatible local client must consume the one-time report and save it in owner-private storage. No report content is included in this public response.`,S="step-8721319d";function V(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;const a=n,i=a.metadata;if(Object.keys(a).sort().join(",")!=="instructions,metadata"||a.instructions!==v&&a.instructions!==y||!i||typeof i!="object"||Array.isArray(i))return!1;const e=i,s=e.privateExecution;let t;try{t=b(s)}catch{return!1}if(t.schemaVersion!==11&&a.instructions!==v)return!1;if(t.schemaVersion===2)return Object.keys(e).sort().join(",")===["mode","storyId","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&(e.mode==="step"&&(e.resolvedTrigger==="research"||e.resolvedTrigger==="write-spec"||e.resolvedTrigger==="create-tasks"||e.resolvedTrigger==="implement")&&t.binding.commandId===e.resolvedTrigger||e.mode==="pipeline"&&e.resolvedTrigger==="exec"&&t.binding.commandId==="exec")&&e.storyId===t.binding.storyId&&e.stepId===t.binding.stepId;if(t.schemaVersion===3){const m=e.epicClaim,c=m&&typeof m=="object"&&!Array.isArray(m)?m:void 0;return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution","epicClaim"].sort().join(",")&&(e.mode==="create-epic"&&e.resolvedTrigger==="create-epic"&&t.binding.commandId==="create-epic"&&t.binding.writeSetId===void 0||e.mode==="step"&&e.resolvedTrigger==="idea-diagnose"&&t.binding.commandId==="idea-diagnose"&&t.binding.writeSetId==="idea-diagnosis-v1")&&e.stepId===t.binding.stepId&&!!c&&Object.keys(c).sort().join(",")===["schemaVersion","claimId","epicId","outcome","publicSafe"].sort().join(",")&&c.schemaVersion===1&&c.outcome==="reserved"&&c.publicSafe===!0&&c.claimId===t.binding.claimId&&c.epicId===t.binding.epicId}if(t.schemaVersion===4){const m=e.mode==="utility"&&e.resolvedTrigger==="sync-openapi"&&t.binding.commandId==="sync-openapi"&&t.binding.writeSetId==="sync-openapi-contract-v1"||e.mode==="utility"&&e.resolvedTrigger==="chaos-plan"&&t.binding.commandId==="chaos-plan"&&t.binding.writeSetId==="chaos-quarterly-v1"||e.mode==="tech-debt"&&e.resolvedTrigger==="tech-debt"&&t.binding.commandId==="tech-debt"&&t.binding.writeSetId==="tech-debt-registry-v1";return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.stepId===t.binding.stepId&&m}if(t.schemaVersion===11)return a.instructions===y&&Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="ui-ux-review"&&e.resolvedTrigger==="ui-ux-review"&&e.stepId===t.binding.stepId;if(t.schemaVersion===5)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger===t.binding.commandId&&e.stepId===t.binding.stepId&&(t.binding.commandId==="arch-prd"&&t.binding.writeSetId==="arch-prd-docs-v1"||t.binding.commandId==="arch-architecture"&&t.binding.writeSetId==="arch-architecture-doc-v1"||t.binding.commandId==="arch-fitness-functions"&&t.binding.writeSetId==="arch-fitness-tools-v1"||t.binding.commandId==="arch-api-contracts"&&t.binding.writeSetId==="arch-api-contracts-docs-v1"||t.binding.commandId==="arch-api-integrations"&&t.binding.writeSetId==="arch-api-integrations-doc-v1"||t.binding.commandId==="arch-database"&&t.binding.writeSetId==="arch-database-doc-v1"||t.binding.commandId==="arch-security"&&t.binding.writeSetId==="arch-security-doc-v1"||t.binding.commandId==="arch-design-system"&&t.binding.writeSetId==="arch-design-system-doc-v1"||t.binding.commandId==="arch-performance"&&t.binding.writeSetId==="arch-performance-doc-v1"||t.binding.commandId==="arch-testing"&&t.binding.writeSetId==="arch-testing-doc-v1"||t.binding.commandId==="arch-infrastructure"&&t.binding.writeSetId==="arch-infrastructure-doc-v1"||t.binding.commandId==="arch-review"&&t.binding.writeSetId==="arch-review-doc-v1"||t.binding.commandId==="update-memory"&&t.binding.writeSetId==="arch-memory-canonical-v1");if(t.schemaVersion===6)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-pacts"&&e.stepId===t.binding.stepId;if(t.schemaVersion===7)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="arch-ux-design"&&e.stepId===t.binding.stepId;if(t.schemaVersion===8)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="idea-research"&&e.stepId===t.binding.stepId&&t.binding.commandId==="idea-research"&&t.binding.writeSetId==="idea-research-v1";if(t.schemaVersion===9)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-epic"&&e.stepId===t.binding.stepId&&t.binding.commandId==="generate-epic"&&t.binding.writeSetId==="generate-epic-v1";if(t.schemaVersion===10)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="utility"&&e.resolvedTrigger==="property-test"&&e.stepId===t.binding.stepId&&t.binding.commandId==="property-test";const r=e.privateExecutionRootAction,d=e.stepId===S,h=e.mutationQaFeature,p=h&&typeof h=="object"&&!Array.isArray(h)?h:void 0,l=["mode","storyId","stepId","resolvedTrigger","gitLifecycleGraphAuthority","privateExecution",...d?["mutationQaFeature"]:[],...r===void 0?[]:["privateExecutionRootAction"]],I=e.gitLifecycleGraphAuthority,g=I&&typeof I=="object"&&!Array.isArray(I)?I:void 0,o=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return(!d||!!p&&Object.keys(p).sort().join(",")===["schemaVersion","id","enabled","publicSafe"].sort().join(",")&&p.schemaVersion===1&&p.id==="mutation-testing"&&typeof p.enabled=="boolean"&&p.publicSafe===!0)&&Object.keys(e).sort().join(",")===l.sort().join(",")&&e.mode==="yolo"&&e.resolvedTrigger==="yolo"&&typeof e.storyId=="string"&&typeof e.stepId=="string"&&!!g&&g.storyId===e.storyId&&g.graphRevision===t.binding.graphRevision&&t.binding.commandId==="yolo"&&t.binding.stepId===e.stepId&&(r===void 0||!!o&&Object.keys(o).sort().join(",")===["schemaVersion","action","storyId","executionBranch","graphRevision","publicSafe",...o.action==="checkpoint-epic-story"?["stepId"]:[]].sort().join(",")&&o.schemaVersion===1&&(o.action==="prepare-epic-checkout"||o.action==="checkpoint-epic-story")&&(o.action!=="checkpoint-epic-story"||o.stepId===e.stepId)&&o.publicSafe===!0&&o.storyId===e.storyId&&o.storyId===g.storyId&&o.executionBranch===g.executionBranch&&o.graphRevision===g.graphRevision)}function j(n){return u("sha256").update("private-step-state-v1\0").update(JSON.stringify(n)).digest("hex")}function b(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("private-execution-descriptor-invalid");const i=n,e=i.binding,s=i.schemaVersion===2||i.schemaVersion===3||i.schemaVersion===4||i.schemaVersion===5||i.schemaVersion===6||i.schemaVersion===7||i.schemaVersion===8||i.schemaVersion===9||i.schemaVersion===10||i.schemaVersion===11,t=s?["schemaVersion","authorityKind","projectId","commandId","stepId",...i.schemaVersion===3?["claimId","epicId",...e?.commandId==="idea-diagnose"?["writeSetId"]:[]]:i.schemaVersion===4?["writeSetId"]:i.schemaVersion===5?["targetEpicId","graphRevision","writeSetId"]:i.schemaVersion===6?["targetEpicId","graphRevision","answersSha256","specSha256","pathsSha256","endpointCount","pathCount"]:i.schemaVersion===7?["targetEpicId","graphRevision","adapterId","authoritySha256","pathsSha256","screenCount","pathCount"]:i.schemaVersion===8?["claimId","epicId","diagnosisReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:i.schemaVersion===9?["claimId","epicId","diagnosisReceiptId","researchReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:i.schemaVersion===10?["prdPath","prdSha256","planSha256","pathsSha256","aggregateCount","invariantCount","pathCount","language","numRuns"]:i.schemaVersion===11?["format"]:["storyId"],"stateSnapshotSha256","generationId","inputSha256","hostKind","hostVersion"]:["commandId","generationId","graphRevision","hostKind","hostVersion","inputSha256","projectId","stepId"];if(Object.keys(i).sort().join(",")!==["schemaVersion","leaseId","materialSha256","byteLength","expiresAt","delivery","publicSafe","binding"].sort().join(",")||i.schemaVersion!==1&&!s||i.delivery!=="private-one-time"||i.publicSafe!==!0||typeof i.leaseId!="string"||!/^px_[a-f0-9]{48}$/.test(i.leaseId)||typeof i.materialSha256!="string"||!/^[a-f0-9]{64}$/.test(i.materialSha256)||!Number.isSafeInteger(i.byteLength)||i.byteLength<1||i.byteLength>256*1024||typeof i.expiresAt!="string"||!Number.isFinite(Date.parse(i.expiresAt))||!e||Object.keys(e).sort().join(",")!==t.sort().join(",")||Object.entries(e).some(([r,d])=>r!=="schemaVersion"&&r!=="endpointCount"&&r!=="screenCount"&&r!=="pathCount"&&r!=="aggregateCount"&&r!=="invariantCount"&&r!=="numRuns"&&(typeof d!="string"||d.length<1||d.length>256))||!/^[a-f0-9]{64}$/.test(String(e.inputSha256))||e.hostKind!=="codex-cli"||s&&!/^[a-f0-9]{64}$/.test(String(e.stateSnapshotSha256))||i.schemaVersion===2&&(e.schemaVersion!==2||e.authorityKind!=="state-snapshot"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(String(e.storyId)))||i.schemaVersion===3&&(e.schemaVersion!==3||e.authorityKind!=="epic-claim"||!(e.commandId==="create-epic"&&e.writeSetId===void 0||e.commandId==="idea-diagnose"&&e.writeSetId==="idea-diagnosis-v1")||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]*$/.test(String(e.epicId)))||i.schemaVersion===4&&(e.schemaVersion!==4||e.authorityKind!=="project-snapshot"||!(e.commandId==="sync-openapi"&&e.writeSetId==="sync-openapi-contract-v1"||e.commandId==="tech-debt"&&e.writeSetId==="tech-debt-registry-v1"||e.commandId==="chaos-plan"&&e.writeSetId==="chaos-quarterly-v1"))||i.schemaVersion===11&&(e.schemaVersion!==11||e.authorityKind!=="private-report"||e.commandId!=="ui-ux-review"||!["markdown","json"].includes(String(e.format))||!/^sha256:[a-f0-9]{64}$/.test(String(e.generationId))||i.materialSha256!==String(e.generationId).slice(7))||i.schemaVersion===5&&(e.schemaVersion!==5||e.authorityKind!=="architecture-stage"||!(e.commandId==="arch-prd"&&e.writeSetId==="arch-prd-docs-v1"||e.commandId==="arch-architecture"&&e.writeSetId==="arch-architecture-doc-v1"||e.commandId==="arch-fitness-functions"&&e.writeSetId==="arch-fitness-tools-v1"||e.commandId==="arch-api-contracts"&&e.writeSetId==="arch-api-contracts-docs-v1"||e.commandId==="arch-api-integrations"&&e.writeSetId==="arch-api-integrations-doc-v1"||e.commandId==="arch-database"&&e.writeSetId==="arch-database-doc-v1"||e.commandId==="arch-security"&&e.writeSetId==="arch-security-doc-v1"||e.commandId==="arch-design-system"&&e.writeSetId==="arch-design-system-doc-v1"||e.commandId==="arch-performance"&&e.writeSetId==="arch-performance-doc-v1"||e.commandId==="arch-testing"&&e.writeSetId==="arch-testing-doc-v1"||e.commandId==="arch-infrastructure"&&e.writeSetId==="arch-infrastructure-doc-v1"||e.commandId==="arch-review"&&e.writeSetId==="arch-review-doc-v1"||e.commandId==="update-memory"&&e.writeSetId==="arch-memory-canonical-v1")||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision)))||i.schemaVersion===6&&(e.schemaVersion!==6||e.authorityKind!=="pact-stage"||e.commandId!=="generate-pacts"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!/^[a-f0-9]{64}$/.test(String(e.answersSha256))||!/^[a-f0-9]{64}$/.test(String(e.specSha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.endpointCount)||e.endpointCount<1||e.endpointCount>256||!Number.isSafeInteger(e.pathCount)||e.pathCount<e.endpointCount||e.pathCount>e.endpointCount+1)||i.schemaVersion===7&&(e.schemaVersion!==7||e.authorityKind!=="ux-stage"||e.commandId!=="arch-ux-design"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!["storybook-react-vite","storybook-nextjs-vite"].includes(String(e.adapterId))||!/^[a-f0-9]{64}$/.test(String(e.authoritySha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.screenCount)||e.screenCount<1||e.screenCount>48||!Number.isSafeInteger(e.pathCount)||e.pathCount!==e.screenCount*6+3)||i.schemaVersion===8&&(e.schemaVersion!==8||e.authorityKind!=="planning-stage"||e.commandId!=="idea-research"||e.writeSetId!=="idea-research-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(r=>!/^[a-f0-9]{64}$/.test(String(r))))||i.schemaVersion===9&&(e.schemaVersion!==9||e.authorityKind!=="planning-generation"||e.commandId!=="generate-epic"||e.writeSetId!=="generate-epic-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.researchReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(r=>!/^[a-f0-9]{64}$/.test(String(r))))||i.schemaVersion===10&&(e.schemaVersion!==10||e.authorityKind!=="property-test-plan"||e.commandId!=="property-test"||!["prd.md","docs/architecture/prd.md"].includes(String(e.prdPath))||[e.prdSha256,e.planSha256,e.pathsSha256].some(r=>!/^[a-f0-9]{64}$/.test(String(r)))||!Number.isSafeInteger(e.aggregateCount)||e.aggregateCount<1||e.aggregateCount>64||!Number.isSafeInteger(e.invariantCount)||e.invariantCount<e.aggregateCount||e.invariantCount>1024||e.pathCount!==e.aggregateCount||!["typescript","python"].includes(String(e.language))||![100,1e3,1e4].includes(e.numRuns))||a&&Object.entries(a).some(([r,d])=>e[r]!==d))throw new Error("private-execution-descriptor-invalid");return i}function f(n,a,i=Date.now()){if(typeof a!="string"||i>=Date.parse(n.expiresAt)||Buffer.byteLength(a,"utf8")!==n.byteLength||u("sha256").update(a,"utf8").digest("hex")!==n.materialSha256)throw new Error("private-execution-material-invalid");return a}async function x(n,a,i,e=Date.now()){const s=b(n,a);if(e>=Date.parse(s.expiresAt))throw new Error("private-execution-material-expired");const t=await i({leaseId:s.leaseId,...s.binding});if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).sort().join(",")!=="material,schemaVersion"||t.schemaVersion!==1)throw new Error("private-execution-delivery-invalid");return f(s,t.material,Math.max(e,Date.now()))}export{v as PRIVATE_EXECUTION_PUBLIC_INSTRUCTION_V1,S as PRIVATE_MUTATION_QA_GATE_STEP_TOKEN,y as PRIVATE_REPORT_PUBLIC_INSTRUCTION_V1,x as consumePrivateExecutionDelivery,V as isPrivateExecutionPublicEnvelope,b as parsePrivateExecutionDescriptor,j as privateExecutionStateSnapshotSha256,f as verifyPrivateExecutionMaterial};
5
+ The compatible local client must consume the one-time report and save it in owner-private storage. No report content is included in this public response.`,j="step-8721319d";function R(o,n){const i=d=>d!==null&&typeof d=="object"&&!Array.isArray(d)?d:void 0,e=i(o),s=i(e?.metadata),t=i(s?.planningRootContinuation);if(!e||Object.keys(e).sort().join("|")!=="instructions|metadata"||!s||Object.keys(s).sort().join("|")!=="epicId|mode|planningRootContinuation|resolvedTrigger"||s.mode!=="continuity"||s.resolvedTrigger!=="create-epic"||!t||Object.keys(t).sort().join("|")!==["schemaVersion","owner","claimId","epicId","nextAction","nextCommand","planningComplete","publicSafe",...t.planningComplete===!0?["memoryReceiptId"]:[]].sort().join("|")||t.schemaVersion!==1||t.owner!=="root"||t.nextAction!==(t.nextCommand==="none"?"complete":t.nextCommand==="refresh-memory"?"root-memory":"delegate-stage")||t.planningComplete!==(t.nextCommand==="none")||t.publicSafe!==!0||t.claimId!==n.claimId||t.epicId!==n.epicId||s.epicId!==n.epicId||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(n.claimId)||!/^P[1-9][0-9]{0,11}$/.test(n.epicId)||!["idea-research","generate-epic","refresh-memory","none"].includes(String(t.nextCommand)))return!1;if(t.planningComplete===!0)return typeof n.memoryReceiptId=="string"&&/^[a-f0-9]{64}$/.test(n.memoryReceiptId)&&t.memoryReceiptId===n.memoryReceiptId&&e.instructions===`# Root planning complete
6
+
7
+ P01-P04 planning checkpoints were independently accepted. The client must acknowledge the same durable creation claim with the verified memory checkpoint. Stories, physical QA, provider and terminal accounting remain pending.`;if(t.nextCommand==="refresh-memory")return e.instructions===`# Root planning memory checkpoint
8
+
9
+ Reopen the committed P03 with planning-generation verify. Run local refresh-memory with an accurate note about the accepted plan; verify every project-memory target with refresh-memory --verify. Independently review and seal the physical memory checkpoint before resuming the original create-epic request. Do not implement stories or release quota.`;const a=t.nextCommand==="idea-research"?`Before P02, the root must collect public Context7 and official web references for this epic and record provenance in docs/research/epic-${t.epicId}/root-sources.md and root-sources.json. Keep private material out of external queries. The private executor has no web or MCP access.
10
+
11
+ `:"";return e.instructions===`# Root planning continuation
12
+
13
+ ${a}Run *${t.nextCommand} ${t.epicId}. Independently review and seal its physical artifacts before resuming the original create-epic request. No story execution or terminal effect is authorized.`}function T(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;const n=o,i=n.metadata;if(Object.keys(n).sort().join(",")!=="instructions,metadata"||n.instructions!==l&&n.instructions!==v||!i||typeof i!="object"||Array.isArray(i))return!1;const e=i,s=e.privateExecution;let t;try{t=f(s)}catch{return!1}if(t.schemaVersion!==11&&n.instructions!==l)return!1;if(t.schemaVersion===2)return Object.keys(e).sort().join(",")===["mode","storyId","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&(e.mode==="step"&&(e.resolvedTrigger==="research"||e.resolvedTrigger==="write-spec"||e.resolvedTrigger==="create-tasks"||e.resolvedTrigger==="implement")&&t.binding.commandId===e.resolvedTrigger||e.mode==="pipeline"&&e.resolvedTrigger==="exec"&&t.binding.commandId==="exec")&&e.storyId===t.binding.storyId&&e.stepId===t.binding.stepId;if(t.schemaVersion===3){const g=e.epicClaim,p=g&&typeof g=="object"&&!Array.isArray(g)?g:void 0;return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution","epicClaim"].sort().join(",")&&(e.mode==="create-epic"&&e.resolvedTrigger==="create-epic"&&t.binding.commandId==="create-epic"&&(t.binding.writeSetId===void 0||t.binding.writeSetId==="idea-diagnosis-v1"&&t.binding.stepId==="step-acd455ed")||e.mode==="step"&&e.resolvedTrigger==="idea-diagnose"&&t.binding.commandId==="idea-diagnose"&&t.binding.writeSetId==="idea-diagnosis-v1")&&e.stepId===t.binding.stepId&&!!p&&Object.keys(p).sort().join(",")===["schemaVersion","claimId","epicId","outcome","publicSafe"].sort().join(",")&&p.schemaVersion===1&&p.outcome==="reserved"&&p.publicSafe===!0&&p.claimId===t.binding.claimId&&p.epicId===t.binding.epicId}if(t.schemaVersion===4){const g=e.mode==="utility"&&e.resolvedTrigger==="sync-openapi"&&t.binding.commandId==="sync-openapi"&&t.binding.writeSetId==="sync-openapi-contract-v1"||e.mode==="utility"&&e.resolvedTrigger==="chaos-plan"&&t.binding.commandId==="chaos-plan"&&t.binding.writeSetId==="chaos-quarterly-v1"||e.mode==="tech-debt"&&e.resolvedTrigger==="tech-debt"&&t.binding.commandId==="tech-debt"&&t.binding.writeSetId==="tech-debt-registry-v1";return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.stepId===t.binding.stepId&&g}if(t.schemaVersion===11)return n.instructions===v&&Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="ui-ux-review"&&e.resolvedTrigger==="ui-ux-review"&&e.stepId===t.binding.stepId;if(t.schemaVersion===5)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger===t.binding.commandId&&e.stepId===t.binding.stepId&&(t.binding.commandId==="arch-prd"&&t.binding.writeSetId==="arch-prd-docs-v1"||t.binding.commandId==="arch-architecture"&&t.binding.writeSetId==="arch-architecture-doc-v1"||t.binding.commandId==="arch-fitness-functions"&&t.binding.writeSetId==="arch-fitness-tools-v1"||t.binding.commandId==="arch-api-contracts"&&t.binding.writeSetId==="arch-api-contracts-docs-v1"||t.binding.commandId==="arch-api-integrations"&&t.binding.writeSetId==="arch-api-integrations-doc-v1"||t.binding.commandId==="arch-database"&&t.binding.writeSetId==="arch-database-doc-v1"||t.binding.commandId==="arch-security"&&t.binding.writeSetId==="arch-security-doc-v1"||t.binding.commandId==="arch-design-system"&&t.binding.writeSetId==="arch-design-system-doc-v1"||t.binding.commandId==="arch-performance"&&t.binding.writeSetId==="arch-performance-doc-v1"||t.binding.commandId==="arch-testing"&&t.binding.writeSetId==="arch-testing-doc-v1"||t.binding.commandId==="arch-infrastructure"&&t.binding.writeSetId==="arch-infrastructure-doc-v1"||t.binding.commandId==="arch-review"&&t.binding.writeSetId==="arch-review-doc-v1"||t.binding.commandId==="update-memory"&&t.binding.writeSetId==="arch-memory-canonical-v1");if(t.schemaVersion===6)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-pacts"&&e.stepId===t.binding.stepId;if(t.schemaVersion===7)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="arch-ux-design"&&e.stepId===t.binding.stepId;if(t.schemaVersion===8)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="idea-research"&&e.stepId===t.binding.stepId&&t.binding.commandId==="idea-research"&&t.binding.writeSetId==="idea-research-v1";if(t.schemaVersion===9)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-epic"&&e.stepId===t.binding.stepId&&t.binding.commandId==="generate-epic"&&t.binding.writeSetId==="generate-epic-v1";if(t.schemaVersion===10)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="utility"&&e.resolvedTrigger==="property-test"&&e.stepId===t.binding.stepId&&t.binding.commandId==="property-test";const a=e.privateExecutionRootAction,d=e.stepId===j,h=e.mutationQaFeature,m=h&&typeof h=="object"&&!Array.isArray(h)?h:void 0,y=["mode","storyId","stepId","resolvedTrigger","gitLifecycleGraphAuthority","privateExecution",...d?["mutationQaFeature"]:[],...a===void 0?[]:["privateExecutionRootAction"]],u=e.gitLifecycleGraphAuthority,c=u&&typeof u=="object"&&!Array.isArray(u)?u:void 0,r=a&&typeof a=="object"&&!Array.isArray(a)?a:void 0;return(!d||!!m&&Object.keys(m).sort().join(",")===["schemaVersion","id","enabled","publicSafe"].sort().join(",")&&m.schemaVersion===1&&m.id==="mutation-testing"&&typeof m.enabled=="boolean"&&m.publicSafe===!0)&&Object.keys(e).sort().join(",")===y.sort().join(",")&&e.mode==="yolo"&&e.resolvedTrigger==="yolo"&&typeof e.storyId=="string"&&typeof e.stepId=="string"&&!!c&&c.storyId===e.storyId&&c.graphRevision===t.binding.graphRevision&&t.binding.commandId==="yolo"&&t.binding.stepId===e.stepId&&(a===void 0||!!r&&Object.keys(r).sort().join(",")===["schemaVersion","action","storyId","executionBranch","graphRevision","publicSafe",...r.action!=="prepare-epic-checkout"?["stepId"]:[],...r.action==="review-test-validation-candidate"?["skippedPredecessors"]:[],...r.action==="review-qa-candidate"?["skippedPredecessors","structuralPrecheck"]:[]].sort().join(",")&&r.schemaVersion===1&&(r.action==="prepare-epic-checkout"||r.action==="checkpoint-epic-story"||r.action==="review-diagnosis-candidate"&&e.stepId==="step-50224b19"||r.action==="review-project-memory-candidate"&&e.stepId==="step-638cc252"||r.action==="review-research-candidate"&&e.stepId==="step-f757f6bf"||r.action==="review-specification-candidate"&&e.stepId==="step-9cd927d0"||r.action==="review-tasks-candidate"&&e.stepId==="step-a3f880e8"||r.action==="review-implementation-candidate"&&e.stepId==="step-41803e35"||r.action==="review-refactor-advisory-candidate"&&e.stepId==="step-fe2e4997"||r.action==="review-test-validation-candidate"&&e.stepId==="step-b2fe7cb5"&&b(r.skippedPredecessors)||r.action==="review-qa-candidate"&&e.stepId==="step-8721319d"&&S(r.skippedPredecessors)&&w(r.structuralPrecheck)&&r.structuralPrecheck.graphRevision===c.graphRevision&&r.structuralPrecheck.generationId===t.binding.generationId)&&(r.action==="prepare-epic-checkout"||r.stepId===e.stepId)&&r.publicSafe===!0&&r.storyId===e.storyId&&r.storyId===c.storyId&&r.executionBranch===c.executionBranch&&r.graphRevision===c.graphRevision)}function A(o){return I("sha256").update("private-step-state-v1\0").update(JSON.stringify(o)).digest("hex")}function f(o,n){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("private-execution-descriptor-invalid");const i=o,e=i.binding,s=i.schemaVersion===2||i.schemaVersion===3||i.schemaVersion===4||i.schemaVersion===5||i.schemaVersion===6||i.schemaVersion===7||i.schemaVersion===8||i.schemaVersion===9||i.schemaVersion===10||i.schemaVersion===11,t=s?["schemaVersion","authorityKind","projectId","commandId","stepId",...i.schemaVersion===3?["claimId","epicId",...e?.commandId==="idea-diagnose"||e?.writeSetId!==void 0?["writeSetId"]:[]]:i.schemaVersion===4?["writeSetId"]:i.schemaVersion===5?["targetEpicId","graphRevision","writeSetId"]:i.schemaVersion===6?["targetEpicId","graphRevision","answersSha256","specSha256","pathsSha256","endpointCount","pathCount"]:i.schemaVersion===7?["targetEpicId","graphRevision","adapterId","authoritySha256","pathsSha256","screenCount","pathCount"]:i.schemaVersion===8?["claimId","epicId","diagnosisReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:i.schemaVersion===9?["claimId","epicId","diagnosisReceiptId","researchReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:i.schemaVersion===10?["prdPath","prdSha256","planSha256","pathsSha256","aggregateCount","invariantCount","pathCount","language","numRuns"]:i.schemaVersion===11?["format"]:["storyId"],"stateSnapshotSha256","generationId","inputSha256","hostKind","hostVersion"]:["commandId","generationId","graphRevision","hostKind","hostVersion","inputSha256","projectId","stepId"];if(Object.keys(i).sort().join(",")!==["schemaVersion","leaseId","materialSha256","byteLength","expiresAt","delivery","publicSafe","binding"].sort().join(",")||i.schemaVersion!==1&&!s||i.delivery!=="private-one-time"||i.publicSafe!==!0||typeof i.leaseId!="string"||!/^px_[a-f0-9]{48}$/.test(i.leaseId)||typeof i.materialSha256!="string"||!/^[a-f0-9]{64}$/.test(i.materialSha256)||!Number.isSafeInteger(i.byteLength)||i.byteLength<1||i.byteLength>256*1024||typeof i.expiresAt!="string"||!Number.isFinite(Date.parse(i.expiresAt))||!e||Object.keys(e).sort().join(",")!==t.sort().join(",")||Object.entries(e).some(([a,d])=>a!=="schemaVersion"&&a!=="endpointCount"&&a!=="screenCount"&&a!=="pathCount"&&a!=="aggregateCount"&&a!=="invariantCount"&&a!=="numRuns"&&(typeof d!="string"||d.length<1||d.length>256))||!/^[a-f0-9]{64}$/.test(String(e.inputSha256))||e.hostKind!=="codex-cli"||s&&!/^[a-f0-9]{64}$/.test(String(e.stateSnapshotSha256))||i.schemaVersion===2&&(e.schemaVersion!==2||e.authorityKind!=="state-snapshot"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(String(e.storyId)))||i.schemaVersion===3&&(e.schemaVersion!==3||e.authorityKind!=="epic-claim"||!(e.commandId==="create-epic"&&(e.writeSetId===void 0||e.writeSetId==="idea-diagnosis-v1"&&e.stepId==="step-acd455ed")||e.commandId==="idea-diagnose"&&e.writeSetId==="idea-diagnosis-v1")||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]*$/.test(String(e.epicId)))||i.schemaVersion===4&&(e.schemaVersion!==4||e.authorityKind!=="project-snapshot"||!(e.commandId==="sync-openapi"&&e.writeSetId==="sync-openapi-contract-v1"||e.commandId==="tech-debt"&&e.writeSetId==="tech-debt-registry-v1"||e.commandId==="chaos-plan"&&e.writeSetId==="chaos-quarterly-v1"))||i.schemaVersion===11&&(e.schemaVersion!==11||e.authorityKind!=="private-report"||e.commandId!=="ui-ux-review"||!["markdown","json"].includes(String(e.format))||!/^sha256:[a-f0-9]{64}$/.test(String(e.generationId))||i.materialSha256!==String(e.generationId).slice(7))||i.schemaVersion===5&&(e.schemaVersion!==5||e.authorityKind!=="architecture-stage"||!(e.commandId==="arch-prd"&&e.writeSetId==="arch-prd-docs-v1"||e.commandId==="arch-architecture"&&e.writeSetId==="arch-architecture-doc-v1"||e.commandId==="arch-fitness-functions"&&e.writeSetId==="arch-fitness-tools-v1"||e.commandId==="arch-api-contracts"&&e.writeSetId==="arch-api-contracts-docs-v1"||e.commandId==="arch-api-integrations"&&e.writeSetId==="arch-api-integrations-doc-v1"||e.commandId==="arch-database"&&e.writeSetId==="arch-database-doc-v1"||e.commandId==="arch-security"&&e.writeSetId==="arch-security-doc-v1"||e.commandId==="arch-design-system"&&e.writeSetId==="arch-design-system-doc-v1"||e.commandId==="arch-performance"&&e.writeSetId==="arch-performance-doc-v1"||e.commandId==="arch-testing"&&e.writeSetId==="arch-testing-doc-v1"||e.commandId==="arch-infrastructure"&&e.writeSetId==="arch-infrastructure-doc-v1"||e.commandId==="arch-review"&&e.writeSetId==="arch-review-doc-v1"||e.commandId==="update-memory"&&e.writeSetId==="arch-memory-canonical-v1")||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision)))||i.schemaVersion===6&&(e.schemaVersion!==6||e.authorityKind!=="pact-stage"||e.commandId!=="generate-pacts"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!/^[a-f0-9]{64}$/.test(String(e.answersSha256))||!/^[a-f0-9]{64}$/.test(String(e.specSha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.endpointCount)||e.endpointCount<1||e.endpointCount>256||!Number.isSafeInteger(e.pathCount)||e.pathCount<e.endpointCount||e.pathCount>e.endpointCount+1)||i.schemaVersion===7&&(e.schemaVersion!==7||e.authorityKind!=="ux-stage"||e.commandId!=="arch-ux-design"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!["storybook-react-vite","storybook-nextjs-vite"].includes(String(e.adapterId))||!/^[a-f0-9]{64}$/.test(String(e.authoritySha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.screenCount)||e.screenCount<1||e.screenCount>48||!Number.isSafeInteger(e.pathCount)||e.pathCount!==e.screenCount*6+3)||i.schemaVersion===8&&(e.schemaVersion!==8||e.authorityKind!=="planning-stage"||e.commandId!=="idea-research"||e.writeSetId!=="idea-research-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(a=>!/^[a-f0-9]{64}$/.test(String(a))))||i.schemaVersion===9&&(e.schemaVersion!==9||e.authorityKind!=="planning-generation"||e.commandId!=="generate-epic"||e.writeSetId!=="generate-epic-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.researchReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(a=>!/^[a-f0-9]{64}$/.test(String(a))))||i.schemaVersion===10&&(e.schemaVersion!==10||e.authorityKind!=="property-test-plan"||e.commandId!=="property-test"||!["prd.md","docs/architecture/prd.md"].includes(String(e.prdPath))||[e.prdSha256,e.planSha256,e.pathsSha256].some(a=>!/^[a-f0-9]{64}$/.test(String(a)))||!Number.isSafeInteger(e.aggregateCount)||e.aggregateCount<1||e.aggregateCount>64||!Number.isSafeInteger(e.invariantCount)||e.invariantCount<e.aggregateCount||e.invariantCount>1024||e.pathCount!==e.aggregateCount||!["typescript","python"].includes(String(e.language))||![100,1e3,1e4].includes(e.numRuns))||n&&Object.entries(n).some(([a,d])=>e[a]!==d))throw new Error("private-execution-descriptor-invalid");return i}function V(o,n,i=Date.now()){if(typeof n!="string"||i>=Date.parse(o.expiresAt)||Buffer.byteLength(n,"utf8")!==o.byteLength||I("sha256").update(n,"utf8").digest("hex")!==o.materialSha256)throw new Error("private-execution-material-invalid");return n}async function k(o,n,i,e=Date.now()){const s=f(o,n);if(e>=Date.parse(s.expiresAt))throw new Error("private-execution-material-expired");const t=await i({leaseId:s.leaseId,...s.binding});if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).sort().join(",")!=="material,schemaVersion"||t.schemaVersion!==1)throw new Error("private-execution-delivery-invalid");return V(s,t.material,Math.max(e,Date.now()))}export{l as PRIVATE_EXECUTION_PUBLIC_INSTRUCTION_V1,j as PRIVATE_MUTATION_QA_GATE_STEP_TOKEN,v as PRIVATE_REPORT_PUBLIC_INSTRUCTION_V1,k as consumePrivateExecutionDelivery,T as isPrivateExecutionPublicEnvelope,R as isPrivatePlanningRootPublicEnvelope,f as parsePrivateExecutionDescriptor,A as privateExecutionStateSnapshotSha256,V as verifyPrivateExecutionMaterial};