@ornexus/neocortex 4.66.6 → 4.66.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1194 -1194
- package/install.ps1 +10 -3
- package/install.sh +8 -10
- package/package.json +2 -2
- package/packages/client/dist/agent/refresh-stubs.d.ts +2 -2
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/cli.js +0 -0
- package/packages/client/dist/commands/activate.js +7 -8
- package/packages/client/dist/commands/invoke.d.ts +7 -1
- package/packages/client/dist/commands/invoke.js +98 -96
- package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +1 -1
- package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
- package/packages/client/dist/generated/public-projections.generated.d.ts +19 -19
- package/packages/client/dist/generated/public-projections.generated.js +1 -1
- package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
- package/packages/client/dist/git/git-lifecycle-store.js +9 -9
- package/packages/client/dist/git/published-story-reconciliation.d.ts +13 -0
- package/packages/client/dist/git/published-story-reconciliation.js +2 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/license/license-client.d.ts +3 -0
- package/packages/client/dist/license/license-client.js +1 -1
- package/packages/client/dist/runner-cli.js +0 -0
- package/packages/client/dist/yoloop/target-normalization.d.ts +8 -2
- package/packages/client/dist/yoloop/target-normalization.js +1 -1
- package/packages/shared/dist/compatibility/index.js +3 -0
- package/packages/shared/dist/generated/public-projections.generated.js +17 -17
- package/packages/shared/dist/invocation/diagnose-degraded-continuation.d.ts +13 -1
- package/packages/shared/dist/invocation/diagnose-degraded-continuation.js +20 -12
- package/packages/shared/dist/invocation/diagnose-degraded-continuation.test.js +30 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +7 -13
- package/targets-stubs/antigravity/skill/SKILL.md +7 -13
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +8 -8
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +8 -8
- package/targets-stubs/codex/AGENTS.md +7 -11
- package/targets-stubs/codex/neocortex.toml +7 -13
- package/targets-stubs/cursor/agent.md +8 -14
- package/targets-stubs/deepseek-harness/SKILL.md +7 -13
- package/targets-stubs/gemini-cli/agent.md +8 -14
- package/targets-stubs/gemini-cli/agents/neocortex.md +8 -14
- package/targets-stubs/grok/SKILL.md +7 -13
- package/targets-stubs/kimi/neocortex.md +7 -13
- package/targets-stubs/lib/managed-config-merge.js +16 -3
- package/targets-stubs/openclaw/SKILL.md +7 -13
- package/targets-stubs/opencode/neocortex-root.md +8 -13
- package/targets-stubs/opencode/neocortex.md +8 -13
- package/targets-stubs/vscode/neocortex.agent.md +8 -14
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`).map(o=>o.trim()).filter(o=>o.startsWith(a));return c.length===1?c[0].slice(a.length):void 0}function ze(e){return St(zt,e)}function X(e,t){return(it(e,t)?.receipts??[]).filter(Tt)}function ke(e){const t=[...e].sort((a,c)=>a.integrationIndex-c.integrationIndex);t.forEach((a,c)=>{(a.integrationIndex!==c+1||c>0&&a.epicHeadBeforeSha!==t[c-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function le(e,t){const a=[...e].sort((c,o)=>o.integrationIndex-c.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const $t=new Set(["done","merged","completed","released"]);function gt(e,t,a,c,o,l=new Set){(it(e,a)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===c||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(c))||i("story-worktree-integration-unbound");const u=new Set(X(e,a).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of o){if(!d.startsWith(`${a}.`))continue;const b=t[d],m=!!e.stories[d]?.checkpoint||typeof b?.status=="string"&&$t.has(b.status);!u.has(d)&&!l.has(d)&&!m&&i("story-worktree-integration-dependency-waiting")}}function Gt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${ge(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:a,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function je(e){return ge(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Te(e){let t;return await ue(e.projectRoot,a=>{const c=X(a,e.epicId);ke(c);const o=[...c].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];o&&o.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...c].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=Gt({epicId:e.epicId,storyId:e.storyId,index:c.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),Ct(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await w(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await C(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&i("story-worktree-integration-epic-head-raced")}}),t}function Ie(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:ze(e.receipt)})}}async function qt(e){let t,a,c="";const o=xe(e.projectRoot);try{(typeof e.storyId!="string"||!Ce.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!Lt.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const l=await Re(await w(o,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await Re(await w(o,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==n&&i("story-worktree-integration-not-root");let f;try{f=await rt(o,e.storyId)}catch(h){i(h instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(h.message)?h.message:"story-worktree-integration-authority-invalid")}const{epicId:g,executionBranch:u,storyId:d}=f;c=g;const b=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,p=await w(o,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p&&i("story-worktree-integration-root-head-mismatch");const T=f.originBinding;(!T||!await C(o,["merge-base","--is-ancestor",T.originHeadSha,p]))&&i("story-worktree-integration-origin-binding-invalid");const A=await V(o,{required:!0}),v=X(A,g);ke(v);const H=v.filter(h=>h.storyId===d).sort((h,x)=>x.integrationIndex-h.integrationIndex),R=A.stories[d]?.checkpoint;if(H[0]?.outcome==="integrated")return Ie({storyId:d,epicId:g,outcome:"already-integrated",receipt:H[0],...R?.headSha?{checkpointHeadSha:R.headSha}:{}});const q=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(h=>typeof h=="string"):[],E=await yt(o,A);gt(A,E,g,d,q);const B=Object.values(A.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===g&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));if(R&&typeof R.headSha=="string"){const h=R.headSha,x=await w(o,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed");(z(x,"Neocortex-Story")!==d||!z(x,me))&&i("story-worktree-integration-checkpoint-not-worktree"),h!==p&&i("story-worktree-integration-epic-head-raced"),le(v,R.baseSha);const re=await wt(o,d,`recover-${h.slice(0,40)}`,()=>Te({projectRoot:o,epicId:g,storyId:d,executionBranch:u,before:R.baseSha,after:h,checkpointDigest:je(R),outcome:"integrated",integratedAt:b})),ae=B.length===1?await qe(o,B[0].leaseId,h):!1;return Ie({storyId:d,epicId:g,outcome:"integrated",receipt:re,checkpointHeadSha:h,worktreeRealigned:ae})}const M=Object.values(A.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===g&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));M.length===0&&i("story-worktree-integration-lease-missing"),M.length>1&&i("story-worktree-integration-lease-ambiguous");const D=M[0];D.executionBranch!==u&&i("story-worktree-integration-lease-invalid");const S=await new _e({projectRoot:o}).probe(D.leaseId);(!S.ok||S.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),S.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const F=await w(o,["rev-parse",`refs/heads/${D.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");S.value.headSha!==F&&i("story-worktree-integration-worktree-dirty");const N=await w(o,["show","--no-patch","--format=%B",p],"story-worktree-integration-git-failed"),Q=z(N,me)===F&&z(N,"Neocortex-Story")===d;let _,W,k,U=!1;if(Q){_=await w(o,["rev-parse",`${p}^`],"story-worktree-integration-git-failed"),W=p;const h=z(N,"Neocortex-Bundle-Digest")??"",x=z(N,"Neocortex-Claim-Revision")??"";k=tt({storyId:d,epicId:g,executionBranch:u,baseSha:_,bundleDigest:h,graphRevision:f.graphRevision,claimRevision:x}),le(v,_)}else{le(v,p);const h=await ht(o,f,d,p,F);if(h.kind==="conflict")return await Fe({projectRoot:o,epicId:g,storyId:d,executionBranch:u,epicHead:p,tip:F,conflictPaths:h.conflictPaths,integratedAt:b,chain:H});const x=h.changedPaths;W=h.commitSha,k=h.idempotencyKey,_=p,U=!0,(!await C(o,["diff","--cached","--quiet"])||!await C(o,["diff","--quiet","HEAD","--",...x]))&&i("story-worktree-integration-root-dirty")}const Z=await ot(f,d,W);Z.ok||i(Z.reasonCode);const ee=await V(o,{required:!0}),G=ee.epics[g]?.branch_lease,ie=G&&G.ownerStoryId===d&&G.sessionId===k&&G.idempotencyKey===k&&Date.parse(String(G.expiresAt))>Date.now()?G:void 0;G&&!ie&&Date.parse(String(G.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const K=ie??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:b,expiresAt:new Date(Date.parse(b)+et).toISOString()};t=await Me(o,{kind:"direct",storyId:d,sessionId:k,idempotencyKey:k,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;ie||(await ue(o,h=>{const x=Ee(h,g),re=x.branch_lease;re&&Date.parse(String(re.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(x.origin_binding)!==JSON.stringify(T)&&i("story-worktree-integration-origin-binding-invalid"),x.graph_revision!==f.graphRevision&&i("story-worktree-integration-graph-revision-raced"),x.branch_lease=K},{expectedRevision:ee.revision,preCommit:async h=>{await nt(Y.path,Y.owner)||i("story-worktree-integration-lock-raced");const x=X(h,g);ke(x),le(x,_),await w(o,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==p&&i("story-worktree-integration-epic-head-raced")}}),a=K),U&&((await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p||await w(o,["rev-parse",m],"story-worktree-integration-git-failed")!==p)&&i("story-worktree-integration-epic-head-raced"),await C(o,["merge","--ff-only","--no-edit",W])||i("story-worktree-integration-ff-refused"),await w(o,["rev-parse",m],"story-worktree-integration-git-failed")!==W&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let te;const ne=await At({projectRoot:o,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,preFastForwardAuthorizedWriteSet:f.authorizedWriteSet,afterCheckpointPersist:async()=>{const h=(await V(o,{required:!0})).stories[d]?.checkpoint;(!h||h.headSha!==W||h.baseSha!==_)&&i("story-worktree-integration-checkpoint-mismatch"),te=await Te({projectRoot:o,epicId:g,storyId:d,executionBranch:u,before:_,after:W,checkpointDigest:je(h),outcome:"integrated",integratedAt:b})}});if(!ne.ok)return{ok:!1,reasonCode:ne.reasonCode};const $=ne.value;($.headSha!==W||$.baseSha!==_||!te)&&i("story-worktree-integration-checkpoint-mismatch");const he=await qe(o,D.leaseId,W);return Ie({storyId:d,epicId:g,outcome:"integrated",receipt:te,checkpointHeadSha:W,worktreeRealigned:he})}catch(l){if(l instanceof De)return{ok:!1,reasonCode:l.reasonCode};const n=l instanceof Error?l.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await We(t.path,t.owner).catch(()=>{}),a&&c){const l=a;await ue(o,n=>{const f=Ee(n,c),g=f.branch_lease;g&&g.sessionId===l.sessionId&&g.idempotencyKey===l.idempotencyKey&&g.acquiredAt===l.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const Le=".neocortex/state.json",Oe=".neocortex",Pe="state.json",j="story-worktree-integration-state-merge-git-failed";function He(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const c=a.indexOf(" "),[o,l,n]=a.slice(0,c).split(" ");(c<0||!o||!l||!n)&&i(j),t.push({mode:o,type:l,oid:n,name:a.slice(c+1)})}return t}function Ft(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function lt(e,t,a,c){const o=await P(e,["ls-tree","-z",t]);o.code!==0&&i(j);const l=He(o.stdout).filter(g=>g.name!==a),n=await dt(e,["mktree","-z"],Ft([...l,c])),f=n.stdout.trim();return(n.code!==0||!fe.test(f))&&i(j),f}async function $e(e,t){const a=await P(e,["ls-tree","-z",t,"--",Le]);a.code!==0&&i(j);const c=He(a.stdout).find(o=>o.name===Le);return c?((c.type!=="blob"||c.mode!=="100644"&&c.mode!=="100755")&&i("state-merge-input-invalid"),fe.test(c.oid)||i(j),c.oid):null}async function Ge(e,t){t===null&&i("state-merge-input-invalid");const a=await P(e,["cat-file","-s",t]),c=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(c)||c<0||c>Bt)&&i(j);const o=await P(e,["cat-file","blob",t]);return o.code!==0&&i(j),o.stdout}async function Kt(e){try{const{projectRoot:t,mergeBase:a,epicHead:c,tip:o,tree:l,storyId:n,epicId:f}=e,g={ok:!0,tree:l,conflictPaths:[...e.conflictPaths],merged:!1},u=await $e(t,a),d=await $e(t,o);if(u===d)return g;const b=await Ge(t,u),m=await Ge(t,await $e(t,c)),p=await Ge(t,d),T=await w(t,["show","--no-patch","--format=%cI",o],j),A=Ht({base:b,epic:m,story:p,storyId:n,epicId:f,aggregateTimestamp:T});if(!A.ok)return{ok:!1,reasonCode:A.reasonCode};const v=e.conflictPaths.filter(S=>S!==Le),H=await P(t,["ls-tree","-z",l,"--",Oe]);H.code!==0&&i(j);const R=He(H.stdout).find(S=>S.name===Oe);if(!R||R.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const q=await P(t,["ls-tree","-z",R.oid,"--",Pe]);q.code!==0&&i(j);const E=He(q.stdout).find(S=>S.name===Pe);if(E&&(E.type!=="blob"||E.mode!=="100644"&&E.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const B=await dt(t,["hash-object","-w","--stdin"],A.bytes),M=B.stdout.trim();if((B.code!==0||!fe.test(M))&&i(j),E?.oid===M)return{ok:!0,tree:l,conflictPaths:v,merged:!0};const D=await lt(t,R.oid,Pe,{mode:E?.mode??"100644",type:"blob",oid:M,name:Pe});return{ok:!0,tree:await lt(t,l,Oe,{mode:R.mode,type:"tree",oid:D,name:Oe}),conflictPaths:v,merged:!0}}catch(t){return t instanceof De?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:j}}}async function ht(e,t,a,c,o){const{epicId:l,executionBranch:n}=t;await C(e,["merge-base","--is-ancestor",o,c])&&i("story-worktree-integration-range-empty");const f=await w(e,["merge-base",c,o],"story-worktree-integration-unrelated-history"),g=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,c,o]);g.code!==0&&g.code!==1&&i("story-worktree-integration-git-unsupported");const u=g.stdout.split("\0"),d=u[0]?.trim()??"";fe.test(d)||i("story-worktree-integration-git-unsupported");const b=g.code===1?[...new Set(u.slice(1).filter(ft))].sort():[];g.code===1&&b.length===0&&i("story-worktree-integration-git-failed");const m=await Kt({projectRoot:e,mergeBase:f,epicHead:c,tip:o,tree:d,storyId:a,epicId:l,conflictPaths:b});m.ok||i(m.reasonCode);const p=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,jt)};const T=(await w(e,["diff","--name-only","-z",c,p],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),A=_t(T,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);A.ok||i(A.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":A.reasonCode===de.WRITE_SET_FORBIDDEN?de.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const v=t.governanceMode==="runtime-store"?await Yt(e,l,a,o):void 0,H=v?v.review:Pt(e,a,p);H?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const R=await P(e,["diff","--binary","--full-index",c,p]);R.code!==0&&i("story-worktree-integration-git-failed");const q=R.stdout;q||i("story-worktree-integration-range-empty");const E=ge(q),B=ge([...t.authorizedWriteSet].sort().join("\0")),M=tt({storyId:a,epicId:l,executionBranch:n,baseSha:c,bundleDigest:E,graphRevision:t.graphRevision,claimRevision:B}),D=(await w(e,["show","--no-patch","--format=%s",o],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,L=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${l}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${c}`,`Neocortex-Bundle-Digest: ${E}`,`Neocortex-Review-Artifact-Digest: ${H.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${B}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Wt(t.rootMemoryEffect)}`]:[],...v?[`${at}: ${v.governanceDigest}`]:[],`${me}: ${o}`],S=(await w(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",o],"story-worktree-integration-git-failed")).split("\0");S.length!==6&&i("story-worktree-integration-git-failed");const F=await w(e,["commit-tree",p,"-p",c,"-m",D,"-m",`Story: ${a}`,"-m",L.join(`
|
|
3
|
-
`)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:S[0],GIT_AUTHOR_EMAIL:S[1],GIT_AUTHOR_DATE:S[2],GIT_COMMITTER_NAME:S[3],GIT_COMMITTER_EMAIL:S[4],GIT_COMMITTER_DATE:S[5]});return fe.test(F)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:F,changedPaths:T,idempotencyKey:M}}async function Yt(e,t,a,c){const o=await w(e,["show","--no-patch","--format=%B",c],"story-worktree-integration-git-failed"),l=z(o,at);l===void 0&&i("story-worktree-integration-governance-trailer-missing");const n=Nt({projectRoot:e,epicId:t,storyId:a});n.ok||i(n.reasonCode===de.UNSAFE?n.reasonCode:de.MISMATCH);const f=n.value.receipt.governanceDigest;l!==f&&i(de.MISMATCH);const g=n.value.files.get(Mt(a));return g||i(de.MISMATCH),{governanceDigest:f,review:Ot(a,g)}}async function yt(e,t){const a=JSON.parse(await It(vt(e,".neocortex","state.json"),"utf8")),o=Dt(a,t).stories;return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}async function wt(e,t,a,c){const o=await Me(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});o.ok||i(o.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await c()}finally{await We(o.path,o.owner).catch(()=>{})}}async function qe(e,t,a){const c=await new _e({projectRoot:e}).probe(t);return!c.ok||c.value.ownership!=="proven"||c.value.clean!==!0?!1:C(c.value.entry.worktreePath,["reset","--keep",a])}async function Fe(e){const t=ge(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),a=e.chain[0];if(a?.outcome==="conflict-reopened"&&a.epicHeadAfterSha===e.epicHead&&a.checkpointDigest===t)return Ie({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const c=()=>Te({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),o=e.lockHeld?await c():await wt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,c);return Ie({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:o,conflictPaths:Object.freeze([...e.conflictPaths])})}const Jt=64,Ut="@ornexus/neocortex",Ke=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Ke)if(!ft(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Vt(e){return C(e,["clean","-X","-f","-q","--",...Ke])}async function Xt(e,t){const a=await P(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Ut?Ke:[]}catch{return[]}}function Qt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function fr(e){let t,a,c="",o=0,l;const n=xe(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Jt||new Set(f).size!==f.length||f.some(r=>typeof r!="string"||!Ce.test(r)))&&i("story-worktree-wave-stories-invalid");const g=await Re(await w(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await Re(await w(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==u&&i("story-worktree-integration-not-root");const d=new Map;for(const r of f)try{d.set(r,await rt(n,r))}catch(s){i(s instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(s.message)?s.message:"story-worktree-integration-authority-invalid")}const b=d.get(f[0]),{epicId:m,executionBranch:p}=b;for(const r of d.values())(r.epicId!==m||r.executionBranch!==p||r.graphRevision!==b.graphRevision||JSON.stringify(r.originBinding)!==JSON.stringify(b.originBinding))&&i("story-worktree-wave-epic-mixed");c=m;const T=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${p}`,v=await w(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==v||await w(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==p)&&i("story-worktree-integration-root-head-mismatch");const H=b.originBinding;(!H||!await C(n,["merge-base","--is-ancestor",H.originHeadSha,v]))&&i("story-worktree-integration-origin-binding-invalid");const R=r=>{const s=d.get(r).story;return Array.isArray(s.depends_on)?s.depends_on.filter(y=>typeof y=="string"):[]},q=new Map(f.map((r,s)=>[r,s]));f.forEach((r,s)=>{for(const y of R(r)){const I=q.get(y);I!==void 0&&I>=s&&i("story-worktree-wave-order-invalid")}});const E=await V(n,{required:!0}),B=X(E,m);ke(B);const M=r=>B.filter(s=>s.storyId===r).sort((s,y)=>y.integrationIndex-s.integrationIndex)[0],D=f.filter(r=>M(r)?.outcome!=="integrated"),L=new Map(f.filter(r=>!D.includes(r)).map(r=>{const s=M(r),y=E.stories[r]?.checkpoint;return[r,Object.freeze({storyId:r,outcome:"already-integrated",receiptDigest:ze(s),...y?.headSha?{checkpointHeadSha:y.headSha}:{}})]})),S=r=>({ok:!0,value:Object.freeze({epicId:m,...r,gateRuns:o,stories:Object.freeze(f.map(s=>L.get(s)??Object.freeze({storyId:s,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(D.length===0)return S({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:v,epicHeadAfterSha:v,gateRunCap:0});const F=new Set(D),N=[];let Q=v;for(let r=0;r<D.length;r++){const s=await w(n,["show","--no-patch","--format=%B",Q],"story-worktree-integration-git-failed"),y=z(s,"Neocortex-Story");if(!y||!F.has(y)||!z(s,me))break;N.unshift(Q),Q=await w(n,["rev-parse",`${Q}^`],"story-worktree-integration-git-failed")}const _=Q;le(B,_);const W=await yt(n,E),k=[];let U,Z=_;for(const[r,s]of D.entries()){const y=d.get(s);gt(E,W,m,s,R(s),new Set(D.slice(0,r)));const I=Object.values(E.storyWorktrees?.entries??{}).filter(J=>J.storyId===s&&J.epicId===m&&J.state==="active"),O=E.stories[s]?.checkpoint;if(O&&typeof O.headSha=="string"){const J=O.headSha,Qe=await w(n,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed");(z(Qe,"Neocortex-Story")!==s||!z(Qe,me))&&i("story-worktree-integration-checkpoint-not-worktree"),(O.baseSha!==Z||N[r]!==J)&&i("story-worktree-integration-checkpoint-mismatch");const mt=(await w(n,["diff-tree","--no-commit-id","--name-only","-r","-z",J],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:s,sha:J,changedPaths:mt,...I.length===1?{leaseId:I[0].leaseId}:{},...typeof O.graphRevision=="string"?{checkpointGraphRevision:O.graphRevision}:{}}),Z=J;continue}I.length===0&&i("story-worktree-integration-lease-missing"),I.length>1&&i("story-worktree-integration-lease-ambiguous");const be=I[0];be.executionBranch!==p&&i("story-worktree-integration-lease-invalid");const Ae=await new _e({projectRoot:n}).probe(be.leaseId);(!Ae.ok||Ae.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Ae.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const Ne=await w(n,["rev-parse",`refs/heads/${be.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Ae.value.headSha!==Ne&&i("story-worktree-integration-worktree-dirty");const ce=await ht(n,y,s,Z,Ne);if(ce.kind==="conflict"){r<N.length&&i("story-worktree-wave-resume-mismatch"),U={storyId:s,tip:Ne,conflictPaths:ce.conflictPaths};break}r<N.length&&N[r]!==ce.commitSha&&i("story-worktree-wave-resume-mismatch"),k.push({storyId:s,sha:ce.commitSha,changedPaths:ce.changedPaths,leaseId:be.leaseId}),Z=ce.commitSha}if(k.length<N.length&&i("story-worktree-wave-resume-mismatch"),k.length===0){const r=U,s=await Fe({projectRoot:n,epicId:m,storyId:r.storyId,executionBranch:p,epicHead:v,tip:r.tip,conflictPaths:r.conflictPaths,integratedAt:T,chain:B.filter(y=>y.storyId===r.storyId).sort((y,I)=>I.integrationIndex-y.integrationIndex)});return s.ok?(L.set(r.storyId,Object.freeze({storyId:r.storyId,outcome:"conflict-reopened",receiptDigest:s.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...r.conflictPaths])})),S({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:v,epicHeadAfterSha:v,gateRunCap:0})):{ok:!1,reasonCode:s.reasonCode,gateRuns:o}}const ee=new Map;for(const r of k){if(r.checkpointGraphRevision!==void 0){const y=await w(n,["show","--no-patch","--format=%B",r.sha],"story-worktree-integration-git-failed"),I=z(y,"Neocortex-Graph-Revision");I===void 0&&i("direct-yolo-trailer-missing:neocortex-graph-revision"),I!==r.checkpointGraphRevision&&i("direct-yolo-trailer-mismatch:neocortex-graph-revision"),ee.set(r.sha,I);continue}const s=await ot(d.get(r.storyId),r.storyId,r.sha);s.ok||i(s.reasonCode),ee.set(r.sha,s.value.graphRevision)}const G=k[k.length-1].sha,ie=[...new Set(k.flatMap(r=>r.changedPaths))].sort();(!await C(n,["diff","--cached","--quiet"])||!await C(n,["diff","--quiet","HEAD","--",...ie]))&&i("story-worktree-integration-root-dirty");const K=Qt(k.length),Y=ge(["p205-wave-lease-v1",m,p,_,...k.map(r=>r.sha)].join("\0")),te=k[0].storyId,ne=await V(n,{required:!0}),$=ne.epics[m]?.branch_lease,he=$&&$.ownerStoryId===te&&$.sessionId===Y&&$.idempotencyKey===Y&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!he&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const h=he??{schemaVersion:1,ownerStoryId:te,sessionId:Y,idempotencyKey:Y,acquiredAt:T,expiresAt:new Date(Date.parse(T)+et*K).toISOString()};t=await Me(n,{kind:"direct",storyId:te,sessionId:Y,idempotencyKey:Y,expiresAt:String(h.expiresAt),persistent:!0,createdAt:String(h.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const x=t;he||await ue(n,r=>{const s=Ee(r,m),y=s.branch_lease;y&&Date.parse(String(y.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(s.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),s.graph_revision!==b.graphRevision&&i("story-worktree-integration-graph-revision-raced"),s.branch_lease=h},{expectedRevision:ne.revision,preCommit:async r=>{await nt(x.path,x.owner)||i("story-worktree-integration-lock-raced");const s=X(r,m);ke(s),le(s,_),await w(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==v&&i("story-worktree-integration-epic-head-raced")}}),a=h;const re=new Set(k.map(r=>r.sha));let ae=!0;if(e.push&&N.length>0){const r=(await P(n,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";fe.test(r)&&await C(n,["merge-base","--is-ancestor",N[0],r])&&(ae=!1)}let se=v;const ve=async r=>{if((await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==se||await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==se||await w(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==p)&&i("story-worktree-integration-epic-head-raced"),se===r)return;const s=await C(n,["merge-base","--is-ancestor",se,r]);!s&&(!ae||!re.has(se))&&i("story-worktree-wave-pushed-immovable"),(!(s?await C(n,["merge","--ff-only","--no-edit",r]):await C(n,["reset","--keep",r]))||await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==r||await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==r)&&i("story-worktree-integration-ff-refused"),se=r};l=ae?{epicRef:A,base:_,owned:re}:void 0,await ve(G),await e.afterWaveFastForward?.();const pt=[...new Set(k.map(r=>ee.get(r.sha)))],ut=await Xt(n,_),Be=async()=>{ut.length!==0&&(await(e.cleanBuildOutputs??Vt)(n)||i("story-worktree-wave-clean-failed"))},Ye=async r=>{const s=k[r];await ve(s.sha),o>=K&&i("story-worktree-wave-gate-cap-exceeded"),o>0&&await Be(),o++;const y=await Et({projectRoot:n,headSha:s.sha,storyId:s.storyId,graphRevisions:pt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==s.sha||await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==s.sha||!await C(n,["diff","--cached","--quiet"])||!await C(n,["diff","--quiet","HEAD","--",...ie]))&&i("story-worktree-integration-epic-head-raced"),!y.ok&&y.kind==="infrastructure"&&i(y.reasonCode),y},Se=await Ye(k.length-1);let Je=k.length-1,Ue=Se.ok?Se.authorities:void 0,ye,we;if(!Se.ok){ae||i("story-worktree-wave-gate-failed-pushed");let r=-1,s=k.length-1;for(we=Se.reasonCode;s-r>1;){const I=Math.floor((r+s)/2),O=await Ye(I);O.ok?(r=I,Ue=O.authorities):(s=I,we=O.reasonCode)}ye=s,Je=r;const y=k[s].storyId;if(L.set(y,Object.freeze({storyId:y,outcome:"gate-failed",reasonCode:we})),r<0)return await ve(_),await Be(),l=void 0,S({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:y,failureReasonCode:we,epicHeadBeforeSha:v,epicHeadAfterSha:_,gateRunCap:K});await ve(k[r].sha),await Be()}const oe=k.slice(0,Je+1),pe=oe[oe.length-1].sha,Ve=bt({epicId:m,executionBranch:p,waveHeadSha:pe,waveStoryIds:oe.map(r=>r.storyId),waveCommitShas:oe.map(r=>r.sha)});e.push&&(l=void 0,await xt(n,e.remote??"origin",p,pe)||i("story-worktree-wave-remote-head-mismatch")),l=void 0;const Xe=[];for(const[r,s]of oe.entries()){const y=r===0?_:oe[r-1].sha,I=await Rt({projectRoot:n,storyId:s.storyId,headSha:s.sha,coverage:Ve,authorities:Ue,expectedLease:h,physicalLock:x,authorizedWriteSet:d.get(s.storyId).authorizedWriteSet,expectedGraphRevision:ee.get(s.sha),...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||i(I.reasonCode),(I.value.headSha!==s.sha||I.value.baseSha!==y)&&i("story-worktree-integration-checkpoint-mismatch");const O=await Te({projectRoot:n,epicId:m,storyId:s.storyId,executionBranch:p,before:y,after:s.sha,checkpointDigest:je(I.value),outcome:"integrated",integratedAt:T,expectedEpicHead:pe});Xe.push(s.storyId),L.set(s.storyId,Object.freeze({storyId:s.storyId,outcome:"integrated",checkpointHeadSha:s.sha,receiptDigest:ze(O)})),await e.afterWaveStoryPersist?.(s.storyId)}if(U&&ye===void 0){const r=U,s=await V(n,{required:!0}),y=await Fe({projectRoot:n,epicId:m,storyId:r.storyId,executionBranch:p,epicHead:pe,tip:r.tip,conflictPaths:r.conflictPaths,integratedAt:T,chain:X(s,m).filter(I=>I.storyId===r.storyId).sort((I,O)=>O.integrationIndex-I.integrationIndex),lockHeld:!0});y.ok||i(y.reasonCode),L.set(r.storyId,Object.freeze({storyId:r.storyId,outcome:"conflict-reopened",receiptDigest:y.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...r.conflictPaths])}))}for(const r of oe){if(!r.leaseId)continue;const s=await qe(n,r.leaseId,r.sha);L.set(r.storyId,Object.freeze({...L.get(r.storyId),worktreeRealigned:s}))}return S({outcome:ye!==void 0?"gate-failed":U?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Xe),...ye!==void 0?{failedStoryId:k[ye].storyId,failureReasonCode:we}:{},epicHeadBeforeSha:v,epicHeadAfterSha:pe,qaCoverage:Ve,gateRunCap:K})}catch(f){let g=f instanceof De?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(l){const u=l,d=(await P(n,["rev-parse",u.epicRef])).stdout.trim(),b=(await P(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==b||!u.owned.has(d)||!await C(n,["reset","--keep",u.base]))&&(g="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:g,gateRuns:o}}finally{if(t?.ok&&await We(t.path,t.owner).catch(()=>{}),a&&c){const f=a;await ue(n,g=>{const u=Ee(g,c),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function gr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(g=>typeof g!="string"||!Ce.test(g)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??qt,c=new Set(e.readyStoryIds),o=xe(e.projectRoot);let l;try{const g=await V(o,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));l=new Set([...u].flatMap(d=>X(g,d)).filter(d=>d.outcome==="integrated").map(d=>d.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const n=[],f=[];for(const g of t){if(l.has(g))continue;if(!c.has(g))return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:b,...m}=e,p=await a({...m,projectRoot:o,storyId:g});if(n.push({storyId:g,result:p}),!p.ok)return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:p.reasonCode};if(p.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:"integration-conflict-reopened"};f.push(g),l.add(g)}return{results:n,integratedStoryIds:f}}async function lr(e){const t=xe(e.projectRoot),a=e.manager??new _e({projectRoot:t});let c;try{c=await V(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const o=[];for(const l of e.directives){const n=l&&typeof l=="object"&&!Array.isArray(l)?l:void 0,f=typeof n?.storyId=="string"&&Ce.test(n.storyId)?n.storyId:"";if(!f){o.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const g=Object.values(c.storyWorktrees?.entries??{}).filter(d=>d.storyId===f&&d.state==="active");if(g.length!==1){o.push({storyId:f,ok:!1,reasonCode:g.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await a.sync({leaseId:g[0].leaseId,directive:l});o.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return o}export{jt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,zt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,Le as STORY_WORKTREE_STATE_JSON_PATH,Ke as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Ut as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Jt as STORY_WORKTREE_WAVE_MAX_STORIES,ze as digestStoryWorktreeIntegrationReceipt,qt as integrateStoryWorktree,fr as integrateStoryWorktreeWave,gr as integrateStoryWorktreesInOrder,Kt as resolveStoryWorktreeStateJsonMerge,Xt as storyWorktreeWaveBuildOutputPaths,Qt as storyWorktreeWaveGateRunCap,lr as syncReleasedDependents};
|
|
1
|
+
import{execFile as tt}from"node:child_process";import{createHash as vt}from"node:crypto";import{readFile as St,realpath as xe}from"node:fs/promises";import{join as bt,resolve as Ee}from"node:path";import{yoloopDomainHash as At}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as rt,directYoloCommitIdempotencyKey as ot,directYoloWaveQaCoverage as Rt,finalizeDirectYoloStoryCheckpoint as xt,persistDirectYoloWaveStoryCheckpoint as Et,pushDirectYoloWaveHead as _t,resolveDirectYoloIntegrationAuthority as it,runDirectYoloWaveP205 as Dt,validateDirectYoloWriteSet as Ct,verifyDirectYoloIntegrationCommit as nt}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as We,appendStoryWorktreeEvidence as Tt,applyGitLifecycleRuntimeOverlay as Ot,ensureRuntimeEpic as _e,isStoryWorktreeIntegrationReceiptRecord as Pt,mutateGitLifecycleRuntime as me,publicStoryReviewArtifactFromBytes as Ht,publicStoryReviewArtifactFromGit as Bt,readGitLifecycleRuntime as Q,readStoryWorktreeEvidence as ze,releaseGitLifecyclePhysicalIntegrationLock as je,verifyGitLifecyclePhysicalIntegrationLock as at}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Nt,STATE_JSON_FIELD_MERGE_MAX_BYTES as Mt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as st,GOVERNANCE_REASON_CODES as fe,readStoryGovernanceSync as Wt,storyReviewGovernancePath as zt}from"./governance-runtime-store.js";import{StoryWorktreeManager as De}from"./story-worktree-manager.js";import{revalidatePublishedStoryDependencies as jt}from"./published-story-reconciliation.js";import{rootMemoryEffectDigest as Lt}from"../private-execution/root-memory-git-evidence.js";const $t="neocortex.p225.story-worktree-receipt.v1",Gt=200,ke="Neocortex-Story-Worktree-Tip",ct=3e4,le=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,qt=/^swt-[a-f0-9]{24}$/,Ce=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class Te extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new Te(e)}const dt=32*1024*1024;function P(e,t,a){return new Promise(s=>{tt("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:dt,timeout:ct,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,g)=>{const n=r?typeof r.code=="number"?r.code:128:0;s({code:n,stdout:String(g??"")})})})}function ft(e,t,a){return new Promise(s=>{const r=tt("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:dt,timeout:ct,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(g,n)=>{const d=g?typeof g.code=="number"?g.code:128:0;s({code:d,stdout:String(n??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(a)})}async function p(e,t,a,s){const r=await P(e,t,s);return r.code!==0&&i(a),r.stdout.trim()}async function _(e,t){return(await P(e,t)).code===0}function ge(e){return vt("sha256").update(e).digest("hex")}function lt(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function W(e,t){const a=`${t}: `,s=e.split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r.startsWith(a));return s.length===1?s[0].slice(a.length):void 0}function Le(e){return At($t,e)}function Z(e,t){return(ze(e,t)?.receipts??[]).filter(Pt)}function Ie(e){const t=[...e].sort((a,s)=>a.integrationIndex-s.integrationIndex);t.forEach((a,s)=>{(a.integrationIndex!==s+1||s>0&&a.epicHeadBeforeSha!==t[s-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function he(e,t){const a=[...e].sort((s,r)=>r.integrationIndex-s.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const Ft=new Set(["done","merged","completed","released"]);function gt(e,t,a,s,r,g,n=new Set){(ze(e,a)?.receipts??[]).some(u=>u.kind==="phase-one-receipt"&&u.storyId===s||u.kind==="spec-barrier-receipt"&&Array.isArray(u.storyIds)&&u.storyIds.includes(s))||i("story-worktree-integration-unbound");const l=new Set(Z(e,a).filter(u=>u.outcome==="integrated").map(u=>u.storyId));for(const u of r){if(!u.startsWith(`${a}.`))continue;const m=t[u],y=!!e.stories[u]?.checkpoint||typeof m?.status=="string"&&Ft.has(m.status);!l.has(u)&&!n.has(u)&&!g.has(u)&&!y&&i("story-worktree-integration-dependency-waiting")}}async function ht(e,t,a){if(!(ze(t,a)?.receipts??[]).some(g=>g.kind==="published-story-reconciliation"))return new Set;const r=await jt(e,a);return new Set(r.map(g=>g.storyId))}function Kt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${ge(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:a,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function $e(e){return ge(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Oe(e){let t;return await me(e.projectRoot,a=>{const s=Z(a,e.epicId);Ie(s);const r=[...s].sort((n,d)=>d.integrationIndex-n.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...s].filter(n=>n.storyId===e.storyId).sort((n,d)=>d.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=Kt({epicId:e.epicId,storyId:e.storyId,index:s.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),Tt(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await p(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await _(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&i("story-worktree-integration-epic-head-raced")}}),t}function ve(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:Le(e.receipt)})}}async function Yt(e){let t,a,s="";const r=Ee(e.projectRoot);try{(typeof e.storyId!="string"||!Ce.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!qt.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const g=await xe(await p(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await xe(await p(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==n&&i("story-worktree-integration-not-root");let d;try{d=await it(r,e.storyId)}catch(h){i(h instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(h.message)?h.message:"story-worktree-integration-authority-invalid")}const{epicId:f,executionBranch:k,storyId:l}=d;s=f;const u=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${k}`,y=await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==y&&i("story-worktree-integration-root-head-mismatch");const C=d.originBinding;(!C||!await _(r,["merge-base","--is-ancestor",C.originHeadSha,y]))&&i("story-worktree-integration-origin-binding-invalid");const b=await Q(r,{required:!0}),S=Z(b,f);Ie(S);const H=S.filter(h=>h.storyId===l).sort((h,R)=>R.integrationIndex-h.integrationIndex),A=b.stories[l]?.checkpoint;if(H[0]?.outcome==="integrated")return ve({storyId:l,epicId:f,outcome:"already-integrated",receipt:H[0],...A?.headSha?{checkpointHeadSha:A.headSha}:{}});const K=Array.isArray(d.story.depends_on)?d.story.depends_on.filter(h=>typeof h=="string"):[],x=await pt(r,b),N=await ht(r,b,f);gt(b,x,f,l,K,N);const j=Object.values(b.storyWorktrees?.entries??{}).filter(h=>h.storyId===l&&h.epicId===f&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));if(A&&typeof A.headSha=="string"){const h=A.headSha,R=await p(r,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed");(W(R,"Neocortex-Story")!==l||!W(R,ke))&&i("story-worktree-integration-checkpoint-not-worktree"),h!==y&&i("story-worktree-integration-epic-head-raced"),he(S,A.baseSha);const oe=await ut(r,l,`recover-${h.slice(0,40)}`,()=>Oe({projectRoot:r,epicId:f,storyId:l,executionBranch:k,before:A.baseSha,after:h,checkpointDigest:$e(A),outcome:"integrated",integratedAt:u})),se=j.length===1?await Ke(r,j[0].leaseId,h):!1;return ve({storyId:l,epicId:f,outcome:"integrated",receipt:oe,checkpointHeadSha:h,worktreeRealigned:se})}const T=Object.values(b.storyWorktrees?.entries??{}).filter(h=>h.storyId===l&&h.epicId===f&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));T.length===0&&i("story-worktree-integration-lease-missing"),T.length>1&&i("story-worktree-integration-lease-ambiguous");const D=T[0];D.executionBranch!==k&&i("story-worktree-integration-lease-invalid");const Y=await new De({projectRoot:r}).probe(D.leaseId);(!Y.ok||Y.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Y.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const B=await p(r,["rev-parse",`refs/heads/${D.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Y.value.headSha!==B&&i("story-worktree-integration-worktree-dirty");const G=await p(r,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed"),L=W(G,ke)===B&&W(G,"Neocortex-Story")===l;let q,M,I,X=!1;if(L){q=await p(r,["rev-parse",`${y}^`],"story-worktree-integration-git-failed"),M=y;const h=W(G,"Neocortex-Bundle-Digest")??"",R=W(G,"Neocortex-Claim-Revision")??"";I=ot({storyId:l,epicId:f,executionBranch:k,baseSha:q,bundleDigest:h,graphRevision:d.graphRevision,claimRevision:R}),he(S,q)}else{he(S,y);const h=await wt(r,d,l,y,B);if(h.kind==="conflict")return await Ye({projectRoot:r,epicId:f,storyId:l,executionBranch:k,epicHead:y,tip:B,conflictPaths:h.conflictPaths,integratedAt:u,chain:H});const R=h.changedPaths;M=h.commitSha,I=h.idempotencyKey,q=y,X=!0,(!await _(r,["diff","--cached","--quiet"])||!await _(r,["diff","--quiet","HEAD","--",...R]))&&i("story-worktree-integration-root-dirty")}const ee=await nt(d,l,M);ee.ok||i(ee.reasonCode);const te=await Q(r,{required:!0}),F=te.epics[f]?.branch_lease,ne=F&&F.ownerStoryId===l&&F.sessionId===I&&F.idempotencyKey===I&&Date.parse(String(F.expiresAt))>Date.now()?F:void 0;F&&!ne&&Date.parse(String(F.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const J=ne??{schemaVersion:1,ownerStoryId:l,sessionId:I,idempotencyKey:I,acquiredAt:u,expiresAt:new Date(Date.parse(u)+rt).toISOString()};t=await We(r,{kind:"direct",storyId:l,sessionId:I,idempotencyKey:I,expiresAt:String(J.expiresAt),persistent:!0,createdAt:String(J.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const U=t;ne||(await me(r,h=>{const R=_e(h,f),oe=R.branch_lease;oe&&Date.parse(String(oe.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(R.origin_binding)!==JSON.stringify(C)&&i("story-worktree-integration-origin-binding-invalid"),R.graph_revision!==d.graphRevision&&i("story-worktree-integration-graph-revision-raced"),R.branch_lease=J},{expectedRevision:te.revision,preCommit:async h=>{await at(U.path,U.owner)||i("story-worktree-integration-lock-raced");const R=Z(h,f);Ie(R),he(R,q),await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==y&&i("story-worktree-integration-epic-head-raced")}}),a=J),X&&((await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==y||await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==y)&&i("story-worktree-integration-epic-head-raced"),await _(r,["merge","--ff-only","--no-edit",M])||i("story-worktree-integration-ff-refused"),await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==M&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let re;const ae=await xt({projectRoot:r,storyId:l,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,preFastForwardAuthorizedWriteSet:d.authorizedWriteSet,afterCheckpointPersist:async()=>{const h=(await Q(r,{required:!0})).stories[l]?.checkpoint;(!h||h.headSha!==M||h.baseSha!==q)&&i("story-worktree-integration-checkpoint-mismatch"),re=await Oe({projectRoot:r,epicId:f,storyId:l,executionBranch:k,before:q,after:M,checkpointDigest:$e(h),outcome:"integrated",integratedAt:u})}});if(!ae.ok)return{ok:!1,reasonCode:ae.reasonCode};const $=ae.value;($.headSha!==M||$.baseSha!==q||!re)&&i("story-worktree-integration-checkpoint-mismatch");const ye=await Ke(r,D.leaseId,M);return ve({storyId:l,epicId:f,outcome:"integrated",receipt:re,checkpointHeadSha:M,worktreeRealigned:ye})}catch(g){if(g instanceof Te)return{ok:!1,reasonCode:g.reasonCode};const n=g instanceof Error?g.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),a&&s){const g=a;await me(r,n=>{const d=_e(n,s),f=d.branch_lease;f&&f.sessionId===g.sessionId&&f.idempotencyKey===g.idempotencyKey&&f.acquiredAt===g.acquiredAt&&(d.branch_lease=null)}).catch(()=>{})}}}const Ge=".neocortex/state.json",Pe=".neocortex",He="state.json",z="story-worktree-integration-state-merge-git-failed";function Be(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const s=a.indexOf(" "),[r,g,n]=a.slice(0,s).split(" ");(s<0||!r||!g||!n)&&i(z),t.push({mode:r,type:g,oid:n,name:a.slice(s+1)})}return t}function Jt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function yt(e,t,a,s){const r=await P(e,["ls-tree","-z",t]);r.code!==0&&i(z);const g=Be(r.stdout).filter(f=>f.name!==a),n=await ft(e,["mktree","-z"],Jt([...g,s])),d=n.stdout.trim();return(n.code!==0||!le.test(d))&&i(z),d}async function qe(e,t){const a=await P(e,["ls-tree","-z",t,"--",Ge]);a.code!==0&&i(z);const s=Be(a.stdout).find(r=>r.name===Ge);return s?((s.type!=="blob"||s.mode!=="100644"&&s.mode!=="100755")&&i("state-merge-input-invalid"),le.test(s.oid)||i(z),s.oid):null}async function Fe(e,t){t===null&&i("state-merge-input-invalid");const a=await P(e,["cat-file","-s",t]),s=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(s)||s<0||s>Mt)&&i(z);const r=await P(e,["cat-file","blob",t]);return r.code!==0&&i(z),r.stdout}async function Ut(e){try{const{projectRoot:t,mergeBase:a,epicHead:s,tip:r,tree:g,storyId:n,epicId:d}=e,f={ok:!0,tree:g,conflictPaths:[...e.conflictPaths],merged:!1},k=await qe(t,a),l=await qe(t,r);if(k===l)return f;const u=await Fe(t,k),m=await Fe(t,await qe(t,s)),y=await Fe(t,l),C=await p(t,["show","--no-patch","--format=%cI",r],z),b=Nt({base:u,epic:m,story:y,storyId:n,epicId:d,aggregateTimestamp:C});if(!b.ok)return{ok:!1,reasonCode:b.reasonCode};const S=e.conflictPaths.filter(E=>E!==Ge),H=await P(t,["ls-tree","-z",g,"--",Pe]);H.code!==0&&i(z);const A=Be(H.stdout).find(E=>E.name===Pe);if(!A||A.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const K=await P(t,["ls-tree","-z",A.oid,"--",He]);K.code!==0&&i(z);const x=Be(K.stdout).find(E=>E.name===He);if(x&&(x.type!=="blob"||x.mode!=="100644"&&x.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const N=await ft(t,["hash-object","-w","--stdin"],b.bytes),j=N.stdout.trim();if((N.code!==0||!le.test(j))&&i(z),x?.oid===j)return{ok:!0,tree:g,conflictPaths:S,merged:!0};const T=await yt(t,A.oid,He,{mode:x?.mode??"100644",type:"blob",oid:j,name:He});return{ok:!0,tree:await yt(t,g,Pe,{mode:A.mode,type:"tree",oid:T,name:Pe}),conflictPaths:S,merged:!0}}catch(t){return t instanceof Te?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:z}}}async function wt(e,t,a,s,r){const{epicId:g,executionBranch:n}=t;await _(e,["merge-base","--is-ancestor",r,s])&&i("story-worktree-integration-range-empty");const d=await p(e,["merge-base",s,r],"story-worktree-integration-unrelated-history"),f=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${d}`,s,r]);f.code!==0&&f.code!==1&&i("story-worktree-integration-git-unsupported");const k=f.stdout.split("\0"),l=k[0]?.trim()??"";le.test(l)||i("story-worktree-integration-git-unsupported");const u=f.code===1?[...new Set(k.slice(1).filter(lt))].sort():[];f.code===1&&u.length===0&&i("story-worktree-integration-git-failed");const m=await Ut({projectRoot:e,mergeBase:d,epicHead:s,tip:r,tree:l,storyId:a,epicId:g,conflictPaths:u});m.ok||i(m.reasonCode);const y=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,Gt)};const C=(await p(e,["diff","--name-only","-z",s,y],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),b=Ct(C,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);b.ok||i(b.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":b.reasonCode===fe.WRITE_SET_FORBIDDEN?fe.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const S=t.governanceMode==="runtime-store"?await Vt(e,g,a,r):void 0,H=S?S.review:Bt(e,a,y);H?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const A=await P(e,["diff","--binary","--full-index",s,y]);A.code!==0&&i("story-worktree-integration-git-failed");const K=A.stdout;K||i("story-worktree-integration-range-empty");const x=ge(K),N=ge([...t.authorizedWriteSet].sort().join("\0")),j=ot({storyId:a,epicId:g,executionBranch:n,baseSha:s,bundleDigest:x,graphRevision:t.graphRevision,claimRevision:N}),T=(await p(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,D=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${g}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${s}`,`Neocortex-Bundle-Digest: ${x}`,`Neocortex-Review-Artifact-Digest: ${H.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${N}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Lt(t.rootMemoryEffect)}`]:[],...S?[`${st}: ${S.governanceDigest}`]:[],`${ke}: ${r}`],E=(await p(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");E.length!==6&&i("story-worktree-integration-git-failed");const Y=await p(e,["commit-tree",y,"-p",s,"-m",T,"-m",`Story: ${a}`,"-m",D.join(`
|
|
3
|
+
`)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:E[0],GIT_AUTHOR_EMAIL:E[1],GIT_AUTHOR_DATE:E[2],GIT_COMMITTER_NAME:E[3],GIT_COMMITTER_EMAIL:E[4],GIT_COMMITTER_DATE:E[5]});return le.test(Y)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:Y,changedPaths:C,idempotencyKey:j}}async function Vt(e,t,a,s){const r=await p(e,["show","--no-patch","--format=%B",s],"story-worktree-integration-git-failed"),g=W(r,st);g===void 0&&i("story-worktree-integration-governance-trailer-missing");const n=Wt({projectRoot:e,epicId:t,storyId:a});n.ok||i(n.reasonCode===fe.UNSAFE?n.reasonCode:fe.MISMATCH);const d=n.value.receipt.governanceDigest;g!==d&&i(fe.MISMATCH);const f=n.value.files.get(zt(a));return f||i(fe.MISMATCH),{governanceDigest:d,review:Ht(a,f)}}async function pt(e,t){const a=JSON.parse(await St(bt(e,".neocortex","state.json"),"utf8")),r=Ot(a,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function ut(e,t,a,s){const r=await We(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||i(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await s()}finally{await je(r.path,r.owner).catch(()=>{})}}async function Ke(e,t,a){const s=await new De({projectRoot:e}).probe(t);return!s.ok||s.value.ownership!=="proven"||s.value.clean!==!0?!1:_(s.value.entry.worktreePath,["reset","--keep",a])}async function Ye(e){const t=ge(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),a=e.chain[0];if(a?.outcome==="conflict-reopened"&&a.epicHeadAfterSha===e.epicHead&&a.checkpointDigest===t)return ve({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const s=()=>Oe({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await s():await ut(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,s);return ve({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Xt=64,Qt="@ornexus/neocortex",Je=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Je)if(!lt(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Zt(e){return _(e,["clean","-X","-f","-q","--",...Je])}async function er(e,t){const a=await P(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Qt?Je:[]}catch{return[]}}function tr(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function yr(e){let t,a,s="",r=0,g;const n=Ee(e.projectRoot);try{const d=e.storyIds;(!Array.isArray(d)||d.length===0||d.length>Xt||new Set(d).size!==d.length||d.some(o=>typeof o!="string"||!Ce.test(o)))&&i("story-worktree-wave-stories-invalid");const f=await xe(await p(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),k=await xe(await p(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));f!==k&&i("story-worktree-integration-not-root");const l=new Map;for(const o of d)try{l.set(o,await it(n,o))}catch(c){i(c instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(c.message)?c.message:"story-worktree-integration-authority-invalid")}const u=l.get(d[0]),{epicId:m,executionBranch:y}=u;for(const o of l.values())(o.epicId!==m||o.executionBranch!==y||o.graphRevision!==u.graphRevision||JSON.stringify(o.originBinding)!==JSON.stringify(u.originBinding))&&i("story-worktree-wave-epic-mixed");s=m;const C=new Date(e.nowIso??Date.now()).toISOString(),b=`refs/heads/${y}`,S=await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing");(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==S||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==y)&&i("story-worktree-integration-root-head-mismatch");const H=u.originBinding;(!H||!await _(n,["merge-base","--is-ancestor",H.originHeadSha,S]))&&i("story-worktree-integration-origin-binding-invalid");const A=o=>{const c=l.get(o).story;return Array.isArray(c.depends_on)?c.depends_on.filter(w=>typeof w=="string"):[]},K=new Map(d.map((o,c)=>[o,c]));d.forEach((o,c)=>{for(const w of A(o)){const v=K.get(w);v!==void 0&&v>=c&&i("story-worktree-wave-order-invalid")}});const x=await Q(n,{required:!0}),N=Z(x,m);Ie(N);const j=o=>N.filter(c=>c.storyId===o).sort((c,w)=>w.integrationIndex-c.integrationIndex)[0],T=d.filter(o=>j(o)?.outcome!=="integrated"),D=new Map(d.filter(o=>!T.includes(o)).map(o=>{const c=j(o),w=x.stories[o]?.checkpoint;return[o,Object.freeze({storyId:o,outcome:"already-integrated",receiptDigest:Le(c),...w?.headSha?{checkpointHeadSha:w.headSha}:{}})]})),E=o=>({ok:!0,value:Object.freeze({epicId:m,...o,gateRuns:r,stories:Object.freeze(d.map(c=>D.get(c)??Object.freeze({storyId:c,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(T.length===0)return E({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0});const Y=new Set(T),B=[];let G=S;for(let o=0;o<T.length;o++){const c=await p(n,["show","--no-patch","--format=%B",G],"story-worktree-integration-git-failed"),w=W(c,"Neocortex-Story");if(!w||!Y.has(w)||!W(c,ke))break;B.unshift(G),G=await p(n,["rev-parse",`${G}^`],"story-worktree-integration-git-failed")}const L=G;he(N,L);const q=await pt(n,x),M=await ht(n,x,m),I=[];let X,ee=L;for(const[o,c]of T.entries()){const w=l.get(c);gt(x,q,m,c,A(c),M,new Set(T.slice(0,o)));const v=Object.values(x.storyWorktrees?.entries??{}).filter(V=>V.storyId===c&&V.epicId===m&&V.state==="active"),O=x.stories[c]?.checkpoint;if(O&&typeof O.headSha=="string"){const V=O.headSha,et=await p(n,["show","--no-patch","--format=%B",V],"story-worktree-integration-git-failed");(W(et,"Neocortex-Story")!==c||!W(et,ke))&&i("story-worktree-integration-checkpoint-not-worktree"),(O.baseSha!==ee||B[o]!==V)&&i("story-worktree-integration-checkpoint-mismatch");const It=(await p(n,["diff-tree","--no-commit-id","--name-only","-r","-z",V],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);I.push({storyId:c,sha:V,changedPaths:It,...v.length===1?{leaseId:v[0].leaseId}:{},...typeof O.graphRevision=="string"?{checkpointGraphRevision:O.graphRevision}:{}}),ee=V;continue}v.length===0&&i("story-worktree-integration-lease-missing"),v.length>1&&i("story-worktree-integration-lease-ambiguous");const Ae=v[0];Ae.executionBranch!==y&&i("story-worktree-integration-lease-invalid");const Re=await new De({projectRoot:n}).probe(Ae.leaseId);(!Re.ok||Re.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Re.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const Me=await p(n,["rev-parse",`refs/heads/${Ae.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Re.value.headSha!==Me&&i("story-worktree-integration-worktree-dirty");const de=await wt(n,w,c,ee,Me);if(de.kind==="conflict"){o<B.length&&i("story-worktree-wave-resume-mismatch"),X={storyId:c,tip:Me,conflictPaths:de.conflictPaths};break}o<B.length&&B[o]!==de.commitSha&&i("story-worktree-wave-resume-mismatch"),I.push({storyId:c,sha:de.commitSha,changedPaths:de.changedPaths,leaseId:Ae.leaseId}),ee=de.commitSha}if(I.length<B.length&&i("story-worktree-wave-resume-mismatch"),I.length===0){const o=X,c=await Ye({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:y,epicHead:S,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:C,chain:N.filter(w=>w.storyId===o.storyId).sort((w,v)=>v.integrationIndex-w.integrationIndex)});return c.ok?(D.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:c.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])})),E({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0})):{ok:!1,reasonCode:c.reasonCode,gateRuns:r}}const te=new Map;for(const o of I){if(o.checkpointGraphRevision!==void 0){const w=await p(n,["show","--no-patch","--format=%B",o.sha],"story-worktree-integration-git-failed"),v=W(w,"Neocortex-Graph-Revision");v===void 0&&i("direct-yolo-trailer-missing:neocortex-graph-revision"),v!==o.checkpointGraphRevision&&i("direct-yolo-trailer-mismatch:neocortex-graph-revision"),te.set(o.sha,v);continue}const c=await nt(l.get(o.storyId),o.storyId,o.sha);c.ok||i(c.reasonCode),te.set(o.sha,c.value.graphRevision)}const F=I[I.length-1].sha,ne=[...new Set(I.flatMap(o=>o.changedPaths))].sort();(!await _(n,["diff","--cached","--quiet"])||!await _(n,["diff","--quiet","HEAD","--",...ne]))&&i("story-worktree-integration-root-dirty");const J=tr(I.length),U=ge(["p205-wave-lease-v1",m,y,L,...I.map(o=>o.sha)].join("\0")),re=I[0].storyId,ae=await Q(n,{required:!0}),$=ae.epics[m]?.branch_lease,ye=$&&$.ownerStoryId===re&&$.sessionId===U&&$.idempotencyKey===U&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!ye&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const h=ye??{schemaVersion:1,ownerStoryId:re,sessionId:U,idempotencyKey:U,acquiredAt:C,expiresAt:new Date(Date.parse(C)+rt*J).toISOString()};t=await We(n,{kind:"direct",storyId:re,sessionId:U,idempotencyKey:U,expiresAt:String(h.expiresAt),persistent:!0,createdAt:String(h.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const R=t;ye||await me(n,o=>{const c=_e(o,m),w=c.branch_lease;w&&Date.parse(String(w.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(c.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),c.graph_revision!==u.graphRevision&&i("story-worktree-integration-graph-revision-raced"),c.branch_lease=h},{expectedRevision:ae.revision,preCommit:async o=>{await at(R.path,R.owner)||i("story-worktree-integration-lock-raced");const c=Z(o,m);Ie(c),he(c,L),await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing")!==S&&i("story-worktree-integration-epic-head-raced")}}),a=h;const oe=new Set(I.map(o=>o.sha));let se=!0;if(e.push&&B.length>0){const o=(await P(n,["ls-remote","--heads",e.remote??"origin",b])).stdout.split(/\s+/)[0]??"";le.test(o)&&await _(n,["merge-base","--is-ancestor",B[0],o])&&(se=!1)}let ce=S;const Se=async o=>{if((await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==ce||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ce||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==y)&&i("story-worktree-integration-epic-head-raced"),ce===o)return;const c=await _(n,["merge-base","--is-ancestor",ce,o]);!c&&(!se||!oe.has(ce))&&i("story-worktree-wave-pushed-immovable"),(!(c?await _(n,["merge","--ff-only","--no-edit",o]):await _(n,["reset","--keep",o]))||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==o||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==o)&&i("story-worktree-integration-ff-refused"),ce=o};g=se?{epicRef:b,base:L,owned:oe}:void 0,await Se(F),await e.afterWaveFastForward?.();const mt=[...new Set(I.map(o=>te.get(o.sha)))],kt=await er(n,L),Ne=async()=>{kt.length!==0&&(await(e.cleanBuildOutputs??Zt)(n)||i("story-worktree-wave-clean-failed"))},Ue=async o=>{const c=I[o];await Se(c.sha),r>=J&&i("story-worktree-wave-gate-cap-exceeded"),r>0&&await Ne(),r++;const w=await Dt({projectRoot:n,headSha:c.sha,storyId:c.storyId,graphRevisions:mt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==c.sha||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==c.sha||!await _(n,["diff","--cached","--quiet"])||!await _(n,["diff","--quiet","HEAD","--",...ne]))&&i("story-worktree-integration-epic-head-raced"),!w.ok&&w.kind==="infrastructure"&&i(w.reasonCode),w},be=await Ue(I.length-1);let Ve=I.length-1,Xe=be.ok?be.authorities:void 0,we,pe;if(!be.ok){se||i("story-worktree-wave-gate-failed-pushed");let o=-1,c=I.length-1;for(pe=be.reasonCode;c-o>1;){const v=Math.floor((o+c)/2),O=await Ue(v);O.ok?(o=v,Xe=O.authorities):(c=v,pe=O.reasonCode)}we=c,Ve=o;const w=I[c].storyId;if(D.set(w,Object.freeze({storyId:w,outcome:"gate-failed",reasonCode:pe})),o<0)return await Se(L),await Ne(),g=void 0,E({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:w,failureReasonCode:pe,epicHeadBeforeSha:S,epicHeadAfterSha:L,gateRunCap:J});await Se(I[o].sha),await Ne()}const ie=I.slice(0,Ve+1),ue=ie[ie.length-1].sha,Qe=Rt({epicId:m,executionBranch:y,waveHeadSha:ue,waveStoryIds:ie.map(o=>o.storyId),waveCommitShas:ie.map(o=>o.sha)});e.push&&(g=void 0,await _t(n,e.remote??"origin",y,ue)||i("story-worktree-wave-remote-head-mismatch")),g=void 0;const Ze=[];for(const[o,c]of ie.entries()){const w=o===0?L:ie[o-1].sha,v=await Et({projectRoot:n,storyId:c.storyId,headSha:c.sha,coverage:Qe,authorities:Xe,expectedLease:h,physicalLock:R,authorizedWriteSet:l.get(c.storyId).authorizedWriteSet,expectedGraphRevision:te.get(c.sha),...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});v.ok||i(v.reasonCode),(v.value.headSha!==c.sha||v.value.baseSha!==w)&&i("story-worktree-integration-checkpoint-mismatch");const O=await Oe({projectRoot:n,epicId:m,storyId:c.storyId,executionBranch:y,before:w,after:c.sha,checkpointDigest:$e(v.value),outcome:"integrated",integratedAt:C,expectedEpicHead:ue});Ze.push(c.storyId),D.set(c.storyId,Object.freeze({storyId:c.storyId,outcome:"integrated",checkpointHeadSha:c.sha,receiptDigest:Le(O)})),await e.afterWaveStoryPersist?.(c.storyId)}if(X&&we===void 0){const o=X,c=await Q(n,{required:!0}),w=await Ye({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:y,epicHead:ue,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:C,chain:Z(c,m).filter(v=>v.storyId===o.storyId).sort((v,O)=>O.integrationIndex-v.integrationIndex),lockHeld:!0});w.ok||i(w.reasonCode),D.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:w.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])}))}for(const o of ie){if(!o.leaseId)continue;const c=await Ke(n,o.leaseId,o.sha);D.set(o.storyId,Object.freeze({...D.get(o.storyId),worktreeRealigned:c}))}return E({outcome:we!==void 0?"gate-failed":X?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ze),...we!==void 0?{failedStoryId:I[we].storyId,failureReasonCode:pe}:{},epicHeadBeforeSha:S,epicHeadAfterSha:ue,qaCoverage:Qe,gateRunCap:J})}catch(d){let f=d instanceof Te?d.reasonCode:d instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(d.message)?d.message:"story-worktree-integration-failed";if(g){const k=g,l=(await P(n,["rev-parse",k.epicRef])).stdout.trim(),u=(await P(n,["rev-parse","HEAD"])).stdout.trim();l!==k.base&&(l!==u||!k.owned.has(l)||!await _(n,["reset","--keep",k.base]))&&(f="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:f,gateRuns:r}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),a&&s){const d=a;await me(n,f=>{const k=_e(f,s),l=k.branch_lease;l&&l.sessionId===d.sessionId&&l.idempotencyKey===d.idempotencyKey&&l.acquiredAt===d.acquiredAt&&(k.branch_lease=null)}).catch(()=>{})}}}async function wr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(f=>typeof f!="string"||!Ce.test(f)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??Yt,s=new Set(e.readyStoryIds),r=Ee(e.projectRoot);let g;try{const f=await Q(r,{required:!0}),k=new Set(t.map(l=>l.split(".")[0]));g=new Set([...k].flatMap(l=>Z(f,l)).filter(l=>l.outcome==="integrated").map(l=>l.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const n=[],d=[];for(const f of t){if(g.has(f))continue;if(!s.has(f))return{results:n,integratedStoryIds:d,stoppedAt:f,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:k,readyStoryIds:l,integrate:u,...m}=e,y=await a({...m,projectRoot:r,storyId:f});if(n.push({storyId:f,result:y}),!y.ok)return{results:n,integratedStoryIds:d,stoppedAt:f,reasonCode:y.reasonCode};if(y.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:d,stoppedAt:f,reasonCode:"integration-conflict-reopened"};d.push(f),g.add(f)}return{results:n,integratedStoryIds:d}}async function pr(e){const t=Ee(e.projectRoot),a=e.manager??new De({projectRoot:t});let s;try{s=await Q(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const g of e.directives){const n=g&&typeof g=="object"&&!Array.isArray(g)?g:void 0,d=typeof n?.storyId=="string"&&Ce.test(n.storyId)?n.storyId:"";if(!d){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const f=Object.values(s.storyWorktrees?.entries??{}).filter(l=>l.storyId===d&&l.state==="active");if(f.length!==1){r.push({storyId:d,ok:!1,reasonCode:f.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const k=await a.sync({leaseId:f[0].leaseId,directive:g});r.push(k.ok?{storyId:d,ok:!0,outcome:k.value.outcome,integratedSha:k.value.integratedSha}:{storyId:d,ok:!1,reasonCode:k.reasonCode,...k.conflictPaths?{conflictPaths:k.conflictPaths}:{}})}return r}export{Gt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,$t as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,Ge as STORY_WORKTREE_STATE_JSON_PATH,Je as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Qt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Xt as STORY_WORKTREE_WAVE_MAX_STORIES,Le as digestStoryWorktreeIntegrationReceipt,Yt as integrateStoryWorktree,yr as integrateStoryWorktreeWave,wr as integrateStoryWorktreesInOrder,Ut as resolveStoryWorktreeStateJsonMerge,er as storyWorktreeWaveBuildOutputPaths,tr as storyWorktreeWaveGateRunCap,pr as syncReleasedDependents};
|
|
@@ -12,6 +12,9 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import type { CacheProvider } from '../types/index.js';
|
|
14
14
|
import { type AuthRecoveryResultV1 } from './host-auth-recovery.js';
|
|
15
|
+
export declare const LICENSE_ACCESS_TOKEN_CACHE_KEY = "neocortex:jwt:token";
|
|
16
|
+
export declare const LICENSE_REFRESH_TOKEN_CACHE_KEY = "neocortex:jwt:refresh_token";
|
|
17
|
+
export declare const LICENSE_REFRESH_TOKEN_TTL_MS: number;
|
|
15
18
|
export interface LicenseClientOptions {
|
|
16
19
|
readonly serverUrl: string;
|
|
17
20
|
readonly licenseKey: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeJwt as l}from"jose";import{NoOpCache as u}from"../types/index.js";import{getMachineFingerprint as f}from"../machine/fingerprint.js";import{CLIENT_VERSION as d}from"../version.js";import{classifyAuthCausalEvidence as h}from"./host-auth-recovery.js";const
|
|
1
|
+
import{decodeJwt as l}from"jose";import{NoOpCache as u}from"../types/index.js";import{getMachineFingerprint as f}from"../machine/fingerprint.js";import{CLIENT_VERSION as d}from"../version.js";import{classifyAuthCausalEvidence as h}from"./host-auth-recovery.js";const k="neocortex:jwt:token",y="neocortex:jwt:refresh_token",R=300,p=10080*60*1e3,a=k,c=y,o=p;class C{serverUrl;licenseKey;cache;clientVersion;machineId;strictReadOnly;causalAuthRecovery;token=null;refreshToken=null;lastRecoveryResult=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new u,this.clientVersion=e.clientVersion??d,this.strictReadOnly=e.strictReadOnly??!1,this.causalAuthRecovery=e.causalAuthRecovery??!1,this.machineId=f({strictReadOnly:this.strictReadOnly})}async getToken(){try{if(this.strictReadOnly){const t=await this.inspectToken();return t.status==="authenticated"?t.token:null}if(this.token){const t=this.checkTokenValidity(this.token);if(t==="valid")return this.token;if(t==="needs-refresh")return this.strictReadOnly?this.token:(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const t=this.checkTokenValidity(e);if(t==="valid")return e;if(t==="needs-refresh")return this.strictReadOnly?e:(await this.refresh())?.token??e;this.token=null}if(this.strictReadOnly)return null;if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const t=await this.refresh();if(t?.token)return t.token;if(this.causalAuthRecovery)return null}return(await this.activate())?.token??null}catch{return null}}async inspectToken(){try{const e=this.token??await this.loadFromCache();if(e){const t=this.checkTokenValidity(e);return t==="valid"?{status:"authenticated",token:e}:{status:"refresh-required",reason:t==="needs-refresh"?"near-expiry":"expired"}}const i=this.refreshToken??await this.loadRefreshTokenFromCache();return i?(this.refreshToken=i,{status:"refresh-required",reason:"expired"}):this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}catch{return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}getLastRecoveryResult(){return this.lastRecoveryResult}refreshRequired(e,i){return this.lastRecoveryResult={status:"refresh-required",cause:e,action:i},null}rememberRecovery(e){return this.lastRecoveryResult=e,null}async activate(){if(this.strictReadOnly)return null;try{const e=this.licenseKey.startsWith("nxk_"),i=e?"activate-key":"activate",t=e?{api_key:this.licenseKey}:{license_key:this.licenseKey},s=await fetch(`${this.serverUrl}/api/v1/license/${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,machine_id:this.machineId,client_version:this.clientVersion})});if(!s.ok){let n="";try{n=String((await s.json()).error??"")}catch{}return this.rememberRecovery(h({kind:"http",status:s.status,...n?{errorCode:n}:{}}))}const r=await s.json();return r.tier!==void 0&&r.tier!=="free"&&r.tier!=="pro"&&r.tier!=="enterprise"?null:(this.token=r.token,this.refreshToken=r.refresh_token??null,await this.cache.set(a,r.token,r.expires_in*1e3).catch(()=>{}),r.refresh_token&&await this.cache.set(c,r.refresh_token,o).catch(()=>{}),{token:r.token,expiresIn:r.expires_in,refreshToken:r.refresh_token,tier:r.tier})}catch{return this.rememberRecovery(h({kind:"transport"}))}}async refresh(e){if(this.strictReadOnly)return null;try{const i=this.refreshToken??await this.loadRefreshTokenFromCache();if(!i)return this.refreshRequired("store-unavailable","retry-later");const t=await fetch(`${this.serverUrl}/api/v1/license/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:i})});if(!t.ok){let r="";try{r=String((await t.json()).error??"")}catch{}return t.status===429?this.refreshRequired("rate-limited","retry-later"):t.status>=500?this.refreshRequired("service-unavailable","retry-later"):r==="invalid_grant"||r==="revoked"?this.refreshRequired("revoked","reactivate"):r==="invalid_scope"||r==="scope_denied"?this.refreshRequired("scope-denied","request-scope"):r==="client_denied"?this.refreshRequired("client-denied","stop"):this.refreshRequired("protocol-invalid","stop")}const s=await t.json();return this.token=s.token,this.refreshToken=s.refresh_token??null,await this.cache.set(a,s.token,s.expires_in*1e3).catch(()=>{}),s.refresh_token&&await this.cache.set(c,s.refresh_token,o).catch(()=>{}),this.lastRecoveryResult={status:"authenticated",generation:0,accessCredential:s.token,expiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()},{token:s.token,expiresIn:s.expires_in,refreshToken:s.refresh_token}}catch{return this.refreshRequired("transport-error","retry-later")}}async forceRefresh(){if(this.strictReadOnly)return null;try{const e=await this.refresh();return e?.token?e.token:this.causalAuthRecovery?null:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const i=l(e);if(!i.exp)return"expired";const t=Math.floor(Date.now()/1e3);return i.exp<=t?"expired":i.exp-t<=R?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(a)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(c);return e&&e.length>0?e:null}catch{return null}}}export{k as LICENSE_ACCESS_TOKEN_CACHE_KEY,y as LICENSE_REFRESH_TOKEN_CACHE_KEY,p as LICENSE_REFRESH_TOKEN_TTL_MS,C as LicenseClient};
|
|
File without changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type YoloopTargetNormalizationReasonCode = 'yoloop-target-unchanged' | 'agent-selector-removed' | 'markdown-link-target-normalized' | 'basename-target-canonicalized' | 'markdown-link-target-malformed' | 'markdown-link-target-ambiguous' | 'markdown-link-target-external' | 'markdown-link-target-unsafe-path' | 'raw-target-malformed' | 'raw-target-external' | 'raw-target-unsafe-path';
|
|
1
|
+
export type YoloopTargetNormalizationReasonCode = 'yoloop-target-unchanged' | 'agent-selector-removed' | 'markdown-link-target-normalized' | 'basename-target-canonicalized' | 'workflow-advisory-root-only' | 'workflow-advisory-invalid' | 'markdown-story-target-normalized' | 'story-target-invalid' | 'markdown-link-target-malformed' | 'markdown-link-target-ambiguous' | 'markdown-link-target-external' | 'markdown-link-target-unsafe-path' | 'raw-target-malformed' | 'raw-target-external' | 'raw-target-unsafe-path';
|
|
2
2
|
export interface ParsedYoloopInvocation {
|
|
3
3
|
readonly triggerToken: string;
|
|
4
4
|
readonly remainder: string;
|
|
@@ -11,7 +11,7 @@ export type YoloopTargetNormalizationResult = {
|
|
|
11
11
|
readonly reasonCodes: readonly YoloopTargetNormalizationReasonCode[];
|
|
12
12
|
} | {
|
|
13
13
|
readonly ok: false;
|
|
14
|
-
readonly errorCode: 'INVALID_YOLOOP_TARGET';
|
|
14
|
+
readonly errorCode: 'INVALID_YOLOOP_TARGET' | 'INVALID_YOLO_TARGET';
|
|
15
15
|
readonly reasonCode: YoloopTargetNormalizationReasonCode;
|
|
16
16
|
readonly message: string;
|
|
17
17
|
};
|
|
@@ -21,4 +21,10 @@ export interface NormalizeYoloopTargetOptions {
|
|
|
21
21
|
export declare function parseYoloopInvocation(args: unknown): ParsedYoloopInvocation | null;
|
|
22
22
|
export declare function isYoloopInvocation(args: unknown): boolean;
|
|
23
23
|
export declare function normalizeYoloopTargetArgs(args: unknown, options?: NormalizeYoloopTargetOptions): YoloopTargetNormalizationResult;
|
|
24
|
+
/**
|
|
25
|
+
* Compatibility for explicitly decorated file invocations. Existing inline
|
|
26
|
+
* YOLO stories and canonical native task prompts keep their original bytes.
|
|
27
|
+
*/
|
|
28
|
+
export declare function normalizeYoloStoryTargetArgs(args: unknown): YoloopTargetNormalizationResult;
|
|
29
|
+
export declare function normalizeWorkflowTargetArgs(args: unknown): YoloopTargetNormalizationResult;
|
|
24
30
|
export declare function extractYoloopTargetPath(args: unknown, projectRoot?: string): string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as z}from"node:fs";import{resolve as T}from"node:path";import{formatFrontmatterDiagnostic as W}from"../errors/frontmatter-diagnostics.js";const x=/^\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)(?=\s|$)/i,b=/^\*?yolo(?=\s|$)/i,C=/^@neocortex(?:-root)?(?![-\w])\s*/i,v=/\[[^\]\r\n]*\]\(([^)\r\n]+)\)/g,P=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*\/?$/,Y=/^epic-[A-Za-z0-9._-]+\.md$/i,R=/^(?:P[0-9]+|EPIC-[0-9]+)$/i,$=/^(?:[ \t]+--[a-z][a-z0-9-]*)*$/,Z=/^docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md$/,j=/^(?:[ \t]+(branchless-preparation|story-worktree-phase-1|story-worktree-phase-2))?$/,E=/[ \t]+—(?=[ \t]|$)/u,D=2048;function w(e){return O(e,x)}function O(e,t){if(typeof e!="string")return null;let r=e.trimStart(),n=!1;const o=r.match(C);o&&(r=r.slice(o[0].length).trimStart(),n=!0);const s=r.match(t);return s?Object.freeze({triggerToken:s[0],remainder:r.slice(s[0].length).trim(),agentSelectorRemoved:n}):null}function G(e){return w(e)!==null}function a(e,t="INVALID_YOLOOP_TARGET"){return Object.freeze({ok:!1,errorCode:t,reasonCode:e,message:`${t}: ${W(e)}`})}function _(e){let t=e.trim().replace(/^@/,"").replace(/^\.\//,"");if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)||t.startsWith("//"))return{ok:!1,failure:"external"};if(t.startsWith("/")||t.startsWith("~")||/^[A-Za-z]:[\\/]/.test(t)||t.includes("\\")||t.includes("\0"))return{ok:!1,failure:"unsafe-path"};const r=t.split("/").filter(Boolean);return!t||!P.test(t)||r.some(n=>n==="."||n==="..")?{ok:!1,failure:"unsafe-path"}:!t.endsWith("/")&&!t.toLowerCase().endsWith(".md")?{ok:!1,failure:"malformed"}:(t=t.replace(/^\.\//,""),{ok:!0,target:t})}function N(e){return`markdown-link-target-${e}`}function F(e){return`raw-target-${e}`}function B(e,t){return e.startsWith("@")||t.includes("/")||t.includes("\\")||t.startsWith(".")||t.startsWith("~")||t.toLowerCase().endsWith(".md")||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function L(e,t){if(!t||!Y.test(e)||z(T(t,e)))return e;const r=`docs/epics/${e}`;return z(T(t,r))?r:e}function p(e){return Object.freeze([...e])}function M(e){return Buffer.byteLength(e,"utf8")>D||!new RegExp("\\p{L}","u").test(e)||/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}`\\]/u.test(e)||/\$\(|\$\{|&&|\|\||:\/\//u.test(e)||/(?:^|[^\p{L}\p{N}_])(?:--|-[a-z]|\*[a-z]|@[a-z./~])/iu.test(e)||/(?:^|[^\p{L}\p{N}_])(?:docs\/(?:epics|stories)\/|epic-[a-z0-9._-]+\.md\b|[a-z0-9._-]+\.story\.md\b)/iu.test(e)?!1:!e.includes("](")&&!/^(?:P[0-9]+(?:\.[0-9]+)*|EPIC-[0-9]+)[.!?]*$/i.test(e)}function I(e){const t=E.exec(e);if(!t)return{prefix:e,hasAdvisory:!1};const r=e.slice(t.index+t[0].length).replace(/^[ \t]+/u,"");return M(r)?{prefix:e.slice(0,t.index),hasAdvisory:!0}:null}function k(e){return Object.freeze({ok:!0,args:typeof e=="string"?e:"",changed:!1,reasonCodes:p(["yoloop-target-unchanged"])})}function V(e){const t=e.match(/^(\S+)(.*)$/u);return!t||!$.test(t[2])?null:{targetToken:t[1],flags:t[2]}}function S(e,t={}){const r=w(e);if(!r)return k(e);const n=[];r.agentSelectorRemoved&&n.push("agent-selector-removed");const o=r.remainder;if(!o){const i=r.triggerToken;return Object.freeze({ok:!0,args:i,changed:i!==e,reasonCodes:p(n.length>0?n:["yoloop-target-unchanged"])})}const s=[...o.matchAll(v)],f=o.startsWith("[")||o.includes("](");if(s.length>1)return a("markdown-link-target-ambiguous");if(f&&s.length===0)return a("markdown-link-target-malformed");const c=s[0];if(c&&c.index!==0)return a("markdown-link-target-ambiguous");const h=I(c?o.slice(c[0].length):o);if(!h)return a("workflow-advisory-invalid");const{prefix:l,hasAdvisory:d}=h;if(d&&n.push("workflow-advisory-root-only"),c){if(!$.test(l))return a("markdown-link-target-ambiguous");const i=_(c[1]);if(!i.ok)return a(N(i.failure));if(d&&i.target.endsWith("/"))return a("workflow-advisory-invalid");const m=L(i.target,t.projectRoot);return n.push("markdown-link-target-normalized"),m!==i.target&&n.push("basename-target-canonicalized"),Object.freeze({ok:!0,args:`${r.triggerToken} @${m}${l}`,changed:!0,reasonCodes:p(n)})}const u=V(l);if(d&&!u)return a("workflow-advisory-invalid");if(u){const i=u.targetToken.replace(/^@/,"");let m=i;if(B(u.targetToken,i)&&!R.test(i)){const A=_(i);if(!A.ok)return a(F(A.failure));m=A.target}if(d&&!R.test(m)&&!m.toLowerCase().endsWith(".md"))return a("workflow-advisory-invalid");const y=L(m,t.projectRoot);if(y!==i)return n.push("basename-target-canonicalized"),Object.freeze({ok:!0,args:`${r.triggerToken} @${y}${u.flags}`,changed:!0,reasonCodes:p(n)})}const g=`${r.triggerToken}${l?` ${l}`:""}`;return Object.freeze({ok:!0,args:g,changed:g!==e,reasonCodes:p(n.length>0?n:["yoloop-target-unchanged"])})}function K(e){const t=O(e,b);if(!t)return k(e);const{remainder:r}=t,n=r.startsWith("["),o=r.match(/^\S+/u)?.[0];if(!n&&(!o||!/^(?:@?(?:\.\/)?docs\/stories\/|\S+\.story\.md$)/.test(o))||!n&&!E.test(r))return k(e);const s=[...r.matchAll(v)],f=()=>a("story-target-invalid","INVALID_YOLO_TARGET");if(s.length>1||n&&s[0]?.index!==0||!n&&s.length>0)return f();const c=s[0],h=c?.[1]??o,l=_(h);if(!l.ok||!Z.test(l.target))return f();const d=I(r.slice(c?c[0].length:h.length));if(!d)return a("workflow-advisory-invalid","INVALID_YOLO_TARGET");const u=j.exec(d.prefix);if(!u)return f();const g=[];t.agentSelectorRemoved&&g.push("agent-selector-removed"),c&&g.push("markdown-story-target-normalized"),d.hasAdvisory&&g.push("workflow-advisory-root-only");const i=u[1]?` ${u[1]}`:"";return Object.freeze({ok:!0,args:`*${t.triggerToken.replace(/^\*/,"").toLowerCase()} @${l.target}${i}`,changed:!0,reasonCodes:p(g)})}function q(e){return G(e)?S(e):K(e)}function Q(e,t){const r=S(e,{projectRoot:t});if(!r.ok)return null;const n=w(r.args);if(!n?.remainder)return null;const o=n.remainder.match(/(?:^|\s)@([^\s]+)/);if(o)return o[1];const s=n.remainder.split(/\s+/).find(f=>f.length>0&&!f.startsWith("-"));return s?s.replace(/^(?:"|')|(?:"|')$/g,""):null}export{Q as extractYoloopTargetPath,G as isYoloopInvocation,q as normalizeWorkflowTargetArgs,K as normalizeYoloStoryTargetArgs,S as normalizeYoloopTargetArgs,w as parseYoloopInvocation};
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* never reads protected response fields, project state, clocks, or environment.
|
|
6
6
|
*/
|
|
7
7
|
import { createHash } from 'node:crypto';
|
|
8
|
+
import { DIAGNOSE_SCOPED_CONTINUATION_SCHEMA } from '../invocation/diagnose-degraded-continuation.js';
|
|
8
9
|
export const COMPATIBILITY_OFFER_SCHEMA = 'CompatibilityOffer/1.0';
|
|
9
10
|
export const COMPATIBILITY_RESULT_SCHEMA = 'CompatibilityResult/1.0';
|
|
10
11
|
export const RELEASE_LIFECYCLE_SCHEMA = 'ReleaseLifecycle/1.0';
|
|
@@ -53,6 +54,7 @@ export const COMPATIBILITY_CAPABILITIES = Object.freeze({
|
|
|
53
54
|
* `story-worktree-state-untracked` fallback for such projects.
|
|
54
55
|
*/
|
|
55
56
|
STORY_GOVERNANCE_RUNTIME_STORE: 'story-governance-runtime-store-v1',
|
|
57
|
+
DIAGNOSE_SCOPED_CONTINUATION: 'diagnose-scoped-continuation-v2',
|
|
56
58
|
});
|
|
57
59
|
/**
|
|
58
60
|
* P228.18: closed host enum for the private-execution envelope, one value per
|
|
@@ -126,6 +128,7 @@ export const COMPATIBILITY_SCHEMAS = Object.freeze({
|
|
|
126
128
|
RELEASE_LIFECYCLE: RELEASE_LIFECYCLE_SCHEMA,
|
|
127
129
|
RELEASE_BLOCKED: 'ReleaseBlockedResult/1.0',
|
|
128
130
|
REVIEW_RECONCILIATION: 'ReviewReconciliation/1',
|
|
131
|
+
DIAGNOSE_SCOPED_CONTINUATION: DIAGNOSE_SCOPED_CONTINUATION_SCHEMA,
|
|
129
132
|
});
|
|
130
133
|
export const COMPATIBILITY_REASON_CODES = Object.freeze({
|
|
131
134
|
COMPATIBLE: 'compatibility-compatible',
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/** Generated by scripts/generate-public-catalog-projections.mjs. Do not edit. */
|
|
2
2
|
export const PUBLIC_PROJECTION_BUNDLE = {
|
|
3
3
|
"schemaVersion": "PublicProjectionBundle/1.0",
|
|
4
|
-
"generationId": "sha256:
|
|
5
|
-
"sourceHash": "
|
|
6
|
-
"catalogHash": "
|
|
7
|
-
"publicProjectionHash": "
|
|
8
|
-
"stageProjectionHash": "
|
|
9
|
-
"compilationHash": "
|
|
4
|
+
"generationId": "sha256:137c29f9194f93ba83d457dcd67a4df28f709c8c2bb42e883cb86553a03b4a04",
|
|
5
|
+
"sourceHash": "137c29f9194f93ba83d457dcd67a4df28f709c8c2bb42e883cb86553a03b4a04",
|
|
6
|
+
"catalogHash": "0f452979cb84c34476fd478379ee5c680d670f31065fb5ac51f19d1160f63c89",
|
|
7
|
+
"publicProjectionHash": "552f6aa4b4e6d121be460f9cde0c3bc0ef2284fcbd6d780ade4860d5e4032ed7",
|
|
8
|
+
"stageProjectionHash": "3492958695bf9d80c4db5e0ba63cf89f1b826df8282f24600018651ecabdaa3b",
|
|
9
|
+
"compilationHash": "ef6dbdd72a65ae50ea6379e04ab5381a91a2107c714986354f6f59a8ea53583c",
|
|
10
10
|
"registry": {
|
|
11
11
|
"version": "1.0.0",
|
|
12
12
|
"checksum": "184a2d616e0734fd3173d60889d74bae031280513831ec1f0a3a8c36959d2994"
|
|
@@ -16,41 +16,41 @@ export const PUBLIC_PROJECTION_BUNDLE = {
|
|
|
16
16
|
"kind": "catalog",
|
|
17
17
|
"schemaVersion": "ExecutableGraphCatalogPublicProjection/1.0",
|
|
18
18
|
"relativePath": "catalog.json",
|
|
19
|
-
"sha256": "
|
|
19
|
+
"sha256": "cef5eeebd75076c029e46bca28450eacbe329cb0f57151f6bc40faaecc4affdf",
|
|
20
20
|
"entryCount": 97,
|
|
21
|
-
"generationId": "sha256:
|
|
21
|
+
"generationId": "sha256:137c29f9194f93ba83d457dcd67a4df28f709c8c2bb42e883cb86553a03b4a04"
|
|
22
22
|
},
|
|
23
23
|
{
|
|
24
24
|
"kind": "commands",
|
|
25
25
|
"schemaVersion": "CommandRegistryPublicProjection/1.0",
|
|
26
26
|
"relativePath": "commands.json",
|
|
27
|
-
"sha256": "
|
|
27
|
+
"sha256": "38e967e221ebab7605009c5113cdbd2f6b5b0243f17fd1006191c932a08c0779",
|
|
28
28
|
"entryCount": 62,
|
|
29
|
-
"generationId": "sha256:
|
|
29
|
+
"generationId": "sha256:137c29f9194f93ba83d457dcd67a4df28f709c8c2bb42e883cb86553a03b4a04"
|
|
30
30
|
},
|
|
31
31
|
{
|
|
32
32
|
"kind": "progress-view",
|
|
33
33
|
"schemaVersion": "ProgressViewContractProjection/1.0",
|
|
34
34
|
"relativePath": "progress-view.json",
|
|
35
|
-
"sha256": "
|
|
35
|
+
"sha256": "92e8e5f2866ad8e51839ba089db703f02ee2391f830e0baa87735719f442dd0b",
|
|
36
36
|
"entryCount": 1,
|
|
37
|
-
"generationId": "sha256:
|
|
37
|
+
"generationId": "sha256:137c29f9194f93ba83d457dcd67a4df28f709c8c2bb42e883cb86553a03b4a04"
|
|
38
38
|
},
|
|
39
39
|
{
|
|
40
40
|
"kind": "stages",
|
|
41
41
|
"schemaVersion": "ExecutableGraphStageProjection/1.0",
|
|
42
42
|
"relativePath": "stages.json",
|
|
43
|
-
"sha256": "
|
|
43
|
+
"sha256": "f2fe325243c432718c2861a726fb2a53ee9c886f715acfd51ca7c82c92f68fd3",
|
|
44
44
|
"entryCount": 85,
|
|
45
|
-
"generationId": "sha256:
|
|
45
|
+
"generationId": "sha256:137c29f9194f93ba83d457dcd67a4df28f709c8c2bb42e883cb86553a03b4a04"
|
|
46
46
|
},
|
|
47
47
|
{
|
|
48
48
|
"kind": "surfaces",
|
|
49
49
|
"schemaVersion": "PublicProjectionSurfaces/1.0",
|
|
50
50
|
"relativePath": "surfaces.json",
|
|
51
|
-
"sha256": "
|
|
51
|
+
"sha256": "d38132db0ad2986acf9452cab72e5655d6f49e6aad4aab06c95245e0a16cf141",
|
|
52
52
|
"entryCount": 6,
|
|
53
|
-
"generationId": "sha256:
|
|
53
|
+
"generationId": "sha256:137c29f9194f93ba83d457dcd67a4df28f709c8c2bb42e883cb86553a03b4a04"
|
|
54
54
|
}
|
|
55
55
|
],
|
|
56
56
|
"compatibility": {
|
|
@@ -143,7 +143,7 @@ export const PUBLIC_PROJECTION_BUNDLE = {
|
|
|
143
143
|
}
|
|
144
144
|
],
|
|
145
145
|
"publicSafe": true,
|
|
146
|
-
"bundleHash": "
|
|
146
|
+
"bundleHash": "18f2220180f7ed7325900c609a29ad61ad66bf7fecfb55e0b441ef2cd55e886e"
|
|
147
147
|
};
|
|
148
148
|
export const PUBLIC_PROJECTION_GENERATION_ID = PUBLIC_PROJECTION_BUNDLE.generationId;
|
|
149
149
|
export const PUBLIC_PROJECTION_BUNDLE_HASH = PUBLIC_PROJECTION_BUNDLE.bundleHash;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export declare const DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED = "DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED";
|
|
2
2
|
export declare const DIAGNOSE_DEGRADED_CONTINUATION_INVALID = "DIAGNOSE_DEGRADED_CONTINUATION_INVALID";
|
|
3
|
+
export declare const DIAGNOSE_SCOPED_CONTINUATION_SCHEMA: "DiagnoseDegradedContinuation/2.0";
|
|
3
4
|
export interface DiagnoseDegradedContinuationV1 {
|
|
4
5
|
readonly schemaVersion: 'DiagnoseDegradedContinuation/1.0';
|
|
5
6
|
readonly outcome: 'degraded-continue';
|
|
@@ -10,5 +11,16 @@ export interface DiagnoseDegradedContinuationV1 {
|
|
|
10
11
|
readonly readOnly: true;
|
|
11
12
|
readonly publicSafe: true;
|
|
12
13
|
}
|
|
14
|
+
export interface DiagnoseDegradedContinuationV2 extends Omit<DiagnoseDegradedContinuationV1, 'schemaVersion' | 'reasonCode' | 'nextAction'> {
|
|
15
|
+
readonly schemaVersion: typeof DIAGNOSE_SCOPED_CONTINUATION_SCHEMA;
|
|
16
|
+
readonly reasonCode: 'diagnose-readonly-evidence-continuation';
|
|
17
|
+
readonly nextAction: 'inspect-authorized-read-only-evidence';
|
|
18
|
+
readonly localEvidence: 'public-project';
|
|
19
|
+
readonly remoteEvidence: 'independently-authorized-scoped-reader';
|
|
20
|
+
readonly memoryUpdate: 'separate-explicit-command';
|
|
21
|
+
}
|
|
22
|
+
export type DiagnoseDegradedContinuation = DiagnoseDegradedContinuationV1 | DiagnoseDegradedContinuationV2;
|
|
13
23
|
export declare function createDiagnoseDegradedContinuation(): DiagnoseDegradedContinuationV1;
|
|
14
|
-
|
|
24
|
+
/** This handoff carries categories only; it supplies no connector or effect authorization. */
|
|
25
|
+
export declare function createDiagnoseScopedDegradedContinuation(): DiagnoseDegradedContinuationV2;
|
|
26
|
+
export declare function assertDiagnoseDegradedContinuation(value: unknown): DiagnoseDegradedContinuation;
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
export const DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED = 'DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED';
|
|
2
2
|
export const DIAGNOSE_DEGRADED_CONTINUATION_INVALID = 'DIAGNOSE_DEGRADED_CONTINUATION_INVALID';
|
|
3
|
-
const
|
|
4
|
-
'schemaVersion', 'outcome', 'terminal', 'reasonCode', 'nextAction',
|
|
5
|
-
'continuationOwner', 'readOnly', 'publicSafe',
|
|
6
|
-
];
|
|
3
|
+
export const DIAGNOSE_SCOPED_CONTINUATION_SCHEMA = 'DiagnoseDegradedContinuation/2.0';
|
|
7
4
|
export function createDiagnoseDegradedContinuation() {
|
|
8
5
|
return Object.freeze({
|
|
9
6
|
schemaVersion: 'DiagnoseDegradedContinuation/1.0',
|
|
@@ -16,6 +13,18 @@ export function createDiagnoseDegradedContinuation() {
|
|
|
16
13
|
publicSafe: true,
|
|
17
14
|
});
|
|
18
15
|
}
|
|
16
|
+
/** This handoff carries categories only; it supplies no connector or effect authorization. */
|
|
17
|
+
export function createDiagnoseScopedDegradedContinuation() {
|
|
18
|
+
return Object.freeze({
|
|
19
|
+
...createDiagnoseDegradedContinuation(),
|
|
20
|
+
schemaVersion: DIAGNOSE_SCOPED_CONTINUATION_SCHEMA,
|
|
21
|
+
reasonCode: 'diagnose-readonly-evidence-continuation',
|
|
22
|
+
nextAction: 'inspect-authorized-read-only-evidence',
|
|
23
|
+
localEvidence: 'public-project',
|
|
24
|
+
remoteEvidence: 'independently-authorized-scoped-reader',
|
|
25
|
+
memoryUpdate: 'separate-explicit-command',
|
|
26
|
+
});
|
|
27
|
+
}
|
|
19
28
|
export function assertDiagnoseDegradedContinuation(value) {
|
|
20
29
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
21
30
|
throw new Error(DIAGNOSE_DEGRADED_CONTINUATION_INVALID);
|
|
@@ -24,15 +33,14 @@ export function assertDiagnoseDegradedContinuation(value) {
|
|
|
24
33
|
if (record.schemaVersion === undefined) {
|
|
25
34
|
throw new Error(DIAGNOSE_DEGRADED_CONTINUATION_INVALID);
|
|
26
35
|
}
|
|
27
|
-
|
|
36
|
+
const expected = record.schemaVersion === 'DiagnoseDegradedContinuation/1.0'
|
|
37
|
+
? createDiagnoseDegradedContinuation()
|
|
38
|
+
: record.schemaVersion === DIAGNOSE_SCOPED_CONTINUATION_SCHEMA
|
|
39
|
+
? createDiagnoseScopedDegradedContinuation() : undefined;
|
|
40
|
+
if (!expected)
|
|
28
41
|
throw new Error(DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED);
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
if (keys.length !== KEYS.length || keys.some((key, index) => key !== [...KEYS].sort()[index])) {
|
|
32
|
-
throw new Error(DIAGNOSE_DEGRADED_CONTINUATION_INVALID);
|
|
33
|
-
}
|
|
34
|
-
const expected = createDiagnoseDegradedContinuation();
|
|
35
|
-
if (KEYS.some((key) => record[key] !== expected[key])) {
|
|
42
|
+
const entries = Object.entries(expected);
|
|
43
|
+
if (Object.keys(record).length !== entries.length || entries.some(([key, expectedValue]) => !Object.prototype.hasOwnProperty.call(record, key) || record[key] !== expectedValue)) {
|
|
36
44
|
throw new Error(DIAGNOSE_DEGRADED_CONTINUATION_INVALID);
|
|
37
45
|
}
|
|
38
46
|
return value;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { assertDiagnoseDegradedContinuation, createDiagnoseDegradedContinuation, DIAGNOSE_DEGRADED_CONTINUATION_INVALID, DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED, } from './diagnose-degraded-continuation.js';
|
|
2
|
+
import { assertDiagnoseDegradedContinuation, createDiagnoseDegradedContinuation, createDiagnoseScopedDegradedContinuation, DIAGNOSE_DEGRADED_CONTINUATION_INVALID, DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED, } from './diagnose-degraded-continuation.js';
|
|
3
3
|
describe('DiagnoseDegradedContinuation/1.0', () => {
|
|
4
4
|
it('creates one frozen closed contract', () => {
|
|
5
5
|
const value = createDiagnoseDegradedContinuation();
|
|
@@ -24,3 +24,32 @@ describe('DiagnoseDegradedContinuation/1.0', () => {
|
|
|
24
24
|
})).toThrow(DIAGNOSE_DEGRADED_CONTINUATION_VERSION_UNSUPPORTED);
|
|
25
25
|
});
|
|
26
26
|
});
|
|
27
|
+
describe('DiagnoseDegradedContinuation/2.0', () => {
|
|
28
|
+
const scoped = createDiagnoseScopedDegradedContinuation();
|
|
29
|
+
it('declares independent reader authority and a separate memory action', () => {
|
|
30
|
+
expect(Object.isFrozen(scoped)).toBe(true);
|
|
31
|
+
expect(assertDiagnoseDegradedContinuation(scoped)).toEqual({
|
|
32
|
+
schemaVersion: 'DiagnoseDegradedContinuation/2.0',
|
|
33
|
+
outcome: 'degraded-continue',
|
|
34
|
+
terminal: false,
|
|
35
|
+
reasonCode: 'diagnose-readonly-evidence-continuation',
|
|
36
|
+
nextAction: 'inspect-authorized-read-only-evidence',
|
|
37
|
+
continuationOwner: 'current-agent',
|
|
38
|
+
readOnly: true,
|
|
39
|
+
publicSafe: true,
|
|
40
|
+
localEvidence: 'public-project',
|
|
41
|
+
remoteEvidence: 'independently-authorized-scoped-reader',
|
|
42
|
+
memoryUpdate: 'separate-explicit-command',
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
it.each([
|
|
46
|
+
{ ...scoped, remoteEvidence: 'shell' },
|
|
47
|
+
{ ...scoped, memoryUpdate: 'automatic' },
|
|
48
|
+
{ ...scoped, connectorId: 'untrusted-connector' },
|
|
49
|
+
{ ...scoped, target: 'untrusted-target' },
|
|
50
|
+
{ ...scoped, nextAction: 'reinvoke' },
|
|
51
|
+
{ ...scoped, readOnly: false },
|
|
52
|
+
])('rejects widened authority', (value) => {
|
|
53
|
+
expect(() => assertDiagnoseDegradedContinuation(value)).toThrow(DIAGNOSE_DEGRADED_CONTINUATION_INVALID);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "Neocortex
|
|
3
|
+
description: "🧠 Neocortex v4.66.8 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
|
|
4
4
|
status: native-needs-validation
|
|
5
5
|
source: https://antigravity.google/docs/subagents
|
|
6
6
|
tools:
|
|
@@ -52,18 +52,12 @@ Then follow stdout exactly.
|
|
|
52
52
|
|
|
53
53
|
## Degraded diagnose continuation
|
|
54
54
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
`
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
For an admitted continuation, the current agent alone may inspect only the
|
|
62
|
-
explicit request and public local read-only evidence. Return probable cause,
|
|
63
|
-
inspected evidence, limitation, and a safe plan. Do not claim protected workflow
|
|
64
|
-
execution, spawn or delegate, reinvoke Neocortex, create tasks, or write files.
|
|
65
|
-
Never include protected prompts, raw logs, secrets, PII, private URLs, ambient
|
|
66
|
-
conversation history, or asset-derived text.
|
|
55
|
+
For the selected `diagnose`, add `--diagnose-scoped-continuation` outside
|
|
56
|
+
`--args`. Require exact `metadata.diagnose` via
|
|
57
|
+
`assertDiagnoseDegradedContinuation`; invalid or absent: stop. The same
|
|
58
|
+
agent reads public local evidence. V2 permits only an independently
|
|
59
|
+
user/host-authorized read-only connector for the project, target and query.
|
|
60
|
+
Follow emitted report limits. No shell, spawn, retry or writes.
|
|
67
61
|
|
|
68
62
|
## P127 Subagent Isolation Contract
|
|
69
63
|
|