@ornexus/neocortex 4.60.63 → 4.60.64

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 (135) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +23 -23
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +7 -2
  6. package/packages/client/dist/cli.js +8 -3
  7. package/packages/client/dist/commands/activate.js +8 -8
  8. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -2
  9. package/packages/client/dist/commands/architecture-non-ui-continuation.d.ts +3 -0
  10. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -0
  11. package/packages/client/dist/commands/invoke.d.ts +19 -16
  12. package/packages/client/dist/commands/invoke.js +85 -80
  13. package/packages/client/dist/commands/planning-generation.js +1 -1
  14. package/packages/client/dist/commands/planning-memory.d.ts +1 -0
  15. package/packages/client/dist/commands/planning-memory.js +1 -0
  16. package/packages/client/dist/commands/private-session.d.ts +1 -0
  17. package/packages/client/dist/commands/private-session.js +1 -0
  18. package/packages/client/dist/commands/qa-control.d.ts +4 -0
  19. package/packages/client/dist/commands/qa-control.js +1 -0
  20. package/packages/client/dist/commands/qa-scan-browser-launch.d.ts +8 -0
  21. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -0
  22. package/packages/client/dist/commands/qa-scan-browser-route.d.ts +3 -0
  23. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -0
  24. package/packages/client/dist/commands/qa-scan-capture.d.ts +43 -0
  25. package/packages/client/dist/commands/qa-scan-capture.js +5 -5
  26. package/packages/client/dist/commands/qa-scan-discovery.d.ts +7 -0
  27. package/packages/client/dist/commands/qa-scan-discovery.js +3 -3
  28. package/packages/client/dist/commands/qa-scan-review.d.ts +8 -1
  29. package/packages/client/dist/commands/qa-scan-review.js +5 -5
  30. package/packages/client/dist/commands/qa-synthetic-backend-capture.d.ts +62 -0
  31. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -0
  32. package/packages/client/dist/commands/qa-synthetic-backend-review.d.ts +104 -0
  33. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -0
  34. package/packages/client/dist/commands/qa-synthetic-backend.d.ts +52 -0
  35. package/packages/client/dist/commands/qa-synthetic-backend.js +7 -0
  36. package/packages/client/dist/commands/qa-synthetic-broker-port.d.ts +30 -0
  37. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -0
  38. package/packages/client/dist/commands/qa-synthetic-browser.d.ts +1 -0
  39. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -0
  40. package/packages/client/dist/commands/refactor-characterization.d.ts +12 -3
  41. package/packages/client/dist/commands/refactor-characterization.js +21 -12
  42. package/packages/client/dist/commands/refactor-control.d.ts +17 -0
  43. package/packages/client/dist/commands/refactor-control.js +3 -0
  44. package/packages/client/dist/commands/refactor-cpp-assertions.d.ts +4 -0
  45. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -0
  46. package/packages/client/dist/commands/refactor-review.d.ts +13 -0
  47. package/packages/client/dist/commands/refactor-review.js +6 -5
  48. package/packages/client/dist/commands/refactor-root.d.ts +165 -1
  49. package/packages/client/dist/commands/refactor-root.js +12 -7
  50. package/packages/client/dist/commands/refresh-memory.d.ts +1 -0
  51. package/packages/client/dist/commands/refresh-memory.js +3 -3
  52. package/packages/client/dist/commands/shared-architecture-non-ui-contract.d.ts +19 -0
  53. package/packages/client/dist/commands/shared-architecture-non-ui-contract.js +1 -0
  54. package/packages/client/dist/errors/error-messages.js +1 -1
  55. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  56. package/packages/client/dist/git/git-lifecycle-store.js +7 -7
  57. package/packages/client/dist/license/license-client.d.ts +3 -1
  58. package/packages/client/dist/license/license-client.js +1 -1
  59. package/packages/client/dist/memory/project-memory-path-scope.d.ts +4 -0
  60. package/packages/client/dist/memory/project-memory-path-scope.js +1 -0
  61. package/packages/client/dist/memory/project-memory-writer.d.ts +4 -1
  62. package/packages/client/dist/memory/project-memory-writer.js +16 -16
  63. package/packages/client/dist/private-execution/clean-baseline.d.ts +6 -0
  64. package/packages/client/dist/private-execution/clean-baseline.js +2 -2
  65. package/packages/client/dist/private-execution/codex-executor.d.ts +48 -4
  66. package/packages/client/dist/private-execution/codex-executor.js +9 -2
  67. package/packages/client/dist/private-execution/codex-host-runtime.d.ts +10 -0
  68. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -0
  69. package/packages/client/dist/private-execution/codex-lifecycle-guard.d.ts +4 -0
  70. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -0
  71. package/packages/client/dist/private-execution/codex-scoped-permissions.d.ts +8 -0
  72. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -0
  73. package/packages/client/dist/private-execution/delivery.d.ts +18 -1
  74. package/packages/client/dist/private-execution/delivery.js +11 -3
  75. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +112 -0
  76. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -0
  77. package/packages/client/dist/private-execution/frozen-handoff.d.ts +2 -0
  78. package/packages/client/dist/private-execution/frozen-handoff.js +7 -0
  79. package/packages/client/dist/private-execution/implementation-validation.d.ts +24 -0
  80. package/packages/client/dist/private-execution/implementation-validation.js +2 -0
  81. package/packages/client/dist/private-execution/isolated-admission.d.ts +11 -7
  82. package/packages/client/dist/private-execution/isolated-admission.js +17 -10
  83. package/packages/client/dist/private-execution/isolated-session.d.ts +68 -0
  84. package/packages/client/dist/private-execution/isolated-session.js +5 -2
  85. package/packages/client/dist/private-execution/pact-test-source.d.ts +1 -1
  86. package/packages/client/dist/private-execution/pact-test-source.js +1 -1
  87. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -0
  88. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  89. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +13 -0
  90. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -3
  91. package/packages/client/dist/private-execution/planning-memory-checkpoint.d.ts +32 -0
  92. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -0
  93. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  94. package/packages/client/dist/private-execution/root-checkpoint.js +1 -1
  95. package/packages/client/dist/private-execution/root-memory-git-evidence.d.ts +30 -0
  96. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -0
  97. package/packages/client/dist/private-execution/root-memory-recovery.d.ts +16 -0
  98. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -0
  99. package/packages/client/dist/private-execution/root-memory-request.d.ts +28 -0
  100. package/packages/client/dist/private-execution/root-memory-request.js +1 -0
  101. package/packages/client/dist/private-execution/root-memory-scope.d.ts +28 -0
  102. package/packages/client/dist/private-execution/root-memory-scope.js +1 -0
  103. package/packages/client/dist/private-execution/root-memory-writer.d.ts +22 -0
  104. package/packages/client/dist/private-execution/root-memory-writer.js +1 -0
  105. package/packages/client/dist/private-execution/session-lease.d.ts +19 -0
  106. package/packages/client/dist/private-execution/session-lease.js +1 -0
  107. package/packages/client/dist/private-execution/ux-source-validation.js +1 -1
  108. package/packages/client/dist/runner-cli.js +0 -0
  109. package/packages/client/dist/yolo/change-evidence-collector.d.ts +2 -2
  110. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  111. package/packages/client/dist/yolo/spec-envelope-collector.js +2 -2
  112. package/packages/shared/dist/invocation/index.js +4 -2
  113. package/packages/shared/dist/invocation/packed-invoke.d.ts +12 -0
  114. package/packages/shared/dist/invocation/packed-invoke.js +58 -0
  115. package/packages/shared/dist/invocation/packed-invoke.test.d.ts +1 -0
  116. package/packages/shared/dist/invocation/packed-invoke.test.js +21 -0
  117. package/packages/shared/dist/planning/diagnosis-state.js +5 -2
  118. package/packages/shared/dist/private-qa-structural-admission.js +14 -0
  119. package/packages/shared/dist/private-yolo-predecessor-decision.js +32 -0
  120. package/packages/shared/dist/project-memory-targets.js +243 -0
  121. package/packages/shared/dist/project-validation-commands.js +96 -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/gemini-cli/agent.md +2 -2
  134. package/targets-stubs/opencode/neocortex-root.md +1 -1
  135. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,5 +1,6 @@
1
- import{createHash as H,randomUUID as C}from"node:crypto";import{closeSync as k,existsSync as R,fsyncSync as O,linkSync as j,lstatSync as x,openSync as N,readFileSync as F,realpathSync as L,unlinkSync as I,writeFileSync as V}from"node:fs";import{join as p,resolve as B}from"node:path";import{readRootRefactorBaseline as D,runRootRefactorCharacterization as T}from"./refactor-characterization.js";import{privateRefactorDirectory as z,readPrivateRefactorAdmission as W,verifyRootRefactor as q}from"./refactor-root.js";const l=/^[a-f0-9]{64}$/,S=128*1024;function v(t){return H("sha256").update(t).digest("hex")}function y(t,e){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).sort().join("\0")===[...e].sort().join("\0")}function J(t,e){return typeof t=="string"&&t.length>=30&&t.length<=e&&!/[\x00-\x1f\x7f]/.test(t)}function g(t,e,n){if(!l.test(e)||!l.test(n))throw new Error("refactor-root-review-unverified");const o=B(t),i=W(o,e),s=D(o,n),r=q(o,e),c=T(o,e,s.testFiles.map(f=>f.path),s.dependencies.map(f=>f.path),"after",!0,s.causalPath,n,s.schemaVersion===2?"vitest":"native");if(s.admissionSha256!==e||s.sourceHead!==i.sourceHead||c.baselineSha256!==n||!c.testsPassedObserved||!c.causalFailureObserved||r.changedFileCount<2)throw new Error("refactor-root-review-unverified");return Object.freeze({root:o,storyId:i.storyId,sourceHead:i.sourceHead,admissionSha256:e,baselineSha256:n,candidateSha256:c.candidateSha256,testFiles:s.testFiles,changedFileCount:r.changedFileCount})}function P(t,e){if(!y(e,["schemaVersion","kind","storyId","sourceHead","admissionSha256","baselineSha256","candidateSha256","verdict","behaviorRationale","assertions"])||e.schemaVersion!==1||e.kind!=="root-refactor-semantic-review"||e.storyId!==t.storyId||e.sourceHead!==t.sourceHead||e.admissionSha256!==t.admissionSha256||e.baselineSha256!==t.baselineSha256||e.candidateSha256!==t.candidateSha256||e.verdict!=="approved"||!J(e.behaviorRationale,1e3)||!Array.isArray(e.assertions)||e.assertions.length<t.testFiles.length||e.assertions.length>64||Buffer.byteLength(JSON.stringify(e))>S)throw new Error("refactor-root-review-unverified");const n=new Map(t.testFiles.map(r=>[r.path,r.sha256])),o=new Map;for(const[r,c]of n){const f=p(t.root,r),a=x(f);if(!a.isFile()||a.isSymbolicLink()||L(f)!==f||a.size<1||a.size>8*1024*1024)throw new Error("refactor-root-review-unverified");const d=F(f);if(v(d)!==c)throw new Error("refactor-root-review-unverified");o.set(r,new TextDecoder("utf-8",{fatal:!0}).decode(d).split(/\r?\n/))}const i=new Set,s=new Set;for(const r of e.assertions){if(!y(r,["testPath","assertionLine","rationale"])||typeof r.testPath!="string"||!n.has(r.testPath)||!Number.isSafeInteger(r.assertionLine)||Number(r.assertionLine)<1||Number(r.assertionLine)>(o.get(r.testPath)?.length??0)||!J(r.rationale,500))throw new Error("refactor-root-review-unverified");const c=`${r.testPath}:${r.assertionLine}`;if(i.has(c))throw new Error("refactor-root-review-unverified");i.add(c),s.add(r.testPath);const f=o.get(r.testPath)[Number(r.assertionLine)-1],a=r.testPath.endsWith(".py")?(f.split("#")[0]??"").trimStart():f.split("//")[0]??"";if(!(r.testPath.endsWith(".py")?/^self\.assert[A-Z][A-Za-z0-9_]*\s*\(/.test(a)||/^assert\s+\S/.test(a):/\b(?:assert|expect|throw)\b/.test(a)))throw new Error("refactor-root-review-unverified")}if(s.size!==n.size)throw new Error("refactor-root-review-unverified");return e}function $(t,e){return Object.freeze({schemaVersion:1,kind:"root-refactor-semantic-acceptance",storyId:t.storyId,sourceHead:t.sourceHead,admissionSha256:t.admissionSha256,baselineSha256:t.baselineSha256,candidateSha256:t.candidateSha256,reviewSha256:v(`root-refactor-semantic-review-v1\0${JSON.stringify(e)}`),testFileCount:t.testFiles.length,assertionCount:e.assertions.length,changedFileCount:t.changedFileCount,executionVerified:!0,qaAccepted:!0,gitCommitAuthorized:!1,publicSafe:!0})}function A(t,e,n){return p(z(t),`review-${e}-${n}.json`)}function E(t){const e=x(t);if(!e.isFile()||e.isSymbolicLink()||e.uid!==process.getuid?.()||(e.mode&63)!==0||e.size<100||e.size>S+4096)throw new Error("refactor-root-review-unverified");const n=F(t),o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));if(!y(o,["schemaVersion","kind","report","receipt","checksumSha256"])||o.schemaVersion!==1||o.kind!=="root-refactor-semantic-record"||typeof o.checksumSha256!="string"||!l.test(o.checksumSha256)||!n.equals(Buffer.from(`${JSON.stringify(o)}
2
- `))||o.checksumSha256!==v(`root-refactor-semantic-record-v1\0${JSON.stringify({report:o.report,receipt:o.receipt})}`))throw new Error("refactor-root-review-unverified");return o}function M(t,e,n,o){try{const i=g(t,e,n),s=P(i,o),r=$(i,s),c=A(i.root,e,i.candidateSha256),f={report:s,receipt:r},a={schemaVersion:1,kind:"root-refactor-semantic-record",...f,checksumSha256:v(`root-refactor-semantic-record-v1\0${JSON.stringify(f)}`)},d=Buffer.from(`${JSON.stringify(a)}
3
- `);if(R(c)){const m=E(c);if(JSON.stringify(m.report)!==JSON.stringify(s)||JSON.stringify(m.receipt)!==JSON.stringify(r))throw new Error("refactor-root-review-conflict");return r}const h=z(i.root),u=p(h,`review-${C()}.tmp`),w=N(u,"wx",384);try{V(w,d),O(w)}finally{k(w)}try{if(g(i.root,e,n).candidateSha256!==r.candidateSha256)throw new Error("refactor-root-review-unverified");j(u,c);const b=N(h,"r");try{O(b)}finally{k(b)}}finally{R(u)&&I(u)}return E(c),r}catch(i){throw i instanceof Error&&i.message==="refactor-root-review-conflict"?i:new Error("refactor-root-review-unverified")}}function _(t,e,n){try{const o=g(t,e,n),i=E(A(o.root,e,o.candidateSha256));if(!y(i,["schemaVersion","kind","report","receipt","checksumSha256"]))throw new Error("refactor-root-review-unverified");const s=P(o,i.report),r=$(o,s);if(JSON.stringify(i.receipt)!==JSON.stringify(r))throw new Error("refactor-root-review-unverified");return r}catch{throw new Error("refactor-root-review-unverified")}}async function G(t){const e=t[0];let n="",o="",i="",s=!1,r=!1,c="plain";const f=new Set;try{if(e!=="review-accept"&&e!=="review-status")throw new Error("refactor-root-review-arguments-invalid");for(let d=1;d<t.length;d++){const h=t[d];if(f.has(h))throw new Error("refactor-root-review-arguments-invalid");f.add(h);const u=()=>{const w=t[++d];if(!w||w.startsWith("--"))throw new Error("refactor-root-review-arguments-invalid");return w};if(h==="--project-root")n=u();else if(h==="--admission-sha")o=u();else if(h==="--baseline-sha")i=u();else if(h==="--authorize-run")s=!0;else if(h==="--authorize-root-review")r=!0;else if(h==="--format")c=u();else throw new Error("refactor-root-review-arguments-invalid")}if(!n||!l.test(o)||!l.test(i)||!["plain","json"].includes(c)||!s||r!==(e==="review-accept"))throw new Error("refactor-root-review-arguments-invalid");let a;if(e==="review-accept"){let d="";for await(const w of process.stdin)if(d+=String(w),Buffer.byteLength(d)>S)throw new Error("refactor-root-review-unverified");const{parseDocument:h}=await import("yaml"),u=h(d,{strict:!0,uniqueKeys:!0,schema:"core",customTags:[]});if(u.errors.length||u.warnings.length)throw new Error("refactor-root-review-unverified");a=M(n,o,i,JSON.parse(d))}else a=_(n,o,i);return process.stdout.write(`${JSON.stringify({ok:!0,acceptance:a})}
4
- `),0}catch(a){const d=a instanceof Error&&/^refactor-root-[a-z-]+$/.test(a.message)?a.message:"refactor-root-review-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:d})}
5
- `),1}}export{M as acceptRootRefactorSemanticReview,_ as readRootRefactorSemanticReview,G as refactorReviewCliHandler};
1
+ import{createHash as _,randomUUID as j}from"node:crypto";import{closeSync as b,existsSync as R,fsyncSync as x,linkSync as P,lstatSync as H,openSync as N,readFileSync as z,realpathSync as U,unlinkSync as I,writeFileSync as $}from"node:fs";import{join as E,resolve as L}from"node:path";import{parse as K}from"@babel/parser";import{readRootRefactorBaseline as V,runRootRefactorCharacterization as X,runRootRefactorTargetCharacterization as Y}from"./refactor-characterization.js";import{cppRefactorExecutableLines as G,isCppRefactorAssertionSite as Q}from"./refactor-cpp-assertions.js";import{privateRefactorDirectory as O,readPrivateRefactorAdmission as ee,verifyRootRefactor as te,readPrivateRefactorTargetAdmission as re,verifyRootRefactorTargetDelta as oe}from"./refactor-root.js";const v=/^[a-f0-9]{64}$/,k=128*1024;function m(t){return _("sha256").update(t).digest("hex")}function y(t,e){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).sort().join("\0")===[...e].sort().join("\0")}function F(t,e){return typeof t=="string"&&t.length>=30&&t.length<=e&&!/[\x00-\x1f\x7f]/.test(t)}function A(t,e,f){if(!v.test(e)||!v.test(f))throw new Error("refactor-root-review-unverified");const a=L(t),i=ee(a,e),s=V(a,f),n=te(a,e),c=X(a,e,s.testFiles.map(r=>r.path),s.dependencies.map(r=>r.path),"after",!0,s.causalPath,f,s.schemaVersion===2?s.runner:"native");if(s.admissionSha256!==e||s.sourceHead!==i.sourceHead||c.baselineSha256!==f||!c.testsPassedObserved||!c.causalFailureObserved||n.changedFileCount<2)throw new Error("refactor-root-review-unverified");return Object.freeze({root:a,storyId:i.storyId,sourceHead:i.sourceHead,admissionSha256:e,baselineSha256:f,candidateSha256:c.candidateSha256,testFiles:s.testFiles,changedFileCount:n.changedFileCount})}function T(t,e){if(!y(e,["schemaVersion","kind","storyId","sourceHead","admissionSha256","baselineSha256","candidateSha256","verdict","behaviorRationale","assertions"])||e.schemaVersion!==1||e.kind!=="root-refactor-semantic-review"||e.storyId!==t.storyId||e.sourceHead!==t.sourceHead||e.admissionSha256!==t.admissionSha256||e.baselineSha256!==t.baselineSha256||e.candidateSha256!==t.candidateSha256||e.verdict!=="approved"||!F(e.behaviorRationale,1e3)||!Array.isArray(e.assertions)||e.assertions.length<t.testFiles.length||e.assertions.length>64||Buffer.byteLength(JSON.stringify(e))>k)throw new Error("refactor-root-review-unverified");return q(t,e.assertions),e}function ie(t){const e=K(t,{sourceType:"unambiguous",plugins:["typescript"],attachComment:!1}),f=new Set,a=r=>r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null,i=r=>{const o=a(r);return o?o.type==="Identifier"?typeof o.name=="string"?o.name:null:o.type==="MemberExpression"?i(o.object):o.type==="CallExpression"?i(o.callee):o.type==="TSAsExpression"||o.type==="TSNonNullExpression"?i(o.expression):null:null},s=r=>{const o=a(r);return!!o&&(o.type==="CallExpression"&&i(o.callee)==="expect"||o.type==="MemberExpression"&&s(o.object))},n=new Set(["ok","equal","notEqual","deepEqual","notDeepEqual","strictEqual","notStrictEqual","deepStrictEqual","notDeepStrictEqual","partialDeepStrictEqual","throws","doesNotThrow","rejects","doesNotReject","ifError","match","doesNotMatch","fail"]),c=r=>{if(Array.isArray(r)){for(const w of r)c(w);return}const o=a(r);if(!o)return;const d=a(o.callee),h=a(d?.property),u=d?.computed?h?.type==="StringLiteral"?h.value:null:h?.name;if(o.type==="CallExpression"&&(d?.type==="Identifier"&&d.name==="assert"||d?.type==="MemberExpression"&&typeof u=="string"&&(i(d.object)==="assert"&&n.has(u)||/^to[A-Z]/.test(u)&&s(d.object)))||o.type==="ThrowStatement"){const w=a(a(o.loc)?.start)?.line;typeof w=="number"&&f.add(w)}for(const[w,p]of Object.entries(o))["loc","start","end","extra","comments","tokens"].includes(w)||c(p)};return c(e),f}function q(t,e){if(!Array.isArray(e)||e.length<t.testFiles.length||e.length>64)throw new Error("refactor-root-review-unverified");const f=new Map(t.testFiles.map(r=>[r.path,r.sha256])),a=new Map,i=new Map,s=new Map;for(const[r,o]of f){const d=E(t.root,r),h=H(d);if(!h.isFile()||h.isSymbolicLink()||U(d)!==d||h.size<1||h.size>8*1024*1024)throw new Error("refactor-root-review-unverified");const u=z(d);if(m(u)!==o)throw new Error("refactor-root-review-unverified");const l=new TextDecoder("utf-8",{fatal:!0}).decode(u);a.set(r,l.split(/\r?\n/)),r.endsWith(".cpp")?i.set(r,G(l)):r.endsWith(".py")||s.set(r,ie(l))}const n=new Set,c=new Set;for(const r of e){if(!y(r,["testPath","assertionLine","rationale"])||typeof r.testPath!="string"||!f.has(r.testPath)||!Number.isSafeInteger(r.assertionLine)||Number(r.assertionLine)<1||Number(r.assertionLine)>(a.get(r.testPath)?.length??0)||!F(r.rationale,500))throw new Error("refactor-root-review-unverified");const o=`${r.testPath}:${r.assertionLine}`;if(n.has(o))throw new Error("refactor-root-review-unverified");n.add(o),c.add(r.testPath);const d=a.get(r.testPath)[Number(r.assertionLine)-1],h=r.testPath.endsWith(".py")?(d.split("#")[0]??"").trimStart():d.split("//")[0]??"";if(!(r.testPath.endsWith(".cpp")?Q(i.get(r.testPath)?.[Number(r.assertionLine)-1]??""):r.testPath.endsWith(".py")?/^(?:with\s+)?self\.assert[A-Z][A-Za-z0-9_]*\s*\(/.test(h)||/^assert\s+\S/.test(h):s.get(r.testPath)?.has(Number(r.assertionLine))===!0))throw new Error("refactor-root-review-unverified")}if(c.size!==f.size)throw new Error("refactor-root-review-unverified")}function D(t,e){return Object.freeze({schemaVersion:1,kind:"root-refactor-semantic-acceptance",storyId:t.storyId,sourceHead:t.sourceHead,admissionSha256:t.admissionSha256,baselineSha256:t.baselineSha256,candidateSha256:t.candidateSha256,reviewSha256:m(`root-refactor-semantic-review-v1\0${JSON.stringify(e)}`),testFileCount:t.testFiles.length,assertionCount:e.assertions.length,changedFileCount:t.changedFileCount,executionVerified:!0,qaAccepted:!0,gitCommitAuthorized:!1,publicSafe:!0})}function M(t,e,f){return E(O(t),`review-${e}-${f}.json`)}function g(t,e="story"){const f=e==="target"?2:1,a=e==="target"?"root-refactor-target-semantic-record":"root-refactor-semantic-record",i=e==="target"?"root-refactor-target-semantic-record-v2":"root-refactor-semantic-record-v1",s=H(t);if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&63)!==0||s.size<100||s.size>k+4096)throw new Error("refactor-root-review-unverified");const n=z(t),c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));if(!y(c,["schemaVersion","kind","report","receipt","checksumSha256"])||c.schemaVersion!==f||c.kind!==a||typeof c.checksumSha256!="string"||!v.test(c.checksumSha256)||!n.equals(Buffer.from(`${JSON.stringify(c)}
2
+ `))||c.checksumSha256!==m(`${i}\0${JSON.stringify({report:c.report,receipt:c.receipt})}`))throw new Error("refactor-root-review-unverified");return c}function ne(t,e,f,a){try{const i=A(t,e,f),s=T(i,a),n=D(i,s),c=M(i.root,e,i.candidateSha256),r={report:s,receipt:n},o={schemaVersion:1,kind:"root-refactor-semantic-record",...r,checksumSha256:m(`root-refactor-semantic-record-v1\0${JSON.stringify(r)}`)},d=Buffer.from(`${JSON.stringify(o)}
3
+ `);if(R(c)){const w=g(c);if(JSON.stringify(w.report)!==JSON.stringify(s)||JSON.stringify(w.receipt)!==JSON.stringify(n))throw new Error("refactor-root-review-conflict");return n}const h=O(i.root),u=E(h,`review-${j()}.tmp`),l=N(u,"wx",384);try{$(l,d),x(l)}finally{b(l)}try{if(A(i.root,e,f).candidateSha256!==n.candidateSha256)throw new Error("refactor-root-review-unverified");P(u,c);const p=N(h,"r");try{x(p)}finally{b(p)}}finally{R(u)&&I(u)}return g(c),n}catch(i){throw i instanceof Error&&i.message==="refactor-root-review-conflict"?i:new Error("refactor-root-review-unverified")}}function ae(t,e,f){try{const a=A(t,e,f),i=g(M(a.root,e,a.candidateSha256));if(!y(i,["schemaVersion","kind","report","receipt","checksumSha256"]))throw new Error("refactor-root-review-unverified");const s=T(a,i.report),n=D(a,s);if(JSON.stringify(i.receipt)!==JSON.stringify(n))throw new Error("refactor-root-review-unverified");return n}catch{throw new Error("refactor-root-review-unverified")}}async function we(t){const e=t[0];let f="",a="",i="",s=!1,n=!1,c="plain";const r=new Set;try{if(e!=="review-accept"&&e!=="review-status")throw new Error("refactor-root-review-arguments-invalid");for(let d=1;d<t.length;d++){const h=t[d];if(r.has(h))throw new Error("refactor-root-review-arguments-invalid");r.add(h);const u=()=>{const l=t[++d];if(!l||l.startsWith("--"))throw new Error("refactor-root-review-arguments-invalid");return l};if(h==="--project-root")f=u();else if(h==="--admission-sha")a=u();else if(h==="--baseline-sha")i=u();else if(h==="--authorize-run")s=!0;else if(h==="--authorize-root-review")n=!0;else if(h==="--format")c=u();else throw new Error("refactor-root-review-arguments-invalid")}if(!f||!v.test(a)||!v.test(i)||!["plain","json"].includes(c)||!s||n!==(e==="review-accept"))throw new Error("refactor-root-review-arguments-invalid");let o;if(e==="review-accept"){let d="";for await(const l of process.stdin)if(d+=String(l),Buffer.byteLength(d)>k)throw new Error("refactor-root-review-unverified");const{parseDocument:h}=await import("yaml"),u=h(d,{strict:!0,uniqueKeys:!0,schema:"core",customTags:[]});if(u.errors.length||u.warnings.length)throw new Error("refactor-root-review-unverified");o=ne(f,a,i,JSON.parse(d))}else o=ae(f,a,i);return process.stdout.write(`${JSON.stringify({ok:!0,acceptance:o})}
4
+ `),0}catch(o){const d=o instanceof Error&&/^refactor-root-[a-z-]+$/.test(o.message)?o.message:"refactor-root-review-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:d})}
5
+ `),1}}function C(t,e,f,a){if(!v.test(e)||!v.test(f))throw new Error("refactor-root-review-unverified");const i=L(t),s=re(i,e,a),n=V(i,f),c=oe(i,e,a),r=Y(i,e,a,n.testFiles.map(o=>o.path),n.dependencies.map(o=>o.path),"after",!0,n.causalPath,f,n.schemaVersion===2?n.runner:"native");if(n.admissionSha256!==e||n.sourceHead!==s.targetPlan.sourceHead||r.baselineSha256!==f||!r.testsPassedObserved||!r.causalFailureObserved||c.changedFileCount<2)throw new Error("refactor-root-review-unverified");return Object.freeze({root:i,scopeId:s.targetPlan.scopeId,sourceHead:s.targetPlan.sourceHead,admissionSha256:e,baselineSha256:f,candidateSha256:r.candidateSha256,testFiles:n.testFiles,changedFileCount:c.changedFileCount})}function B(t,e){if(!y(e,["schemaVersion","kind","scopeId","sourceHead","admissionSha256","baselineSha256","candidateSha256","verdict","behaviorRationale","assertions"])||e.schemaVersion!==2||e.kind!=="root-refactor-target-semantic-review"||e.scopeId!==t.scopeId||e.sourceHead!==t.sourceHead||e.admissionSha256!==t.admissionSha256||e.baselineSha256!==t.baselineSha256||e.candidateSha256!==t.candidateSha256||e.verdict!=="approved"||!F(e.behaviorRationale,1e3)||Buffer.byteLength(JSON.stringify(e))>k)throw new Error("refactor-root-review-unverified");return q(t,e.assertions),e}function W(t,e){return Object.freeze({schemaVersion:2,kind:"root-refactor-target-semantic-acceptance",scopeId:t.scopeId,sourceHead:t.sourceHead,admissionSha256:t.admissionSha256,baselineSha256:t.baselineSha256,candidateSha256:t.candidateSha256,reviewSha256:m(`root-refactor-target-semantic-review-v2\0${JSON.stringify(e)}`),testFileCount:t.testFiles.length,assertionCount:e.assertions.length,changedFileCount:t.changedFileCount,executionVerified:!0,qaAccepted:!0,gitCommitAuthorized:!1,publicSafe:!0})}function Z(t){return E(O(t.root),`target-review-${t.admissionSha256}-${t.candidateSha256}.json`)}function pe(t,e,f,a,i,s){if(!s)throw new Error("refactor-root-review-authorization-required");try{const n=C(t,e,f,a),c=B(n,i),r=W(n,c),o=Z(n),d={report:c,receipt:r},h={schemaVersion:2,kind:"root-refactor-target-semantic-record",...d,checksumSha256:m(`root-refactor-target-semantic-record-v2\0${JSON.stringify(d)}`)},u=Buffer.from(`${JSON.stringify(h)}
6
+ `);if(R(o)){const S=g(o,"target");if(JSON.stringify(S.report)!==JSON.stringify(c)||JSON.stringify(S.receipt)!==JSON.stringify(r))throw new Error("refactor-root-review-conflict");return r}const l=O(n.root),w=E(l,`target-review-${j()}.tmp`),p=N(w,"wx",384);try{$(p,u),x(p)}finally{b(p)}try{const S=C(n.root,e,f,a);if(S.scopeId!==r.scopeId||S.candidateSha256!==r.candidateSha256)throw new Error("refactor-root-review-unverified");P(w,o);const J=N(l,"r");try{x(J)}finally{b(J)}}finally{R(w)&&I(w)}return g(o,"target"),r}catch(n){throw n instanceof Error&&n.message==="refactor-root-review-conflict"?n:new Error("refactor-root-review-unverified")}}function ve(t,e,f,a){try{const i=C(t,e,f,a),s=g(Z(i),"target");if(!y(s,["schemaVersion","kind","report","receipt","checksumSha256"]))throw new Error("refactor-root-review-unverified");const n=B(i,s.report),c=W(i,n);if(JSON.stringify(s.receipt)!==JSON.stringify(c))throw new Error("refactor-root-review-unverified");return c}catch{throw new Error("refactor-root-review-unverified")}}export{ne as acceptRootRefactorSemanticReview,pe as acceptRootRefactorTargetSemanticReview,ae as readRootRefactorSemanticReview,ve as readRootRefactorTargetSemanticReview,we as refactorReviewCliHandler};
@@ -17,7 +17,7 @@ export declare function exactCommittedRefactorFile(root: string, path: string):
17
17
  sha256: string;
18
18
  mode: number;
19
19
  }>;
20
- /** Preserve the pre-existing visible Neocortex sidecar state byte-for-byte. */
20
+ /** Preserve pre-existing visible and ignored Neocortex controls without copying them to a model. */
21
21
  export declare function refactorSidecarDigest(root: string): string;
22
22
  export interface PrivateRefactorAdmissionV1 {
23
23
  readonly schemaVersion: 1;
@@ -81,5 +81,169 @@ export interface RefactorRootContainmentReceiptV2 extends Omit<RefactorRootConta
81
81
  readonly newFileCount: number;
82
82
  }
83
83
  export declare function verifyRootRefactor(projectRoot: string, admissionSha256: string): RefactorRootContainmentReceiptV1 | RefactorRootContainmentReceiptV2;
84
+ /** Private characterization preparation only. Full review/commit still requires
85
+ * every admitted new file. Missing Markdown cannot authorize QA or Git effects.
86
+ */
87
+ export declare function verifyRootRefactorForCharacterization(projectRoot: string, admissionSha256: string): Readonly<{
88
+ receipt: RefactorRootContainmentReceiptV1 | RefactorRootContainmentReceiptV2;
89
+ pendingDocumentationPaths: readonly string[];
90
+ }>;
84
91
  export declare function planRootRefactor(projectRoot: string, storyId: string): RefactorRootPlanV1;
85
92
  export declare function refactorRootCliHandler(args: readonly string[]): number;
93
+ /** Read-only target identity; later admission must bind this exact plan. */
94
+ export type RefactorRootTargetV2 = Readonly<{
95
+ kind: 'story';
96
+ storyId: string;
97
+ }> | Readonly<{
98
+ kind: 'epic';
99
+ epicId: string;
100
+ }> | Readonly<{
101
+ kind: 'idea';
102
+ idea: string;
103
+ }>;
104
+ export declare function planRootRefactorTarget(projectRoot: string, target: RefactorRootTargetV2): Readonly<{
105
+ schemaVersion: 2;
106
+ kind: "root-refactor-target-scope";
107
+ targetKind: "epic" | "story" | "idea";
108
+ targetId: string | null;
109
+ sourceHead: string;
110
+ projectBindingSha256: string;
111
+ targetContentSha256: string;
112
+ targetSha256: string;
113
+ planSha256: string;
114
+ scopeId: `rfs_${string}`;
115
+ candidateWriteSetRequired: true;
116
+ characterizationRequired: true;
117
+ executionAuthorized: false;
118
+ gitAuthority: "ROOT_ONLY";
119
+ graphExecution: "NOT_RUN";
120
+ publicSafe: true;
121
+ }>;
122
+ /** Reopen identity during a candidate run; grants no cleanliness or effect authority. */
123
+ export declare function inspectRootRefactorTargetIdentity(projectRoot: string, target: RefactorRootTargetV2): Readonly<{
124
+ schemaVersion: 2;
125
+ kind: "root-refactor-target-scope";
126
+ targetKind: "epic" | "story" | "idea";
127
+ targetId: string | null;
128
+ sourceHead: string;
129
+ projectBindingSha256: string;
130
+ targetContentSha256: string;
131
+ targetSha256: string;
132
+ planSha256: string;
133
+ scopeId: `rfs_${string}`;
134
+ candidateWriteSetRequired: true;
135
+ characterizationRequired: true;
136
+ executionAuthorized: false;
137
+ gitAuthority: "ROOT_ONLY";
138
+ graphExecution: "NOT_RUN";
139
+ publicSafe: true;
140
+ }>;
141
+ /** Recompute from physical Git and root-owned target input; never trust a DTO. */
142
+ export declare function verifyRootRefactorTargetPlan(projectRoot: string, plan: unknown, target: RefactorRootTargetV2): Readonly<{
143
+ schemaVersion: 2;
144
+ kind: "root-refactor-target-scope";
145
+ targetKind: "epic" | "story" | "idea";
146
+ targetId: string | null;
147
+ sourceHead: string;
148
+ projectBindingSha256: string;
149
+ targetContentSha256: string;
150
+ targetSha256: string;
151
+ planSha256: string;
152
+ scopeId: `rfs_${string}`;
153
+ candidateWriteSetRequired: true;
154
+ characterizationRequired: true;
155
+ executionAuthorized: false;
156
+ gitAuthority: "ROOT_ONLY";
157
+ graphExecution: "NOT_RUN";
158
+ publicSafe: true;
159
+ }>;
160
+ /** Identity binding only; authenticated registration and graph gates stay separate. */
161
+ export declare function bindRootRefactorTargetControl(projectRoot: string, plan: unknown, target: RefactorRootTargetV2, context: Readonly<{
162
+ runId: string;
163
+ generationId: string;
164
+ includeScopeDecision: boolean;
165
+ }>): Readonly<{
166
+ schemaVersion: 2;
167
+ kind: "root-refactor-target-control-binding";
168
+ scopeId: `rfs_${string}`;
169
+ targetKind: "epic" | "story" | "idea";
170
+ planSha256: string;
171
+ controlBindingSha256: string;
172
+ runId: string;
173
+ generationId: string;
174
+ includeScopeDecision: boolean;
175
+ executionAuthorized: false;
176
+ graphExecution: "NOT_RUN";
177
+ qaAccepted: false;
178
+ gitAuthority: "NONE";
179
+ }>;
180
+ export interface PrivateRefactorTargetAdmissionV3 {
181
+ readonly schemaVersion: 3;
182
+ readonly kind: 'private-root-refactor-target-admission';
183
+ readonly targetPlan: ReturnType<typeof planRootRefactorTarget>;
184
+ readonly indexSha256: string;
185
+ readonly sidecarSha256: string;
186
+ readonly files: readonly Readonly<{
187
+ path: string;
188
+ sha256: string;
189
+ mode: number;
190
+ }>[];
191
+ readonly newFiles: readonly Readonly<{
192
+ path: string;
193
+ }>[];
194
+ readonly admissionSha256: string;
195
+ }
196
+ /** Owner-private precommit read. It grants no containment, review or commit. */
197
+ export declare function readPrivateRefactorTargetAdmission(projectRoot: string, sha256: string, target: RefactorRootTargetV2): PrivateRefactorTargetAdmissionV3;
198
+ /** Root-only explicit write-set preparation, without project edits or stage execution. */
199
+ export declare function admitRootRefactorTarget(projectRoot: string, plan: unknown, target: RefactorRootTargetV2, paths: readonly string[], newPaths: readonly string[], authorizeRootEdit: boolean): Readonly<{
200
+ schemaVersion: 3;
201
+ kind: "root-refactor-target-write-set-admission";
202
+ scopeId: `rfs_${string}`;
203
+ targetKind: "epic" | "story" | "idea";
204
+ sourceHead: string;
205
+ planSha256: string;
206
+ admissionSha256: string;
207
+ writeSetSha256: string;
208
+ fileCount: number;
209
+ newFileCount: number;
210
+ rootEditPrepared: true;
211
+ privateChildAuthorized: false;
212
+ gitCommitAuthorized: false;
213
+ publicSafe: true;
214
+ }>;
215
+ export declare function verifyRootRefactorTargetDelta(projectRoot: string, admissionSha256: string, target: RefactorRootTargetV2): Readonly<{
216
+ newFileCount: number;
217
+ kind: "root-refactor-target-delta-containment";
218
+ scopeId: `rfs_${string}`;
219
+ targetKind: "epic" | "story" | "idea";
220
+ sourceHead: string;
221
+ planSha256: string;
222
+ admissionSha256: string;
223
+ writeSetSha256: string;
224
+ changedFileCount: number;
225
+ rootEditContained: true;
226
+ qaAccepted: false;
227
+ gitCommitAuthorized: false;
228
+ publicSafe: true;
229
+ schemaVersion: 3;
230
+ }>;
231
+ export declare function verifyRootRefactorTargetForCharacterization(projectRoot: string, admissionSha256: string, target: RefactorRootTargetV2): Readonly<{
232
+ receipt: Readonly<{
233
+ newFileCount: number;
234
+ kind: "root-refactor-target-delta-containment";
235
+ scopeId: `rfs_${string}`;
236
+ targetKind: "epic" | "story" | "idea";
237
+ sourceHead: string;
238
+ planSha256: string;
239
+ admissionSha256: string;
240
+ writeSetSha256: string;
241
+ changedFileCount: number;
242
+ rootEditContained: true;
243
+ qaAccepted: false;
244
+ gitCommitAuthorized: false;
245
+ publicSafe: true;
246
+ schemaVersion: 3;
247
+ }>;
248
+ pendingDocumentationPaths: readonly string[];
249
+ }>;
@@ -1,7 +1,12 @@
1
- import{createHash as rr}from"node:crypto";import{closeSync as J,constants as $,existsSync as er,fsyncSync as q,lstatSync as p,mkdirSync as tr,openSync as I,readFileSync as k,realpathSync as x,writeFileSync as or}from"node:fs";import{dirname as Y,isAbsolute as X,join as z,resolve as H}from"node:path";import{mutationQaGit as g}from"./mutation-qa-git.js";const G=/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/,F=/^[a-f0-9]{64}$/,j=8*1024*1024,_=256;function m(i){return rr("sha256").update(i).digest("hex")}function M(i){const o=g(i,["rev-parse","--git-common-dir"]).toString("utf8").trim(),r=X(o)?H(o):H(i,o);if(x(r)!==r||p(r).isSymbolicLink()||p(r).uid!==process.getuid?.())throw new Error("refactor-root-store-unverified");const e=z(r,"neocortex-refactor");tr(e,{recursive:!0,mode:448});const s=p(e);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&63)!==0)throw new Error("refactor-root-store-unverified");return e}function R(i){return!i||i.length>512||X(i)||i.includes("\\")||/[\u0000-\u001f\u007f:*?\[\]]/.test(i)||i.normalize("NFC")!==i?!1:!i.split("/").some(r=>!r||r==="."||r===".."||[".git",".neocortex","node_modules"].includes(r.toLowerCase()))}function ir(i,o){if(!R(o))throw new Error("refactor-root-write-set-invalid");const r=z(i,o),e=p(r);if(x(r)!==r||!e.isFile()||e.isSymbolicLink()||e.size===0||e.size>j)throw new Error("refactor-root-write-set-invalid");const s=k(r);if(s.length===0||s.length>j)throw new Error("refactor-root-write-set-invalid");if(new TextDecoder("utf-8",{fatal:!0}).decode(s),s.includes(0))throw new Error("refactor-root-write-set-invalid");const n=g(i,["show",`HEAD:${o}`]);if(!s.equals(n))throw new Error("refactor-root-source-dirty");return Object.freeze({sha256:m(s),mode:e.mode&511})}function U(i,o){try{return g(i,["check-ignore","--no-index","-q","--",o]),!0}catch(r){if(r.status===1)return!1;throw r}}function T(i,o){if(!R(o))throw new Error("refactor-root-write-set-invalid");const r=z(i,o),e=Y(r),s=p(e);if(!s.isDirectory()||s.isSymbolicLink()||x(e)!==e||g(i,["ls-files","--stage","-z","--",o]).length>0||U(i,o))throw new Error("refactor-root-write-set-invalid");try{throw p(r),new Error("refactor-root-write-set-invalid")}catch(n){if(n.code!=="ENOENT")throw n}}function L(i){return m(g(i,["ls-files","--stage","-z"]))}function D(i,o){const r=g(i,o);return new TextDecoder("utf-8",{fatal:!0}).decode(r).split("\0").filter(Boolean)}function W(i){if(D(i,["ls-files","-v","-z"]).some(r=>!r.startsWith("H ")))throw new Error("refactor-root-index-unverified")}function C(i){const o=[];let r=0;for(const e of D(i,["status","--porcelain=v1","-z","--untracked-files=all"])){if(e.length<4||e[2]!==" ")throw new Error("refactor-root-sidecar-unverified");const s=e.slice(3);if(!s.startsWith(".neocortex/"))continue;if(s.includes("\\")||/[\u0000-\u001f\u007f]/.test(s)||s.split("/").some(l=>!l||l==="."||l===".."))throw new Error("refactor-root-sidecar-unverified");const n=z(i,s),t=p(n);if(x(n)!==n||!t.isFile()||t.isSymbolicLink()||t.size>64*1024*1024)throw new Error("refactor-root-sidecar-unverified");if(r+=t.size,r>128*1024*1024)throw new Error("refactor-root-sidecar-unverified");const c=k(n);if(c.length>64*1024*1024)throw new Error("refactor-root-sidecar-unverified");o.push({status:e.slice(0,2),path:s,sha256:m(c),mode:t.mode&511})}return o.sort((e,s)=>Buffer.from(e.path).compare(Buffer.from(s.path))),m(JSON.stringify(o))}function P(i){return[...i].sort((o,r)=>Buffer.from(o).compare(Buffer.from(r)))}function Q(i){const o=i.files.map(r=>r.path);return m(JSON.stringify(i.schemaVersion===1?o:{files:o,newFiles:i.newFiles.map(r=>r.path)}))}function K(i,o){if(!F.test(o))throw new Error("refactor-root-admission-invalid");return z(M(i),`admission-${o}.json`)}function B(i,o){const r=K(i,o),e=p(r);if(!e.isFile()||e.isSymbolicLink()||e.uid!==process.getuid?.()||(e.mode&63)!==0||e.size<100||e.size>512*1024)throw new Error("refactor-root-admission-invalid");const s=k(r);if(s.length>512*1024)throw new Error("refactor-root-admission-invalid");let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{throw new Error("refactor-root-admission-invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("refactor-root-admission-invalid");const t=n,c=t.schemaVersion===2,l=["schemaVersion","kind","storyId","sourceHead","storySha256","planSha256","indexSha256","sidecarSha256","files","admissionSha256"];if(c&&l.push("newFiles"),Object.keys(t).sort().join("\0")!==l.sort().join("\0")||![1,2].includes(t.schemaVersion)||t.kind!=="private-root-refactor-admission"||typeof t.storyId!="string"||!G.test(t.storyId)||typeof t.sourceHead!="string"||!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(t.sourceHead)||typeof t.storySha256!="string"||!F.test(t.storySha256)||typeof t.planSha256!="string"||!F.test(t.planSha256)||typeof t.indexSha256!="string"||!F.test(t.indexSha256)||typeof t.sidecarSha256!="string"||!F.test(t.sidecarSha256)||t.admissionSha256!==o||!Array.isArray(t.files)||t.files.length>_||(c?!Array.isArray(t.newFiles)||t.newFiles.length<1||t.files.length+t.newFiles.length>_:t.files.length<1))throw new Error("refactor-root-admission-invalid");if(m(`root-refactor-story-scope-v1\0${t.sourceHead}\0${t.storyId}\0${t.storySha256}`)!==t.planSha256)throw new Error("refactor-root-admission-invalid");const S=t.files;if(S.some(a=>!a||typeof a!="object"||Array.isArray(a)||Object.keys(a).sort().join("\0")!==["mode","path","sha256"].join("\0")||typeof a.path!="string"||!R(a.path)||typeof a.sha256!="string"||!F.test(a.sha256)||!Number.isSafeInteger(a.mode)||a.mode<0||a.mode>511))throw new Error("refactor-root-admission-invalid");const d=S.map(a=>a.path);if(new Set(d).size!==d.length||d.join("\0")!==P(d).join("\0"))throw new Error("refactor-root-admission-invalid");if(c){const a=t.newFiles;if(a.some(E=>!E||typeof E!="object"||Array.isArray(E)||Object.keys(E).join("\0")!=="path"||typeof E.path!="string"||!R(E.path)))throw new Error("refactor-root-admission-invalid");const y=a.map(E=>E.path);if(new Set([...d,...y]).size!==d.length+y.length||y.join("\0")!==P(y).join("\0")||[...d,...y].includes(`docs/stories/${t.storyId}.story.md`))throw new Error("refactor-root-admission-invalid")}const{admissionSha256:h,...w}=t;if(m(JSON.stringify(w))!==o||!s.equals(Buffer.from(`${JSON.stringify(t)}
2
- `)))throw new Error("refactor-root-admission-invalid");return t}function sr(i,o,r,e,s,n=[]){if(!s)throw new Error("refactor-root-authorization-required");if(!F.test(r)||e.length+n.length<1||e.length+n.length>_)throw new Error("refactor-root-write-set-invalid");const t=H(i);try{const c=V(t,o);if(c.planSha256!==r)throw new Error("refactor-root-plan-stale");W(t);const l=L(t),S=C(t),d=P(e),h=P(n);if(new Set([...d,...h]).size!==d.length+h.length||[...d,...h].includes(`docs/stories/${o}.story.md`))throw new Error("refactor-root-write-set-invalid");const w=d.map(u=>Object.freeze({path:u,...ir(t,u)})),a=h.map(u=>(T(t,u),Object.freeze({path:u})));if(L(t)!==l||C(t)!==S||V(t,o).planSha256!==r)throw new Error("refactor-root-source-dirty");for(const u of a)T(t,u.path);const y={kind:"private-root-refactor-admission",storyId:o,sourceHead:c.sourceHead,storySha256:c.storySha256,planSha256:r,indexSha256:l,sidecarSha256:S,files:w},E=a.length>0?{schemaVersion:2,...y,newFiles:a}:{schemaVersion:1,...y},A=m(JSON.stringify(E)),N={...E,admissionSha256:A},f=K(t,A),b=Buffer.from(`${JSON.stringify(N)}
3
- `);if(er(f))B(t,A);else{const u=I(f,$.O_WRONLY|$.O_CREAT|$.O_EXCL|($.O_NOFOLLOW??0),384);try{or(u,b),q(u)}finally{J(u)}const O=I(M(t),$.O_RDONLY|($.O_DIRECTORY??0));try{q(O)}finally{J(O)}}if(B(t,A),L(t)!==l||C(t)!==S||V(t,o).planSha256!==r)throw new Error("refactor-root-source-dirty");for(const u of a)T(t,u.path);const v={kind:"root-refactor-write-set-admission",storyId:o,sourceHead:c.sourceHead,planSha256:r,writeSetSha256:Q(N),admissionSha256:A,fileCount:w.length,rootEditPrepared:!0,privateChildAuthorized:!1,gitCommitAuthorized:!1,publicSafe:!0};return N.schemaVersion===2?Object.freeze({schemaVersion:2,...v,newFileCount:a.length}):Object.freeze({schemaVersion:1,...v})}catch(c){throw c instanceof Error&&c.message.startsWith("refactor-root-")?c:new Error("refactor-root-write-set-invalid")}}function Z(i,o){if(!R(o)||U(i,o)||g(i,["ls-files","--stage","-z","--",o]).length>0)throw new Error("refactor-root-delta-outside-admission");const r=z(i,o),e=Y(r);if(!p(e).isDirectory()||x(e)!==e)throw new Error("refactor-root-delta-outside-admission");const s=p(r);if(x(r)!==r||!s.isFile()||s.isSymbolicLink()||s.size===0||s.size>j||(s.mode&75)!==0)throw new Error("refactor-root-delta-outside-admission");const n=k(r);if(n.length===0||n.length>j||n.includes(0))throw new Error("refactor-root-delta-outside-admission");return new TextDecoder("utf-8",{fatal:!0}).decode(n),m(n)}function nr(i,o){const r=H(i);try{const e=B(r,o),s=g(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(s!==e.sourceHead||L(r)!==e.indexSha256||C(r)!==e.sidecarSha256)throw new Error("refactor-root-baseline-stale");W(r);const n=z(r,"docs","stories",`${e.storyId}.story.md`),t=p(n);if(!t.isFile()||t.isSymbolicLink()||x(n)!==n||m(k(n))!==e.storySha256||m(g(r,["show",`HEAD:docs/stories/${e.storyId}.story.md`]))!==e.storySha256)throw new Error("refactor-root-baseline-stale");const c=D(r,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(f=>!f.startsWith(".neocortex/")),l=D(r,["ls-files","--others","--exclude-standard","-z"]).filter(f=>!f.startsWith(".neocortex/")),S=new Set(e.files.map(f=>f.path)),d=e.schemaVersion===2?e.newFiles.map(f=>f.path):[],h=new Set(d);if(c.length+l.length===0||l.length!==h.size||c.some(f=>!S.has(f))||l.some(f=>!h.has(f)))throw new Error("refactor-root-delta-outside-admission");let w=0;const a=[];for(const f of e.files){const b=z(r,f.path);if(m(g(r,["show",`HEAD:${f.path}`]))!==f.sha256)throw new Error("refactor-root-admission-invalid");const v=p(b);if(x(b)!==b||!v.isFile()||v.isSymbolicLink()||v.size===0||v.size>j||(v.mode&511)!==f.mode)throw new Error("refactor-root-delta-outside-admission");const u=k(b);if(u.length===0||u.length>j)throw new Error("refactor-root-delta-outside-admission");if(new TextDecoder("utf-8",{fatal:!0}).decode(u),u.includes(0))throw new Error("refactor-root-delta-outside-admission");const O=m(u);a.push(O),O!==f.sha256&&w++}const y=d.map(f=>Z(r,f));w+=y.length;const E=D(r,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(f=>!f.startsWith(".neocortex/")),A=D(r,["ls-files","--others","--exclude-standard","-z"]).filter(f=>!f.startsWith(".neocortex/"));if(W(r),w===0||w!==c.length+l.length||E.join("\0")!==c.join("\0")||A.join("\0")!==l.join("\0")||e.files.some((f,b)=>{const v=z(r,f.path),u=p(v);if(x(v)!==v||!u.isFile()||u.isSymbolicLink()||u.size>j||(u.mode&511)!==f.mode)return!0;const O=k(v);return O.length>j||m(O)!==a[b]})||d.some((f,b)=>Z(r,f)!==y[b])||L(r)!==e.indexSha256||C(r)!==e.sidecarSha256||g(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim()!==s)throw new Error("refactor-root-baseline-stale");const N={kind:"root-refactor-delta-containment",storyId:e.storyId,sourceHead:e.sourceHead,planSha256:e.planSha256,admissionSha256:o,writeSetSha256:Q(e),changedFileCount:w,rootEditContained:!0,qaAccepted:!1,gitCommitAuthorized:!1,publicSafe:!0};return e.schemaVersion===2?Object.freeze({schemaVersion:2,...N,newFileCount:d.length}):Object.freeze({schemaVersion:1,...N})}catch(e){throw e instanceof Error&&e.message.startsWith("refactor-root-")?e:new Error("refactor-root-delta-unverified")}}function V(i,o){if(!G.test(o))throw new Error("refactor-root-story-invalid");const r=H(i);try{if(x(r)!==r||!p(r).isDirectory())throw new Error("refactor-root-source-unverified");if(g(r,["rev-parse","--show-toplevel"]).toString("utf8").trim()!==r)throw new Error("refactor-root-source-unverified");if(g(r,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(a=>!/^.{2} \.neocortex\//.test(a)))throw new Error("refactor-root-source-dirty");const n=g(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(n))throw new Error("refactor-root-source-unverified");const t=`docs/stories/${o}.story.md`,c=z(r,t),l=p(c);if(x(c)!==c||!l.isFile()||l.isSymbolicLink()||l.size===0||l.size>1024*1024)throw new Error("refactor-root-story-unverified");const S=k(c),d=g(r,["show",`HEAD:${t}`]);if(!S.equals(d))throw new Error("refactor-root-story-unverified");const h=m(S),w=m(`root-refactor-story-scope-v1\0${n}\0${o}\0${h}`);return Object.freeze({schemaVersion:1,kind:"root-refactor-story-scope",storyId:o,sourceHead:n,storySha256:h,planSha256:w,candidateWriteSetRequired:!0,characterizationRequired:!0,executionAuthorized:!1,gitAuthority:"ROOT_ONLY",graphExecution:"NOT_RUN",publicSafe:!0})}catch(e){throw e instanceof Error&&e.message.startsWith("refactor-root-")?e:new Error("refactor-root-source-unverified")}}function lr(i){let o="",r="",e="",s="",n="",t=!1;const c=[],l=[];let S="plain";try{const d=[...i];o=d.shift()??"";for(let h=0;h<d.length;h++){const w=d[h],a=()=>{const y=d[++h];if(!y||y.startsWith("--"))throw new Error("refactor-root-arguments-invalid");return y};if(w==="--project-root")r=a();else if(w==="--story")e=a();else if(w==="--plan-sha")s=a();else if(w==="--admission-sha")n=a();else if(w==="--path")c.push(a());else if(w==="--new-path")l.push(a());else if(w==="--authorize-root-edit")t=!0;else if(w==="--format")S=a();else throw new Error("refactor-root-arguments-invalid")}if(!r||!["plain","json"].includes(S))throw new Error("refactor-root-arguments-invalid");if(o==="plan"&&e&&!s&&!n&&c.length===0&&l.length===0&&!t){const h=V(r,e);process.stdout.write(`${JSON.stringify({ok:!0,plan:h})}
4
- `)}else if(o==="admit"&&e&&s&&!n&&c.length+l.length>0){const h=sr(r,e,s,c,t,l);process.stdout.write(`${JSON.stringify({ok:!0,admission:h})}
5
- `)}else if(o==="verify"&&!e&&!s&&n&&c.length===0&&l.length===0&&!t){const h=nr(r,n);process.stdout.write(`${JSON.stringify({ok:!0,containment:h})}
6
- `)}else throw new Error("refactor-root-arguments-invalid");return 0}catch(d){const h=d instanceof Error&&/^refactor-root-[a-z-]+$/.test(d.message)?d.message:"refactor-root-source-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:h})}
7
- `),1}}export{sr as admitRootRefactor,ir as exactCommittedRefactorFile,V as planRootRefactor,M as privateRefactorDirectory,B as readPrivateRefactorAdmission,lr as refactorRootCliHandler,C as refactorSidecarDigest,nr as verifyRootRefactor};
1
+ import{createHash as pe}from"node:crypto";import{closeSync as V,constants as N,existsSync as ne,fstatSync as ge,fsyncSync as K,lstatSync as v,mkdirSync as ye,openSync as q,readFileSync as H,readSync as se,realpathSync as j,writeFileSync as ae}from"node:fs";import{dirname as ce,isAbsolute as Z,join as A,resolve as F}from"node:path";import{mutationQaGit as E}from"./mutation-qa-git.js";const Q=/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/,$=/^[a-f0-9]{64}$/,D=8*1024*1024,Y=256;function y(s){return pe("sha256").update(s).digest("hex")}function M(s){const t=E(s,["rev-parse","--git-common-dir"]).toString("utf8").trim(),i=Z(t)?F(t):F(s,t);if(j(i)!==i||v(i).isSymbolicLink()||v(i).uid!==process.getuid?.())throw new Error("refactor-root-store-unverified");const e=A(i,"neocortex-refactor");ye(e,{recursive:!0,mode:448});const r=v(e);if(!r.isDirectory()||r.isSymbolicLink()||r.uid!==process.getuid?.()||(r.mode&63)!==0)throw new Error("refactor-root-store-unverified");return e}function _(s){return!s||s.length>512||Z(s)||s.includes("\\")||/[\u0000-\u001f\u007f:*?\[\]]/.test(s)||s.normalize("NFC")!==s?!1:!s.split("/").some(i=>!i||i==="."||i===".."||[".git",".neocortex","node_modules"].includes(i.toLowerCase()))}function ee(s,t){if(!_(t))throw new Error("refactor-root-write-set-invalid");const i=A(s,t),e=v(i);if(j(i)!==i||!e.isFile()||e.isSymbolicLink()||e.size===0||e.size>D)throw new Error("refactor-root-write-set-invalid");const r=H(i);if(r.length===0||r.length>D)throw new Error("refactor-root-write-set-invalid");if(new TextDecoder("utf-8",{fatal:!0}).decode(r),r.includes(0))throw new Error("refactor-root-write-set-invalid");const a=E(s,["show",`HEAD:${t}`]);if(!r.equals(a))throw new Error("refactor-root-source-dirty");return Object.freeze({sha256:y(r),mode:e.mode&511})}function te(s,t){try{return E(s,["check-ignore","--no-index","-q","--",t]),!0}catch(i){if(i.status===1)return!1;throw i}}function T(s,t){if(!_(t))throw new Error("refactor-root-write-set-invalid");const i=A(s,t),e=ce(i),r=v(e);if(!r.isDirectory()||r.isSymbolicLink()||j(e)!==e||E(s,["ls-files","--stage","-z","--",t]).length>0||te(s,t))throw new Error("refactor-root-write-set-invalid");try{throw v(i),new Error("refactor-root-write-set-invalid")}catch(a){if(a.code!=="ENOENT")throw a}}function C(s){return y(E(s,["ls-files","--stage","-z"]))}function I(s,t){const i=E(s,t);return new TextDecoder("utf-8",{fatal:!0}).decode(i).split("\0").filter(Boolean)}function W(s){if(I(s,["ls-files","-v","-z"]).some(i=>!i.startsWith("H ")))throw new Error("refactor-root-index-unverified")}function L(s){const t=[],i=new Set;let e=0;const r=I(s,["status","--porcelain=v1","-z","--untracked-files=all"]);r.push(...I(s,["ls-files","--others","--ignored","--exclude-standard","-z","--",".neocortex/"]).map(a=>`!! ${a}`));for(const a of r){if(a.length<4||a[2]!==" ")throw new Error("refactor-root-sidecar-unverified");const o=a.slice(3);if(!o.startsWith(".neocortex/"))continue;if(i.has(o)||o.includes("\\")||/[\u0000-\u001f\u007f]/.test(o)||o.split("/").some(m=>!m||m==="."||m===".."))throw new Error("refactor-root-sidecar-unverified");i.add(o);const l=A(s,o),n=v(l);if(j(l)!==l||!n.isFile()||n.isSymbolicLink()||n.nlink!==1||n.size>64*1024*1024)throw new Error("refactor-root-sidecar-unverified");if(e+=n.size,e>128*1024*1024)throw new Error("refactor-root-sidecar-unverified");const g=q(l,N.O_RDONLY|N.O_NOFOLLOW);try{const m=Buffer.alloc(n.size+1);let w=0;for(;w<m.length;){const d=se(g,m,w,m.length-w,w);if(!d)break;w+=d}const p=ge(g),f=v(l);if(w!==n.size||j(l)!==l||[p,f].some(d=>d.dev!==n.dev||d.ino!==n.ino||d.size!==n.size||d.mtimeMs!==n.mtimeMs||d.ctimeMs!==n.ctimeMs||d.mode!==n.mode||d.nlink!==1))throw new Error("refactor-root-sidecar-unverified");t.push({status:a.slice(0,2),path:o,sha256:y(m.subarray(0,w)),mode:n.mode&511})}finally{V(g)}}return t.sort((a,o)=>Buffer.from(a.path).compare(Buffer.from(o.path))),y(JSON.stringify(t))}function J(s){return[...s].sort((t,i)=>Buffer.from(t).compare(Buffer.from(i)))}function fe(s){const t=s.files.map(i=>i.path);return y(JSON.stringify(s.schemaVersion===1?t:{files:t,newFiles:s.newFiles.map(i=>i.path)}))}function de(s,t){if(!$.test(t))throw new Error("refactor-root-admission-invalid");return A(M(s),`admission-${t}.json`)}function re(s,t){const i=de(s,t),e=v(i);if(!e.isFile()||e.isSymbolicLink()||e.uid!==process.getuid?.()||(e.mode&63)!==0||e.size<100||e.size>512*1024)throw new Error("refactor-root-admission-invalid");const r=H(i);if(r.length>512*1024)throw new Error("refactor-root-admission-invalid");let a;try{a=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new Error("refactor-root-admission-invalid")}if(!a||typeof a!="object"||Array.isArray(a))throw new Error("refactor-root-admission-invalid");const o=a,l=o.schemaVersion===2,n=["schemaVersion","kind","storyId","sourceHead","storySha256","planSha256","indexSha256","sidecarSha256","files","admissionSha256"];if(l&&n.push("newFiles"),Object.keys(o).sort().join("\0")!==n.sort().join("\0")||![1,2].includes(o.schemaVersion)||o.kind!=="private-root-refactor-admission"||typeof o.storyId!="string"||!Q.test(o.storyId)||typeof o.sourceHead!="string"||!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(o.sourceHead)||typeof o.storySha256!="string"||!$.test(o.storySha256)||typeof o.planSha256!="string"||!$.test(o.planSha256)||typeof o.indexSha256!="string"||!$.test(o.indexSha256)||typeof o.sidecarSha256!="string"||!$.test(o.sidecarSha256)||o.admissionSha256!==t||!Array.isArray(o.files)||o.files.length>Y||(l?!Array.isArray(o.newFiles)||o.newFiles.length<1||o.files.length+o.newFiles.length>Y:o.files.length<1))throw new Error("refactor-root-admission-invalid");if(y(`root-refactor-story-scope-v1\0${o.sourceHead}\0${o.storyId}\0${o.storySha256}`)!==o.planSha256)throw new Error("refactor-root-admission-invalid");const g=o.files;if(g.some(f=>!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).sort().join("\0")!==["mode","path","sha256"].join("\0")||typeof f.path!="string"||!_(f.path)||typeof f.sha256!="string"||!$.test(f.sha256)||!Number.isSafeInteger(f.mode)||f.mode<0||f.mode>511))throw new Error("refactor-root-admission-invalid");const m=g.map(f=>f.path);if(new Set(m).size!==m.length||m.join("\0")!==J(m).join("\0"))throw new Error("refactor-root-admission-invalid");if(l){const f=o.newFiles;if(f.some(c=>!c||typeof c!="object"||Array.isArray(c)||Object.keys(c).join("\0")!=="path"||typeof c.path!="string"||!_(c.path)))throw new Error("refactor-root-admission-invalid");const d=f.map(c=>c.path);if(new Set([...m,...d]).size!==m.length+d.length||d.join("\0")!==J(d).join("\0")||[...m,...d].includes(`docs/stories/${o.storyId}.story.md`))throw new Error("refactor-root-admission-invalid")}const{admissionSha256:w,...p}=o;if(y(JSON.stringify(p))!==t||!r.equals(Buffer.from(`${JSON.stringify(o)}
2
+ `)))throw new Error("refactor-root-admission-invalid");return o}function Se(s,t,i,e,r,a=[]){if(!r)throw new Error("refactor-root-authorization-required");if(!$.test(i)||e.length+a.length<1||e.length+a.length>Y)throw new Error("refactor-root-write-set-invalid");const o=F(s);try{const l=X(o,t);if(l.planSha256!==i)throw new Error("refactor-root-plan-stale");W(o);const n=C(o),g=L(o),m=J(e),w=J(a);if(new Set([...m,...w]).size!==m.length+w.length||[...m,...w].includes(`docs/stories/${t}.story.md`))throw new Error("refactor-root-write-set-invalid");const p=m.map(h=>Object.freeze({path:h,...ee(o,h)})),f=w.map(h=>(T(o,h),Object.freeze({path:h})));if(C(o)!==n||L(o)!==g||X(o,t).planSha256!==i)throw new Error("refactor-root-source-dirty");for(const h of f)T(o,h.path);const d={kind:"private-root-refactor-admission",storyId:t,sourceHead:l.sourceHead,storySha256:l.storySha256,planSha256:i,indexSha256:n,sidecarSha256:g,files:p},c=f.length>0?{schemaVersion:2,...d,newFiles:f}:{schemaVersion:1,...d},S=y(JSON.stringify(c)),x={...c,admissionSha256:S},R=de(o,S),O=Buffer.from(`${JSON.stringify(x)}
3
+ `);if(ne(R))re(o,S);else{const h=q(R,N.O_WRONLY|N.O_CREAT|N.O_EXCL|(N.O_NOFOLLOW??0),384);try{ae(h,O),K(h)}finally{V(h)}const u=q(M(o),N.O_RDONLY|(N.O_DIRECTORY??0));try{K(u)}finally{V(u)}}if(re(o,S),C(o)!==n||L(o)!==g||X(o,t).planSha256!==i)throw new Error("refactor-root-source-dirty");for(const h of f)T(o,h.path);const P={kind:"root-refactor-write-set-admission",storyId:t,sourceHead:l.sourceHead,planSha256:i,writeSetSha256:fe(x),admissionSha256:S,fileCount:p.length,rootEditPrepared:!0,privateChildAuthorized:!1,gitCommitAuthorized:!1,publicSafe:!0};return x.schemaVersion===2?Object.freeze({schemaVersion:2,...P,newFileCount:f.length}):Object.freeze({schemaVersion:1,...P})}catch(l){throw l instanceof Error&&l.message.startsWith("refactor-root-")?l:new Error("refactor-root-write-set-invalid")}}function U(s,t){if(!_(t)||te(s,t)||E(s,["ls-files","--stage","-z","--",t]).length>0)throw new Error("refactor-root-delta-outside-admission");const i=A(s,t),e=ce(i);if(!v(e).isDirectory()||j(e)!==e)throw new Error("refactor-root-delta-outside-admission");const r=v(i);if(j(i)!==i||!r.isFile()||r.isSymbolicLink()||r.size===0||r.size>D||(r.mode&75)!==0)throw new Error("refactor-root-delta-outside-admission");const a=H(i);if(a.length===0||a.length>D||a.includes(0))throw new Error("refactor-root-delta-outside-admission");return new TextDecoder("utf-8",{fatal:!0}).decode(a),y(a)}function Ee(s,t){return le(s,t,!1).receipt}function Ae(s,t){return le(s,t,!0)}function le(s,t,i){const e=F(s);try{const r=re(e,t),a=E(e,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(a!==r.sourceHead||C(e)!==r.indexSha256||L(e)!==r.sidecarSha256)throw new Error("refactor-root-baseline-stale");W(e);const o=A(e,"docs","stories",`${r.storyId}.story.md`),l=v(o);if(!l.isFile()||l.isSymbolicLink()||j(o)!==o||y(H(o))!==r.storySha256||y(E(e,["show",`HEAD:docs/stories/${r.storyId}.story.md`]))!==r.storySha256)throw new Error("refactor-root-baseline-stale");const n=I(e,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(u=>!u.startsWith(".neocortex/")),g=I(e,["ls-files","--others","--exclude-standard","-z"]).filter(u=>!u.startsWith(".neocortex/")),m=new Set(r.files.map(u=>u.path)),w=r.schemaVersion===2?r.newFiles.map(u=>u.path):[],p=[];if(i){for(const u of w)if(u.endsWith(".md"))try{v(A(e,u))}catch(b){if(b.code!=="ENOENT")throw b;T(e,u),p.push(u)}}const f=w.filter(u=>!p.includes(u)),d=new Set(w);if(n.length+g.length===0||g.length!==f.length||n.some(u=>!m.has(u))||g.some(u=>!d.has(u)))throw new Error("refactor-root-delta-outside-admission");let c=0;const S=[];for(const u of r.files){const b=A(e,u.path);if(y(E(e,["show",`HEAD:${u.path}`]))!==u.sha256)throw new Error("refactor-root-admission-invalid");const z=v(b);if(j(b)!==b||!z.isFile()||z.isSymbolicLink()||z.size===0||z.size>D||(z.mode&511)!==u.mode)throw new Error("refactor-root-delta-outside-admission");const k=H(b);if(k.length===0||k.length>D)throw new Error("refactor-root-delta-outside-admission");if(new TextDecoder("utf-8",{fatal:!0}).decode(k),k.includes(0))throw new Error("refactor-root-delta-outside-admission");const B=y(k);S.push(B),B!==u.sha256&&c++}const x=f.map(u=>U(e,u));c+=x.length;const R=I(e,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(u=>!u.startsWith(".neocortex/")),O=I(e,["ls-files","--others","--exclude-standard","-z"]).filter(u=>!u.startsWith(".neocortex/"));if(W(e),c===0||c!==n.length+g.length||R.join("\0")!==n.join("\0")||O.join("\0")!==g.join("\0")||r.files.some((u,b)=>{const z=A(e,u.path),k=v(z);if(j(z)!==z||!k.isFile()||k.isSymbolicLink()||k.size>D||(k.mode&511)!==u.mode)return!0;const B=H(z);return B.length>D||y(B)!==S[b]})||f.some((u,b)=>U(e,u)!==x[b])||C(e)!==r.indexSha256||L(e)!==r.sidecarSha256||E(e,["rev-parse","--verify","HEAD"]).toString("utf8").trim()!==a)throw new Error("refactor-root-baseline-stale");for(const u of p)T(e,u);const P={kind:"root-refactor-delta-containment",storyId:r.storyId,sourceHead:r.sourceHead,planSha256:r.planSha256,admissionSha256:t,writeSetSha256:fe(r),changedFileCount:c,rootEditContained:!0,qaAccepted:!1,gitCommitAuthorized:!1,publicSafe:!0},h=r.schemaVersion===2?Object.freeze({schemaVersion:2,...P,newFileCount:f.length}):Object.freeze({schemaVersion:1,...P});return Object.freeze({receipt:h,pendingDocumentationPaths:Object.freeze(p)})}catch(r){throw r instanceof Error&&r.message.startsWith("refactor-root-")?r:new Error("refactor-root-delta-unverified")}}function X(s,t){if(!Q.test(t))throw new Error("refactor-root-story-invalid");const i=F(s);try{if(j(i)!==i||!v(i).isDirectory())throw new Error("refactor-root-source-unverified");if(E(i,["rev-parse","--show-toplevel"]).toString("utf8").trim()!==i)throw new Error("refactor-root-source-unverified");if(E(i,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(f=>!/^.{2} \.neocortex\//.test(f)))throw new Error("refactor-root-source-dirty");const a=E(i,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(a))throw new Error("refactor-root-source-unverified");const o=`docs/stories/${t}.story.md`,l=A(i,o),n=v(l);if(j(l)!==l||!n.isFile()||n.isSymbolicLink()||n.size===0||n.size>1024*1024)throw new Error("refactor-root-story-unverified");const g=H(l),m=E(i,["show",`HEAD:${o}`]);if(!g.equals(m))throw new Error("refactor-root-story-unverified");const w=y(g),p=y(`root-refactor-story-scope-v1\0${a}\0${t}\0${w}`);return Object.freeze({schemaVersion:1,kind:"root-refactor-story-scope",storyId:t,sourceHead:a,storySha256:w,planSha256:p,candidateWriteSetRequired:!0,characterizationRequired:!0,executionAuthorized:!1,gitAuthority:"ROOT_ONLY",graphExecution:"NOT_RUN",publicSafe:!0})}catch(e){throw e instanceof Error&&e.message.startsWith("refactor-root-")?e:new Error("refactor-root-source-unverified")}}function xe(s){let t="",i="",e="",r="",a="",o=!1,l=!1;const n=[],g=[];let m="plain";try{const w=[...s];t=w.shift()??"";for(let f=0;f<w.length;f++){const d=w[f],c=()=>{const S=w[++f];if(!S||S.startsWith("--"))throw new Error("refactor-root-arguments-invalid");return S};if(d==="--project-root")i=c();else if(d==="--story")e=c();else if(d==="--target-stdin"){if(l)throw new Error("refactor-root-arguments-invalid");l=!0}else if(d==="--plan-sha")r=c();else if(d==="--admission-sha")a=c();else if(d==="--path")n.push(c());else if(d==="--new-path")g.push(c());else if(d==="--authorize-root-edit")o=!0;else if(d==="--format")m=c();else throw new Error("refactor-root-arguments-invalid")}if(!i||!["plain","json"].includes(m))throw new Error("refactor-root-arguments-invalid");if(l!==["target-plan","target-admit","target-verify"].includes(t)||l&&e)throw new Error("refactor-root-arguments-invalid");let p;if(l){const f=Buffer.alloc(65537);let d=0;for(;d<f.length;){const c=se(0,f,d,f.length-d,null);if(!c)break;d+=c}if(!d||d>65536)throw new Error("refactor-root-arguments-invalid");try{p=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f.subarray(0,d)))}catch{throw new Error("refactor-root-arguments-invalid")}}if(t==="target-plan"&&p&&!r&&!a&&n.length===0&&g.length===0&&!o)process.stdout.write(`${JSON.stringify({ok:!0,plan:oe(i,p)})}
4
+ `);else if(t==="target-admit"&&p&&r&&!a&&n.length+g.length>0){const f=oe(i,p);if(f.planSha256!==r)throw new Error("refactor-root-target-plan-unverified");const d=ve(i,f,p,n,g,o);process.stdout.write(`${JSON.stringify({ok:!0,admission:d})}
5
+ `)}else if(t==="target-verify"&&p&&!r&&a&&n.length===0&&g.length===0&&!o)process.stdout.write(`${JSON.stringify({ok:!0,containment:Oe(i,a,p)})}
6
+ `);else if(t==="plan"&&e&&!r&&!a&&n.length===0&&g.length===0&&!o){const f=X(i,e);process.stdout.write(`${JSON.stringify({ok:!0,plan:f})}
7
+ `)}else if(t==="admit"&&e&&r&&!a&&n.length+g.length>0){const f=Se(i,e,r,n,o,g);process.stdout.write(`${JSON.stringify({ok:!0,admission:f})}
8
+ `)}else if(t==="verify"&&!e&&!r&&a&&n.length===0&&g.length===0&&!o){const f=Ee(i,a);process.stdout.write(`${JSON.stringify({ok:!0,containment:f})}
9
+ `)}else throw new Error("refactor-root-arguments-invalid");return 0}catch(w){const p=w instanceof Error&&/^refactor-root-[a-z-]+$/.test(w.message)?w.message:"refactor-root-source-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:p})}
10
+ `),1}}function oe(s,t){return ie(s,t,!0)}function Ne(s,t){return ie(s,t,!1)}function ie(s,t,i){const e=F(s),r=()=>{throw new Error("refactor-root-target-invalid")};(!t||typeof t!="object"||Array.isArray(t))&&r();const a=Object.keys(t).sort().join(",");let o=null,l=null,n;if(t.kind==="story"&&a==="kind,storyId"&&Q.test(t.storyId)?(l=t.storyId,o=`docs/stories/${t.storyId}.story.md`):t.kind==="epic"&&a==="epicId,kind"&&/^P[1-9][0-9]{0,11}$/.test(t.epicId)?(l=t.epicId,o=`docs/epics/epic-${t.epicId}.md`):t.kind==="idea"&&a==="idea,kind"&&typeof t.idea=="string"&&t.idea.trim()&&!t.idea.includes("\0")&&Buffer.byteLength(t.idea,"utf8")<=8192&&Buffer.from(t.idea,"utf8").toString("utf8")===t.idea?n=y(Buffer.from(t.idea,"utf8")):r(),j(e)!==e||!v(e).isDirectory()||E(e,["rev-parse","--show-toplevel"]).toString("utf8").trim()!==e)throw new Error("refactor-root-source-unverified");const g=()=>E(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8"),m=g();if(i&&m.split("\0").filter(Boolean).some(O=>!/^.{2} \.neocortex\//.test(O)))throw new Error("refactor-root-source-dirty");const w=E(e,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(w))throw new Error("refactor-root-source-unverified");o&&(n=ee(e,o).sha256);const p=y(JSON.stringify(["root-refactor-target-v2",t.kind,l,n])),f=v(e),d=E(e,["rev-parse","--git-common-dir"]).toString("utf8").trim(),c=Z(d)?F(d):F(e,d),S=v(c);if(j(c)!==c||!S.isDirectory()||S.isSymbolicLink()||S.uid!==process.getuid?.())throw new Error("refactor-root-source-unverified");const x=y(JSON.stringify(["root-refactor-project-v2",e,f.dev,f.ino,c,S.dev,S.ino])),R=y(JSON.stringify(["root-refactor-target-plan-v2",x,w,p]));if(w!==E(e,["rev-parse","--verify","HEAD"]).toString("utf8").trim()||m!==g())throw new Error("refactor-root-source-raced");return Object.freeze({schemaVersion:2,kind:"root-refactor-target-scope",targetKind:t.kind,targetId:l,sourceHead:w,projectBindingSha256:x,targetContentSha256:n,targetSha256:p,planSha256:R,scopeId:`rfs_${R}`,candidateWriteSetRequired:!0,characterizationRequired:!0,executionAuthorized:!1,gitAuthority:"ROOT_ONLY",graphExecution:"NOT_RUN",publicSafe:!0})}function G(s,t,i){const e=oe(s,i),r=Object.keys(e);if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).sort().join(",")!==[...r].sort().join(",")||r.some(a=>t[a]!==e[a]))throw new Error("refactor-root-target-plan-unverified");return e}function Re(s,t,i,e){const r=G(s,t,i);if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).sort().join(",")!=="generationId,includeScopeDecision,runId"||typeof e.runId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(e.runId)||typeof e.generationId!="string"||!/^sha256:[a-f0-9]{64}$/.test(e.generationId)||typeof e.includeScopeDecision!="boolean"||r.targetKind!=="story"&&!e.includeScopeDecision)throw new Error("refactor-root-target-control-invalid");const a=y(JSON.stringify(["root-refactor-target-control-v2",r.projectBindingSha256,r.sourceHead,r.targetSha256,r.planSha256,e.runId,e.generationId,e.includeScopeDecision]));return Object.freeze({schemaVersion:2,kind:"root-refactor-target-control-binding",scopeId:r.scopeId,targetKind:r.targetKind,planSha256:r.planSha256,controlBindingSha256:a,runId:e.runId,generationId:e.generationId,includeScopeDecision:e.includeScopeDecision,executionAuthorized:!1,graphExecution:"NOT_RUN",qaAccepted:!1,gitAuthority:"NONE"})}function he(s,t){if(!$.test(t))throw new Error("refactor-root-target-admission-invalid");return A(M(s),`target-admission-${t}.json`)}function ue(s){return y(JSON.stringify(["root-refactor-target-write-set-v3",s.targetPlan.scopeId,s.targetPlan.planSha256,s.files,s.newFiles]))}function we(s,t,i){const e=F(s),r=ie(e,i,!1),a=he(e,t),o=v(a);if(!o.isFile()||o.isSymbolicLink()||j(a)!==a||o.uid!==process.getuid?.()||(o.mode&63)!==0||o.size<100||o.size>512*1024)throw new Error("refactor-root-target-admission-invalid");const l=H(a);let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l))}catch{throw new Error("refactor-root-target-admission-invalid")}const g=["schemaVersion","kind","targetPlan","indexSha256","sidecarSha256","files","newFiles","admissionSha256"];if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join(",")!==g.sort().join(",")||n.schemaVersion!==3||n.kind!=="private-root-refactor-target-admission"||!$.test(n.indexSha256)||!$.test(n.sidecarSha256)||!Array.isArray(n.files)||!Array.isArray(n.newFiles)||n.files.length+n.newFiles.length<1||n.files.length+n.newFiles.length>Y||n.admissionSha256!==t||!l.equals(Buffer.from(`${JSON.stringify(n)}
11
+ `)))throw new Error("refactor-root-target-admission-invalid");const{admissionSha256:m,...w}=n;if(y(`root-refactor-target-admission-v3\0${JSON.stringify(w)}`)!==t)throw new Error("refactor-root-target-admission-invalid");if(!n.targetPlan||typeof n.targetPlan!="object"||Array.isArray(n.targetPlan)||Object.keys(n.targetPlan).sort().join(",")!==Object.keys(r).sort().join(",")||Object.keys(r).some(c=>n.targetPlan[c]!==r[c]))throw new Error("refactor-root-target-plan-unverified");const p=n.files.map(c=>c?.path),f=n.newFiles.map(c=>c?.path),d=i.kind==="story"?`docs/stories/${i.storyId}.story.md`:i.kind==="epic"?`docs/epics/epic-${i.epicId}.md`:null;if(n.files.some(c=>!c||Object.keys(c).sort().join(",")!=="mode,path,sha256"||typeof c.path!="string"||!_(c.path)||!$.test(c.sha256)||!Number.isSafeInteger(c.mode)||c.mode<0||c.mode>511||y(E(e,["show",`HEAD:${c.path}`]))!==c.sha256)||n.newFiles.some(c=>!c||Object.keys(c).join(",")!=="path"||typeof c.path!="string"||!_(c.path)||E(e,["ls-files","--stage","-z","--",c.path]).length>0||te(e,c.path))||new Set([...p,...f]).size!==p.length+f.length||p.join("\0")!==J(p).join("\0")||f.join("\0")!==J(f).join("\0")||d!==null&&[...p,...f].includes(d))throw new Error("refactor-root-target-admission-invalid");if(W(e),C(e)!==n.indexSha256||L(e)!==n.sidecarSha256)throw new Error("refactor-root-source-dirty");return Object.freeze({...n,targetPlan:r,files:Object.freeze(n.files.map(c=>Object.freeze({...c}))),newFiles:Object.freeze(n.newFiles.map(c=>Object.freeze({...c})))})}function ve(s,t,i,e,r,a){if(!a)throw new Error("refactor-root-authorization-required");if(!Array.isArray(e)||!Array.isArray(r)||e.length+r.length<1||e.length+r.length>Y||[...e,...r].some(O=>typeof O!="string"||!_(O)))throw new Error("refactor-root-write-set-invalid");const o=F(s),l=G(o,t,i);W(o);const n=C(o),g=L(o),m=J(e),w=J(r),p=i.kind==="story"?`docs/stories/${i.storyId}.story.md`:i.kind==="epic"?`docs/epics/epic-${i.epicId}.md`:null;if(new Set([...m,...w]).size!==m.length+w.length||p!==null&&[...m,...w].includes(p))throw new Error("refactor-root-write-set-invalid");const f=m.map(O=>Object.freeze({path:O,...ee(o,O)})),d=w.map(O=>(T(o,O),Object.freeze({path:O})));if(C(o)!==n||L(o)!==g||G(o,t,i).planSha256!==l.planSha256)throw new Error("refactor-root-source-raced");const c={schemaVersion:3,kind:"private-root-refactor-target-admission",targetPlan:l,indexSha256:n,sidecarSha256:g,files:f,newFiles:d},S=y(`root-refactor-target-admission-v3\0${JSON.stringify(c)}`),x={...c,admissionSha256:S},R=he(o,S);if(!ne(R)){const O=q(R,N.O_WRONLY|N.O_CREAT|N.O_EXCL|(N.O_NOFOLLOW??0),384);try{ae(O,`${JSON.stringify(x)}
12
+ `),K(O)}finally{V(O)}const P=q(M(o),N.O_RDONLY|(N.O_DIRECTORY??0));try{K(P)}finally{V(P)}}we(o,S,i),G(o,t,i);for(const O of d)T(o,O.path);return Object.freeze({schemaVersion:3,kind:"root-refactor-target-write-set-admission",scopeId:l.scopeId,targetKind:l.targetKind,sourceHead:l.sourceHead,planSha256:l.planSha256,admissionSha256:S,writeSetSha256:ue(x),fileCount:f.length,newFileCount:d.length,rootEditPrepared:!0,privateChildAuthorized:!1,gitCommitAuthorized:!1,publicSafe:!0})}function Oe(s,t,i){return me(s,t,i,!1).receipt}function De(s,t,i){return me(s,t,i,!0)}function me(s,t,i,e){const r=F(s);try{const a=we(r,t,i),o=E(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(o!==a.targetPlan.sourceHead||C(r)!==a.indexSha256||L(r)!==a.sidecarSha256)throw new Error("refactor-root-baseline-stale");W(r);const l=I(r,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(h=>!h.startsWith(".neocortex/")),n=I(r,["ls-files","--others","--exclude-standard","-z"]).filter(h=>!h.startsWith(".neocortex/")),g=new Set(a.files.map(h=>h.path)),m=a.newFiles.map(h=>h.path),w=[];if(e){for(const h of m)if(h.endsWith(".md"))try{v(A(r,h))}catch(u){if(u.code!=="ENOENT")throw u;T(r,h),w.push(h)}}const p=m.filter(h=>!w.includes(h)),f=new Set(m);if(l.length+n.length===0||n.length!==p.length||l.some(h=>!g.has(h))||n.some(h=>!f.has(h)))throw new Error("refactor-root-delta-outside-admission");let d=0;const c=[];for(const h of a.files){const u=A(r,h.path);if(y(E(r,["show",`HEAD:${h.path}`]))!==h.sha256)throw new Error("refactor-root-admission-invalid");const b=v(u);if(j(u)!==u||!b.isFile()||b.isSymbolicLink()||b.size===0||b.size>D||(b.mode&511)!==h.mode)throw new Error("refactor-root-delta-outside-admission");const z=H(u);if(z.length===0||z.length>D)throw new Error("refactor-root-delta-outside-admission");if(new TextDecoder("utf-8",{fatal:!0}).decode(z),z.includes(0))throw new Error("refactor-root-delta-outside-admission");const k=y(z);c.push(k),k!==h.sha256&&d++}const S=p.map(h=>U(r,h));d+=S.length;const x=I(r,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(h=>!h.startsWith(".neocortex/")),R=I(r,["ls-files","--others","--exclude-standard","-z"]).filter(h=>!h.startsWith(".neocortex/"));if(W(r),d===0||d!==l.length+n.length||x.join("\0")!==l.join("\0")||R.join("\0")!==n.join("\0")||a.files.some((h,u)=>{const b=A(r,h.path),z=v(b);if(j(b)!==b||!z.isFile()||z.isSymbolicLink()||z.size>D||(z.mode&511)!==h.mode)return!0;const k=H(b);return k.length>D||y(k)!==c[u]})||p.some((h,u)=>U(r,h)!==S[u])||C(r)!==a.indexSha256||L(r)!==a.sidecarSha256||E(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim()!==o)throw new Error("refactor-root-baseline-stale");for(const h of w)T(r,h);const O={kind:"root-refactor-target-delta-containment",scopeId:a.targetPlan.scopeId,targetKind:a.targetPlan.targetKind,sourceHead:a.targetPlan.sourceHead,planSha256:a.targetPlan.planSha256,admissionSha256:t,writeSetSha256:ue(a),changedFileCount:d,rootEditContained:!0,qaAccepted:!1,gitCommitAuthorized:!1,publicSafe:!0},P=Object.freeze({schemaVersion:3,...O,newFileCount:p.length});return Object.freeze({receipt:P,pendingDocumentationPaths:Object.freeze(w)})}catch(a){throw a instanceof Error&&a.message.startsWith("refactor-root-")?a:new Error("refactor-root-delta-unverified")}}export{Se as admitRootRefactor,ve as admitRootRefactorTarget,Re as bindRootRefactorTargetControl,ee as exactCommittedRefactorFile,Ne as inspectRootRefactorTargetIdentity,X as planRootRefactor,oe as planRootRefactorTarget,M as privateRefactorDirectory,re as readPrivateRefactorAdmission,we as readPrivateRefactorTargetAdmission,xe as refactorRootCliHandler,L as refactorSidecarDigest,Ee as verifyRootRefactor,Ae as verifyRootRefactorForCharacterization,Oe as verifyRootRefactorTargetDelta,De as verifyRootRefactorTargetForCharacterization,G as verifyRootRefactorTargetPlan};
@@ -5,6 +5,7 @@ export interface RefreshMemoryCliOptions {
5
5
  readonly targetIds: readonly ProjectMemoryTargetId[];
6
6
  readonly dryRun: boolean;
7
7
  readonly verify?: boolean;
8
+ readonly backupDirectory?: string;
8
9
  readonly memoryNotes?: readonly string[];
9
10
  }
10
11
  export interface ProjectMemoryVerification {
@@ -1,3 +1,3 @@
1
- import{createHash as m}from"node:crypto";import{lstatSync as w,readFileSync as f}from"node:fs";import{join as g,resolve as R}from"node:path";import{getProjectMemoryTarget as E,isProjectMemoryTargetId as b,listProjectMemoryTargets as u}from"../memory/shared-project-memory-types.js";import{writeProjectMemoryTargetFiles as v}from"../memory/project-memory-writer.js";function h(r){return(r??"").split(",").map(t=>t.trim()).filter(Boolean)}function M(r){let t=process.cwd(),c=!1,i=!1;const a=[],o=[];for(let s=0;s<r.length;s++){const e=r[s];if(e==="--dry-run"||e==="--preview")c=!0;else if(e==="--verify")i=!0,c=!0;else if(e==="--project-root")t=r[++s]??t;else if(e.startsWith("--project-root="))t=e.slice(15);else if(e==="--target"||e==="--targets")a.push(...h(r[++s]));else if(e.startsWith("--target="))a.push(...h(e.slice(9)));else if(e.startsWith("--targets="))a.push(...h(e.slice(10)));else if(e==="--note"||e==="--memory-note"||e==="--change"){const n=r[++s];n&&o.push(n)}else e.startsWith("--note=")?o.push(e.slice(7)):e.startsWith("--memory-note=")?o.push(e.slice(14)):e.startsWith("--change=")&&o.push(e.slice(9))}if(i&&(a.length>0||o.length>0))throw new Error("Project memory verification requires all targets and no update notes.");const l=a.length>0?a.map(s=>{if(!b(s))throw new Error(`Unknown project-memory target: ${s}`);return s}):["canonical",...u().map(s=>s.targetId)];return{projectRoot:R(t),targetIds:Array.from(new Set(l)),dryRun:c,verify:i,memoryNotes:o}}function d(r){return r.targetIds.map(t=>v({projectRoot:r.projectRoot,targetId:t,dryRun:r.dryRun,memoryNotes:r.memoryNotes??[]}))}function P(r){if(!r.verify||!r.dryRun||r.memoryNotes?.length||r.targetIds.join(",")!==["canonical",...u().map(n=>n.targetId)].join(","))throw new Error("Project memory verification requires the complete read-only target set.");const t=g(r.projectRoot,"NEOCORTEX.md");let c;try{c=w(t)}catch{throw new Error("Canonical project memory is missing or unsafe.")}if(!c.isFile()||c.isSymbolicLink())throw new Error("Canonical project memory must be a regular file.");const i=f(t,"utf8"),a="<!-- NEOCORTEX-MEMORY-START -->",o="<!-- NEOCORTEX-MEMORY-END -->",l=E("canonical").budget;if(i.split(a).length!==2||i.split(o).length!==2||i.indexOf(a)>=i.indexOf(o)||Buffer.byteLength(i,"utf8")>l.maxBytes||i.split(`
2
- `).length>l.maxLines)throw new Error("Canonical project memory markers or budget are invalid.");const s=d(r).flatMap(n=>n.files);if(s.some(n=>n.changed||n.mode==="compatibility-materialized-fallback"||n.fallbackReason||n.remediationDebt))throw new Error("Project memory verification found stale or fallback targets.");let e;try{if(e=[...new Set(s.map(n=>n.relativeFile))].sort().map(n=>{const y=f(g(r.projectRoot,n)),p=s.find(j=>j.relativeFile===n).mode;return`${n}:${p}:${m("sha256").update(y).digest("hex")}`}),f(t,"utf8")!==i||d(r).some(n=>n.changed))throw new Error("project-memory-verification-race")}catch{throw new Error("Project memory changed during verification.")}return{schemaVersion:"ProjectMemoryVerification/1",canonicalSha256:m("sha256").update(i).digest("hex"),projectionSha256:m("sha256").update(e.join(`
3
- `)).digest("hex"),fileCount:e.length,publicSafe:!0}}async function O(r){try{const t=M(r);if(t.verify){const a=P(t);return console.log(`Project memory verified: files=${a.fileCount} canonical_sha256=${a.canonicalSha256} projection_sha256=${a.projectionSha256}`),0}const i=d(t).flatMap(a=>a.files.map(o=>[o.changed?t.dryRun?"would-change":"changed":"unchanged",o.mode,o.relativeFile,o.fallbackReason?`warning=${o.fallbackReason}`:void 0,o.remediationDebt?`debt=${o.remediationDebt}`:void 0,o.reasonCodes&&o.reasonCodes.length>0?`reasons=${o.reasonCodes.join(",")}`:void 0].filter(Boolean).join(" ")));console.log(`${t.dryRun?"Project memory preview":"Project memory refreshed"}: ${t.projectRoot}`);for(const a of i)console.log(a);return 0}catch(t){return console.error(t instanceof Error?t.message:String(t)),1}}export{M as parseRefreshMemoryArgs,O as refreshMemoryCliHandler,d as refreshProjectMemoryTargets,P as verifyProjectMemoryTargets};
1
+ import{createHash as m}from"node:crypto";import{lstatSync as w,readFileSync as f}from"node:fs";import{join as u,resolve as R}from"node:path";import{getProjectMemoryTarget as b,isProjectMemoryTargetId as E,listProjectMemoryTargets as g}from"../memory/shared-project-memory-types.js";import{writeProjectMemoryTargetFiles as v}from"../memory/project-memory-writer.js";function h(r){return(r??"").split(",").map(t=>t.trim()).filter(Boolean)}function M(r){let t=process.cwd(),c=!1,i=!1;const a=[],o=[];for(let s=0;s<r.length;s++){const e=r[s];if(e==="--dry-run"||e==="--preview")c=!0;else if(e==="--verify")i=!0,c=!0;else if(e==="--project-root")t=r[++s]??t;else if(e.startsWith("--project-root="))t=e.slice(15);else if(e==="--target"||e==="--targets")a.push(...h(r[++s]));else if(e.startsWith("--target="))a.push(...h(e.slice(9)));else if(e.startsWith("--targets="))a.push(...h(e.slice(10)));else if(e==="--note"||e==="--memory-note"||e==="--change"){const n=r[++s];n&&o.push(n)}else e.startsWith("--note=")?o.push(e.slice(7)):e.startsWith("--memory-note=")?o.push(e.slice(14)):e.startsWith("--change=")&&o.push(e.slice(9))}if(i&&(a.length>0||o.length>0))throw new Error("Project memory verification requires all targets and no update notes.");const l=a.length>0?a.map(s=>{if(!E(s))throw new Error(`Unknown project-memory target: ${s}`);return s}):["canonical",...g().map(s=>s.targetId)];return{projectRoot:R(t),targetIds:Array.from(new Set(l)),dryRun:c,verify:i,memoryNotes:o}}function d(r){return r.targetIds.map(t=>v({projectRoot:r.projectRoot,targetId:t,dryRun:r.dryRun,memoryNotes:r.memoryNotes??[],backupDirectory:r.backupDirectory}))}function P(r){if(!r.verify||!r.dryRun||r.memoryNotes?.length||r.targetIds.join(",")!==["canonical",...g().map(n=>n.targetId)].join(","))throw new Error("Project memory verification requires the complete read-only target set.");const t=u(r.projectRoot,"NEOCORTEX.md");let c;try{c=w(t)}catch{throw new Error("Canonical project memory is missing or unsafe.")}if(!c.isFile()||c.isSymbolicLink())throw new Error("Canonical project memory must be a regular file.");const i=f(t,"utf8"),a="<!-- NEOCORTEX-MEMORY-START -->",o="<!-- NEOCORTEX-MEMORY-END -->",l=b("canonical").budget;if(i.split(a).length!==2||i.split(o).length!==2||i.indexOf(a)>=i.indexOf(o)||Buffer.byteLength(i,"utf8")>l.maxBytes||i.split(`
2
+ `).length>l.maxLines)throw new Error("Canonical project memory markers or budget are invalid.");const s=d(r).flatMap(n=>n.files);if(s.some(n=>n.changed||n.mode==="compatibility-materialized-fallback"||n.fallbackReason||n.remediationDebt))throw new Error("Project memory verification found stale or fallback targets.");let e;try{if(e=[...new Set(s.map(n=>n.relativeFile))].sort().map(n=>{const y=f(u(r.projectRoot,n)),p=s.find(j=>j.relativeFile===n).mode;return`${n}:${p}:${m("sha256").update(y).digest("hex")}`}),f(t,"utf8")!==i||d(r).some(n=>n.changed))throw new Error("project-memory-verification-race")}catch{throw new Error("Project memory changed during verification.")}return{schemaVersion:"ProjectMemoryVerification/1",canonicalSha256:m("sha256").update(i).digest("hex"),projectionSha256:m("sha256").update(e.join(`
3
+ `)).digest("hex"),fileCount:e.length,publicSafe:!0}}async function k(r){try{const t=M(r);if(t.verify){const a=P(t);return console.log(`Project memory verified: files=${a.fileCount} canonical_sha256=${a.canonicalSha256} projection_sha256=${a.projectionSha256}`),0}const i=d(t).flatMap(a=>a.files.map(o=>[o.changed?t.dryRun?"would-change":"changed":"unchanged",o.mode,o.relativeFile,o.fallbackReason?`warning=${o.fallbackReason}`:void 0,o.remediationDebt?`debt=${o.remediationDebt}`:void 0,o.reasonCodes&&o.reasonCodes.length>0?`reasons=${o.reasonCodes.join(",")}`:void 0].filter(Boolean).join(" ")));console.log(`${t.dryRun?"Project memory preview":"Project memory refreshed"}: ${t.projectRoot}`);for(const a of i)console.log(a);return 0}catch(t){return console.error(t instanceof Error?t.message:String(t)),1}}export{M as parseRefreshMemoryArgs,k as refreshMemoryCliHandler,d as refreshProjectMemoryTargets,P as verifyProjectMemoryTargets};
@@ -0,0 +1,19 @@
1
+ /** Public architecture stage projection required by the standalone client. */
2
+ export declare const ARCHITECTURE_PUBLIC_STAGE_COMMANDS: readonly ["arch-prd", "arch-architecture", "arch-fitness-functions", "arch-api-contracts", "generate-pacts", "arch-api-integrations", "arch-database", "arch-security", "arch-design-system", "arch-ux-design", "arch-performance", "arch-testing", "arch-infrastructure", "arch-review", "update-memory"];
3
+ export declare const NON_UI_ARCHITECTURE_STAGE_COMMANDS: readonly ["arch-prd", "arch-architecture", "arch-fitness-functions", "arch-api-contracts", "generate-pacts", "arch-api-integrations", "arch-database", "arch-security", "arch-performance", "arch-testing", "arch-infrastructure", "arch-review", "update-memory"];
4
+ export interface ArchitectureNonUiScopeReceipt {
5
+ readonly schemaVersion: 1;
6
+ readonly kind: 'ArchitectureNonUiScope/1';
7
+ readonly licenseHash: string;
8
+ readonly projectHash: string;
9
+ readonly targetEpicId: string;
10
+ readonly graphRevision: string;
11
+ readonly rootInputSha256: string;
12
+ readonly accountingId: string;
13
+ readonly applicability: 'non-ui';
14
+ readonly excludedStageCommands: readonly string[];
15
+ readonly macSha256: string;
16
+ readonly publicSafe: true;
17
+ }
18
+ /** Public syntax only. Authenticity is checked by the server. */
19
+ export declare function parseArchitectureNonUiScopeReceipt(value: unknown): ArchitectureNonUiScopeReceipt | undefined;
@@ -0,0 +1 @@
1
+ const i=Object.freeze(["arch-prd","arch-architecture","arch-fitness-functions","arch-api-contracts","generate-pacts","arch-api-integrations","arch-database","arch-security","arch-design-system","arch-ux-design","arch-performance","arch-testing","arch-infrastructure","arch-review","update-memory"]),s=Object.freeze(["arch-prd","arch-architecture","arch-fitness-functions","arch-api-contracts","generate-pacts","arch-api-integrations","arch-database","arch-security","arch-performance","arch-testing","arch-infrastructure","arch-review","update-memory"]),a=Object.freeze(["arch-design-system","arch-ux-design"]);function o(r){if(!r||typeof r!="object"||Array.isArray(r))return;const e=r,c=["schemaVersion","kind","licenseHash","projectHash","targetEpicId","graphRevision","rootInputSha256","accountingId","applicability","excludedStageCommands","macSha256","publicSafe"];if(!(Object.keys(e).sort().join(",")!==c.sort().join(",")||e.schemaVersion!==1||e.kind!=="ArchitectureNonUiScope/1"||e.publicSafe!==!0||e.applicability!=="non-ui"||typeof e.targetEpicId!="string"||!/^P[1-9][0-9]{0,11}$/.test(e.targetEpicId)||typeof e.accountingId!="string"||!/^arch-accounting-[a-f0-9]{32}$/.test(e.accountingId)||!["licenseHash","projectHash","graphRevision","rootInputSha256","macSha256"].every(t=>typeof e[t]=="string"&&/^[a-f0-9]{64}$/.test(e[t])))&&!(!Array.isArray(e.excludedStageCommands)||e.excludedStageCommands.length!==a.length||!e.excludedStageCommands.every((t,n)=>t===a[n])))return Object.freeze({...e,excludedStageCommands:Object.freeze([...a])})}export{i as ARCHITECTURE_PUBLIC_STAGE_COMMANDS,s as NON_UI_ARCHITECTURE_STAGE_COMMANDS,o as parseArchitectureNonUiScopeReceipt};
@@ -1,2 +1,2 @@
1
- const t="support@neocortex.sh",u={AUTH_REFRESH_REQUIRED:{en:{summary:"Authentication must be refreshed.",whatHappened:"Strict read-only mode found configured credentials, but no safely reusable token is available. It did not refresh or change authentication state.",whatToDo:"Re-activate outside strict read-only mode, then retry the command.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"A autentica\xE7\xE3o precisa ser renovada.",whatHappened:"O modo estritamente somente leitura encontrou credenciais configuradas, mas nenhum token reutiliz\xE1vel com seguran\xE7a. Nenhum refresh ou estado de autentica\xE7\xE3o foi alterado.",whatToDo:"Reative fora do modo estritamente somente leitura e tente o comando novamente.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},AUTH_EXPIRED:{en:{summary:"Your session has expired.",whatHappened:"The token we use to authenticate your CLI has expired. This is normal and happens every few hours.",whatToDo:"Re-activate with the license key that was emailed to you.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Sua sess\xE3o expirou.",whatHappened:"O token de autentica\xE7\xE3o do CLI expirou. Isso \xE9 normal e acontece a cada poucas horas.",whatToDo:"Reative o CLI com a license key que voc\xEA recebeu por email.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},UPGRADE_REQUIRED:{en:{summary:"Your CLI version is outdated.",whatHappened:"The server requires a newer CLI version. Older versions are not allowed for security and compatibility reasons.",whatToDo:"Install the latest CLI globally with npm.",command:"npm install -g @ornexus/neocortex@latest"},"pt-BR":{summary:"Sua vers\xE3o do CLI est\xE1 desatualizada.",whatHappened:"O servidor exige uma vers\xE3o mais recente do CLI. Vers\xF5es antigas n\xE3o s\xE3o permitidas por motivos de seguran\xE7a e compatibilidade.",whatToDo:"Instale a vers\xE3o mais recente globalmente via npm.",command:"npm install -g @ornexus/neocortex@latest"}},RATE_LIMITED:{en:{summary:"You sent too many requests in a short window.",whatHappened:"You hit the rate limit for your plan. This protects the service from abuse and keeps it fast for everyone.",whatToDo:"Wait a few seconds and try again. If you hit this often, upgrading your plan raises the limit.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Voc\xEA fez muitas requisi\xE7\xF5es em pouco tempo.",whatHappened:"O limite de taxa do seu plano foi atingido. Isso protege o servi\xE7o contra abuso e mant\xE9m a velocidade para todos.",whatToDo:"Espere alguns segundos e tente novamente. Se isso acontece com frequ\xEAncia, fazer upgrade do seu plano aumenta o limite.",url:"https://neocortex.sh/portal/plans"}},TRIGGER_NOT_ALLOWED:{en:{summary:"This command is not available on your current plan.",whatHappened:"You tried to use a trigger that requires a paid plan (Pro or Enterprise).",whatToDo:"See the full comparison and upgrade in the portal.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Este comando n\xE3o est\xE1 dispon\xEDvel no seu plano atual.",whatHappened:"Voc\xEA tentou usar um trigger que requer um plano pago (Pro ou Enterprise).",whatToDo:"Veja a compara\xE7\xE3o completa e fa\xE7a upgrade no portal.",url:"https://neocortex.sh/portal/plans"}},QUOTA_EXCEEDED:{en:{summary:"Daily quota reached.",whatHappened:"You have used all invocations allowed by your plan today. Quotas reset at midnight UTC.",whatToDo:"Wait for the daily reset, or upgrade your plan for a higher quota.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Quota di\xE1ria atingida.",whatHappened:"Voc\xEA usou todas as invoca\xE7\xF5es permitidas pelo seu plano hoje. As quotas s\xE3o resetadas \xE0 meia-noite UTC.",whatToDo:"Aguarde o reset di\xE1rio ou fa\xE7a upgrade do plano para uma quota maior.",url:"https://neocortex.sh/portal/plans"}},SERVER_ERROR:{en:{summary:"Server error.",whatHappened:"Something went wrong on our side. We have logged the error and will investigate.",whatToDo:`Try again in a minute. If the problem persists, please contact ${t} with the details.`},"pt-BR":{summary:"Erro do servidor.",whatHappened:"Algo deu errado no nosso lado. O erro foi registrado e vamos investigar.",whatToDo:`Tente novamente em um minuto. Se o problema persistir, entre em contato: ${t}.`}},ECONNREFUSED:{en:{summary:"Cannot reach the Neocortex server.",whatHappened:"We could not open a connection to the server. This is usually a network problem on your side.",whatToDo:"Check your internet connection, any VPN or corporate proxy, and try again."},"pt-BR":{summary:"N\xE3o foi poss\xEDvel alcan\xE7ar o servidor Neocortex.",whatHappened:"N\xE3o conseguimos abrir uma conex\xE3o com o servidor. Isso geralmente \xE9 um problema de rede do seu lado.",whatToDo:"Verifique sua conex\xE3o, qualquer VPN ou proxy corporativo, e tente novamente."}},MACHINE_LIMIT_EXCEEDED:{en:{summary:"Machine limit reached.",whatHappened:"Your plan allows a limited number of active machines, and this one would exceed it.",whatToDo:"Deactivate a machine you no longer use from the portal, then re-run activate here.",url:"https://neocortex.sh/portal/machines"},"pt-BR":{summary:"Limite de m\xE1quinas atingido.",whatHappened:"Seu plano permite um n\xFAmero limitado de m\xE1quinas ativas, e esta ultrapassaria o limite.",whatToDo:"Desative uma m\xE1quina que voc\xEA n\xE3o usa mais no portal e rode activate aqui de novo.",url:"https://neocortex.sh/portal/machines"}},NOT_CONFIGURED:{en:{summary:"Neocortex is not configured on this machine.",whatHappened:"No license key was found. You need to run `neocortex activate` once before using the CLI.",whatToDo:"Get a license key from the portal and activate.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Neocortex n\xE3o est\xE1 configurado nesta m\xE1quina.",whatHappened:"Nenhuma license key encontrada. Voc\xEA precisa rodar `neocortex activate` uma vez antes de usar o CLI.",whatToDo:"Pegue uma license key no portal e ative.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}}};function r(o=process.env){return(o.LC_ALL??o.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function p(o,a=r()){const e=u[o];return e?e[a]??e.en??null:null}function c(o,a=r()){const e=[];e.push(""),e.push(`[Neocortex] ${o.summary}`),e.push("");const n=a==="pt-BR"?"O que aconteceu":"What happened",s=a==="pt-BR"?"O que fazer":"What to do",i=a==="pt-BR"?`Precisa de ajuda? ${t}`:`Need help? ${t}`;return e.push(`${n}: ${o.whatHappened}`),e.push(`${s}: ${o.whatToDo}`),o.command&&(e.push(""),e.push(` ${o.command}`)),o.url&&(e.push(""),e.push(` ${o.url}`)),e.push(""),e.push(i),e.push(""),e.join(`
1
+ const t="support@neocortex.sh",u={AUTH_REFRESH_REQUIRED:{en:{summary:"Authentication must be refreshed.",whatHappened:"Credentials are configured, but a valid authentication token is unavailable. The token may have expired or the authentication service may be unreachable. Strict read-only commands do not refresh tokens.",whatToDo:"Check the server connection and retry. If authentication remains unavailable, re-activate outside strict read-only mode.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"A autentica\xE7\xE3o precisa ser renovada.",whatHappened:"As credenciais est\xE3o configuradas, mas n\xE3o h\xE1 um token de autentica\xE7\xE3o v\xE1lido dispon\xEDvel. O token pode ter expirado ou o servi\xE7o de autentica\xE7\xE3o pode estar inacess\xEDvel. Comandos estritamente somente leitura n\xE3o renovam tokens.",whatToDo:"Verifique a conex\xE3o com o servidor e tente novamente. Se a autentica\xE7\xE3o continuar indispon\xEDvel, reative fora do modo estritamente somente leitura.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},AUTH_EXPIRED:{en:{summary:"Your session has expired.",whatHappened:"The token we use to authenticate your CLI has expired. This is normal and happens every few hours.",whatToDo:"Re-activate with the license key that was emailed to you.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Sua sess\xE3o expirou.",whatHappened:"O token de autentica\xE7\xE3o do CLI expirou. Isso \xE9 normal e acontece a cada poucas horas.",whatToDo:"Reative o CLI com a license key que voc\xEA recebeu por email.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},UPGRADE_REQUIRED:{en:{summary:"Your CLI version is outdated.",whatHappened:"The server requires a newer CLI version. Older versions are not allowed for security and compatibility reasons.",whatToDo:"Install the latest CLI globally with npm.",command:"npm install -g @ornexus/neocortex@latest"},"pt-BR":{summary:"Sua vers\xE3o do CLI est\xE1 desatualizada.",whatHappened:"O servidor exige uma vers\xE3o mais recente do CLI. Vers\xF5es antigas n\xE3o s\xE3o permitidas por motivos de seguran\xE7a e compatibilidade.",whatToDo:"Instale a vers\xE3o mais recente globalmente via npm.",command:"npm install -g @ornexus/neocortex@latest"}},RATE_LIMITED:{en:{summary:"You sent too many requests in a short window.",whatHappened:"You hit the rate limit for your plan. This protects the service from abuse and keeps it fast for everyone.",whatToDo:"Wait a few seconds and try again. If you hit this often, upgrading your plan raises the limit.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Voc\xEA fez muitas requisi\xE7\xF5es em pouco tempo.",whatHappened:"O limite de taxa do seu plano foi atingido. Isso protege o servi\xE7o contra abuso e mant\xE9m a velocidade para todos.",whatToDo:"Espere alguns segundos e tente novamente. Se isso acontece com frequ\xEAncia, fazer upgrade do seu plano aumenta o limite.",url:"https://neocortex.sh/portal/plans"}},TRIGGER_NOT_ALLOWED:{en:{summary:"This command is not available on your current plan.",whatHappened:"You tried to use a trigger that requires a paid plan (Pro or Enterprise).",whatToDo:"See the full comparison and upgrade in the portal.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Este comando n\xE3o est\xE1 dispon\xEDvel no seu plano atual.",whatHappened:"Voc\xEA tentou usar um trigger que requer um plano pago (Pro ou Enterprise).",whatToDo:"Veja a compara\xE7\xE3o completa e fa\xE7a upgrade no portal.",url:"https://neocortex.sh/portal/plans"}},QUOTA_EXCEEDED:{en:{summary:"Daily quota reached.",whatHappened:"You have used all invocations allowed by your plan today. Quotas reset at midnight UTC.",whatToDo:"Wait for the daily reset, or upgrade your plan for a higher quota.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Quota di\xE1ria atingida.",whatHappened:"Voc\xEA usou todas as invoca\xE7\xF5es permitidas pelo seu plano hoje. As quotas s\xE3o resetadas \xE0 meia-noite UTC.",whatToDo:"Aguarde o reset di\xE1rio ou fa\xE7a upgrade do plano para uma quota maior.",url:"https://neocortex.sh/portal/plans"}},SERVER_ERROR:{en:{summary:"Server error.",whatHappened:"Something went wrong on our side. We have logged the error and will investigate.",whatToDo:`Try again in a minute. If the problem persists, please contact ${t} with the details.`},"pt-BR":{summary:"Erro do servidor.",whatHappened:"Algo deu errado no nosso lado. O erro foi registrado e vamos investigar.",whatToDo:`Tente novamente em um minuto. Se o problema persistir, entre em contato: ${t}.`}},ECONNREFUSED:{en:{summary:"Cannot reach the Neocortex server.",whatHappened:"We could not open a connection to the server. This is usually a network problem on your side.",whatToDo:"Check your internet connection, any VPN or corporate proxy, and try again."},"pt-BR":{summary:"N\xE3o foi poss\xEDvel alcan\xE7ar o servidor Neocortex.",whatHappened:"N\xE3o conseguimos abrir uma conex\xE3o com o servidor. Isso geralmente \xE9 um problema de rede do seu lado.",whatToDo:"Verifique sua conex\xE3o, qualquer VPN ou proxy corporativo, e tente novamente."}},MACHINE_LIMIT_EXCEEDED:{en:{summary:"Machine limit reached.",whatHappened:"Your plan allows a limited number of active machines, and this one would exceed it.",whatToDo:"Deactivate a machine you no longer use from the portal, then re-run activate here.",url:"https://neocortex.sh/portal/machines"},"pt-BR":{summary:"Limite de m\xE1quinas atingido.",whatHappened:"Seu plano permite um n\xFAmero limitado de m\xE1quinas ativas, e esta ultrapassaria o limite.",whatToDo:"Desative uma m\xE1quina que voc\xEA n\xE3o usa mais no portal e rode activate aqui de novo.",url:"https://neocortex.sh/portal/machines"}},NOT_CONFIGURED:{en:{summary:"Neocortex is not configured on this machine.",whatHappened:"No license key was found. You need to run `neocortex activate` once before using the CLI.",whatToDo:"Get a license key from the portal and activate.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Neocortex n\xE3o est\xE1 configurado nesta m\xE1quina.",whatHappened:"Nenhuma license key encontrada. Voc\xEA precisa rodar `neocortex activate` uma vez antes de usar o CLI.",whatToDo:"Pegue uma license key no portal e ative.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}}};function r(o=process.env){return(o.LC_ALL??o.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function p(o,a=r()){const e=u[o];return e?e[a]??e.en??null:null}function c(o,a=r()){const e=[];e.push(""),e.push(`[Neocortex] ${o.summary}`),e.push("");const n=a==="pt-BR"?"O que aconteceu":"What happened",s=a==="pt-BR"?"O que fazer":"What to do",i=a==="pt-BR"?`Precisa de ajuda? ${t}`:`Need help? ${t}`;return e.push(`${n}: ${o.whatHappened}`),e.push(`${s}: ${o.whatToDo}`),o.command&&(e.push(""),e.push(` ${o.command}`)),o.url&&(e.push(""),e.push(` ${o.url}`)),e.push(""),e.push(i),e.push(""),e.join(`
2
2
  `)}function m(o){if(!o||typeof o!="object")return null;const a=o;return typeof a.code=="string"&&(a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"||a.code==="ETIMEDOUT"||a.code==="ECONNRESET")||typeof a.message=="string"&&(/connect/i.test(a.message)&&/refus/i.test(a.message)||/fetch failed/i.test(a.message))?"ECONNREFUSED":null}export{r as detectErrorLocale,c as formatHumanizedError,p as humanizeError,m as inferErrorCodeFromException};