@ornexus/neocortex 4.60.64 → 4.60.66
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +31 -38
- package/install.js +1 -0
- package/install.ps1 +34 -3
- package/install.sh +35 -3
- package/package.json +9 -5
- package/packages/client/dist/cli.js +1 -1
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -1
- package/packages/client/dist/commands/architecture-root-binding.js +1 -1
- package/packages/client/dist/commands/invoke.d.ts +1 -1
- package/packages/client/dist/commands/invoke.js +79 -78
- package/packages/client/dist/commands/mutation-qa-run.js +2 -2
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -1
- package/packages/client/dist/commands/refactor-characterization.d.ts +3 -10
- package/packages/client/dist/commands/refactor-characterization.js +16 -16
- package/packages/client/dist/commands/refactor-control.d.ts +3 -11
- package/packages/client/dist/commands/refactor-control.js +3 -3
- package/packages/client/dist/commands/refactor-review.d.ts +0 -13
- package/packages/client/dist/commands/refactor-review.js +5 -6
- package/packages/client/dist/commands/refactor-root.d.ts +0 -157
- package/packages/client/dist/commands/refactor-root.js +7 -12
- package/packages/client/dist/commands/shared-architecture-non-ui.d.ts +18 -0
- package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -0
- package/packages/client/dist/commands/story-checkpoint.d.ts +3 -1
- package/packages/client/dist/commands/story-checkpoint.js +1 -1
- package/packages/client/dist/git/direct-yolo-c01-retry.d.ts +21 -0
- package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -0
- package/packages/client/dist/git/git-lifecycle-store.js +1 -1
- package/packages/client/dist/private-execution/clean-baseline.d.ts +2 -9
- package/packages/client/dist/private-execution/clean-baseline.js +2 -2
- package/packages/client/dist/private-execution/codex-executor.d.ts +1 -25
- package/packages/client/dist/private-execution/codex-executor.js +4 -9
- package/packages/client/dist/private-execution/delivery.d.ts +1 -2
- package/packages/client/dist/private-execution/delivery.js +3 -3
- package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
- package/packages/client/dist/private-execution/frozen-handoff.js +4 -5
- package/packages/client/dist/private-execution/implementation-validation.d.ts +1 -10
- package/packages/client/dist/private-execution/implementation-validation.js +2 -2
- package/packages/client/dist/private-execution/isolated-admission.d.ts +2 -0
- package/packages/client/dist/private-execution/isolated-admission.js +16 -11
- package/packages/client/dist/private-execution/isolated-session.d.ts +1 -1
- package/packages/client/dist/private-execution/isolated-session.js +5 -5
- package/packages/client/dist/private-execution/root-memory-git-evidence.d.ts +1 -1
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -3
- package/packages/client/dist/private-execution/root-memory-recovery.d.ts +1 -1
- package/packages/client/dist/private-execution/root-memory-recovery.js +1 -1
- package/packages/client/dist/private-execution/root-memory-scope.d.ts +1 -1
- package/packages/client/dist/private-execution/root-memory-scope.js +1 -1
- package/packages/client/dist/private-execution/root-memory-writer.d.ts +1 -1
- package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
- package/packages/client/dist/private-execution/shared-private-admission-types.d.ts +34 -0
- package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -0
- package/packages/client/dist/private-execution/shared-project-validation.d.ts +17 -0
- package/packages/client/dist/private-execution/shared-project-validation.js +1 -0
- package/packages/client/dist/private-execution/shared-root-memory-types.d.ts +37 -0
- package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -0
- package/packages/client/dist/private-execution/ux-source-validation.js +1 -1
- package/packages/client/dist/runner/binary.d.ts +1 -1
- package/packages/client/dist/runner/binary.js +1 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
- package/packages/client/dist/runner-cli.js +0 -0
- package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +16 -0
- package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -0
- package/packages/client/dist/yolo/spec-envelope-collector.d.ts +7 -0
- package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
- package/packages/shared/dist/architecture-non-ui-scope.js +22 -0
- package/packages/shared/dist/architecture-public-topology.js +11 -0
- package/packages/shared/dist/project-validation-commands.js +10 -32
- package/packages/shared/dist/yolo/spec-envelope.js +2 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +64 -0
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
- package/packages/client/dist/commands/shared-architecture-non-ui-contract.d.ts +0 -19
- package/packages/client/dist/commands/shared-architecture-non-ui-contract.js +0 -1
- package/packages/shared/dist/invocation/packed-invoke.d.ts +0 -12
- package/packages/shared/dist/invocation/packed-invoke.js +0 -58
- package/packages/shared/dist/invocation/packed-invoke.test.d.ts +0 -1
- package/packages/shared/dist/invocation/packed-invoke.test.js +0 -21
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{spawnSync as E}from"node:child_process";import{createHash as q}from"node:crypto";import{existsSync as p,lstatSync as k,mkdirSync as G,mkdtempSync as V,readFileSync as Y,realpathSync as l,rmSync as J,writeFileSync as K}from"node:fs";import{homedir as Z,tmpdir as ee}from"node:os";import{isAbsolute as M,join as u,relative as F,resolve as C,sep as B}from"node:path";import{mutationQaGit as f}from"./mutation-qa-git.js";import{planMutationQa as I}from"./mutation-qa.js";import{evaluateMutationQaReport as te}from"./mutation-qa-verdict.js";const re="reports/mutation/mutation.json",oe=8*1024*1024,ne=1800*1e3,ie=300*1e3;function x(n,t){const a=F(n,t);return a!==".."&&!a.startsWith(`..${B}`)&&!M(a)}function $(n){const t=u(n,re);if(!p(t))return null;const a=l(t);if(a!==t||!x(n,a))throw new Error("mutation-qa-report-path-unsafe");const r=k(t);if(!r.isFile()||r.size===0||r.size>oe)throw new Error("mutation-qa-report-size-invalid");return Y(t)}function se(n,t){const a=f(n,["rev-parse","--verify","HEAD"]).toString("utf8").trim(),r=t.baseRef.startsWith("sha:")?t.baseSha:t.baseRef,i=f(n,["rev-parse","--verify","--end-of-options",`${r}^{commit}`]).toString("utf8").trim();if(a!==t.headSha||i!==t.baseSha)throw new Error("mutation-qa-physical-drift");if(f(n,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(o=>!o.startsWith("?? ")||!(o.slice(3).startsWith("node_modules/")||o.slice(3).startsWith("reports/mutation/")||o.slice(3).startsWith(".stryker-tmp/"))))throw new Error("mutation-qa-checkout-drift");for(const o of t.eligibleFiles){const e=C(n,o.path);if(!x(n,e)||l(e)!==e||!k(e).isFile()||f(n,["hash-object","--",o.path]).toString("utf8").trim()!==o.blobSha)throw new Error("mutation-qa-source-drift")}}function N(n){for(const t of(process.env.PATH??"").split(":")){if(!M(t))continue;const a=u(t,n);if(p(a)){try{const r=l(a);if((r.startsWith("/usr/")||r.startsWith("/home/linuxbrew/.linuxbrew/"))&&k(r).isFile()&&(n!=="npm"||r.endsWith(".js")))return r}catch{}return null}}return null}function Q(n,t,a,r,i){const s=l(process.execPath),o="/home/linuxbrew/.linuxbrew";if(!s.startsWith("/usr/")&&!s.startsWith(`${o}/`))return null;const e=["--die-with-parent","--unshare-net","--unshare-pid","--new-session","--ro-bind","/usr","/usr"];for(const c of["/bin","/lib","/lib64"])p(c)&&e.push("--ro-bind",c,c);if(s.startsWith(`${o}/`)){if(!p(o))return null;e.push("--dir","/home","--dir","/home/linuxbrew","--ro-bind",o,o)}else e.push("--dir","/home");e.push("--bind",t,"/home/worker"),i&&e.push("--dir","/npm-cache","--
|
|
1
|
+
import{spawnSync as E}from"node:child_process";import{createHash as q}from"node:crypto";import{existsSync as p,lstatSync as k,mkdirSync as G,mkdtempSync as V,readFileSync as Y,realpathSync as l,rmSync as J,writeFileSync as K}from"node:fs";import{homedir as Z,tmpdir as ee}from"node:os";import{isAbsolute as M,join as u,relative as F,resolve as C,sep as B}from"node:path";import{mutationQaGit as f}from"./mutation-qa-git.js";import{planMutationQa as I}from"./mutation-qa.js";import{evaluateMutationQaReport as te}from"./mutation-qa-verdict.js";const re="reports/mutation/mutation.json",oe=8*1024*1024,ne=1800*1e3,ie=300*1e3;function x(n,t){const a=F(n,t);return a!==".."&&!a.startsWith(`..${B}`)&&!M(a)}function $(n){const t=u(n,re);if(!p(t))return null;const a=l(t);if(a!==t||!x(n,a))throw new Error("mutation-qa-report-path-unsafe");const r=k(t);if(!r.isFile()||r.size===0||r.size>oe)throw new Error("mutation-qa-report-size-invalid");return Y(t)}function se(n,t){const a=f(n,["rev-parse","--verify","HEAD"]).toString("utf8").trim(),r=t.baseRef.startsWith("sha:")?t.baseSha:t.baseRef,i=f(n,["rev-parse","--verify","--end-of-options",`${r}^{commit}`]).toString("utf8").trim();if(a!==t.headSha||i!==t.baseSha)throw new Error("mutation-qa-physical-drift");if(f(n,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(o=>!o.startsWith("?? ")||!(o.slice(3).startsWith("node_modules/")||o.slice(3).startsWith("reports/mutation/")||o.slice(3).startsWith(".stryker-tmp/"))))throw new Error("mutation-qa-checkout-drift");for(const o of t.eligibleFiles){const e=C(n,o.path);if(!x(n,e)||l(e)!==e||!k(e).isFile()||f(n,["hash-object","--",o.path]).toString("utf8").trim()!==o.blobSha)throw new Error("mutation-qa-source-drift")}}function N(n){for(const t of(process.env.PATH??"").split(":")){if(!M(t))continue;const a=u(t,n);if(p(a)){try{const r=l(a);if((r.startsWith("/usr/")||r.startsWith("/home/linuxbrew/.linuxbrew/"))&&k(r).isFile()&&(n!=="npm"||r.endsWith(".js")))return r}catch{}return null}}return null}function Q(n,t,a,r,i){const s=l(process.execPath),o="/home/linuxbrew/.linuxbrew";if(!s.startsWith("/usr/")&&!s.startsWith(`${o}/`))return null;const e=["--die-with-parent","--unshare-net","--unshare-pid","--new-session","--ro-bind","/usr","/usr"];for(const c of["/bin","/lib","/lib64"])p(c)&&e.push("--ro-bind",c,c);if(s.startsWith(`${o}/`)){if(!p(o))return null;e.push("--dir","/home","--dir","/home/linuxbrew","--ro-bind",o,o)}else e.push("--dir","/home");e.push("--bind",t,"/home/worker"),i&&e.push("--dir","/npm-cache","--overlay-src",i,"--tmp-overlay","/npm-cache"),e.push("--dir","/etc","--ro-bind",a,"/etc/hosts","--proc","/proc","--dev","/dev","--tmpfs","/tmp","--dir","/work","--bind",n,"/work","--chdir","/work","--clearenv");for(const[c,m]of Object.entries(r))e.push("--setenv",c,m);return e}function de(n,t,a){if(!/^[a-f0-9]{64}$/.test(a))throw new Error("mutation-qa-plan-digest-invalid");const r=C(n),i=I(r,t);if(i.planSha256!==a)throw new Error("mutation-qa-plan-drift");const s={schemaVersion:1,kind:"mutation-qa-run",planSha256:i.planSha256,headSha:i.headSha,checkpointAccepted:!1,localOnly:!0,executionEnvironment:"os-sandbox-clone"};if(i.outcome==="skipped-no-files")return Object.freeze({...s,outcome:"skipped-no-files"});if(!p(u(r,"package-lock.json")))return Object.freeze({...s,outcome:"skipped-dependencies-unavailable"});const o=V(u(ee(),"mutation-qa-run-")),e=u(o,"checkout"),c=u(o,"home");G(c,{mode:448});const m=u(o,"hosts");K(m,`127.0.0.1 localhost
|
|
2
2
|
::1 localhost
|
|
3
|
-
`,{mode:384});const A={PATH:process.env.PATH??"/usr/bin:/bin",HOME:"/home/worker",TMPDIR:"/tmp",CI:"true",LANG:"C.UTF-8",NO_COLOR:"1",npm_config_offline:"true",npm_config_yes:"false",npm_config_ignore_scripts:"true",npm_config_audit:"false",npm_config_fund:"false",npm_config_userconfig:"/dev/null",npm_config_globalconfig:"/tmp/npm-global.npmrc"};try{f(r,["clone","--local","--no-hardlinks","--no-checkout",r,e]),f(e,["checkout","--detach",i.headSha]),i.baseRef.startsWith("sha:")||f(e,["update-ref",i.baseRef,i.baseSha]);const O=N("npm"),d=N("bwrap"),j=u(Z(),".npm");if(!O||!d||!p(j))return Object.freeze({...s,outcome:"skipped-host-isolation-unavailable"});const
|
|
3
|
+
`,{mode:384});const A={PATH:process.env.PATH??"/usr/bin:/bin",HOME:"/home/worker",TMPDIR:"/tmp",CI:"true",LANG:"C.UTF-8",NO_COLOR:"1",npm_config_offline:"true",npm_config_yes:"false",npm_config_ignore_scripts:"true",npm_config_audit:"false",npm_config_fund:"false",npm_config_userconfig:"/dev/null",npm_config_globalconfig:"/tmp/npm-global.npmrc"};try{f(r,["clone","--local","--no-hardlinks","--no-checkout",r,e]),f(e,["checkout","--detach",i.headSha]),i.baseRef.startsWith("sha:")||f(e,["update-ref",i.baseRef,i.baseSha]);const O=N("npm"),d=N("bwrap"),j=u(Z(),".npm");if(!O||!d||!p(j))return Object.freeze({...s,outcome:"skipped-host-isolation-unavailable"});const v=Q(e,c,m,A),R=Q(e,c,m,{...A,npm_config_cache:"/npm-cache",npm_config_logs_dir:"/tmp/npm-logs"},l(j));if(!v||!R)return Object.freeze({...s,outcome:"skipped-host-isolation-unavailable"});const w=l(process.execPath),g=E(d,[...v,"--",w,"-e","process.exit(0)"],{cwd:e,timeout:1e4,maxBuffer:4096,stdio:["ignore","pipe","pipe"],env:{PATH:process.env.PATH??"/usr/bin:/bin"}});if(g.error||g.signal||g.status!==0)return Object.freeze({...s,outcome:"skipped-host-isolation-unavailable"});const y=E(d,[...R,"--",w,O,"ci","--offline","--ignore-scripts","--no-audit","--no-fund"],{cwd:e,timeout:ie,maxBuffer:2*1024*1024,stdio:["ignore","pipe","pipe"],env:{PATH:process.env.PATH??"/usr/bin:/bin"}});if(y.error||y.signal||y.status!==0)return Object.freeze({...s,outcome:"skipped-dependencies-unavailable"});const P=u(e,"node_modules/.bin/stryker");if(!p(P))return Object.freeze({...s,outcome:"skipped-stryker-missing"});const S=l(P);if(!x(e,S)||!k(S).isFile())throw new Error("mutation-qa-stryker-path-unsafe");const D=`/work/${F(e,S).split(B).join("/")}`,T=$(e),L=T?q("sha256").update(T).digest("hex"):null,U=process.umask(63);let h=null,z=!1,H=!1;try{const b=E(d,[...v,"--",w,D,"run","--mutate",i.eligibleFiles.map(X=>X.path).join(","),"--reporters","json","--timeoutMS","600000","--concurrency","4","--coverageAnalysis","off"],{cwd:e,timeout:ne,maxBuffer:2097152,stdio:["ignore","pipe","pipe"],env:{PATH:process.env.PATH??"/usr/bin:/bin"}});h=b.status,z=!!b.error||!!b.signal,H=b.error?.code==="ENOENT"}finally{process.umask(U)}if(se(e,i),I(r,t).planSha256!==i.planSha256)throw new Error("mutation-qa-physical-drift");if(H)return Object.freeze({...s,outcome:"skipped-host-isolation-unavailable"});if(z||h!==0&&h!==1)return Object.freeze({...s,outcome:"skipped-stryker-error"});const _=$(e);if(!_||q("sha256").update(_).digest("hex")===L){if(h===1)return Object.freeze({...s,outcome:"skipped-stryker-error"});throw new Error("mutation-qa-report-stale")}const W=te(i,_);return h===1&&!W.runnerBreakCrossed?Object.freeze({...s,outcome:"skipped-stryker-error"}):Object.freeze({...s,outcome:"verified",verdict:W})}finally{J(o,{recursive:!0,force:!0})}}export{de as runMutationQa};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as re,randomUUID as ce}from"node:crypto";import{closeSync as N,constants as c,fsyncSync as B,openSync as D,writeFileSync as ne}from"node:fs";import{join as oe}from"node:path";import le from"axe-core";import{launchSyntheticBackendBrowser as de}from"./qa-synthetic-browser.js";import{scenarioRequirementDigest as V,validateRootQaScanScenario as he}from"./qa-scan-capture.js";import{planRootQaScan as U,rootQaScanEvidenceDirectory as fe}from"./qa-scan-review.js";import{openSyntheticBackendSession as we}from"./qa-synthetic-backend.js";const F=a=>re("sha256").update(a).digest("hex");async function Se(a,
|
|
1
|
+
import{createHash as re,randomUUID as ce}from"node:crypto";import{closeSync as N,constants as c,fsyncSync as B,openSync as D,writeFileSync as ne}from"node:fs";import{join as oe}from"node:path";import le from"axe-core";import{launchSyntheticBackendBrowser as de}from"./qa-synthetic-browser.js";import{scenarioRequirementDigest as V,validateRootQaScanScenario as he}from"./qa-scan-capture.js";import{planRootQaScan as U,rootQaScanEvidenceDirectory as fe}from"./qa-scan-review.js";import{openSyntheticBackendSession as we}from"./qa-synthetic-backend.js";const F=a=>re("sha256").update(a).digest("hex");async function Se(a,w,i){const d=he(a.scenario),g=F(JSON.stringify(d)),y=U(a.projectRoot,a.surface,a.targetUrl),q=V(a.projectRoot,d);if(w&&(Object.keys(w).sort().join(",")!=="contractSha256,observations,request,scopeSha256,verify"||!["observations","request","verify"].every(n=>typeof w[n]=="function")||!/^[a-f0-9]{64}$/.test(w.contractSha256)||w.scopeSha256!==F(JSON.stringify([y.sourceHead,a.surface,a.targetUrl,a.generation,g,a.grantId]))))throw new Error("qa-synthetic-backend-broker-port-unverified");const u=w??await we({...a,scenarioSha256:g});if(i&&(!w||Object.keys(i).sort().join(",")!=="containerId,imageId,jobBindingSha256,kind,launch"||i.kind!=="operator-docker-job"||!/^sha256:[a-f0-9]{64}$/.test(i.imageId)||!/^[a-f0-9]{64}$/.test(i.containerId)||!/^[a-f0-9]{64}$/.test(i.jobBindingSha256)||typeof i.launch!="function"))throw new Error("qa-synthetic-backend-docker-context-invalid");const E=i?await i.launch():await de();let O,W=!1,b="context",R="";try{const n=await E.newContext({serviceWorkers:"block",acceptDownloads:!1,permissions:[],ignoreHTTPSErrors:!1,viewport:{width:1280,height:900}});let l=0,h=0,j=!1,k=0,x=0,H=0,J=0,I=0,M=0;const p=new Set,$=new URL(a.targetUrl);await n.route("**/*",async e=>{try{const t=e.request();j?k++:x++;const s=u.request(t.url(),t.method(),t.postData(),await t.allHeaders());p.add(s);let o;try{o=await s}finally{p.delete(s)}await e.fulfill({status:o.status,body:o.body,headers:{"content-type":o.contentType,"cache-control":"no-store"}})}catch(t){t instanceof Error&&/^qa-[a-z-]+$/.test(t.message)&&(R=t.message),l++,await e.abort("blockedbyclient").catch(()=>{})}}),await n.routeWebSocket(/.*/,async e=>{l++,await e.close({code:1008,reason:"blocked"})});const r=await n.newPage();n.on("page",e=>{e!==r&&(h++,e.close())}),r.on("framenavigated",()=>{j&&h++}),r.on("download",()=>{h++}),r.on("pageerror",()=>{h++,J++}),r.on("console",e=>{e.type()==="error"&&(h++,H++)}),r.on("request",()=>{M++}),r.on("requestfailed",()=>{I++}),r.on("response",e=>{e.status()>=400&&(I++,h++)}),O=setTimeout(()=>{W=!0,n.close().catch(()=>{})},15e3),b="navigation";const z=await r.goto($.href,{waitUntil:"load",timeout:5e3});if(!z||z.status()>=400||r.url()!==$.href||l||h)throw new Error("qa-synthetic-backend-target-unavailable");j=!0;const f=()=>{if(l)throw new Error("qa-synthetic-backend-effects-denied-network");if(h)throw new Error("qa-synthetic-backend-effects-denied-page");if(W)throw new Error("qa-synthetic-backend-effects-denied-budget");if(r.url()!==$.href)throw new Error("qa-synthetic-backend-effects-denied-navigation")},C=async e=>{const t=r.locator(e);if(await t.count()!==1)throw new Error("qa-synthetic-backend-target-ambiguous");return t};b="scenario";for(const e of d.actions){const t=await C(e.selector);if(!await t.isVisible()||!await t.isEnabled())throw new Error("qa-synthetic-backend-action-unavailable");e.kind==="click"?await t.click({timeout:2e3}):e.kind==="fill"?await t.fill(e.value,{timeout:2e3}):e.kind==="select"?await t.selectOption(e.value,{timeout:2e3}):e.kind==="press"&&await t.press(e.key,{timeout:2e3}),f()}const A=[];for(const e of d.checks){const t=await C(e.selector),s=Date.now()+2e3;for(;f(),(e.kind==="text"?(await t.textContent({timeout:1e3}))?.trim():e.kind==="value"?await t.inputValue({timeout:1e3}):e.kind==="visible"?await t.isVisible():e.kind==="enabled"?await t.isEnabled():await t.isChecked({timeout:1e3}))!==e.expected;){if(Date.now()>=s)throw new Error("qa-synthetic-backend-check-failed");await r.waitForTimeout(25)}A.push({id:`functional-${e.id}`,passed:!0})}if(await r.waitForTimeout(250),f(),await Promise.allSettled([...p]),f(),await u.verify(),!k||!u.observations().length)throw new Error("qa-synthetic-backend-no-backend-observation");if(U(a.projectRoot,a.surface,a.targetUrl).planSha256!==y.planSha256)throw new Error("qa-synthetic-backend-source-drift");if(V(a.projectRoot,d)!==q)throw new Error("qa-synthetic-backend-source-drift");b="artifacts";const T=fe(a.projectRoot),Y=[],Q=new Date().toISOString(),m=(e,t,s,o,ie)=>{if(s.length<8||s.length>8*1024*1024)throw new Error("qa-synthetic-backend-artifact-limit");const se=re("sha256").update(s).digest("hex"),ae=`backend-${e}-${ce().replaceAll("-","").slice(0,20)}.${o}`,L=D(oe(T,ae),c.O_WRONLY|c.O_CREAT|c.O_EXCL|c.O_NOFOLLOW,384);try{ne(L,s),B(L)}finally{N(L)}Y.push({kind:e,artifactId:ae,sha256:se,captureMethod:t,capturedAt:Q,rationale:ie})},v=e=>Buffer.from(JSON.stringify(e));await r.addScriptTag({content:le.source});let X=0,Z=0,G=0;for(const[e,t,s]of[["visual",1440,900],["responsive",375,812],["responsive-tablet",768,1024],["responsive-desktop",1024,768]]){await r.setViewportSize({width:t,height:s}),f(),m(e,"browser-screenshot",await r.screenshot({type:"png",animations:"disabled",timeout:2e3}),"png",`Isolated network-namespace browser screenshot at ${t}x${s} after the source-bound synthetic scenario.`);const o=await r.evaluate("window.axe.run(document)");if(!o||!Array.isArray(o.violations)||!Array.isArray(o.incomplete)||!Array.isArray(o.passes))throw new Error("qa-synthetic-backend-accessibility-unavailable");X+=o.violations.length,Z+=o.incomplete.length,G+=o.passes.length,f()}m("accessibility","axe-scan",v({schemaVersion:1,engine:"axe-core",violationCount:X,incompleteCount:Z,passCount:G}),"json","Independent-review input: axe observations across all four declared viewport widths after the synthetic scenario.");const S=await r.evaluate("performance.getEntriesByType('navigation')[0]?.duration");if(typeof S!="number"||!Number.isFinite(S)||S<0)throw new Error("qa-synthetic-backend-performance-unavailable");if(m("performance","performance-trace",v({schemaVersion:1,metric:"load",observedMs:Math.ceil(S),budgetMs:1e4}),"json","Physical navigation load observation in the isolated browser with a predeclared ten-second load budget."),await Promise.allSettled([...p]),f(),await n.close(),await Promise.allSettled([...p]),f(),await u.verify(),m("interaction","browser-interaction",v({schemaVersion:3,syntheticTarget:!0,allowedActionRequests:k,deniedRequests:l,generation:a.generation,scenarioSha256:g,checks:A,backend:u.observations()}),"json","Source-bound synthetic backend interaction with exact declared transport and physical browser/backend observations."),m("console-network","console-capture",v({schemaVersion:1,initialCapture:!0,consoleErrors:H,pageErrors:J,failedRequests:I,requestsObserved:M}),"json","Console and request listeners were installed before navigation in a fresh network-isolated browser context."),U(a.projectRoot,a.surface,a.targetUrl).planSha256!==y.planSha256||V(a.projectRoot,d)!==q)throw new Error("qa-synthetic-backend-source-drift");const K={schemaVersion:3,kind:"root-qa-synthetic-backend-observation",sourceHead:y.sourceHead,planSha256:y.planSha256,surface:a.surface,targetSha256:y.targetSha256,generation:a.generation,scenarioSha256:g,backendContractSha256:u.contractSha256,requirementSourceSha256:q,requirementIds:d.requirementIds,capturedAt:Q,checks:A,scenario:d,grantId:a.grantId,evidenceCount:8,observations:Y,initialRequests:x,allowedActionRequests:k,deniedRequests:l,backend:u.observations(),sandboxNetwork:"none",browserNetwork:i?"docker-none":"unshared",browserHostWorkspaceMounted:!1,browserVersion:E.version(),...i?{producerJob:{imageId:i.imageId,containerId:i.containerId,jobBindingSha256:i.jobBindingSha256}}:{},qaAccepted:!1,checkpointAccepted:!1,workflowContinuationAuthorized:!1},P=JSON.stringify(K),ee=F(P),_=D(oe(T,`synthetic-backend-${ee}.json`),c.O_WRONLY|c.O_CREAT|c.O_EXCL|c.O_NOFOLLOW,384);try{ne(_,P),B(_)}finally{N(_)}const te=D(T,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW);try{B(te)}finally{N(te)}return{...K,observationSha256:ee}}catch(n){if(R)throw new Error(R);if(n instanceof Error&&/^qa-(synthetic-backend|scan-review)-[a-z-]+$/.test(n.message))throw n;if(n instanceof Error){const l=n.message.match(/net::(ERR_[A-Z_]+)/)?.[1];if(l)throw new Error(`qa-synthetic-backend-${b}-${l.toLowerCase().replaceAll("_","-")}`);if(/Target.*closed|browser has been closed/i.test(n.message))throw new Error(`qa-synthetic-backend-${b}-browser-closed`);if(/Timeout/i.test(n.message))throw new Error(`qa-synthetic-backend-${b}-timeout`)}throw new Error(`qa-synthetic-backend-${b}-unavailable`)}finally{O&&clearTimeout(O),await E.close().catch(()=>{})}}export{Se as captureSyntheticBackendScenario};
|
|
@@ -1,14 +1,8 @@
|
|
|
1
|
-
import { type RefactorRootTargetV2 } from './refactor-root.js';
|
|
2
1
|
export type RefactorCharacterizationRunner = 'native' | 'vitest' | 'cpp';
|
|
3
2
|
/** Node's native type-stripping switch first exists in 22.6.0. */
|
|
4
3
|
export declare function supportsNativeTypeStrippingVersion(version: string): boolean;
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
-
* releases did not expose `process.features.typescript`, so retain the version
|
|
8
|
-
* fallback only when the property is absent. An explicit false/unknown value
|
|
9
|
-
* means this binary cannot safely run the native TypeScript path.
|
|
10
|
-
*/
|
|
11
|
-
export declare function supportsNativeTypeStrippingRuntime(version: string, feature: unknown): boolean;
|
|
4
|
+
/** Distribution capability is separate from semver; some Node builds disable Amaro. */
|
|
5
|
+
export declare function supportsNativeTypeStrippingRuntime(): boolean;
|
|
12
6
|
interface FileDigest {
|
|
13
7
|
readonly path: string;
|
|
14
8
|
readonly sha256: string;
|
|
@@ -50,7 +44,6 @@ export interface RefactorCharacterizationReceiptV1 {
|
|
|
50
44
|
readonly gitCommitAuthorized: false;
|
|
51
45
|
readonly publicSafe: true;
|
|
52
46
|
}
|
|
53
|
-
export declare function runRootRefactorCharacterization(projectRoot: string, admissionSha256: string, testPaths: readonly string[], dependencyPaths: readonly string[], phase: 'baseline' | 'after', authorizeRun: boolean, causalPath: string, baselineSha256?: string, runner?: RefactorCharacterizationRunner
|
|
47
|
+
export declare function runRootRefactorCharacterization(projectRoot: string, admissionSha256: string, testPaths: readonly string[], dependencyPaths: readonly string[], phase: 'baseline' | 'after', authorizeRun: boolean, causalPath: string, baselineSha256?: string, runner?: RefactorCharacterizationRunner): RefactorCharacterizationReceiptV1;
|
|
54
48
|
export declare function refactorCharacterizationCliHandler(args: readonly string[]): number;
|
|
55
|
-
export declare function runRootRefactorTargetCharacterization(projectRoot: string, admissionSha256: string, target: RefactorRootTargetV2, testPaths: readonly string[], dependencyPaths: readonly string[], phase: 'baseline' | 'after', authorizeRun: boolean, causalPath: string, baselineSha256?: string, runner?: RefactorCharacterizationRunner): RefactorCharacterizationReceiptV1;
|
|
56
49
|
export {};
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{spawnSync as
|
|
2
|
-
`)))throw new Error("refactor-root-baseline-invalid");return s}function
|
|
3
|
-
`);if(C(n))Y(e,r);else{const
|
|
4
|
-
`,{mode:384,flag:"wx"})}if(r==="cpp"){if(!s||!
|
|
1
|
+
import{spawnSync as G}from"node:child_process";import{createHash as lt,randomBytes as dt}from"node:crypto";import{closeSync as Q,constants as R,existsSync as C,fsyncSync as K,lstatSync as $,mkdirSync as Z,mkdtempSync as ut,openSync as tt,readFileSync as H,realpathSync as W,rmSync as pt,writeFileSync as z}from"node:fs";import{tmpdir as ht}from"node:os";import{basename as mt,dirname as N,join as y,resolve as wt}from"node:path";import{mutationQaGit as et}from"./mutation-qa-git.js";import{exactCommittedRefactorFile as vt,privateRefactorDirectory as rt,readPrivateRefactorAdmission as yt,verifyRootRefactorForCharacterization as ot}from"./refactor-root.js";const A=/^[a-f0-9]{64}$/,gt=64*1024*1024,st=32,nt=128;function bt(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)return!1;const r=Number(t[1]),n=Number(t[2]);return r>22||r===22&&n>=6}function St(){return bt(process.versions.node)&&process.config.variables.node_use_amaro===!0}function b(e){return lt("sha256").update(e).digest("hex")}function D(e){return e.length>0&&e.length<=512&&/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(e)&&e.split("/").every(t=>t!=="."&&t!==".."&&![".git",".neocortex","node_modules"].includes(t.toLowerCase()))}function V(e){return[...e].sort((t,r)=>Buffer.from(t).compare(Buffer.from(r)))}function Et(e,t,r){if(!t.endsWith(".js")&&!t.endsWith(".ts"))return;let n=N(t);for(;;){const f=n==="."?"package.json":`${n}/package.json`;if(C(y(e,f))){if(!r.includes(f))throw new Error("refactor-root-tests-manifest-unbound");let s;try{s=JSON.parse(L(e,f).toString("utf8"))}catch{throw new Error("refactor-root-tests-manifest-invalid")}if(!s||typeof s!="object"||Array.isArray(s)||!["module","commonjs"].includes(s.type)||t.endsWith(".ts")&&s.type!=="module")throw new Error("refactor-root-tests-manifest-invalid");return}if(n===".")break;n=N(n)}throw new Error("refactor-root-tests-manifest-missing")}function L(e,t){if(!D(t))throw new Error("refactor-root-tests-path-invalid");const r=y(e,t),n=$(r);if(W(r)!==r||!n.isFile()||n.isSymbolicLink()||n.size<1||n.size>8*1024*1024)throw new Error("refactor-root-tests-source-unverified");const f=H(r);if(f.length<1||f.length>8*1024*1024||f.includes(0))throw new Error("refactor-root-tests-source-unverified");return new TextDecoder("utf-8",{fatal:!0}).decode(f),f}function q(e,t){if(!A.test(t))throw new Error("refactor-root-baseline-invalid");return y(rt(e),`characterization-baseline-${t}.json`)}function Y(e,t){const r=$(q(e,t));if(!r.isFile()||r.isSymbolicLink()||r.uid!==process.getuid?.()||(r.mode&63)!==0||r.size<100||r.size>64*1024)throw new Error("refactor-root-baseline-invalid");const n=H(q(e,t));if(n.length>64*1024)throw new Error("refactor-root-baseline-invalid");let f;try{f=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new Error("refactor-root-baseline-invalid")}if(!f||typeof f!="object"||Array.isArray(f))throw new Error("refactor-root-baseline-invalid");const s=f,a=["schemaVersion","kind","admissionSha256","sourceHead","testFiles","dependencies","causalPath","candidateSha256","outputSha256","causalOutputSha256","baselineSha256"],l=o=>Array.isArray(o)&&o.every(p=>p&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).sort().join("\0")==="path\0sha256"&&typeof p.path=="string"&&typeof p.sha256=="string"&&D(p.path)&&A.test(p.sha256)),w=s.schemaVersion===2;if(Object.keys(s).sort().join("\0")!==(w?[...a,"runner","toolchainSha256"]:a).sort().join("\0")||s.schemaVersion!==1&&s.schemaVersion!==2||w&&(!["vitest","cpp"].includes(String(s.runner))||!A.test(String(s.toolchainSha256)))||s.kind!=="root-refactor-characterization-baseline"||!A.test(String(s.admissionSha256))||typeof s.sourceHead!="string"||!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(s.sourceHead)||!l(s.testFiles)||!l(s.dependencies)||s.testFiles.length<1||s.testFiles.length>st||s.dependencies.length>nt||typeof s.causalPath!="string"||!D(s.causalPath)||!A.test(String(s.candidateSha256))||!A.test(String(s.outputSha256))||!A.test(String(s.causalOutputSha256))||s.baselineSha256!==t)throw new Error("refactor-root-baseline-invalid");const c=s.testFiles,d=s.dependencies;if(new Set([...c,...d].map(o=>o.path)).size!==c.length+d.length||c.map(o=>o.path).join("\0")!==V(c.map(o=>o.path)).join("\0")||d.map(o=>o.path).join("\0")!==V(d.map(o=>o.path)).join("\0"))throw new Error("refactor-root-baseline-invalid");const{baselineSha256:i,...u}=s;if(b(JSON.stringify(u))!==t||!n.equals(Buffer.from(`${JSON.stringify(s)}
|
|
2
|
+
`)))throw new Error("refactor-root-baseline-invalid");return s}function kt(e,t){const r=b(JSON.stringify(t)),n=q(e,r),f={...t,baselineSha256:r},s=Buffer.from(`${JSON.stringify(f)}
|
|
3
|
+
`);if(C(n))Y(e,r);else{const a=tt(n,R.O_WRONLY|R.O_CREAT|R.O_EXCL|(R.O_NOFOLLOW??0),384);try{z(a,s),K(a)}finally{Q(a)}const l=tt(rt(e),R.O_RDONLY|(R.O_DIRECTORY??0));try{K(l)}finally{Q(l)}}return Y(e,r),r}function it(e){return[...e.files.map(t=>t.path),...e.schemaVersion===2?e.newFiles.map(t=>t.path):[]]}function at(e,t,r,n=[]){const f=new Map;let s=0;for(const l of[...it(t),...r]){if(n.includes(l)){try{$(y(e,l))}catch(c){if(c.code==="ENOENT")continue;throw c}throw new Error("refactor-root-tests-source-stale")}const w=L(e,l);if(s+=w.length,s>gt)throw new Error("refactor-root-tests-snapshot-too-large");f.set(l,w)}const a=b(JSON.stringify([...[...f].map(([l,w])=>[l,b(w)]),...n.map(l=>[l,null])]));return{files:f,candidateSha256:a}}function ct(){try{const e=W("/usr/bin/g++"),t=$(e);if(!e.startsWith("/usr/")||!/^[A-Za-z0-9_./+-]+$/.test(e)||!t.isFile()||t.uid!==0||(t.mode&18)!==0||t.size<1||t.size>32*1024*1024)throw new Error("invalid compiler");const r=G(e,["-dumpfullversion","-dumpversion"],{env:{PATH:"/usr/bin:/bin"},encoding:"utf8",timeout:1e4,maxBuffer:4096}),n=r.stdout?.trim();if(r.status!==0||!/^(?:11|12|13|14|15)\.[0-9]+\.[0-9]+$/.test(n))throw new Error("unsupported compiler");return{executable:e,sha256:b(JSON.stringify([e,n,b(H(e))]))}}catch{throw new Error("refactor-root-tests-toolchain-unverified")}}function Ot(e,t,r){let n="";for(const M of t){let J=N(M),F="";for(;;){const I=J==="."?"package.json":`${J}/package.json`;if(C(y(e,I))){F=I;break}if(J===".")break;J=N(J)}if(!F||n&&F!==n)throw new Error("refactor-root-tests-toolchain-unverified");n=F}if(!r.includes(n)||!r.includes("package-lock.json"))throw new Error("refactor-root-tests-toolchain-unbound");const f=L(e,n),s=L(e,"package-lock.json");let a,l;try{a=JSON.parse(f.toString("utf8")),l=JSON.parse(s.toString("utf8"))}catch{throw new Error("refactor-root-tests-toolchain-unverified")}const w=a.devDependencies?.vitest??a.dependencies?.vitest,c=l.packages,d=n==="package.json"?"":N(n),i=c?.[d],u=i?.devDependencies?.vitest??i?.dependencies?.vitest,o=c?.["node_modules/vitest"]?.version,p=c?.["node_modules/vite"]?.version;if(typeof w!="string"||w.length>80||!/^[\^~]?[0-9]+\.[0-9]+\.[0-9]+$/.test(w)||w!==u||typeof o!="string"||!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(o)||!o.startsWith("3.2.")||typeof p!="string"||!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(p)||!_t(p))throw new Error("refactor-root-tests-toolchain-unverified");const v=W(y(e,"node_modules")),g=$(v);if(mt(v)!=="node_modules"||!g.isDirectory()||g.isSymbolicLink()||g.uid!==process.getuid?.())throw new Error("refactor-root-tests-toolchain-unverified");const h=y(v,"vitest","package.json"),S=y(v,"vitest","vitest.mjs"),O=y(v,"vite","package.json"),E=$(h),_=$(S),B=$(O);if(!E.isFile()||E.isSymbolicLink()||!_.isFile()||_.isSymbolicLink()||!B.isFile()||B.isSymbolicLink()||W(h)!==h||W(S)!==S||W(O)!==O||E.size>64*1024||_.size>1024*1024||B.size>64*1024)throw new Error("refactor-root-tests-toolchain-unverified");const P=H(h),k=H(S),x=H(O);let j,T;try{j=JSON.parse(P.toString("utf8")),T=JSON.parse(x.toString("utf8"))}catch{throw new Error("refactor-root-tests-toolchain-unverified")}if(j.name!=="vitest"||j.version!==o||T.name!=="vite"||T.version!==p)throw new Error("refactor-root-tests-toolchain-unverified");return{nodeModules:v,sha256:b(JSON.stringify([b(f),b(s),b(P),b(k),b(x)]))}}function _t(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);return!!t&&Number(t[1])<=7&&(Number(t[1])>6||Number(t[1])===6&&Number(t[2])>=1)}function ft(e,t,r,n,f,s,a){if(r==="python"){const c=N(t[0]),d=V([...e.keys()].filter(i=>(c==="."||i.startsWith(`${c}/`))&&/(?:^|\/)test_[A-Za-z0-9_]+\.py$/.test(i)));if(JSON.stringify(d)!==JSON.stringify(t))throw new Error("refactor-root-tests-path-invalid")}const l=W(r==="cpp"?"/usr/bin/dash":r==="python"?"/usr/bin/python3":process.execPath);if(r==="node-typescript"&&!St())throw new Error("refactor-root-tests-toolchain-unavailable");if(process.platform!=="linux"||!C("/usr/bin/bwrap")||!$("/usr/bin/bwrap").isFile()||!(l.startsWith("/usr/")||l.startsWith("/home/linuxbrew/.linuxbrew/")))throw new Error("refactor-root-tests-sandbox-unavailable");const w=ut(y(ht(),"p222-refactor-characterization-"));try{const c=y(w,"work");Z(c,{mode:448});for(const[h,S]of e){const O=y(c,h);Z(N(O),{recursive:!0,mode:448}),z(O,S,{mode:384,flag:"wx"})}if(r==="vitest"){if(!f)throw new Error("refactor-root-tests-toolchain-unavailable");Z(y(c,"node_modules"),{mode:448}),z(y(c,"p222-vitest.config.mjs"),`export default ${JSON.stringify({test:{include:t,environment:"node",silent:!0,passWithNoTests:!1,watch:!1,maxWorkers:1,fileParallelism:!1,pool:"forks",coverage:{enabled:!1}}})};
|
|
4
|
+
`,{mode:384,flag:"wx"})}if(r==="cpp"){if(!s||!a||!e.has(a))throw new Error("refactor-root-tests-toolchain-unavailable");const h=s.executable,S=V([...e.keys()].filter(E=>E.endsWith(".cpp")&&E!==a&&!t.includes(E))).map(E=>`'/work/${E}'`);n&&z(y(c,"p222-cpp-causal.cpp"),`#include <cstdio>
|
|
5
5
|
#include <cstdlib>
|
|
6
6
|
extern "C" void __cyg_profile_func_enter(void*,void*) { std::fputs(${JSON.stringify(n+`
|
|
7
7
|
`)},stderr); std::_Exit(86); }
|
|
8
8
|
extern "C" void __cyg_profile_func_exit(void*,void*) {}
|
|
9
|
-
`,{mode:384,flag:"wx"});const
|
|
9
|
+
`,{mode:384,flag:"wx"});const O=["set -eu","ulimit -c 0",`'${h}' -std=c++17 -O0 -UNDEBUG -I/work ${n?"-finstrument-functions -finstrument-functions-exclude-file-list=/usr/include ":""}-c '/work/${a}' -o /tmp/p222-cpp-causal.o`,...t.flatMap((E,_)=>[`'${h}' -std=c++17 -O0 -UNDEBUG -I/work '/work/${E}' ${S.join(" ")} /tmp/p222-cpp-causal.o ${n?"/work/p222-cpp-causal.cpp ":""}-o /tmp/p222-cpp-test-${_}`,`/tmp/p222-cpp-test-${_}`,`printf 'P222_CPP_TEST_PASSED_${_}\\n'`])].join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`;
|
|
12
|
-
`,{mode:384}),
|
|
13
|
-
`,{mode:384}),
|
|
14
|
-
`,{mode:384}),
|
|
15
|
-
`,{mode:384});const
|
|
16
|
-
`).includes(`P222_CPP_TEST_PASSED_${S}`));return{passed:
|
|
17
|
-
`).includes(n):o.includes(Buffer.from(n)))}}finally{
|
|
18
|
-
`:`throw new Error(${JSON.stringify(
|
|
19
|
-
`)
|
|
20
|
-
`),
|
|
21
|
-
`),1}}
|
|
11
|
+
`;z(y(c,"p222-cpp-runner.sh"),O,{mode:384,flag:"wx"})}const d=y(w,"etc");Z(d,{mode:448}),z(y(d,"passwd"),`nobody:x:65534:65534:nobody:/tmp:/bin/sh
|
|
12
|
+
`,{mode:384}),z(y(d,"group"),`nogroup:x:65534:
|
|
13
|
+
`,{mode:384}),z(y(d,"hosts"),`127.0.0.1 localhost
|
|
14
|
+
`,{mode:384}),z(y(d,"nsswitch.conf"),`hosts: files
|
|
15
|
+
`,{mode:384});const i=["--die-with-parent","--new-session","--unshare-all","--clearenv","--setenv","HOME","/tmp","--setenv","TMPDIR","/tmp","--setenv","PATH","/home/linuxbrew/.linuxbrew/bin:/usr/bin:/bin","--setenv","CI","true","--ro-bind","/usr","/usr"];r==="python"&&i.push("--setenv","PYTHONPATH","/work");for(const h of["/lib","/lib64","/bin"])C(h)&&i.push("--ro-bind",h,h);C("/home/linuxbrew/.linuxbrew")&&i.push("--ro-bind","/home/linuxbrew/.linuxbrew","/home/linuxbrew/.linuxbrew"),i.push("--dir","/etc");for(const h of["passwd","group","hosts","nsswitch.conf"])i.push("--ro-bind",y(d,h),`/etc/${h}`);i.push("--dev","/dev","--proc","/proc","--tmpfs","/tmp","--ro-bind",c,"/work"),r==="vitest"&&i.push("--ro-bind",f.nodeModules,"/work/node_modules"),i.push("--chdir","/work","--",l),r==="cpp"?i.push("/work/p222-cpp-runner.sh"):r==="python"?i.push("-B","-S","-m","unittest","discover","-s",N(t[0]),"-p","test_*.py"):r==="vitest"?i.push("/work/node_modules/vitest/vitest.mjs","run","--root","/work","--config","/work/p222-vitest.config.mjs","--configLoader=runner","--reporter=json","--no-cache","--no-file-parallelism","--maxWorkers=1"):(r==="node-typescript"&&i.push("--experimental-strip-types"),i.push("--test","--test-reporter=tap",...t));const u=G("/usr/bin/bwrap",i,{env:{PATH:"/usr/bin:/bin"},encoding:"buffer",timeout:18e4,maxBuffer:4*1024*1024});if(u.error||u.signal||u.status===null)throw new Error("refactor-root-tests-sandbox-unavailable");const o=Buffer.concat([u.stdout??Buffer.alloc(0),u.stderr??Buffer.alloc(0)]),p=r!=="python"||/^Ran [1-9][0-9]* tests? in /m.test(o.toString("utf8"));let v=!0;if(r==="vitest")try{const h=JSON.parse((u.stdout??Buffer.alloc(0)).toString("utf8"));v=Number.isSafeInteger(h.numPassedTests)&&Number(h.numPassedTests)>0&&h.numTotalTests===h.numPassedTests&&h.numFailedTests===0}catch{v=!1}const g=r!=="cpp"||t.every((h,S)=>o.toString("utf8").split(`
|
|
16
|
+
`).includes(`P222_CPP_TEST_PASSED_${S}`));return{passed:u.status===0&&p&&v&&g,outputSha256:b(o),canaryObserved:n!==void 0&&(r==="cpp"?o.toString("utf8").split(`
|
|
17
|
+
`).includes(n):o.includes(Buffer.from(n)))}}finally{pt(w,{recursive:!0,force:!0})}}function xt(e,t,r,n,f,s,a,l,w="native"){if(!s)throw new Error("refactor-root-run-authorization-required");if(r.length<1||r.length>st||n.length>nt||!["native","vitest","cpp"].includes(w)||f==="baseline"&&l!==void 0||f==="after"&&(!l||!A.test(l)))throw new Error("refactor-root-tests-arguments-invalid");const c=V(r),d=V(n),i=w==="cpp"?"cpp":w==="vitest"?"vitest":c.every(o=>/(?:^|\/)test_[A-Za-z0-9_]+\.py$/.test(o))&&a.endsWith(".py")?"python":c.every(o=>o.endsWith(".test.ts"))&&a.endsWith(".ts")?"node-typescript":"node";if(new Set([...c,...d]).size!==c.length+d.length||c.some(o=>!D(o)||(i==="cpp"?!o.endsWith(".test.cpp"):i==="python"?!/(?:^|\/)test_[A-Za-z0-9_]+\.py$/.test(o)||N(o)!==N(c[0]):i==="vitest"?!/\.test\.(?:ts|js|mjs)$/.test(o):i==="node-typescript"?!o.endsWith(".test.ts"):!/\.test\.(?:mjs|cjs|js)$/.test(o)))||!D(a)||(i==="cpp"?!a.endsWith(".cpp")||a.endsWith(".test.cpp"):i==="python"?!a.endsWith(".py"):i==="vitest"?!/\.(?:ts|js|mjs)$/.test(a)||/\.test\./.test(a):i==="node-typescript"?!a.endsWith(".ts")||a.endsWith(".test.ts"):!/\.(?:mjs|cjs|js)$/.test(a))||d.some(o=>!D(o)||i==="python"&&/(?:^|\/)test_[A-Za-z0-9_]+\.py$/.test(o)))throw new Error("refactor-root-tests-path-invalid");const u=wt(e);try{const o=yt(u,t),{pendingDocumentationPaths:p}=ot(u,t),v=new Set(it(o));if(c.some(m=>!v.has(m))||!o.files.some(m=>m.path===a)||c.includes(a)||d.some(m=>v.has(m)))throw new Error("refactor-root-tests-path-invalid");for(const m of[...c,a,...d])Et(u,m,d);for(const m of d)vt(u,m);const g=i==="vitest"?Ot(u,c,d):void 0,h=i==="cpp"?ct():void 0,S=g?.sha256??h?.sha256,O=et(u,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).toString("utf8").split("\0").filter(m=>m&&!m.startsWith(".neocortex/")),E=et(u,["ls-files","--others","--exclude-standard","-z"]).toString("utf8").split("\0").filter(m=>m&&!m.startsWith(".neocortex/")),_=[...O,...E].filter(m=>!c.includes(m));if(f==="baseline"&&_.length>0||f==="after"&&_.length===0)throw new Error("refactor-root-tests-phase-invalid");const B=c.map(m=>({path:m,sha256:b(L(u,m))})),P=d.map(m=>({path:m,sha256:b(L(u,m))})),k=f==="after"?Y(u,l):null;if(k&&(k.admissionSha256!==t||k.sourceHead!==o.sourceHead||k.causalPath!==a||(k.schemaVersion===2?w!==k.runner||k.toolchainSha256!==S:w!=="native")||JSON.stringify(k.testFiles)!==JSON.stringify(B)||JSON.stringify(k.dependencies)!==JSON.stringify(P)))throw new Error("refactor-root-baseline-stale");const x=at(u,o,d,p);if(k&&b(x.files.get(a))===o.files.find(m=>m.path===a).sha256)throw new Error("refactor-root-tests-phase-invalid");const j=ft(x.files,c,i,void 0,g,h,a);let T=null,M=!1;if(j.passed){const m=`P222_REFACTOR_CAUSAL_${dt(16).toString("hex")}`,X=new Map(x.files);i!=="cpp"&&X.set(a,Buffer.concat([Buffer.from(i==="python"?`raise RuntimeError(${JSON.stringify(m)})
|
|
18
|
+
`:`throw new Error(${JSON.stringify(m)});
|
|
19
|
+
`),x.files.get(a)]));const U=ft(X,c,i,m,g,h,a);T=U.outputSha256,M=!U.passed&&U.canaryObserved}const J=ot(u,t);if(JSON.stringify(J.pendingDocumentationPaths)!==JSON.stringify(p))throw new Error("refactor-root-tests-source-stale");const F=at(u,o,d,p);if(h&&ct().sha256!==h.sha256)throw new Error("refactor-root-tests-toolchain-stale");if(x.candidateSha256!==F.candidateSha256)throw new Error("refactor-root-tests-source-stale");let I=l??null;return f==="baseline"&&j.passed&&M&&T&&(I=kt(u,{...i==="vitest"||i==="cpp"?{schemaVersion:2,runner:i,toolchainSha256:S}:{schemaVersion:1},kind:"root-refactor-characterization-baseline",admissionSha256:t,sourceHead:o.sourceHead,testFiles:B,dependencies:P,causalPath:a,candidateSha256:x.candidateSha256,outputSha256:j.outputSha256,causalOutputSha256:T})),Object.freeze({schemaVersion:1,kind:"root-refactor-characterization-observation",phase:f,admissionSha256:t,baselineSha256:I,candidateSha256:x.candidateSha256,outputSha256:j.outputSha256,causalOutputSha256:T,testFileCount:c.length,dependencyCount:d.length,testsPassedObserved:j.passed,causalFailureObserved:M,qaAccepted:!1,gitCommitAuthorized:!1,publicSafe:!0})}catch(o){throw o instanceof Error&&o.message.startsWith("refactor-root-")?o:new Error("refactor-root-tests-unverified")}}function Wt(e){let t="",r="",n,f="",s=!1,a="",l="native",w="plain";const c=[],d=[];try{if(e[0]!=="characterize")throw new Error("refactor-root-tests-arguments-invalid");for(let o=1;o<e.length;o++){const p=e[o],v=()=>{const g=e[++o];if(!g||g.startsWith("--"))throw new Error("refactor-root-tests-arguments-invalid");return g};if(p==="--project-root"&&!t)t=v();else if(p==="--admission-sha"&&!r)r=v();else if(p==="--baseline-sha"&&!n)n=v();else if(p==="--phase"&&!f){const g=v();if(g!=="baseline"&&g!=="after")throw new Error("refactor-root-tests-arguments-invalid");f=g}else if(p==="--test-path")c.push(v());else if(p==="--dependency")d.push(v());else if(p==="--causal-path"&&!a)a=v();else if(p==="--runner"&&l==="native"){const g=v();if(g!=="vitest"&&g!=="cpp")throw new Error("refactor-root-tests-arguments-invalid");l=g}else if(p==="--authorize-run"&&!s)s=!0;else if(p==="--format"&&w==="plain")w=v();else throw new Error("refactor-root-tests-arguments-invalid")}if(!t||!r||!f||!a||!["plain","json"].includes(w))throw new Error("refactor-root-tests-arguments-invalid");const i=xt(t,r,c,d,f,s,a,n,l),u=i.testsPassedObserved&&i.causalFailureObserved;return process.stdout.write(`${JSON.stringify({ok:u,observation:i})}
|
|
20
|
+
`),u?0:1}catch(i){const u=i instanceof Error&&/^refactor-root-[a-z-]+$/.test(i.message)?i.message:"refactor-root-tests-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:u})}
|
|
21
|
+
`),1}}export{Y as readRootRefactorBaseline,Wt as refactorCharacterizationCliHandler,xt as runRootRefactorCharacterization,St as supportsNativeTypeStrippingRuntime,bt as supportsNativeTypeStrippingVersion};
|
|
@@ -1,17 +1,9 @@
|
|
|
1
|
-
export
|
|
1
|
+
export declare function requestRootControl(family: 'refactor' | 'qa', input: Readonly<{
|
|
2
2
|
serverUrl: string;
|
|
3
3
|
token: string;
|
|
4
4
|
projectId: string;
|
|
5
|
-
platformTarget: string;
|
|
6
|
-
} & ({
|
|
7
5
|
storyId: string;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
} | {
|
|
11
|
-
schemaVersion: 2;
|
|
12
|
-
scopeId: string;
|
|
13
|
-
storyId?: never;
|
|
14
|
-
})>;
|
|
15
|
-
export declare function requestRootControl(family: 'refactor' | 'qa', input: RootControlRequestInput, fetchFn?: typeof fetch): Promise<Record<string, unknown>>;
|
|
6
|
+
platformTarget: string;
|
|
7
|
+
}>, fetchFn?: typeof fetch): Promise<Record<string, unknown>>;
|
|
16
8
|
export declare function requestRefactorControl(input: Parameters<typeof requestRootControl>[1], fetchFn?: typeof fetch): Promise<Record<string, unknown>>;
|
|
17
9
|
export declare function refactorControlCliHandler(args: readonly string[], family?: 'refactor' | 'qa'): Promise<number>;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{lstatSync as
|
|
2
|
-
`),0}catch(
|
|
3
|
-
`),1}}export{
|
|
1
|
+
import{lstatSync as S,readFileSync as v,realpathSync as R}from"node:fs";import{join as w,resolve as g}from"node:path";import{signNxInvokeRequest as k}from"../../../shared/dist/nx-invoke-signature.js";import{COMMAND_REGISTRY_VERSION as q,COMMAND_REGISTRY_CHECKSUM as C}from"../generated/command-registry.generated.js";import{CLIENT_VERSION as N}from"../version.js";import{loadSecureConfig as b}from"../config/secure-config.js";import{neocortexProfileDirectory as _}from"../config/profile-directory.js";import{EncryptedCache as A}from"../cache/encrypted-cache.js";import{LicenseClient as T}from"../license/license-client.js";import{detectPlatform as I}from"../adapters/platform-detector.js";const y=new Set(["refactor-control-input-invalid","refactor-control-auth-required","refactor-control-tier-required","refactor-control-read-only","refactor-control-signature-required","refactor-control-client-unsupported","refactor-control-registry-mismatch","refactor-control-executor-unavailable"]),L=new Set(["arguments-invalid","authorization-required","host-unsupported","project-unbound","auth-required","response-invalid","request-refused","outcome-unknown"].map(e=>`refactor-root-control-${e}`));async function j(e){const o=e.body?.getReader();if(!o)throw new Error("refactor-root-control-response-invalid");let n=!1;try{const t=[];let c=0;for(;;){const a=await o.read();if(a.done){n=!0;break}if(c+=a.value.byteLength,c>16384)throw new Error("refactor-root-control-response-invalid");t.push(Buffer.from(a.value))}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(t,c)))}catch{throw new Error("refactor-root-control-response-invalid")}finally{n||await o.cancel().catch(()=>{}),o.releaseLock()}}async function E(e,o,n=fetch){if(e!=="refactor"&&e!=="qa")throw new Error("refactor-root-control-arguments-invalid");const t=`/api/v1/invoke/${e}/control`,c=k({method:"POST",target:t,body:Buffer.from(JSON.stringify({projectId:o.projectId,storyId:o.storyId,platformTarget:o.platformTarget,registryVersion:q,registryChecksum:C})),bearerToken:o.token,clientVersion:N}),a=await n(`${o.serverUrl.replace(/\/+$/,"")}${t}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(2e5),headers:{...c.headers,Authorization:`Bearer ${o.token}`},body:c.body}),r=await j(a);if(!a.ok)throw new Error(typeof r?.error_code=="string"&&y.has(r.error_code.replace(/^qa-/,"refactor-"))&&r.error_code.startsWith(`${e}-`)?r.error_code:"refactor-root-control-request-refused");const l=["schemaVersion","kind","status","completedStages","authority","qaAccepted","gitAuthority","billingAuthority","publicSafe"];if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>!l.includes(s))||r.schemaVersion!==1||r.kind!==`root-${e}-control`||typeof r.status!="string"||!["advanced","waiting","blocked","candidate-ready",...e==="qa"?["debt"]:[]].includes(r.status)||r.authority!==(e==="qa"?"LOCAL_ROOT_QA_CANDIDATE_ONLY":"LOCAL_ROOT_CANDIDATE_ONLY")||r.qaAccepted!==!1||r.gitAuthority!=="NONE"||r.billingAuthority!=="NONE"||r.publicSafe!==!0||r.completedStages!==void 0&&(typeof r.completedStages!="number"||!Number.isInteger(r.completedStages)||r.completedStages<0||r.completedStages>(e==="qa"?3:7)))throw new Error("refactor-root-control-response-invalid");return r}async function B(e,o=fetch){return E("refactor",e,o)}async function Y(e,o="refactor"){try{let n="",t="",c=!1,a="json";const r=[...e];if(r.shift()!=="control")throw new Error("refactor-root-control-arguments-invalid");for(let i=0;i<r.length;i++){const d=r[i];if(d==="--authorize-root-control")c=!0;else if(d==="--project-root")n=r[++i]??"";else if(d==="--story")t=r[++i]??"";else if(d==="--format")a=r[++i]??"";else throw new Error("refactor-root-control-arguments-invalid")}if(!c||!n||a!=="json"||!/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/.test(t))throw new Error("refactor-root-control-authorization-required");const l=I({cwd:g(n),env:process.env}).targetId;if(l!=="codex")throw new Error("refactor-root-control-host-unsupported");const s=w(g(n),".neocortex","state.json"),u=S(s);if(!u.isFile()||u.isSymbolicLink()||R(s)!==s||u.size>16*1024*1024)throw new Error("refactor-root-control-project-unbound");const p=JSON.parse(v(s,"utf8")).config?.project_id;if(typeof p!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(p))throw new Error("refactor-root-control-project-unbound");const f=b({strictReadOnly:!0});if(!f?.licenseKey)throw new Error("refactor-root-control-auth-required");const h=process.env.NEOCORTEX_SERVER_URL??f.serverUrl;if(!h)throw new Error("refactor-root-control-auth-required");const m=await new T({serverUrl:h,licenseKey:f.licenseKey,cacheProvider:new A({cacheDir:w(_(),"cache"),passphrase:f.licenseKey})}).getToken();if(!m)throw new Error("refactor-root-control-auth-required");const O=await E(o,{serverUrl:h,token:m,projectId:p,storyId:t,platformTarget:l});return process.stdout.write(`${JSON.stringify({ok:!0,control:O})}
|
|
2
|
+
`),0}catch(n){const t=n instanceof Error?n.message.replace(/^qa-/,"refactor-"):"",c=L.has(t)||y.has(t)?t:"refactor-root-control-outcome-unknown";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:o==="qa"?c.replace(/^refactor-/,"qa-"):c})}
|
|
3
|
+
`),1}}export{Y as refactorControlCliHandler,B as requestRefactorControl,E as requestRootControl};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { type RefactorRootTargetV2 } from './refactor-root.js';
|
|
2
1
|
export interface RefactorSemanticReviewV1 {
|
|
3
2
|
readonly schemaVersion: 1;
|
|
4
3
|
readonly kind: 'root-refactor-semantic-review';
|
|
@@ -36,15 +35,3 @@ export declare function acceptRootRefactorSemanticReview(projectRoot: string, ad
|
|
|
36
35
|
export declare function readRootRefactorSemanticReview(projectRoot: string, admissionSha256: string, baselineSha256: string): RefactorSemanticAcceptanceV1;
|
|
37
36
|
/** The report travels only over stdin and is never echoed on public CLI output. */
|
|
38
37
|
export declare function refactorReviewCliHandler(args: readonly string[]): Promise<number>;
|
|
39
|
-
export interface RefactorTargetSemanticReviewV2 extends Omit<RefactorSemanticReviewV1, 'schemaVersion' | 'kind' | 'storyId'> {
|
|
40
|
-
readonly schemaVersion: 2;
|
|
41
|
-
readonly kind: 'root-refactor-target-semantic-review';
|
|
42
|
-
readonly scopeId: string;
|
|
43
|
-
}
|
|
44
|
-
export interface RefactorTargetSemanticAcceptanceV2 extends Omit<RefactorSemanticAcceptanceV1, 'schemaVersion' | 'kind' | 'storyId'> {
|
|
45
|
-
readonly schemaVersion: 2;
|
|
46
|
-
readonly kind: 'root-refactor-target-semantic-acceptance';
|
|
47
|
-
readonly scopeId: string;
|
|
48
|
-
}
|
|
49
|
-
export declare function acceptRootRefactorTargetSemanticReview(projectRoot: string, admissionSha256: string, baselineSha256: string, targetInput: RefactorRootTargetV2, report: unknown, authorizeRootReview: boolean): RefactorTargetSemanticAcceptanceV2;
|
|
50
|
-
export declare function readRootRefactorTargetSemanticReview(projectRoot: string, admissionSha256: string, baselineSha256: string, targetInput: RefactorRootTargetV2): RefactorTargetSemanticAcceptanceV2;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import{createHash as
|
|
2
|
-
`))||
|
|
3
|
-
`);if(
|
|
4
|
-
`),0}catch(
|
|
5
|
-
`),1}}
|
|
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};
|
|
1
|
+
import{createHash as $,randomUUID as C}from"node:crypto";import{closeSync as R,existsSync as k,fsyncSync as x,linkSync as H,lstatSync as N,openSync as O,readFileSync as F,realpathSync as j,unlinkSync as I,writeFileSync as V}from"node:fs";import{join as y,resolve as B}from"node:path";import{readRootRefactorBaseline as W,runRootRefactorCharacterization as D}from"./refactor-characterization.js";import{cppRefactorExecutableLines as M,isCppRefactorAssertionSite as T}from"./refactor-cpp-assertions.js";import{privateRefactorDirectory as z,readPrivateRefactorAdmission as q,verifyRootRefactor as _}from"./refactor-root.js";const l=/^[a-f0-9]{64}$/,S=128*1024;function v(t){return $("sha256").update(t).digest("hex")}function p(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=q(o,e),a=W(o,n),c=_(o,e),r=D(o,e,a.testFiles.map(u=>u.path),a.dependencies.map(u=>u.path),"after",!0,a.causalPath,n,a.schemaVersion===2?a.runner:"native");if(a.admissionSha256!==e||a.sourceHead!==i.sourceHead||r.baselineSha256!==n||!r.testsPassedObserved||!r.causalFailureObserved||c.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:r.candidateSha256,testFiles:a.testFiles,changedFileCount:c.changedFileCount})}function P(t,e){if(!p(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,i=new Map;for(const[r,u]of n){const f=y(t.root,r),s=N(f);if(!s.isFile()||s.isSymbolicLink()||j(f)!==f||s.size<1||s.size>8*1024*1024)throw new Error("refactor-root-review-unverified");const d=F(f);if(v(d)!==u)throw new Error("refactor-root-review-unverified");const h=new TextDecoder("utf-8",{fatal:!0}).decode(d);o.set(r,h.split(/\r?\n/)),r.endsWith(".cpp")&&i.set(r,M(h))}const a=new Set,c=new Set;for(const r of e.assertions){if(!p(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 u=`${r.testPath}:${r.assertionLine}`;if(a.has(u))throw new Error("refactor-root-review-unverified");a.add(u),c.add(r.testPath);const f=o.get(r.testPath)[Number(r.assertionLine)-1],s=r.testPath.endsWith(".py")?(f.split("#")[0]??"").trimStart():f.split("//")[0]??"";if(!(r.testPath.endsWith(".cpp")?T(i.get(r.testPath)?.[Number(r.assertionLine)-1]??""):r.testPath.endsWith(".py")?/^self\.assert[A-Z][A-Za-z0-9_]*\s*\(/.test(s)||/^assert\s+\S/.test(s):/\b(?:assert|expect|throw)\b/.test(s)))throw new Error("refactor-root-review-unverified")}if(c.size!==n.size)throw new Error("refactor-root-review-unverified");return e}function A(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 L(t,e,n){return y(z(t),`review-${e}-${n}.json`)}function E(t){const e=N(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(!p(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 U(t,e,n,o){try{const i=g(t,e,n),a=P(i,o),c=A(i,a),r=L(i.root,e,i.candidateSha256),u={report:a,receipt:c},f={schemaVersion:1,kind:"root-refactor-semantic-record",...u,checksumSha256:v(`root-refactor-semantic-record-v1\0${JSON.stringify(u)}`)},s=Buffer.from(`${JSON.stringify(f)}
|
|
3
|
+
`);if(k(r)){const m=E(r);if(JSON.stringify(m.report)!==JSON.stringify(a)||JSON.stringify(m.receipt)!==JSON.stringify(c))throw new Error("refactor-root-review-conflict");return c}const d=z(i.root),h=y(d,`review-${C()}.tmp`),w=O(h,"wx",384);try{V(w,s),x(w)}finally{R(w)}try{if(g(i.root,e,n).candidateSha256!==c.candidateSha256)throw new Error("refactor-root-review-unverified");H(h,r);const b=O(d,"r");try{x(b)}finally{R(b)}}finally{k(h)&&I(h)}return E(r),c}catch(i){throw i instanceof Error&&i.message==="refactor-root-review-conflict"?i:new Error("refactor-root-review-unverified")}}function Z(t,e,n){try{const o=g(t,e,n),i=E(L(o.root,e,o.candidateSha256));if(!p(i,["schemaVersion","kind","report","receipt","checksumSha256"]))throw new Error("refactor-root-review-unverified");const a=P(o,i.report),c=A(o,a);if(JSON.stringify(i.receipt)!==JSON.stringify(c))throw new Error("refactor-root-review-unverified");return c}catch{throw new Error("refactor-root-review-unverified")}}async function te(t){const e=t[0];let n="",o="",i="",a=!1,c=!1,r="plain";const u=new Set;try{if(e!=="review-accept"&&e!=="review-status")throw new Error("refactor-root-review-arguments-invalid");for(let s=1;s<t.length;s++){const d=t[s];if(u.has(d))throw new Error("refactor-root-review-arguments-invalid");u.add(d);const h=()=>{const w=t[++s];if(!w||w.startsWith("--"))throw new Error("refactor-root-review-arguments-invalid");return w};if(d==="--project-root")n=h();else if(d==="--admission-sha")o=h();else if(d==="--baseline-sha")i=h();else if(d==="--authorize-run")a=!0;else if(d==="--authorize-root-review")c=!0;else if(d==="--format")r=h();else throw new Error("refactor-root-review-arguments-invalid")}if(!n||!l.test(o)||!l.test(i)||!["plain","json"].includes(r)||!a||c!==(e==="review-accept"))throw new Error("refactor-root-review-arguments-invalid");let f;if(e==="review-accept"){let s="";for await(const w of process.stdin)if(s+=String(w),Buffer.byteLength(s)>S)throw new Error("refactor-root-review-unverified");const{parseDocument:d}=await import("yaml"),h=d(s,{strict:!0,uniqueKeys:!0,schema:"core",customTags:[]});if(h.errors.length||h.warnings.length)throw new Error("refactor-root-review-unverified");f=U(n,o,i,JSON.parse(s))}else f=Z(n,o,i);return process.stdout.write(`${JSON.stringify({ok:!0,acceptance:f})}
|
|
4
|
+
`),0}catch(f){const s=f instanceof Error&&/^refactor-root-[a-z-]+$/.test(f.message)?f.message:"refactor-root-review-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:s})}
|
|
5
|
+
`),1}}export{U as acceptRootRefactorSemanticReview,Z as readRootRefactorSemanticReview,te as refactorReviewCliHandler};
|