@ornexus/neocortex 4.65.1 → 4.66.1
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 +1206 -1193
- package/install.ps1 +243 -77
- package/install.sh +221 -102
- package/package.json +2 -2
- package/packages/client/dist/adapters/platform-detector.js +1 -1
- package/packages/client/dist/agent/refresh-stubs.d.ts +50 -0
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/cli.js +5 -4
- package/packages/client/dist/commands/doctor.d.ts +26 -1
- package/packages/client/dist/commands/doctor.js +2 -2
- package/packages/client/dist/commands/invoke.d.ts +183 -5
- package/packages/client/dist/commands/invoke.js +94 -87
- package/packages/client/dist/commands/planning-qa.d.ts +64 -0
- package/packages/client/dist/commands/planning-qa.js +1 -0
- package/packages/client/dist/commands/refactor-control.js +3 -3
- package/packages/client/dist/commands/story-checkpoint.d.ts +3 -1
- package/packages/client/dist/commands/story-checkpoint.js +1 -1
- package/packages/client/dist/commands/story-worktree.d.ts +1 -1
- package/packages/client/dist/commands/story-worktree.js +1 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +64 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
- package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
- package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
- package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
- package/packages/client/dist/git/git-lifecycle-store.js +9 -8
- package/packages/client/dist/git/governance-runtime-store.d.ts +172 -0
- package/packages/client/dist/git/governance-runtime-store.js +3 -0
- package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
- package/packages/client/dist/git/story-worktree-manager.js +3 -3
- package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
- package/packages/client/dist/git/story-write-set-extension.js +1 -1
- package/packages/client/dist/memory/shared-project-memory-types.d.ts +39 -2
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
- package/packages/client/dist/policy/subagent-approval-policy.js +1 -1
- package/packages/client/dist/private-execution/codex-executor.d.ts +21 -1
- package/packages/client/dist/private-execution/codex-executor.js +4 -4
- package/packages/client/dist/private-execution/delivery.d.ts +17 -11
- package/packages/client/dist/private-execution/delivery.js +8 -6
- package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +89 -0
- package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
- package/packages/client/dist/private-execution/frozen-handoff.js +3 -3
- package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
- package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
- package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
- package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
- package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
- package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
- package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
- package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
- package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
- package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
- package/packages/client/dist/private-execution/harness-executor.js +1 -0
- package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
- package/packages/client/dist/private-execution/harness-process.js +1 -0
- package/packages/client/dist/private-execution/isolated-admission.js +12 -12
- package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
- package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +75 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
- package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +9 -1
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -4
- package/packages/client/dist/private-execution/planning-research-checkpoint.d.ts +9 -1
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
- package/packages/client/dist/private-execution/root-memory-request.d.ts +4 -1
- package/packages/client/dist/private-execution/root-memory-request.js +1 -1
- package/packages/client/dist/runner/epic-background-dispatcher.d.ts +3 -1
- package/packages/client/dist/runner/epic-background-dispatcher.js +1 -1
- package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
- package/packages/client/dist/runner/headless/managed-profile.d.ts +20 -0
- package/packages/client/dist/runner/headless/managed-profile.js +1 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +40 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
- package/packages/client/dist/runner/headless/types.d.ts +20 -0
- package/packages/client/dist/runner/headless/types.js +2 -2
- package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
- package/packages/client/dist/state/structural-dag-projection.js +1 -1
- package/packages/client/dist/yoloop/target-normalization.js +1 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- package/packages/shared/dist/compatibility/index.js +96 -0
- package/packages/shared/dist/planning/diagnosis-state.js +105 -1
- package/packages/shared/dist/project-memory-targets.js +36 -5
- package/targets-stubs/antigravity/README.md +1 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/install-antigravity.sh +1 -1
- package/targets-stubs/antigravity/mcp-config.json +0 -3
- package/targets-stubs/antigravity/neocortex.md +25 -13
- package/targets-stubs/antigravity/skill/SKILL.md +4 -4
- package/targets-stubs/claude-code/.mcp.json +0 -4
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +2 -4
- package/targets-stubs/claude-code/neocortex-root.md +33 -43
- package/targets-stubs/claude-code/neocortex-sentinel.md +261 -0
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -3
- package/targets-stubs/claude-code/neocortex.md +61 -84
- package/targets-stubs/codex/AGENTS.md +19 -18
- package/targets-stubs/codex/README.md +1 -1
- package/targets-stubs/codex/config-mcp.toml +0 -3
- package/targets-stubs/codex/neocortex-sentinel.toml +87 -0
- package/targets-stubs/codex/neocortex.toml +23 -44
- package/targets-stubs/cursor/README.md +1 -1
- package/targets-stubs/cursor/agent.md +26 -15
- package/targets-stubs/cursor/mcp.json +0 -3
- package/targets-stubs/deepseek-harness/SKILL.md +11 -8
- package/targets-stubs/gemini-cli/README.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +25 -12
- package/targets-stubs/gemini-cli/agents/neocortex-sentinel.md +75 -0
- package/targets-stubs/gemini-cli/agents/neocortex.md +280 -49
- package/targets-stubs/gemini-cli/settings-mcp.json +0 -3
- package/targets-stubs/grok/SKILL.md +13 -1
- package/targets-stubs/grok/agents/neocortex-sentinel.md +64 -0
- package/targets-stubs/grok/config-mcp.toml +0 -3
- package/targets-stubs/grok/install-grok.sh +51 -1
- package/targets-stubs/kimi/mcp.json +0 -6
- package/targets-stubs/kimi/neocortex.md +21 -8
- package/targets-stubs/lib/managed-config-merge.js +301 -6
- package/targets-stubs/lib/managed-profile.sh +12 -1
- package/targets-stubs/lib/mcp-merge.js +122 -8
- package/targets-stubs/openclaw/SKILL.md +33 -4
- package/targets-stubs/opencode/neocortex-root.md +41 -41
- package/targets-stubs/opencode/neocortex-sentinel.md +115 -0
- package/targets-stubs/opencode/neocortex.md +292 -67
- package/targets-stubs/opencode/opencode-mcp.json +0 -7
- package/targets-stubs/vscode/README.md +1 -1
- package/targets-stubs/vscode/mcp.json +0 -4
- package/targets-stubs/vscode/neocortex.agent.md +29 -18
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`,{flag:"wx",mode:384});const
|
|
3
|
-
`,{flag:"wx",mode:384});try{await this.mutate(k=>{const y=P(k);(y.entries[g.leaseId]||Object.values(y.entries).some(R=>this.samePath(R.worktreePath,o)))&&s("story-worktree-entry-conflict"),y.entries[g.leaseId]=g})}catch(k){throw await this.removeOwnMarker(i,u),k}const m={...this.leaseValue(g,!1),sharedResolution:d};return{ok:!0,value:h?{...m,alignment:h}:m,privatePath:o}}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 l=e.directive;(!pe(e.directive)||l.epicId!==t.epicId||l.storyId!==t.storyId||a!==void 0&&a!==l.integratedEpicHeadSha)&&s("story-worktree-directive-invalid"),a=String(l.integratedEpicHeadSha)}(typeof a!="string"||!E.test(a))&&s("story-worktree-sync-sha-invalid"),await this.clean(t.worktreePath)||s("story-worktree-dirty");const o=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,o])||s("story-worktree-sync-sha-unintegrated");let n="already-synced";if(!await p(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(ve).sort().slice(0,ke);return d.length===0&&s("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:d}}n="synced"}const i=await b(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return await this.mutate(l=>{const h=P(l),d=h.entries[t.leaseId];(!d||d.nonceDigest!==t.nonceDigest)&&s("story-worktree-entry-conflict"),h.entries[t.leaseId]={...d,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:n,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{e.leaseId===void 0==(e.epicId===void 0)&&s("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!C.test(e.leaseId)&&s("story-worktree-lease-invalid"),e.epicId!==void 0&&!G.test(e.epicId)&&s("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(o=>e.leaseId?o.leaseId===e.leaseId:o.epicId===e.epicId).sort((o,n)=>o.leaseId.localeCompare(n.leaseId));e.leaseId&&t.length===0&&s("story-worktree-lease-unknown");const a=[];for(const o of t)a.push(await this.project(o,r));return{ok:!0,value:{entries:a}}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||s("story-worktree-dirty");const a=await b(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),o=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,o])||s("story-worktree-not-integrated"),await p(r.mainRoot,["worktree","remove",t.worktreePath])||s("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let n;t.workspaceMechanism==="native_subagent_worktree"?n="story-worktree-adopted-branch-preserved":await p(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(n="story-worktree-branch-moved");const i=n===void 0,l=this.now().toISOString(),h={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${D(`${t.leaseId}|${t.nonceDigest}|${l}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...n?{preservedReasonCode:n}:{},cleanedAt:l};return oe(h)||s("story-worktree-receipt-invalid"),await this.mutate(d=>{const u=P(d),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...h});u.cleanupReceipts.length>re;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:h,receiptDigest:j(h)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!C.test(e))&&s("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||s("story-worktree-lease-unknown");const a=await this.listWorktrees(r),o=a.some((I,v)=>v>0&&this.samePath(I.path,t.worktreePath)),n=a.some(I=>I.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),l=i.ok&&E.test(i.stdout.trim())?i.stdout.trim():void 0,h=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),d=h.ok&&E.test(h.stdout.trim())?h.stdout.trim():void 0,u=await Ie(t.worktreePath),w=u==="present",g=t.state==="active"&&w&&await this.ownershipProven(t,r);let m,k;if(g){const I=await f(t.worktreePath,["rev-parse","HEAD"]);I.ok&&E.test(I.stdout.trim())&&(m=I.stdout.trim()),k=await this.clean(t.worktreePath)}const y=m??(w?void 0:l),R=y&&d?await p(r.mainRoot,["merge-base","--is-ancestor",y,d]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:g?"proven":"unproven",pathExists:w,pathAbsence:u,registered:o,...l?{branchSha:l}:{},branchCheckedOut:n,...m?{headSha:m}:{},...k!==void 0?{clean:k}:{},...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 q)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=le(e);return r.ok||s(r.reasonCode),e.ownerId!==void 0&&!V.test(e.ownerId)&&s("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())&&s("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${D(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await S(this.projectRoot)}catch{s("story-worktree-project-root-invalid")}const r=await b(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await S(r),o=J(await b(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return o||s("story-worktree-project-root-invalid"),{mainRoot:await S(o.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!z.test(a))&&s("story-worktree-graph-revision-invalid"),(typeof t!="string"||!E.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&s("story-worktree-base-invalid");const o=await this.epicHead(e,r);await p(e.mainRoot,["merge-base","--is-ancestor",t,o])||s("story-worktree-base-divergent")}async epicHead(e,r){return b(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await S(await b(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await S(await b(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),o=A(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${o}/`)&&!t.startsWith(`${o}\\`))&&s("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(o,n)=>{for(let i=1;i<=8;i++){if(await p(o,n))return;await F(25*i)}s("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 S(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await _(A(t,W),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||D(a.nonce)!==e.nonceDigest)return!1;const o=await this.listWorktrees(r),n=o.findIndex(i=>this.samePath(i.path,e.worktreePath));return n>0&&o[n].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!C.test(e))&&s("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||s("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&s("story-worktree-ownership-unproven"),t}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"]),o=a.stdout.trim();if(!a.ok||!E.test(o))return{...t,ownership:"proven"};const n=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=n.ok&&await p(r.mainRoot,["merge-base","--is-ancestor",o,n.stdout.trim()]);return{...t,ownership:"proven",headSha:o,clean:await this.clean(e.worktreePath),integrated:i}}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:j(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[ne]: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"])||s("story-worktree-shared-link-not-ignored");const o=await de({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(o.ok)return o.value;if(o.reasonCode==="story-worktree-shared-build-missing")return"build-missing";s(o.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(o=>o.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(o=>{const n=P(o),i=n.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete n.entries[r.leaseId],ae(o)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await _(e,"utf8")).nonce===r&&await O(e)}catch{}}async listWorktrees(e){const r=J(await b(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 S(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 _(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await T(e.worktreePath)&&!await p(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(o=>{const n=P(o),i=n.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete n.entries[e.leaseId],a=!0)}),a}async readDocument(){return ie(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 se(this.projectRoot,e);return}catch(o){if(!(o instanceof Error&&(o.message==="git-lifecycle-runtime-lock-active"||o.code==="ENOENT"&&o.message.includes("runtime.lock")))||a>=r)throw o;await F(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{W as STORY_WORKTREE_MARKER_FILE,we as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,Oe as StoryWorktreeManager,j as digestStoryWorktreeReceiptLocal,J as parseWorktreeList,_e as runStoryWorktreeGit,Ie as storyWorktreePathAbsence};
|
|
1
|
+
import{execFile as ee}from"node:child_process";import{createHash as te,randomBytes as re}from"node:crypto";import{chmod as ae,lstat as x,readFile as C,realpath as b,rename as se,unlink as B,writeFile as W}from"node:fs/promises";import{homedir as oe}from"node:os";import{isAbsolute as H,join as P,resolve as ie}from"node:path";import{isDeepStrictEqual as ne}from"node:util";import{yoloopDomainHash as ce}from"../../../shared/dist/yoloop/canonical.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as de,bindStoryWorktreeLeaseEvidence as he,compactStoryWorktreeJournal as le,ensureStoryWorktreeJournal as D,isStoryWorktreeCleanupReceiptRecord as fe,mutateGitLifecycleRuntime as we,readGitLifecycleRuntime as ue}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as pe,ensurePrivateStoryWorktreeRoot as me,ensureStoryWorktreeSharedResolution as ye,resolveStoryWorktreePath as N,resolveStoryWorktreeRoot as ke,storyWorktreeIdentity as ge}from"./story-worktree-paths.js";const T="nx-owner",ve="neocortex.p225.story-worktree-receipt.v1";function L(n){return ce(ve,n)}const z=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),Ie=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,$=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Re=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function be(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==z.length||!r.every(a=>z.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&q.test(e.directiveId)&&typeof e.epicId=="string"&&F.test(e.epicId)&&typeof e.storyId=="string"&&$.test(e.storyId)&&typeof e.releasedStepId=="string"&&Ie.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&$.test(a))&&typeof e.integratedEpicHeadSha=="string"&&A.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&G.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Re.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const V=1440*60*1e3,Se=3e4,Ee=200,A=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,G=/^[a-f0-9]{64}$/,j=/^swt-[a-f0-9]{24}$/,q=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,F=/^P[1-9][0-9]*$/,Pe=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,_=".neocortex/pending-epic-claims.json",J=128*1024,De=/^[a-f0-9]{64}$/;function U(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(!De.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function Y(n){return`docs/epics/epic-${n}.md`}function Ae(n,e){if(e===Y(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 K extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new K(n)}function Oe(){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 Le(n,e){return f(n,e)}function f(n,e){return new Promise(r=>{ee("git",[...e],{cwd:n,encoding:"utf8",env:Oe(),maxBuffer:8*1024*1024,timeout:Se,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function m(n,e){return(await f(n,e)).ok}async function I(n,e,r){const t=await f(n,e);return t.ok||o(r),t.stdout.trim()}function O(n){return te("sha256").update(n).digest("hex")}async function xe(n){try{return await x(n),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function M(n){try{return await x(n),!0}catch{return!1}}function Z(n){return new Promise(e=>setTimeout(e,n))}function X(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 _e(n){return n.length>0&&n.length<=512&&!H(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class ze{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ie(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>re(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=ke({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??oe(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=N({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await me(a.value,this.platform);c.ok||o(c.reasonCode);const i=N({root:await b(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const h=i.value,l=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(l){if(l.state==="active"&&l.baseSha===e.baseSha&&l.graphRevision===e.graphRevision&&await this.ownershipProven(l,t))return await this.assertNoCleanupInProgress(t,l.leaseId),{ok:!0,value:this.leaseValue(l,!0),privatePath:l.worktreePath};await this.reclaimStaleReservation(l,t)||o("story-worktree-entry-conflict")}await M(h)&&o("story-worktree-path-occupied"),await m(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const d=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:h,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,d),nonceDigest:O(d),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??V)).toISOString()};await this.mutate(k=>{const y=D(k);(y.entries[w.leaseId]||Object.values(y.entries).some(g=>g.worktreePath===h))&&o("story-worktree-entry-conflict"),y.entries[w.leaseId]=w});let p=!1;try{await m(t.mainRoot,["worktree","add","-b",r.temporaryBranch,h,e.baseSha])||o("story-worktree-add-failed"),p=!0,this.platform!=="win32"?await ae(h,448):await this.enableWindowsLongPaths(t,h);const k=await this.prepareSharedResolution(t,h,e.baseSha),y=await this.worktreeGitDir(h,t);await W(P(y,T),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:d})}
|
|
2
|
+
`,{flag:"wx",mode:384});const g={...w,state:"active"};return await this.mutate(R=>{const v=D(R),S=v.entries[w.leaseId];(!S||S.state!=="creating"||S.nonceDigest!==w.nonceDigest)&&o("story-worktree-entry-conflict"),v.entries[w.leaseId]=g}),{ok:!0,value:{...this.leaseValue(g,!1),sharedResolution:k},privatePath:h}}catch(k){throw await this.rollbackCreate(t,w,p),k}})}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"||!H(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(E=>this.samePath(E.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"),(Pe.test(i.branch)||i.branch===s[0]?.branch||await m(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const l=(await this.readDocument()).storyWorktrees?.entries??{},d=l[r.leaseId];if(d){if(this.samePath(d.worktreePath,a)&&d.state==="active"&&await this.ownershipProven(d,t))return(d.graphRevision!==e.graphRevision||d.baseSha!==e.baseSha)&&o("story-worktree-reuse-base-divergent"),await m(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,d.leaseId),await this.mutate(E=>{this.bindLeaseEvidence(E,d)}),{ok:!0,value:this.leaseValue(d,!0),privatePath:d.worktreePath};o("story-worktree-entry-conflict")}Object.values(l).some(E=>this.samePath(E.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 p=await I(a,["rev-parse","HEAD"],"story-worktree-git-failed");p!==e.baseSha&&!await m(a,["merge-base","--is-ancestor",p,e.baseSha])&&o(await this.planningOnlyDrift(a,e.epicId,p,e.baseSha)?"epic-planning-not-in-base":"native-worktree-base-mismatch");const k=await this.worktreeGitDir(a,t),y=P(k,T),g=await M(y);g&&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 R;p!==e.baseSha&&(await this.alignWorktree(a,i.branch,p,e.baseSha),R=Object.freeze({mode:"fast-forward",fromSha:p,toSha:e.baseSha}));const v=P(a,"node_modules","@neocortex","shared"),S=await x(v).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:y,orphanMarker:g,alignment:R})}catch(E){throw!S&&await x(v).then(Q=>Q.isSymbolicLink(),()=>!1)&&await B(v).catch(()=>{}),R&&await this.restoreAlignment(a,i.branch,p,e.baseSha),E}})}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(d=>d.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(d=>i.some(u=>d===u||d.startsWith(`${u}/`)||u.startsWith(`${d}/`)))&&o("native-worktree-align-failed"),(await f(e,["read-tree","-m","-u",t,a])).ok||o("native-worktree-align-failed"),await m(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 I(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 m(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:h,alignment:l}=e,d=await this.prepareSharedResolution(r,s,a.baseSha);h&&await B(i);const u=this.randomNonce(),w=this.now(),p={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??V)).toISOString()};await W(i,`${JSON.stringify({schemaVersion:1,leaseId:p.leaseId,nonce:u})}
|
|
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};
|
|
@@ -45,3 +45,65 @@ export interface ExtendStoryWriteSetOptions {
|
|
|
45
45
|
* integration lock serializes it with the single integrator.
|
|
46
46
|
*/
|
|
47
47
|
export declare function extendStoryWriteSet(options: ExtendStoryWriteSetOptions): Promise<StoryWriteSetExtensionResult>;
|
|
48
|
+
export declare const STORY_WRITE_SET_MANUAL_EDIT_REFUSED: "story-write-set-manual-edit-refused";
|
|
49
|
+
export declare const STORY_WRITE_SET_MANUAL_EDIT_UNVERIFIED: "story-write-set-manual-edit-unverified";
|
|
50
|
+
/** Closed, public-safe request a story child returns to the root (DEC-01). */
|
|
51
|
+
export interface StoryWriteSetExtensionRequest {
|
|
52
|
+
readonly schemaVersion: 1;
|
|
53
|
+
readonly kind: 'story-write-set-extension-request';
|
|
54
|
+
readonly storyId: string;
|
|
55
|
+
readonly epicId: string;
|
|
56
|
+
readonly outcome: 'requested' | 'already-authorized';
|
|
57
|
+
/** Authorized extension UNION the requested paths outside `files_to_modify` (the root needs a superset). */
|
|
58
|
+
readonly paths: readonly string[];
|
|
59
|
+
readonly requestedPathCount: number;
|
|
60
|
+
readonly digest: string;
|
|
61
|
+
readonly requestedBy: 'story_child';
|
|
62
|
+
/** Exact command only the root runs to apply the amendment under CAS; empty when nothing is outside `files_to_modify`. */
|
|
63
|
+
readonly applyCommand: string;
|
|
64
|
+
}
|
|
65
|
+
export type StoryWriteSetExtensionRequestResult = {
|
|
66
|
+
readonly ok: true;
|
|
67
|
+
readonly value: StoryWriteSetExtensionRequest;
|
|
68
|
+
} | {
|
|
69
|
+
readonly ok: false;
|
|
70
|
+
readonly reasonCode: string;
|
|
71
|
+
};
|
|
72
|
+
export type StoryWriteSetManualEditResult = {
|
|
73
|
+
readonly ok: true;
|
|
74
|
+
readonly value: {
|
|
75
|
+
readonly storiesCompared: number;
|
|
76
|
+
};
|
|
77
|
+
} | {
|
|
78
|
+
readonly ok: false;
|
|
79
|
+
readonly reasonCode: string;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* DEC-05: refuse a hand-edited `files_to_modify` (any story) in the candidate
|
|
83
|
+
* `state.json` against the authorized base: the merge-base of the candidate
|
|
84
|
+
* with the epic execution branch, or `HEAD` for a working-tree candidate when
|
|
85
|
+
* that branch is absent. The candidate is the checkout's working file, or the
|
|
86
|
+
* blob at the tip of `candidateRef` (a story temporary branch, root-side
|
|
87
|
+
* integration). Read-only; fail-closed.
|
|
88
|
+
*/
|
|
89
|
+
export declare function detectStoryWriteSetManualEdit(options: {
|
|
90
|
+
readonly projectRoot: string;
|
|
91
|
+
readonly storyId: string;
|
|
92
|
+
readonly candidateRef?: string;
|
|
93
|
+
}): Promise<StoryWriteSetManualEditResult>;
|
|
94
|
+
/**
|
|
95
|
+
* DEC-01: a story child asks for an amendment. Writes nothing (no state, no
|
|
96
|
+
* overlay, no lock) and runs in a secondary worktree; the root applies the
|
|
97
|
+
* returned `applyCommand` through `extendStoryWriteSet` under CAS.
|
|
98
|
+
*/
|
|
99
|
+
export declare function requestStoryWriteSetExtension(options: {
|
|
100
|
+
readonly projectRoot: string;
|
|
101
|
+
readonly storyId: string;
|
|
102
|
+
readonly paths: readonly string[];
|
|
103
|
+
}): Promise<StoryWriteSetExtensionRequestResult>;
|
|
104
|
+
/**
|
|
105
|
+
* DEC-05 for root-side integration: the temporary branch named by the story's
|
|
106
|
+
* live lease receipt; undefined when no lease receipt is recorded (the
|
|
107
|
+
* integrator then refuses on its own lease checks).
|
|
108
|
+
*/
|
|
109
|
+
export declare function storyWorktreeTemporaryBranchForManualEditGate(projectRoot: string, storyId: string): Promise<string | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFile as
|
|
1
|
+
import{execFile as T}from"node:child_process";import{createHash as Y}from"node:crypto";import{readFile as x,realpath as L}from"node:fs/promises";import{join as R,resolve as _}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLockWithin as U,ensureRuntimeStory as V,isStoryWorktreeIntegrationReceiptRecord as J,isStoryWriteSetExtension as Z,isStoryWriteSetExtensionPath as P,mutateGitLifecycleRuntime as K,readGitLifecycleRuntime as A,readStoryWorktreeEvidence as b,releaseGitLifecyclePhysicalIntegrationLock as X,STORY_WRITE_SET_MAX_ENTRIES as I,storyWriteSetExtensionDigest as O,storyWriteSetExtensionPaths as W,verifyGitLifecyclePhysicalIntegrationLock as Q}from"./git-lifecycle-store.js";const E=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class v extends Error{reasonCode;constructor(r){super(r),this.reasonCode=r}}function c(e){throw new v(e)}function $(e,r){return new Promise((t,n)=>{T("git",[...r],{cwd:e,encoding:"utf8",timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(s,o)=>s?n(new v("story-write-set-extension-not-root")):t(String(o).trim()))})}function l(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function B(e){try{return Z(e)}catch{return!1}}function ee(e){return Y("sha256").update([...e].sort().join("\0")).digest("hex")}function z(e,r,t,n,s){const o=l(l(r.stories)?.[t]);o||c("story-write-set-extension-story-missing");const i=typeof o.epic_id=="string"?o.epic_id:t.split(".")[0];t.startsWith(`${i}.`)||c("story-write-set-extension-story-missing");const a=e.stories[t];(b(e,i)?.receipts??[]).filter(J).some(y=>y.storyId===t&&y.outcome==="integrated")&&c("story-write-set-extension-story-integrated"),(a?.checkpoint||o.checkpoint)&&c("story-write-set-extension-checkpoint-accepted");const h=l(e.epics[i]?.branch_lease);h&&Date.parse(String(h.expiresAt))>s&&c("story-write-set-extension-writer-active"),a?.write_set_extension!==void 0&&!B(a.write_set_extension)&&c("story-write-set-extension-invalid");const f=W(a);f.some(y=>!n.includes(y))&&c("story-write-set-extension-not-superset");const d=Array.isArray(o.files_to_modify)?o.files_to_modify.filter(y=>typeof y=="string"):[],w=[...new Set([...d,...n])].sort();return w.length>I&&c("story-write-set-extension-too-large"),{epicId:i,union:w,unchanged:f.length===n.length}}async function de(e){const r=_(e.projectRoot);let t;try{(typeof e.storyId!="string"||!E.test(e.storyId))&&c("story-write-set-extension-story-invalid"),(!Array.isArray(e.paths)||e.paths.length===0||e.paths.length>I||e.paths.some(u=>!P(u)))&&c("story-write-set-extension-path-invalid");const n=[...new Set(e.paths)].sort(),s=await L(await $(r,["rev-parse","--absolute-git-dir"])),o=await L(await $(r,["rev-parse","--path-format=absolute","--git-common-dir"]));s!==o&&c("story-write-set-extension-not-root");const i=await q({projectRoot:r,storyId:e.storyId});i.ok||c(i.reasonCode);const a=new Date(e.nowIso??Date.now()).toISOString(),g=R(r,".neocortex","state.json"),h=async()=>{const u=await x(g,"utf8"),p=l(JSON.parse(u))??c("story-write-set-extension-state-invalid"),D=await A(r,{required:!0});return{trackedBytes:u,tracked:p,runtime:D,plan:z(D,p,e.storyId,n,Date.now())}},f=O(n),d=(u,p)=>({ok:!0,value:Object.freeze({storyId:e.storyId,epicId:u.epicId,outcome:p,extensionPathCount:n.length,extensionDigest:f,authorizedPathCount:u.union.length,claimRevision:ee(u.union)})}),w=await h();if(w.plan.unchanged)return d(w.plan,"unchanged");const y=`write-set-extension-${f.slice(0,40)}`;t=await U(r,{kind:"direct",storyId:e.storyId,sessionId:y,idempotencyKey:y,expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1},e.lockWait),t.ok||c(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-write-set-extension-backpressure":"story-write-set-extension-lock-failed");const m=t,{trackedBytes:N,tracked:G,runtime:F,plan:k}=await h();if(k.unchanged)return d(k,"unchanged");await e.beforeCas?.();const H={schemaVersion:1,kind:"root-write-set-extension",paths:n,digest:f,approvedAt:a,approvedBy:"root_agent"};try{await K(r,u=>{z(u,G,e.storyId,n,Date.now()).unchanged&&c("story-write-set-extension-raced"),V(u,e.storyId).write_set_extension=H},{expectedRevision:F.revision,preCommit:async()=>{await Q(m.path,m.owner)||c("story-write-set-extension-lock-raced"),await x(g,"utf8")!==N&&c("story-write-set-extension-raced")}})}catch(u){throw u instanceof Error&&u.message==="git-lifecycle-runtime-revision-conflict"&&c("story-write-set-extension-raced"),u}return d(k,"recorded")}catch(n){if(n instanceof v)return{ok:!1,reasonCode:n.reasonCode};const s=n instanceof Error?n.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(s)?{ok:!1,reasonCode:s}:{ok:!1,reasonCode:"story-write-set-extension-failed"}}finally{t?.ok&&await X(t.path,t.owner).catch(()=>{})}}const te="story-write-set-manual-edit-refused",re="story-write-set-manual-edit-unverified",ne="neocortex-client story-checkpoint extend-write-set",C=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;function S(e,r){return new Promise(t=>{T("git",[...r],{cwd:e,encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(n,s)=>t(n?void 0:String(s)))})}function j(e){if(e!==void 0)try{return l(JSON.parse(e))}catch{return}}function M(e){const r=l(e.stories)??{},t=new Map;for(const[n,s]of Object.entries(r)){const o=l(s)?.files_to_modify;o!==void 0&&t.set(n,Array.isArray(o)?JSON.stringify([...new Set(o.filter(i=>typeof i=="string"))].sort()):"!invalid")}return t}async function q(e){const r=_(e.projectRoot),t={ok:!1,reasonCode:re};if(typeof e.storyId!="string"||!E.test(e.storyId)||e.candidateRef!==void 0&&(!C.test(e.candidateRef)||e.candidateRef.includes("..")))return t;const n=e.candidateRef===void 0?await x(R(r,".neocortex","state.json"),"utf8").catch(()=>{}):await S(r,["show",`refs/heads/${e.candidateRef}:.neocortex/state.json`]),s=j(n);if(!s)return t;const o=l(l(s.stories)?.[e.storyId]),i=typeof o?.epic_id=="string"?o.epic_id:e.storyId.split(".")[0],a=l(l(s.epics)?.[i])?.execution_branch,g=e.candidateRef===void 0?"HEAD":`refs/heads/${e.candidateRef}`;let h;if(typeof a=="string"&&C.test(a)&&!a.includes("..")&&await S(r,["rev-parse","--verify","--quiet",`refs/heads/${a}^{commit}`])!==void 0){const y=(await S(r,["merge-base",g,`refs/heads/${a}`]))?.trim();if(!y||!/^[a-f0-9]{40,64}$/.test(y))return t;h=y}else if(e.candidateRef===void 0)h="HEAD";else return t;const f=j(await S(r,["show",`${h}:.neocortex/state.json`]));if(!f)return t;const d=M(f),w=M(s);for(const[y,m]of d)if(w.get(y)!==m)return{ok:!1,reasonCode:te};return{ok:!0,value:Object.freeze({storiesCompared:d.size})}}async function fe(e){const r=_(e.projectRoot);if(typeof e.storyId!="string"||!E.test(e.storyId))return{ok:!1,reasonCode:"story-write-set-extension-story-invalid"};if(!Array.isArray(e.paths)||e.paths.length===0||e.paths.length>I||e.paths.some(d=>!P(d)))return{ok:!1,reasonCode:"story-write-set-extension-path-invalid"};const t=await q({projectRoot:r,storyId:e.storyId});if(!t.ok)return t;const n=j(await x(R(r,".neocortex","state.json"),"utf8").catch(()=>{}));if(!n)return{ok:!1,reasonCode:"story-write-set-extension-state-invalid"};const s=l(l(n.stories)?.[e.storyId]);if(!s)return{ok:!1,reasonCode:"story-write-set-extension-story-missing"};const o=typeof s.epic_id=="string"?s.epic_id:e.storyId.split(".")[0];if(!e.storyId.startsWith(`${o}.`))return{ok:!1,reasonCode:"story-write-set-extension-story-missing"};let i;try{const w=(await A(r)).stories[e.storyId];if(w?.write_set_extension!==void 0&&!B(w.write_set_extension))return{ok:!1,reasonCode:"story-write-set-extension-invalid"};i=W(w)}catch{return{ok:!1,reasonCode:"story-write-set-extension-state-invalid"}}const a=new Set(Array.isArray(s.files_to_modify)?s.files_to_modify.filter(d=>typeof d=="string"):[]),g=new Set([...a,...i]),h=[...new Set(e.paths)].filter(d=>!g.has(d)),f=[...new Set([...i,...e.paths.filter(d=>!a.has(d))])].sort();return a.size+f.length>I?{ok:!1,reasonCode:"story-write-set-extension-too-large"}:{ok:!0,value:Object.freeze({schemaVersion:1,kind:"story-write-set-extension-request",storyId:e.storyId,epicId:o,outcome:h.length===0?"already-authorized":"requested",paths:Object.freeze(f),requestedPathCount:h.length,digest:O(f),requestedBy:"story_child",applyCommand:f.length>0?`${ne} --story ${e.storyId} --paths ${f.join(",")}`:""})}}async function ye(e,r){try{const t=await A(_(e)),n=r.split(".")[0],o=(b(t,n)?.receipts??[]).map(i=>l(i)).filter(i=>i?.kind==="story-worktree-lease"&&i.storyId===r&&typeof i.temporaryBranch=="string"&&C.test(i.temporaryBranch)).sort((i,a)=>String(i.acquiredAt??"").localeCompare(String(a.acquiredAt??""))).at(-1);return o?String(o.temporaryBranch):void 0}catch{return}}export{te as STORY_WRITE_SET_MANUAL_EDIT_REFUSED,re as STORY_WRITE_SET_MANUAL_EDIT_UNVERIFIED,q as detectStoryWriteSetManualEdit,de as extendStoryWriteSet,fe as requestStoryWriteSetExtension,ye as storyWorktreeTemporaryBranchForManualEditGate};
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* at runtime. Keep this file in sync with `packages/shared/src/project-memory-*`
|
|
6
6
|
* and enforce drift through the P130.06 release tests.
|
|
7
7
|
*/
|
|
8
|
-
export type ProjectMemoryTargetId = 'canonical' | 'claude-code' | 'codex' | 'grok' | 'gemini-cli' | 'antigravity' | 'vscode' | 'cursor' | 'opencode' | 'openclaw' | 'kimi' | 'github-copilot-cli';
|
|
8
|
+
export type ProjectMemoryTargetId = 'canonical' | 'claude-code' | 'codex' | 'grok' | 'gemini-cli' | 'antigravity' | 'vscode' | 'cursor' | 'opencode' | 'openclaw' | 'kimi' | 'github-copilot-cli' | 'deepseek';
|
|
9
9
|
export type ProjectMemoryTemplateKind = 'neocortex-md' | 'claude-md' | 'agents-md' | 'gemini-md' | 'copilot-instructions' | 'cursor-rule';
|
|
10
10
|
export interface ProjectMemoryBudget {
|
|
11
11
|
readonly maxLines: number;
|
|
@@ -71,7 +71,14 @@ export interface BootstrapArchitectureMemory {
|
|
|
71
71
|
readonly heuristics?: readonly string[];
|
|
72
72
|
}
|
|
73
73
|
export declare const CANONICAL_PROJECT_MEMORY_SOURCE: "NEOCORTEX.md";
|
|
74
|
-
export declare const PROJECT_MEMORY_TARGET_IDS: readonly ["claude-code", "codex", "grok", "gemini-cli", "antigravity", "vscode", "cursor", "opencode", "openclaw", "kimi", "github-copilot-cli"];
|
|
74
|
+
export declare const PROJECT_MEMORY_TARGET_IDS: readonly ["claude-code", "codex", "grok", "gemini-cli", "antigravity", "vscode", "cursor", "opencode", "openclaw", "kimi", "github-copilot-cli", "deepseek"];
|
|
75
|
+
/**
|
|
76
|
+
* P228.20: native per-story child profiles (`neocortex-sentinel`). The child
|
|
77
|
+
* receives only the server-authored per-story prompt, so these paths are never
|
|
78
|
+
* memory wrappers: no target lists them as primary or secondary file. The
|
|
79
|
+
* orchestrator `neocortex` and the alias `neocortex-root` keep their wrappers.
|
|
80
|
+
*/
|
|
81
|
+
export declare const PROJECT_MEMORY_CHILD_PROFILE_PATHS: readonly [".claude/agents/neocortex-sentinel.md", ".gemini/agents/neocortex-sentinel.md", ".opencode/agents/neocortex-sentinel.md", ".codex/agents/neocortex-sentinel.toml"];
|
|
75
82
|
export declare const PROJECT_MEMORY_TARGETS: {
|
|
76
83
|
readonly canonical: {
|
|
77
84
|
readonly targetId: "canonical";
|
|
@@ -400,6 +407,36 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
400
407
|
readonly requiresWrapperPreservation: true;
|
|
401
408
|
readonly notes: "GitHub Copilot CLI or gh alias instructions. Resolve compact memory back to NEOCORTEX.md without copying private prompt bodies.";
|
|
402
409
|
};
|
|
410
|
+
readonly deepseek: {
|
|
411
|
+
readonly targetId: "deepseek";
|
|
412
|
+
readonly platformName: "DeepSeek Harness";
|
|
413
|
+
readonly canonicalSource: "NEOCORTEX.md";
|
|
414
|
+
readonly primaryFile: ".dsh/skills/neocortex/SKILL.md";
|
|
415
|
+
readonly secondaryFiles: readonly [{
|
|
416
|
+
readonly scope: "user";
|
|
417
|
+
readonly path: ".dsh/skills/neocortex/SKILL.md";
|
|
418
|
+
}];
|
|
419
|
+
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
420
|
+
readonly templateKind: "agents-md";
|
|
421
|
+
readonly budget: {
|
|
422
|
+
readonly maxLines: 220;
|
|
423
|
+
readonly maxBytes: 18000;
|
|
424
|
+
};
|
|
425
|
+
readonly linkRequirement: {
|
|
426
|
+
readonly canonicalSource: "NEOCORTEX.md";
|
|
427
|
+
readonly semanticFileRequired: true;
|
|
428
|
+
readonly symlinkBacked: true;
|
|
429
|
+
readonly wrapperAllowed: true;
|
|
430
|
+
readonly includeFallbackAllowed: true;
|
|
431
|
+
readonly requiresWrapperPreservation: true;
|
|
432
|
+
readonly fallbackIsCompatibilityRemediation: true;
|
|
433
|
+
readonly policy: "safe-include-fallback";
|
|
434
|
+
readonly notes: "Use a safe include/import only for platforms that cannot consume symlinks directly; the include must resolve back to NEOCORTEX.md.";
|
|
435
|
+
};
|
|
436
|
+
readonly bidirectionalReference: ProjectMemoryBidirectionalReference;
|
|
437
|
+
readonly requiresWrapperPreservation: true;
|
|
438
|
+
readonly notes: "DeepSeek Harness Skill thin-client memory entrypoint (P228.04). Use the project Skill path when --create-project is requested and keep memory content public-safe.";
|
|
439
|
+
};
|
|
403
440
|
};
|
|
404
441
|
export declare function getProjectMemoryTarget(targetId: ProjectMemoryTargetId): ProjectMemoryTarget;
|
|
405
442
|
export declare function isProjectMemoryTargetId(value: string): value is ProjectMemoryTargetId;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function i(...
|
|
2
|
-
`)}export{e as CANONICAL_PROJECT_MEMORY_SOURCE,m as PROJECT_MEMORY_TARGETS,s as PROJECT_MEMORY_TARGET_IDS,
|
|
1
|
+
function i(...o){return o.map(a=>({scope:"project",path:a}))}const e="NEOCORTEX.md",r={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!1,includeFallbackAllowed:!1,requiresWrapperPreservation:!1,fallbackIsCompatibilityRemediation:!0,policy:"mandatory-semantic-symlink",notes:"Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter."},l={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!0,includeFallbackAllowed:!1,requiresWrapperPreservation:!0,fallbackIsCompatibilityRemediation:!0,policy:"symlink-backed-wrapper",notes:"Platform wrapper/frontmatter is allowed only when the semantic memory payload remains symlink-backed by NEOCORTEX.md."},n={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!0,includeFallbackAllowed:!0,requiresWrapperPreservation:!0,fallbackIsCompatibilityRemediation:!0,policy:"safe-include-fallback",notes:"Use a safe include/import only for platforms that cannot consume symlinks directly; the include must resolve back to NEOCORTEX.md."};function t(o){return{canonicalSource:e,resolvesVia:o.policy,feedbackTrigger:"*update-memory",guidance:"Treat NEOCORTEX.md as canonical project memory; consult it before platform-specific memory, and run *update-memory when durable project context changes should flow back to the canonical source."}}const s=["claude-code","codex","grok","gemini-cli","antigravity","vscode","cursor","opencode","openclaw","kimi","github-copilot-cli","deepseek"],p=Object.freeze([".claude/agents/neocortex-sentinel.md",".gemini/agents/neocortex-sentinel.md",".opencode/agents/neocortex-sentinel.md",".codex/agents/neocortex-sentinel.toml"]),m={canonical:{targetId:"canonical",platformName:"Neocortex Canonical Memory",canonicalSource:e,primaryFile:e,secondaryFiles:i("AGENTS.md","CLAUDE.md","GEMINI.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"neocortex-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Canonical compact project memory source for platform symlinks and wrappers. Store only summaries, indexes, and links to architecture docs here."},"claude-code":{targetId:"claude-code",platformName:"Claude Code",canonicalSource:e,primaryFile:"CLAUDE.md",secondaryFiles:i(),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"claude-md",budget:{maxLines:320,maxBytes:28e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Claude Code project memory. Resolve to NEOCORTEX.md; keep root content concise and link deeper docs with @path references."},codex:{targetId:"codex",platformName:"Codex CLI",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".codex/agents/neocortex.toml"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!0,notes:"Codex root instructions. Uppercase AGENTS.md is required on case-sensitive filesystems."},grok:{targetId:"grok",platformName:"Grok Build",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".grok/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!0,notes:"Grok Build reads AGENTS.md and the project-local Neocortex Skill; both resolve to canonical NEOCORTEX.md context."},"gemini-cli":{targetId:"gemini-cli",platformName:"Gemini CLI",canonicalSource:e,primaryFile:"GEMINI.md",secondaryFiles:i(),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"gemini-md",budget:{maxLines:260,maxBytes:22e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Gemini CLI context file. Prefer shallow @file.md imports for detailed architecture docs."},antigravity:{targetId:"antigravity",platformName:"Antigravity",canonicalSource:e,primaryFile:"GEMINI.md",secondaryFiles:i(),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"gemini-md",budget:{maxLines:260,maxBytes:22e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Antigravity currently shares GEMINI.md behavior with the Gemini target stubs."},vscode:{targetId:"vscode",platformName:"VS Code / GitHub Copilot",canonicalSource:e,primaryFile:".github/copilot-instructions.md",secondaryFiles:i(".github/instructions/neocortex.instructions.md",".github/agents/neocortex.agent.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"copilot-instructions",budget:{maxLines:180,maxBytes:14e3},linkRequirement:l,bidirectionalReference:t(l),requiresWrapperPreservation:!0,notes:"VS Code and GitHub Copilot always-on repository instructions."},cursor:{targetId:"cursor",platformName:"Cursor",canonicalSource:e,primaryFile:".cursor/rules/neocortex.mdc",secondaryFiles:i("AGENTS.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"cursor-rule",budget:{maxLines:180,maxBytes:14e3},linkRequirement:l,bidirectionalReference:t(l),requiresWrapperPreservation:!0,notes:"Cursor rule memory. Use AGENTS.md as compatibility fallback when Cursor rules are absent."},opencode:{targetId:"opencode",platformName:"OpenCode",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".opencode/AGENTS.md",".opencode/agents/neocortex-root.md",".opencode/agents/neocortex.md",".agent/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!0,notes:"OpenCode agent memory. It consumes AGENTS.md-compatible instructions and must resolve to canonical NEOCORTEX.md."},openclaw:{targetId:"openclaw",platformName:"OpenClaw",canonicalSource:e,primaryFile:".openclaw/skills/neocortex/SKILL.md",secondaryFiles:[{scope:"user",path:".openclaw/skills/neocortex/SKILL.md"}],ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"OpenClaw Skill thin-client memory entrypoint. Use the project Skill path when --create-project is requested; do not mutate ~/.openclaw/openclaw.json, and keep memory content public-safe."},kimi:{targetId:"kimi",platformName:"Kimi",canonicalSource:e,primaryFile:"KIMI.md",secondaryFiles:i("AGENTS.md",".kimi/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"Kimi memory entrypoint. Prefer a symlink to NEOCORTEX.md; use a compact include only if the host cannot follow symlinks."},"github-copilot-cli":{targetId:"github-copilot-cli",platformName:"GitHub Copilot CLI / gh alias",canonicalSource:e,primaryFile:".github/copilot-instructions.md",secondaryFiles:i("AGENTS.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"copilot-instructions",budget:{maxLines:180,maxBytes:14e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"GitHub Copilot CLI or gh alias instructions. Resolve compact memory back to NEOCORTEX.md without copying private prompt bodies."},deepseek:{targetId:"deepseek",platformName:"DeepSeek Harness",canonicalSource:e,primaryFile:".dsh/skills/neocortex/SKILL.md",secondaryFiles:[{scope:"user",path:".dsh/skills/neocortex/SKILL.md"}],ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"DeepSeek Harness Skill thin-client memory entrypoint (P228.04). Use the project Skill path when --create-project is requested and keep memory content public-safe."}};function u(o){return m[o]}function y(o){return o==="canonical"||s.includes(o)}function E(){return s.map(o=>m[o])}function R(o){const a=c=>c.replace(/\|/g,"\\|").replace(/\n/g," ");return["| Path | Title | Purpose | Suggested Usage |","| --- | --- | --- | --- |",...o.map(c=>`| ${a(c.path)} | ${a(c.title)} | ${a(c.purpose)} | ${a(c.suggestedUsage)} |`)].join(`
|
|
2
|
+
`)}export{e as CANONICAL_PROJECT_MEMORY_SOURCE,p as PROJECT_MEMORY_CHILD_PROFILE_PATHS,m as PROJECT_MEMORY_TARGETS,s as PROJECT_MEMORY_TARGET_IDS,u as getProjectMemoryTarget,y as isProjectMemoryTargetId,E as listProjectMemoryTargets,R as renderArchitectureReferenceTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const u=1,p="max",s="[P201-EV-MAX-POLICY]",c=new Set(["claude-code","cursor","vscode","gemini","codex","opencode","github-copilot-cli","kimi","antigravity","openclaw","grok","deepseek","runner","unknown"]),r=e=>c.has(e)?e:"unknown",d=Object.freeze({"claude-code":{status:"validated",scope:"child",fallbackMode:"none",fallbackReasonCode:null},opencode:{status:"unvalidated",scope:"child",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},codex:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},gemini:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},vscode:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},"github-copilot-cli":{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},kimi:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},cursor:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},antigravity:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},grok:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},openclaw:{status:"
|
|
1
|
+
const u=1,p="max",s="[P201-EV-MAX-POLICY]",c=new Set(["claude-code","cursor","vscode","gemini","codex","opencode","github-copilot-cli","kimi","antigravity","openclaw","grok","deepseek","runner","unknown"]),r=e=>c.has(e)?e:"unknown",d=Object.freeze({"claude-code":{status:"validated",scope:"child",fallbackMode:"none",fallbackReasonCode:null},opencode:{status:"unvalidated",scope:"child",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},codex:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},gemini:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},vscode:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},"github-copilot-cli":{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},kimi:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},cursor:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},antigravity:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},grok:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},openclaw:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},deepseek:{status:"unsupported",scope:"none",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unsupported"},runner:{status:"unsupported",scope:"none",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unsupported"},unknown:{status:"unsupported",scope:"none",fallbackMode:"shell-loop",fallbackReasonCode:"platform-target-unknown"}}),n=Object.freeze({disabled:0,standard:1,max:2});function f(e){return e==="max"||e==="standard"||e==="disabled"}function i(e){const o=r(e),a=d[o];return o==="unknown"?Object.freeze({platformTarget:o,maximumMode:"disabled",scope:a.scope,reductionReason:"platform-target-unknown"}):a.status==="unsupported"?Object.freeze({platformTarget:o,maximumMode:"disabled",scope:a.scope,reductionReason:"host-capability-unsupported"}):a.status==="unvalidated"?Object.freeze({platformTarget:o,maximumMode:"standard",scope:a.scope,reductionReason:"host-capability-unvalidated"}):Object.freeze({platformTarget:o,maximumMode:"max",scope:a.scope,reductionReason:"host-policy-reduced"})}function b(e={}){const o=e.userOverride??"max",a=e.hostPolicy??i(e.platformTarget),t=d[a.platformTarget],l=n[o]>n[a.maximumMode];return Object.freeze({schemaVersion:1,requestedMode:o,effectiveMode:l?a.maximumMode:o,source:e.userOverride?"user-override":"managed-default",platformTarget:a.platformTarget,scope:a.scope,effectiveReason:l?a.reductionReason:"requested-mode-honored",fallbackMode:t.fallbackMode,fallbackReasonCode:t.fallbackReasonCode})}function m(e,o,a){return Object.freeze({evidence:s,event:e,occurredAt:a,...o})}export{s as SUBAGENT_APPROVAL_EVIDENCE,p as SUBAGENT_APPROVAL_MANAGED_DEFAULT,u as SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION,m as createSubagentApprovalAuditEvent,i as deriveSubagentHostApprovalPolicy,f as isSubagentApprovalMode,b as resolveSubagentApprovalPolicy};
|
|
@@ -1,6 +1,26 @@
|
|
|
1
|
+
import { type PrivateHarnessAdapter } from './harness-executor.js';
|
|
2
|
+
import type { PRIVATE_EXECUTION_CODEX_HOST_KIND } from '../../../shared/dist/compatibility/index.js';
|
|
3
|
+
export declare const PRIVATE_CODEX_DATA_CONTROLS: readonly string[];
|
|
4
|
+
/**
|
|
5
|
+
* P229.01 (CON-P229.01-CODEX-PARITY): Codex is the first declarative
|
|
6
|
+
* PrivateHarnessAdapter. The Linux exec argv below is assembled from this
|
|
7
|
+
* declaration so the bytes stay identical to the P222.16 path; the supervised
|
|
8
|
+
* Linux guard and the v6 preflight remain Codex-specific.
|
|
9
|
+
*
|
|
10
|
+
* P229.02 (AC3): the declaration admits darwin and win32 through the
|
|
11
|
+
* host-neutral core port; `preflightPrivateCodexExecutor`/`runPrivateCodexStep`
|
|
12
|
+
* (v6) stay Linux-only and byte-identical.
|
|
13
|
+
*/
|
|
14
|
+
export declare const PRIVATE_CODEX_HARNESS_ADAPTER: PrivateHarnessAdapter;
|
|
15
|
+
/**
|
|
16
|
+
* Codex-host attributes of the private-execution envelope (P228.18, ADR-3).
|
|
17
|
+
* The Linux platform, ChatGPT subscription login and the v6 sandbox proof are
|
|
18
|
+
* preconditions of this executor only; the envelope itself is host-neutral and
|
|
19
|
+
* other enum hosts never run this preflight.
|
|
20
|
+
*/
|
|
1
21
|
export interface PrivateCodexPreflightV6 {
|
|
2
22
|
readonly schemaVersion: 6;
|
|
3
|
-
readonly hostKind:
|
|
23
|
+
readonly hostKind: typeof PRIVATE_EXECUTION_CODEX_HOST_KIND;
|
|
4
24
|
readonly hostVersion: string;
|
|
5
25
|
readonly projectRoot: string;
|
|
6
26
|
readonly observedAtMs: number;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{codexLifecycleGuardPath as
|
|
2
|
-
`),
|
|
3
|
-
`))>=0;){const
|
|
4
|
-
`)throw new Error("private-codex-workspace-write-unproven")}catch{throw new Error("private-codex-workspace-write-unproven")}finally{try{
|
|
1
|
+
import{codexLifecycleGuardPath as Y}from"./codex-lifecycle-guard.js";import{execFileSync as q,spawn as U}from"node:child_process";import{createHash as k,randomBytes as Z}from"node:crypto";import{connect as Q,createServer as ee}from"node:net";import{accessSync as M,lstatSync as T,mkdtempSync as te,readFileSync as re,realpathSync as oe,rmdirSync as B,unlinkSync as C,constants as L}from"node:fs";import{homedir as ne}from"node:os";import{join as E,resolve as H}from"node:path";import{gitLifecycleRuntimeDirectory as ie}from"../git/git-lifecycle-store.js";import{captureDirectYoloCheckoutEvidence as j}from"../git/direct-yolo-checkpoint.js";import{createPrivateCodexScopedRunner as se}from"./codex-scoped-permissions.js";import{createPrivateCodexHostRuntime as ae}from"./codex-host-runtime.js";import{sha256Hex as N}from"./harness-executor.js";import{assertPrivateHarnessMaterial as ce}from"./harness-process.js";const G=3e4,m=16*1024,de=1024*1024,I=/^codex-cli\s+(\d+\.\d+\.\d+)\s*$/,y="p222-isolated",z=["PATH","HOME","LANG","LC_ALL","TERM","CODEX_HOME"],$=Object.freeze(["-c",'web_search="disabled"',"-c","features.hooks=false","-c","analytics.enabled=false","-c",'history.persistence="none"',"-c",'otel.exporter="none"',"-c",'otel.metrics_exporter="none"',"-c",'otel.trace_exporter="none"',"-c","otel.log_user_prompt=false","-c","notify=[]"]),ue=Object.freeze({hostKind:"codex-cli",binary:"codex",fixedArgs:Object.freeze(["exec","--ephemeral","--json","--strict-config","-c","features.plugins=false"]),stdinFlag:"-",nativeFlags:$,configDirEnv:"CODEX_HOME",credentialFiles:Object.freeze(["auth.json","config.toml"]),environmentKeys:z,versionArgs:Object.freeze(["--version"]),versionPattern:I,minimumVersion:"0.0.0",platforms:Object.freeze(["linux","darwin","win32"]),credentialSource:Object.freeze({env:"CODEX_HOME",homeRelative:".codex"})});function le(r){try{return ce(r),!0}catch{return!1}}const D=new WeakMap,P=new WeakMap;function fe(r){const e={};for(const t of z)typeof r[t]=="string"&&(e[t]=r[t]);return e}async function F(r,e){if(e.configReadProbe&&(e.stdin!==void 0||r.at(-1)!=="app-server"))throw new Error("private-codex-web-search-isolation-unproven");return new Promise((t,o)=>{const i=fe(process.env);e.codexHome!==void 0&&(i.CODEX_HOME=e.codexHome);const n=process.platform==="linux",a=U(n?process.execPath:e.codexHome===void 0?"codex":"/bin/sh",n?[Y,"process"]:e.codexHome===void 0?[...r]:["-c",'umask 077; exec codex "$@"',"neocortex-private-codex",...r],{cwd:e.cwd,stdio:n?["pipe","pipe","pipe","ipc"]:["pipe","pipe","pipe"],env:i,detached:n}),d=()=>{if(process.platform==="linux"&&a.pid!==void 0)try{process.kill(-a.pid,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}else a.kill("SIGKILL")},s=[],u=[];let w=0,f=0,c=!1,p=!1,x="",S=!1;const b=l=>a.stdin.write(`${JSON.stringify(l)}
|
|
2
|
+
`),O=setTimeout(()=>{c=!0,d()},e.timeoutMs);a.stdout.on("data",l=>{if(w+=l.byteLength,w+f>e.maxOutputBytes)p=!0,d();else if(s.push(l),e.configReadProbe){x+=l.toString("utf8");let v;for(;(v=x.indexOf(`
|
|
3
|
+
`))>=0;){const A=x.slice(0,v);x=x.slice(v+1);try{const R=JSON.parse(A);R.id===1&&R.result&&!S?(S=!0,b({method:"initialized",params:{}}),b({id:2,method:"config/read",params:{includeLayers:!1,cwd:e.cwd}})):R.id===2&&a.stdin.end()}catch{}}}}),a.stderr.on("data",l=>{f+=l.byteLength,w+f>e.maxOutputBytes?(p=!0,d()):u.push(l)}),a.on("error",l=>{clearTimeout(O),o(l)}),a.on("close",l=>{clearTimeout(O),t({exitCode:l,stdout:Buffer.concat(s),stderr:Buffer.concat(u),timedOut:c,outputExceeded:p})}),a.stdin.on("error",()=>{}),n&&a.send({kind:"private-codex-launch",args:[...r],codexHome:e.codexHome},l=>{l&&(clearTimeout(O),d(),o(new Error("private-codex-process-guard-unavailable")))}),e.configReadProbe?b({id:1,method:"initialize",params:{clientInfo:{name:"p222-isolation-probe",version:"1"},capabilities:{}}}):a.stdin.end(e.stdin)})}function h(r){return r.exitCode===0&&!r.timedOut&&!r.outputExceeded}async function W(r,e){const t=await e(["-c","features.plugins=false","plugin","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m}),o=await e(["mcp","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t)||!h(o))return null;try{const i=JSON.parse(t.stdout.toString("utf8")),n=JSON.parse(o.stdout.toString("utf8"));if(!!!(i&&typeof i=="object"&&!Array.isArray(i)&&Array.isArray(i.installed)&&i.installed.length===0)||!Array.isArray(n)||n.length>64)return null;const d=n.map(c=>{if(!c||typeof c!="object"||Array.isArray(c))throw new Error("invalid catalog");const p=c;if(typeof p.name!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(p.name)||typeof p.enabled!="boolean")throw new Error("invalid catalog");return p.name});if(new Set(d).size!==d.length)return null;if(d.length===0)return[];const s=[...d].sort().flatMap(c=>["-c",`mcp_servers.${c}.enabled=false`]),u=await e([...s,"mcp","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(u))return null;const w=JSON.parse(u.stdout.toString("utf8"));if(!Array.isArray(w)||w.length!==d.length)return null;const f=new Set;for(const c of w){if(!c||typeof c!="object"||Array.isArray(c)||typeof c.name!="string"||!d.includes(c.name)||c.enabled!==!1||f.has(c.name))return null;f.add(c.name)}return Object.freeze(s)}catch{return null}}async function V(r,e){const t=await e(["-c","features.hooks=false","features","list"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t))return!1;const o=t.stdout.toString("utf8").split(/\r?\n/).filter(i=>/^hooks\s+\S+\s+(?:true|false)\s*$/.test(i));return o.length===1&&/^hooks\s+\S+\s+false\s*$/.test(o[0])}async function K(r,e,t){const o=await e(["-c","features.plugins=false",...t,...$,"--strict-config","app-server"],{cwd:r,configReadProbe:!0,timeoutMs:1e4,maxOutputBytes:262144});try{if(!h(o))return!1;const n=o.stdout.toString("utf8").split(/\r?\n/).filter(Boolean).map(a=>JSON.parse(a)).filter(a=>a&&a.id===2);return n.length===1&&!n[0].error&&n[0].result?.config?.web_search==="disabled"}catch{return!1}finally{o.stdout.fill(0),o.stderr.fill(0)}}function pe(r){const e=T(r);if(!e.isFile()||e.isSymbolicLink())throw new Error("private-codex-auth-unavailable");M(r,L.R_OK)}function X(r){const e={...process.env};for(const t of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[t];try{const t=i=>q("git",[...i],{cwd:r,env:e,encoding:"utf8",timeout:5e3,maxBuffer:m,stdio:["ignore","pipe","ignore"]}).trim(),o=[t(["rev-parse","--git-dir"]),t(["rev-parse","--git-common-dir"])].map(i=>oe(H(r,i)));if(o.some(i=>!T(i).isDirectory()))throw new Error("git-control-invalid");return[...new Set(o)]}catch{throw new Error("private-codex-git-control-unavailable")}}async function me(r,e){const t=await e(["sandbox","-P",y,"--","git","rev-parse","--git-dir"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t))return!1;for(const o of X(r)){const i=E(o,`.neocortex-git-probe-${Z(16).toString("hex")}`),n=await e(["sandbox","-P",y,"--","sh","-c",'mkdir "$1"',"sh",i],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});let a=!1,d=!1;try{const s=T(i);a=!0,d=s.isDirectory()}catch(s){if(s.code!=="ENOENT")return!1}if(a&&(d?B(i):C(i)),n.exitCode!==1||n.timedOut||n.outputExceeded||a)return!1}return!0}async function we(r,e,t){if(!T(e).isDirectory())return!1;M(e,L.R_OK);const o=await t(["sandbox","-P",y,"--","sh","-c",'if test -r "$1"; then exit 42; else exit 43; fi',"sh",e],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});return o.exitCode===43&&!o.timedOut&&!o.outputExceeded}async function he(r,e){const t=ee(o=>o.end());await new Promise((o,i)=>{t.once("error",i),t.listen(0,"127.0.0.1",()=>o())});try{const o=t.address();if(!o||typeof o=="string")return!1;const i='const s=require("node:net").connect(Number(process.argv[1]),"127.0.0.1");s.setTimeout(1500);s.on("connect",()=>{s.end();process.exit(0)});s.on("error",()=>process.exit(1));s.on("timeout",()=>process.exit(1))';if(!await new Promise(s=>{const u=Q(o.port,"127.0.0.1");u.setTimeout(1500),u.once("connect",()=>{u.end(),s(!0)}),u.once("error",()=>s(!1)),u.once("timeout",()=>{u.destroy(),s(!1)})}))return!1;const a=await e(["sandbox","-P",y,"--","node","--version"],{cwd:r,timeoutMs:5e3,maxOutputBytes:m});if(!h(a))return!1;const d=await e(["sandbox","-P",y,"--","node","-e",i,String(o.port)],{cwd:r,timeoutMs:5e3,maxOutputBytes:m});return d.exitCode===1&&!d.timedOut&&!d.outputExceeded}finally{t.close()}}async function Ae(r,e={}){if((e.platform??process.platform)!=="linux")throw new Error("private-codex-platform-unsupported");const t=H(r),o=e.userHome??ne(),i=e.codexHome??process.env.CODEX_HOME??E(o,".codex"),n=e.runner?void 0:ae(t,i);try{const a=n?async(g,J)=>(n.verify(),F(g,{...J,codexHome:n.home})):F,d=n?.home??i,s=e.runner??await se(t,a,{...e,codexHome:d,credentialSourceHome:n?.sourceHome??i,gitControlDirectories:X(t)}),u=E(d,"auth.json");try{pe(u)}catch{throw new Error("private-codex-auth-unavailable")}const w=await s(["--version"],{cwd:t,timeoutMs:5e3,maxOutputBytes:m}),f=h(w)?I.exec(w.stdout.toString("utf8").trim()):null;if(!f)throw new Error("private-codex-version-unavailable");const c=await s(["login","status"],{cwd:t,timeoutMs:5e3,maxOutputBytes:m});if(!h(c)||!/Logged in using ChatGPT/i.test(Buffer.concat([c.stdout,c.stderr]).toString("utf8")))throw new Error("private-codex-subscription-required");const p=await W(t,s).catch(()=>null);if(p===null)throw new Error("private-codex-mcp-isolation-unproven");if(!await V(t,s).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");if(!await K(t,s,p).catch(()=>!1))throw new Error("private-codex-web-search-isolation-unproven");const S=await ie(t).catch(()=>{throw new Error("private-codex-git-lifecycle-read-isolation-unproven")}),b=E(o,".ssh"),O=await s(["sandbox","-P",y,"--","sh","-c",...n?['test ! -r "$1" && test ! -r "$2" && test ! -r "$3"',"sh",u,b,E(i,"auth.json")]:['test ! -r "$1" && test ! -r "$2"',"sh",u,b]],{cwd:t,timeoutMs:1e4,maxOutputBytes:m});if(!h(O))throw new Error("private-codex-auth-isolation-unproven");const l=te(E(t,".private-codex-probe-")),v=E(l,"receipt");try{const g=await s(["sandbox","-P",y,"--","sh","-c",'printf "P222_PROBE\\n" > "$1"',"sh",v],{cwd:t,timeoutMs:1e4,maxOutputBytes:m});if(!h(g)||re(v,"utf8")!==`P222_PROBE
|
|
4
|
+
`)throw new Error("private-codex-workspace-write-unproven")}catch{throw new Error("private-codex-workspace-write-unproven")}finally{try{C(v)}catch{}B(l)}if(!await me(t,s).catch(()=>!1))throw new Error("private-codex-git-control-isolation-unproven");if(!await we(t,S,s).catch(()=>!1))throw new Error("private-codex-git-lifecycle-read-isolation-unproven");if(!await(e.networkProbe??he)(t,s))throw new Error("private-codex-network-isolation-unproven");const _=Object.freeze({schemaVersion:6,hostKind:"codex-cli",hostVersion:f[1],projectRoot:t,observedAtMs:(e.now??Date.now)(),authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",credentialKind:"chatgpt-subscription"});if(D.set(_,s),n){const g=setTimeout(()=>{P.delete(_),D.delete(_);try{n.close()}catch{}},G);g.unref(),P.set(_,{runtime:n,timer:g})}return _}catch(a){throw n?.close(),a}}async function ke(r,e,t={}){const o=P.get(e);o&&(clearTimeout(o.timer),P.delete(e));try{const i=(t.now??Date.now)();if(t.model!==void 0&&!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(t.model))throw new Error("private-codex-model-invalid");if(e.schemaVersion!==6||e.hostKind!=="codex-cli"||e.authIsolation!=="passed"||e.workspaceWrite!=="passed"||e.gitControlWriteDenied!=="passed"||e.gitLifecycleReadDenied!=="passed"||e.mcpIsolation!=="passed"||e.environmentIsolation!=="passed"||e.webSearchDisabled!=="passed"||e.networkDenied!=="passed"||e.credentialKind!=="chatgpt-subscription"||i<e.observedAtMs||i-e.observedAtMs>G||!le(r))throw new Error("private-codex-preflight-stale");const n=t.runner??D.get(e);if(!n)throw new Error("private-codex-preflight-stale");const a=await n(["--version"],{cwd:e.projectRoot,timeoutMs:5e3,maxOutputBytes:m});if(!h(a)||I.exec(a.stdout.toString("utf8").trim())?.[1]!==e.hostVersion)throw new Error("private-codex-version-drift");const d=(c,p)=>{const x=Object.freeze({schemaVersion:1,kind:"PrivateCodexWorkspaceEffectFailure/1",phase:c,agentReturnedSuccessfully:p!==void 0,...p===void 0?{}:{stdoutSha256:k("sha256").update(p.stdout).digest("hex"),stderrSha256:k("sha256").update(p.stderr).digest("hex"),stdoutBytes:p.stdout.length,stderrBytes:p.stderr.length},publicSafe:!0});try{Promise.resolve(t.onWorkspaceEffectFailure?.(x)).catch(()=>{})}catch{}return new Error("private-codex-workspace-effect-unverified")},s=t.requireWorkspaceEffect?await j(e.projectRoot).catch(()=>{throw d("before-capture")}):void 0;if(s&&t.expectedExecutionBranch!==void 0&&s.branch!==t.expectedExecutionBranch)throw d("branch-before");if(!await V(e.projectRoot,n).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");const u=await W(e.projectRoot,n).catch(()=>null);if(u===null)throw new Error("private-codex-mcp-isolation-unproven");if(!await K(e.projectRoot,n,u).catch(()=>!1))throw new Error("private-codex-web-search-isolation-unproven");const w=ue,f=await n([...w.fixedArgs,...t.model===void 0?[]:["--model",t.model],...u,...w.nativeFlags,"-c","shell_environment_policy.ignore_default_excludes=false","-c",'shell_environment_policy.include_only=["PATH","HOME","LANG","LC_ALL","TERM"]',"-c",`default_permissions="${y}"`,"-C",e.projectRoot,w.stdinFlag],{cwd:e.projectRoot,stdin:r,timeoutMs:10*6e4,maxOutputBytes:de});if(!h(f))throw new Error("private-codex-execution-unverified");if(o?.runtime.verify(),s){const c=await j(e.projectRoot).catch(()=>{throw d("after-capture",f)});if(c.headSha!==s.headSha||c.branch!==s.branch)throw d("identity-after",f);if(c.payloadDigest===s.payloadDigest)throw d("no-payload-change",f)}return Object.freeze({schemaVersion:1,outcome:"executor-returned-unverified",exitCode:0,stdoutSha256:N(f.stdout),stderrSha256:N(f.stderr),stdoutBytes:f.stdout.byteLength,stderrBytes:f.stderr.byteLength,publicSafe:!0})}finally{o&&(D.delete(e),o.runtime.close())}}export{$ as PRIVATE_CODEX_DATA_CONTROLS,ue as PRIVATE_CODEX_HARNESS_ADAPTER,Ae as preflightPrivateCodexExecutor,fe as privateCodexEnvironment,F as runBoundedCodexProcess,ke as runPrivateCodexStep};
|