@ornexus/neocortex 4.66.14 → 4.66.15
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 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/commands/invoke.js +55 -55
- package/packages/client/dist/git/git-lifecycle-store.d.ts +3 -0
- package/packages/client/dist/git/git-lifecycle-store.js +9 -9
- package/packages/client/dist/git/published-story-reconciliation.js +4 -4
- package/packages/client/dist/git/state-json-field-merge.d.ts +5 -0
- package/packages/client/dist/git/state-json-field-merge.js +2 -2
- package/packages/client/dist/git/story-worktree-manager.d.ts +1 -0
- package/packages/client/dist/git/story-worktree-manager.js +3 -3
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`);if(!
|
|
3
|
-
`),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!
|
|
4
|
-
`).filter(Boolean);if(
|
|
1
|
+
import{execFile as se}from"node:child_process";import{createHash as ce}from"node:crypto";import{realpath as Q}from"node:fs/promises";import{promisify as ue}from"node:util";import{parseYoloopInvocation as V}from"../yoloop/target-normalization.js";import{resolveYoloopStartTarget as de}from"../yoloop/yoloop-start-origin-binding.js";import{recoverLegacyDirectYoloStoryCheckpoint as he,resolveDirectYoloIntegrationAuthority as fe,verifyDirectYoloIntegrationCommit as le}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as G}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as pe,isStoryWorktreeEvidenceReceiptRecord as ye,mutateGitLifecycleRuntime as me,publishedStoryReconciliationId as Z,readGitLifecycleRuntime as A,readStoryWorktreeEvidence as K}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as we}from"./governance-runtime-store.js";import{parseNeocortexTrailers as U,trailerValue as q}from"./neocortex-trailers.js";import{StoryWorktreeManager as X}from"./story-worktree-manager.js";const j=ue(se),R=/^[a-f0-9]{64}$/,N=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ge=16;function W(e){return ce("sha256").update(e).digest("hex")}function I(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ve(e,a){let r;try{r=I(JSON.parse(e))}catch{return}if(!(r?.schemaVersion!==2||r.storyId!==a||r.publicSafe!==!0||r.status!=="qa-passed"||r.safeToContinueYoloop!==!0||!Array.isArray(r.blockingChecks)||r.blockingChecks.length!==0))return W(e)}async function Pe(e,a){const r=V(a);if(!r||!/^@?(?:\.\/)?docs\/epics\/epic-[A-Za-z][A-Za-z0-9_-]{0,63}\.md$/.test(r.remainder))return[];const t=de(a);return!t||t.source!=="explicit"?[]:te(e,t.epicId,!0)}async function qe(e,a,r){const t=V(a)?.remainder,s=t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase();if(!s)return;const f=ee(e);let m;try{const p=(await f("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await A(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==p)return;const[o,c,...H]=(await f("show","-s","--format=%H%n%P%n%B","HEAD")).split(`
|
|
2
|
+
`);if(!o||!c||!N.test(o)||!N.test(c))return;const B=U(H.join(`
|
|
3
|
+
`),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!B.ok)return;const h=w=>q(B.values,w),g=h("Neocortex-Story");if(!g||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(g)||h("Neocortex-Epic")!==s||h("Neocortex-Execution-Branch")!==p||h("Neocortex-Prepared-Base")!==c||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(w=>R.test(h(w)??""))||k.stories[g]?.checkpoint||r.some(w=>w.storyId===g))return;const D=we(e);if(!D.ok||!D.value||I(I(I(JSON.parse(D.value.toString("utf8")))?.stories)?.[g])?.epic_id!==s)return;m={storyId:g,headSha:o,executionBranch:p}}catch{return}const{storyId:d,headSha:l,executionBranch:y}=m;try{if(await G(f,y)!==l)return}catch{return{status:"pending",storyId:d,headSha:l,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const u=await he({projectRoot:e,storyId:d,commitSha:l});if(u.ok)return{status:"recovered",storyId:d,headSha:l};if(u.reasonCode==="direct-yolo-checkpoint-conflict"){const p=await A(e,{required:!0});if(I(p.stories[d]?.checkpoint)?.headSha===l)return}return{status:"pending",storyId:d,headSha:l,reasonCode:u.reasonCode}}function ee(e){return async(...a)=>(await j("git",[...a],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Re(e,a){const r=/^\s*\*?yolo\s+@(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]{0,63})\.[A-Za-z0-9.]+\.story\.md\s+story-worktree-phase-[12]\s*$/.exec(a);if(!r)return[];try{const s=(await j("git",["worktree","list","--porcelain","-z"],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:1048576})).stdout.split("\0",1)[0];return s?.startsWith("worktree ")?await Se(s.slice(9),r[1]):[]}catch{return[]}}function Se(e,a){return te(e,a,!1)}async function te(e,a,r){const t=ee(e),s=async d=>(await t("rev-parse","--verify","--quiet",`${d}^{commit}`)).trim(),f=async(d,l)=>{try{return await t("merge-base","--is-ancestor",d,l),!0}catch{return!1}},m=[];try{const d=await Q((await t("rev-parse","--absolute-git-dir")).trim()),l=await Q((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(d!==l)return[];const y=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),u=await s("HEAD"),p=await A(e,{required:!0});if(p.epics[a]?.execution_branch!==y)return[];const k=Object.values(p.storyWorktrees?.entries??{}).filter(i=>i.epicId===a&&i.executionBranch===y&&i.state==="active");if(k.length>ge)return[];for(const i of k)try{const o=await A(e,{required:!0});if(o.stories[i.storyId]?.checkpoint||k.filter(n=>n.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const c=I(o.epics[a]?.branch_lease);if(c&&Date.parse(String(c.expiresAt))>Date.now())continue;const H=K(o,a)?.receipts??[];if(H.some(n=>n.kind==="integration-receipt"&&n.storyId===i.storyId))continue;const B=H.filter(n=>n.kind==="phase-one-receipt"&&n.storyId===i.storyId&&n.leaseId===i.leaseId&&n.graphRevision===i.graphRevision);if(B.length!==1)continue;const h=B[0],g=String(h.graphRevision),D=String(h.receiptId);if(!R.test(g)||!N.test(String(h.headSha))||h.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const $=H.filter(n=>n.kind==="published-story-reconciliation"&&n.storyId===i.storyId&&n.graphRevision===g);if($.length>1||!r&&$.length===0)continue;const w=await fe(e,i.storyId),b=w.originBinding;if(w.epicId!==a||w.executionBranch!==y||!b||b.originBranch===y||!await f(b.originHeadSha,u))continue;const v=await new X({projectRoot:e}).probe(i.leaseId);if(!v.ok||v.value.ownership!=="proven"||v.value.clean!==!0||!v.value.headSha||!N.test(v.value.headSha)||!await f(String(h.headSha),v.value.headSha))continue;const T=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${v.value.headSha}`,`${b.originHeadSha}..${u}`)).trim().split(`
|
|
4
|
+
`).filter(Boolean);if(T.length!==1||!N.test(T[0]))continue;const S=T[0],re=(await t("show","-s","--format=%P",S)).trim();if(!N.test(re))continue;const _=U(await t("show","-s","--format=%B",S),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!_.ok||q(_.values,"Neocortex-Story-Worktree-Tip")!==v.value.headSha)continue;const E=q(_.values,"Neocortex-Graph-Revision"),Y=q(_.values,"Neocortex-Review-Artifact-Digest");if(!E||!R.test(E)||!Y||!R.test(Y))continue;const ie=(await t("rev-parse",`${S}^{tree}`)).trim(),oe=(await t("rev-parse",`${v.value.headSha}^{tree}`)).trim();if(ie!==oe)continue;const F=await le(w,i.storyId,S,{expectedGraphRevision:E});if(!F.ok)continue;const ne=I(JSON.parse(await t("show",`${S}:.neocortex/state.json`))),L=I(I(ne?.stories)?.[i.storyId]);if(L?.epic_id!==a||JSON.stringify(L.depends_on??[])!==JSON.stringify(w.story.depends_on??[]))continue;const C=String(h.specRef),P=`docs/stories/${i.storyId}.story.md`;if(W(await t("show",`${S}:${C}`))!==h.specDigest||W(await t("show",`${u}:${C}`))!==h.specDigest||await t("show",`${S}:${P}`)!==await t("show",`${u}:${P}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,P);const J=ve(await t("show",`${S}:.neocortex/stories/${i.storyId}/qa-gate-result.json`),i.storyId);if(!J)continue;const x=await G(t,b.originBranch);if(!x)continue;try{await s(x)}catch{if(!r||(await t("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",x),await s(x)!==x))continue}if(!await f(b.originHeadSha,x)||!await f(S,x))continue;const O={schemaVersion:1,kind:"published-story-reconciliation",epicId:a,storyId:i.storyId,graphRevision:g,historicalGraphRevision:E,phaseOneReceiptId:D,executionBranch:y,executionHeadSha:u,originBranch:b.originBranch,originHeadSha:x,commitSha:S,bundleDigest:F.value.bundleDigest,historicalQaDigest:J},M=async()=>{if(await s("HEAD")!==u||await s(`refs/heads/${y}`)!==u||await G(t,b.originBranch)!==x)throw new Error("published-story-reconciliation-ref-raced");const n=await new X({projectRoot:e}).probe(i.leaseId);if(!n.ok||n.value.ownership!=="proven"||n.value.clean!==!0||n.value.headSha!==v.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,P)};if($[0]){const n=$[0],ae={...O,executionHeadSha:n.executionHeadSha,originHeadSha:n.originHeadSha};if(n.receiptId!==Z(ae)||!await f(n.executionHeadSha,u)||!await f(n.originHeadSha,x)||(await M(),(await A(e,{required:!0})).revision!==o.revision))continue;m.push(n);continue}const z=Object.freeze({...O,receiptId:Z(O)});if(!ye(z))continue;await me(e,n=>{pe(n,a,{receipts:[z]})},{expectedRevision:o.revision,preCommit:M}),m.push(z)}catch{}}catch{}return m.length===0?m:xe(e,a,m,t)}async function xe(e,a,r,t){try{const s=await A(e,{required:!0}),f=(K(s,a)?.receipts??[]).filter(o=>o.kind==="integration-receipt"&&o.outcome==="integrated").sort((o,c)=>Number(c.integrationIndex)-Number(o.integrationIndex));if(f.length===0)return r;const m=String(f[0].epicHeadAfterSha),d=r[0].executionBranch;if(s.epics[a]?.execution_branch!==d)return r;const l=`refs/heads/${d}`,y=(await t("rev-parse","--verify",l)).trim(),u=async(o,c)=>{if(o===c)return!0;try{return await t("merge-base","--is-ancestor",o,c),!0}catch{return!1}},p=[...new Set([m,...r.map(o=>o.commitSha)])],k=[...p,...r.map(o=>o.executionHeadSha)];if(!(await Promise.all(k.map(o=>u(o,y)))).every(Boolean))return r;let i=y;for(const o of p)if((await Promise.all(p.map(c=>u(c,o)))).every(Boolean)){i=o;break}return(await t("rev-parse","--verify",l)).trim()!==y||(await A(e,{required:!0})).revision!==s.revision?r:r.map(o=>{const c={...o,syncBaseSha:i,syncIntegrationHeadSha:m};return Object.freeze({...c,receiptId:Z(c)})})}catch{return r}}export{ve as historicalStoryQaDigest,Pe as reconcilePublishedStoriesForYoloop,qe as recoverPublishedCheckpointForYoloop,Re as revalidatePublishedStoriesForYolo,Se as revalidatePublishedStoryDependencies};
|
|
@@ -73,4 +73,9 @@ export declare function recomputeStateJsonEpicAggregates(input: {
|
|
|
73
73
|
}): StateJsonEpicAggregateResult;
|
|
74
74
|
/** P227-CON-STATE-MERGE: pure, deterministic 3-way field merge (R1-R7). */
|
|
75
75
|
export declare function mergeStateJsonFields(input: StateJsonFieldMergeInput): StateJsonFieldMergeResult;
|
|
76
|
+
/** Legacy phase checkpoints can prepend locally and append on the epic.
|
|
77
|
+
* Permit only an intact shared sequence and new local checkpoints for this
|
|
78
|
+
* story. Keep arbitrary conflicting history out of the automatic sync path.
|
|
79
|
+
*/
|
|
80
|
+
export declare function mergeLegacyStateForStorySync(input: StateJsonFieldMergeInput): string | undefined;
|
|
76
81
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
`}function
|
|
1
|
+
const B=33554432,g=Object.freeze({inputInvalid:"state-merge-input-invalid",outsideAllowlist:"state-merge-outside-allowlist",storyEntryInvalid:"state-merge-story-entry-invalid",storyEntryConflict:"state-merge-story-entry-conflict",aggregateInvalid:"state-merge-aggregate-invalid"}),F=Object.freeze(["total_stories","completed_stories","status","completed_at"]),J=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,L=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,I=Symbol("absent");class $ extends Error{reasonCode;pointer;constructor(t,s){super(t),this.reasonCode=t,this.pointer=s}}function b(e,t){throw new $(e,t)}function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function i(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:I}function l(e,t){if(e===t)return!0;if(e===I||t===I)return!1;if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((s,n)=>l(s,t[n]));if(m(e)){if(!m(t))return!1;const s=Object.keys(e);return s.length!==Object.keys(t).length?!1:s.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&l(e[n],t[n]))}return!1}function v(e){const t=typeof e=="string"?e:e.toString("utf8");Buffer.byteLength(t,"utf8")>33554432&&b(g.inputInvalid);let s;try{s=JSON.parse(t)}catch{b(g.inputInvalid)}m(s)||b(g.inputInvalid);for(const n of["stories","epics"]){const r=i(s,n);r!==I&&!m(r)&&b(g.inputInvalid,n)}return{text:t,value:s}}function N(...e){const t=[],s=new Set;for(const n of e)for(const r of Object.keys(n??{}))s.has(r)||(s.add(r),t.push(r));return t}function A(e,t,s){s===I?delete e[t]:Object.defineProperty(e,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}function P(e,t){const s=Object.keys(e).filter(o=>i(t,o)!==I),n=Object.keys(e).filter(o=>i(t,o)===I).sort(),r={};for(const o of[...s,...n])A(r,o,e[o]);return r}function w(e,t,s,n){if(l(s,e)||l(s,t))return t;b(g.outsideAllowlist,n)}function O(e){return m(e)?e:void 0}function R(e,t,s,n,r){if(l(s,e))return t;if(m(s)||b(g.storyEntryInvalid,`stories.${n}`),(i(s,"id")!==I&&s.id!==n||i(s,"epic_id")!==I&&s.epic_id!==r)&&b(g.storyEntryInvalid,`stories.${n}`),l(t,e))return s;t!==I&&!m(t)&&b(g.storyEntryInvalid,`stories.${n}`);const o=O(e),c=O(t),u={...c??{}};for(const d of N(c,s,o)){const p=i(o,d),f=i(c,d),y=i(s,d);l(y,p)||l(y,f)?A(u,d,f):l(f,p)?A(u,d,y):b(g.storyEntryConflict,`stories.${n}.${d}`)}return u}function z(e,t,s,n){if(l(s,e)||l(s,t))return t;(!m(s)||!m(t)||e!==I&&!m(e))&&b(g.outsideAllowlist,`epics.${n}`);const r=O(e),o={...t};for(const c of N(t,s,r))F.includes(c)||A(o,c,w(i(r,c),i(t,c),i(s,c),`epics.${n}.${c}`));return o}function G(e,t,s){if(l(s,e)||l(s,t))return t;const n=typeof s=="string"?Date.parse(s):Number.NaN;Number.isFinite(n)||b(g.outsideAllowlist,"last_updated");const r=typeof t=="string"?Date.parse(t):Number.NaN;return Number.isFinite(r)&&r>=n?t:s}const D=new Set(["done","completed","merged"]);function C(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function M(e){const t=()=>b(g.aggregateInvalid,`epics.${e.epicId}`);m(e.epic)||t();const s={...e.epic};(s.id!==e.epicId||!Array.isArray(s.stories))&&t();const n=new Set;let r=0;for(const f of s.stories){(typeof f!="string"||f.length===0||n.has(f))&&t(),n.add(f);const y=e.stories[f];(!m(y)||y.id!==f||y.epic_id!==e.epicId)&&t(),D.has(C(y.status))&&(r+=1)}const o=n.size,c=o>0&&r===o,u=D.has(C(s.status));u&&!c&&o>0&&t(),s.total_stories=o,s.completed_stories=r;let d=!1,p=!1;return!u&&c&&(s.status="done",d=!0,(s.completed_at===void 0||s.completed_at===null)&&(s.completed_at=e.nowIso,p=!0)),{epic:s,totalStories:o,completedStories:r,promotedDone:d,completedAtSet:p}}function T(e){return`${JSON.stringify(e,null,2)}
|
|
2
|
+
`}function x(e){try{(!J.test(e.storyId)||!L.test(e.epicId)||!Number.isFinite(Date.parse(e.aggregateTimestamp)))&&b(g.inputInvalid);const t=v(e.base).value,s=v(e.epic),n=s.value,r=v(e.story).value,o={...n};for(const a of N(n,r,t)){const E=i(t,a),S=i(n,a),h=i(r,a);a==="stories"||a==="epics"||(a==="last_updated"?A(o,a,G(E,S,h)):A(o,a,w(E,S,h,a)))}const c=O(i(t,"stories")),u=O(i(n,"stories")),d=O(i(r,"stories"));if(d||u||c){const a={...u??{}};for(const E of N(u,d,c)){const S=i(c,E),h=i(u,E),k=i(d,E);A(a,E,E===e.storyId?R(S,h,k,e.storyId,e.epicId):w(S,h,k,`stories.${E}`))}(u||Object.keys(a).length>0)&&A(o,"stories",P(a,c))}const p=O(i(t,"epics")),f=O(i(n,"epics")),y=O(i(r,"epics"));let _=!1;if(y||f||p){const a={...f??{}};for(const S of N(f,y,p)){const h=i(p,S),k=i(f,S),j=i(y,S);A(a,S,S===e.epicId?z(h,k,j,S):w(h,k,j,`epics.${S}`))}const E=i(a,e.epicId);m(E)&&Array.isArray(E.stories)&&(A(a,e.epicId,M({epicId:e.epicId,epic:E,stories:O(i(o,"stories"))??{},nowIso:e.aggregateTimestamp}).epic),_=!0),(f||Object.keys(a).length>0)&&A(o,"epics",a)}return l(o,n)?{ok:!0,bytes:s.text,changed:!1,aggregatesRecomputed:_}:{ok:!0,bytes:T(o),changed:!0,aggregatesRecomputed:_}}catch(t){return t instanceof $?t.pointer===void 0?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:t.reasonCode,pointer:t.pointer.slice(0,256)}:{ok:!1,reasonCode:g.inputInvalid}}}function Y(e){try{const t=v(e.base).value,s=v(e.epic).value,n=v(e.story).value,r=t.checkpoints,o=s.checkpoints,c=n.checkpoints;if(l(r,c)){const _=x(e);return _.ok?_.bytes:void 0}if(!Array.isArray(r)||!Array.isArray(o)||!Array.isArray(c)||c.length<=r.length||!l(o.slice(0,r.length),r))return;const u=c.length-r.length,d=l(c.slice(u),r);if(!d&&!l(c.slice(0,r.length),r))return;const p=d?c.slice(0,u):c.slice(r.length);if(!p.every(_=>m(_)&&_.story_id===e.storyId)||p.some(_=>o.some(a=>l(_,a))))return;const f=x({...e,story:T({...n,checkpoints:r})});if(!f.ok)return;const y=v(f.bytes).value;return T({...y,checkpoints:d?[...p,...o]:[...o,...p]})}catch{return}}export{F as STATE_JSON_EPIC_AGGREGATE_FIELDS,B as STATE_JSON_FIELD_MERGE_MAX_BYTES,g as STATE_JSON_FIELD_MERGE_REASON_CODES,Y as mergeLegacyStateForStorySync,x as mergeStateJsonFields,M as recomputeStateJsonEpicAggregates,l as stateJsonValuesEqual};
|
|
@@ -188,6 +188,7 @@ export declare class StoryWorktreeManager {
|
|
|
188
188
|
readonly leaseId: string;
|
|
189
189
|
readonly integratedSha?: string;
|
|
190
190
|
readonly directive?: unknown;
|
|
191
|
+
readonly automatic?: boolean;
|
|
191
192
|
}): Promise<StoryWorktreeResult<StoryWorktreeSyncValue>>;
|
|
192
193
|
status(input: {
|
|
193
194
|
readonly leaseId?: string;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`,{flag:"wx",mode:384});const
|
|
3
|
-
`,{flag:"wx",mode:384});try{await this.mutate(y=>{const g=D(y);(g.entries[p.leaseId]||Object.values(g.entries).some(R=>this.samePath(R.worktreePath,s)))&&o("story-worktree-entry-conflict"),g.entries[p.leaseId]=p,this.bindLeaseEvidence(y,p)})}catch(y){throw await this.removeOwnMarker(i,u),y}const k={...this.leaseValue(p,!1),sharedResolution:d};return{ok:!0,value:l?{...k,alignment:l}:k,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const h=e.directive;(!be(e.directive)||h.epicId!==t.epicId||h.storyId!==t.storyId||a!==void 0&&a!==h.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(h.integratedEpicHeadSha)}(typeof a!="string"||!A.test(a))&&o("story-worktree-sync-sha-invalid"),await this.clean(t.worktreePath)||o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(!await m(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await f(t.worktreePath,["merge","--no-edit",a])).ok){const d=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(_e).sort().slice(0,Ee);return d.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:d}}c="synced"}const i=await I(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return await this.mutate(h=>{const l=D(h),d=l.entries[t.leaseId];(!d||d.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),l.entries[t.leaseId]={...d,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{[e.leaseId,e.epicId,e.storyId].filter(s=>s!==void 0).length!==1&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!j.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!F.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!$.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:e.storyId?s.storyId===e.storyId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async assertPhaseTwo(e){return this.guard(async()=>{(typeof e.storyId!="string"||!$.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await b(await I(this.projectRoot,["rev-parse","--show-toplevel"],"story-worktree-project-root-invalid"))}catch{o("story-worktree-project-root-invalid")}this.samePath(t,r.mainRoot)&&o("story-worktree-phase-two-root-checkout");const a=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>s.storyId===e.storyId&&s.state==="active"&&this.samePath(s.worktreePath,t));return(a.length!==1||!await this.ownershipProven(a[0],r))&&o("story-worktree-phase-two-lease-mismatch"),{ok:!0,value:await this.project(a[0],r)}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await I(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-not-integrated"),await m(r.mainRoot,["worktree","remove",t.worktreePath])||o("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let c;t.workspaceMechanism==="native_subagent_worktree"?c="story-worktree-adopted-branch-preserved":await m(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(c="story-worktree-branch-moved");const i=c===void 0,h=this.now().toISOString(),l={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${h}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:h};return fe(l)||o("story-worktree-receipt-invalid"),await this.mutate(d=>{const u=D(d),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...l});u.cleanupReceipts.length>de;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:l,receiptDigest:L(l)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!j.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((v,S)=>S>0&&this.samePath(v.path,t.worktreePath)),c=a.some(v=>v.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),h=i.ok&&A.test(i.stdout.trim())?i.stdout.trim():void 0,l=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),d=l.ok&&A.test(l.stdout.trim())?l.stdout.trim():void 0,u=await xe(t.worktreePath),w=u==="present",p=t.state==="active"&&w&&await this.ownershipProven(t,r);let k,y;if(p){const v=await f(t.worktreePath,["rev-parse","HEAD"]);v.ok&&A.test(v.stdout.trim())&&(k=v.stdout.trim()),y=await this.clean(t.worktreePath)}const g=k??(w?void 0:h),R=g&&d?await m(r.mainRoot,["merge-base","--is-ancestor",g,d]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:p?"proven":"unproven",pathExists:w,pathAbsence:u,registered:s,...h?{branchSha:h}:{},branchCheckedOut:c,...k?{headSha:k}:{},...y!==void 0?{clean:y}:{},...d?{epicHead:d}:{},...R!==void 0?{integrated:R}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof K)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=ge(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!q.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${O(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await b(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await I(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await b(r),s=X(await I(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await b(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!G.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!A.test(t)||!await m(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r);await m(e.mainRoot,["merge-base","--is-ancestor",t,s])||o("story-worktree-base-divergent")}async epicHead(e,r){return I(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await b(await I(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await b(await I(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=P(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await m(s,c))return;await Z(25*i)}o("story-worktree-config-failed")},a=await f(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await b(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await C(P(t,T),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||O(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!j.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async reconciledClaimsSidecar(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${_}\0`||(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=P(e,_);try{const a=await x(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>J)return;const s=await f(e,["show",`HEAD:${_}`]);if(!s.ok||s.stdout.length>J)return;const c=U(JSON.parse(await C(t,"utf8"))),i=U(JSON.parse(s.stdout));if(!c||!i)return;const h=Object.keys(c);return h.length>=Object.keys(i).length||!h.every(l=>Object.hasOwn(i,l)&&ne(c[l],i[l]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=P(e,_),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await x(t)).mode&511;await W(a,r,{encoding:"utf8",flag:"wx",mode:s}),await se(a,t)}catch{await B(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=Y(r);return(await f(e,["cat-file","-e",`${t}:${s}`])).ok?!(await f(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await f(e.mainRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]);a.ok&&await this.planningMissingFromBase(e.mainRoot,r,a.stdout.trim(),t)&&o("epic-planning-not-in-base")}async planningOnlyDrift(e,r,t,a){if(!await this.planningMissingFromBase(e,r,t,a))return!1;const s=await f(e,["merge-base",t,a]);if(!s.ok)return!1;const c=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!c.ok)return!1;const i=c.stdout.split("\0").filter(Boolean);return i.length>0&&i.every(h=>Ae(r,h))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!A.test(s))return{...t,ownership:"proven"};const c=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=c.ok&&await m(r.mainRoot,["merge-base","--is-ancestor",s,c.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:i}}bindLeaseEvidence(e,r){try{he(e,this.leaseValue(r,!1).lease)}catch(t){const a=t instanceof Error?t.message:"";o(a==="git-lifecycle-runtime-story-worktree-evidence-conflict"?"story-worktree-lease-evidence-conflict":"story-worktree-lease-evidence-invalid")}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:L(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[pe]:a}}}async prepareSharedResolution(e,r,t){const a=await f(r,["show",`${t}:packages/shared/package.json`]);if(!a.ok)return"not-applicable";try{if(JSON.parse(a.stdout)?.name!=="@neocortex/shared")return"not-applicable"}catch{return"not-applicable"}await m(r,["check-ignore","-q","node_modules/@neocortex/shared"])||o("story-worktree-shared-link-not-ignored");const s=await ye({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(s.ok)return s.value;if(s.reasonCode==="story-worktree-shared-build-missing")return"build-missing";o(s.reasonCode)}async rollbackCreate(e,r,t){t&&(await f(e.mainRoot,["worktree","remove",r.worktreePath]),await f(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=D(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],le(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await C(e,"utf8")).nonce===r&&await B(e)}catch{}}async listWorktrees(e){const r=X(await I(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await b(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await C(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await M(e.worktreePath)&&!await m(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=D(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return ue(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await we(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await Z(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{T as STORY_WORKTREE_MARKER_FILE,ve as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,ze as StoryWorktreeManager,L as digestStoryWorktreeReceiptLocal,X as parseWorktreeList,Le as runStoryWorktreeGit,xe as storyWorktreePathAbsence};
|
|
1
|
+
import{execFile as ie}from"node:child_process";import{createHash as ne,randomBytes as ce}from"node:crypto";import{chmod as de,lstat as P,mkdir as he,open as le,readFile as A,realpath as b,rename as W,rmdir as fe,unlink as C,writeFile as j}from"node:fs/promises";import{homedir as we}from"node:os";import{isAbsolute as z,join as S,resolve as ue}from"node:path";import{isDeepStrictEqual as pe}from"node:util";import{yoloopDomainHash as q}from"../../../shared/dist/yoloop/canonical.js";import{mergeLegacyStateForStorySync as me,STATE_JSON_FIELD_MERGE_MAX_BYTES as ye}from"./state-json-field-merge.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as ke,bindStoryWorktreeLeaseEvidence as ge,compactStoryWorktreeJournal as ve,ensureStoryWorktreeJournal as _,isStoryWorktreeCleanupReceiptRecord as Ie,mutateGitLifecycleRuntime as Re,readGitLifecycleRuntime as Se}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as be,ensurePrivateStoryWorktreeRoot as Ee,ensureStoryWorktreeSharedResolution as Pe,resolveStoryWorktreePath as G,resolveStoryWorktreeRoot as Ae,storyWorktreeIdentity as De}from"./story-worktree-paths.js";const H="nx-owner",_e="neocortex.p225.story-worktree-receipt.v1";function F(n){return q(_e,n)}const V=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),xe=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,B=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Oe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function J(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==V.length||!r.every(a=>V.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&K.test(e.directiveId)&&typeof e.epicId=="string"&&X.test(e.epicId)&&typeof e.storyId=="string"&&B.test(e.storyId)&&typeof e.releasedStepId=="string"&&xe.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&B.test(a))&&typeof e.integratedEpicHeadSha=="string"&&x.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&U.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Oe.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const Y=1440*60*1e3,Ce="neocortex.p225.two-phase-release-directive-id.v1",T=".neocortex/state.json",M=".story-worktree-sync",Te=3e4,$e=200,x=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,U=/^[a-f0-9]{64}$/,N=/^swt-[a-f0-9]{24}$/,K=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,X=/^P[1-9][0-9]*$/,Be=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,$=".neocortex/pending-epic-claims.json",Z=128*1024,We=/^[a-f0-9]{64}$/;function Q(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;if(Object.keys(e).length!==2||e.schemaVersion!==1)return;const t=e.operations;if(!(!t||typeof t!="object"||Array.isArray(t))){for(const[a,s]of Object.entries(t))if(!We.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function ee(n){return`docs/epics/epic-${n}.md`}function je(n,e){if(e===ee(n)||e===".neocortex/state.json"||e===$||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${n}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${n}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class te extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new te(n)}function He(){const n={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete n[e];return n.GIT_TERMINAL_PROMPT="0",n}function Ze(n,e){return f(n,e)}function f(n,e){return new Promise(r=>{ie("git",[...e],{cwd:n,encoding:"utf8",env:He(),maxBuffer:8*1024*1024,timeout:Te,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function p(n,e){return(await f(n,e)).ok}async function R(n,e,r){const t=await f(n,e);return t.ok||o(r),t.stdout.trim()}async function re(n,e){return p(n,["merge","--ff-only","--no-autostash","--no-overwrite-ignore",e])}async function Me(n,e,r){const t=n.worktreePath,a=S(t,T),s=S(t,".neocortex"),c=S(s,M),i=S(c,"original.json"),d=S(c,"merged.json"),h=await P(a).catch(()=>{});if(!h?.isFile()||h.nlink!==1||h.size>ye||await b(a)!==a||!await p(t,["diff","--cached","--quiet"])||await p(t,["diff","--quiet","--",T])||await p(t,["cat-file","-e",`${r}:.neocortex/${M}`])||await R(t,["rev-parse","HEAD"],"story-worktree-git-failed")!==e)return!1;const[l,u,w]=await Promise.all([f(t,["show",`${e}:${T}`]),f(t,["show",`${r}:${T}`]),f(t,["show","-s","--format=%cI",r])]);if(!l.ok||!u.ok||!w.ok||l.stdout===u.stdout)return!1;const m=await A(a),g=me({base:l.stdout,epic:u.stdout,story:m,storyId:n.storyId,epicId:n.epicId,aggregateTimestamp:w.stdout.trim()});if(g===void 0)return!1;try{await he(c,{mode:448})}catch{return!1}let y=!1,v=!1;try{const I=await le(d,"wx",h.mode&511);try{await I.writeFile(g,"utf8"),await I.sync()}finally{await I.close()}if(!(await A(a)).equals(m))return!1;await W(a,i),y=!0,(!(await A(i)).equals(m)||!await p(t,["checkout-index","--",T]))&&o("story-worktree-sync-state-backup-preserved"),await re(t,r);const k=await R(t,["rev-parse","HEAD"],"story-worktree-git-failed"),E=k===r?u.stdout:k===e?l.stdout:void 0;return(E===void 0||!(await A(a)).equals(Buffer.from(E)))&&o("story-worktree-sync-state-backup-preserved"),await W(k===r?d:i,a),v=!0,k===r}finally{(!y||v)&&(await C(i).catch(()=>{}),await C(d).catch(()=>{}),await fe(c).catch(()=>{}))}}function O(n){return ne("sha256").update(n).digest("hex")}async function Ne(n){try{return await P(n),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function L(n){try{return await P(n),!0}catch{return!1}}function ae(n){return new Promise(e=>setTimeout(e,n))}function se(n){const e=[];for(const r of n.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(i=>i.startsWith("HEAD "))?.slice(5),c=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...c?.startsWith("refs/heads/")?{branch:c.slice(11)}:{}})}return e}function Le(n){return n.length>0&&n.length<=512&&!z(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class Qe{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ue(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>ce(32).toString("hex")),this.platform=e.platform??process.platform}async create(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha);const a=Ae({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??we(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=G({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await Ee(a.value,this.platform);c.ok||o(c.reasonCode);const i=G({root:await b(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const d=i.value,h=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(h){if(h.state==="active"&&h.baseSha===e.baseSha&&h.graphRevision===e.graphRevision&&await this.ownershipProven(h,t))return await this.assertNoCleanupInProgress(t,h.leaseId),{ok:!0,value:this.leaseValue(h,!0),privatePath:h.worktreePath};await this.reclaimStaleReservation(h,t)||o("story-worktree-entry-conflict")}await L(d)&&o("story-worktree-path-occupied"),await p(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const l=this.randomNonce(),u=this.now(),w={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:O(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:d,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,l),nonceDigest:O(l),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??Y)).toISOString()};await this.mutate(g=>{const y=_(g);(y.entries[w.leaseId]||Object.values(y.entries).some(v=>v.worktreePath===d))&&o("story-worktree-entry-conflict"),y.entries[w.leaseId]=w});let m=!1;try{await p(t.mainRoot,["worktree","add","-b",r.temporaryBranch,d,e.baseSha])||o("story-worktree-add-failed"),m=!0,this.platform!=="win32"?await de(d,448):await this.enableWindowsLongPaths(t,d);const g=await this.prepareSharedResolution(t,d,e.baseSha),y=await this.worktreeGitDir(d,t);await j(S(y,H),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:l})}
|
|
2
|
+
`,{flag:"wx",mode:384});const v={...w,state:"active"};return await this.mutate(I=>{const k=_(I),E=k.entries[w.leaseId];(!E||E.state!=="creating"||E.nonceDigest!==w.nonceDigest)&&o("story-worktree-entry-conflict"),k.entries[w.leaseId]=v}),{ok:!0,value:{...this.leaseValue(v,!1),sharedResolution:g},privatePath:d}}catch(g){throw await this.rollbackCreate(t,w,m),g}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha),(typeof e.worktreePath!="string"||!z(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await b(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(D=>this.samePath(D.path,a));c===0&&o("story-worktree-adopt-main-refused"),c<0&&o("story-worktree-adopt-unregistered");const i=s[c];i.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(Be.test(i.branch)||i.branch===s[0]?.branch||await p(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const h=(await this.readDocument()).storyWorktrees?.entries??{},l=h[r.leaseId];if(l){if(this.samePath(l.worktreePath,a)&&l.state==="active"&&await this.ownershipProven(l,t))return(l.graphRevision!==e.graphRevision||l.baseSha!==e.baseSha)&&o("story-worktree-reuse-base-divergent"),await p(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,l.leaseId),await this.mutate(D=>{this.bindLeaseEvidence(D,l)}),{ok:!0,value:this.leaseValue(l,!0),privatePath:l.worktreePath};o("story-worktree-entry-conflict")}Object.values(h).some(D=>this.samePath(D.worktreePath,a))&&o("story-worktree-entry-conflict"),(await f(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed");let w;await this.clean(a)||(w=await this.reconciledClaimsSidecar(a),w===void 0&&o("native-worktree-dirty"));const m=await R(a,["rev-parse","HEAD"],"story-worktree-git-failed");m!==e.baseSha&&!await p(a,["merge-base","--is-ancestor",m,e.baseSha])&&o(await this.planningOnlyDrift(a,e.epicId,m,e.baseSha)?"epic-planning-not-in-base":"native-worktree-base-mismatch");const g=await this.worktreeGitDir(a,t),y=S(g,H),v=await L(y);v&&await this.markerLeaseId(y)!==r.leaseId&&o("story-worktree-marker-exists"),w!==void 0&&(await this.restoreClaimsSidecar(a,w),await this.clean(a)||o("native-worktree-dirty"));let I;m!==e.baseSha&&(await this.alignWorktree(a,i.branch,m,e.baseSha),I=Object.freeze({mode:"fast-forward",fromSha:m,toSha:e.baseSha}));const k=S(a,"node_modules","@neocortex","shared"),E=await P(k).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:y,orphanMarker:v,alignment:I})}catch(D){throw!E&&await P(k).then(oe=>oe.isSymbolicLink(),()=>!1)&&await C(k).catch(()=>{}),I&&await this.restoreAlignment(a,i.branch,m,e.baseSha),D}})}async alignWorktree(e,r,t,a){const s=await f(e,["diff","--name-only","--no-renames","-z",t,a]),c=await f(e,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"]);(!s.ok||!c.ok)&&o("native-worktree-align-failed");const i=c.stdout.split("\0").filter(Boolean).map(l=>l.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(l=>i.some(u=>l===u||l.startsWith(`${u}/`)||u.startsWith(`${l}/`)))&&o("native-worktree-align-failed"),(await f(e,["read-tree","-m","-u",t,a])).ok||o("native-worktree-align-failed"),await p(e,["update-ref","-m","neocortex: adopt align",`refs/heads/${r}`,a,t])||((await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),o("native-worktree-align-failed")),(await R(e,["rev-parse","HEAD"],"story-worktree-git-failed")!==a||!await this.clean(e))&&(await this.restoreAlignment(e,r,t,a),o("native-worktree-align-failed"))}async restoreAlignment(e,r,t,a){(await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),await p(e,["update-ref","-m","neocortex: adopt align rollback",`refs/heads/${r}`,t,a])||o("native-worktree-align-restore-failed")}async adoptAligned(e){const{facts:r,identity:t,input:a,canonical:s,temporaryBranch:c,markerPath:i,orphanMarker:d,alignment:h}=e,l=await this.prepareSharedResolution(r,s,a.baseSha);d&&await C(i);const u=this.randomNonce(),w=this.now(),m={schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,dispatchDigest:O(t.dispatchId),hash8:t.hash8,executionBranch:t.executionBranch,temporaryBranch:c,worktreeRef:t.worktreeRef,worktreePath:s,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(a.ownerId,u),nonceDigest:O(u),baseSha:a.baseSha,graphRevision:a.graphRevision,state:"active",acquiredAt:w.toISOString(),expiresAt:new Date(w.getTime()+(this.options.ttlMs??Y)).toISOString()};await j(i,`${JSON.stringify({schemaVersion:1,leaseId:m.leaseId,nonce:u})}
|
|
3
|
+
`,{flag:"wx",mode:384});try{await this.mutate(y=>{const v=_(y);(v.entries[m.leaseId]||Object.values(v.entries).some(I=>this.samePath(I.worktreePath,s)))&&o("story-worktree-entry-conflict"),v.entries[m.leaseId]=m,this.bindLeaseEvidence(y,m)})}catch(y){throw await this.removeOwnMarker(i,u),y}const g={...this.leaseValue(m,!1),sharedResolution:l};return{ok:!0,value:h?{...g,alignment:h}:g,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const d=e.directive;(!J(e.directive)||d.epicId!==t.epicId||d.storyId!==t.storyId||a!==void 0&&a!==d.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(d.integratedEpicHeadSha)}if(e.automatic){const d=e.directive;(!J(d)||d.graphRevision!==t.graphRevision||Array.isArray(d.dependsOn)&&d.dependsOn.includes(t.storyId)||d.directiveId!==q(Ce,{epicId:d.epicId,storyId:d.storyId,dependsOn:d.dependsOn,integratedEpicHeadSha:d.integratedEpicHeadSha,graphRevision:d.graphRevision}))&&o("story-worktree-directive-invalid");const h=await this.assertPhaseTwo({storyId:t.storyId});(!h.ok||h.value.leaseId!==t.leaseId)&&o("story-worktree-phase-two-lease-mismatch")}(typeof a!="string"||!x.test(a))&&o("story-worktree-sync-sha-invalid"),!e.automatic&&!await this.clean(t.worktreePath)&&o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(e.automatic){await P(S(t.worktreePath,".neocortex",M)).catch(()=>{})&&o("story-worktree-sync-state-backup-preserved");const d=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");d!==a&&(await p(t.worktreePath,["merge-base","--is-ancestor",d,a])||o("story-worktree-sync-not-fast-forward"),!await re(t.worktreePath,a)&&!await Me(t,d,a)&&o("story-worktree-sync-conflict-preserved"),c="synced")}if(!e.automatic&&!await p(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await f(t.worktreePath,["merge","--no-edit",a])).ok){const l=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(Le).sort().slice(0,$e);return l.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:l}}c="synced"}const i=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return e.automatic&&i!==a&&o("story-worktree-sync-head-raced"),await this.mutate(d=>{const h=_(d),l=h.entries[t.leaseId];(!l||l.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),h.entries[t.leaseId]={...l,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{[e.leaseId,e.epicId,e.storyId].filter(s=>s!==void 0).length!==1&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!N.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!X.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:e.storyId?s.storyId===e.storyId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async assertPhaseTwo(e){return this.guard(async()=>{(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await b(await R(this.projectRoot,["rev-parse","--show-toplevel"],"story-worktree-project-root-invalid"))}catch{o("story-worktree-project-root-invalid")}this.samePath(t,r.mainRoot)&&o("story-worktree-phase-two-root-checkout");const a=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>s.storyId===e.storyId&&s.state==="active"&&this.samePath(s.worktreePath,t));return(a.length!==1||!await this.ownershipProven(a[0],r))&&o("story-worktree-phase-two-lease-mismatch"),{ok:!0,value:await this.project(a[0],r)}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-not-integrated"),await p(r.mainRoot,["worktree","remove",t.worktreePath])||o("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let c;t.workspaceMechanism==="native_subagent_worktree"?c="story-worktree-adopted-branch-preserved":await p(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(c="story-worktree-branch-moved");const i=c===void 0,d=this.now().toISOString(),h={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${d}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:d};return Ie(h)||o("story-worktree-receipt-invalid"),await this.mutate(l=>{const u=_(l),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...h});u.cleanupReceipts.length>ke;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:h,receiptDigest:F(h)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((k,E)=>E>0&&this.samePath(k.path,t.worktreePath)),c=a.some(k=>k.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),d=i.ok&&x.test(i.stdout.trim())?i.stdout.trim():void 0,h=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),l=h.ok&&x.test(h.stdout.trim())?h.stdout.trim():void 0,u=await Ne(t.worktreePath),w=u==="present",m=t.state==="active"&&w&&await this.ownershipProven(t,r);let g,y;if(m){const k=await f(t.worktreePath,["rev-parse","HEAD"]);k.ok&&x.test(k.stdout.trim())&&(g=k.stdout.trim()),y=await this.clean(t.worktreePath)}const v=g??(w?void 0:d),I=v&&l?await p(r.mainRoot,["merge-base","--is-ancestor",v,l]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:m?"proven":"unproven",pathExists:w,pathAbsence:u,registered:s,...d?{branchSha:d}:{},branchCheckedOut:c,...g?{headSha:g}:{},...y!==void 0?{clean:y}:{},...l?{epicHead:l}:{},...I!==void 0?{integrated:I}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof te)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=De(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!K.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${O(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await b(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await b(r),s=se(await R(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await b(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!U.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!x.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r);await p(e.mainRoot,["merge-base","--is-ancestor",t,s])||o("story-worktree-base-divergent")}async epicHead(e,r){return R(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await b(await R(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await b(await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=S(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await p(s,c))return;await ae(25*i)}o("story-worktree-config-failed")},a=await f(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await b(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await A(S(t,H),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||O(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async reconciledClaimsSidecar(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${$}\0`||(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=S(e,$);try{const a=await P(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>Z)return;const s=await f(e,["show",`HEAD:${$}`]);if(!s.ok||s.stdout.length>Z)return;const c=Q(JSON.parse(await A(t,"utf8"))),i=Q(JSON.parse(s.stdout));if(!c||!i)return;const d=Object.keys(c);return d.length>=Object.keys(i).length||!d.every(h=>Object.hasOwn(i,h)&&pe(c[h],i[h]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=S(e,$),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await P(t)).mode&511;await j(a,r,{encoding:"utf8",flag:"wx",mode:s}),await W(a,t)}catch{await C(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=ee(r);return(await f(e,["cat-file","-e",`${t}:${s}`])).ok?!(await f(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await f(e.mainRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]);a.ok&&await this.planningMissingFromBase(e.mainRoot,r,a.stdout.trim(),t)&&o("epic-planning-not-in-base")}async planningOnlyDrift(e,r,t,a){if(!await this.planningMissingFromBase(e,r,t,a))return!1;const s=await f(e,["merge-base",t,a]);if(!s.ok)return!1;const c=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!c.ok)return!1;const i=c.stdout.split("\0").filter(Boolean);return i.length>0&&i.every(d=>je(r,d))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!x.test(s))return{...t,ownership:"proven"};const c=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=c.ok&&await p(r.mainRoot,["merge-base","--is-ancestor",s,c.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:i}}bindLeaseEvidence(e,r){try{ge(e,this.leaseValue(r,!1).lease)}catch(t){const a=t instanceof Error?t.message:"";o(a==="git-lifecycle-runtime-story-worktree-evidence-conflict"?"story-worktree-lease-evidence-conflict":"story-worktree-lease-evidence-invalid")}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:F(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[be]:a}}}async prepareSharedResolution(e,r,t){const a=await f(r,["show",`${t}:packages/shared/package.json`]);if(!a.ok)return"not-applicable";try{if(JSON.parse(a.stdout)?.name!=="@neocortex/shared")return"not-applicable"}catch{return"not-applicable"}await p(r,["check-ignore","-q","node_modules/@neocortex/shared"])||o("story-worktree-shared-link-not-ignored");const s=await Pe({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(s.ok)return s.value;if(s.reasonCode==="story-worktree-shared-build-missing")return"build-missing";o(s.reasonCode)}async rollbackCreate(e,r,t){t&&(await f(e.mainRoot,["worktree","remove",r.worktreePath]),await f(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=_(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],ve(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await A(e,"utf8")).nonce===r&&await C(e)}catch{}}async listWorktrees(e){const r=se(await R(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await b(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await A(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await L(e.worktreePath)&&!await p(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=_(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return Se(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await Re(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await ae(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{H as STORY_WORKTREE_MARKER_FILE,_e as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,Qe as StoryWorktreeManager,F as digestStoryWorktreeReceiptLocal,se as parseWorktreeList,Ze as runStoryWorktreeGit,Ne as storyWorktreePathAbsence};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | 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:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex Root Agent v4.66.
|
|
3
|
+
description: "🧠 Neocortex Root Agent v4.66.15 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
tools:
|
|
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
113
113
|
┌────────────────────────────────────────────────────────────┐
|
|
114
114
|
│ │
|
|
115
115
|
│ ####### N E O C O R T E X │
|
|
116
|
-
│ ### ######## v4.66.
|
|
116
|
+
│ ### ######## v4.66.15 │
|
|
117
117
|
│ ######### ##### │
|
|
118
118
|
│ ## ############## Development Orchestrator │
|
|
119
119
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -102,7 +102,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
102
102
|
┌────────────────────────────────────────────────────────────┐
|
|
103
103
|
│ │
|
|
104
104
|
│ ####### N E O C O R T E X │
|
|
105
|
-
│ ### ######## v4.66.
|
|
105
|
+
│ ### ######## v4.66.15 │
|
|
106
106
|
│ ######### ##### │
|
|
107
107
|
│ ## ############## Development Orchestrator │
|
|
108
108
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
permissionMode: bypassPermissions
|
|
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
113
113
|
┌────────────────────────────────────────────────────────────┐
|
|
114
114
|
│ │
|
|
115
115
|
│ ####### N E O C O R T E X │
|
|
116
|
-
│ ### ######## v4.66.
|
|
116
|
+
│ ### ######## v4.66.15 │
|
|
117
117
|
│ ######### ##### │
|
|
118
118
|
│ ## ############## Development Orchestrator │
|
|
119
119
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -28,7 +28,7 @@ returned instructions.
|
|
|
28
28
|
|
|
29
29
|
<!-- END: Plugin Conflict Prevention -->
|
|
30
30
|
|
|
31
|
-
# Neocortex v4.66.
|
|
31
|
+
# Neocortex v4.66.15 | OrNexus Team
|
|
32
32
|
|
|
33
33
|
You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
|
|
34
34
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Codex custom agent reference:
|
|
2
2
|
# https://developers.openai.com/codex/subagents
|
|
3
3
|
name = "neocortex"
|
|
4
|
-
description = "🧠 Neocortex v4.66.
|
|
4
|
+
description = "🧠 Neocortex v4.66.15 | OrNexus Team — Development orchestrator for direct @neocortex requests."
|
|
5
5
|
# [P201-EV-CODEX-GEMINI] Approval and sandbox keys are intentionally omitted.
|
|
6
6
|
# Codex reapplies the parent turn's live sandbox/approval settings, including
|
|
7
7
|
# --yolo, when spawning this profile. This profile must not claim child-only max.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team"
|
|
4
4
|
model: inherit
|
|
5
5
|
readonly: false
|
|
6
6
|
is_background: false
|
|
@@ -115,7 +115,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
115
115
|
┌────────────────────────────────────────────────────────────┐
|
|
116
116
|
│ │
|
|
117
117
|
│ ####### N E O C O R T E X │
|
|
118
|
-
│ ### ######## v4.66.
|
|
118
|
+
│ ### ######## v4.66.15 │
|
|
119
119
|
│ ######### ##### │
|
|
120
120
|
│ ## ############## Development Orchestrator │
|
|
121
121
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team — Route explicit Neocortex *commands through the public thin client in DeepSeek Harness."
|
|
4
4
|
user-invocable: true
|
|
5
5
|
disable-model-invocation: false
|
|
6
6
|
---
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team"
|
|
4
4
|
kind: local
|
|
5
5
|
tools:
|
|
6
6
|
# File operations (Gemini CLI built-ins)
|
|
@@ -73,7 +73,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
73
73
|
┌────────────────────────────────────────────────────────────┐
|
|
74
74
|
│ │
|
|
75
75
|
│ ####### N E O C O R T E X │
|
|
76
|
-
│ ### ######## v4.66.
|
|
76
|
+
│ ### ######## v4.66.15 │
|
|
77
77
|
│ ######### ##### │
|
|
78
78
|
│ ## ############## Development Orchestrator │
|
|
79
79
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team"
|
|
4
4
|
kind: local
|
|
5
5
|
tools:
|
|
6
6
|
# File operations (Gemini CLI built-ins)
|
|
@@ -72,7 +72,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
72
72
|
┌────────────────────────────────────────────────────────────┐
|
|
73
73
|
│ │
|
|
74
74
|
│ ####### N E O C O R T E X │
|
|
75
|
-
│ ### ######## v4.66.
|
|
75
|
+
│ ### ######## v4.66.15 │
|
|
76
76
|
│ ######### ##### │
|
|
77
77
|
│ ## ############## Development Orchestrator │
|
|
78
78
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team — Run development orchestration commands through the public thin client."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Neocortex for Grok Build
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
|
|
4
4
|
status: native-needs-validation
|
|
5
5
|
source: https://www.kimi.com/code/docs/en/kimi-code-cli/customization/agents.html
|
|
6
6
|
model_preference: primary
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 | OrNexus Team — Run Neocortex commands through the public thin client in OpenClaw."
|
|
4
4
|
status: skill-fallback
|
|
5
5
|
user-invocable: true
|
|
6
6
|
---
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex Root Agent v4.66.
|
|
3
|
+
description: "🧠 Neocortex Root Agent v4.66.15 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
|
|
4
4
|
mode: primary
|
|
5
5
|
color: "#00B4FF"
|
|
6
6
|
permission:
|
|
@@ -74,7 +74,7 @@ user's own `*yolo @docs/stories/<id>.story.md` is never refused.
|
|
|
74
74
|
┌────────────────────────────────────────────────────────────┐
|
|
75
75
|
│ │
|
|
76
76
|
│ ####### N E O C O R T E X │
|
|
77
|
-
│ ### ######## v4.66.
|
|
77
|
+
│ ### ######## v4.66.15 │
|
|
78
78
|
│ ######### ##### │
|
|
79
79
|
│ ## ############## Development Orchestrator │
|
|
80
80
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.15 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
|
|
4
4
|
mode: primary
|
|
5
5
|
color: "#00B4FF"
|
|
6
6
|
permission:
|
|
@@ -73,7 +73,7 @@ user's own `*yolo @docs/stories/<id>.story.md` is never refused.
|
|
|
73
73
|
┌────────────────────────────────────────────────────────────┐
|
|
74
74
|
│ │
|
|
75
75
|
│ ####### N E O C O R T E X │
|
|
76
|
-
│ ### ######## v4.66.
|
|
76
|
+
│ ### ######## v4.66.15 │
|
|
77
77
|
│ ######### ##### │
|
|
78
78
|
│ ## ############## Development Orchestrator │
|
|
79
79
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: "neocortex"
|
|
3
|
-
description: "Neocortex v4.66.
|
|
3
|
+
description: "Neocortex v4.66.15 | OrNexus Team"
|
|
4
4
|
tools:
|
|
5
5
|
# Read / Edit (built-in tool sets)
|
|
6
6
|
- read
|
|
@@ -82,7 +82,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
82
82
|
┌────────────────────────────────────────────────────────────┐
|
|
83
83
|
│ │
|
|
84
84
|
│ ####### N E O C O R T E X │
|
|
85
|
-
│ ### ######## v4.66.
|
|
85
|
+
│ ### ######## v4.66.15 │
|
|
86
86
|
│ ######### ##### │
|
|
87
87
|
│ ## ############## Development Orchestrator │
|
|
88
88
|
│ ## ### ###### ## OrNexus Team │
|