@ornexus/neocortex 4.60.64 → 4.60.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +31 -38
  3. package/install.js +1 -0
  4. package/install.ps1 +34 -3
  5. package/install.sh +35 -3
  6. package/package.json +4 -7
  7. package/packages/client/dist/cli.js +1 -1
  8. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -1
  9. package/packages/client/dist/commands/invoke.js +75 -75
  10. package/packages/client/dist/commands/mutation-qa-run.js +2 -2
  11. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -1
  12. package/packages/client/dist/commands/refactor-characterization.d.ts +3 -10
  13. package/packages/client/dist/commands/refactor-characterization.js +16 -16
  14. package/packages/client/dist/commands/refactor-control.d.ts +3 -11
  15. package/packages/client/dist/commands/refactor-control.js +3 -3
  16. package/packages/client/dist/commands/refactor-review.d.ts +0 -13
  17. package/packages/client/dist/commands/refactor-review.js +5 -6
  18. package/packages/client/dist/commands/refactor-root.d.ts +0 -157
  19. package/packages/client/dist/commands/refactor-root.js +7 -12
  20. package/packages/client/dist/commands/shared-architecture-non-ui.d.ts +18 -0
  21. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -0
  22. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +5 -1
  23. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  24. package/packages/client/dist/git/git-lifecycle-store.d.ts +2 -0
  25. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  26. package/packages/client/dist/private-execution/clean-baseline.d.ts +0 -6
  27. package/packages/client/dist/private-execution/clean-baseline.js +2 -2
  28. package/packages/client/dist/private-execution/codex-executor.d.ts +1 -25
  29. package/packages/client/dist/private-execution/codex-executor.js +4 -9
  30. package/packages/client/dist/private-execution/delivery.d.ts +1 -2
  31. package/packages/client/dist/private-execution/delivery.js +3 -3
  32. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
  33. package/packages/client/dist/private-execution/frozen-handoff.js +4 -5
  34. package/packages/client/dist/private-execution/implementation-validation.d.ts +1 -10
  35. package/packages/client/dist/private-execution/implementation-validation.js +2 -2
  36. package/packages/client/dist/private-execution/isolated-session.d.ts +1 -1
  37. package/packages/client/dist/private-execution/isolated-session.js +5 -5
  38. package/packages/client/dist/private-execution/root-memory-git-evidence.d.ts +1 -1
  39. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -3
  40. package/packages/client/dist/private-execution/root-memory-recovery.d.ts +1 -1
  41. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -1
  42. package/packages/client/dist/private-execution/root-memory-scope.d.ts +1 -1
  43. package/packages/client/dist/private-execution/root-memory-scope.js +1 -1
  44. package/packages/client/dist/private-execution/root-memory-writer.d.ts +1 -1
  45. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  46. package/packages/client/dist/private-execution/shared-private-admission-types.d.ts +34 -0
  47. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -0
  48. package/packages/client/dist/private-execution/shared-project-validation.d.ts +17 -0
  49. package/packages/client/dist/private-execution/shared-project-validation.js +1 -0
  50. package/packages/client/dist/private-execution/shared-root-memory-types.d.ts +37 -0
  51. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -0
  52. package/packages/client/dist/private-execution/ux-source-validation.js +1 -1
  53. package/packages/client/dist/runner/binary.d.ts +1 -1
  54. package/packages/client/dist/runner/binary.js +1 -1
  55. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  56. package/packages/client/dist/runner-cli.js +0 -0
  57. package/packages/shared/dist/invocation/index.js +2 -4
  58. package/targets-stubs/antigravity/gemini.md +1 -1
  59. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  60. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  61. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  62. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  63. package/targets-stubs/claude-code/neocortex.md +2 -2
  64. package/targets-stubs/codex/AGENTS.md +1 -1
  65. package/targets-stubs/cursor/agent.md +2 -2
  66. package/targets-stubs/deepseek-harness/SKILL.md +64 -0
  67. package/targets-stubs/gemini-cli/agent.md +2 -2
  68. package/targets-stubs/opencode/neocortex-root.md +1 -1
  69. package/targets-stubs/vscode/neocortex.agent.md +2 -2
  70. package/packages/client/dist/commands/shared-architecture-non-ui-contract.d.ts +0 -19
  71. package/packages/client/dist/commands/shared-architecture-non-ui-contract.js +0 -1
  72. package/packages/shared/dist/invocation/packed-invoke.d.ts +0 -12
  73. package/packages/shared/dist/invocation/packed-invoke.js +0 -58
  74. package/packages/shared/dist/invocation/packed-invoke.test.d.ts +0 -1
  75. package/packages/shared/dist/invocation/packed-invoke.test.js +0 -21
  76. package/packages/shared/dist/private-qa-structural-admission.js +0 -14
  77. package/packages/shared/dist/private-yolo-predecessor-decision.js +0 -32
  78. package/packages/shared/dist/project-validation-commands.js +0 -96
@@ -1,5 +1,5 @@
1
- import{execFileSync as ge,spawnSync as je}from"node:child_process";import{createCipheriv as _e,createHash as C,randomBytes as Ee,randomUUID as Ae}from"node:crypto";import{existsSync as Y,lstatSync as U,mkdirSync as Oe,readFileSync as R,unlinkSync as qe}from"node:fs";import{homedir as Te}from"node:os";import{basename as De,dirname as Ge,join as x,resolve as _}from"node:path";import{isRootProjectMemoryEffect as Be,rootProjectMemoryPaths as Ce}from"../../../shared/dist/yoloop/root-memory-effect.js";import{readPrivateRootMemoryScope as Me,privateRootMemoryEffect as Re}from"./root-memory-scope.js";import{executeRootMemoryWriter as Ne,rootMemoryFileState as xe,verifyRootMemoryWriterExecution as ze}from"./root-memory-writer.js";import{rootMemoryGitFileState as He,verifyRootMemoryEffectGitEvidence as $e}from"./root-memory-git-evidence.js";import{parsePrivateRootMemoryRequest as Le}from"./root-memory-request.js";import{rootMemoryOperationJournalName as Ye,readVerifiedPreparedRootMemory as Je}from"./root-memory-recovery.js";import{assertProjectMemoryPaths as Ve}from"../memory/project-memory-path-scope.js";import{isDeepStrictEqual as J}from"node:util";import{acquireGitLifecyclePhysicalIntegrationLock as Fe,applyGitLifecycleRuntimeOverlay as We,assertGitLifecyclePrivateFile as X,ensureGitLifecyclePrivateChildDirectory as he,gitLifecycleRuntimeDirectory as Qe,mutateGitLifecycleRuntime as Ke,readGitLifecycleRuntimeSync as fe,releaseGitLifecyclePhysicalIntegrationLock as Ue}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as z,anchoredDirectoryIdentity as Xe,anchoredExecuteGit as Ze}from"../git/secure-filesystem-boundary.js";import{privateYoloRecordLocation as et,privateYoloRootOnlySetupReady as tt,readPrivateYoloFrozenWriteSet as M,readPrivateYoloFrozenWriteSetForTransition as at}from"./clean-baseline.js";import{admitPrivateYoloFrozenWorkspace as ot,verifyPrivateYoloSnapshotBoundary as V,verifyPrivateYoloRejectedCandidateOrigin as st}from"./isolated-admission.js";import{preparePrivateYoloIsolatedWorkspace as rt}from"./isolated-workspace.js";async function Pt(t,a,e={}){const o=Le(a),{directive:r,review:s}=o,i=_(t),n=r.storyId,u=n.split(".")[0],p=d=>C("sha256").update(d).digest("hex");let h="session";const f=()=>{throw new Error(`private-root-memory-acceptance-${h}-unverified`)};try{return await D(i,n,b(i,n),async()=>{const d=fe(i,{required:!0}),m=d.epics[u],l=m?.branch_lease,c=await T(i,n);if(!c||m?.graph_revision!==r.graphRevision||l?.ownerStoryId!==n||typeof l.expiresAt!="string"||Date.parse(l.expiresAt)<=Date.now()||c.workspace.executionBranch!==r.executionBranch)return f();ee(c,i,n,r.graphRevision);const S=await he(await Qe(i),"private-execution"),H=Ye(c,o),G=c.rootMemoryEffect===void 0&&Y(x(S,H));G||await A(c,i,n,r.graphRevision);const W=await Xe(i);h="source-evidence",Ve(i,[".neocortex/state.json",`.neocortex/stories/${n}/validation-evidence.md`]);const g=R(x(i,".neocortex/state.json"));if(p(g)!==s.sourceStateSha256)return f();const y=We(JSON.parse(g.toString("utf8")),d).stories?.[n];if(!y||y.checkpoint!==void 0||!Array.isArray(y.steps_completed))return f();const te=[...y.steps_completed],ae=`.neocortex/stories/${n}/validation-evidence.md`,$=U(x(i,ae));if(!$.isFile()||$.isSymbolicLink()||$.nlink!==1||$.size<128||$.size>256*1024||p(R(x(i,ae)))!==s.proposalSha256)return f();const we=x(S,`qa-review-${s.rootQaReceiptId}.json`);h="qa-predecessor",await X(we,S);const oe=R(we);if(oe.length>16384||p(oe)!==s.rootQaReceiptId)return f();const q=JSON.parse(oe.toString("utf8"));if(q.kind!=="private-qa-root-review"||q.storyId!==n||q.sourceHeadSha!==c.workspace.baseSha||q.precommitQaAccepted!==!0||q.independentStoryQaAccepted!==!1||q.terminalAccepted!==!1)return f();const se=p(JSON.stringify(s.notes)),re=w=>`memory-review-${p(JSON.stringify(w))}.json`,me=y.status==="qa-gate-passed"&&typeof y.last_step=="string"&&p(y.last_step)==="8721319de90ade506bc9b72a908d8296856b34a11bc640629178bed3fe32e373"&&te.at(-1)===y.last_step,Se=async w=>{await Ke(i,j=>{if(!J(j.epics[u],m)||!J(j.stories[n],d.stories[n]))return f();j.stories[n]={...j.stories[n],status:"memory-updated",last_step:s.rawStepId,steps_completed:[...te,s.rawStepId]}},{expectedRevision:d.revision,preCommit:async()=>{await A(w,i,n,r.graphRevision)}})};if(c.rootMemoryEffect){if(h="replay",c.rootMemoryEffect.sourceSnapshotSha!==s.snapshotSha||c.rootMemoryEffect.proposalSha256!==se||c.rootMemoryEffect.rootQaReceiptId!==s.rootQaReceiptId)return f();const w=x(S,re(c.rootMemoryEffect));await X(w,S);const j=R(w),k=JSON.parse(j.toString("utf8"));if(k.proposalSha256!==s.proposalSha256||k.notesSha256!==se||!J(k.rootMemoryEffect,c.rootMemoryEffect))return f();const B=y.status==="memory-updated"&&y.last_step===s.rawStepId&&te.at(-1)===s.rawStepId;return!B&&!me?f():(B||(h="phase-recovery",await Se(c)),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(j),snapshotSha:c.snapshotSha,reused:!0,sourceStateUnchanged:!0,phaseRecovered:!B,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0})}if(c.snapshotSha!==s.snapshotSha||!me)return f();const I=c.workspace.workspacePath;v(I,["merge-base","--is-ancestor",q.snapshotSha,c.snapshotSha]);const Pe=[`.neocortex/stories/${n}/qa-gate-result.json`,ae,`.neocortex/stories/${n}/tdd-evidence.md`,`docs/stories/${n}.rtm.md`];if(P(I,["diff","--name-only","-z",q.snapshotSha,c.snapshotSha]).toString("utf8").split("\0").filter(Boolean).some(w=>!Pe.includes(w)))return f();const ie=await M(i,n,r.executionBranch,r.graphRevision);if(!ue(i,["diff","--cached","--quiet"]))return f();const Ie=P(i,["status","--porcelain=v1","-z","--untracked-files=all"]);let E,Q,N,K=!1;if(G){h="prepared-recovery";const w=await Je({projectRoot:i,parent:S,current:c,request:o,childPaths:ie});E=w.effect,Q=w.receipt,N=w.patch,K=w.sourceAlreadyApplied}else{for(const L of Ce())if(ie.includes(L)||!J(xe(i,L),He(I,c.snapshotSha,L)))return f();h="writer";const w=await he(S,"memory-backups"),j=Ne({snapshotRoot:I,expectedSnapshotSha:c.snapshotSha,notes:s.notes,backupDirectory:w}),k=ze(j);h="writer-snapshot",k.files.length&&(v(I,["add","-A","--",...k.files.map(L=>L.path)]),v(I,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private root memory ${n} ${c.sequence+1}`]));const B=v(I,["rev-parse","HEAD"]);E={schemaVersion:"RootProjectMemoryEffect/1",producer:"root-project-memory",storyId:n,epicId:u,executionBranch:r.executionBranch,sourceHeadSha:c.workspace.baseSha,sourceSnapshotSha:c.snapshotSha,memorySnapshotSha:B,graphRevision:r.graphRevision,childClaimRevision:p([...ie].sort().join("\0")),setupSessionId:c.setupSessionId,rootQaReceiptId:s.rootQaReceiptId,proposalSha256:k.notesSha256,canonicalSha256:k.verification.canonicalSha256,projectionSha256:k.verification.projectionSha256,projectionFileCount:k.verification.fileCount,files:k.files,recordedAt:s.reviewedAt,publicSafe:!0},h="git-evidence",$e(I,E,{storyId:n,graphRevision:r.graphRevision,childClaimRevision:E.childClaimRevision,setupSessionId:c.setupSessionId,sourceHeadSha:c.workspace.baseSha,executionBranch:r.executionBranch}),N=P(I,["diff","--binary","--full-index",c.snapshotSha,B]),Q={schemaVersion:1,kind:"private-project-memory-root-review",storyId:n,graphRevision:r.graphRevision,sourceHeadSha:c.workspace.baseSha,snapshotSha:B,proposalSha256:s.proposalSha256,notesSha256:se,sourceStateSha256:s.sourceStateSha256,checks:s.checks,reviewedAt:s.reviewedAt,rootMemoryEffect:E,independentStoryQaAccepted:!1,terminalAccepted:!1},h="prepared-journal",await z(S,H,JSON.stringify({schemaVersion:1,kind:"prepared-root-memory-effect",previousSession:c,receipt:Q,patchSha256:p(N)})+`
2
- `),await e.fault?.("after-prepared-journal")}const ne=JSON.stringify(Q)+`
3
- `,ye=E.memorySnapshotSha;if(h="source-admission",!P(i,["status","--porcelain=v1","-z","--untracked-files=all"]).equals(Ie)||v(i,["rev-parse","HEAD"])!==c.workspace.baseSha||v(i,["symbolic-ref","--short","HEAD"])!==r.executionBranch)return f();if(!K){for(const w of E.files)if(!J(xe(i,w.path),w.before))return f()}const ve=w=>Ze(Ge(i),De(i),W,["apply",...w?["--check"]:[],"--binary","-"],N);if(N.length&&!K&&(await ve(!0),await ve(!1)),await e.fault?.("after-source-admission"),!R(x(i,".neocortex/state.json")).equals(g))return f();const ce=x(S,re(E));if(Y(ce)){if(await X(ce,S),R(ce,"utf8")!==ne)return f()}else await z(S,re(E),ne);const pe=Object.freeze({...c,snapshotSha:ye,sequence:c.sequence+(E.files.length?1:0),lastPatchSha256:E.files.length?p(N):c.lastPatchSha256,rootMemoryEffect:E});return h="session-pin",await e.fault?.("before-session-pin"),await F(i,pe),await A(pe,i,n,r.graphRevision),h="phase-transition",await Se(pe),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(ne),snapshotSha:ye,reused:G,sourceStateUnchanged:!0,preparedRecovered:G,sourceWriteReused:K,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0}})}catch(d){if(d instanceof Error&&/^(private-root-memory|private-execution-isolated)-[a-z0-9-]+$/.test(d.message)?d.message:void 0)throw new Error(`private-root-memory-acceptance-${h}-unverified`,{cause:d});return f()}}function v(t,a){const e={...process.env};for(const o of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[o];return ge("git",[...a],{cwd:t,env:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024}).trim()}function P(t,a){const e={...process.env};for(const o of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[o];return ge("git",[...a],{cwd:t,env:e,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function ue(t,a){const e={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[r];const o=je("git",[...a],{cwd:t,env:e,stdio:"ignore",timeout:3e4});if(o.error||o.signal)throw new Error("git-unverified");return o.status===0}async function de(t,a){return et(t,a,"session",b(t,a))}function b(t,a){const e=a.split(".")[0],r=fe(t,{required:!0}).epics[e]?.branch_lease,s=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,i=s?.sessionId;if(s?.ownerStoryId!==a||typeof i!="string"||!/^setup-[a-f0-9]{64}$/.test(i)||i!==s.idempotencyKey)throw new Error("session-lease-invalid");return i}function ke(t,a){const e=fe(t,{required:!0}).stories[a];return tt(e)}function it(t){const a=JSON.parse(t);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("session-invalid");const e=a,o=e.workspace;if(Object.keys(e).sort().join(",")!==["schemaVersion","kind","storyId","initialGraphRevision","graphRevision","graphHistory","setupSessionId","workspace","snapshotSha","sequence","lastPatchSha256",...e.rootMemoryEffect===void 0?[]:["rootMemoryEffect"]].sort().join(",")||e.schemaVersion!==1||e.kind!=="private-yolo-isolated-session"||typeof e.storyId!="string"||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(e.storyId)||typeof e.initialGraphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.initialGraphRevision)||typeof e.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.graphRevision)||!Array.isArray(e.graphHistory)||e.graphHistory.length<1||e.graphHistory.length>65||e.graphHistory.some(s=>typeof s!="string"||!/^[a-f0-9]{64}$/.test(s))||new Set(e.graphHistory).size!==e.graphHistory.length||e.graphHistory[0]!==e.initialGraphRevision||e.graphHistory[e.graphHistory.length-1]!==e.graphRevision||typeof e.setupSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(e.setupSessionId)||typeof e.snapshotSha!="string"||!/^[a-f0-9]{40,64}$/.test(e.snapshotSha)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<0||Number(e.sequence)>64||Number(e.sequence)===0&&e.initialGraphRevision!==e.graphRevision&&e.graphHistory.length!==2||Number(e.sequence)===0&&e.lastPatchSha256!==null||Number(e.sequence)>0&&e.lastPatchSha256===null||e.lastPatchSha256!==null&&(typeof e.lastPatchSha256!="string"||!/^[a-f0-9]{64}$/.test(e.lastPatchSha256))||e.rootMemoryEffect!==void 0&&!Be(e.rootMemoryEffect)||!o||typeof o!="object"||Array.isArray(o))throw new Error("session-invalid");const r=o;if(Object.keys(r).sort().join(",")!==["schemaVersion","sourceRoot","workspacePath","baseSha","executionBranch"].sort().join(",")||r.schemaVersion!==1||typeof r.sourceRoot!="string"||typeof r.workspacePath!="string"||typeof r.baseSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.baseSha)||typeof r.executionBranch!="string"||!r.executionBranch)throw new Error("session-invalid");return e}async function T(t,a){const e=await de(t,a);if(Y(e.path))return await X(e.path,e.parent),it(R(e.path,"utf8"))}async function F(t,a){const e=await de(t,a.storyId);await z(e.parent,e.name,`${JSON.stringify(a)}
4
- `)}async function D(t,a,e,o){const r=await Fe(t,{kind:"direct",storyId:a,sessionId:e,idempotencyKey:e,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});if(!r.ok)throw new Error("private-execution-isolated-session-backpressure");try{return await o()}finally{if(!await Ue(r.path,r.owner))throw new Error("private-execution-isolated-session-lock-unverified")}}async function A(t,a,e,o){ee(t,a,e,o);const r=await M(a,e,t.workspace.executionBranch,o),s=await Z(t,r);return V(t.workspace,r,t.snapshotSha,s),s}async function Z(t,a){if(t.rootMemoryEffect===void 0)return;const e=await Me({projectRoot:t.workspace.sourceRoot,storyId:t.storyId,snapshotRoot:t.workspace.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace.baseSha,executionBranch:t.workspace.executionBranch,graphRevision:t.graphRevision,setupSessionId:t.setupSessionId,childPaths:a});if(!e||JSON.stringify(Re(e))!==JSON.stringify(t.rootMemoryEffect))throw new Error("private-root-memory-scope-unverified");return e}function ee(t,a,e,o){if(t.storyId!==e||t.graphRevision!==o||t.workspace.sourceRoot!==a||t.setupSessionId!==b(a,e)||t.sequence===0&&t.snapshotSha!==t.workspace.baseSha||t.sequence===0&&t.graphHistory.length>1&&!ke(a,e)||t.sequence>0&&t.snapshotSha===t.workspace.baseSha)throw new Error("session-binding-invalid")}async function It(t,a,e){const o=_(t.sourceRoot);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(s){if(await A(s,o,a,e),s.workspace.workspacePath!==t.workspacePath)throw new Error("session-replacement-denied");return s}const i=await M(o,a,t.executionBranch,e);V(t,i,t.baseSha);const n=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:r,workspace:t,snapshotSha:t.baseSha,sequence:0,lastPatchSha256:null});return await F(o,n),n})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function be(t,a,e,o){if(t.graphRevision===o)return await A(t,a,e,o),t;if(t.storyId!==e||t.workspace.sourceRoot!==a||t.setupSessionId!==b(a,e)||t.sequence===0&&(t.graphHistory.length!==1||t.lastPatchSha256!==null||!ke(a,e))||t.sequence>0&&t.lastPatchSha256===null||t.graphHistory.includes(o)||t.graphHistory.length>=65)throw new Error("session-graph-transition-invalid");const r=await at(a,e,t.workspace.executionBranch,t.initialGraphRevision,o);V(t.workspace,r,t.snapshotSha,await Z(t,r));const s=Object.freeze({...t,graphRevision:o,graphHistory:Object.freeze([...t.graphHistory,o])});return await F(a,s),await A(s,a,e,o),s}async function jt(t,a,e){const o=_(t);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(!s)throw new Error("session-missing");return be(s,o,a,e)})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function _t(t,a,e,o){const r=_(t);try{const s=b(r,a);return await D(r,a,s,async()=>{const i=await T(r,a);if(i)return be(i,r,a,e);const n=o??x(Te(),".local","share","neocortex","private-yolo-workspaces");o===void 0&&Oe(n,{recursive:!0,mode:448});const u=rt(r,n),p=await M(r,a,u.executionBranch,e);V(u,p,u.baseSha);const h=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:s,workspace:u,snapshotSha:u.baseSha,sequence:0,lastPatchSha256:null});return await F(r,h),h})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function At(t,a,e){const o=_(t);try{const r=await T(o,a);if(!r)throw new Error("session-missing");return await A(r,o,a,e),r}catch{throw new Error("private-execution-isolated-session-unverified")}}async function Ot(t,a,e){const o=_(t);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(!s)throw new Error("session-missing");ee(s,o,a,e);const i=await M(o,a,s.workspace.executionBranch,e),n=await Z(s,i),u=await ot(s.workspace,a,e,s.snapshotSha,!1,n);v(s.workspace.workspacePath,["add","-A","--",...u.changedPaths]),v(s.workspace.workspacePath,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private snapshot ${a} ${s.sequence+1}`]);const p=v(s.workspace.workspacePath,["rev-parse","HEAD"]);V(s.workspace,i,p,n);const h=Object.freeze({...s,snapshotSha:p,sequence:s.sequence+1,lastPatchSha256:u.patchSha256});return await F(o,h),{session:h,admission:u}})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function qt(t,a,e){const o=_(t);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(!s||s.sequence<1)throw new Error("session-incomplete");const i=await A(s,o,a,e),n=await M(o,a,s.workspace.executionBranch,e),u=s.workspace.workspacePath,p=P(u,["diff","--name-only","-z",s.workspace.baseSha,s.snapshotSha]).toString("utf8").split("\0").filter(Boolean).sort(),h=[".neocortex/state.json",`docs/stories/${a}.story.md`,`.neocortex/stories/${a}/qa-gate-result.json`,`.neocortex/stories/${a}/validation-evidence.md`,`.neocortex/stories/${a}/review.md`];if(p.length===0||p.length>1024||new Set(p).size!==p.length||p.some(l=>!n.includes(l)&&!(i&&Re(i).files.some(c=>c.path===l)))||h.some(l=>!p.includes(l)))throw new Error("bundle-incomplete");if(!ue(o,["diff","--cached","--quiet"])||P(o,["ls-files","-u","-z"]).byteLength!==0)throw new Error("index-not-clean");const f=P(u,["diff","--binary","--full-index",s.workspace.baseSha,s.snapshotSha]);if(f.byteLength===0)throw new Error("bundle-empty");v(o,["add","-A","--",...p]);const d=P(o,["diff","--cached","--binary","--full-index"]),m=P(o,["diff","--cached","--name-only","-z"]).toString("utf8").split("\0").filter(Boolean).sort();if(!d.equals(f)||m.length!==p.length||m.some((l,c)=>l!==p[c])||!ue(o,["diff","--quiet"])||v(o,["rev-parse","HEAD"])!==s.workspace.baseSha||v(o,["symbolic-ref","--quiet","--short","HEAD"])!==s.workspace.executionBranch)throw new Error("bundle-raced");return Object.freeze({schemaVersion:1,outcome:"staged-unverified",snapshotSha:s.snapshotSha,bundleSha256:C("sha256").update(d).digest("hex"),changedPaths:Object.freeze(p)})})}catch{throw new Error("private-execution-root-stage-unverified")}}function nt(t){const a=t.workspace.workspacePath,e=P(a,["status","--porcelain=v1","-z","-uall"]),o=e.toString("utf8").split("\0").filter(Boolean);if(o.length<1||o.length>1024)throw new Error("rejected-candidate-invalid");let r=0;const s=o.map(n=>{const u=n.slice(0,2),p=n.slice(3);if(![" M"," D","??"].includes(u)||p.length<1||p.length>1024||p.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(p)||p.split("/").some(l=>!l||l==="."||l===".."||l===".git"))throw new Error("rejected-candidate-path-invalid");const h=p.split("/");for(let l=1;l<h.length;l++){const c=x(a,...h.slice(0,l));if(!Y(c))break;const S=U(c);if(!S.isDirectory()||S.isSymbolicLink()||S.uid!==process.getuid?.())throw new Error("rejected-candidate-parent-invalid")}const f=x(a,p);if(u===" D"){if(Y(f))throw new Error("rejected-candidate-raced");return{path:p,code:u,mode:null,sha256:null,content:null}}const d=U(f);if(!d.isFile()||d.isSymbolicLink()||d.nlink!==1||d.uid!==process.getuid?.()||d.size>16*1024*1024)throw new Error("rejected-candidate-file-invalid");const m=R(f);if(r+=m.byteLength,r>16*1024*1024)throw new Error("rejected-candidate-too-large");return{path:p,code:u,mode:d.mode&511,sha256:C("sha256").update(m).digest("hex"),content:m}});if(new Set(s.map(n=>n.path)).size!==s.length)throw new Error("rejected-candidate-path-invalid");const i={schemaVersion:"PrivateYoloRejectedCandidateInspection/1",storyId:t.storyId,graphRevision:t.graphRevision,snapshotSha:t.snapshotSha,sourceHead:t.workspace.baseSha,sequence:t.sequence,statusSha256:C("sha256").update(e).digest("hex"),files:s.map(({content:n,...u})=>u)};return{files:s,inspection:{schemaVersion:i.schemaVersion,storyId:i.storyId,graphRevision:i.graphRevision,snapshotSha:i.snapshotSha,sourceHead:i.sourceHead,sequence:i.sequence,candidateDigest:C("sha256").update(JSON.stringify(i)).digest("hex"),changedPaths:s.map(n=>n.path),publicSafe:!0}}}async function le(t,a,e){const o=await T(t,a);if(!o)throw new Error("session-missing");ee(o,t,a,e);const r=await M(t,a,o.workspace.executionBranch,e);return st(o.workspace,r,o.snapshotSha,await Z(o,r)),{record:o,...nt(o)}}async function Tt(t,a,e,o){if(o!==!0)throw new Error("private-execution-rejected-candidate-executor-not-stopped");const r=_(t);try{return await D(r,a,b(r,a),async()=>(await le(r,a,e)).inspection)}catch{throw new Error("private-execution-rejected-candidate-unverified")}}async function Dt(t,a,e,o){if(o.executorStopped!==!0||o.authorizeDiscard!==!0||!/^[a-f0-9]{64}$/.test(o.expectedCandidateDigest))throw new Error("private-execution-rejected-candidate-input-invalid");const r=_(t);try{return await D(r,a,b(r,a),async()=>{const s=await le(r,a,e);if(s.inspection.candidateDigest!==o.expectedCandidateDigest)throw new Error("candidate-review-stale");const i=await de(r,a),n=R(i.path),u=`rejected-${Ae()}`,p=await he(i.parent,u),h=Ee(32),f=Ee(12),d=Buffer.from(JSON.stringify({schemaVersion:"PrivateYoloRejectedCandidateArchive/1",inspection:s.inspection,files:s.files.map(({content:g,...O})=>({...O,contentBase64:g?.toString("base64")??null}))})),m=_e("aes-256-gcm",h,f);m.setAAD(Buffer.from("private-yolo-rejected-candidate-v1"));const l=Buffer.concat([m.update(d),m.final()]);d.fill(0);const c=Buffer.concat([f,m.getAuthTag(),l]);try{await z(p,"candidate.key",h),await z(p,"candidate.aesgcm",c)}finally{h.fill(0)}if((await le(r,a,e)).inspection.candidateDigest!==o.expectedCandidateDigest||!R(i.path).equals(n))throw new Error("candidate-raced");const H=s.record.workspace.workspacePath,G=s.files.filter(g=>g.code!=="??").map(g=>g.path);G.length&&v(H,["restore","--source",s.record.snapshotSha,"--worktree","--",...G]);for(const g of s.files.filter(O=>O.code==="??")){const O=x(H,g.path),y=U(O);if(!y.isFile()||y.isSymbolicLink()||y.nlink!==1||C("sha256").update(R(O)).digest("hex")!==g.sha256)throw new Error("candidate-raced");qe(O)}if(await A(s.record,r,a,e),!R(i.path).equals(n))throw new Error("session-pin-raced");const W={schemaVersion:"PrivateYoloRejectedCandidateRecovery/1",outcome:"candidate-discarded",archiveId:u,archiveSha256:C("sha256").update(c).digest("hex"),candidateDigest:o.expectedCandidateDigest,snapshotSha:s.record.snapshotSha,sourceHead:s.record.workspace.baseSha,sessionPinPreserved:!0,sourcePreserved:!0,checkpointAccepted:!1,publicSafe:!0};return await z(p,"recovery.json",`${JSON.stringify(W)}
5
- `),W})}catch{throw new Error("private-execution-rejected-candidate-recovery-unverified")}}export{Pt as acceptPrivateYoloProjectMemoryRootReview,Ot as admitPrivateYoloIsolatedSessionStep,It as beginPrivateYoloIsolatedSession,Dt as discardPrivateYoloRejectedCandidate,_t as ensurePrivateYoloIsolatedSession,Tt as inspectPrivateYoloRejectedCandidate,jt as reconcilePrivateYoloIsolatedSession,At as resumePrivateYoloIsolatedSession,qt as stagePrivateYoloIsolatedSessionBundle};
1
+ import{execFileSync as ge,spawnSync as _e}from"node:child_process";import{createCipheriv as Ae,createHash as T,randomBytes as Ee,randomUUID as Oe}from"node:crypto";import{existsSync as Y,lstatSync as U,mkdirSync as qe,readFileSync as R,unlinkSync as Te}from"node:fs";import{homedir as De}from"node:os";import{basename as Ge,dirname as Be,join as v,resolve as _}from"node:path";import{isRootProjectMemoryEffect as Ce,rootProjectMemoryPaths as Me}from"./shared-root-memory-types.js";import{readPrivateRootMemoryScope as Ne,privateRootMemoryEffect as xe}from"./root-memory-scope.js";import{executeRootMemoryWriter as ze,rootMemoryFileState as Re,verifyRootMemoryWriterExecution as He}from"./root-memory-writer.js";import{rootMemoryGitFileState as $e,verifyRootMemoryEffectGitEvidence as Le}from"./root-memory-git-evidence.js";import{parsePrivateRootMemoryRequest as Ye}from"./root-memory-request.js";import{rootMemoryOperationJournalName as Je,readVerifiedPreparedRootMemory as Ve}from"./root-memory-recovery.js";import{assertProjectMemoryPaths as Fe}from"../memory/project-memory-path-scope.js";import{isDeepStrictEqual as J}from"node:util";import{acquireGitLifecyclePhysicalIntegrationLock as We,applyGitLifecycleRuntimeOverlay as Qe,assertGitLifecyclePrivateFile as X,ensureGitLifecyclePrivateChildDirectory as Z,gitLifecycleRuntimeDirectory as ke,mutateGitLifecycleRuntime as Ke,readGitLifecycleRuntimeSync as ue,releaseGitLifecyclePhysicalIntegrationLock as Ue}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as z,anchoredDirectoryIdentity as Xe,anchoredExecuteGit as Ze}from"../git/secure-filesystem-boundary.js";import{privateYoloRootOnlySetupReady as et,readPrivateYoloFrozenWriteSet as M,readPrivateYoloFrozenWriteSetForTransition as tt}from"./clean-baseline.js";import{admitPrivateYoloFrozenWorkspace as at,verifyPrivateYoloSnapshotBoundary as V,verifyPrivateYoloRejectedCandidateOrigin as ot}from"./isolated-admission.js";import{preparePrivateYoloIsolatedWorkspace as st}from"./isolated-workspace.js";async function bt(t,a,e={}){const o=Ye(a),{directive:r,review:s}=o,i=_(t),n=r.storyId,f=n.split(".")[0],p=d=>T("sha256").update(d).digest("hex");let h="session";const u=()=>{throw new Error(`private-root-memory-acceptance-${h}-unverified`)};try{return await G(i,n,I(i,n),async()=>{const d=ue(i,{required:!0}),m=d.epics[f],l=m?.branch_lease,c=await D(i,n);if(!c||m?.graph_revision!==r.graphRevision||l?.ownerStoryId!==n||typeof l.expiresAt!="string"||Date.parse(l.expiresAt)<=Date.now()||c.workspace.executionBranch!==r.executionBranch)return u();te(c,i,n,r.graphRevision);const S=await Z(await ke(i),"private-execution"),H=Je(c,o),B=c.rootMemoryEffect===void 0&&Y(v(S,H));B||await A(c,i,n,r.graphRevision);const W=await Xe(i);h="source-evidence",Fe(i,[".neocortex/state.json",`.neocortex/stories/${n}/validation-evidence.md`]);const E=R(v(i,".neocortex/state.json"));if(p(E)!==s.sourceStateSha256)return u();const y=Qe(JSON.parse(E.toString("utf8")),d).stories?.[n];if(!y||y.checkpoint!==void 0||!Array.isArray(y.steps_completed))return u();const ae=[...y.steps_completed],oe=`.neocortex/stories/${n}/validation-evidence.md`,$=U(v(i,oe));if(!$.isFile()||$.isSymbolicLink()||$.nlink!==1||$.size<128||$.size>256*1024||p(R(v(i,oe)))!==s.proposalSha256)return u();const we=v(S,`qa-review-${s.rootQaReceiptId}.json`);h="qa-predecessor",await X(we,S);const se=R(we);if(se.length>16384||p(se)!==s.rootQaReceiptId)return u();const q=JSON.parse(se.toString("utf8"));if(q.kind!=="private-qa-root-review"||q.storyId!==n||q.sourceHeadSha!==c.workspace.baseSha||q.precommitQaAccepted!==!0||q.independentStoryQaAccepted!==!1||q.terminalAccepted!==!1)return u();const re=p(JSON.stringify(s.notes)),ie=w=>`memory-review-${p(JSON.stringify(w))}.json`,me=y.status==="qa-gate-passed"&&typeof y.last_step=="string"&&p(y.last_step)==="8721319de90ade506bc9b72a908d8296856b34a11bc640629178bed3fe32e373"&&ae.at(-1)===y.last_step,Se=async w=>{await Ke(i,j=>{if(!J(j.epics[f],m)||!J(j.stories[n],d.stories[n]))return u();j.stories[n]={...j.stories[n],status:"memory-updated",last_step:s.rawStepId,steps_completed:[...ae,s.rawStepId]}},{expectedRevision:d.revision,preCommit:async()=>{await A(w,i,n,r.graphRevision)}})};if(c.rootMemoryEffect){if(h="replay",c.rootMemoryEffect.sourceSnapshotSha!==s.snapshotSha||c.rootMemoryEffect.proposalSha256!==re||c.rootMemoryEffect.rootQaReceiptId!==s.rootQaReceiptId)return u();const w=v(S,ie(c.rootMemoryEffect));await X(w,S);const j=R(w),k=JSON.parse(j.toString("utf8"));if(k.proposalSha256!==s.proposalSha256||k.notesSha256!==re||!J(k.rootMemoryEffect,c.rootMemoryEffect))return u();const C=y.status==="memory-updated"&&y.last_step===s.rawStepId&&ae.at(-1)===s.rawStepId;return!C&&!me?u():(C||(h="phase-recovery",await Se(c)),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(j),snapshotSha:c.snapshotSha,reused:!0,sourceStateUnchanged:!0,phaseRecovered:!C,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0})}if(c.snapshotSha!==s.snapshotSha||!me)return u();const P=c.workspace.workspacePath;g(P,["merge-base","--is-ancestor",q.snapshotSha,c.snapshotSha]);const Pe=[`.neocortex/stories/${n}/qa-gate-result.json`,oe,`.neocortex/stories/${n}/tdd-evidence.md`,`docs/stories/${n}.rtm.md`];if(b(P,["diff","--name-only","-z",q.snapshotSha,c.snapshotSha]).toString("utf8").split("\0").filter(Boolean).some(w=>!Pe.includes(w)))return u();const ne=await M(i,n,r.executionBranch,r.graphRevision);if(!fe(i,["diff","--cached","--quiet"]))return u();const je=b(i,["status","--porcelain=v1","-z","--untracked-files=all"]);let x,Q,N,K=!1;if(B){h="prepared-recovery";const w=await Ve({projectRoot:i,parent:S,current:c,request:o,childPaths:ne});x=w.effect,Q=w.receipt,N=w.patch,K=w.sourceAlreadyApplied}else{for(const L of Me())if(ne.includes(L)||!J(Re(i,L),$e(P,c.snapshotSha,L)))return u();h="writer";const w=await Z(S,"memory-backups"),j=ze({snapshotRoot:P,expectedSnapshotSha:c.snapshotSha,notes:s.notes,backupDirectory:w}),k=He(j);h="writer-snapshot",k.files.length&&(g(P,["add","-A","--",...k.files.map(L=>L.path)]),g(P,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private root memory ${n} ${c.sequence+1}`]));const C=g(P,["rev-parse","HEAD"]);x={schemaVersion:"RootProjectMemoryEffect/1",producer:"root-project-memory",storyId:n,epicId:f,executionBranch:r.executionBranch,sourceHeadSha:c.workspace.baseSha,sourceSnapshotSha:c.snapshotSha,memorySnapshotSha:C,graphRevision:r.graphRevision,childClaimRevision:p([...ne].sort().join("\0")),setupSessionId:c.setupSessionId,rootQaReceiptId:s.rootQaReceiptId,proposalSha256:k.notesSha256,canonicalSha256:k.verification.canonicalSha256,projectionSha256:k.verification.projectionSha256,projectionFileCount:k.verification.fileCount,files:k.files,recordedAt:s.reviewedAt,publicSafe:!0},h="git-evidence",Le(P,x,{storyId:n,graphRevision:r.graphRevision,childClaimRevision:x.childClaimRevision,setupSessionId:c.setupSessionId,sourceHeadSha:c.workspace.baseSha,executionBranch:r.executionBranch}),N=b(P,["diff","--binary","--full-index",c.snapshotSha,C]),Q={schemaVersion:1,kind:"private-project-memory-root-review",storyId:n,graphRevision:r.graphRevision,sourceHeadSha:c.workspace.baseSha,snapshotSha:C,proposalSha256:s.proposalSha256,notesSha256:re,sourceStateSha256:s.sourceStateSha256,checks:s.checks,reviewedAt:s.reviewedAt,rootMemoryEffect:x,independentStoryQaAccepted:!1,terminalAccepted:!1},h="prepared-journal",await z(S,H,JSON.stringify({schemaVersion:1,kind:"prepared-root-memory-effect",previousSession:c,receipt:Q,patchSha256:p(N)})+`
2
+ `),await e.fault?.("after-prepared-journal")}const ce=JSON.stringify(Q)+`
3
+ `,ye=x.memorySnapshotSha;if(h="source-admission",!b(i,["status","--porcelain=v1","-z","--untracked-files=all"]).equals(je)||g(i,["rev-parse","HEAD"])!==c.workspace.baseSha||g(i,["symbolic-ref","--short","HEAD"])!==r.executionBranch)return u();if(!K){for(const w of x.files)if(!J(Re(i,w.path),w.before))return u()}const ve=w=>Ze(Be(i),Ge(i),W,["apply",...w?["--check"]:[],"--binary","-"],N);if(N.length&&!K&&(await ve(!0),await ve(!1)),await e.fault?.("after-source-admission"),!R(v(i,".neocortex/state.json")).equals(E))return u();const pe=v(S,ie(x));if(Y(pe)){if(await X(pe,S),R(pe,"utf8")!==ce)return u()}else await z(S,ie(x),ce);const he=Object.freeze({...c,snapshotSha:ye,sequence:c.sequence+(x.files.length?1:0),lastPatchSha256:x.files.length?p(N):c.lastPatchSha256,rootMemoryEffect:x});return h="session-pin",await e.fault?.("before-session-pin"),await F(i,he),await A(he,i,n,r.graphRevision),h="phase-transition",await Se(he),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(ce),snapshotSha:ye,reused:B,sourceStateUnchanged:!0,preparedRecovered:B,sourceWriteReused:K,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0}})}catch(d){if(d instanceof Error&&/^(private-root-memory|private-execution-isolated)-[a-z0-9-]+$/.test(d.message)?d.message:void 0)throw new Error(`private-root-memory-acceptance-${h}-unverified`,{cause:d});return u()}}function g(t,a){const e={...process.env};for(const o of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[o];return ge("git",[...a],{cwd:t,env:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024}).trim()}function b(t,a){const e={...process.env};for(const o of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[o];return ge("git",[...a],{cwd:t,env:e,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function fe(t,a){const e={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[r];const o=_e("git",[...a],{cwd:t,env:e,stdio:"ignore",timeout:3e4});if(o.error||o.signal)throw new Error("git-unverified");return o.status===0}async function de(t,a){const e=await ke(t),o=await Z(e,"private-execution"),r=`session-${T("sha256").update(a).digest("hex")}.json`;return{parent:o,name:r,path:v(o,r)}}function I(t,a){const e=a.split(".")[0],r=ue(t,{required:!0}).epics[e]?.branch_lease,s=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,i=s?.sessionId;if(s?.ownerStoryId!==a||typeof i!="string"||!/^setup-[a-f0-9]{64}$/.test(i)||i!==s.idempotencyKey)throw new Error("session-lease-invalid");return i}function be(t,a){const e=ue(t,{required:!0}).stories[a];return et(e)}function rt(t){const a=JSON.parse(t);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("session-invalid");const e=a,o=e.workspace;if(Object.keys(e).sort().join(",")!==["schemaVersion","kind","storyId","initialGraphRevision","graphRevision","graphHistory","setupSessionId","workspace","snapshotSha","sequence","lastPatchSha256",...e.rootMemoryEffect===void 0?[]:["rootMemoryEffect"]].sort().join(",")||e.schemaVersion!==1||e.kind!=="private-yolo-isolated-session"||typeof e.storyId!="string"||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(e.storyId)||typeof e.initialGraphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.initialGraphRevision)||typeof e.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.graphRevision)||!Array.isArray(e.graphHistory)||e.graphHistory.length<1||e.graphHistory.length>65||e.graphHistory.some(s=>typeof s!="string"||!/^[a-f0-9]{64}$/.test(s))||new Set(e.graphHistory).size!==e.graphHistory.length||e.graphHistory[0]!==e.initialGraphRevision||e.graphHistory[e.graphHistory.length-1]!==e.graphRevision||typeof e.setupSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(e.setupSessionId)||typeof e.snapshotSha!="string"||!/^[a-f0-9]{40,64}$/.test(e.snapshotSha)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<0||Number(e.sequence)>64||Number(e.sequence)===0&&e.initialGraphRevision!==e.graphRevision&&e.graphHistory.length!==2||Number(e.sequence)===0&&e.lastPatchSha256!==null||Number(e.sequence)>0&&e.lastPatchSha256===null||e.lastPatchSha256!==null&&(typeof e.lastPatchSha256!="string"||!/^[a-f0-9]{64}$/.test(e.lastPatchSha256))||e.rootMemoryEffect!==void 0&&!Ce(e.rootMemoryEffect)||!o||typeof o!="object"||Array.isArray(o))throw new Error("session-invalid");const r=o;if(Object.keys(r).sort().join(",")!==["schemaVersion","sourceRoot","workspacePath","baseSha","executionBranch"].sort().join(",")||r.schemaVersion!==1||typeof r.sourceRoot!="string"||typeof r.workspacePath!="string"||typeof r.baseSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.baseSha)||typeof r.executionBranch!="string"||!r.executionBranch)throw new Error("session-invalid");return e}async function D(t,a){const e=await de(t,a);if(Y(e.path))return await X(e.path,e.parent),rt(R(e.path,"utf8"))}async function F(t,a){const e=await de(t,a.storyId);await z(e.parent,e.name,`${JSON.stringify(a)}
4
+ `)}async function G(t,a,e,o){const r=await We(t,{kind:"direct",storyId:a,sessionId:e,idempotencyKey:e,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});if(!r.ok)throw new Error("private-execution-isolated-session-backpressure");try{return await o()}finally{if(!await Ue(r.path,r.owner))throw new Error("private-execution-isolated-session-lock-unverified")}}async function A(t,a,e,o){te(t,a,e,o);const r=await M(a,e,t.workspace.executionBranch,o),s=await ee(t,r);return V(t.workspace,r,t.snapshotSha,s),s}async function ee(t,a){if(t.rootMemoryEffect===void 0)return;const e=await Ne({projectRoot:t.workspace.sourceRoot,storyId:t.storyId,snapshotRoot:t.workspace.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace.baseSha,executionBranch:t.workspace.executionBranch,graphRevision:t.graphRevision,setupSessionId:t.setupSessionId,childPaths:a});if(!e||JSON.stringify(xe(e))!==JSON.stringify(t.rootMemoryEffect))throw new Error("private-root-memory-scope-unverified");return e}function te(t,a,e,o){if(t.storyId!==e||t.graphRevision!==o||t.workspace.sourceRoot!==a||t.setupSessionId!==I(a,e)||t.sequence===0&&t.snapshotSha!==t.workspace.baseSha||t.sequence===0&&t.graphHistory.length>1&&!be(a,e)||t.sequence>0&&t.snapshotSha===t.workspace.baseSha)throw new Error("session-binding-invalid")}async function It(t,a,e){const o=_(t.sourceRoot);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(s){if(await A(s,o,a,e),s.workspace.workspacePath!==t.workspacePath)throw new Error("session-replacement-denied");return s}const i=await M(o,a,t.executionBranch,e);V(t,i,t.baseSha);const n=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:r,workspace:t,snapshotSha:t.baseSha,sequence:0,lastPatchSha256:null});return await F(o,n),n})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function Ie(t,a,e,o){if(t.graphRevision===o)return await A(t,a,e,o),t;if(t.storyId!==e||t.workspace.sourceRoot!==a||t.setupSessionId!==I(a,e)||t.sequence===0&&(t.graphHistory.length!==1||t.lastPatchSha256!==null||!be(a,e))||t.sequence>0&&t.lastPatchSha256===null||t.graphHistory.includes(o)||t.graphHistory.length>=65)throw new Error("session-graph-transition-invalid");const r=await tt(a,e,t.workspace.executionBranch,t.initialGraphRevision,o);V(t.workspace,r,t.snapshotSha,await ee(t,r));const s=Object.freeze({...t,graphRevision:o,graphHistory:Object.freeze([...t.graphHistory,o])});return await F(a,s),await A(s,a,e,o),s}async function Pt(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s)throw new Error("session-missing");return Ie(s,o,a,e)})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function jt(t,a,e,o){const r=_(t);try{const s=I(r,a);return await G(r,a,s,async()=>{const i=await D(r,a);if(i)return Ie(i,r,a,e);const n=o??v(De(),".local","share","neocortex","private-yolo-workspaces");o===void 0&&qe(n,{recursive:!0,mode:448});const f=st(r,n),p=await M(r,a,f.executionBranch,e);V(f,p,f.baseSha);const h=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:s,workspace:f,snapshotSha:f.baseSha,sequence:0,lastPatchSha256:null});return await F(r,h),h})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function _t(t,a,e){const o=_(t);try{const r=await D(o,a);if(!r)throw new Error("session-missing");return await A(r,o,a,e),r}catch{throw new Error("private-execution-isolated-session-unverified")}}async function At(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s)throw new Error("session-missing");te(s,o,a,e);const i=await M(o,a,s.workspace.executionBranch,e),n=await ee(s,i),f=await at(s.workspace,a,e,s.snapshotSha,!1,n);g(s.workspace.workspacePath,["add","-A","--",...f.changedPaths]),g(s.workspace.workspacePath,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private snapshot ${a} ${s.sequence+1}`]);const p=g(s.workspace.workspacePath,["rev-parse","HEAD"]);V(s.workspace,i,p,n);const h=Object.freeze({...s,snapshotSha:p,sequence:s.sequence+1,lastPatchSha256:f.patchSha256});return await F(o,h),{session:h,admission:f}})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function Ot(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s||s.sequence<1)throw new Error("session-incomplete");const i=await A(s,o,a,e),n=await M(o,a,s.workspace.executionBranch,e),f=s.workspace.workspacePath,p=b(f,["diff","--name-only","-z",s.workspace.baseSha,s.snapshotSha]).toString("utf8").split("\0").filter(Boolean).sort(),h=[".neocortex/state.json",`docs/stories/${a}.story.md`,`.neocortex/stories/${a}/qa-gate-result.json`,`.neocortex/stories/${a}/validation-evidence.md`,`.neocortex/stories/${a}/review.md`];if(p.length===0||p.length>1024||new Set(p).size!==p.length||p.some(l=>!n.includes(l)&&!(i&&xe(i).files.some(c=>c.path===l)))||h.some(l=>!p.includes(l)))throw new Error("bundle-incomplete");if(!fe(o,["diff","--cached","--quiet"])||b(o,["ls-files","-u","-z"]).byteLength!==0)throw new Error("index-not-clean");const u=b(f,["diff","--binary","--full-index",s.workspace.baseSha,s.snapshotSha]);if(u.byteLength===0)throw new Error("bundle-empty");g(o,["add","-A","--",...p]);const d=b(o,["diff","--cached","--binary","--full-index"]),m=b(o,["diff","--cached","--name-only","-z"]).toString("utf8").split("\0").filter(Boolean).sort();if(!d.equals(u)||m.length!==p.length||m.some((l,c)=>l!==p[c])||!fe(o,["diff","--quiet"])||g(o,["rev-parse","HEAD"])!==s.workspace.baseSha||g(o,["symbolic-ref","--quiet","--short","HEAD"])!==s.workspace.executionBranch)throw new Error("bundle-raced");return Object.freeze({schemaVersion:1,outcome:"staged-unverified",snapshotSha:s.snapshotSha,bundleSha256:T("sha256").update(d).digest("hex"),changedPaths:Object.freeze(p)})})}catch{throw new Error("private-execution-root-stage-unverified")}}function it(t){const a=t.workspace.workspacePath,e=b(a,["status","--porcelain=v1","-z","-uall"]),o=e.toString("utf8").split("\0").filter(Boolean);if(o.length<1||o.length>1024)throw new Error("rejected-candidate-invalid");let r=0;const s=o.map(n=>{const f=n.slice(0,2),p=n.slice(3);if(![" M"," D","??"].includes(f)||p.length<1||p.length>1024||p.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(p)||p.split("/").some(l=>!l||l==="."||l===".."||l===".git"))throw new Error("rejected-candidate-path-invalid");const h=p.split("/");for(let l=1;l<h.length;l++){const c=v(a,...h.slice(0,l));if(!Y(c))break;const S=U(c);if(!S.isDirectory()||S.isSymbolicLink()||S.uid!==process.getuid?.())throw new Error("rejected-candidate-parent-invalid")}const u=v(a,p);if(f===" D"){if(Y(u))throw new Error("rejected-candidate-raced");return{path:p,code:f,mode:null,sha256:null,content:null}}const d=U(u);if(!d.isFile()||d.isSymbolicLink()||d.nlink!==1||d.uid!==process.getuid?.()||d.size>16*1024*1024)throw new Error("rejected-candidate-file-invalid");const m=R(u);if(r+=m.byteLength,r>16*1024*1024)throw new Error("rejected-candidate-too-large");return{path:p,code:f,mode:d.mode&511,sha256:T("sha256").update(m).digest("hex"),content:m}});if(new Set(s.map(n=>n.path)).size!==s.length)throw new Error("rejected-candidate-path-invalid");const i={schemaVersion:"PrivateYoloRejectedCandidateInspection/1",storyId:t.storyId,graphRevision:t.graphRevision,snapshotSha:t.snapshotSha,sourceHead:t.workspace.baseSha,sequence:t.sequence,statusSha256:T("sha256").update(e).digest("hex"),files:s.map(({content:n,...f})=>f)};return{files:s,inspection:{schemaVersion:i.schemaVersion,storyId:i.storyId,graphRevision:i.graphRevision,snapshotSha:i.snapshotSha,sourceHead:i.sourceHead,sequence:i.sequence,candidateDigest:T("sha256").update(JSON.stringify(i)).digest("hex"),changedPaths:s.map(n=>n.path),publicSafe:!0}}}async function le(t,a,e){const o=await D(t,a);if(!o)throw new Error("session-missing");te(o,t,a,e);const r=await M(t,a,o.workspace.executionBranch,e);return ot(o.workspace,r,o.snapshotSha,await ee(o,r)),{record:o,...it(o)}}async function qt(t,a,e,o){if(o!==!0)throw new Error("private-execution-rejected-candidate-executor-not-stopped");const r=_(t);try{return await G(r,a,I(r,a),async()=>(await le(r,a,e)).inspection)}catch{throw new Error("private-execution-rejected-candidate-unverified")}}async function Tt(t,a,e,o){if(o.executorStopped!==!0||o.authorizeDiscard!==!0||!/^[a-f0-9]{64}$/.test(o.expectedCandidateDigest))throw new Error("private-execution-rejected-candidate-input-invalid");const r=_(t);try{return await G(r,a,I(r,a),async()=>{const s=await le(r,a,e);if(s.inspection.candidateDigest!==o.expectedCandidateDigest)throw new Error("candidate-review-stale");const i=await de(r,a),n=R(i.path),f=`rejected-${Oe()}`,p=await Z(i.parent,f),h=Ee(32),u=Ee(12),d=Buffer.from(JSON.stringify({schemaVersion:"PrivateYoloRejectedCandidateArchive/1",inspection:s.inspection,files:s.files.map(({content:E,...O})=>({...O,contentBase64:E?.toString("base64")??null}))})),m=Ae("aes-256-gcm",h,u);m.setAAD(Buffer.from("private-yolo-rejected-candidate-v1"));const l=Buffer.concat([m.update(d),m.final()]);d.fill(0);const c=Buffer.concat([u,m.getAuthTag(),l]);try{await z(p,"candidate.key",h),await z(p,"candidate.aesgcm",c)}finally{h.fill(0)}if((await le(r,a,e)).inspection.candidateDigest!==o.expectedCandidateDigest||!R(i.path).equals(n))throw new Error("candidate-raced");const H=s.record.workspace.workspacePath,B=s.files.filter(E=>E.code!=="??").map(E=>E.path);B.length&&g(H,["restore","--source",s.record.snapshotSha,"--worktree","--",...B]);for(const E of s.files.filter(O=>O.code==="??")){const O=v(H,E.path),y=U(O);if(!y.isFile()||y.isSymbolicLink()||y.nlink!==1||T("sha256").update(R(O)).digest("hex")!==E.sha256)throw new Error("candidate-raced");Te(O)}if(await A(s.record,r,a,e),!R(i.path).equals(n))throw new Error("session-pin-raced");const W={schemaVersion:"PrivateYoloRejectedCandidateRecovery/1",outcome:"candidate-discarded",archiveId:f,archiveSha256:T("sha256").update(c).digest("hex"),candidateDigest:o.expectedCandidateDigest,snapshotSha:s.record.snapshotSha,sourceHead:s.record.workspace.baseSha,sessionPinPreserved:!0,sourcePreserved:!0,checkpointAccepted:!1,publicSafe:!0};return await z(p,"recovery.json",`${JSON.stringify(W)}
5
+ `),W})}catch{throw new Error("private-execution-rejected-candidate-recovery-unverified")}}export{bt as acceptPrivateYoloProjectMemoryRootReview,At as admitPrivateYoloIsolatedSessionStep,It as beginPrivateYoloIsolatedSession,Tt as discardPrivateYoloRejectedCandidate,jt as ensurePrivateYoloIsolatedSession,qt as inspectPrivateYoloRejectedCandidate,Pt as reconcilePrivateYoloIsolatedSession,_t as resumePrivateYoloIsolatedSession,Ot as stagePrivateYoloIsolatedSessionBundle};
@@ -1,4 +1,4 @@
1
- import { type RootMemoryFileState, type RootProjectMemoryEffect } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
+ import { type RootMemoryFileState, type RootProjectMemoryEffect } from './shared-root-memory-types.js';
2
2
  /** Hash Git blobs without following links, using the same link-byte hash as the writer. */
3
3
  export declare function rootMemoryGitFileState(root: string, sha: string, path: string): RootMemoryFileState;
4
4
  export interface RootMemoryGitBinding {
@@ -1,3 +1,3 @@
1
- import{execFileSync as S}from"node:child_process";import{createHash as R}from"node:crypto";import{isDeepStrictEqual as f}from"node:util";import{canonicalRootMemoryEffectJson as x,isRootProjectMemoryEffect as p,rootProjectMemoryPaths as d}from"../../../shared/dist/yoloop/root-memory-effect.js";import{getProjectMemoryTarget as E,listProjectMemoryTargets as P}from"../../../shared/dist/project-memory-targets.js";import{shouldUseManagedWrapper as g}from"../memory/project-memory-writer.js";const u=o=>R("sha256").update(o).digest("hex"),i=()=>{throw new Error("private-root-memory-git-evidence-unverified")};function l(o,t){return S("git",[...t],{cwd:o,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([e])=>!e.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}function m(o,t,e){if(t!==":"&&!/^[a-f0-9]{40,64}$/.test(t)||!d().includes(e))return i();const h=l(o,t===":"?["ls-files","--stage","-z","--",e]:["ls-tree","-z",t,"--",e]).toString("utf8");if(!h)return{kind:"absent",sha256:null};const s=(t===":"?/^(100644|120000) ([a-f0-9]{40,64}) 0\t([^\0]+)\0$/:/^(100644|120000) blob ([a-f0-9]{40,64})\t([^\0]+)\0$/).exec(h);if(!s||s[3]!==e)return i();const c=l(o,["cat-file","blob",s[2]]);return c.byteLength>512*1024?i():s[1]==="120000"?{kind:"symlink",sha256:u(c),linkTarget:c.toString("utf8")}:{kind:"regular",sha256:u(c)}}function C(o,t,e){try{if(!p(t)||!e||["storyId","graphRevision","childClaimRevision","setupSessionId","sourceHeadSha","executionBranch"].some(s=>t[s]!==e[s]))return i();l(o,["merge-base","--is-ancestor",t.sourceHeadSha,t.sourceSnapshotSha]),l(o,["merge-base","--is-ancestor",t.sourceSnapshotSha,t.memorySnapshotSha]);const h=l(o,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",t.sourceSnapshotSha,t.memorySnapshotSha]).toString("utf8").split("\0").filter(Boolean).sort();if(!f(h,t.files.map(s=>s.path).sort()))return i();for(const s of t.files){const c=m(o,t.sourceSnapshotSha,s.path),r=m(o,t.memorySnapshotSha,s.path);if(!f(c,s.before)||!f(r,s.after)||f(c,r))return i()}return y(o,t.memorySnapshotSha,t),t}catch{return i()}}function y(o,t,e){const h=m(o,t,"NEOCORTEX.md");if(h.kind!=="regular"||h.sha256!==e.canonicalSha256)return i();const s=new Map;for(const r of[E("canonical"),...P()])for(const a of[r.primaryFile,...r.targetId==="canonical"?[]:r.secondaryFiles.filter(n=>n.scope==="project").map(n=>n.path)])s.has(a)||s.set(a,r.targetId==="canonical"?"canonical":g(r,a)?"managed-wrapper":"semantic-symlink");const c=[...s].sort(([r],[a])=>r<a?-1:r>a?1:0).map(([r,a])=>{const n=m(o,t,r);return n.kind==="absent"||a!=="semantic-symlink"&&n.kind!=="regular"||a==="semantic-symlink"&&(n.kind!=="symlink"||n.linkTarget!=="../".repeat(r.split("/").length-1)+"NEOCORTEX.md")?i():`${r}:${a}:${n.kind==="symlink"?h.sha256:n.sha256}`});if(e.projectionFileCount!==c.length||e.projectionSha256!==u(Buffer.from(c.join(`
2
- `))))return i()}function k(o){return u(Buffer.from(x(o)))}function I(o,t,e){try{if(!p(t)||!e||t.storyId!==e.storyId||t.executionBranch!==e.executionBranch||t.sourceHeadSha!==e.baseSha||!/^[a-f0-9]{40,64}$/.test(e.baseSha)||e.headRef!==":"&&!/^[a-f0-9]{40,64}$/.test(e.headRef)||!Array.isArray(e.childPaths)||e.childPaths.length<1||e.childPaths.length>1024||e.childPaths.some(r=>typeof r!="string"||!r||r.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(r)||r.split("/").includes("..")||r.split("/").includes(".git"))||new Set(e.childPaths).size!==e.childPaths.length||t.childClaimRevision!==u(Buffer.from([...e.childPaths].sort().join("\0"))))return i();const h=r=>e.childPaths.some(a=>a===r||a.endsWith("/")&&r.startsWith(a)),s=l(o,["diff",...e.headRef===":"?["--cached"]:[],"--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.baseSha,...e.headRef===":"?[]:[e.headRef]]).toString("utf8").split("\0").filter(Boolean),c=t.files.map(r=>r.path).sort();if(!f(s.filter(r=>!h(r)).sort(),c)||t.files.some(r=>h(r.path)))return i();for(const r of t.files){const a=m(o,e.baseSha,r.path),n=m(o,e.headRef,r.path);if(!f(a,r.before)||!f(n,r.after)||f(a,n))return i()}if(y(o,e.headRef,t),e.headRef!==":"){const a=l(o,["show","--no-patch","--format=%B",e.headRef]).toString("utf8").split(`
3
- `).filter(n=>n.startsWith("Neocortex-Root-Memory-Effect:"));if(a.length!==1||a[0]!==`Neocortex-Root-Memory-Effect: ${k(t)}`)return i()}return t}catch{return i()}}export{k as rootMemoryEffectDigest,m as rootMemoryGitFileState,C as verifyRootMemoryEffectGitEvidence,I as verifyRootMemoryPhysicalWriteSet};
1
+ import{execFileSync as S}from"node:child_process";import{createHash as R}from"node:crypto";import{isDeepStrictEqual as f}from"node:util";import{canonicalRootMemoryEffectJson as x,getProjectMemoryTarget as d,listProjectMemoryTargets as E,isRootProjectMemoryEffect as p,rootProjectMemoryPaths as P}from"./shared-root-memory-types.js";import{shouldUseManagedWrapper as g}from"../memory/project-memory-writer.js";const u=o=>R("sha256").update(o).digest("hex"),i=()=>{throw new Error("private-root-memory-git-evidence-unverified")};function l(o,t){return S("git",[...t],{cwd:o,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([e])=>!e.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}function m(o,t,e){if(t!==":"&&!/^[a-f0-9]{40,64}$/.test(t)||!P().includes(e))return i();const h=l(o,t===":"?["ls-files","--stage","-z","--",e]:["ls-tree","-z",t,"--",e]).toString("utf8");if(!h)return{kind:"absent",sha256:null};const s=(t===":"?/^(100644|120000) ([a-f0-9]{40,64}) 0\t([^\0]+)\0$/:/^(100644|120000) blob ([a-f0-9]{40,64})\t([^\0]+)\0$/).exec(h);if(!s||s[3]!==e)return i();const c=l(o,["cat-file","blob",s[2]]);return c.byteLength>512*1024?i():s[1]==="120000"?{kind:"symlink",sha256:u(c),linkTarget:c.toString("utf8")}:{kind:"regular",sha256:u(c)}}function $(o,t,e){try{if(!p(t)||!e||["storyId","graphRevision","childClaimRevision","setupSessionId","sourceHeadSha","executionBranch"].some(s=>t[s]!==e[s]))return i();l(o,["merge-base","--is-ancestor",t.sourceHeadSha,t.sourceSnapshotSha]),l(o,["merge-base","--is-ancestor",t.sourceSnapshotSha,t.memorySnapshotSha]);const h=l(o,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",t.sourceSnapshotSha,t.memorySnapshotSha]).toString("utf8").split("\0").filter(Boolean).sort();if(!f(h,t.files.map(s=>s.path).sort()))return i();for(const s of t.files){const c=m(o,t.sourceSnapshotSha,s.path),r=m(o,t.memorySnapshotSha,s.path);if(!f(c,s.before)||!f(r,s.after)||f(c,r))return i()}return y(o,t.memorySnapshotSha,t),t}catch{return i()}}function y(o,t,e){const h=m(o,t,"NEOCORTEX.md");if(h.kind!=="regular"||h.sha256!==e.canonicalSha256)return i();const s=new Map;for(const r of[d("canonical"),...E()])for(const a of[r.primaryFile,...r.targetId==="canonical"?[]:r.secondaryFiles.filter(n=>n.scope==="project").map(n=>n.path)])s.has(a)||s.set(a,r.targetId==="canonical"?"canonical":g(r,a)?"managed-wrapper":"semantic-symlink");const c=[...s].sort(([r],[a])=>r<a?-1:r>a?1:0).map(([r,a])=>{const n=m(o,t,r);return n.kind==="absent"||a!=="semantic-symlink"&&n.kind!=="regular"||a==="semantic-symlink"&&(n.kind!=="symlink"||n.linkTarget!=="../".repeat(r.split("/").length-1)+"NEOCORTEX.md")?i():`${r}:${a}:${n.kind==="symlink"?h.sha256:n.sha256}`});if(e.projectionFileCount!==c.length||e.projectionSha256!==u(Buffer.from(c.join(`
2
+ `))))return i()}function k(o){return u(Buffer.from(x(o)))}function C(o,t,e){try{if(!p(t)||!e||t.storyId!==e.storyId||t.executionBranch!==e.executionBranch||t.sourceHeadSha!==e.baseSha||!/^[a-f0-9]{40,64}$/.test(e.baseSha)||e.headRef!==":"&&!/^[a-f0-9]{40,64}$/.test(e.headRef)||!Array.isArray(e.childPaths)||e.childPaths.length<1||e.childPaths.length>1024||e.childPaths.some(r=>typeof r!="string"||!r||r.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(r)||r.split("/").includes("..")||r.split("/").includes(".git"))||new Set(e.childPaths).size!==e.childPaths.length||t.childClaimRevision!==u(Buffer.from([...e.childPaths].sort().join("\0"))))return i();const h=r=>e.childPaths.some(a=>a===r||a.endsWith("/")&&r.startsWith(a)),s=l(o,["diff",...e.headRef===":"?["--cached"]:[],"--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.baseSha,...e.headRef===":"?[]:[e.headRef]]).toString("utf8").split("\0").filter(Boolean),c=t.files.map(r=>r.path).sort();if(!f(s.filter(r=>!h(r)).sort(),c)||t.files.some(r=>h(r.path)))return i();for(const r of t.files){const a=m(o,e.baseSha,r.path),n=m(o,e.headRef,r.path);if(!f(a,r.before)||!f(n,r.after)||f(a,n))return i()}if(y(o,e.headRef,t),e.headRef!==":"){const a=l(o,["show","--no-patch","--format=%B",e.headRef]).toString("utf8").split(`
3
+ `).filter(n=>n.startsWith("Neocortex-Root-Memory-Effect:"));if(a.length!==1||a[0]!==`Neocortex-Root-Memory-Effect: ${k(t)}`)return i()}return t}catch{return i()}}export{k as rootMemoryEffectDigest,m as rootMemoryGitFileState,$ as verifyRootMemoryEffectGitEvidence,C as verifyRootMemoryPhysicalWriteSet};
@@ -9,7 +9,7 @@ export declare function readVerifiedPreparedRootMemory(input: {
9
9
  readonly childPaths: readonly string[];
10
10
  }): Promise<{
11
11
  receipt: any;
12
- effect: import("../../../shared/dist/yoloop/root-memory-effect.js").RootProjectMemoryEffect;
12
+ effect: import("./shared-root-memory-types.js").RootProjectMemoryEffect;
13
13
  patch: Buffer<ArrayBufferLike>;
14
14
  sourceAlreadyApplied: boolean;
15
15
  journalPath: string;
@@ -1 +1 @@
1
- import{createHash as x}from"node:crypto";import{execFileSync as M}from"node:child_process";import{existsSync as O,lstatSync as m,readFileSync as P,realpathSync as A}from"node:fs";import{join as l}from"node:path";import{isDeepStrictEqual as d}from"node:util";import{isRootProjectMemoryEffect as D,rootProjectMemoryPaths as H}from"../../../shared/dist/yoloop/root-memory-effect.js";import{assertGitLifecyclePrivateFile as B}from"../git/git-lifecycle-store.js";import{privateYoloSourceFileMatchesSnapshot as F}from"./isolated-admission.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as J}from"./root-memory-git-evidence.js";import{rootMemoryFileState as N}from"./root-memory-writer.js";const S=s=>x("sha256").update(s).digest("hex"),n=()=>{throw new Error("private-root-memory-prepared-recovery-unverified")},b=(s,e)=>Object.keys(s).sort().join("|")===[...e].sort().join("|");function c(s,e){return M("git",[...e],{cwd:s,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([t])=>!t.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:16*1024*1024})}function G(s,e){return`memory-operation-${S(JSON.stringify([s.storyId,s.setupSessionId,s.graphRevision,e.review.snapshotSha,e.review.proposalSha256,e.review.sourceStateSha256,e.review.rootQaReceiptId,S(JSON.stringify(e.review.notes))]))}.json`}async function U(s){try{const{projectRoot:e,current:t,request:g,childPaths:f}=s,{review:h,directive:u}=g,y=l(s.parent,G(t,g));await B(y,s.parent);const w=P(y);if(w.length>256*1024)return n();const p=JSON.parse(w.toString("utf8"));if(!p||!b(p,["schemaVersion","kind","previousSession","receipt","patchSha256"])||p.schemaVersion!==1||p.kind!=="prepared-root-memory-effect"||!d(p.previousSession,t)||t.rootMemoryEffect!==void 0)return n();const r=p.receipt,a=r?.rootMemoryEffect;if(!r||!b(r,["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"])||!D(a)||r.schemaVersion!==1||r.kind!=="private-project-memory-root-review"||r.storyId!==t.storyId||r.graphRevision!==t.graphRevision||r.sourceHeadSha!==t.workspace.baseSha||r.snapshotSha!==a.memorySnapshotSha||r.proposalSha256!==h.proposalSha256||r.sourceStateSha256!==h.sourceStateSha256||r.notesSha256!==S(JSON.stringify(h.notes))||r.notesSha256!==a.proposalSha256||!d(r.checks,h.checks)||r.reviewedAt!==a.recordedAt||a.sourceSnapshotSha!==t.snapshotSha||a.rootQaReceiptId!==h.rootQaReceiptId||r.independentStoryQaAccepted!==!1||r.terminalAccepted!==!1)return n();const o=t.workspace.workspacePath;if(A(e)!==e||A(o)!==o||!m(o).isDirectory()||m(o).uid!==process.getuid?.()||(m(o).mode&63)!==0||!m(l(o,".git")).isDirectory()||m(l(o,".git")).isSymbolicLink()||O(l(o,".git/objects/info/alternates"))||c(o,["rev-parse","--show-toplevel"]).toString().trim()!==o||c(e,["rev-parse","--show-toplevel"]).toString().trim()!==e||c(e,["rev-parse","HEAD"]).toString().trim()!==t.workspace.baseSha||c(e,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["rev-parse","HEAD"]).toString().trim()!==a.memorySnapshotSha||c(o,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["status","--porcelain=v1","-z","--untracked-files=all","--ignored=matching"]).length!==0||c(e,["diff","--cached","--name-only","-z"]).length!==0||(J(o,a,{storyId:t.storyId,graphRevision:t.graphRevision,childClaimRevision:S([...f].sort().join("\0")),setupSessionId:t.setupSessionId,sourceHeadSha:t.workspace.baseSha,executionBranch:u.executionBranch}),f.some(i=>!F(e,o,t.snapshotSha,i))))return n();const k=a.files.map(i=>i.path);if(c(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(i=>![" M"," D","??"," T"].includes(i.slice(0,2))||!f.includes(i.slice(3))&&!k.includes(i.slice(3))||i.slice(0,2)===" T"&&!k.includes(i.slice(3))))return n();let E=!0,v=!0;for(const i of H()){if(f.includes(i))return n();const R=N(e,i);E&&=d(R,I(o,t.snapshotSha,i)),v&&=d(R,I(o,a.memorySnapshotSha,i))}if(!E&&!v)return n();const j=c(o,["diff","--binary","--full-index",t.snapshotSha,a.memorySnapshotSha]);return S(j)!==p.patchSha256?n():{receipt:r,effect:a,patch:j,sourceAlreadyApplied:v,journalPath:y}}catch{return n()}}export{U as readVerifiedPreparedRootMemory,G as rootMemoryOperationJournalName};
1
+ import{createHash as x}from"node:crypto";import{execFileSync as M}from"node:child_process";import{existsSync as O,lstatSync as m,readFileSync as P,realpathSync as A}from"node:fs";import{join as l}from"node:path";import{isDeepStrictEqual as d}from"node:util";import{isRootProjectMemoryEffect as D,rootProjectMemoryPaths as H}from"./shared-root-memory-types.js";import{assertGitLifecyclePrivateFile as B}from"../git/git-lifecycle-store.js";import{privateYoloSourceFileMatchesSnapshot as F}from"./isolated-admission.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as J}from"./root-memory-git-evidence.js";import{rootMemoryFileState as N}from"./root-memory-writer.js";const S=s=>x("sha256").update(s).digest("hex"),n=()=>{throw new Error("private-root-memory-prepared-recovery-unverified")},b=(s,e)=>Object.keys(s).sort().join("|")===[...e].sort().join("|");function c(s,e){return M("git",[...e],{cwd:s,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([t])=>!t.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:16*1024*1024})}function G(s,e){return`memory-operation-${S(JSON.stringify([s.storyId,s.setupSessionId,s.graphRevision,e.review.snapshotSha,e.review.proposalSha256,e.review.sourceStateSha256,e.review.rootQaReceiptId,S(JSON.stringify(e.review.notes))]))}.json`}async function U(s){try{const{projectRoot:e,current:t,request:g,childPaths:f}=s,{review:h,directive:u}=g,y=l(s.parent,G(t,g));await B(y,s.parent);const w=P(y);if(w.length>256*1024)return n();const p=JSON.parse(w.toString("utf8"));if(!p||!b(p,["schemaVersion","kind","previousSession","receipt","patchSha256"])||p.schemaVersion!==1||p.kind!=="prepared-root-memory-effect"||!d(p.previousSession,t)||t.rootMemoryEffect!==void 0)return n();const r=p.receipt,a=r?.rootMemoryEffect;if(!r||!b(r,["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"])||!D(a)||r.schemaVersion!==1||r.kind!=="private-project-memory-root-review"||r.storyId!==t.storyId||r.graphRevision!==t.graphRevision||r.sourceHeadSha!==t.workspace.baseSha||r.snapshotSha!==a.memorySnapshotSha||r.proposalSha256!==h.proposalSha256||r.sourceStateSha256!==h.sourceStateSha256||r.notesSha256!==S(JSON.stringify(h.notes))||r.notesSha256!==a.proposalSha256||!d(r.checks,h.checks)||r.reviewedAt!==a.recordedAt||a.sourceSnapshotSha!==t.snapshotSha||a.rootQaReceiptId!==h.rootQaReceiptId||r.independentStoryQaAccepted!==!1||r.terminalAccepted!==!1)return n();const o=t.workspace.workspacePath;if(A(e)!==e||A(o)!==o||!m(o).isDirectory()||m(o).uid!==process.getuid?.()||(m(o).mode&63)!==0||!m(l(o,".git")).isDirectory()||m(l(o,".git")).isSymbolicLink()||O(l(o,".git/objects/info/alternates"))||c(o,["rev-parse","--show-toplevel"]).toString().trim()!==o||c(e,["rev-parse","--show-toplevel"]).toString().trim()!==e||c(e,["rev-parse","HEAD"]).toString().trim()!==t.workspace.baseSha||c(e,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["rev-parse","HEAD"]).toString().trim()!==a.memorySnapshotSha||c(o,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["status","--porcelain=v1","-z","--untracked-files=all","--ignored=matching"]).length!==0||c(e,["diff","--cached","--name-only","-z"]).length!==0||(J(o,a,{storyId:t.storyId,graphRevision:t.graphRevision,childClaimRevision:S([...f].sort().join("\0")),setupSessionId:t.setupSessionId,sourceHeadSha:t.workspace.baseSha,executionBranch:u.executionBranch}),f.some(i=>!F(e,o,t.snapshotSha,i))))return n();const k=a.files.map(i=>i.path);if(c(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(i=>![" M"," D","??"," T"].includes(i.slice(0,2))||!f.includes(i.slice(3))&&!k.includes(i.slice(3))||i.slice(0,2)===" T"&&!k.includes(i.slice(3))))return n();let E=!0,v=!0;for(const i of H()){if(f.includes(i))return n();const R=N(e,i);E&&=d(R,I(o,t.snapshotSha,i)),v&&=d(R,I(o,a.memorySnapshotSha,i))}if(!E&&!v)return n();const j=c(o,["diff","--binary","--full-index",t.snapshotSha,a.memorySnapshotSha]);return S(j)!==p.patchSha256?n():{receipt:r,effect:a,patch:j,sourceAlreadyApplied:v,journalPath:y}}catch{return n()}}export{U as readVerifiedPreparedRootMemory,G as rootMemoryOperationJournalName};
@@ -1,4 +1,4 @@
1
- import { type RootProjectMemoryEffect } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
+ import { type RootProjectMemoryEffect } from './shared-root-memory-types.js';
2
2
  export interface PrivateRootMemoryScope {
3
3
  readonly __rootMemoryScope: never;
4
4
  }
@@ -1 +1 @@
1
- import{createHash as S}from"node:crypto";import{execFileSync as A}from"node:child_process";import{existsSync as B,readFileSync as l}from"node:fs";import{join as g,resolve as w}from"node:path";import{isDeepStrictEqual as u}from"node:util";import{isRootProjectMemoryEffect as _}from"../../../shared/dist/yoloop/root-memory-effect.js";import{assertGitLifecyclePrivateFile as R,ensureGitLifecyclePrivateChildDirectory as k,gitLifecycleRuntimeDirectory as P,readGitLifecycleRuntime as H}from"../git/git-lifecycle-store.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as C,verifyRootMemoryPhysicalWriteSet as $}from"./root-memory-git-evidence.js";import{rootMemoryFileState as G}from"./root-memory-writer.js";import{ROOT_MEMORY_REVIEW_CHECKS as b,ROOT_MEMORY_STEP_DIGEST as T}from"./root-memory-request.js";import{parseRefreshMemoryArgs as q,verifyProjectMemoryTargets as F}from"../commands/refresh-memory.js";const j=new WeakMap,n=()=>{throw new Error("private-root-memory-scope-unverified")};function m(e,o){return A("git",[...o],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([h])=>!h.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}async function J(e){let o="pin";try{const h=w(e.projectRoot);if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return n();const r=await k(await P(h),"private-execution"),a=g(r,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);await R(a,r);const i=l(a);if(i.length>128*1024)return n();const s=JSON.parse(i.toString("utf8"));if(o="binding",s.storyId!==e.storyId||s.graphRevision!==e.graphRevision||s.setupSessionId!==e.setupSessionId||s.snapshotSha!==e.snapshotSha||s.workspace?.sourceRoot!==h||s.workspace?.workspacePath!==e.snapshotRoot||s.workspace?.baseSha!==e.sourceHeadSha||s.workspace?.executionBranch!==e.executionBranch)return n();if(s.rootMemoryEffect===void 0)return;const t=s.rootMemoryEffect;if(!_(t)||!Array.isArray(s.graphHistory)||!s.graphHistory.includes(t.graphRevision))return n();o="producer-receipt";const d=f=>S("sha256").update(f).digest("hex"),y=g(r,`memory-review-${d(JSON.stringify(t))}.json`);await R(y,r);const x=l(y);if(x.length>128*1024)return n();const c=JSON.parse(x.toString("utf8"));if(Object.keys(c).sort().join("|")!==["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"].sort().join("|")||c.schemaVersion!==1||c.kind!=="private-project-memory-root-review"||c.storyId!==e.storyId||c.graphRevision!==t.graphRevision||c.sourceHeadSha!==e.sourceHeadSha||c.snapshotSha!==t.memorySnapshotSha||c.notesSha256!==t.proposalSha256||c.reviewedAt!==t.recordedAt||c.independentStoryQaAccepted!==!1||c.terminalAccepted!==!1||!u(c.rootMemoryEffect,t)||!c.checks||Object.keys(c.checks).sort().join("|")!==[...b].sort().join("|")||b.some(f=>c.checks[f]!==!0)||c.proposalSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/stories/${e.storyId}/validation-evidence.md`])))||c.sourceStateSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/state.json`]))))return n();const E=g(r,`qa-review-${t.rootQaReceiptId}.json`);await R(E,r);const v=l(E);if(v.length>16384||d(v)!==t.rootQaReceiptId)return n();const p=JSON.parse(v.toString("utf8"));if(p.kind!=="private-qa-root-review"||p.storyId!==e.storyId||p.sourceHeadSha!==e.sourceHeadSha||p.precommitQaAccepted!==!0||p.independentStoryQaAccepted!==!1||p.terminalAccepted!==!1||(m(e.snapshotRoot,["merge-base","--is-ancestor",p.snapshotSha,t.sourceSnapshotSha]),o="git-evidence",C(e.snapshotRoot,t,{storyId:e.storyId,executionBranch:e.executionBranch,sourceHeadSha:e.sourceHeadSha,graphRevision:t.graphRevision,setupSessionId:e.setupSessionId,childClaimRevision:S("sha256").update([...e.childPaths].sort().join("\0")).digest("hex")}),o="range",m(e.snapshotRoot,["merge-base","--is-ancestor",t.memorySnapshotSha,e.snapshotSha]),m(e.snapshotRoot,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.sourceHeadSha,e.snapshotSha]).split("\0").filter(Boolean).some(f=>!e.childPaths.includes(f)&&!t.files.some(O=>O.path===f))))return n();o="files";for(const f of t.files)if(e.childPaths.includes(f.path)||!u(I(e.snapshotRoot,e.sourceHeadSha,f.path),f.before)||!u(I(e.snapshotRoot,e.snapshotSha,f.path),f.after))return n();const M=Object.freeze(Object.create(null));return j.set(M,Object.freeze({effect:structuredClone(t),root:h,snapshotRoot:e.snapshotRoot})),M}catch{throw new Error(`private-root-memory-scope-${o}-unverified`)}}function N(e){const o=j.get(e);return o?structuredClone(o.effect):n()}function Q(e,o,h,r){return L(e,o,h,r)==="matched"}function L(e,o,h,r){const a=j.get(e);if(!a||a.root!==w(o)||h!==void 0&&h!==a.snapshotRoot)return"scope-binding";let i="snapshot-ancestry";try{if(r&&(m(a.snapshotRoot,["merge-base","--is-ancestor",a.effect.memorySnapshotSha,r]),i="snapshot-content",a.effect.files.some(t=>!u(I(a.snapshotRoot,r,t.path),t.after)))||(i="source-content",!a.effect.files.every(t=>u(G(o,t.path),t.after))))return i;i="source-projection";const s=F(q(["--project-root",o,"--verify"]));return s.canonicalSha256===a.effect.canonicalSha256&&s.projectionSha256===a.effect.projectionSha256&&s.fileCount===a.effect.projectionFileCount?"matched":i}catch{return i+"-unsafe"}}async function re(e){try{const o=w(e.projectRoot),h=await H(o,{required:!0}),r=h.stories[e.storyId]?.checkpoint;if(r?.rootMemoryEffect!==void 0)return r.storyId!==e.storyId||r.branch!==e.executionBranch||typeof r.baseSha!="string"||typeof r.headSha!="string"?n():structuredClone($(o,r.rootMemoryEffect,{storyId:e.storyId,executionBranch:e.executionBranch,baseSha:r.baseSha,headRef:r.headSha,childPaths:e.childPaths}));if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return;const a=await k(await P(o),"private-execution"),i=g(a,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);if(!B(i))return;await R(i,a);const s=l(i);if(s.length>128*1024)return n();const t=JSON.parse(s.toString("utf8"));if(t.rootMemoryEffect===void 0)return;const d=h.stories[e.storyId];if(d?.status!=="memory-updated"||typeof d.last_step!="string"||S("sha256").update(d.last_step).digest("hex")!==T||!Array.isArray(d.steps_completed)||d.steps_completed.at(-1)!==d.last_step)return n();const y=await J({projectRoot:o,storyId:e.storyId,snapshotRoot:t.workspace?.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace?.baseSha,executionBranch:e.executionBranch,graphRevision:e.graphRevision,setupSessionId:t.setupSessionId,childPaths:e.childPaths});return!y||!Q(y,o,t.workspace?.workspacePath,t.snapshotSha)?n():N(y)}catch{return n()}}export{N as privateRootMemoryEffect,L as privateRootMemorySourceMatchReason,Q as privateRootMemorySourceMatches,J as readPrivateRootMemoryScope,re as readRootMemoryEffectForCheckpoint};
1
+ import{createHash as S}from"node:crypto";import{execFileSync as A}from"node:child_process";import{existsSync as B,readFileSync as l}from"node:fs";import{join as g,resolve as w}from"node:path";import{isDeepStrictEqual as u}from"node:util";import{isRootProjectMemoryEffect as _}from"./shared-root-memory-types.js";import{assertGitLifecyclePrivateFile as R,ensureGitLifecyclePrivateChildDirectory as k,gitLifecycleRuntimeDirectory as P,readGitLifecycleRuntime as H}from"../git/git-lifecycle-store.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as C,verifyRootMemoryPhysicalWriteSet as $}from"./root-memory-git-evidence.js";import{rootMemoryFileState as G}from"./root-memory-writer.js";import{ROOT_MEMORY_REVIEW_CHECKS as b,ROOT_MEMORY_STEP_DIGEST as T}from"./root-memory-request.js";import{parseRefreshMemoryArgs as q,verifyProjectMemoryTargets as F}from"../commands/refresh-memory.js";const j=new WeakMap,n=()=>{throw new Error("private-root-memory-scope-unverified")};function m(e,o){return A("git",[...o],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([h])=>!h.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}async function J(e){let o="pin";try{const h=w(e.projectRoot);if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return n();const r=await k(await P(h),"private-execution"),a=g(r,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);await R(a,r);const i=l(a);if(i.length>128*1024)return n();const s=JSON.parse(i.toString("utf8"));if(o="binding",s.storyId!==e.storyId||s.graphRevision!==e.graphRevision||s.setupSessionId!==e.setupSessionId||s.snapshotSha!==e.snapshotSha||s.workspace?.sourceRoot!==h||s.workspace?.workspacePath!==e.snapshotRoot||s.workspace?.baseSha!==e.sourceHeadSha||s.workspace?.executionBranch!==e.executionBranch)return n();if(s.rootMemoryEffect===void 0)return;const t=s.rootMemoryEffect;if(!_(t)||!Array.isArray(s.graphHistory)||!s.graphHistory.includes(t.graphRevision))return n();o="producer-receipt";const d=f=>S("sha256").update(f).digest("hex"),y=g(r,`memory-review-${d(JSON.stringify(t))}.json`);await R(y,r);const x=l(y);if(x.length>128*1024)return n();const c=JSON.parse(x.toString("utf8"));if(Object.keys(c).sort().join("|")!==["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"].sort().join("|")||c.schemaVersion!==1||c.kind!=="private-project-memory-root-review"||c.storyId!==e.storyId||c.graphRevision!==t.graphRevision||c.sourceHeadSha!==e.sourceHeadSha||c.snapshotSha!==t.memorySnapshotSha||c.notesSha256!==t.proposalSha256||c.reviewedAt!==t.recordedAt||c.independentStoryQaAccepted!==!1||c.terminalAccepted!==!1||!u(c.rootMemoryEffect,t)||!c.checks||Object.keys(c.checks).sort().join("|")!==[...b].sort().join("|")||b.some(f=>c.checks[f]!==!0)||c.proposalSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/stories/${e.storyId}/validation-evidence.md`])))||c.sourceStateSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/state.json`]))))return n();const E=g(r,`qa-review-${t.rootQaReceiptId}.json`);await R(E,r);const v=l(E);if(v.length>16384||d(v)!==t.rootQaReceiptId)return n();const p=JSON.parse(v.toString("utf8"));if(p.kind!=="private-qa-root-review"||p.storyId!==e.storyId||p.sourceHeadSha!==e.sourceHeadSha||p.precommitQaAccepted!==!0||p.independentStoryQaAccepted!==!1||p.terminalAccepted!==!1||(m(e.snapshotRoot,["merge-base","--is-ancestor",p.snapshotSha,t.sourceSnapshotSha]),o="git-evidence",C(e.snapshotRoot,t,{storyId:e.storyId,executionBranch:e.executionBranch,sourceHeadSha:e.sourceHeadSha,graphRevision:t.graphRevision,setupSessionId:e.setupSessionId,childClaimRevision:S("sha256").update([...e.childPaths].sort().join("\0")).digest("hex")}),o="range",m(e.snapshotRoot,["merge-base","--is-ancestor",t.memorySnapshotSha,e.snapshotSha]),m(e.snapshotRoot,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.sourceHeadSha,e.snapshotSha]).split("\0").filter(Boolean).some(f=>!e.childPaths.includes(f)&&!t.files.some(O=>O.path===f))))return n();o="files";for(const f of t.files)if(e.childPaths.includes(f.path)||!u(I(e.snapshotRoot,e.sourceHeadSha,f.path),f.before)||!u(I(e.snapshotRoot,e.snapshotSha,f.path),f.after))return n();const M=Object.freeze(Object.create(null));return j.set(M,Object.freeze({effect:structuredClone(t),root:h,snapshotRoot:e.snapshotRoot})),M}catch{throw new Error(`private-root-memory-scope-${o}-unverified`)}}function N(e){const o=j.get(e);return o?structuredClone(o.effect):n()}function Q(e,o,h,r){return L(e,o,h,r)==="matched"}function L(e,o,h,r){const a=j.get(e);if(!a||a.root!==w(o)||h!==void 0&&h!==a.snapshotRoot)return"scope-binding";let i="snapshot-ancestry";try{if(r&&(m(a.snapshotRoot,["merge-base","--is-ancestor",a.effect.memorySnapshotSha,r]),i="snapshot-content",a.effect.files.some(t=>!u(I(a.snapshotRoot,r,t.path),t.after)))||(i="source-content",!a.effect.files.every(t=>u(G(o,t.path),t.after))))return i;i="source-projection";const s=F(q(["--project-root",o,"--verify"]));return s.canonicalSha256===a.effect.canonicalSha256&&s.projectionSha256===a.effect.projectionSha256&&s.fileCount===a.effect.projectionFileCount?"matched":i}catch{return i+"-unsafe"}}async function re(e){try{const o=w(e.projectRoot),h=await H(o,{required:!0}),r=h.stories[e.storyId]?.checkpoint;if(r?.rootMemoryEffect!==void 0)return r.storyId!==e.storyId||r.branch!==e.executionBranch||typeof r.baseSha!="string"||typeof r.headSha!="string"?n():structuredClone($(o,r.rootMemoryEffect,{storyId:e.storyId,executionBranch:e.executionBranch,baseSha:r.baseSha,headRef:r.headSha,childPaths:e.childPaths}));if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return;const a=await k(await P(o),"private-execution"),i=g(a,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);if(!B(i))return;await R(i,a);const s=l(i);if(s.length>128*1024)return n();const t=JSON.parse(s.toString("utf8"));if(t.rootMemoryEffect===void 0)return;const d=h.stories[e.storyId];if(d?.status!=="memory-updated"||typeof d.last_step!="string"||S("sha256").update(d.last_step).digest("hex")!==T||!Array.isArray(d.steps_completed)||d.steps_completed.at(-1)!==d.last_step)return n();const y=await J({projectRoot:o,storyId:e.storyId,snapshotRoot:t.workspace?.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace?.baseSha,executionBranch:e.executionBranch,graphRevision:e.graphRevision,setupSessionId:t.setupSessionId,childPaths:e.childPaths});return!y||!Q(y,o,t.workspace?.workspacePath,t.snapshotSha)?n():N(y)}catch{return n()}}export{N as privateRootMemoryEffect,L as privateRootMemorySourceMatchReason,Q as privateRootMemorySourceMatches,J as readPrivateRootMemoryScope,re as readRootMemoryEffectForCheckpoint};
@@ -1,4 +1,4 @@
1
- import { type RootMemoryFileEffect, type RootMemoryFileState } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
+ import { type RootMemoryFileEffect, type RootMemoryFileState } from './shared-root-memory-types.js';
2
2
  import { type ProjectMemoryVerification } from '../commands/refresh-memory.js';
3
3
  export interface RootMemoryWriterAuthority {
4
4
  readonly __rootMemoryWriter?: never;
@@ -1 +1 @@
1
- import{execFileSync as z}from"node:child_process";import{createHash as N}from"node:crypto";import{lstatSync as y,readFileSync as E,readlinkSync as D,realpathSync as v}from"node:fs";import{join as O,resolve as l}from"node:path";import{rootProjectMemoryPaths as j}from"../../../shared/dist/yoloop/root-memory-effect.js";import{parseRefreshMemoryArgs as x,refreshProjectMemoryTargets as M,verifyProjectMemoryTargets as J}from"../commands/refresh-memory.js";import{assertProjectMemoryPaths as w}from"../memory/project-memory-path-scope.js";import{classifyProjectMemoryUpdate as P}from"../memory/project-memory-writer.js";const d=r=>N("sha256").update(r).digest("hex"),h=new WeakMap,n=()=>{throw new Error("private-root-memory-writer-unverified")};function c(r,...e){return z("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:Object.fromEntries(Object.entries(process.env).filter(([i])=>!i.startsWith("GIT_"))),timeout:3e4,maxBuffer:2*1024*1024})}function m(r,e){if(!j().includes(e))return n();w(r,[e]);const i=O(r,e);let o;try{o=y(i)}catch(a){return a.code==="ENOENT"?{kind:"absent",sha256:null}:n()}if(o.uid!==process.getuid?.()||o.nlink!==1||(o.mode&18)!==0&&!o.isSymbolicLink())return n();if(o.isSymbolicLink()){const a=D(i);return l(r,e,"..",a)!==O(l(r),"NEOCORTEX.md")?n():{kind:"symlink",sha256:d(a),linkTarget:a}}return!o.isFile()||o.size>512*1024?n():{kind:"regular",sha256:d(E(i))}}function G(r){const e=l(r.snapshotRoot),i=l(r.backupDirectory),o=y(e),a=y(i);if(!o.isDirectory()||o.uid!==process.getuid?.()||(o.mode&63)!==0||v(e)!==e||!a.isDirectory()||a.isSymbolicLink()||a.uid!==process.getuid?.()||(a.mode&63)!==0||v(i)!==i||i===e||i.startsWith(e+"/")||!/^[a-f0-9]{40,64}$/.test(r.expectedSnapshotSha)||!Array.isArray(r.notes)||r.notes.length<1||r.notes.length>8||r.notes.some(t=>typeof t!="string"||Buffer.byteLength(t)<1||Buffer.byteLength(t)>512)||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha||c(e,"status","--porcelain=v1","--untracked-files=all").length!==0)return n();for(const t of r.notes)P(t);const f=j(),g=new Map(f.map(t=>[t,m(e,t)])),S=x(["--project-root",e,...r.notes.flatMap(t=>["--note",t])]);if(M({...S,dryRun:!0}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();for(const[t,s]of g)if(JSON.stringify(m(e,t))!==JSON.stringify(s))return n();if(M({...S,backupDirectory:i}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();const R=J(x(["--project-root",e,"--verify"])),u=c(e,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(t=>t.slice(3));if(u.some(t=>!f.includes(t))||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha)return n();const p=f.flatMap(t=>{const s=g.get(t),k=m(e,t);return JSON.stringify(s)===JSON.stringify(k)?[]:[Object.freeze({path:t,before:Object.freeze(s),after:Object.freeze(k)})]});if(p.some(t=>!u.includes(t.path))||u.some(t=>!p.some(s=>s.path===t)))return n();const b=Object.freeze(Object.create(null));return h.set(b,Object.freeze({snapshotRoot:e,sourceSnapshotSha:r.expectedSnapshotSha,notesSha256:d(JSON.stringify(r.notes)),files:Object.freeze(p),verification:Object.freeze(R)})),b}function U(r){return h.get(r)}function X(r){const e=h.get(r);if(!e||c(e.snapshotRoot,"rev-parse","HEAD").trim()!==e.sourceSnapshotSha)return n();const i=c(e.snapshotRoot,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(o=>o.slice(3)).sort();return JSON.stringify(i)!==JSON.stringify(e.files.map(o=>o.path).sort())||e.files.some(o=>JSON.stringify(m(e.snapshotRoot,o.path))!==JSON.stringify(o.after))?n():e}export{G as executeRootMemoryWriter,U as projectRootMemoryWriterExecution,m as rootMemoryFileState,X as verifyRootMemoryWriterExecution};
1
+ import{execFileSync as z}from"node:child_process";import{createHash as N}from"node:crypto";import{lstatSync as y,readFileSync as E,readlinkSync as D,realpathSync as v}from"node:fs";import{join as O,resolve as l}from"node:path";import{rootProjectMemoryPaths as j}from"./shared-root-memory-types.js";import{parseRefreshMemoryArgs as x,refreshProjectMemoryTargets as M,verifyProjectMemoryTargets as J}from"../commands/refresh-memory.js";import{assertProjectMemoryPaths as w}from"../memory/project-memory-path-scope.js";import{classifyProjectMemoryUpdate as P}from"../memory/project-memory-writer.js";const d=r=>N("sha256").update(r).digest("hex"),h=new WeakMap,n=()=>{throw new Error("private-root-memory-writer-unverified")};function c(r,...e){return z("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:Object.fromEntries(Object.entries(process.env).filter(([i])=>!i.startsWith("GIT_"))),timeout:3e4,maxBuffer:2*1024*1024})}function m(r,e){if(!j().includes(e))return n();w(r,[e]);const i=O(r,e);let o;try{o=y(i)}catch(a){return a.code==="ENOENT"?{kind:"absent",sha256:null}:n()}if(o.uid!==process.getuid?.()||o.nlink!==1||(o.mode&18)!==0&&!o.isSymbolicLink())return n();if(o.isSymbolicLink()){const a=D(i);return l(r,e,"..",a)!==O(l(r),"NEOCORTEX.md")?n():{kind:"symlink",sha256:d(a),linkTarget:a}}return!o.isFile()||o.size>512*1024?n():{kind:"regular",sha256:d(E(i))}}function G(r){const e=l(r.snapshotRoot),i=l(r.backupDirectory),o=y(e),a=y(i);if(!o.isDirectory()||o.uid!==process.getuid?.()||(o.mode&63)!==0||v(e)!==e||!a.isDirectory()||a.isSymbolicLink()||a.uid!==process.getuid?.()||(a.mode&63)!==0||v(i)!==i||i===e||i.startsWith(e+"/")||!/^[a-f0-9]{40,64}$/.test(r.expectedSnapshotSha)||!Array.isArray(r.notes)||r.notes.length<1||r.notes.length>8||r.notes.some(t=>typeof t!="string"||Buffer.byteLength(t)<1||Buffer.byteLength(t)>512)||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha||c(e,"status","--porcelain=v1","--untracked-files=all").length!==0)return n();for(const t of r.notes)P(t);const f=j(),g=new Map(f.map(t=>[t,m(e,t)])),S=x(["--project-root",e,...r.notes.flatMap(t=>["--note",t])]);if(M({...S,dryRun:!0}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();for(const[t,s]of g)if(JSON.stringify(m(e,t))!==JSON.stringify(s))return n();if(M({...S,backupDirectory:i}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();const R=J(x(["--project-root",e,"--verify"])),u=c(e,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(t=>t.slice(3));if(u.some(t=>!f.includes(t))||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha)return n();const p=f.flatMap(t=>{const s=g.get(t),k=m(e,t);return JSON.stringify(s)===JSON.stringify(k)?[]:[Object.freeze({path:t,before:Object.freeze(s),after:Object.freeze(k)})]});if(p.some(t=>!u.includes(t.path))||u.some(t=>!p.some(s=>s.path===t)))return n();const b=Object.freeze(Object.create(null));return h.set(b,Object.freeze({snapshotRoot:e,sourceSnapshotSha:r.expectedSnapshotSha,notesSha256:d(JSON.stringify(r.notes)),files:Object.freeze(p),verification:Object.freeze(R)})),b}function U(r){return h.get(r)}function X(r){const e=h.get(r);if(!e||c(e.snapshotRoot,"rev-parse","HEAD").trim()!==e.sourceSnapshotSha)return n();const i=c(e.snapshotRoot,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(o=>o.slice(3)).sort();return JSON.stringify(i)!==JSON.stringify(e.files.map(o=>o.path).sort())||e.files.some(o=>JSON.stringify(m(e.snapshotRoot,o.path))!==JSON.stringify(o.after))?n():e}export{G as executeRootMemoryWriter,U as projectRootMemoryWriterExecution,m as rootMemoryFileState,X as verifyRootMemoryWriterExecution};
@@ -0,0 +1,34 @@
1
+ export interface PrivateYoloSkippedPredecessor {
2
+ readonly stepId: 'step-a8ce5c64';
3
+ readonly featureFlagId: 'property-testing';
4
+ readonly enabled: boolean;
5
+ readonly tier: 'free' | 'pro' | 'enterprise';
6
+ readonly publicSafe: true;
7
+ }
8
+ export interface PrivateQaTierSkippedPredecessor {
9
+ readonly stepId: 'step-b2fe7cb5';
10
+ readonly featureGate: 'validate-tests';
11
+ readonly reason: 'subscription-tier';
12
+ readonly tier: 'free';
13
+ readonly publicSafe: true;
14
+ }
15
+ export type PrivateQaSkippedPredecessor = PrivateYoloSkippedPredecessor | PrivateQaTierSkippedPredecessor;
16
+ export interface PrivateQaStructuralAdmission {
17
+ readonly schemaVersion: 1;
18
+ readonly kind: 'server-private-qa-structural-admission';
19
+ readonly stepId: 'step-8721319d';
20
+ readonly generationId: string;
21
+ readonly graphRevision: string;
22
+ readonly topologyGenerationId: string;
23
+ readonly tier: 'free' | 'pro' | 'enterprise';
24
+ readonly checks: {
25
+ readonly classifiedAssetDelivery: true;
26
+ readonly licensedCommandAdmission: true;
27
+ readonly registeredStatusMapping: true;
28
+ readonly prerequisiteStateAdmitted: true;
29
+ };
30
+ readonly publicSafe: true;
31
+ }
32
+ export declare function isPrivateYoloSkippedPredecessors(value: unknown): value is readonly PrivateYoloSkippedPredecessor[];
33
+ export declare function isPrivateQaSkippedPredecessors(value: unknown): value is readonly PrivateQaSkippedPredecessor[];
34
+ export declare function isPrivateQaStructuralAdmission(value: unknown): value is PrivateQaStructuralAdmission;
@@ -0,0 +1 @@
1
+ const i="step-a8ce5c64",o="step-b2fe7cb5",n="step-8721319d";function a(t){return Array.isArray(t)&&t.length<=1&&t.every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e;return Object.keys(r).sort().join("|")===["stepId","featureFlagId","enabled","tier","publicSafe"].sort().join("|")&&r.stepId===i&&r.featureFlagId==="property-testing"&&typeof r.enabled=="boolean"&&["free","pro","enterprise"].includes(String(r.tier))&&(r.enabled===!1||r.tier==="free")&&r.publicSafe===!0})}function p(t){if(!Array.isArray(t)||t.length>2)return!1;const e=[];for(const r of t){if(a([r])){e.push(r.stepId);continue}if(!r||typeof r!="object"||Array.isArray(r))return!1;const s=r;if(Object.keys(s).sort().join("|")!==["stepId","featureGate","reason","tier","publicSafe"].sort().join("|")||s.stepId!==o||s.featureGate!=="validate-tests"||s.reason!=="subscription-tier"||s.tier!=="free"||s.publicSafe!==!0)return!1;e.push(s.stepId)}return new Set(e).size===e.length&&(t.length<2||e[0]===i&&e[1]===o&&t[0].tier==="free")}function c(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const e=t,r=e.checks;return Object.keys(e).sort().join("|")===["schemaVersion","kind","stepId","generationId","graphRevision","topologyGenerationId","tier","checks","publicSafe"].sort().join("|")&&e.schemaVersion===1&&e.kind==="server-private-qa-structural-admission"&&e.stepId===n&&typeof e.generationId=="string"&&/^sha256:[a-f0-9]{64}$/.test(e.generationId)&&typeof e.graphRevision=="string"&&/^[a-f0-9]{64}$/.test(e.graphRevision)&&typeof e.topologyGenerationId=="string"&&/^sha256:[a-f0-9]{64}$/.test(e.topologyGenerationId)&&["free","pro","enterprise"].includes(String(e.tier))&&e.publicSafe===!0&&!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).sort().join("|")===["classifiedAssetDelivery","licensedCommandAdmission","registeredStatusMapping","prerequisiteStateAdmitted"].sort().join("|")&&Object.values(r).every(s=>s===!0)}export{p as isPrivateQaSkippedPredecessors,c as isPrivateQaStructuralAdmission,a as isPrivateYoloSkippedPredecessors};
@@ -0,0 +1,17 @@
1
+ /** Standalone-client shadow of bounded project validation declarations. */
2
+ export declare const PROJECT_VALIDATION_KINDS: readonly ["unit", "integration", "contract", "bdd-example", "e2e"];
3
+ export type ProjectValidationKind = typeof PROJECT_VALIDATION_KINDS[number];
4
+ export interface ProjectValidationSource {
5
+ readonly path: string;
6
+ readonly content: string;
7
+ }
8
+ export interface ProjectValidationDeclaration {
9
+ readonly kind: ProjectValidationKind;
10
+ readonly command: string;
11
+ readonly sourcePaths: readonly string[];
12
+ }
13
+ export declare function readProjectValidationCommands(storyId: string, sources: readonly ProjectValidationSource[]): {
14
+ declared: boolean;
15
+ invalid: boolean;
16
+ commands: readonly ProjectValidationDeclaration[];
17
+ };
@@ -0,0 +1 @@
1
+ const P=["unit","integration","contract","bdd-example","e2e"];function x(p,a){const o=new Map;let c=!1,t=!1;const h=new Set(["story","spec","tasks"].map(e=>`docs/stories/${p}.${e}.md`));if(a.length>3||new Set(a.map(e=>e.path)).size!==a.length)return{declared:!0,invalid:!0,commands:[]};for(const e of a){if(!h.has(e.path)||Buffer.byteLength(e.content)>131072){t=!0,c=!0;continue}let n=!1,d=!1,m=0,r=0;for(const g of e.content.split(/\r?\n/)){const i=g.trim();if(/^(?:```|~~~)/.test(i)){d=!d;continue}if(d)continue;if(/^##\s+/.test(i)){n&&r===0&&(t=!0),n=i==="## Validation Commands",n&&(c=!0,m++,r=0,m>1&&(t=!0));continue}if(!n||!i)continue;const l=/^- (unit|integration|contract|bdd-example|e2e): `([^`]{1,220})`$/.exec(i);if(!l){t=!0;continue}const f=l[1],s=l[2];if(!/^[A-Za-z0-9_./-]+(?: [A-Za-z0-9_./:@%+=,-]+)*$/.test(s)||/(?:token|password|license_key|secret|credential)=|(?:https?|ssh):\/\/|@[^ /]+\.[A-Za-z]/i.test(s)||s.split(" ").some(w=>w.split("/").includes(".."))){t=!0;continue}r++;const u=o.get(f);if(u&&u.command!==s||u?.sourcePaths.includes(e.path)){t=!0;continue}o.set(f,{kind:f,command:s,sourcePaths:[...u?.sourcePaths??[],e.path]})}n&&r===0&&(t=!0)}return c&&!o.has("unit")&&(t=!0),{declared:c,invalid:t,commands:[...o.values()]}}export{P as PROJECT_VALIDATION_KINDS,x as readProjectValidationCommands};
@@ -0,0 +1,37 @@
1
+ /** Standalone-client shadow of the public root-memory effect contract. */
2
+ import { getProjectMemoryTarget, listProjectMemoryTargets } from '../memory/shared-project-memory-types.js';
3
+ export { getProjectMemoryTarget, listProjectMemoryTargets };
4
+ export interface RootMemoryFileState {
5
+ readonly kind: 'absent' | 'regular' | 'symlink';
6
+ readonly sha256: string | null;
7
+ readonly linkTarget?: string;
8
+ }
9
+ export interface RootMemoryFileEffect {
10
+ readonly path: string;
11
+ readonly before: RootMemoryFileState;
12
+ readonly after: RootMemoryFileState;
13
+ }
14
+ export interface RootProjectMemoryEffect {
15
+ readonly schemaVersion: 'RootProjectMemoryEffect/1';
16
+ readonly producer: 'root-project-memory';
17
+ readonly storyId: string;
18
+ readonly epicId: string;
19
+ readonly executionBranch: string;
20
+ readonly sourceHeadSha: string;
21
+ readonly sourceSnapshotSha: string;
22
+ readonly memorySnapshotSha: string;
23
+ readonly graphRevision: string;
24
+ readonly childClaimRevision: string;
25
+ readonly setupSessionId: string;
26
+ readonly rootQaReceiptId: string;
27
+ readonly proposalSha256: string;
28
+ readonly canonicalSha256: string;
29
+ readonly projectionSha256: string;
30
+ readonly projectionFileCount: number;
31
+ readonly files: readonly RootMemoryFileEffect[];
32
+ readonly recordedAt: string;
33
+ readonly publicSafe: true;
34
+ }
35
+ export declare function canonicalRootMemoryEffectJson(effect: RootProjectMemoryEffect): string;
36
+ export declare function rootProjectMemoryPaths(): readonly string[];
37
+ export declare function isRootProjectMemoryEffect(value: unknown): value is RootProjectMemoryEffect;
@@ -0,0 +1 @@
1
+ import{getProjectMemoryTarget as u,listProjectMemoryTargets as l}from"../memory/shared-project-memory-types.js";function S(n){const s=e=>Array.isArray(e)?e.map(s):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(i=>[i,s(e[i])])):e;return JSON.stringify(s(n))}function y(){return[...new Set(["NEOCORTEX.md",...l().flatMap(n=>[n.primaryFile,...n.secondaryFiles.filter(s=>s.scope==="project").map(s=>s.path)])])].sort()}function g(n){const s=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0,e=s(n),i=["schemaVersion","producer","storyId","epicId","executionBranch","sourceHeadSha","sourceSnapshotSha","memorySnapshotSha","graphRevision","childClaimRevision","setupSessionId","rootQaReceiptId","proposalSha256","canonicalSha256","projectionSha256","projectionFileCount","files","recordedAt","publicSafe"];if(!e||Object.keys(e).sort().join("|")!==i.sort().join("|")||e.schemaVersion!=="RootProjectMemoryEffect/1"||e.producer!=="root-project-memory"||e.publicSafe!==!0||typeof e.storyId!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId)||e.epicId!==e.storyId.split(".")[0]||e.executionBranch!==`epic/${e.epicId}`||["sourceHeadSha","sourceSnapshotSha","memorySnapshotSha"].some(t=>typeof e[t]!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(e[t]))||["graphRevision","childClaimRevision","rootQaReceiptId","proposalSha256","canonicalSha256","projectionSha256"].some(t=>typeof e[t]!="string"||!/^[a-f0-9]{64}$/.test(e[t]))||typeof e.setupSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(e.setupSessionId)||typeof e.recordedAt!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e.recordedAt)||!Number.isFinite(Date.parse(e.recordedAt))||new Date(e.recordedAt).toISOString()!==e.recordedAt||!Number.isSafeInteger(e.projectionFileCount)||e.projectionFileCount<1||e.projectionFileCount>128||!Array.isArray(e.files)||e.files.length>128)return!1;const d=new Set(y()),a=new Set,c=(t,o,p)=>{const r=s(t);if(!r||!["absent","regular","symlink"].includes(String(r.kind))||Object.keys(r).sort().join("|")!==["kind","sha256",...r.kind==="symlink"?["linkTarget"]:[]].sort().join("|"))return!1;if(r.kind==="absent")return!p&&r.sha256===null;if(typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256)||o==="NEOCORTEX.md"&&r.kind!=="regular")return!1;const f="../".repeat(o.split("/").length-1)+"NEOCORTEX.md";return r.kind!=="symlink"||typeof r.linkTarget=="string"&&r.linkTarget.length<=1024&&(p?r.linkTarget===f:r.linkTarget.split("/").filter(h=>h!==".").join("/")===f)};return e.files.every(t=>{const o=s(t);return!o||Object.keys(o).sort().join("|")!=="after|before|path"||typeof o.path!="string"||!d.has(o.path)||a.has(o.path)||!c(o.before,o.path,!1)||!c(o.after,o.path,!0)?!1:(a.add(o.path),!0)})}export{S as canonicalRootMemoryEffectJson,u as getProjectMemoryTarget,g as isRootProjectMemoryEffect,l as listProjectMemoryTargets,y as rootProjectMemoryPaths};
@@ -1 +1 @@
1
- import{parse as H}from"@babel/parser";import{lstatSync as q,readFileSync as G}from"node:fs";import{join as U,posix as V}from"node:path";const Q=1024*1024,ee=1e5,P=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function p(){throw new Error("private-execution-ux-source-unverified")}function o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function k(e,r){const t=q(U(e,r));(!t.isFile()||t.isSymbolicLink()||t.size<1||t.size>Q)&&p();const s=new TextDecoder("utf-8",{fatal:!0}).decode(G(U(e,r)));return(!s.trim()||s.includes("\0"))&&p(),s}function w(e,r){const t=H(k(e,r),{sourceType:"module",plugins:["typescript","jsx"],errorRecovery:!1});let s=0;const i=[t];for(;i.length>0;){const f=i.pop();if(o(f)){++s>ee&&p();for(const[n,l]of Object.entries(f))n==="loc"||n==="tokens"||n==="comments"||n==="errors"||(Array.isArray(l)?i.push(...l):o(l)&&i.push(l))}}return t}function S(e){const r=e.program;return(!o(r)||!Array.isArray(r.body))&&p(),r.body.filter(o)}function m(e,r){if(!o(e)||e.type!=="ObjectExpression"||!Array.isArray(e.properties))return;const t=e.properties.filter(s=>o(s)&&s.type==="ObjectProperty"&&s.computed!==!0&&o(s.key)&&(s.key.name===r||s.key.value===r));return t.length===1&&o(t[0])?t[0].value:void 0}function E(e){return o(e)&&e.type==="StringLiteral"&&typeof e.value=="string"?e.value:void 0}function u(e){return o(e)&&e.type==="Identifier"&&typeof e.name=="string"?e.name:void 0}function A(e){return e.type==="VariableDeclaration"&&Array.isArray(e.declarations)?e.declarations.filter(o):[]}function b(e){let r=e;for(let t=0;t<4&&o(r)&&["TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","ParenthesizedExpression"].includes(String(r.type));t++)r=r.expression;return r}function te(e,r){const t=e.flatMap(A).filter(s=>u(s.id)===r);return t.length===1?b(t[0].init):void 0}function K(e,r){for(const t of e){if(t.type!=="ExportNamedDeclaration"||!o(t.declaration))continue;const s=t.declaration;if(s.type==="FunctionDeclaration"&&o(s.id)&&s.id.name===r)return s;const i=A(s).find(f=>o(f.id)&&f.id.name===r);if(i)return b(i.init)}}function g(e,r){const t=[],s=[e];for(;s.length>0;){const i=s.pop();if(o(i)){i.type===r&&t.push(i);for(const[f,n]of Object.entries(i))f==="loc"||f==="comments"||(Array.isArray(n)?s.push(...n):o(n)&&s.push(n))}}return t}function z(e){return e.screenId.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function R(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(r=>`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()}`).join("")}function Z(e,r,t){const s=[];for(const i of e){if(i.type!=="ImportDeclaration"||i.importKind==="type"||!o(i.source)||typeof i.source.value!="string"||!i.source.value.startsWith("./")&&!i.source.value.startsWith("../"))continue;const f=V.normalize(V.join(V.dirname(r),i.source.value));if(!(f!==t.screenViewPath&&f!==t.screenViewPath.replace(/\.tsx$/,"")))for(const n of Array.isArray(i.specifiers)?i.specifiers:[])o(n)&&n.type==="ImportSpecifier"&&o(n.imported)&&n.imported.name===t.screenViewExport&&n.importKind!=="type"&&o(n.local)&&typeof n.local.name=="string"&&s.push(n.local.name)}return s.length!==1&&p(),s[0]}function re(e,r){return g(e,"JSXOpeningElement").some(t=>o(t.name)&&t.name.name===r)}function j(e,r,t){const s=e.filter(i=>i.type==="ImportDeclaration"&&o(i.source)&&i.source.value===r).flatMap(i=>Array.isArray(i.specifiers)?i.specifiers:[]).filter(i=>o(i)&&i.type==="ImportSpecifier"&&o(i.imported)&&i.imported.name===t&&o(i.local)&&typeof i.local.name=="string").map(i=>i.local);return s.length===1?s[0].name:void 0}function Y(e,r,t){return o(e)&&e.type==="CallExpression"&&o(e.callee)&&e.callee.type==="MemberExpression"&&e.callee.computed!==!0&&u(e.callee.object)===r&&u(e.callee.property)===t}function ne(e,r){const t=j(r,"storybook/test","within"),s=j(r,"storybook/test","userEvent"),i=j(r,"storybook/test","expect");if(!t||!s||!i||!Array.isArray(e.params)||!o(e.params[0])||e.params[0].type!=="ObjectPattern"||!Array.isArray(e.params[0].properties)||!e.params[0].properties.some(a=>o(a)&&o(a.key)&&a.key.name==="canvasElement"&&o(a.value)&&a.value.name==="canvasElement"))return!1;const f=g(e.body,"VariableDeclarator"),n=f.filter(a=>o(a.init)&&a.init.type==="CallExpression"&&u(a.init.callee)===t&&Array.isArray(a.init.arguments)&&a.init.arguments.length===1&&u(a.init.arguments[0])==="canvasElement").map(a=>u(a.id)).filter(a=>!!a),l=f.filter(a=>n.some(O=>Y(a.init,O,"getByRole")&&Array.isArray(a.init.arguments)&&E(a.init.arguments[0])==="button"&&typeof E(m(a.init.arguments[1],"name"))=="string"&&!!E(m(a.init.arguments[1],"name"))?.trim())).map(a=>u(a.id)).filter(a=>!!a);if(l.length===0)return!1;const d=g(e.body,"AwaitExpression").map(a=>a.argument),x=d.some(a=>Y(a,s,"tab")&&Array.isArray(a.arguments)&&a.arguments.length===0),h=d.some(a=>o(a)&&a.type==="CallExpression"&&o(a.callee)&&a.callee.type==="MemberExpression"&&u(a.callee.property)==="toHaveFocus"&&o(a.callee.object)&&a.callee.object.type==="CallExpression"&&u(a.callee.object.callee)===i&&Array.isArray(a.callee.object.arguments)&&l.includes(u(a.callee.object.arguments[0])??""));return x&&h}function se(e,r){const t=b(e);if(o(t)&&["ArrowFunctionExpression","FunctionExpression"].includes(String(t.type)))return t;const s=u(t);if(!s||!o(t))return;const i=r.flatMap(d=>A(d).filter(x=>u(x.id)===s).map(x=>({kind:d.kind,declaration:x})));if(i.length!==1||i[0].kind!=="const")return;const f=i[0].declaration;if(typeof f.start!="number"||typeof t.start!="number"||f.start>=t.start)return;const n={body:r};if(g(n,"AssignmentExpression").some(d=>u(b(d.left))===s)||g(n,"UpdateExpression").some(d=>u(b(d.argument))===s))return;const l=b(f.init);return o(l)&&["ArrowFunctionExpression","FunctionExpression"].includes(String(l.type))?l:void 0}function oe(e,r,t){const s=`src/screens/${z(r)}/${z(r)}`,i=w(e,r.screenViewPath),f=K(S(i),r.screenViewExport);(!f||g(f,"JSXElement").length+g(f,"JSXFragment").length===0)&&p();const n=w(e,r.appRoutePath),l=Z(S(n),r.appRoutePath,r);re(n,l)||p();const d=`${s}.stories.tsx`,x=w(e,d),h=S(x),a=t==="storybook-react-vite"?"@storybook/react-vite":"@storybook/nextjs-vite";(!j(h,a,"Meta")||!j(h,a,"StoryObj"))&&p();const O=Z(h,d,r),D=h.filter(c=>c.type==="ExportDefaultDeclaration");D.length!==1&&p();const v=b(D[0].declaration),C=u(v)?te(h,u(v)):v;(u(m(C,"component"))!==O||E(m(C,"title"))!==`Screens/${r.screenId}`)&&p();const M=new Set;for(const c of r.states)for(const y of r.viewports){const J=`${R(c)}${R(y)}`;M.add(J);const I=K(h,J);if((!o(I)||I.type!=="ObjectExpression"||E(m(m(I,"args"),"state"))!==c||E(m(m(m(I,"parameters"),"viewport"),"defaultViewport"))!==y)&&p(),r.critical&&(c==="success"||c==="recovery")){const L=se(m(I,"play"),h);(!L||!ne(L,h))&&p()}}const F=h.filter(c=>c.type==="ExportNamedDeclaration");F.some(c=>!o(c.declaration)||A(c.declaration).length!==1||Array.isArray(c.specifiers)&&c.specifiers.length>0)&&p();const T=F.flatMap(c=>A(c.declaration)).map(c=>u(c.id)).filter(c=>!!c);(T.length!==M.size||T.some(c=>!M.has(c)))&&p();const W=w(e,`${s}.fixtures.ts`);S(W).filter(c=>c.type==="ExportNamedDeclaration").flatMap(c=>o(c.declaration)?A(c.declaration):[]).some(c=>{const y=m(c.init,"synthetic");return o(y)&&y.type==="BooleanLiteral"&&y.value===!0&&m(c.init,"data")!==void 0})||p();const X=w(e,`${s}.handlers.ts`),_=S(X);(!_.some(c=>c.type==="ImportDeclaration"&&o(c.source)&&c.source.value==="msw"&&Array.isArray(c.specifiers)&&c.specifiers.some(y=>o(y)&&o(y.imported)&&y.imported.name==="http"))||!_.some(c=>c.type==="ExportNamedDeclaration"&&o(c.declaration)&&A(c.declaration).some(y=>o(y.init)&&y.init.type==="ArrayExpression"&&Array.isArray(y.init.elements)&&y.init.elements.length>0))||!g(X,"CallExpression").some(c=>o(c.callee)&&c.callee.type==="MemberExpression"&&o(c.callee.object)&&c.callee.object.name==="http"))&&p();const N=k(e,`${s}.mdx`),B=new RegExp(`import\\s+\\*\\s+as\\s+([A-Za-z_$][\\w$]*)\\s+from\\s+['"]\\./${z(r)}\\.stories(?:\\.tsx)?['"];?\\r?\\n(?:[ \\t]*\\r?\\n)+`).exec(N);(!/import\s+\{\s*Meta\s*\}\s+from\s+['"]@storybook\/addon-docs\/blocks['"]/.test(N)||!B||!N.includes(`<Meta of={${B[1]}} />`))&&p()}function $(e){return Array.isArray(e)?`[${e.map($).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([r],[t])=>r.localeCompare(t)).map(([r,t])=>`${JSON.stringify(r)}:${$(t)}`).join(",")}}`:JSON.stringify(e)??"null"}function ie(e){const r=$(e);let t=2166136261;for(let s=0;s<r.length;s++)t^=r.charCodeAt(s),t=Math.imul(t,16777619);return`uxm-${(t>>>0).toString(16).padStart(8,"0")}`}function ae(e,r){let t;try{t=JSON.parse(k(e,"docs/architecture/ux-coverage-manifest.json"))}catch{p()}(!o(t)||t.schemaVersion!==1||t.manifestId!=="P201-UX-MANIFEST-01"||!Array.isArray(t.entries)||typeof t.fingerprint!="string"||Object.keys(t).sort().join(",")!=="entries,fingerprint,manifestId,schemaVersion")&&p(),t.fingerprint!==ie(t.entries)&&p();const s=new Map;for(const n of r.screens)for(const l of n.states)for(const d of n.viewports)s.set(`Screens/${n.screenId}/${l}/${d}`,{screen:n,state:l,viewport:d});t.entries.length!==s.size&&p();const i=new Set;let f="";for(const n of t.entries){(!o(n)||typeof n.storyId!="string"||i.has(n.storyId))&&p(),f&&f.localeCompare(n.storyId)>=0&&p(),f=n.storyId,Object.keys(n).sort().join(",")!=="approvalEvidenceIds,fixtureId,handlerIds,journeyIds,screenId,screenViewPath,state,storyId,viewport"&&p(),i.add(n.storyId);const l=s.get(n.storyId);(!l||n.screenId!==l.screen.screenId||n.state!==l.state||n.viewport!==l.viewport||n.screenViewPath!==l.screen.screenViewPath||!Array.isArray(n.approvalEvidenceIds)||$([...n.approvalEvidenceIds].sort())!==$([...l.screen.approvalEvidenceIds].sort())||!Array.isArray(n.journeyIds)||n.journeyIds.length<1||n.journeyIds.some(d=>typeof d!="string"||!P.test(d))||new Set(n.journeyIds).size!==n.journeyIds.length||typeof n.fixtureId!="string"||!P.test(n.fixtureId)||!Array.isArray(n.handlerIds)||n.handlerIds.length<1||n.handlerIds.some(d=>typeof d!="string"||!P.test(d))||new Set(n.handlerIds).size!==n.handlerIds.length)&&p()}}function de(e,r){try{for(const[t,s]of[["docs/architecture/ux-design.md","P201-UX-STORYBOOK-01"],["docs/architecture/storybook-ux-contract.md","P201-UX-STORYBOOK-01"]])k(e,t).includes(s)||p();for(const t of r.screens)oe(e,t,r.adapterId);ae(e,r)}catch{p()}}export{de as validateUxCandidateSource};
1
+ import{parse as H}from"@babel/parser";import{lstatSync as q,readFileSync as G}from"node:fs";import{join as K,posix as V}from"node:path";const Q=1024*1024,ee=1e5,z=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function p(){throw new Error("private-execution-ux-source-unverified")}function o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j(e,t){const r=q(K(e,t));(!r.isFile()||r.isSymbolicLink()||r.size<1||r.size>Q)&&p();const s=new TextDecoder("utf-8",{fatal:!0}).decode(G(K(e,t)));return(!s.trim()||s.includes("\0"))&&p(),s}function I(e,t){const r=H(j(e,t),{sourceType:"module",plugins:["typescript","jsx"],errorRecovery:!1});let s=0;const i=[r];for(;i.length>0;){const l=i.pop();if(o(l)){++s>ee&&p();for(const[n,f]of Object.entries(l))n==="loc"||n==="tokens"||n==="comments"||n==="errors"||(Array.isArray(f)?i.push(...f):o(f)&&i.push(f))}}return r}function E(e){const t=e.program;return(!o(t)||!Array.isArray(t.body))&&p(),t.body.filter(o)}function m(e,t){if(!o(e)||e.type!=="ObjectExpression"||!Array.isArray(e.properties))return;const r=e.properties.filter(s=>o(s)&&s.type==="ObjectProperty"&&s.computed!==!0&&o(s.key)&&(s.key.name===t||s.key.value===t));return r.length===1&&o(r[0])?r[0].value:void 0}function g(e){return o(e)&&e.type==="StringLiteral"&&typeof e.value=="string"?e.value:void 0}function y(e){return o(e)&&e.type==="Identifier"&&typeof e.name=="string"?e.name:void 0}function x(e){return e.type==="VariableDeclaration"&&Array.isArray(e.declarations)?e.declarations.filter(o):[]}function D(e){let t=e;for(let r=0;r<4&&o(t)&&["TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","ParenthesizedExpression"].includes(String(t.type));r++)t=t.expression;return t}function te(e,t){const r=e.flatMap(x).filter(s=>y(s.id)===t);return r.length===1?D(r[0].init):void 0}function R(e,t){for(const r of e){if(r.type!=="ExportNamedDeclaration"||!o(r.declaration))continue;const s=r.declaration;if(s.type==="FunctionDeclaration"&&o(s.id)&&s.id.name===t)return s;const i=x(s).find(l=>o(l.id)&&l.id.name===t);if(i)return D(i.init)}}function A(e,t){const r=[],s=[e];for(;s.length>0;){const i=s.pop();if(o(i)){i.type===t&&r.push(i);for(const[l,n]of Object.entries(i))l==="loc"||l==="comments"||(Array.isArray(n)?s.push(...n):o(n)&&s.push(n))}}return r}function P(e){return e.screenId.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function U(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>`${t.charAt(0).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Z(e,t,r){const s=[];for(const i of e){if(i.type!=="ImportDeclaration"||i.importKind==="type"||!o(i.source)||typeof i.source.value!="string"||!i.source.value.startsWith("./")&&!i.source.value.startsWith("../"))continue;const l=V.normalize(V.join(V.dirname(t),i.source.value));if(!(l!==r.screenViewPath&&l!==r.screenViewPath.replace(/\.tsx$/,"")))for(const n of Array.isArray(i.specifiers)?i.specifiers:[])o(n)&&n.type==="ImportSpecifier"&&o(n.imported)&&n.imported.name===r.screenViewExport&&n.importKind!=="type"&&o(n.local)&&typeof n.local.name=="string"&&s.push(n.local.name)}return s.length!==1&&p(),s[0]}function re(e,t){return A(e,"JSXOpeningElement").some(r=>o(r.name)&&r.name.name===t)}function w(e,t,r){const s=e.filter(i=>i.type==="ImportDeclaration"&&o(i.source)&&i.source.value===t).flatMap(i=>Array.isArray(i.specifiers)?i.specifiers:[]).filter(i=>o(i)&&i.type==="ImportSpecifier"&&o(i.imported)&&i.imported.name===r&&o(i.local)&&typeof i.local.name=="string").map(i=>i.local);return s.length===1?s[0].name:void 0}function Y(e,t,r){return o(e)&&e.type==="CallExpression"&&o(e.callee)&&e.callee.type==="MemberExpression"&&e.callee.computed!==!0&&y(e.callee.object)===t&&y(e.callee.property)===r}function ne(e,t){const r=w(t,"storybook/test","within"),s=w(t,"storybook/test","userEvent"),i=w(t,"storybook/test","expect");if(!r||!s||!i||!Array.isArray(e.params)||!o(e.params[0])||e.params[0].type!=="ObjectPattern"||!Array.isArray(e.params[0].properties)||!e.params[0].properties.some(a=>o(a)&&o(a.key)&&a.key.name==="canvasElement"&&o(a.value)&&a.value.name==="canvasElement"))return!1;const l=A(e.body,"VariableDeclarator"),n=l.filter(a=>o(a.init)&&a.init.type==="CallExpression"&&y(a.init.callee)===r&&Array.isArray(a.init.arguments)&&a.init.arguments.length===1&&y(a.init.arguments[0])==="canvasElement").map(a=>y(a.id)).filter(a=>!!a),f=l.filter(a=>n.some(k=>Y(a.init,k,"getByRole")&&Array.isArray(a.init.arguments)&&g(a.init.arguments[0])==="button"&&typeof g(m(a.init.arguments[1],"name"))=="string"&&!!g(m(a.init.arguments[1],"name"))?.trim())).map(a=>y(a.id)).filter(a=>!!a);if(f.length===0)return!1;const u=A(e.body,"AwaitExpression").map(a=>a.argument),$=u.some(a=>Y(a,s,"tab")&&Array.isArray(a.arguments)&&a.arguments.length===0),h=u.some(a=>o(a)&&a.type==="CallExpression"&&o(a.callee)&&a.callee.type==="MemberExpression"&&y(a.callee.property)==="toHaveFocus"&&o(a.callee.object)&&a.callee.object.type==="CallExpression"&&y(a.callee.object.callee)===i&&Array.isArray(a.callee.object.arguments)&&f.includes(y(a.callee.object.arguments[0])??""));return $&&h}function se(e,t,r){const s=`src/screens/${P(t)}/${P(t)}`,i=I(e,t.screenViewPath),l=R(E(i),t.screenViewExport);(!l||A(l,"JSXElement").length+A(l,"JSXFragment").length===0)&&p();const n=I(e,t.appRoutePath),f=Z(E(n),t.appRoutePath,t);re(n,f)||p();const u=`${s}.stories.tsx`,$=I(e,u),h=E($),a=r==="storybook-react-vite"?"@storybook/react-vite":"@storybook/nextjs-vite";(!w(h,a,"Meta")||!w(h,a,"StoryObj"))&&p();const k=Z(h,u,t),C=h.filter(c=>c.type==="ExportDefaultDeclaration");C.length!==1&&p();const O=D(C[0].declaration),T=y(O)?te(h,y(O)):O;(y(m(T,"component"))!==k||g(m(T,"title"))!==`Screens/${t.screenId}`)&&p();const v=new Set;for(const c of t.states)for(const d of t.viewports){const L=`${U(c)}${U(d)}`;v.add(L);const b=R(h,L);if((!o(b)||b.type!=="ObjectExpression"||g(m(m(b,"args"),"state"))!==c||g(m(m(m(b,"parameters"),"viewport"),"defaultViewport"))!==d)&&p(),t.critical&&(c==="success"||c==="recovery")){const N=m(b,"play");(!o(N)||!["ArrowFunctionExpression","FunctionExpression"].includes(String(N.type))||!ne(N,h))&&p()}}const F=h.filter(c=>c.type==="ExportNamedDeclaration");F.some(c=>!o(c.declaration)||x(c.declaration).length!==1||Array.isArray(c.specifiers)&&c.specifiers.length>0)&&p();const X=F.flatMap(c=>x(c.declaration)).map(c=>y(c.id)).filter(c=>!!c);(X.length!==v.size||X.some(c=>!v.has(c)))&&p();const W=I(e,`${s}.fixtures.ts`);E(W).filter(c=>c.type==="ExportNamedDeclaration").flatMap(c=>o(c.declaration)?x(c.declaration):[]).some(c=>{const d=m(c.init,"synthetic");return o(d)&&d.type==="BooleanLiteral"&&d.value===!0&&m(c.init,"data")!==void 0})||p();const _=I(e,`${s}.handlers.ts`),B=E(_);(!B.some(c=>c.type==="ImportDeclaration"&&o(c.source)&&c.source.value==="msw"&&Array.isArray(c.specifiers)&&c.specifiers.some(d=>o(d)&&o(d.imported)&&d.imported.name==="http"))||!B.some(c=>c.type==="ExportNamedDeclaration"&&o(c.declaration)&&x(c.declaration).some(d=>o(d.init)&&d.init.type==="ArrayExpression"&&Array.isArray(d.init.elements)&&d.init.elements.length>0))||!A(_,"CallExpression").some(c=>o(c.callee)&&c.callee.type==="MemberExpression"&&o(c.callee.object)&&c.callee.object.name==="http"))&&p();const M=j(e,`${s}.mdx`),J=new RegExp(`import\\s+\\*\\s+as\\s+([A-Za-z_$][\\w$]*)\\s+from\\s+['"]\\./${P(t)}\\.stories(?:\\.tsx)?['"];?\\r?\\n(?:[ \\t]*\\r?\\n)+`).exec(M);(!/import\s+\{\s*Meta\s*\}\s+from\s+['"]@storybook\/addon-docs\/blocks['"]/.test(M)||!J||!M.includes(`<Meta of={${J[1]}} />`))&&p()}function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${S(r)}`).join(",")}}`:JSON.stringify(e)??"null"}function oe(e){const t=S(e);let r=2166136261;for(let s=0;s<t.length;s++)r^=t.charCodeAt(s),r=Math.imul(r,16777619);return`uxm-${(r>>>0).toString(16).padStart(8,"0")}`}function ie(e,t){let r;try{r=JSON.parse(j(e,"docs/architecture/ux-coverage-manifest.json"))}catch{p()}(!o(r)||r.schemaVersion!==1||r.manifestId!=="P201-UX-MANIFEST-01"||!Array.isArray(r.entries)||typeof r.fingerprint!="string"||Object.keys(r).sort().join(",")!=="entries,fingerprint,manifestId,schemaVersion"||r.fingerprint!==oe(r.entries))&&p();const s=new Map;for(const n of t.screens)for(const f of n.states)for(const u of n.viewports)s.set(`Screens/${n.screenId}/${f}/${u}`,{screen:n,state:f,viewport:u});r.entries.length!==s.size&&p();const i=new Set;let l="";for(const n of r.entries){(!o(n)||typeof n.storyId!="string"||i.has(n.storyId))&&p(),l&&l.localeCompare(n.storyId)>=0&&p(),l=n.storyId,Object.keys(n).sort().join(",")!=="approvalEvidenceIds,fixtureId,handlerIds,journeyIds,screenId,screenViewPath,state,storyId,viewport"&&p(),i.add(n.storyId);const f=s.get(n.storyId);(!f||n.screenId!==f.screen.screenId||n.state!==f.state||n.viewport!==f.viewport||n.screenViewPath!==f.screen.screenViewPath||!Array.isArray(n.approvalEvidenceIds)||S([...n.approvalEvidenceIds].sort())!==S([...f.screen.approvalEvidenceIds].sort())||!Array.isArray(n.journeyIds)||n.journeyIds.length<1||n.journeyIds.some(u=>typeof u!="string"||!z.test(u))||new Set(n.journeyIds).size!==n.journeyIds.length||typeof n.fixtureId!="string"||!z.test(n.fixtureId)||!Array.isArray(n.handlerIds)||n.handlerIds.length<1||n.handlerIds.some(u=>typeof u!="string"||!z.test(u))||new Set(n.handlerIds).size!==n.handlerIds.length)&&p()}}function fe(e,t){try{for(const[r,s]of[["docs/architecture/ux-design.md","P201-UX-STORYBOOK-01"],["docs/architecture/storybook-ux-contract.md","P201-UX-STORYBOOK-01"]])j(e,r).includes(s)||p();for(const r of t.screens)se(e,r,t.adapterId);ie(e,t)}catch{p()}}export{fe as validateUxCandidateSource};
@@ -77,7 +77,7 @@ export interface HeadlessRuntimeBinaryCheckOptions {
77
77
  readonly commandLocator?: (commandName: string, env?: NodeJS.ProcessEnv) => string | undefined;
78
78
  readonly realpathBasenamePolicy?: HeadlessRuntimeRealpathBasenamePolicy;
79
79
  }
80
- export type HeadlessRuntimeRealpathBasenamePolicy = 'strict' | 'claude-code-versioned';
80
+ export type HeadlessRuntimeRealpathBasenamePolicy = 'strict' | 'claude-code-versioned' | 'opencode-npm-native';
81
81
  export type HeadlessRuntimeBinaryCheckResult = {
82
82
  readonly ok: true;
83
83
  readonly trusted: true;
@@ -1 +1 @@
1
- import{existsSync as g,readFileSync as j,realpathSync as z,statSync as M}from"node:fs";import{basename as P,delimiter as K,dirname as p,isAbsolute as k,join as B,relative as X,resolve as E,sep as F,win32 as Z}from"node:path";const o=Object.freeze({OK:"continuity-ok",MISSING:"runner-binary-missing",AMBIGUOUS:"runner-binary-ambiguous",NON_EXECUTABLE:"runner-binary-non-executable",VERSION_MISMATCHED:"runner-binary-version-mismatched",UNTRUSTED:"runner-binary-untrusted"}),m=Object.freeze({OK:"continuity-ok",UNAVAILABLE:"headless-adapter-unavailable",UNTRUSTED:"headless-runtime-untrusted"}),y=new Set(["@ornexus/neocortex","@neocortex/client"]),v=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function re(e={}){const t=J(e);if(!t)return b(o.MISSING,"Runner binary resolution did not receive a usable start path.");const r=w(t);if(!r)return b(o.AMBIGUOUS,"Runner binary was not inside an accepted Neocortex package.");const{packageRoot:n,pkg:c}=r,a=typeof c.name=="string"?c.name:void 0,i=typeof c.version=="string"?c.version:void 0,u=G(n,a);if(!a||!y.has(a))return b(o.AMBIGUOUS,"Runner package identity was not accepted.",{packageName:a,packageVersion:i,packageRoot:n,provenance:u});if(!i||!v.test(i))return b(o.VERSION_MISMATCHED,"Runner package version was missing or invalid.",{packageName:a,packageVersion:i,packageRoot:n,provenance:u});const s=_(c,a);if(!s)return b(o.MISSING,"Runner package did not declare an accepted runner bin target.",{packageName:a,packageVersion:i,packageRoot:n,provenance:u});const d=D(n,s),l=R(d);if(!l||!g(l))return b(o.MISSING,"Runner package bin target was not present.",{packageName:a,packageVersion:i,packageRoot:n,expectedRelativePath:s,provenance:u});const S=A(l,e.platform,e.requireExecutable);return S?b(S,N(S),{packageName:a,packageVersion:i,packageRoot:n,executablePath:l,expectedRelativePath:s,provenance:u}):V(n,a,i)?b(o.VERSION_MISMATCHED,"Runner package version did not match the development workspace root.",{packageName:a,packageVersion:i,packageRoot:n,executablePath:l,expectedRelativePath:s,provenance:u}):{ok:!0,trusted:!0,command:l,args:[],executablePath:l,packageName:a,packageVersion:i,packageRoot:n,expectedRelativePath:s,provenance:u,reasonCodes:[o.OK],publicSummary:`Resolved trusted ${u} runner for ${a}.`,publicSafe:!0}}function ae(e,t={}){const r=I(e);if(!r)return f(o.MISSING,"Runner executable path was missing.");const n=R(r);if(!n||!g(n))return f(o.MISSING,"Runner executable was not present.",{executablePath:r});const c=w(p(n));if(!c)return f(o.AMBIGUOUS,"Runner executable was not inside an accepted Neocortex package.",{executablePath:n});const{packageRoot:a,pkg:i}=c,u=typeof i.name=="string"?i.name:void 0,s=typeof i.version=="string"?i.version:void 0,d=G(a,u);if(!u||!y.has(u))return f(o.AMBIGUOUS,"Runner package identity was not accepted.",{executablePath:n,packageName:u,packageVersion:s,packageRoot:a,provenance:d});if(!s||!v.test(s))return f(o.VERSION_MISMATCHED,"Runner package version was missing or invalid.",{executablePath:n,packageName:u,packageVersion:s,packageRoot:a,provenance:d});const l=_(i,u);if(!l)return f(o.MISSING,"Runner package did not declare an accepted runner bin target.",{executablePath:n,packageName:u,packageVersion:s,packageRoot:a,provenance:d});const S=R(D(a,l));if(!S||!g(S))return f(o.MISSING,"Runner package bin target was not present.",{executablePath:n,packageName:u,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d});if(S!==n)return f(o.AMBIGUOUS,"Runner executable did not match the package-declared bin target.",{executablePath:n,packageName:u,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d});const x=A(n,t.platform,t.requireExecutable);return x?f(x,N(x),{executablePath:n,packageName:u,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d}):V(a,u,s)?f(o.VERSION_MISMATCHED,"Runner package version did not match the development workspace root.",{executablePath:n,packageName:u,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d}):{trusted:!0,packageName:u,packageVersion:s,packageRoot:a,executablePath:n,expectedRelativePath:l,provenance:d,reasonCodes:[o.OK],publicSummary:`Trusted ${d} runner for ${u}.`,publicSafe:!0}}function ce(e,t){return H(e)||H(t)?Z.relative(e,t).split("\\").join("/"):X(e,t).split("\\").join("/")}function oe(e){const t=e.commandName,r=e.realpathBasenamePolicy??"strict";if(!U(t))return h(m.UNTRUSTED,"Headless runtime command name was not allowlisted by adapter code.",t,"commandName","unsafe_key");const c=(e.commandLocator??q)(t,e.env);if(!c)return h(m.UNAVAILABLE,"Headless runtime command was not found on PATH.",t,"runtimeBinary","missing");if(!$(c,t,e.platform))return h(m.UNTRUSTED,"Headless runtime executable path did not match adapter-owned command constraints.",t,"runtimeBinary","executable_path");const a=R(c);if(!a||!g(a))return h(m.UNAVAILABLE,"Headless runtime executable was not present.",t,"runtimeBinary","missing");if(!Q(a,t,e.platform,r))return h(m.UNTRUSTED,"Headless runtime executable realpath did not match adapter-owned command constraints.",t,"runtimeBinary","executable_path");const i=A(a,e.platform,e.requireExecutable??!0);if(i)return h(i===o.NON_EXECUTABLE||i===o.MISSING?m.UNAVAILABLE:m.UNTRUSTED,N(i),t,"runtimeBinary",i);const u={ok:!0,trusted:!0,commandName:t,reasonCodes:[m.OK],publicSummary:`Trusted headless runtime command ${t} is available.`,redactionSummary:[],publicSafe:!0};return Object.defineProperty(u,"executablePath",{value:a,enumerable:!1,configurable:!1}),u}function q(e,t=process.env){if(!U(e))return;const r=t.PATH??"",n=process.platform==="win32"?(t.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean):[""];for(const c of r.split(K))if(!(!c||/[\r\n\0]/.test(c)))for(const a of n){const i=E(c,`${e}${a}`);if(g(i))return i}}function J(e){if(e.packageRoot)return I(e.packageRoot);const t=I(e.from??process.argv[1]);if(!t)return null;const r=R(t);if(r)try{return M(r).isDirectory()?r:p(r)}catch{return p(r)}return p(t)}function I(e){if(!e||/[\r\n\0]/.test(e))return null;const t=k(e)?e:E(e);return k(t)?t:null}function R(e){try{return z(e)}catch{return null}}function w(e){let t=e;for(let r=0;r<10;r++){const n=C(B(t,"package.json"));if(n&&typeof n.name=="string"&&y.has(n.name))return{packageRoot:t,pkg:n};const c=p(t);if(c===t)break;t=c}return null}function O(e){let t=e;for(let r=0;r<10;r++){const n=C(B(t,"package.json"));if(n?.name==="@ornexus/neocortex")return{packageRoot:t,pkg:n};const c=p(t);if(c===t)break;t=c}return null}function C(e){try{return JSON.parse(j(e,"utf8"))}catch{return null}}function _(e,t){const r=W(e.bin)?e.bin["neocortex-runner"]:void 0;if(typeof r!="string"||r.length===0)return null;const n=Y(r);return t==="@ornexus/neocortex"&&n!=="packages/client/dist/runner-cli.js"||t==="@neocortex/client"&&n!=="dist/runner-cli.js"?null:n}function Y(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function D(e,t){return E(e,...t.split("/").filter(Boolean))}function G(e,t){return t==="@ornexus/neocortex"?"published-root-package":t!=="@neocortex/client"?"published-client-package":O(p(e))?"development-workspace":"published-client-package"}function V(e,t,r){if(t!=="@neocortex/client")return!1;const n=O(p(e));return!!(n&&n.pkg.version!==r)}function A(e,t=process.platform,r=!0){try{const n=M(e);return n.isFile()?r&&t!=="win32"&&(n.mode&73)===0?o.NON_EXECUTABLE:null:o.AMBIGUOUS}catch{return o.MISSING}}function b(e,t,r={}){const n=L(r);return{ok:!1,trusted:!1,reasonCode:e,reasonCodes:[e],publicSummary:T(t),publicSafe:!0,...n}}function f(e,t,r={}){const n=L(r);return{trusted:!1,reasonCode:e,reasonCodes:[e],publicSummary:T(t),publicSafe:!0,...n}}function L(e){return{...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{},...e.expectedRelativePath?{expectedRelativePath:e.expectedRelativePath}:{},...e.provenance?{provenance:e.provenance}:{}}}function N(e){switch(e){case o.MISSING:return"Runner package bin target was not present.";case o.AMBIGUOUS:return"Runner binary candidate was ambiguous.";case o.NON_EXECUTABLE:return"Runner package bin target was not executable.";case o.VERSION_MISMATCHED:return"Runner package version did not match the development workspace root.";default:return"Runner binary trust check failed."}}function T(e){return e.length<=180?e:`${e.slice(0,180)}\u2026[TRUNCATED:${e.length-180}]`}function H(e){return/^[A-Za-z]:[\\/]/.test(e)||e.includes("\\")||F==="\\"}function W(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function U(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(e)&&!/[\\/\s;&|`$<>\r\n\0]/.test(e)}function $(e,t,r=process.platform){if(!e||/[\r\n\0]/.test(e)||!k(e))return!1;const n=P(e).toLowerCase(),c=t.toLowerCase();return r==="win32"?n===c||[".exe",".cmd",".bat",".com"].some(a=>n===`${c}${a}`):n===c}function Q(e,t,r=process.platform,n="strict"){return $(e,t,r)?!0:n!=="claude-code-versioned"||t!=="claude"||!e||/[\r\n\0]/.test(e)||!k(e)?!1:ee(P(e),r)}function ee(e,t=process.platform){const r=e.toLowerCase(),n=t==="win32"?r.replace(/\.(?:exe|cmd|bat|com)$/i,""):r;return/^(?:(?:claude|claude-code)[._-])?v?\d+\.\d+\.\d+(?:[-+][0-9a-z][0-9a-z.-]*)?(?:\.(?:js|mjs|cjs))?$/.test(n)}function h(e,t,r,n,c){return{ok:!1,trusted:!1,...r&&U(r)?{commandName:r}:{},reasonCode:e,reasonCodes:[e],publicSummary:T(t),redactionSummary:[{field:n,reason:c,evidence:"value-denied",publicSafe:!0}],publicSafe:!0}}export{m as HEADLESS_RUNTIME_BINARY_REASON_CODES,o as RUNNER_BINARY_REASON_CODES,ae as checkRunnerBinaryTrust,oe as checkTrustedHeadlessRuntimeBinary,q as defaultHeadlessRuntimeCommandLocator,re as resolveTrustedRunnerBinary,ce as runnerTrustRelativePath};
1
+ import{existsSync as g,readFileSync as j,realpathSync as z,statSync as P}from"node:fs";import{basename as E,delimiter as K,dirname as p,isAbsolute as R,join as B,relative as X,resolve as y,sep as F,win32 as Z}from"node:path";const o=Object.freeze({OK:"continuity-ok",MISSING:"runner-binary-missing",AMBIGUOUS:"runner-binary-ambiguous",NON_EXECUTABLE:"runner-binary-non-executable",VERSION_MISMATCHED:"runner-binary-version-mismatched",UNTRUSTED:"runner-binary-untrusted"}),m=Object.freeze({OK:"continuity-ok",UNAVAILABLE:"headless-adapter-unavailable",UNTRUSTED:"headless-runtime-untrusted"}),I=new Set(["@ornexus/neocortex","@neocortex/client"]),w=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function re(e={}){const t=J(e);if(!t)return b(o.MISSING,"Runner binary resolution did not receive a usable start path.");const r=v(t);if(!r)return b(o.AMBIGUOUS,"Runner binary was not inside an accepted Neocortex package.");const{packageRoot:n,pkg:c}=r,a=typeof c.name=="string"?c.name:void 0,u=typeof c.version=="string"?c.version:void 0,i=G(n,a);if(!a||!I.has(a))return b(o.AMBIGUOUS,"Runner package identity was not accepted.",{packageName:a,packageVersion:u,packageRoot:n,provenance:i});if(!u||!w.test(u))return b(o.VERSION_MISMATCHED,"Runner package version was missing or invalid.",{packageName:a,packageVersion:u,packageRoot:n,provenance:i});const s=_(c,a);if(!s)return b(o.MISSING,"Runner package did not declare an accepted runner bin target.",{packageName:a,packageVersion:u,packageRoot:n,provenance:i});const d=D(n,s),l=x(d);if(!l||!g(l))return b(o.MISSING,"Runner package bin target was not present.",{packageName:a,packageVersion:u,packageRoot:n,expectedRelativePath:s,provenance:i});const S=N(l,e.platform,e.requireExecutable);return S?b(S,T(S),{packageName:a,packageVersion:u,packageRoot:n,executablePath:l,expectedRelativePath:s,provenance:i}):L(n,a,u)?b(o.VERSION_MISMATCHED,"Runner package version did not match the development workspace root.",{packageName:a,packageVersion:u,packageRoot:n,executablePath:l,expectedRelativePath:s,provenance:i}):{ok:!0,trusted:!0,command:l,args:[],executablePath:l,packageName:a,packageVersion:u,packageRoot:n,expectedRelativePath:s,provenance:i,reasonCodes:[o.OK],publicSummary:`Resolved trusted ${i} runner for ${a}.`,publicSafe:!0}}function ae(e,t={}){const r=A(e);if(!r)return f(o.MISSING,"Runner executable path was missing.");const n=x(r);if(!n||!g(n))return f(o.MISSING,"Runner executable was not present.",{executablePath:r});const c=v(p(n));if(!c)return f(o.AMBIGUOUS,"Runner executable was not inside an accepted Neocortex package.",{executablePath:n});const{packageRoot:a,pkg:u}=c,i=typeof u.name=="string"?u.name:void 0,s=typeof u.version=="string"?u.version:void 0,d=G(a,i);if(!i||!I.has(i))return f(o.AMBIGUOUS,"Runner package identity was not accepted.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,provenance:d});if(!s||!w.test(s))return f(o.VERSION_MISMATCHED,"Runner package version was missing or invalid.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,provenance:d});const l=_(u,i);if(!l)return f(o.MISSING,"Runner package did not declare an accepted runner bin target.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,provenance:d});const S=x(D(a,l));if(!S||!g(S))return f(o.MISSING,"Runner package bin target was not present.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d});if(S!==n)return f(o.AMBIGUOUS,"Runner executable did not match the package-declared bin target.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d});const k=N(n,t.platform,t.requireExecutable);return k?f(k,T(k),{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d}):L(a,i,s)?f(o.VERSION_MISMATCHED,"Runner package version did not match the development workspace root.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d}):{trusted:!0,packageName:i,packageVersion:s,packageRoot:a,executablePath:n,expectedRelativePath:l,provenance:d,reasonCodes:[o.OK],publicSummary:`Trusted ${d} runner for ${i}.`,publicSafe:!0}}function ce(e,t){return H(e)||H(t)?Z.relative(e,t).split("\\").join("/"):X(e,t).split("\\").join("/")}function oe(e){const t=e.commandName,r=e.realpathBasenamePolicy??"strict";if(!M(t))return h(m.UNTRUSTED,"Headless runtime command name was not allowlisted by adapter code.",t,"commandName","unsafe_key");const c=(e.commandLocator??q)(t,e.env);if(!c)return h(m.UNAVAILABLE,"Headless runtime command was not found on PATH.",t,"runtimeBinary","missing");if(!$(c,t,e.platform))return h(m.UNTRUSTED,"Headless runtime executable path did not match adapter-owned command constraints.",t,"runtimeBinary","executable_path");const a=x(c);if(!a||!g(a))return h(m.UNAVAILABLE,"Headless runtime executable was not present.",t,"runtimeBinary","missing");if(!Q(a,t,e.platform,r))return h(m.UNTRUSTED,"Headless runtime executable realpath did not match adapter-owned command constraints.",t,"runtimeBinary","executable_path");const u=N(a,e.platform,e.requireExecutable??!0);if(u)return h(u===o.NON_EXECUTABLE||u===o.MISSING?m.UNAVAILABLE:m.UNTRUSTED,T(u),t,"runtimeBinary",u);const i={ok:!0,trusted:!0,commandName:t,reasonCodes:[m.OK],publicSummary:`Trusted headless runtime command ${t} is available.`,redactionSummary:[],publicSafe:!0};return Object.defineProperty(i,"executablePath",{value:a,enumerable:!1,configurable:!1}),i}function q(e,t=process.env){if(!M(e))return;const r=t.PATH??"",n=process.platform==="win32"?(t.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean):[""];for(const c of r.split(K))if(!(!c||/[\r\n\0]/.test(c)))for(const a of n){const u=y(c,`${e}${a}`);if(g(u))return u}}function J(e){if(e.packageRoot)return A(e.packageRoot);const t=A(e.from??process.argv[1]);if(!t)return null;const r=x(t);if(r)try{return P(r).isDirectory()?r:p(r)}catch{return p(r)}return p(t)}function A(e){if(!e||/[\r\n\0]/.test(e))return null;const t=R(e)?e:y(e);return R(t)?t:null}function x(e){try{return z(e)}catch{return null}}function v(e){let t=e;for(let r=0;r<10;r++){const n=O(B(t,"package.json"));if(n&&typeof n.name=="string"&&I.has(n.name))return{packageRoot:t,pkg:n};const c=p(t);if(c===t)break;t=c}return null}function C(e){let t=e;for(let r=0;r<10;r++){const n=O(B(t,"package.json"));if(n?.name==="@ornexus/neocortex")return{packageRoot:t,pkg:n};const c=p(t);if(c===t)break;t=c}return null}function O(e){try{return JSON.parse(j(e,"utf8"))}catch{return null}}function _(e,t){const r=W(e.bin)?e.bin["neocortex-runner"]:void 0;if(typeof r!="string"||r.length===0)return null;const n=Y(r);return t==="@ornexus/neocortex"&&n!=="packages/client/dist/runner-cli.js"||t==="@neocortex/client"&&n!=="dist/runner-cli.js"?null:n}function Y(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function D(e,t){return y(e,...t.split("/").filter(Boolean))}function G(e,t){return t==="@ornexus/neocortex"?"published-root-package":t!=="@neocortex/client"?"published-client-package":C(p(e))?"development-workspace":"published-client-package"}function L(e,t,r){if(t!=="@neocortex/client")return!1;const n=C(p(e));return!!(n&&n.pkg.version!==r)}function N(e,t=process.platform,r=!0){try{const n=P(e);return n.isFile()?r&&t!=="win32"&&(n.mode&73)===0?o.NON_EXECUTABLE:null:o.AMBIGUOUS}catch{return o.MISSING}}function b(e,t,r={}){const n=V(r);return{ok:!1,trusted:!1,reasonCode:e,reasonCodes:[e],publicSummary:U(t),publicSafe:!0,...n}}function f(e,t,r={}){const n=V(r);return{trusted:!1,reasonCode:e,reasonCodes:[e],publicSummary:U(t),publicSafe:!0,...n}}function V(e){return{...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{},...e.expectedRelativePath?{expectedRelativePath:e.expectedRelativePath}:{},...e.provenance?{provenance:e.provenance}:{}}}function T(e){switch(e){case o.MISSING:return"Runner package bin target was not present.";case o.AMBIGUOUS:return"Runner binary candidate was ambiguous.";case o.NON_EXECUTABLE:return"Runner package bin target was not executable.";case o.VERSION_MISMATCHED:return"Runner package version did not match the development workspace root.";default:return"Runner binary trust check failed."}}function U(e){return e.length<=180?e:`${e.slice(0,180)}\u2026[TRUNCATED:${e.length-180}]`}function H(e){return/^[A-Za-z]:[\\/]/.test(e)||e.includes("\\")||F==="\\"}function W(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function M(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(e)&&!/[\\/\s;&|`$<>\r\n\0]/.test(e)}function $(e,t,r=process.platform){if(!e||/[\r\n\0]/.test(e)||!R(e))return!1;const n=E(e).toLowerCase(),c=t.toLowerCase();return r==="win32"?n===c||[".exe",".cmd",".bat",".com"].some(a=>n===`${c}${a}`):n===c}function Q(e,t,r=process.platform,n="strict"){return $(e,t,r)?!0:n==="opencode-npm-native"&&t==="opencode"?!e||/[\r\n\0]/.test(e)||!R(e)?!1:E(e).toLowerCase()==="opencode.exe":n!=="claude-code-versioned"||t!=="claude"||!e||/[\r\n\0]/.test(e)||!R(e)?!1:ee(E(e),r)}function ee(e,t=process.platform){const r=e.toLowerCase(),n=t==="win32"?r.replace(/\.(?:exe|cmd|bat|com)$/i,""):r;return/^(?:(?:claude|claude-code)[._-])?v?\d+\.\d+\.\d+(?:[-+][0-9a-z][0-9a-z.-]*)?(?:\.(?:js|mjs|cjs))?$/.test(n)}function h(e,t,r,n,c){return{ok:!1,trusted:!1,...r&&M(r)?{commandName:r}:{},reasonCode:e,reasonCodes:[e],publicSummary:U(t),redactionSummary:[{field:n,reason:c,evidence:"value-denied",publicSafe:!0}],publicSafe:!0}}export{m as HEADLESS_RUNTIME_BINARY_REASON_CODES,o as RUNNER_BINARY_REASON_CODES,ae as checkRunnerBinaryTrust,oe as checkTrustedHeadlessRuntimeBinary,q as defaultHeadlessRuntimeCommandLocator,re as resolveTrustedRunnerBinary,ce as runnerTrustRelativePath};
@@ -1,2 +1,2 @@
1
- import{checkTrustedHeadlessRuntimeBinary as _}from"../binary.js";import{HEADLESS_REASON_CODES as s,adapterAvailabilityFailure as m,adapterAvailabilitySuccess as R,createRejectedExecutionResult as E,createUnavailableExecutionResult as I,hashPublicValue as f,normalizeHeadlessCommandResult as p,redaction as A,runHeadlessCommand as v,validateHeadlessAdapterExecutionInput as b}from"./types.js";import{governedPreflightFailureResult as h,preflightManagedHeadlessProfile as y,withGovernedHeadlessEvidence as c}from"./managed-profile.js";const r="opencode",d="opencode",S="neocortex",T=2e3,C=2e3,O=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i,P=/\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i,k=/\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;function w(){return{id:r,displayName:"OpenCode Headless Adapter",async checkAvailability(n={}){return N(r,d,n)},buildInvocation(n){const e=b(n,r);return e.ok?{ok:!0,invocation:{adapterId:r,commandName:d,args:V(e.prompt,e.input.modelId),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(n,e={}){const t=b(n,r);if(!t.ok)return E(r,r,t);const a=y(r,e);if(!a.ok)return h(r,t.input,a);if(e.signal?.aborted)return c(p(r,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const i=await this.checkAvailability(e);if(!i.ok)return c(I(r,t.input,i));const o=this.buildInvocation(t.input);if(!o.ok)return E(r,r,o);const u=await(e.commandRunner??v)(i.executablePath??d,o.invocation.args,{cwd:e.cwd,env:e.env,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return c(p(r,t.input,u))}}}async function N(n,e,t,a={}){const i=_({commandName:e,env:t.env,platform:t.platform,commandLocator:t.commandLocator,realpathBasenamePolicy:a.realpathBasenamePolicy});if(!i.ok)return m(n,e,i.reasonCode===s.ADAPTER_UNAVAILABLE?s.ADAPTER_UNAVAILABLE:s.RUNTIME_UNTRUSTED,i.publicSummary,i.redactionSummary);const l=await(t.versionRunner??t.commandRunner??v)(i.executablePath,["--version"],{env:t.env,timeoutMs:5e3,maxOutputBytes:2e3}),u=g(l,a.versionEvidence??"generic-public");return u.ok?R(n,e,D(e,a.versionEvidence),{executablePath:i.executablePath,versionText:u.versionText}):m(n,e,s.ADAPTER_UNAVAILABLE,u.publicSummary,u.redactionSummary)}function g(n,e){const t=x(`${n.stdout}
2
- ${n.stderr}`.trim()),a=t?[A("runtimeVersion","raw_log",f(t))]:[A("runtimeVersion","missing","value-denied")];return n.timedOut||n.exitCode!==0||t.length===0||t.length>T||n.stdoutBytes+n.stderrBytes>C||O.test(t)?{ok:!1,publicSummary:"Headless runtime version check did not return a bounded public result.",redactionSummary:a}:e==="claude-code"&&(!P.test(t)||!k.test(t))?{ok:!1,publicSummary:"Headless runtime version check did not return bounded Claude Code product/version evidence.",redactionSummary:a}:{ok:!0,versionText:t}}function x(n){return n.replace(/\s+/g," ").trim()}function D(n,e){return e==="claude-code"?`Trusted ${n} runtime is available with bounded Claude Code version evidence.`:`Trusted ${n} runtime is available.`}function V(n,e){const t=["run","--agent",S,"--auto"];return e&&t.push("--model",e),t.push("--",n),t}export{N as checkRuntimeAvailability,w as createOpenCodeHeadlessAdapter};
1
+ import{checkTrustedHeadlessRuntimeBinary as _}from"../binary.js";import{HEADLESS_REASON_CODES as s,adapterAvailabilityFailure as m,adapterAvailabilitySuccess as R,createRejectedExecutionResult as p,createUnavailableExecutionResult as I,hashPublicValue as f,normalizeHeadlessCommandResult as E,redaction as A,runHeadlessCommand as v,validateHeadlessAdapterExecutionInput as b}from"./types.js";import{governedPreflightFailureResult as h,preflightManagedHeadlessProfile as y,withGovernedHeadlessEvidence as c}from"./managed-profile.js";const r="opencode",d="opencode",S="neocortex",T=2e3,C=2e3,P=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i,O=/\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i,k=/\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;function w(){return{id:r,displayName:"OpenCode Headless Adapter",async checkAvailability(n={}){return N(r,d,n,{realpathBasenamePolicy:"opencode-npm-native"})},buildInvocation(n){const e=b(n,r);return e.ok?{ok:!0,invocation:{adapterId:r,commandName:d,args:V(e.prompt,e.input.modelId),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(n,e={}){const t=b(n,r);if(!t.ok)return p(r,r,t);const a=y(r,e);if(!a.ok)return h(r,t.input,a);if(e.signal?.aborted)return c(E(r,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const i=await this.checkAvailability(e);if(!i.ok)return c(I(r,t.input,i));const o=this.buildInvocation(t.input);if(!o.ok)return p(r,r,o);const u=await(e.commandRunner??v)(i.executablePath??d,o.invocation.args,{cwd:e.cwd,env:e.env,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return c(E(r,t.input,u))}}}async function N(n,e,t,a={}){const i=_({commandName:e,env:t.env,platform:t.platform,commandLocator:t.commandLocator,realpathBasenamePolicy:a.realpathBasenamePolicy});if(!i.ok)return m(n,e,i.reasonCode===s.ADAPTER_UNAVAILABLE?s.ADAPTER_UNAVAILABLE:s.RUNTIME_UNTRUSTED,i.publicSummary,i.redactionSummary);const l=await(t.versionRunner??t.commandRunner??v)(i.executablePath,["--version"],{env:t.env,timeoutMs:5e3,maxOutputBytes:2e3}),u=g(l,a.versionEvidence??"generic-public");return u.ok?R(n,e,D(e,a.versionEvidence),{executablePath:i.executablePath,versionText:u.versionText}):m(n,e,s.ADAPTER_UNAVAILABLE,u.publicSummary,u.redactionSummary)}function g(n,e){const t=x(`${n.stdout}
2
+ ${n.stderr}`.trim()),a=t?[A("runtimeVersion","raw_log",f(t))]:[A("runtimeVersion","missing","value-denied")];return n.timedOut||n.exitCode!==0||t.length===0||t.length>T||n.stdoutBytes+n.stderrBytes>C||P.test(t)?{ok:!1,publicSummary:"Headless runtime version check did not return a bounded public result.",redactionSummary:a}:e==="claude-code"&&(!O.test(t)||!k.test(t))?{ok:!1,publicSummary:"Headless runtime version check did not return bounded Claude Code product/version evidence.",redactionSummary:a}:{ok:!0,versionText:t}}function x(n){return n.replace(/\s+/g," ").trim()}function D(n,e){return e==="claude-code"?`Trusted ${n} runtime is available with bounded Claude Code version evidence.`:`Trusted ${n} runtime is available.`}function V(n,e){const t=["run","--standalone","--agent",S,"--auto"];return e&&t.push("--model",e),t.push("--",n),t}export{N as checkRuntimeAvailability,w as createOpenCodeHeadlessAdapter};
File without changes