@ornexus/neocortex 4.64.4 → 4.65.0
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 +1193 -1193
- package/install.ps1 +7 -1
- package/install.sh +7 -1
- package/package.json +2 -2
- package/packages/client/dist/agent/claude-worktree-base.d.ts +18 -0
- package/packages/client/dist/agent/claude-worktree-base.js +1 -0
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/commands/doctor.d.ts +4 -0
- package/packages/client/dist/commands/doctor.js +2 -2
- package/packages/client/dist/commands/invoke.js +79 -77
- package/packages/client/dist/git/story-worktree-cleanup.d.ts +44 -1
- package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/README.md +6 -3
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/lib/claude-worktree-setting.js +87 -0
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* See the LICENSE file in the project root for full license text.
|
|
12
12
|
*/
|
|
13
13
|
import type { CleanupReceipt } from '../../../shared/dist/yoloop/story-worktree-receipts.js';
|
|
14
|
+
import { type GitLifecycleRuntimeDocument } from './git-lifecycle-store.js';
|
|
14
15
|
import { StoryWorktreeManager, type RepositoryFacts, type StoryWorktreeResult } from './story-worktree-manager.js';
|
|
15
16
|
export declare const STORY_WORKTREE_CLEANUP_FILE = "story-worktree-cleanup.json";
|
|
16
17
|
export declare const STORY_WORKTREE_BUNDLE_DIRECTORY = "story-worktree-bundles";
|
|
@@ -43,6 +44,10 @@ export declare const STORY_WORKTREE_CLEANUP_REASON_CODES: Readonly<{
|
|
|
43
44
|
readonly ENTRY_CONFLICT: "story-worktree-entry-conflict";
|
|
44
45
|
readonly STATE_INVALID: "story-worktree-cleanup-state-invalid";
|
|
45
46
|
readonly SWEEP_FAILED: "story-worktree-sweep-failed";
|
|
47
|
+
/** Hotfix 4.65.0: C01-only phase-1 progress of a proven-lost worktree was reset. */
|
|
48
|
+
readonly ORPHAN_PROGRESS_RESET: "story-worktree-orphan-progress-reset";
|
|
49
|
+
/** Hotfix 4.65.0: story progress kept (committed progress or ambiguous evidence). */
|
|
50
|
+
readonly ORPHAN_PROGRESS_PRESERVED: "story-worktree-orphan-progress-preserved";
|
|
46
51
|
}>;
|
|
47
52
|
export interface StoryWorktreeRemotePush {
|
|
48
53
|
readonly remote: string;
|
|
@@ -122,7 +127,9 @@ export interface StoryWorktreeAbsenceProof {
|
|
|
122
127
|
}
|
|
123
128
|
export interface StoryWorktreeSweepItem {
|
|
124
129
|
readonly leaseId: string;
|
|
125
|
-
|
|
130
|
+
/** Present only on the hotfix 4.65.0 story-progress items (opaque public ID). */
|
|
131
|
+
readonly storyId?: string;
|
|
132
|
+
readonly action: 'skipped' | 'recovered' | 'remove-pending' | 'preserved' | 'planned' | 'record-closed' | 'progress-reset' | 'progress-preserved';
|
|
126
133
|
readonly reasonCode?: string;
|
|
127
134
|
readonly bundleDigest?: string;
|
|
128
135
|
readonly plannedActions?: readonly string[];
|
|
@@ -140,6 +147,34 @@ export interface StoryWorktreeSweepValue {
|
|
|
140
147
|
readonly items: readonly StoryWorktreeSweepItem[];
|
|
141
148
|
readonly reasonCodes: readonly string[];
|
|
142
149
|
}
|
|
150
|
+
/** Hotfix 4.65.0: what orphan recovery proved about the lost worktree. */
|
|
151
|
+
export interface StoryWorktreeOrphanLossEvidence {
|
|
152
|
+
/** The registered directory was definitely missing (`ENOENT`). */
|
|
153
|
+
readonly worktreeAbsent: boolean;
|
|
154
|
+
/** The lease branch is gone: proven absent, or removed by this recovery. */
|
|
155
|
+
readonly branchGone: boolean;
|
|
156
|
+
/** Exclusive commits were bundled (committed progress existed). */
|
|
157
|
+
readonly bundled: boolean;
|
|
158
|
+
}
|
|
159
|
+
export type StoryWorktreeOrphanProgressDecision = 'reset' | 'preserved' | 'none';
|
|
160
|
+
/**
|
|
161
|
+
* Hotfix 4.65.0 (pure): may the runtime phase-1 progress of a story whose
|
|
162
|
+
* worktree was lost be reset to its pre-adoption state? `reset` only when the
|
|
163
|
+
* runtime story carries exactly the C01 setup overlay written by the story
|
|
164
|
+
* worktree accept-setup, the loss is proven (directory `ENOENT`, branch gone,
|
|
165
|
+
* nothing bundled), no other lease of the story is journaled, the tracked
|
|
166
|
+
* story has no progress, and no phase-one/integration/spec evidence names the
|
|
167
|
+
* story. `none` when there is no runtime progress at all; anything else (or any
|
|
168
|
+
* unreadable evidence) is `preserved`.
|
|
169
|
+
*/
|
|
170
|
+
export declare function classifyStoryWorktreeOrphanProgress(input: {
|
|
171
|
+
readonly runtime: GitLifecycleRuntimeDocument;
|
|
172
|
+
readonly trackedText: string | undefined;
|
|
173
|
+
readonly epicId: string;
|
|
174
|
+
readonly storyId: string;
|
|
175
|
+
readonly recoveredLeaseId: string;
|
|
176
|
+
readonly loss: StoryWorktreeOrphanLossEvidence;
|
|
177
|
+
}): StoryWorktreeOrphanProgressDecision;
|
|
143
178
|
/** Private bundle file name: one immutable file per (lease, verified tip). */
|
|
144
179
|
export declare function storyWorktreeBundleFileName(leaseId: string, headSha: string): string;
|
|
145
180
|
export declare function storyWorktreeOwnerHostDigest(host?: string): string;
|
|
@@ -205,6 +240,14 @@ export declare class StoryWorktreeCleanup {
|
|
|
205
240
|
* P227.07 (C11 finding 3): `show-ref --verify --quiet` exits 1 only when the
|
|
206
241
|
* ref does not exist; any other failure leaves the absence unproven.
|
|
207
242
|
*/
|
|
243
|
+
/**
|
|
244
|
+
* Hotfix 4.65.0: reset the C01-only phase-1 progress a lost worktree left in
|
|
245
|
+
* the runtime overlay, so the root can re-dispatch the story to phase 1 and
|
|
246
|
+
* the server issues `storyWorktreeAdoption` again. Runs only after (or, in
|
|
247
|
+
* dry-run, in place of) a vanished-directory recovery; the tracked state is
|
|
248
|
+
* never written. Committed progress or any ambiguity keeps today's state.
|
|
249
|
+
*/
|
|
250
|
+
private reconcileOrphanProgress;
|
|
208
251
|
private branchAbsence;
|
|
209
252
|
private removeWithRetry;
|
|
210
253
|
private probe;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createHash as Ie,randomBytes as X}from"node:crypto";import{existsSync as U}from"node:fs";import{chmod as ve,open as Z,readFile as x,readdir as ee,rename as ke,rm as C,stat as H,unlink as De}from"node:fs/promises";import{hostname as Ae}from"node:os";import{join as A}from"node:path";import{GIT_LIFECYCLE_RUNTIME_DIRECTORY as F,STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as te,assertGitLifecyclePrivateFile as re,compactStoryWorktreeJournal as Oe,ensureGitLifecyclePrivateChildDirectory as _e,ensureStoryWorktreeJournal as se,gitLifecycleRuntimeDirectory as oe,isStoryWorktreeCleanupReceiptRecord as ne,mutateGitLifecycleRuntime as Se,readGitLifecycleRuntime as ae}from"./git-lifecycle-store.js";import{StoryWorktreeManager as be,digestStoryWorktreeReceiptLocal as ie,runStoryWorktreeGit as O,storyWorktreePathAbsence as Ne}from"./story-worktree-manager.js";const j="story-worktree-cleanup.json",G="story-worktree-bundles",Te=256,de=Object.freeze(["success","failure","abandon","orphan-recovery"]),Ce=Object.freeze(["active","integrated","failed","abandoned","bundled","remove-pending","removed"]),Pe=Object.freeze({MANUAL_PRESERVED:"manual-worktree-preserved",REMOVE_PENDING:"story-worktree-remove-pending",ORPHAN_RECOVERED:"story-worktree-orphan-recovered",ORPHAN_UNPROVEN:"story-worktree-orphan-unproven",OWNER_ALIVE:"story-worktree-owner-alive",LEASE_LIVE:"story-worktree-lease-live",CLAIMED:"story-worktree-cleanup-claimed",IN_PROGRESS:"story-worktree-cleanup-in-progress",DIRTY_PRESERVED:"story-worktree-dirty-preserved",BUNDLE_QUOTA:"story-worktree-bundle-quota-exceeded",BUNDLE_FAILED:"story-worktree-bundle-failed",BUNDLE_UNVERIFIED:"story-worktree-bundle-unverified",REMOTE_DIVERGED:"story-worktree-remote-sha-diverged",REMOTE_UNVERIFIED:"story-worktree-remote-unverified",REMOTE_ABSENT:"story-worktree-remote-absent",REMOTE_UNPRESERVED:"story-worktree-remote-unpreserved",REMOTE_UNKNOWN:"story-worktree-remote-unknown",BRANCH_MOVED:"story-worktree-branch-moved",BRANCH_CHECKED_OUT:"story-worktree-branch-checked-out",ADOPTED_BRANCH:"story-worktree-adopted-branch-preserved",ENTRY_CONFLICT:"story-worktree-entry-conflict",STATE_INVALID:"story-worktree-cleanup-state-invalid",SWEEP_FAILED:"story-worktree-sweep-failed"}),a=Pe,ce=10080*60*1e3,Le=600*1e3,Me=64,Be=512*1024*1024,le=3,Ve=50,Ue=/^swt-[a-f0-9]{24}$/,Y=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ue=/^[a-f0-9]{64}$/,xe=/^[a-f0-9]{16}$/,he=/^P[1-9][0-9]*$/,We=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,me=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,fe=/^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,pe=/^swt-[a-f0-9]{24}-[a-f0-9]{12}\.bundle$/,K=["integrated","failed","abandoned","bundled","remove-pending"];class W extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function c(u){throw new W(u)}function M(u){return Ie("sha256").update(u).digest("hex")}function z(u){return new Promise(t=>setTimeout(t,u))}function Ee(u){return[...new Set(u)]}function He(u){try{return process.kill(u,0),!0}catch(t){return t.code==="EPERM"}}function q(u,t){return`${u}-${t.slice(0,12)}.bundle`}function we(u=Ae()){return M(`neocortex.p225.owner-host|${u}`)}function $(u){return u!==null&&typeof u=="object"&&!Array.isArray(u)?u:void 0}const ge=["schemaVersion","leaseId","epicId","storyId","state","removeAttempts","updatedAt"],Fe=new Set([...ge,"trigger","headSha","bundleDigest","bundleBytes","bundleExpiresAt","remotePush","remoteBranchRemoved","ownerPid","ownerHostDigest","claimToken","claimExpiresAt"]);function Re(u,t){const e=$(t);if(!e||Object.keys(e).some(o=>!Fe.has(o))||ge.some(o=>e[o]===void 0))return!1;const r=e.remotePush===void 0?void 0:$(e.remotePush);if(e.remotePush!==void 0&&(!r||Object.keys(r).length!==3||typeof r.remote!="string"||!me.test(r.remote)||typeof r.branch!="string"||!fe.test(r.branch)||!r.branch.startsWith(`nx/${String(e.epicId)}/`)||typeof r.sha!="string"||!Y.test(r.sha)))return!1;const s=o=>e[o]===void 0||typeof e[o]=="string"&&$e.test(e[o])&&Number.isFinite(Date.parse(e[o]));return e.schemaVersion===1&&e.leaseId===u&&Ue.test(u)&&typeof e.epicId=="string"&&he.test(e.epicId)&&typeof e.storyId=="string"&&We.test(e.storyId)&&e.storyId.startsWith(`${e.epicId}.`)&&Ce.includes(e.state)&&Number.isSafeInteger(e.removeAttempts)&&e.removeAttempts>=0&&e.removeAttempts<=1e3&&s("updatedAt")&&s("bundleExpiresAt")&&s("claimExpiresAt")&&e.claimToken===void 0==(e.claimExpiresAt===void 0)&&(e.claimToken===void 0||typeof e.claimToken=="string"&&xe.test(e.claimToken))&&(e.trigger===void 0||de.includes(e.trigger))&&(e.headSha===void 0||typeof e.headSha=="string"&&Y.test(e.headSha))&&(e.bundleDigest===void 0||typeof e.bundleDigest=="string"&&ue.test(e.bundleDigest)&&e.headSha!==void 0&&e.bundleExpiresAt!==void 0)&&(e.bundleBytes===void 0||Number.isSafeInteger(e.bundleBytes)&&e.bundleBytes>0)&&(e.remoteBranchRemoved===void 0||typeof e.remoteBranchRemoved=="boolean")&&(e.ownerPid===void 0||Number.isSafeInteger(e.ownerPid)&&e.ownerPid>0)&&(e.ownerHostDigest===void 0||typeof e.ownerHostDigest=="string"&&ue.test(e.ownerHostDigest))}function J(u){let t;try{t=JSON.parse(u)}catch{c(a.STATE_INVALID)}const e=$(t),r=$(e?.records);return(!e||Object.keys(e).length!==2||e.schemaVersion!==1||!r||Object.keys(r).length>Te||!Object.entries(r).every(([s,o])=>Re(s,o)))&&c(a.STATE_INVALID),{schemaVersion:1,records:r}}async function ye(u){const t=A(u,F),e=A(t,j);if(!U(e))return{schemaVersion:1,records:{}};try{await re(e,t)}catch{c(a.STATE_INVALID)}return J(await x(e,"utf8"))}function N(u,t){return u?.claimToken!==void 0&&u.claimExpiresAt!==void 0&&Date.parse(u.claimExpiresAt)>t}async function tt(u,t,e=Date.now()){try{const r=(await ye(u)).records[t];return r!==void 0&&(K.includes(r.state)||N(r,e))}catch{return!0}}class je{options;manager;now;isProcessAlive;constructor(t){this.options=t,this.manager=t.manager??new be({projectRoot:t.projectRoot,...t.worktreeRoot?{worktreeRoot:t.worktreeRoot}:{},...t.now?{now:t.now}:{}}),this.now=t.now??(()=>new Date),this.isProcessAlive=t.isProcessAlive??He}async readState(t){return ye(t?.commonDir??(await this.facts()).commonDir)}async recordPush(t){return this.guard(async()=>{(typeof t.remote!="string"||!me.test(t.remote))&&c("story-worktree-remote-invalid");const e=await this.probe(t.leaseId);(e.ownership!=="proven"||!e.headSha)&&c("story-worktree-ownership-unproven"),(e.entry.workspaceMechanism!=="client_managed_worktree"||!fe.test(e.entry.temporaryBranch))&&c(a.ADOPTED_BRANCH),await this.gitOk(e.facts.mainRoot,["config","--get",`remote.${t.remote}.url`])||c(a.REMOTE_UNKNOWN);const r=await this.lsRemote(e.facts.mainRoot,t.remote,e.entry.temporaryBranch);r===null&&c(a.REMOTE_UNVERIFIED),r===void 0&&c(a.REMOTE_ABSENT),r!==e.headSha&&c(a.REMOTE_DIVERGED);const s={remote:t.remote,branch:e.entry.temporaryBranch,sha:r};return await this.update(e.entry,void 0,o=>{const n={...o,remotePush:s};return delete n.remoteBranchRemoved,n}),{ok:!0,value:{leaseId:e.entry.leaseId,...s}}})}async registerOwnerProcess(t){return this.guard(async()=>{(!Number.isSafeInteger(t.pid)||t.pid<=0)&&c("story-worktree-owner-pid-invalid");const e=await this.probe(t.leaseId);return await this.update(e.entry,void 0,r=>({...r,ownerPid:t.pid,ownerHostDigest:we()})),{ok:!0,value:{leaseId:e.entry.leaseId}}})}async cleanup(t){return this.guard(async()=>({ok:!0,value:await this.cleanupUnguarded(t)}))}async sweep(t={}){return this.guard(async()=>{t.epicId!==void 0&&!he.test(t.epicId)&&c("story-worktree-identity-invalid");const e=t.dryRun===!0,r=await this.facts(),s=await ae(this.options.projectRoot),o=Object.values(s.storyWorktrees?.entries??{}),n=o.filter(d=>t.epicId===void 0||d.epicId===t.epicId).sort((d,E)=>d.leaseId.localeCompare(E.leaseId)),h=await this.readState(r),m=this.now().getTime(),f=we(),i=[],l=[];for(const d of n){const E=h.records[d.leaseId],y=E!==void 0&&K.includes(E.state),b=Date.parse(d.expiresAt)<=m,k=E?.ownerPid!==void 0&&E.ownerHostDigest===f&&this.isProcessAlive(E.ownerPid),T=!k&&!N(E,m)&&!y&&!b&&d.state==="active"&&await Ne(d.worktreePath)==="enoent";if(!T&&(k||N(E,m)||!y&&!b)){const S=k?a.OWNER_ALIVE:N(E,m)?a.CLAIMED:a.LEASE_LIVE;i.push({leaseId:d.leaseId,action:"skipped",reasonCode:S});continue}const B=y?E?.trigger==="success"&&b?"orphan-recovery":E?.trigger??"orphan-recovery":"orphan-recovery";let I;try{I={ok:!0,value:await this.cleanupUnguarded({leaseId:d.leaseId,trigger:B,dryRun:e,...T?{requireVanished:!0}:{}})}}catch(S){I={ok:!1,reasonCode:S instanceof W?S.reasonCode:a.SWEEP_FAILED}}if(!I.ok&&T&&I.reasonCode===a.LEASE_LIVE){i.push({leaseId:d.leaseId,action:"skipped",reasonCode:a.LEASE_LIVE});continue}if(!I.ok){i.push({leaseId:d.leaseId,action:"preserved",reasonCode:I.reasonCode}),l.push(I.reasonCode);continue}const D=I.value;D.outcome==="dry-run"?i.push({leaseId:d.leaseId,action:"planned",plannedActions:D.plannedActions??[]}):D.outcome==="remove-pending"?(i.push({leaseId:d.leaseId,action:"remove-pending",reasonCode:a.REMOVE_PENDING,...D.bundleDigest?{bundleDigest:D.bundleDigest}:{}}),l.push(a.REMOVE_PENDING)):(i.push({leaseId:d.leaseId,action:"recovered",reasonCode:a.ORPHAN_RECOVERED,...D.bundleDigest?{bundleDigest:D.bundleDigest}:{},...D.absenceProof?{absenceProof:D.absenceProof}:{}}),l.push(a.ORPHAN_RECOVERED))}const g=new Set(o.map(d=>d.leaseId));for(const d of Object.values(h.records).sort((E,y)=>E.leaseId.localeCompare(y.leaseId))){if(g.has(d.leaseId)||d.state==="removed"||N(d,m)||t.epicId!==void 0&&d.epicId!==t.epicId)continue;const E=await this.closeDetachedRecord(d,r,e);i.push({leaseId:d.leaseId,action:e?"planned":"record-closed",...E?{reasonCode:E}:{}}),E&&l.push(E)}const R=await this.expireBundles(h,r,m,e),v=await this.manager.registeredWorktrees();v.ok||c(v.reasonCode);const P=v.value.worktrees.filter(d=>!o.some(E=>this.manager.sameWorktreePath(E.worktreePath,d.path))).length;return P>0&&l.push(a.MANUAL_PRESERVED),{ok:!0,value:{dryRun:e,entriesScanned:n.length,recovered:i.filter(d=>d.action==="recovered").length,removePending:i.filter(d=>d.action==="remove-pending").length,preserved:i.filter(d=>d.action==="preserved").length,skipped:i.filter(d=>d.action==="skipped").length,manualWorktreesPreserved:P,bundlesExpired:R,items:i,reasonCodes:Ee(l)}}})}async cleanupUnguarded(t){de.includes(t.trigger)||c("story-worktree-trigger-invalid");const e=await this.probe(t.leaseId),{entry:r,facts:s}=e;t.requireVanished===!0&&(e.pathAbsence!=="enoent"||r.state!=="active")&&c(a.LEASE_LIVE);const n=(await this.readState(s)).records[r.leaseId];if(r.state==="creating")return t.trigger!=="orphan-recovery"&&c("story-worktree-ownership-unproven"),this.recoverCreating(e,t.dryRun===!0);const h=n!==void 0&&K.includes(n.state);let m=!1;e.pathExists||(e.pathAbsence!=="enoent"&&c(a.ORPHAN_UNPROVEN),t.trigger!=="orphan-recovery"&&!h&&c("story-worktree-ownership-unproven"),m=!0),!m&&e.ownership!=="proven"&&c("story-worktree-ownership-unproven"),!m&&e.clean!==!0&&c(t.trigger==="success"?"story-worktree-dirty":a.DIRTY_PRESERVED),e.epicHead||c("story-worktree-epic-branch-missing");const f=e.epicHead,i=m?e.branchSha:e.headSha;!m&&!i&&c("story-worktree-git-failed");const l=e.integrated===!0;t.trigger==="success"&&!l&&c("story-worktree-not-integrated");const g=r.workspaceMechanism==="client_managed_worktree",R=n?.bundleDigest!==void 0&&n.headSha!==void 0&&n.headSha===i&&await this.bundleMatches(s,r.leaseId,n.headSha,n.bundleDigest),v=!l&&i!==void 0&&(g||t.trigger==="orphan-recovery")&&!R,P=n?.remotePush!==void 0&&n.remoteBranchRemoved!==!0;if(t.dryRun===!0){const y=[...v?["bundle-unintegrated-range"]:[],m?"drop-worktree-metadata":"remove-worktree",...g&&e.branchSha?["delete-local-branch"]:[],...P?["delete-remote-branch"]:[]];return{leaseId:r.leaseId,outcome:"dry-run",trigger:t.trigger,state:n?.state??"active",plannedActions:y,preservedReasonCodes:[]}}const d=await this.claim(r);let E=!1;try{let y=R?n?.bundleDigest:void 0;if(v){const w=await this.createBundle(e,i,f);y=w.digest,await this.update(r,d,p=>({...p,state:"bundled",trigger:t.trigger,headSha:i,bundleDigest:w.digest,bundleBytes:w.bytes,bundleExpiresAt:new Date(this.now().getTime()+(this.options.bundleTtlMs??ce)).toISOString()}))}else if(!R){const w=l?"integrated":t.trigger==="failure"?"failed":"abandoned";await this.update(r,d,p=>({...p,state:p.state==="remove-pending"?"remove-pending":w,trigger:t.trigger,...i?{headSha:i}:{}}))}if(m)await O(s.mainRoot,["worktree","remove",r.worktreePath]);else{const w=this.options.removeAttempts??le;if(!await this.removeWithRetry(s.mainRoot,r.worktreePath,w))return await this.update(r,d,p=>({...p,state:"remove-pending",trigger:t.trigger,removeAttempts:Math.min(1e3,p.removeAttempts+w)})),{leaseId:r.leaseId,outcome:"remove-pending",trigger:t.trigger,state:"remove-pending",...y?{bundleDigest:y}:{},preservedReasonCodes:[a.REMOVE_PENDING]}}await O(s.mainRoot,["worktree","prune"]);const b=await this.manager.registeredWorktrees();b.ok||c(b.reasonCode),b.value.worktrees.some(w=>this.manager.sameWorktreePath(w.path,r.worktreePath))&&c(a.ORPHAN_UNPROVEN);const k=[];let T=!1;if(!g)k.push(a.ADOPTED_BRANCH);else if(e.branchSha){const w=i??e.branchSha,p=l||y!==void 0,_=b.value.worktrees.some(L=>L.branch===r.temporaryBranch);p?_?k.push(a.BRANCH_CHECKED_OUT):await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,w])?T=!0:k.push(a.BRANCH_MOVED):k.push(a.ORPHAN_UNPROVEN)}const B=(await this.readState(s)).records[r.leaseId]??n,I=await this.deleteRemote(r,s,B,d,{epicHead:f,...i?{tip:i}:{},bundled:y!==void 0});I.reasonCode&&k.push(I.reasonCode);const D=B?.remotePush!==void 0&&!I.removed&&(I.reasonCode===a.REMOTE_UNVERIFIED||I.reasonCode===a.REMOTE_UNPRESERVED),S=this.now().toISOString(),V={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${M(`${r.leaseId}|${r.nonceDigest}|${t.trigger}|${S}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:t.trigger,worktreeRemoved:!0,localBranchRemoved:T,remoteBranchRemoved:I.removed,...k[0]?{preservedReasonCode:k[0]}:{},cleanedAt:S};ne(V)||c("story-worktree-receipt-invalid"),await this.mutate(w=>{const p=se(w),_=p.entries[r.leaseId];for((!_||_.nonceDigest!==r.nonceDigest)&&c(a.ENTRY_CONFLICT),delete p.entries[r.leaseId],p.cleanupReceipts.push({...V});p.cleanupReceipts.length>te;)p.cleanupReceipts.shift()},w=>{const p=w.records[r.leaseId];if(p)if(D&&p.remotePush!==void 0){const _=p.state==="removed"||p.state==="remove-pending"||p.state==="active"?p.bundleDigest?"bundled":"integrated":p.state,L={...p,state:_,updatedAt:S,remoteBranchRemoved:!1};delete L.claimToken,delete L.claimExpiresAt,w.records[r.leaseId]=L}else if(p.bundleDigest){const _={...p,state:"removed",updatedAt:S,remoteBranchRemoved:I.removed};delete _.claimToken,delete _.claimExpiresAt,w.records[r.leaseId]=_}else delete w.records[r.leaseId]}),E=!0;const Q=m?{worktree:"enoent",branch:e.branchSha?"present":await this.branchAbsence(s,r.temporaryBranch),bundled:y!==void 0}:void 0;return{leaseId:r.leaseId,outcome:"removed",trigger:t.trigger,state:"removed",receipt:V,receiptDigest:ie(V),...y?{bundleDigest:y}:{},preservedReasonCodes:Ee(k),...Q?{absenceProof:Q}:{}}}finally{E||await this.releaseClaim(r,d).catch(()=>{})}}async recoverCreating(t,e){const{entry:r,facts:s}=t,o={leaseId:r.leaseId,trigger:"orphan-recovery",preservedReasonCodes:[]};let n=!1;if(t.pathExists){const f=await O(r.worktreePath,["rev-parse","HEAD"]),i=await O(r.worktreePath,["symbolic-ref","--quiet","--short","HEAD"]),l=await O(r.worktreePath,["status","--porcelain=v1","--untracked-files=all","-z"]);t.registered&&f.ok&&f.stdout.trim()===r.baseSha&&i.ok&&i.stdout.trim()===r.temporaryBranch&&l.ok&&l.stdout.length===0||c(a.ORPHAN_UNPROVEN),n=!0}else t.pathAbsence!=="enoent"&&c(a.ORPHAN_UNPROVEN),t.branchCheckedOut&&c(a.ORPHAN_UNPROVEN);if(t.branchSha!==void 0&&t.branchSha!==r.baseSha&&c(a.ORPHAN_UNPROVEN),e)return{...o,outcome:"dry-run",state:"active",plannedActions:[...n?["remove-worktree"]:[],...t.branchSha?["delete-local-branch"]:[],"drop-reservation"]};const h=await this.claim(r);let m=!1;try{n&&!await this.removeWithRetry(s.mainRoot,r.worktreePath,this.options.removeAttempts??le)&&c(a.REMOVE_PENDING),n&&await O(s.mainRoot,["worktree","prune"]);let f=!1;t.branchSha&&(f=await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]));const i=this.now().toISOString(),l={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${M(`${r.leaseId}|${r.nonceDigest}|creating|${i}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:"orphan-recovery",worktreeRemoved:n,localBranchRemoved:f,remoteBranchRemoved:!1,...t.branchSha&&!f?{preservedReasonCode:a.BRANCH_MOVED}:{},cleanedAt:i};return ne(l)||c("story-worktree-receipt-invalid"),await this.mutate(g=>{const R=se(g),v=R.entries[r.leaseId];for((!v||v.state!=="creating"||v.nonceDigest!==r.nonceDigest)&&c(a.ENTRY_CONFLICT),delete R.entries[r.leaseId],R.cleanupReceipts.push({...l});R.cleanupReceipts.length>te;)R.cleanupReceipts.shift()},g=>{delete g.records[r.leaseId]}),m=!0,{...o,outcome:"reclaimed",state:"removed",receipt:l,receiptDigest:ie(l),preservedReasonCodes:l.preservedReasonCode?[l.preservedReasonCode]:[]}}finally{m||await this.releaseClaim(r,h).catch(()=>{})}}async closeDetachedRecord(t,e,r){let s,o=t.remoteBranchRemoved===!0;if(t.remotePush&&!o){const n=await O(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/epic/${t.epicId}^{commit}`]);if(!(n.ok&&await this.gitOk(e.mainRoot,["merge-base","--is-ancestor",t.remotePush.sha,n.stdout.trim()])))s=a.REMOTE_UNPRESERVED;else if(!r){const m=await this.deleteRecordedRemote(e.mainRoot,t.remotePush);o=m.removed,s=m.reasonCode}}return r||s===a.REMOTE_UNPRESERVED||s===a.REMOTE_UNVERIFIED||await this.mutate(void 0,n=>{const h=n.records[t.leaseId];!h||h.state==="removed"||(h.bundleDigest?n.records[t.leaseId]={...h,state:"removed",remoteBranchRemoved:o,updatedAt:this.now().toISOString()}:delete n.records[t.leaseId])}),s}async deleteRemote(t,e,r,s,o){const n=r?.remotePush;if(!n)return{removed:!1};if(r?.remoteBranchRemoved===!0)return{removed:!0};if(t.workspaceMechanism!=="client_managed_worktree"||n.branch!==t.temporaryBranch)return{removed:!1,reasonCode:a.ADOPTED_BRANCH};const h=await this.gitOk(e.mainRoot,["merge-base","--is-ancestor",n.sha,o.epicHead]),m=!h&&o.bundled&&o.tip!==void 0&&await this.gitOk(e.mainRoot,["merge-base","--is-ancestor",n.sha,o.tip]);if(!h&&!m)return{removed:!1,reasonCode:a.REMOTE_UNPRESERVED};const f=await this.deleteRecordedRemote(e.mainRoot,n);return f.removed&&await this.update(t,s,i=>({...i,remoteBranchRemoved:!0})),f}async deleteRecordedRemote(t,e){if(!await this.gitOk(t,["config","--get",`remote.${e.remote}.url`]))return{removed:!1,reasonCode:a.REMOTE_UNKNOWN};const r=await this.lsRemote(t,e.remote,e.branch);return r===null?{removed:!1,reasonCode:a.REMOTE_UNVERIFIED}:r===void 0?{removed:!1,reasonCode:a.REMOTE_ABSENT}:r!==e.sha?{removed:!1,reasonCode:a.REMOTE_DIVERGED}:await this.gitOk(t,["push","--porcelain",`--force-with-lease=refs/heads/${e.branch}:${e.sha}`,e.remote,"--delete",`refs/heads/${e.branch}`])?await this.lsRemote(t,e.remote,e.branch)===void 0?{removed:!0}:{removed:!1,reasonCode:a.REMOTE_UNVERIFIED}:{removed:!1,reasonCode:a.REMOTE_UNVERIFIED}}async lsRemote(t,e,r){const s=await O(t,["ls-remote","--heads",e,`refs/heads/${r}`]);if(!s.ok)return null;const o=s.stdout.split(`
|
|
2
|
-
`).map(
|
|
3
|
-
`).some(
|
|
4
|
-
`;
|
|
1
|
+
import{createHash as ke,randomBytes as Z}from"node:crypto";import{existsSync as M}from"node:fs";import{chmod as _e,open as ee,readFile as B,readdir as te,rename as Ae,rm as V,stat as $,unlink as Se}from"node:fs/promises";import{hostname as Oe}from"node:os";import{join as A}from"node:path";import{GIT_LIFECYCLE_RUNTIME_DIRECTORY as F,STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,assertGitLifecyclePrivateFile as se,compactStoryWorktreeJournal as be,ensureGitLifecyclePrivateChildDirectory as De,ensureStoryWorktreeJournal as oe,gitLifecycleRuntimeDirectory as ne,isStoryWorktreeCleanupReceiptRecord as ae,mutateGitLifecycleRuntime as ie,readGitLifecycleRuntime as j}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as de}from"./git-lifecycle-step-ids.js";import{StoryWorktreeManager as Ne,digestStoryWorktreeReceiptLocal as ce,runStoryWorktreeGit as S,storyWorktreePathAbsence as Te}from"./story-worktree-manager.js";const G="story-worktree-cleanup.json",Y="story-worktree-bundles",Ce=256,le=Object.freeze(["success","failure","abandon","orphan-recovery"]),Pe=Object.freeze(["active","integrated","failed","abandoned","bundled","remove-pending","removed"]),Le=Object.freeze({MANUAL_PRESERVED:"manual-worktree-preserved",REMOVE_PENDING:"story-worktree-remove-pending",ORPHAN_RECOVERED:"story-worktree-orphan-recovered",ORPHAN_UNPROVEN:"story-worktree-orphan-unproven",OWNER_ALIVE:"story-worktree-owner-alive",LEASE_LIVE:"story-worktree-lease-live",CLAIMED:"story-worktree-cleanup-claimed",IN_PROGRESS:"story-worktree-cleanup-in-progress",DIRTY_PRESERVED:"story-worktree-dirty-preserved",BUNDLE_QUOTA:"story-worktree-bundle-quota-exceeded",BUNDLE_FAILED:"story-worktree-bundle-failed",BUNDLE_UNVERIFIED:"story-worktree-bundle-unverified",REMOTE_DIVERGED:"story-worktree-remote-sha-diverged",REMOTE_UNVERIFIED:"story-worktree-remote-unverified",REMOTE_ABSENT:"story-worktree-remote-absent",REMOTE_UNPRESERVED:"story-worktree-remote-unpreserved",REMOTE_UNKNOWN:"story-worktree-remote-unknown",BRANCH_MOVED:"story-worktree-branch-moved",BRANCH_CHECKED_OUT:"story-worktree-branch-checked-out",ADOPTED_BRANCH:"story-worktree-adopted-branch-preserved",ENTRY_CONFLICT:"story-worktree-entry-conflict",STATE_INVALID:"story-worktree-cleanup-state-invalid",SWEEP_FAILED:"story-worktree-sweep-failed",ORPHAN_PROGRESS_RESET:"story-worktree-orphan-progress-reset",ORPHAN_PROGRESS_PRESERVED:"story-worktree-orphan-progress-preserved"}),i=Le,ue=10080*60*1e3,Me=600*1e3,Be=64,Ve=512*1024*1024,he=3,Ue=50,xe=/^swt-[a-f0-9]{24}$/,K=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,fe=/^[a-f0-9]{64}$/,We=/^[a-f0-9]{16}$/,me=/^P[1-9][0-9]*$/,He=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,pe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ee=/^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,Re=/^swt-[a-f0-9]{24}-[a-f0-9]{12}\.bundle$/,z=["integrated","failed","abandoned","bundled","remove-pending"],Fe="last_step,status,steps_completed",je=new Set(["backlog","ready_to_start"]);function Ge(l){const{runtime:e,epicId:t,storyId:r}=l,s=O(e.stories[r]),n=s?Object.keys(s).filter(p=>p!=="write_set_extension").sort():[];if(n.length===0)return"none";const o=s.steps_completed;if(!(n.join(",")===Fe&&s.status==="branch-ready"&&s.last_step===de&&Array.isArray(o)&&o.length===1&&o[0]===de)||!l.loss.worktreeAbsent||!l.loss.branchGone||l.loss.bundled||Object.values(e.storyWorktrees?.entries??{}).some(p=>p.storyId===r&&p.leaseId!==l.recoveredLeaseId))return"preserved";let h;try{h=l.trackedText===void 0?void 0:O(JSON.parse(l.trackedText))}catch{return"preserved"}const a=O(h?.stories),d=O(a?.[r]),g=d?.steps_completed;if(!d||!je.has(String(d.status))||g!==void 0&&(!Array.isArray(g)||g.length>0)||d.branch_name||d.checkpoint||d.commit_sha)return"preserved";const E=O(O(e.epics[t])?.story_worktree_evidence);if(E!==void 0){const p=E.receipts,D=E.specAcceptances;if(p!==void 0&&!Array.isArray(p)||D!==void 0&&!Array.isArray(D))return"preserved";const c=R=>{const y=O(R);return!y||y.storyId===r||Array.isArray(y.storyIds)&&y.storyIds.includes(r)};if(p?.some(c)||D?.some(c))return"preserved"}return"reset"}class H extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function u(l){throw new H(l)}function x(l){return ke("sha256").update(l).digest("hex")}function q(l){return new Promise(e=>setTimeout(e,l))}function we(l){return[...new Set(l)]}function Ye(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function J(l,e){return`${l}-${e.slice(0,12)}.bundle`}function ge(l=Oe()){return x(`neocortex.p225.owner-host|${l}`)}function O(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)?l:void 0}const ye=["schemaVersion","leaseId","epicId","storyId","state","removeAttempts","updatedAt"],Ke=new Set([...ye,"trigger","headSha","bundleDigest","bundleBytes","bundleExpiresAt","remotePush","remoteBranchRemoved","ownerPid","ownerHostDigest","claimToken","claimExpiresAt"]);function Ie(l,e){const t=O(e);if(!t||Object.keys(t).some(n=>!Ke.has(n))||ye.some(n=>t[n]===void 0))return!1;const r=t.remotePush===void 0?void 0:O(t.remotePush);if(t.remotePush!==void 0&&(!r||Object.keys(r).length!==3||typeof r.remote!="string"||!pe.test(r.remote)||typeof r.branch!="string"||!Ee.test(r.branch)||!r.branch.startsWith(`nx/${String(t.epicId)}/`)||typeof r.sha!="string"||!K.test(r.sha)))return!1;const s=n=>t[n]===void 0||typeof t[n]=="string"&&$e.test(t[n])&&Number.isFinite(Date.parse(t[n]));return t.schemaVersion===1&&t.leaseId===l&&xe.test(l)&&typeof t.epicId=="string"&&me.test(t.epicId)&&typeof t.storyId=="string"&&He.test(t.storyId)&&t.storyId.startsWith(`${t.epicId}.`)&&Pe.includes(t.state)&&Number.isSafeInteger(t.removeAttempts)&&t.removeAttempts>=0&&t.removeAttempts<=1e3&&s("updatedAt")&&s("bundleExpiresAt")&&s("claimExpiresAt")&&t.claimToken===void 0==(t.claimExpiresAt===void 0)&&(t.claimToken===void 0||typeof t.claimToken=="string"&&We.test(t.claimToken))&&(t.trigger===void 0||le.includes(t.trigger))&&(t.headSha===void 0||typeof t.headSha=="string"&&K.test(t.headSha))&&(t.bundleDigest===void 0||typeof t.bundleDigest=="string"&&fe.test(t.bundleDigest)&&t.headSha!==void 0&&t.bundleExpiresAt!==void 0)&&(t.bundleBytes===void 0||Number.isSafeInteger(t.bundleBytes)&&t.bundleBytes>0)&&(t.remoteBranchRemoved===void 0||typeof t.remoteBranchRemoved=="boolean")&&(t.ownerPid===void 0||Number.isSafeInteger(t.ownerPid)&&t.ownerPid>0)&&(t.ownerHostDigest===void 0||typeof t.ownerHostDigest=="string"&&fe.test(t.ownerHostDigest))}function Q(l){let e;try{e=JSON.parse(l)}catch{u(i.STATE_INVALID)}const t=O(e),r=O(t?.records);return(!t||Object.keys(t).length!==2||t.schemaVersion!==1||!r||Object.keys(r).length>Ce||!Object.entries(r).every(([s,n])=>Ie(s,n)))&&u(i.STATE_INVALID),{schemaVersion:1,records:r}}async function ve(l){const e=A(l,F),t=A(e,G);if(!M(t))return{schemaVersion:1,records:{}};try{await se(t,e)}catch{u(i.STATE_INVALID)}return Q(await B(t,"utf8"))}function P(l,e){return l?.claimToken!==void 0&&l.claimExpiresAt!==void 0&&Date.parse(l.claimExpiresAt)>e}async function at(l,e,t=Date.now()){try{const r=(await ve(l)).records[e];return r!==void 0&&(z.includes(r.state)||P(r,t))}catch{return!0}}class ze{options;manager;now;isProcessAlive;constructor(e){this.options=e,this.manager=e.manager??new Ne({projectRoot:e.projectRoot,...e.worktreeRoot?{worktreeRoot:e.worktreeRoot}:{},...e.now?{now:e.now}:{}}),this.now=e.now??(()=>new Date),this.isProcessAlive=e.isProcessAlive??Ye}async readState(e){return ve(e?.commonDir??(await this.facts()).commonDir)}async recordPush(e){return this.guard(async()=>{(typeof e.remote!="string"||!pe.test(e.remote))&&u("story-worktree-remote-invalid");const t=await this.probe(e.leaseId);(t.ownership!=="proven"||!t.headSha)&&u("story-worktree-ownership-unproven"),(t.entry.workspaceMechanism!=="client_managed_worktree"||!Ee.test(t.entry.temporaryBranch))&&u(i.ADOPTED_BRANCH),await this.gitOk(t.facts.mainRoot,["config","--get",`remote.${e.remote}.url`])||u(i.REMOTE_UNKNOWN);const r=await this.lsRemote(t.facts.mainRoot,e.remote,t.entry.temporaryBranch);r===null&&u(i.REMOTE_UNVERIFIED),r===void 0&&u(i.REMOTE_ABSENT),r!==t.headSha&&u(i.REMOTE_DIVERGED);const s={remote:e.remote,branch:t.entry.temporaryBranch,sha:r};return await this.update(t.entry,void 0,n=>{const o={...n,remotePush:s};return delete o.remoteBranchRemoved,o}),{ok:!0,value:{leaseId:t.entry.leaseId,...s}}})}async registerOwnerProcess(e){return this.guard(async()=>{(!Number.isSafeInteger(e.pid)||e.pid<=0)&&u("story-worktree-owner-pid-invalid");const t=await this.probe(e.leaseId);return await this.update(t.entry,void 0,r=>({...r,ownerPid:e.pid,ownerHostDigest:ge()})),{ok:!0,value:{leaseId:t.entry.leaseId}}})}async cleanup(e){return this.guard(async()=>({ok:!0,value:await this.cleanupUnguarded(e)}))}async sweep(e={}){return this.guard(async()=>{e.epicId!==void 0&&!me.test(e.epicId)&&u("story-worktree-identity-invalid");const t=e.dryRun===!0,r=await this.facts(),s=await j(this.options.projectRoot),n=Object.values(s.storyWorktrees?.entries??{}),o=n.filter(c=>e.epicId===void 0||c.epicId===e.epicId).sort((c,R)=>c.leaseId.localeCompare(R.leaseId)),f=await this.readState(r),m=this.now().getTime(),h=ge(),a=[],d=[];for(const c of o){const R=f.records[c.leaseId],y=R!==void 0&&z.includes(R.state),C=Date.parse(c.expiresAt)<=m,k=R?.ownerPid!==void 0&&R.ownerHostDigest===h&&this.isProcessAlive(R.ownerPid),L=!k&&!P(R,m)&&!y&&!C&&c.state==="active"&&await Te(c.worktreePath)==="enoent";if(!L&&(k||P(R,m)||!y&&!C)){const T=k?i.OWNER_ALIVE:P(R,m)?i.CLAIMED:i.LEASE_LIVE;a.push({leaseId:c.leaseId,action:"skipped",reasonCode:T});continue}const W=y?R?.trigger==="success"&&C?"orphan-recovery":R?.trigger??"orphan-recovery":"orphan-recovery";let v;try{v={ok:!0,value:await this.cleanupUnguarded({leaseId:c.leaseId,trigger:W,dryRun:t,...L?{requireVanished:!0}:{}})}}catch(T){v={ok:!1,reasonCode:T instanceof H?T.reasonCode:i.SWEEP_FAILED}}if(!v.ok&&L&&v.reasonCode===i.LEASE_LIVE){a.push({leaseId:c.leaseId,action:"skipped",reasonCode:i.LEASE_LIVE});continue}if(!v.ok){a.push({leaseId:c.leaseId,action:"preserved",reasonCode:v.reasonCode}),d.push(v.reasonCode);continue}const _=v.value,N=await this.reconcileOrphanProgress(c,_,r,t);_.outcome==="dry-run"?a.push({leaseId:c.leaseId,action:"planned",plannedActions:_.plannedActions??[]}):_.outcome==="remove-pending"?(a.push({leaseId:c.leaseId,action:"remove-pending",reasonCode:i.REMOVE_PENDING,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{}}),d.push(i.REMOVE_PENDING)):(a.push({leaseId:c.leaseId,action:"recovered",reasonCode:i.ORPHAN_RECOVERED,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{},..._.absenceProof?{absenceProof:_.absenceProof}:{}}),d.push(i.ORPHAN_RECOVERED)),N&&(a.push(N),N.reasonCode&&d.push(N.reasonCode))}const g=new Set(n.map(c=>c.leaseId));for(const c of Object.values(f.records).sort((R,y)=>R.leaseId.localeCompare(y.leaseId))){if(g.has(c.leaseId)||c.state==="removed"||P(c,m)||e.epicId!==void 0&&c.epicId!==e.epicId)continue;const R=await this.closeDetachedRecord(c,r,t);a.push({leaseId:c.leaseId,action:t?"planned":"record-closed",...R?{reasonCode:R}:{}}),R&&d.push(R)}const E=await this.expireBundles(f,r,m,t),p=await this.manager.registeredWorktrees();p.ok||u(p.reasonCode);const D=p.value.worktrees.filter(c=>!n.some(R=>this.manager.sameWorktreePath(R.worktreePath,c.path))).length;return D>0&&d.push(i.MANUAL_PRESERVED),{ok:!0,value:{dryRun:t,entriesScanned:o.length,recovered:a.filter(c=>c.action==="recovered").length,removePending:a.filter(c=>c.action==="remove-pending").length,preserved:a.filter(c=>c.action==="preserved").length,skipped:a.filter(c=>c.action==="skipped").length,manualWorktreesPreserved:D,bundlesExpired:E,items:a,reasonCodes:we(d)}}})}async cleanupUnguarded(e){le.includes(e.trigger)||u("story-worktree-trigger-invalid");const t=await this.probe(e.leaseId),{entry:r,facts:s}=t;e.requireVanished===!0&&(t.pathAbsence!=="enoent"||r.state!=="active")&&u(i.LEASE_LIVE);const o=(await this.readState(s)).records[r.leaseId];if(r.state==="creating")return e.trigger!=="orphan-recovery"&&u("story-worktree-ownership-unproven"),this.recoverCreating(t,e.dryRun===!0);const f=o!==void 0&&z.includes(o.state);let m=!1;t.pathExists||(t.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.trigger!=="orphan-recovery"&&!f&&u("story-worktree-ownership-unproven"),m=!0),!m&&t.ownership!=="proven"&&u("story-worktree-ownership-unproven"),!m&&t.clean!==!0&&u(e.trigger==="success"?"story-worktree-dirty":i.DIRTY_PRESERVED),t.epicHead||u("story-worktree-epic-branch-missing");const h=t.epicHead,a=m?t.branchSha:t.headSha;!m&&!a&&u("story-worktree-git-failed");const d=t.integrated===!0;e.trigger==="success"&&!d&&u("story-worktree-not-integrated");const g=r.workspaceMechanism==="client_managed_worktree",E=o?.bundleDigest!==void 0&&o.headSha!==void 0&&o.headSha===a&&await this.bundleMatches(s,r.leaseId,o.headSha,o.bundleDigest),p=!d&&a!==void 0&&(g||e.trigger==="orphan-recovery")&&!E,D=o?.remotePush!==void 0&&o.remoteBranchRemoved!==!0;if(e.dryRun===!0){const y=[...p?["bundle-unintegrated-range"]:[],m?"drop-worktree-metadata":"remove-worktree",...g&&t.branchSha?["delete-local-branch"]:[],...D?["delete-remote-branch"]:[]];return{leaseId:r.leaseId,outcome:"dry-run",trigger:e.trigger,state:o?.state??"active",plannedActions:y,preservedReasonCodes:[]}}const c=await this.claim(r);let R=!1;try{let y=E?o?.bundleDigest:void 0;if(p){const I=await this.createBundle(t,a,h);y=I.digest,await this.update(r,c,w=>({...w,state:"bundled",trigger:e.trigger,headSha:a,bundleDigest:I.digest,bundleBytes:I.bytes,bundleExpiresAt:new Date(this.now().getTime()+(this.options.bundleTtlMs??ue)).toISOString()}))}else if(!E){const I=d?"integrated":e.trigger==="failure"?"failed":"abandoned";await this.update(r,c,w=>({...w,state:w.state==="remove-pending"?"remove-pending":I,trigger:e.trigger,...a?{headSha:a}:{}}))}if(m)await S(s.mainRoot,["worktree","remove",r.worktreePath]);else{const I=this.options.removeAttempts??he;if(!await this.removeWithRetry(s.mainRoot,r.worktreePath,I))return await this.update(r,c,w=>({...w,state:"remove-pending",trigger:e.trigger,removeAttempts:Math.min(1e3,w.removeAttempts+I)})),{leaseId:r.leaseId,outcome:"remove-pending",trigger:e.trigger,state:"remove-pending",...y?{bundleDigest:y}:{},preservedReasonCodes:[i.REMOVE_PENDING]}}await S(s.mainRoot,["worktree","prune"]);const C=await this.manager.registeredWorktrees();C.ok||u(C.reasonCode),C.value.worktrees.some(I=>this.manager.sameWorktreePath(I.path,r.worktreePath))&&u(i.ORPHAN_UNPROVEN);const k=[];let L=!1;if(!g)k.push(i.ADOPTED_BRANCH);else if(t.branchSha){const I=a??t.branchSha,w=d||y!==void 0,b=C.value.worktrees.some(U=>U.branch===r.temporaryBranch);w?b?k.push(i.BRANCH_CHECKED_OUT):await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,I])?L=!0:k.push(i.BRANCH_MOVED):k.push(i.ORPHAN_UNPROVEN)}const W=(await this.readState(s)).records[r.leaseId]??o,v=await this.deleteRemote(r,s,W,c,{epicHead:h,...a?{tip:a}:{},bundled:y!==void 0});v.reasonCode&&k.push(v.reasonCode);const _=W?.remotePush!==void 0&&!v.removed&&(v.reasonCode===i.REMOTE_UNVERIFIED||v.reasonCode===i.REMOTE_UNPRESERVED),N=this.now().toISOString(),T={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|${e.trigger}|${N}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:e.trigger,worktreeRemoved:!0,localBranchRemoved:L,remoteBranchRemoved:v.removed,...k[0]?{preservedReasonCode:k[0]}:{},cleanedAt:N};ae(T)||u("story-worktree-receipt-invalid"),await this.mutate(I=>{const w=oe(I),b=w.entries[r.leaseId];for((!b||b.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete w.entries[r.leaseId],w.cleanupReceipts.push({...T});w.cleanupReceipts.length>re;)w.cleanupReceipts.shift()},I=>{const w=I.records[r.leaseId];if(w)if(_&&w.remotePush!==void 0){const b=w.state==="removed"||w.state==="remove-pending"||w.state==="active"?w.bundleDigest?"bundled":"integrated":w.state,U={...w,state:b,updatedAt:N,remoteBranchRemoved:!1};delete U.claimToken,delete U.claimExpiresAt,I.records[r.leaseId]=U}else if(w.bundleDigest){const b={...w,state:"removed",updatedAt:N,remoteBranchRemoved:v.removed};delete b.claimToken,delete b.claimExpiresAt,I.records[r.leaseId]=b}else delete I.records[r.leaseId]}),R=!0;const X=m?{worktree:"enoent",branch:t.branchSha?"present":await this.branchAbsence(s,r.temporaryBranch),bundled:y!==void 0}:void 0;return{leaseId:r.leaseId,outcome:"removed",trigger:e.trigger,state:"removed",receipt:T,receiptDigest:ce(T),...y?{bundleDigest:y}:{},preservedReasonCodes:we(k),...X?{absenceProof:X}:{}}}finally{R||await this.releaseClaim(r,c).catch(()=>{})}}async recoverCreating(e,t){const{entry:r,facts:s}=e,n={leaseId:r.leaseId,trigger:"orphan-recovery",preservedReasonCodes:[]};let o=!1;if(e.pathExists){const h=await S(r.worktreePath,["rev-parse","HEAD"]),a=await S(r.worktreePath,["symbolic-ref","--quiet","--short","HEAD"]),d=await S(r.worktreePath,["status","--porcelain=v1","--untracked-files=all","-z"]);e.registered&&h.ok&&h.stdout.trim()===r.baseSha&&a.ok&&a.stdout.trim()===r.temporaryBranch&&d.ok&&d.stdout.length===0||u(i.ORPHAN_UNPROVEN),o=!0}else e.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.branchCheckedOut&&u(i.ORPHAN_UNPROVEN);if(e.branchSha!==void 0&&e.branchSha!==r.baseSha&&u(i.ORPHAN_UNPROVEN),t)return{...n,outcome:"dry-run",state:"active",plannedActions:[...o?["remove-worktree"]:[],...e.branchSha?["delete-local-branch"]:[],"drop-reservation"]};const f=await this.claim(r);let m=!1;try{o&&!await this.removeWithRetry(s.mainRoot,r.worktreePath,this.options.removeAttempts??he)&&u(i.REMOVE_PENDING),o&&await S(s.mainRoot,["worktree","prune"]);let h=!1;e.branchSha&&(h=await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]));const a=this.now().toISOString(),d={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|creating|${a}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:"orphan-recovery",worktreeRemoved:o,localBranchRemoved:h,remoteBranchRemoved:!1,...e.branchSha&&!h?{preservedReasonCode:i.BRANCH_MOVED}:{},cleanedAt:a};return ae(d)||u("story-worktree-receipt-invalid"),await this.mutate(g=>{const E=oe(g),p=E.entries[r.leaseId];for((!p||p.state!=="creating"||p.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete E.entries[r.leaseId],E.cleanupReceipts.push({...d});E.cleanupReceipts.length>re;)E.cleanupReceipts.shift()},g=>{delete g.records[r.leaseId]}),m=!0,{...n,outcome:"reclaimed",state:"removed",receipt:d,receiptDigest:ce(d),preservedReasonCodes:d.preservedReasonCode?[d.preservedReasonCode]:[]}}finally{m||await this.releaseClaim(r,f).catch(()=>{})}}async closeDetachedRecord(e,t,r){let s,n=e.remoteBranchRemoved===!0;if(e.remotePush&&!n){const o=await S(t.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/epic/${e.epicId}^{commit}`]);if(!(o.ok&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",e.remotePush.sha,o.stdout.trim()])))s=i.REMOTE_UNPRESERVED;else if(!r){const m=await this.deleteRecordedRemote(t.mainRoot,e.remotePush);n=m.removed,s=m.reasonCode}}return r||s===i.REMOTE_UNPRESERVED||s===i.REMOTE_UNVERIFIED||await this.mutate(void 0,o=>{const f=o.records[e.leaseId];!f||f.state==="removed"||(f.bundleDigest?o.records[e.leaseId]={...f,state:"removed",remoteBranchRemoved:n,updatedAt:this.now().toISOString()}:delete o.records[e.leaseId])}),s}async deleteRemote(e,t,r,s,n){const o=r?.remotePush;if(!o)return{removed:!1};if(r?.remoteBranchRemoved===!0)return{removed:!0};if(e.workspaceMechanism!=="client_managed_worktree"||o.branch!==e.temporaryBranch)return{removed:!1,reasonCode:i.ADOPTED_BRANCH};const f=await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.epicHead]),m=!f&&n.bundled&&n.tip!==void 0&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.tip]);if(!f&&!m)return{removed:!1,reasonCode:i.REMOTE_UNPRESERVED};const h=await this.deleteRecordedRemote(t.mainRoot,o);return h.removed&&await this.update(e,s,a=>({...a,remoteBranchRemoved:!0})),h}async deleteRecordedRemote(e,t){if(!await this.gitOk(e,["config","--get",`remote.${t.remote}.url`]))return{removed:!1,reasonCode:i.REMOTE_UNKNOWN};const r=await this.lsRemote(e,t.remote,t.branch);return r===null?{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:r===void 0?{removed:!1,reasonCode:i.REMOTE_ABSENT}:r!==t.sha?{removed:!1,reasonCode:i.REMOTE_DIVERGED}:await this.gitOk(e,["push","--porcelain",`--force-with-lease=refs/heads/${t.branch}:${t.sha}`,t.remote,"--delete",`refs/heads/${t.branch}`])?await this.lsRemote(e,t.remote,t.branch)===void 0?{removed:!0}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}}async lsRemote(e,t,r){const s=await S(e,["ls-remote","--heads",t,`refs/heads/${r}`]);if(!s.ok)return null;const n=s.stdout.split(`
|
|
2
|
+
`).map(f=>f.trim()).find(f=>f.endsWith(` refs/heads/${r}`));if(!n)return;const o=n.split(" ")[0]??"";return K.test(o)?o:null}async createBundle(e,t,r){const{entry:s,facts:n}=e,o=await De(await ne(this.options.projectRoot),Y),f=J(s.leaseId,t),h=(await te(o)).filter(c=>Re.test(c)).filter(c=>c!==f);h.length>=(this.options.maxBundles??Be)&&u(i.BUNDLE_QUOTA);let a=0;for(const c of h)a+=(await $(A(o,c))).size;const d=A(o,f);await V(d,{force:!0});const g=`refs/heads/${s.temporaryBranch}`;await this.gitOk(n.mainRoot,["bundle","create",d,g,`^${r}`])||(await V(d,{force:!0}),u(i.BUNDLE_FAILED)),process.platform!=="win32"&&await _e(d,384);const E=(await $(d)).size;a+E>(this.options.maxBundleBytes??Ve)&&(await V(d,{force:!0}),u(i.BUNDLE_QUOTA));const p=await S(n.mainRoot,["bundle","list-heads",d]);return(!await this.gitOk(n.mainRoot,["bundle","verify","--quiet",d])||!p.ok||!p.stdout.split(`
|
|
3
|
+
`).some(c=>c.trim()===`${t} ${g}`))&&(await V(d,{force:!0}),u(i.BUNDLE_UNVERIFIED)),{digest:x(await B(d)),bytes:E}}async bundleMatches(e,t,r,s){try{const n=A(e.commonDir,F,Y,J(t,r));return x(await B(n))===s}catch{return!1}}async expireBundles(e,t,r,s){const n=A(t.commonDir,F,Y),o=Object.values(e.records).filter(a=>a.state==="removed"&&a.bundleExpiresAt!==void 0&&Date.parse(a.bundleExpiresAt)<=r),f=new Set(Object.values(e.records).filter(a=>a.bundleDigest!==void 0&&a.headSha!==void 0&&!o.some(d=>d.leaseId===a.leaseId)).map(a=>J(a.leaseId,a.headSha))),m=this.options.bundleTtlMs??ue,h=[];if(M(n))for(const a of(await te(n)).filter(d=>Re.test(d)&&!f.has(d))){const d=a.slice(0,28),g=e.records[d];(o.some(E=>E.leaseId===d)||!g&&r-(await $(A(n,a))).mtimeMs>=m)&&h.push(a)}if(s||h.length===0&&o.length===0)return h.length;await this.mutate(void 0,a=>{for(const d of o){const g=a.records[d.leaseId];g?.state==="removed"&&g.bundleExpiresAt===d.bundleExpiresAt&&delete a.records[d.leaseId]}});for(const a of h)await V(A(n,a),{force:!0});return h.length}async reconcileOrphanProgress(e,t,r,s){let n;if(t.outcome==="dry-run"){const h=t.plannedActions??[];if(!h.includes("drop-worktree-metadata"))return;const a=await this.branchAbsence(r,e.temporaryBranch);n={worktreeAbsent:!0,bundled:h.includes("bundle-unintegrated-range"),branchGone:a==="absent"||a==="present"&&h.includes("delete-local-branch")}}else{const h=t.absenceProof;if(t.outcome!=="removed"||!h)return;n={worktreeAbsent:h.worktree==="enoent",bundled:h.bundled,branchGone:h.branch==="absent"||h.branch==="present"&&t.receipt?.localBranchRemoved===!0}}const o={leaseId:e.leaseId,storyId:e.storyId},f={...o,action:"progress-preserved",reasonCode:i.ORPHAN_PROGRESS_PRESERVED},m=A(this.options.projectRoot,".neocortex","state.json");for(let h=1;h<=3;h++){let a,d;try{a=await j(this.options.projectRoot),d=M(m)?await B(m,"utf8"):void 0}catch{return f}const g=Ge({runtime:a,trackedText:d,epicId:e.epicId,storyId:e.storyId,recoveredLeaseId:e.leaseId,loss:n});if(g==="none")return;if(g==="preserved")return f;if(s)return{...o,action:"planned",reasonCode:i.ORPHAN_PROGRESS_RESET,plannedActions:["reset-story-phase-1-progress"]};try{return await ie(this.options.projectRoot,E=>{const p=E.stories[e.storyId];if(!p)throw new Error("git-lifecycle-runtime-revision-conflict");delete p.status,delete p.last_step,delete p.steps_completed,Object.keys(p).length===0&&delete E.stories[e.storyId]},{expectedRevision:a.revision,preCommit:async()=>{if((M(m)?await B(m,"utf8"):void 0)!==d)throw new Error("git-lifecycle-runtime-revision-conflict")}}),{...o,action:"progress-reset",reasonCode:i.ORPHAN_PROGRESS_RESET}}catch(E){if(!(E instanceof Error&&E.message==="git-lifecycle-runtime-revision-conflict"))return f}}return f}async branchAbsence(e,t){const r=await S(e.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${t}`]);return r.ok?"present":r.exitCode===1?"absent":"unknown"}async removeWithRetry(e,t,r){const s=this.options.removeWorktree??((o,f)=>this.gitOk(o,["worktree","remove",f])),n=this.options.removeDelayMs??Ue;for(let o=1;o<=r;o++){if(await s(e,t))return!0;o<r&&await q(n*o)}return!1}async probe(e){const t=await this.manager.probe(e);return t.ok||u(t.reasonCode),t.value}async facts(){const e=await this.manager.registeredWorktrees();return e.ok||u(e.reasonCode),e.value.facts}async gitOk(e,t){return(await S(e,t)).ok}async claim(e){const t=Z(8).toString("hex");return await this.mutate(r=>{const s=r.storyWorktrees?.entries[e.leaseId];(!s||s.nonceDigest!==e.nonceDigest)&&u(i.ENTRY_CONFLICT)},r=>{const s=this.now().getTime(),n=r.records[e.leaseId]??this.emptyRecord(e);P(n,s)&&u(i.CLAIMED),r.records[e.leaseId]={...n,claimToken:t,claimExpiresAt:new Date(s+(this.options.claimTtlMs??Me)).toISOString(),updatedAt:new Date(s).toISOString()}}),t}async releaseClaim(e,t){await this.mutate(void 0,r=>{const s=r.records[e.leaseId];if(!s||s.claimToken!==t)return;const n={...s};delete n.claimToken,delete n.claimExpiresAt,s.state!=="active"||s.remotePush!==void 0||s.ownerPid!==void 0||s.bundleDigest!==void 0||s.removeAttempts>0?r.records[e.leaseId]=n:delete r.records[e.leaseId]})}emptyRecord(e){return{schemaVersion:1,leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,state:"active",removeAttempts:0,updatedAt:this.now().toISOString()}}async update(e,t,r){await this.mutate(s=>{const n=s.storyWorktrees?.entries[e.leaseId];(!n||n.nonceDigest!==e.nonceDigest)&&u(i.ENTRY_CONFLICT)},s=>{const n=s.records[e.leaseId]??this.emptyRecord(e);P(n,this.now().getTime())&&n.claimToken!==t&&u(i.CLAIMED);const o={...r(n),updatedAt:this.now().toISOString()};Ie(e.leaseId,o)||u(i.STATE_INVALID),s.records[e.leaseId]=o})}async mutate(e,t){const r=this.options.lockRetry?.attempts??40,s=this.options.lockRetry?.delayMs??25;for(let n=1;;n++)try{await ie(this.options.projectRoot,o=>{e?.(o),be(o)},{preCommit:async()=>{const o=await ne(this.options.projectRoot),f=A(o,G);let m={schemaVersion:1,records:{}};if(M(f)&&(await se(f,o),m={schemaVersion:1,records:{...Q(await B(f,"utf8")).records}}),t(m),Object.keys(m.records).length===0){M(f)&&await Se(f);return}const h=`${JSON.stringify(m,null,2)}
|
|
4
|
+
`;Q(h),await qe(o,G,h)}});return}catch(o){if(!(o instanceof Error&&(o.message==="git-lifecycle-runtime-lock-active"||o.code==="ENOENT"&&o.message.includes("runtime.lock")))||n>=r)throw o;await q(s*Math.min(n,8)+Math.floor(Math.random()*s))}}async guard(e){try{return await e()}catch(t){if(t instanceof H)return{ok:!1,reasonCode:t.reasonCode};const r=t instanceof Error?t.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(r)?{ok:!1,reasonCode:r}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}}async function qe(l,e,t){const r=A(l,`.${e}.${Z(6).toString("hex")}.tmp`),s=await ee(r,"wx",384);try{await s.writeFile(t,"utf8"),await s.sync()}finally{await s.close()}try{await Ae(r,A(l,e))}catch(n){throw await V(r,{force:!0}),n}try{const n=await ee(l,"r");try{await n.sync()}finally{await n.close()}}catch(n){if(process.platform!=="win32")throw n}}const Je=new Set([i.MANUAL_PRESERVED]);async function Qe(l,e={}){let t;try{const s=await j(l);if(t=new ze({...e,projectRoot:l}),!(Object.keys(s.storyWorktrees?.entries??{}).length>0)&&Object.keys((await t.readState()).records).length===0)return{reasonCodes:[]}}catch(s){return{reasonCodes:s instanceof H?[s.reasonCode]:[]}}const r=await t.sweep({...e.epicId?{epicId:e.epicId}:{},...e.dryRun?{dryRun:!0}:{}});return r.ok?{reasonCodes:r.value.reasonCodes.filter(s=>!Je.has(s)),value:r.value}:{reasonCodes:[r.reasonCode]}}function it(l,e=r=>Qe(r),t=r=>{process.kill(process.pid,r)}){let r=!1;const s=o=>{r||(r=!0,n(),Promise.race([e(l),q(25e3)]).catch(()=>{}).finally(()=>t(o)))},n=()=>{process.removeListener("SIGINT",s),process.removeListener("SIGTERM",s)};return process.once("SIGINT",s),process.once("SIGTERM",s),n}export{Y as STORY_WORKTREE_BUNDLE_DIRECTORY,G as STORY_WORKTREE_CLEANUP_FILE,Ce as STORY_WORKTREE_CLEANUP_MAX_RECORDS,Le as STORY_WORKTREE_CLEANUP_REASON_CODES,Pe as STORY_WORKTREE_CLEANUP_STATES,le as STORY_WORKTREE_CLEANUP_TRIGGERS,ze as StoryWorktreeCleanup,Ge as classifyStoryWorktreeOrphanProgress,it as installStoryWorktreeSignalSweep,Ie as isStoryWorktreeCleanupRecord,Q as parseStoryWorktreeCleanupDocument,J as storyWorktreeBundleFileName,at as storyWorktreeCleanupInProgress,ge as storyWorktreeOwnerHostDigest,Qe as sweepStoryWorktreeOrphans};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as B}from"node:crypto";import{analyzeDependencyDag as C,StructuralDagError as y}from"./structural-dag-projection.js";import{classifyInvocationShapeV2 as O}from"./invocation-shape.js";const U=12,J=16,k=["active","archived","rolled-back","synthetic","orphan"],X=new Set(["in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","partial"]);function Q(r){return r==="STRUCTURAL_TARGET_NOT_FOUND"?"registration-missing":r==="STRUCTURAL_DEPENDENCY_CYCLE"?"dependency-cycle":"dependency-missing"}function Fe(r){const e=/^[a-f0-9]{64}$/,t=/^P[1-9][0-9]*(?:\.[0-9]+)*$/,i=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/;if(r.schemaVersion!=="EpicOperationalPublicProjection/1.0"||!e.test(r.repositoryFingerprint)||!e.test(r.identityHash)||!t.test(r.epicId)||!i.test(r.executionBranch)||!e.test(r.graphRevision)||!Number.isSafeInteger(r.storeRevision)||r.storeRevision<0||!Number.isSafeInteger(r.writerEpoch)||r.writerEpoch<1||r.runId!==null&&r.runId.length>128||r.runStatus!==null&&r.runStatus.length>32||r.runRevision!==null&&(!Number.isSafeInteger(r.runRevision)||r.runRevision<0)||r.snapshotHash!==null&&!e.test(r.snapshotHash)||!e.test(r.continuationSessionHash)||!e.test(r.pendingAuthorityHash)||!Number.isSafeInteger(r.pendingAuthorityCount)||r.pendingAuthorityCount<0||r.pendingAuthorityCount>1024||r.reasonCodes.length>16||r.reasonCodes.some(c=>!/^[a-z0-9][a-z0-9-]{0,79}$/.test(c))||r.publicSafe!==!0)throw new Error("epic-operational-projection-invalid");return Object.freeze({schemaVersion:r.schemaVersion,repositoryFingerprint:r.repositoryFingerprint,identityHash:r.identityHash,epicId:r.epicId,executionBranch:r.executionBranch,graphRevision:r.graphRevision,storeRevision:r.storeRevision,writerEpoch:r.writerEpoch,runId:r.runId,runStatus:r.runStatus,runRevision:r.runRevision,snapshotHash:r.snapshotHash,continuationSessionHash:r.continuationSessionHash,pendingAuthorityHash:r.pendingAuthorityHash,pendingAuthorityCount:r.pendingAuthorityCount,lockActive:r.lockActive,currentSessionActive:r.currentSessionActive,journalActive:r.journalActive,reasonCodes:[...r.reasonCodes],publicSafe:!0})}const o=(r,e,t={})=>({commandId:r,stateProjectionPolicy:e,...t}),A=Object.freeze({status:o("status","full"),"arch-plan":o("arch-plan","full"),"arch-prd":o("arch-prd","full"),"arch-architecture":o("arch-architecture","epic-targeted",{structuralRequired:!0}),"arch-api-contracts":o("arch-api-contracts","epic-targeted",{structuralRequired:!0}),"arch-api-integrations":o("arch-api-integrations","epic-targeted",{structuralRequired:!0}),"arch-database":o("arch-database","epic-targeted",{structuralRequired:!0}),"arch-security":o("arch-security","epic-targeted",{structuralRequired:!0}),"arch-design-system":o("arch-design-system","epic-targeted",{structuralRequired:!0}),"arch-ux-design":o("arch-ux-design","epic-targeted",{structuralRequired:!0}),"arch-performance":o("arch-performance","epic-targeted",{structuralRequired:!0}),"arch-testing":o("arch-testing","epic-targeted",{structuralRequired:!0}),"arch-infrastructure":o("arch-infrastructure","epic-targeted",{structuralRequired:!0}),"arch-review":o("arch-review","epic-targeted",{structuralRequired:!0}),"arch-fitness-functions":o("arch-fitness-functions","epic-targeted",{structuralRequired:!0}),"create-epic":o("create-epic","epic-summary"),"idea-diagnose":o("idea-diagnose","full"),"idea-research":o("idea-research","epic-targeted",{structuralRequired:!0}),"generate-epic":o("generate-epic","epic-targeted",{structuralRequired:!0}),exec:o("exec","story-targeted",{structuralRequired:!0}),yolo:o("yolo","story-targeted",{structuralRequired:!0}),"yolo-inline":o("yolo-inline","story-targeted",{structuralRequired:!0}),epic:o("epic","epic-targeted",{structuralRequired:!0}),"setup-branch":o("setup-branch","story-targeted",{structuralRequired:!0}),diagnose:o("diagnose","adaptive-targeted"),"diagnose-inline":o("diagnose-inline","full"),research:o("research","adaptive-targeted"),"research-inline":o("research-inline","full"),"write-spec":o("write-spec","story-targeted",{structuralRequired:!0}),"create-tasks":o("create-tasks","story-targeted",{structuralRequired:!0}),implement:o("implement","story-targeted",{structuralRequired:!0}),commit:o("commit","story-targeted",{structuralRequired:!0}),"commit-push":o("commit","story-targeted",{structuralRequired:!0}),sync:o("sync","story-targeted",{structuralRequired:!0}),"sync-main":o("sync","story-targeted",{structuralRequired:!0}),"create-pr":o("create-pr","story-targeted",{structuralRequired:!0}),review:o("review","story-targeted"),"review-pr":o("review","story-targeted"),merge:o("merge","story-targeted",{structuralRequired:!0}),"merge-pr":o("merge","story-targeted",{structuralRequired:!0}),"fix-blocked":o("fix-blocked","story-targeted"),"finalize-epic":o("finalize-epic","epic-targeted"),"resolve-conflicts":o("resolve-conflicts","story-targeted"),"update-memory":o("update-memory","full"),"update-project-memory":o("update-memory","story-targeted",{structuralRequired:!0}),refactor:o("refactor","adaptive-targeted"),"refactor-suggest":o("refactor","story-targeted",{structuralRequired:!0}),cleanup:o("cleanup","full"),audit:o("audit","full"),"tech-debt":o("tech-debt","full"),menu:o("menu","full"),plans:o("plans","full"),billing:o("billing","full"),subscribe:o("subscribe","full"),"qa-scan":o("qa-scan","full"),yoloop:o("yoloop","yoloop-targeted",{structuralRequired:!0}),"migrate-state":o("migrate-state","full"),"migrate-project-id":o("migrate-project-id","full"),"policy-audit":o("policy-audit","full"),"mutation-test":o("mutation-test","full"),"sync-openapi":o("sync-openapi","full"),"generate-pacts":o("generate-pacts","full"),"verify-pacts":o("verify-pacts","full"),"property-test":o("property-test","full"),"property-tests":o("property-test","story-targeted",{structuralRequired:!0}),"chaos-plan":o("chaos-plan","full"),"ui-ux-review":o("ui-ux-review","adaptive-targeted"),"solyd-system":o("solyd-system","adaptive-targeted"),goal:o("goal","continuity-scoped"),loop:o("loop","continuity-scoped"),jobs:o("jobs","continuity-scoped"),runner:o("runner","continuity-scoped"),"goal-tick":o("goal-tick","continuity-scoped"),"loop-tick":o("loop-tick","continuity-scoped"),"validate-tests":o("validate-tests","story-targeted",{structuralRequired:!0}),"qa-gate":o("qa-gate","story-targeted",{structuralRequired:!0})}),ee=Object.freeze({st:"status",arquitetura:"arch-plan",architecture:"arch-plan",arch:"arch-plan",prd:"arch-prd","product-requirements":"arch-prd","arch-doc":"arch-architecture","tech-architecture":"arch-architecture","api-contracts":"arch-api-contracts","api-contract":"arch-api-contracts","api-integrations":"arch-api-integrations","api-int":"arch-api-integrations","database-schema":"arch-database","db-schema":"arch-database",db:"arch-database","cyber-security":"arch-security",security:"arch-security",sec:"arch-security","design-system":"arch-design-system",ds:"arch-design-system","atomic-design":"arch-design-system","ux-design":"arch-ux-design",ux:"arch-ux-design",wireframes:"arch-ux-design",wireframe:"arch-ux-design","user-flows":"arch-ux-design",performance:"arch-performance",perf:"arch-performance","capacity-planning":"arch-performance",capacity:"arch-performance","arch-perf":"arch-performance","performance-strategy":"arch-performance","testing-strategy":"arch-testing","test-plan":"arch-testing","test-strategy":"arch-testing","arch-test":"arch-testing",infrastructure:"arch-infrastructure",infra:"arch-infrastructure","deploy-plan":"arch-infrastructure",deployment:"arch-infrastructure","arch-infra":"arch-infrastructure","arch-deploy":"arch-infrastructure","review-consolidation":"arch-review",consolidation:"arch-review","architecture-review":"arch-review","arch-consolidation":"arch-review",fitness:"arch-fitness-functions","fitness-functions":"arch-fitness-functions",archfit:"arch-fitness-functions","arch-fit":"arch-fitness-functions","fit-funcs":"arch-fitness-functions","criar-epic":"create-epic",planejamento:"create-epic","idea-diag":"idea-diagnose","idea-pesq":"idea-research","gerar-epic":"generate-epic",executar:"exec",pipeline:"exec","parallel-epic":"epic",setup:"setup-branch",branch:"setup-branch",diag:"diagnose",diagnostico:"diagnose",c02:"diagnose",pesquisar:"research",pesq:"research","research-fix":"research",c03:"research",spec:"write-spec",especificacao:"write-spec",c04:"write-spec",tasks:"create-tasks",tarefas:"create-tasks",c05:"create-tasks",impl:"implement",implementar:"implement",c06:"implement",push:"commit",commit_push:"commit",cp:"commit",c07:"commit",sincronizar:"sync",c08:"sync",pr:"create-pr",c09:"create-pr",revisar:"review",c11:"review",mesclar:"merge",c12:"merge",fix:"fix-blocked",corrigir:"fix-blocked",finalizar:"finalize-epic",conflitos:"resolve-conflicts",memoria:"update-memory",refactoring:"refactor",refact:"refactor",refac:"refactor",rf:"refactor","cleanup-code":"refactor","code-cleanup":"refactor","code-quality":"refactor","improve-code":"refactor",modernize:"refactor",modernization:"refactor",legacy:"refactor","legacy-code":"refactor","debt-pay":"refactor","pay-debt":"refactor","debt-reduction":"refactor","smell-fix":"refactor","fix-smells":"refactor","code-smells":"refactor",strangler:"refactor","strangler-fig":"refactor",limpar:"cleanup",limpeza:"cleanup",auditar:"audit",auditoria:"audit",debt:"tech-debt",debts:"tech-debt","debt-list":"tech-debt","tech-debts":"tech-debt",td:"tech-debt",help:"menu",ajuda:"menu","?":"menu",commands:"menu",cmds:"menu",planos:"plans",pricing:"plans",bill:"billing",subscription:"billing",sub:"billing",upgrade:"subscribe",checkout:"subscribe",qa:"qa-scan","qa-test":"qa-scan","visual-qa":"qa-scan","e2e-scan":"qa-scan",troubleshoot:"qa-scan","debug-ui":"qa-scan",scan:"qa-scan",a11y:"qa-scan",accessibility:"qa-scan",wcag:"qa-scan","auto-yolo":"yoloop","epic-runner":"yoloop","story-runner":"yoloop","loop-yolo":"yoloop","auto-epic":"yoloop",migrate:"migrate-state","state-migrate":"migrate-state","schema-migrate":"migrate-state",policy:"policy-audit","audit-policy":"policy-audit","policy-history":"policy-audit",policies:"policy-audit",mutation:"mutation-test",stryker:"mutation-test","kill-mutants":"mutation-test","openapi-sync":"sync-openapi","api-sync":"sync-openapi","spec-sync":"sync-openapi","regen-openapi":"sync-openapi",pacts:"generate-pacts","gen-pacts":"generate-pacts","regen-pacts":"generate-pacts","create-pacts":"generate-pacts","verify-pact":"verify-pacts","pact-verify":"verify-pacts","check-pacts":"verify-pacts","pact-check":"verify-pacts",property:"property-test",pbt:"property-test",proptest:"property-test","invariant-test":"property-test",chaos:"chaos-plan",gameday:"chaos-plan","resilience-test":"chaos-plan","ux-review":"ui-ux-review","design-review":"ui-ux-review","visual-review":"ui-ux-review","product-polish":"ui-ux-review","security-system":"solyd-system","authorized-security":"solyd-system","sec-system":"solyd-system",goals:"goal","durable-goal":"goal","continuity-goal":"goal",loops:"loop","durable-loop":"loop","continuity-loop":"loop",job:"jobs","continuity-jobs":"jobs","neocortex-runner":"runner","continuity-runner":"runner"}),te=Object.freeze({1:"status",3:"arch-plan",4:"arch-prd",5:"arch-architecture",6:"arch-api-contracts",7:"arch-api-integrations",8:"arch-database",9:"arch-security",10:"arch-design-system",11:"arch-ux-design",12:"arch-performance",13:"arch-testing",14:"arch-infrastructure",15:"arch-review",16:"arch-fitness-functions",17:"create-epic",18:"idea-diagnose",19:"idea-research",20:"generate-epic",21:"exec",22:"yolo",23:"epic",24:"setup-branch",25:"diagnose",26:"research",27:"write-spec",28:"create-tasks",29:"implement",30:"commit",31:"sync",32:"create-pr",33:"review",34:"merge",35:"fix-blocked",36:"finalize-epic",37:"resolve-conflicts",38:"update-memory",39:"refactor",40:"cleanup",41:"audit",42:"tech-debt",43:"menu",44:"plans",45:"billing",46:"subscribe",47:"qa-scan",48:"yoloop",49:"migrate-state",50:"policy-audit",51:"mutation-test",52:"sync-openapi",53:"generate-pacts",54:"verify-pacts",55:"property-test",56:"chaos-plan",57:"ui-ux-review",58:"solyd-system",59:"goal",60:"loop",61:"jobs",62:"runner"});function d(r,e=120){if(typeof r!="string")return;const t=r.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,e)}function w(r,e=120){if(typeof r!="string")return;const t=r.trim(),i=d(r,e);return i===t?i:void 0}function T(r){if(typeof r!="string")return;const e=r.trim();if(!(!e||e.length>240||!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(e)||e.includes("..")||e.includes("//")||e.includes("@{")||e.endsWith("/")||e.endsWith(".")||e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))))return e}function re(r){if(typeof r!="string")return;const e=r.replace(/\\/g,"/");if(!(!e||e.length>240||e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.includes("..")||e.includes("//")||e.split("/").includes(".")||!/^[A-Za-z0-9._/:@#-]+$/.test(e)))return e}function S(r){if(r===void 0||!Array.isArray(r)||r.length>128)return;const e=r.map(re);if(!e.some(t=>t===void 0))return[...new Set(e)].sort((t,i)=>t.localeCompare(i,"en"))}function ie(r){return typeof r=="string"&&X.has(r.trim().toLowerCase().replace(/_/g,"-"))}function v(r,e){const t={};for(const i of e){const c=r[i];typeof c=="string"||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)?t[i]=c:Array.isArray(c)&&c.every(n=>typeof n=="string")&&(t[i]=[...c])}return t}function ce(r,e){const t=e.checkpoint;if(!h(t)||t.schemaVersion!==1||t.storyId!==r||t.epicId!==e.epic_id||!T(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.headSha)||t.baseSha===t.headSha||!w(t.idempotencyKey)||typeof t.recordedAt!="string"||!Number.isFinite(Date.parse(t.recordedAt))||!Array.isArray(t.commits)||t.commits.length===0||t.commits.length>256||t.commits.some(c=>typeof c!="string"||!/^[0-9a-f]{7,64}$/i.test(c))||!Array.isArray(t.receiptRefs)||t.receiptRefs.length===0||t.receiptRefs.length>256||t.receiptRefs.some(c=>typeof c!="string"||c.length>240||c.includes("..")||!/^[A-Za-z0-9._:/#\-[\]]+$/.test(c))||!h(t.qaReceipt)||t.qaReceipt.kind!=="story_qa_evidence"||t.qaReceipt.producer!=="local-yolo-tdd"||!["passed","blocked"].includes(String(t.qaVerdict))||!["approved","changes-requested","pending"].includes(String(t.reviewVerdict))||(t.reviewVerdict==="pending"?t.reviewReceipt!==void 0:!h(t.reviewReceipt)))return;const i=v(t,["schemaVersion","storyId","epicId","branch","baseSha","headSha","idempotencyKey","dispatchId","bundleId","bundleDigest","graphRevision","claimRevision","qaVerdict","reviewVerdict","recordedAt","commits","receiptRefs"]);return i.qaReceipt=v(t.qaReceipt,["schemaVersion","kind","producer","evidenceVersion","storyId","epicId","contract","command","manifestDigest","gateIds","resultDigest","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","verdict","checkedAt","receiptRef"]),h(t.reviewReceipt)&&(i.reviewReceipt=v(t.reviewReceipt,["schemaVersion","kind","producer","storyId","epicId","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","qaReceiptRef","verdict","reviewedAt","receiptRef"])),i}function ne(r,e){const t=e.checkpoint_verification;if(!(!h(t)||t.schemaVersion!==1||t.kind!=="story_checkpoint_physical_verification"||t.producer!=="client-p205-transient-v1"||t.publicSafe!==!0||t.storyId!==r||t.epicId!==e.epic_id||!["verified","rejected"].includes(String(t.verdict))))return v(t,["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","aggregateHeadSha","commitBodyDigest","changedPathsDigest","claimVerification","effectiveClaimRevision","command","manifestDigest","gateIds","resultDigest","graphRevision","executionEvidenceDigest","sourceEvidenceDigest","verifiedAt","verdict","reasonCodes","publicSafe"])}function M(r,e){const t=e.scheduling_checkpoint_evidence,i=new Set(["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"]);if(!(!h(t)||Object.keys(t).some(c=>!i.has(c))||t.schemaVersion!==1||t.kind!=="story_scheduling_checkpoint_evidence"||t.producer!=="client-git-physical-v1"||t.publicSafe!==!0||t.integrationAuthorized!==!1||t.storyId!==r||t.epicId!==e.epic_id||!T(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{40,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{40,64}$/i.test(t.headSha)||typeof t.graphRevision!="string"||!/^[0-9a-f]{64}$/i.test(t.graphRevision)||typeof t.effectiveClaimRevision!="string"||!/^[0-9a-f]{64}$/i.test(t.effectiveClaimRevision)||typeof t.sourceEvidenceDigest!="string"||!/^[0-9a-f]{64}$/i.test(t.sourceEvidenceDigest)||typeof t.verifiedAt!="string"||!Number.isFinite(Date.parse(t.verifiedAt))||!Array.isArray(t.reasonCodes)||t.reasonCodes.length!==1||t.reasonCodes[0]!=="checkpoint-git-scheduling-verified"))return v(t,[...i])}function oe(r,e){const t={...e},i=M(r,e);return i?(t.scheduling_checkpoint_evidence=i,delete t.checkpoint,delete t.checkpoint_verification):delete t.scheduling_checkpoint_evidence,t}function h(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function _(...r){const e=new Set,t=[];for(const i of r)for(const c of i??[]){const n=d(c,80);if(!(!n||e.has(n))&&(e.add(n),t.push(n),t.length>=J))return t}return t}function se(r){return r.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function ae(r){return r.trim().split(/\s+/,1)[0]??""}function z(r){if(/^@epic-P[0-9]{1,12}$/.test(r.trim()))return A.epic;const e=ae(r);if(!e)return A.menu;const t=se(e),i=te[t]??ee[t]??t;return A[i]??null}function de(r,e,t,i="full-compatible",c=["full-state"]){return{kind:"full",commandId:t?.commandId??null,stateProjectionPolicy:t?.stateProjectionPolicy??null,projectionMode:i,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(e.stories).length,includedEpicCount:Object.keys(e.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",reasonCodes:_(c)}}function Le(r,e,t,i="full-compatible",c=["full-state"]){const n=de(r,e,t,i,c);return I({...e,scope:n},e,n)}function ue(r){const[e]=r.trim().split(/\s+/,1);return e?/^[A-Z]?\d+(?:\.\d+)+$/i.test(e.replace(/^@/,""))||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(e.replace(/^@/,"")):!1}function F(r){const e=r.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return e?.[1]?e[1]:r.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function le(r){const e=r.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function q(r){return le(r).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function $e(r){return q(r)[0]??null}function P(r,e){const i=r.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),c=[i,i.toUpperCase(),/^p\d+$/i.test(i)?`P${i.replace(/^p/i,"")}`:null,/^\d+$/.test(i)?`P${i}`:null].filter(n=>typeof n=="string"&&n.length>0);for(const n of c)if(e.epics[n])return n;return null}function pe(r,e){const t=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?P(t[1],e):null}function R(r,e){const t=r.trim().match(/^@epic-(P[0-9]{1,12})$/);if(t)return P(t[1],e);const i=pe(r,e);if(i)return i;for(const c of q(r)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(c))continue;const n=P(c,e);if(n)return n}return null}function fe(r,e){const t=R(r,e);if(t)return t;const i=e.yoloop,c=i?.state?.currentSession?.currentEpicId;if(typeof c=="string"&&e.epics[c])return c;const n=i?.lock?.currentEpicId??i?.lock?.epicId;return typeof n=="string"&&e.epics[n]?n:null}function ye(r){const e=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];if(e)return/^P/i.test(e)?e.toUpperCase():`P${e}`;for(const t of q(r)){if(/^P\d+$/i.test(t))return t.toUpperCase();if(/^\d+$/.test(t))return`P${t}`}return null}function j(r,e){if(typeof r.epic_id=="string"&&r.epic_id.length>0)return r.epic_id;const t=e.split(".").slice(0,-1).join(".");return t.length>0?t:null}function L(r){return typeof r=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(r.toLowerCase())}function x(r,e,t){if(t.has(r))return;const i=e.stories[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const n of c)typeof n=="string"&&x(n,e,t)}function me(r,e){const t=C(e.stories,[r]),i={};for(const c of t.orderedIds){const n=e.stories[c];n&&(i[c]=n)}return i}function $(r,e,t=[]){const i={};for(const c of t)e.epics[c]&&(i[c]=e.epics[c]);for(const[c,n]of Object.entries(r)){const s=j(n,c);s&&e.epics[s]&&(i[s]=e.epics[s])}return i}function ge(r,e,t){if(t.has(r))return;const i=e.epics[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const n of c)typeof n=="string"&&n.length>0&&ge(n,e,t)}function V(r,e,t){const i=C(t.epics,[r]),c=new Set(i.orderedIds);for(const[s,a]of Object.entries(e)){const u=j(a,s);u&&t.epics[u]&&c.add(u)}const n={};for(const s of[...c].sort((a,u)=>a.localeCompare(u,"en"))){const a=t.epics[s];a&&(n[s]=s===r?a:H(s,a))}return n}function G(r,e,t){const i=e.stories;if(!Array.isArray(i)||i.some(s=>typeof s!="string"||s.length===0))throw new y("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedStoryMemberships:1});const c=C(t.stories,i),n={};for(const s of c.orderedIds){const a=t.stories[s];a&&(n[s]=j(a,s)===r?oe(s,a):Y(s,a))}return n}function he(r,e,t){const i=[...e.stories].sort((s,a)=>s.localeCompare(a,"en")),c=Object.entries(t).filter(([s,a])=>j(a,s)===r).map(([s])=>s).sort((s,a)=>s.localeCompare(a,"en")),n=B("sha256").update(`target-epic-coverage-v1\0${JSON.stringify({targetEpicId:r,declaredStoryIds:i,includedStoryIds:c})}`).digest("hex");return{schemaVersion:"TargetEpicCoverage/1.0",targetEpicId:r,declaredStoryIds:i,includedStoryIds:c,membershipSha256:n,publicSafe:!0}}function Y(r,e){const t=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(m=>typeof m=="string"&&m.length>0))].sort((m,E)=>m.localeCompare(E,"en")):void 0,i={id:d(e.id)??r,...d(e.epic_id)?{epic_id:d(e.epic_id)}:{},...d(e.status,40)?{status:d(e.status,40)}:{},...t?{depends_on:t}:{}},c=M(r,e);if(!ie(e.status))return{...i,...c?{scheduling_checkpoint_evidence:c}:{}};const n=e.source==="create-epic"||e.source==="discovered"?e.source:void 0,s=T(e.branch_name),a=w(e.last_step,120),u=Array.isArray(e.steps_completed)&&e.steps_completed.length<=64?e.steps_completed.map(m=>w(m,120)):[],l=u.length>0&&u.every(m=>m!==void 0)?u:void 0,f=typeof e.pr_number=="number"&&Number.isSafeInteger(e.pr_number)&&e.pr_number>0?e.pr_number:void 0,p=ce(r,e),g=p?ne(r,e):void 0;return{...i,...n?{source:n}:{},...s?{branch_name:s}:{},...a?{last_step:a}:{},...l?{steps_completed:l}:{},...f?{pr_number:f}:{},...p?{checkpoint:p}:{},...g?{checkpoint_verification:g}:{},...c?{scheduling_checkpoint_evidence:c}:{},...S(e.files_to_modify)!==void 0?{files_to_modify:S(e.files_to_modify)}:{},...S(e.contracts)!==void 0?{contracts:S(e.contracts)}:{},...S(e.contract_refs)!==void 0?{contract_refs:S(e.contract_refs)}:{},...S(e.shared_surfaces)!==void 0?{shared_surfaces:S(e.shared_surfaces)}:{}}}function H(r,e){const t=Array.isArray(e.stories)?[...new Set(e.stories.filter(c=>typeof c=="string"&&c.length>0))].sort((c,n)=>c.localeCompare(n,"en")):[],i=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(c=>typeof c=="string"&&c.length>0))].sort((c,n)=>c.localeCompare(n,"en")):[];return{id:d(e.id)??r,...d(e.status,40)?{status:d(e.status,40)}:{},...d(e.lifecycle_classification,40)?{lifecycle_classification:d(e.lifecycle_classification,40)}:{},stories:t,depends_on:i}}function be(r,e,t){const i=C(e.stories),c=C(e.epics),n=Object.fromEntries(i.orderedIds.map(u=>[u,Y(u,e.stories[u])])),s=Object.fromEntries(c.orderedIds.map(u=>[u,H(u,e.epics[u])])),a={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"yoloop-discovery",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:i.orderedIds.length,includedEpicCount:c.orderedIds.length,omittedStoryCount:0,omittedEpicCount:0,reason:"targeted-invocation",reasonCodes:_(["structural-required","yoloop-discovery",`structural-edges-${i.edgeCount+c.edgeCount}`,"content-fields-omitted"])};return I({...e,stories:n,epics:s,scope:a},e,a)}function _e(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const n of i)typeof n=="string"&&x(n,e,t);const c={};for(const n of t){const s=e.stories[n];s&&(c[n]=s)}return c}function Se(r){const e={};for(const[t,i]of Object.entries(r.epics))e[t]={id:d(i.id)??t,...d(i.status)?{status:d(i.status)}:{},...k.includes(i.lifecycle_classification)?{lifecycle_classification:i.lifecycle_classification}:{},...typeof i.total_stories=="number"&&Number.isFinite(i.total_stories)?{total_stories:i.total_stories}:{},...typeof i.completed_stories=="number"&&Number.isFinite(i.completed_stories)?{completed_stories:i.completed_stories}:{}};return e}function K(r){const e={};for(const t of Object.values(r)){const i=d(t.status,40)??"unknown";e[i]=(e[i]??0)+1}return e}function je(r){const e=Object.fromEntries(k.map(t=>[t,0]));for(const t of Object.values(r)){const i=k.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[i]=(e[i]??0)+1}return e}function N(r,e){if(!e)return!0;const t=r.epics[e];return t?!k.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function Z(r){for(const e of["last_updated","updated_at","completed_at","created_at","discovered_at"]){const t=r[e];if(typeof t!="string")continue;const i=Date.parse(t);if(Number.isFinite(i))return i}return 0}function Ie(r){return Object.entries(r.stories).map(([e,t])=>({id:e,story:t,timestamp:Z(t)})).sort((e,t)=>t.timestamp-e.timestamp||e.id.localeCompare(t.id)).slice(0,U).map(({id:e,story:t})=>({id:e,...d(t.epic_id)?{epicId:d(t.epic_id)}:{},...d(t.status,40)?{status:d(t.status,40)}:{},...d(t.last_step??t.lastStep)?{lastStep:d(t.last_step??t.lastStep)}:{},...d(t.last_updated??t.updated_at??t.completed_at??t.created_at)?{lastUpdated:d(t.last_updated??t.updated_at??t.completed_at??t.created_at)}:{}}))}function Ce(r){const e=r.current_session;if(!e)return;const t={activeEpicId:d(e.active_epic_id)??null,activeStoryId:d(e.active_story_id)??null,activeStepId:d(e.active_step_id)??null,sessionId:d(e.session_id)??null,startedAt:d(e.started_at)??null};return Object.values(t).some(i=>i!=null)?t:void 0}function ke(r){const e=r.yoloop;if(!h(e))return;const t=h(e.state)?e.state:void 0,i=h(t?.currentSession)?t.currentSession:void 0,c=h(e.lock)?e.lock:void 0,n={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:d(i?.currentEpicId??e.currentEpicId)??null,currentStoryId:d(i?.currentStoryId??e.currentStoryId)??null,sessionId:d(i?.sessionId??e.sessionId)??null,lockEpicId:d(c?.currentEpicId??c?.epicId)??null};return Object.keys(n).length>0?n:void 0}function ve(r){const e=r.continuity;if(!h(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(i=>typeof i=="string"):void 0;return{present:!0,activeJobId:d(e.activeJobId??e.jobId)??null,activeGoalId:d(e.activeGoalId??e.goalId)??null,activeLoopId:d(e.activeLoopId??e.loopId)??null,...t&&t.length>0?{reasonCodes:_(t)}:{}}}function Ee(r,e,t){const i=d(e?.activeStoryId),c=d(e?.activeEpicId),n=d(e?.activeStepId),s=i&&r.stories[i]?j(r.stories[i],i):null;if((i||c||n)&&N(r,c??s))return{epicId:c??null,storyId:i??null,stepId:n??null};const a=d(t?.currentStoryId),u=d(t?.currentEpicId??t?.lockEpicId);if((a||u)&&N(r,u))return{epicId:u??null,storyId:a??null,stepId:null};const l=Object.entries(r.stories).map(([f,p])=>({id:f,story:p,timestamp:Z(p)})).filter(({id:f,story:p})=>!L(p.status)&&N(r,j(p,f))).sort((f,p)=>p.timestamp-f.timestamp||f.id.localeCompare(p.id))[0];return l?{epicId:j(l.story,l.id),storyId:l.id,stepId:d(l.story.last_step??l.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function Re(r,e){const t=K(r.stories),i=K(r.epics),c=je(r.epics),n=Object.values(r.epics).filter(g=>(k.includes(g.lifecycle_classification)?g.lifecycle_classification:"active")==="active"&&!L(g.status)).length,s=Ce(r),a=ke(r),u=ve(r),l=Ee(r,s,a),f=Ie(r),p=_(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",f.length>=U?"recent-stories-capped":"recent-stories-bounded",l.storyId||l.epicId?"active-ref-derived":"active-ref-empty",a?"yoloop-session-present":"yoloop-session-absent",u?"continuity-session-present":"continuity-session-absent"]);return{schemaVersion:1,totals:{stories:Object.keys(r.stories).length,epics:Object.keys(r.epics).length,storyStatus:t,epicStatus:i,epicLifecycle:c,activeEpics:n,blockedStories:t.blocked??0},active:l,blockedCount:t.blocked??0,recentStories:f,...s?{currentSession:s}:{},...a?{currentYoloopSession:a}:{},...u?{currentContinuitySession:u}:{},projection:{commandId:e.commandId??null,stateProjectionPolicy:e.stateProjectionPolicy??null,projectionMode:e.projectionMode,scopeKind:e.kind,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??Object.keys(r.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:p,publicSafe:!0}}function I(r,e,t){return{...r,stateSummary:Re(e,t)}}function Oe(r,e,t){const i={};for(const n of Object.keys(e.epics))i[n]={id:n};const c={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"summary-only",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(i).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:0,reason:"epic-summary",reasonCodes:["epic-summary","stories-omitted","epic-stubs-only"]};return I({...e,stories:{},epics:i,scope:c},e,c)}function b(r,e,t,i=["summary-only","stories-omitted"],c="summary-only"){const n=Se(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(n).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(n).length),reason:"summary-only",reasonCodes:_(i)};return I({...e,stories:{},epics:n,scope:s},e,s)}function D(r,e,t,i,c,n){const s=e.stories[i];if(!s)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"});const a=j(s,i);if(!a)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=e.epics[a];if(!u)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const l=c==="yolo-story",f=l?G(a,u,e):me(i,e),p=l?V(a,f,e):$(f,e);if(!f[i]||!p[a])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(f).length,epics:Object.keys(p).length,targetKind:"story"});const g={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:a,targetStoryId:i,includedStoryCount:Object.keys(f).length,includedEpicCount:Object.keys(p).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(f).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(p).length),reason:"targeted-invocation",reasonCodes:_(n,l?["epic-graph-authority-complete"]:[])};return I({...e,stories:f,epics:p,scope:g},e,g)}function W(r,e,t,i,c,n){const s=e.epics[i];if(!s)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=_e(s,e),u=$(a,e,[i]);if(!u[i])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(a).length,epics:Object.keys(u).length,targetKind:"epic"});const l={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:i,targetStoryId:null,includedStoryCount:Object.keys(a).length,includedEpicCount:Object.keys(u).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(a).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(u).length),reason:"targeted-invocation",reasonCodes:_(n)};return I({...e,stories:a,epics:u,scope:l},e,l)}function Ae(r,e,t){const i=ye(r),c=R(r,e);if(i&&!c)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const n=fe(r,e),s=O({commandId:t.commandId,explicitYoloopEpicId:c,sessionYoloopEpicId:c?null:n});if(s==="yoloop-discovery")return be(r,e,t);if(!n||s!=="yoloop-target"&&s!=="yoloop-session")throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=e.epics[n];if(!a)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=G(n,a,e),l=V(n,u,e);if(!l[n])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(u).length,epics:Object.keys(l).length,targetKind:"epic"});const f=s,p={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:f,trigger:r,targetEpicId:n,targetStoryId:null,targetEpicCoverage:he(n,a,u),includedStoryCount:Object.keys(u).length,includedEpicCount:Object.keys(l).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(u).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(l).length),reason:"targeted-invocation",reasonCodes:["structural-required",f,"yoloop-targeted"]};return I({...e,stories:u,epics:l,scope:p},e,p)}function we(r,e){const t={};for(const[i,c]of Object.entries(r.epics)){const n=Array.isArray(c.stories)?c.stories.filter(s=>typeof s=="string"&&e.has(s)):[];t[i]={id:d(c.id)??i,...d(c.status,40)?{status:d(c.status,40)}:{},...typeof c.total_stories=="number"&&Number.isFinite(c.total_stories)?{total_stories:c.total_stories}:{},...typeof c.completed_stories=="number"&&Number.isFinite(c.completed_stories)?{completed_stories:c.completed_stories}:{},...n.length>0?{stories:n}:{},...n.length>0&&Array.isArray(c.depends_on)?{depends_on:c.depends_on.filter(s=>typeof s=="string"&&s.length>0)}:{},...n.length>0&&(c.branch_mode==="epic"||c.branch_mode==="story")?{branch_mode:c.branch_mode}:{},...n.length>0&&typeof c.execution_branch=="string"?{execution_branch:c.execution_branch}:{},...n.length>0&&typeof c.origin_branch=="string"?{origin_branch:c.origin_branch}:{},...n.length>0&&(c.branch_lease===null||typeof c.branch_lease=="object")?{branch_lease:c.branch_lease}:{},...n.length>0&&(c.origin_binding===null||typeof c.origin_binding=="object")?{origin_binding:c.origin_binding}:{},...n.length>0&&(c.aggregate_qa_receipt===null||typeof c.aggregate_qa_receipt=="object")?{aggregate_qa_receipt:c.aggregate_qa_receipt}:{},...n.length>0&&(c.head_reconciliation_receipt===null||typeof c.head_reconciliation_receipt=="object")?{head_reconciliation_receipt:c.head_reconciliation_receipt}:{},...n.length>0&&c.story_worktree_evidence!==null&&typeof c.story_worktree_evidence=="object"?{story_worktree_evidence:c.story_worktree_evidence}:{},...n.length>0&&c.branch_mode_conversion_receipt!==null&&typeof c.branch_mode_conversion_receipt=="object"&&!Array.isArray(c.branch_mode_conversion_receipt)?{branch_mode_conversion_receipt:c.branch_mode_conversion_receipt}:{}}}return t}function Te(r){return r.stateSummary?.totals.stories??(r.scope?.includedStoryCount??Object.keys(r.stories).length)+(r.scope?.omittedStoryCount??0)}function qe(r){return r.stateSummary?.totals.epics??(r.scope?.includedEpicCount??Object.keys(r.epics).length)+(r.scope?.omittedEpicCount??0)}function Pe(r,e){if(r.stateSummary)return{...r.stateSummary,projection:{...r.stateSummary.projection,scopeKind:"projected",projectionMode:e.projectionMode,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??r.stateSummary.projection.includedEpicCount,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:"body-size"},reasonCodes:_(r.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function Ve(r){const e=r.scope,t=new Set,i=e?.projectionMode==="structural-required"||e?.projectionMode==="yolo-story"||e?.projectionMode==="yoloop-target"||e?.projectionMode==="yoloop-session"||e?.projectionMode==="yoloop-discovery";if(i)for(const m of Object.keys(r.stories))t.add(m);else e?.targetStoryId&&x(e.targetStoryId,r,t);const c={};for(const m of t){const E=r.stories[m];E&&(c[m]=E)}const n=we(r,t),s=Object.keys(c).length,a=Object.keys(n).length,u=Math.max(0,Te(r)-s),l=Math.max(0,qe(r)-a),f=i?e?.projectionMode??"structural-required":e?.projectionMode==="yolo-story"?"yolo-story":"summary-only",p={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:f,targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,...e?.targetEpicCoverage?{targetEpicCoverage:e.targetEpicCoverage}:{},includedStoryCount:s,includedEpicCount:a,omittedStoryCount:u,omittedEpicCount:l,reason:"body-size",reasonCodes:_(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved","redundant-trigger-omitted"])},g=Pe(r,p);return{...r,stories:c,epics:n,scope:p,...g?{stateSummary:g}:{}}}function xe(r,e){const t=r.trim(),i=z(t);try{if(!i){if(ue(t)){const n=o("story-reference","story-targeted"),s=F(t);if(s)return D(t,e,n,s,"targeted-story",["story-reference-targeted"])}return b(t,e,o("unknown","adaptive-targeted"),["unknown-command-summary-only"])}if(i.stateProjectionPolicy==="epic-summary")return Oe(t,e,i);if(i.stateProjectionPolicy==="yoloop-targeted")return Ae(t,e,i);const c=F(t);if(i.stateProjectionPolicy==="story-targeted"){if(c){const s=O({commandId:i.commandId,targetStoryId:c})==="yolo-story";return D(t,e,i,c,s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story",[s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story"])}if(i.commandId==="yolo"||i.commandId==="yolo-inline"){const n=O({commandId:i.commandId});return b(t,e,i,["yolo-inline","stories-omitted","historical-content-omitted"],n??"yolo-inline")}return i.commandId==="commit"&&/^\*?(?:commit|commit-push)$/i.test(t)?b(t,e,i,["working-tree-commit","stories-omitted","historical-content-omitted"]):i.structuralRequired?(()=>{throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"})})():b(t,e,i,["story-target-missing-summary-only"])}if(i.stateProjectionPolicy==="adaptive-targeted"){if(c&&e.stories[c])return D(t,e,i,c,"targeted-story",["adaptive-story-targeted"]);const n=R(t,e);return n?W(t,e,i,n,"targeted-epic",["adaptive-epic-targeted"]):b(t,e,i,["adaptive-summary-only","target-unresolved-summary-only"])}if(i.stateProjectionPolicy==="epic-targeted"){if(i.commandId.startsWith("arch-")&&/(?:^|\s)epic-arch\s*$/i.test(t)&&e.archPlan?.execution?.currentStageCommand===i.commandId)return b(t,e,i,["architecture-root-delegated"]);const n=R(t,e);return n?W(t,e,i,n,i.structuralRequired?"structural-required":"targeted-epic",[i.structuralRequired?"structural-required":"targeted-epic"]):i.structuralRequired?(()=>{throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"})})():b(t,e,i,["epic-target-missing-summary-only"])}return i.stateProjectionPolicy==="continuity-scoped"?b(t,e,i,["continuity-scoped-summary-only"]):b(t,e,i,["policy-full-summary-only"])}catch(c){if(c instanceof y)throw c;if(i?.structuralRequired)throw new y("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,projectionErrors:1});return b(t,e,i??o("unknown","adaptive-targeted"),["projection-error-summary-only"])}}const Ne=new Set(["yolo-story","yolo-inline","yoloop-target","yoloop-session","yoloop-discovery"]);function De(r){let e=0;for(const t of[r.stories,r.epics])for(const i of Object.values(t))Array.isArray(i.depends_on)&&(e+=i.depends_on.filter(c=>typeof c=="string").length);return e}function Ge(r,e){const t=z(r.trim());if(!t||!["yolo","yolo-inline","yoloop"].includes(t.commandId))return null;try{const i=xe(r,e),c=i.scope?.projectionMode;if(!c||!Ne.has(c))throw new y("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(i.stories).length,epics:Object.keys(i.epics).length,projectionShapeErrors:1});return Object.freeze({ok:!0,version:2,shape:c,snapshot:i,included:{epics:i.scope?.includedEpicCount??Object.keys(i.epics).length,stories:i.scope?.includedStoryCount??Object.keys(i.stories).length,edges:De(i)},omitted:{epics:i.scope?.omittedEpicCount??0,stories:i.scope?.omittedStoryCount??0},cycleCount:0})}catch(i){if(!(i instanceof y))throw i;return Object.freeze({ok:!1,code:i.code,publicDetails:{...i.publicDetails,...i.code==="STRUCTURAL_CONTEXT_TOO_LARGE"?{}:{planningCause:Q(i.code)}}})}}export{Ve as degradeStateSnapshotForPayloadLimit,Q as planningProjectionCauseForStructuralCode,Fe as projectEpicOperationalEvidenceForRequest,xe as projectStateSnapshotForInvoke,Ge as projectStateSnapshotResultV2ForInvoke};
|
|
1
|
+
import{createHash as W}from"node:crypto";import{analyzeDependencyDag as C,StructuralDagError as y}from"./structural-dag-projection.js";import{classifyInvocationShapeV2 as O}from"./invocation-shape.js";const U=12,J=16,k=["active","archived","rolled-back","synthetic","orphan"],X=new Set(["in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","partial"]);function Q(r){return r==="STRUCTURAL_TARGET_NOT_FOUND"?"registration-missing":r==="STRUCTURAL_DEPENDENCY_CYCLE"?"dependency-cycle":"dependency-missing"}function Fe(r){const e=/^[a-f0-9]{64}$/,t=/^P[1-9][0-9]*(?:\.[0-9]+)*$/,i=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/;if(r.schemaVersion!=="EpicOperationalPublicProjection/1.0"||!e.test(r.repositoryFingerprint)||!e.test(r.identityHash)||!t.test(r.epicId)||!i.test(r.executionBranch)||!e.test(r.graphRevision)||!Number.isSafeInteger(r.storeRevision)||r.storeRevision<0||!Number.isSafeInteger(r.writerEpoch)||r.writerEpoch<1||r.runId!==null&&r.runId.length>128||r.runStatus!==null&&r.runStatus.length>32||r.runRevision!==null&&(!Number.isSafeInteger(r.runRevision)||r.runRevision<0)||r.snapshotHash!==null&&!e.test(r.snapshotHash)||!e.test(r.continuationSessionHash)||!e.test(r.pendingAuthorityHash)||!Number.isSafeInteger(r.pendingAuthorityCount)||r.pendingAuthorityCount<0||r.pendingAuthorityCount>1024||r.reasonCodes.length>16||r.reasonCodes.some(c=>!/^[a-z0-9][a-z0-9-]{0,79}$/.test(c))||r.publicSafe!==!0)throw new Error("epic-operational-projection-invalid");return Object.freeze({schemaVersion:r.schemaVersion,repositoryFingerprint:r.repositoryFingerprint,identityHash:r.identityHash,epicId:r.epicId,executionBranch:r.executionBranch,graphRevision:r.graphRevision,storeRevision:r.storeRevision,writerEpoch:r.writerEpoch,runId:r.runId,runStatus:r.runStatus,runRevision:r.runRevision,snapshotHash:r.snapshotHash,continuationSessionHash:r.continuationSessionHash,pendingAuthorityHash:r.pendingAuthorityHash,pendingAuthorityCount:r.pendingAuthorityCount,lockActive:r.lockActive,currentSessionActive:r.currentSessionActive,journalActive:r.journalActive,reasonCodes:[...r.reasonCodes],publicSafe:!0})}const n=(r,e,t={})=>({commandId:r,stateProjectionPolicy:e,...t}),A=Object.freeze({status:n("status","full"),"arch-plan":n("arch-plan","full"),"arch-prd":n("arch-prd","full"),"arch-architecture":n("arch-architecture","epic-targeted",{structuralRequired:!0}),"arch-api-contracts":n("arch-api-contracts","epic-targeted",{structuralRequired:!0}),"arch-api-integrations":n("arch-api-integrations","epic-targeted",{structuralRequired:!0}),"arch-database":n("arch-database","epic-targeted",{structuralRequired:!0}),"arch-security":n("arch-security","epic-targeted",{structuralRequired:!0}),"arch-design-system":n("arch-design-system","epic-targeted",{structuralRequired:!0}),"arch-ux-design":n("arch-ux-design","epic-targeted",{structuralRequired:!0}),"arch-performance":n("arch-performance","epic-targeted",{structuralRequired:!0}),"arch-testing":n("arch-testing","epic-targeted",{structuralRequired:!0}),"arch-infrastructure":n("arch-infrastructure","epic-targeted",{structuralRequired:!0}),"arch-review":n("arch-review","epic-targeted",{structuralRequired:!0}),"arch-fitness-functions":n("arch-fitness-functions","epic-targeted",{structuralRequired:!0}),"create-epic":n("create-epic","epic-summary"),"idea-diagnose":n("idea-diagnose","full"),"idea-research":n("idea-research","epic-targeted",{structuralRequired:!0}),"generate-epic":n("generate-epic","epic-targeted",{structuralRequired:!0}),exec:n("exec","story-targeted",{structuralRequired:!0}),yolo:n("yolo","story-targeted",{structuralRequired:!0}),"yolo-inline":n("yolo-inline","story-targeted",{structuralRequired:!0}),epic:n("epic","epic-targeted",{structuralRequired:!0}),"setup-branch":n("setup-branch","story-targeted",{structuralRequired:!0}),diagnose:n("diagnose","adaptive-targeted"),"diagnose-inline":n("diagnose-inline","full"),research:n("research","adaptive-targeted"),"research-inline":n("research-inline","full"),"write-spec":n("write-spec","story-targeted",{structuralRequired:!0}),"create-tasks":n("create-tasks","story-targeted",{structuralRequired:!0}),implement:n("implement","story-targeted",{structuralRequired:!0}),commit:n("commit","story-targeted",{structuralRequired:!0}),"commit-push":n("commit","story-targeted",{structuralRequired:!0}),sync:n("sync","story-targeted",{structuralRequired:!0}),"sync-main":n("sync","story-targeted",{structuralRequired:!0}),"create-pr":n("create-pr","story-targeted",{structuralRequired:!0}),review:n("review","story-targeted"),"review-pr":n("review","story-targeted"),merge:n("merge","story-targeted",{structuralRequired:!0}),"merge-pr":n("merge","story-targeted",{structuralRequired:!0}),"fix-blocked":n("fix-blocked","story-targeted"),"finalize-epic":n("finalize-epic","epic-targeted"),"resolve-conflicts":n("resolve-conflicts","story-targeted"),"update-memory":n("update-memory","full"),"update-project-memory":n("update-memory","story-targeted",{structuralRequired:!0}),refactor:n("refactor","adaptive-targeted"),"refactor-suggest":n("refactor","story-targeted",{structuralRequired:!0}),cleanup:n("cleanup","full"),audit:n("audit","full"),"tech-debt":n("tech-debt","full"),menu:n("menu","full"),plans:n("plans","full"),billing:n("billing","full"),subscribe:n("subscribe","full"),"qa-scan":n("qa-scan","full"),yoloop:n("yoloop","yoloop-targeted",{structuralRequired:!0}),"migrate-state":n("migrate-state","full"),"migrate-project-id":n("migrate-project-id","full"),"policy-audit":n("policy-audit","full"),"mutation-test":n("mutation-test","full"),"sync-openapi":n("sync-openapi","full"),"generate-pacts":n("generate-pacts","full"),"verify-pacts":n("verify-pacts","full"),"property-test":n("property-test","full"),"property-tests":n("property-test","story-targeted",{structuralRequired:!0}),"chaos-plan":n("chaos-plan","full"),"ui-ux-review":n("ui-ux-review","adaptive-targeted"),"solyd-system":n("solyd-system","adaptive-targeted"),goal:n("goal","continuity-scoped"),loop:n("loop","continuity-scoped"),jobs:n("jobs","continuity-scoped"),runner:n("runner","continuity-scoped"),"goal-tick":n("goal-tick","continuity-scoped"),"loop-tick":n("loop-tick","continuity-scoped"),"validate-tests":n("validate-tests","story-targeted",{structuralRequired:!0}),"qa-gate":n("qa-gate","story-targeted",{structuralRequired:!0})}),ee=Object.freeze({st:"status",arquitetura:"arch-plan",architecture:"arch-plan",arch:"arch-plan",prd:"arch-prd","product-requirements":"arch-prd","arch-doc":"arch-architecture","tech-architecture":"arch-architecture","api-contracts":"arch-api-contracts","api-contract":"arch-api-contracts","api-integrations":"arch-api-integrations","api-int":"arch-api-integrations","database-schema":"arch-database","db-schema":"arch-database",db:"arch-database","cyber-security":"arch-security",security:"arch-security",sec:"arch-security","design-system":"arch-design-system",ds:"arch-design-system","atomic-design":"arch-design-system","ux-design":"arch-ux-design",ux:"arch-ux-design",wireframes:"arch-ux-design",wireframe:"arch-ux-design","user-flows":"arch-ux-design",performance:"arch-performance",perf:"arch-performance","capacity-planning":"arch-performance",capacity:"arch-performance","arch-perf":"arch-performance","performance-strategy":"arch-performance","testing-strategy":"arch-testing","test-plan":"arch-testing","test-strategy":"arch-testing","arch-test":"arch-testing",infrastructure:"arch-infrastructure",infra:"arch-infrastructure","deploy-plan":"arch-infrastructure",deployment:"arch-infrastructure","arch-infra":"arch-infrastructure","arch-deploy":"arch-infrastructure","review-consolidation":"arch-review",consolidation:"arch-review","architecture-review":"arch-review","arch-consolidation":"arch-review",fitness:"arch-fitness-functions","fitness-functions":"arch-fitness-functions",archfit:"arch-fitness-functions","arch-fit":"arch-fitness-functions","fit-funcs":"arch-fitness-functions","criar-epic":"create-epic",planejamento:"create-epic","idea-diag":"idea-diagnose","idea-pesq":"idea-research","gerar-epic":"generate-epic",executar:"exec",pipeline:"exec","parallel-epic":"epic",setup:"setup-branch",branch:"setup-branch",diag:"diagnose",diagnostico:"diagnose",c02:"diagnose",pesquisar:"research",pesq:"research","research-fix":"research",c03:"research",spec:"write-spec",especificacao:"write-spec",c04:"write-spec",tasks:"create-tasks",tarefas:"create-tasks",c05:"create-tasks",impl:"implement",implementar:"implement",c06:"implement",push:"commit",commit_push:"commit",cp:"commit",c07:"commit",sincronizar:"sync",c08:"sync",pr:"create-pr",c09:"create-pr",revisar:"review",c11:"review",mesclar:"merge",c12:"merge",fix:"fix-blocked",corrigir:"fix-blocked",finalizar:"finalize-epic",conflitos:"resolve-conflicts",memoria:"update-memory",refactoring:"refactor",refact:"refactor",refac:"refactor",rf:"refactor","cleanup-code":"refactor","code-cleanup":"refactor","code-quality":"refactor","improve-code":"refactor",modernize:"refactor",modernization:"refactor",legacy:"refactor","legacy-code":"refactor","debt-pay":"refactor","pay-debt":"refactor","debt-reduction":"refactor","smell-fix":"refactor","fix-smells":"refactor","code-smells":"refactor",strangler:"refactor","strangler-fig":"refactor",limpar:"cleanup",limpeza:"cleanup",auditar:"audit",auditoria:"audit",debt:"tech-debt",debts:"tech-debt","debt-list":"tech-debt","tech-debts":"tech-debt",td:"tech-debt",help:"menu",ajuda:"menu","?":"menu",commands:"menu",cmds:"menu",planos:"plans",pricing:"plans",bill:"billing",subscription:"billing",sub:"billing",upgrade:"subscribe",checkout:"subscribe",qa:"qa-scan","qa-test":"qa-scan","visual-qa":"qa-scan","e2e-scan":"qa-scan",troubleshoot:"qa-scan","debug-ui":"qa-scan",scan:"qa-scan",a11y:"qa-scan",accessibility:"qa-scan",wcag:"qa-scan","auto-yolo":"yoloop","epic-runner":"yoloop","story-runner":"yoloop","loop-yolo":"yoloop","auto-epic":"yoloop",migrate:"migrate-state","state-migrate":"migrate-state","schema-migrate":"migrate-state",policy:"policy-audit","audit-policy":"policy-audit","policy-history":"policy-audit",policies:"policy-audit",mutation:"mutation-test",stryker:"mutation-test","kill-mutants":"mutation-test","openapi-sync":"sync-openapi","api-sync":"sync-openapi","spec-sync":"sync-openapi","regen-openapi":"sync-openapi",pacts:"generate-pacts","gen-pacts":"generate-pacts","regen-pacts":"generate-pacts","create-pacts":"generate-pacts","verify-pact":"verify-pacts","pact-verify":"verify-pacts","check-pacts":"verify-pacts","pact-check":"verify-pacts",property:"property-test",pbt:"property-test",proptest:"property-test","invariant-test":"property-test",chaos:"chaos-plan",gameday:"chaos-plan","resilience-test":"chaos-plan","ux-review":"ui-ux-review","design-review":"ui-ux-review","visual-review":"ui-ux-review","product-polish":"ui-ux-review","security-system":"solyd-system","authorized-security":"solyd-system","sec-system":"solyd-system",goals:"goal","durable-goal":"goal","continuity-goal":"goal",loops:"loop","durable-loop":"loop","continuity-loop":"loop",job:"jobs","continuity-jobs":"jobs","neocortex-runner":"runner","continuity-runner":"runner"}),te=Object.freeze({1:"status",3:"arch-plan",4:"arch-prd",5:"arch-architecture",6:"arch-api-contracts",7:"arch-api-integrations",8:"arch-database",9:"arch-security",10:"arch-design-system",11:"arch-ux-design",12:"arch-performance",13:"arch-testing",14:"arch-infrastructure",15:"arch-review",16:"arch-fitness-functions",17:"create-epic",18:"idea-diagnose",19:"idea-research",20:"generate-epic",21:"exec",22:"yolo",23:"epic",24:"setup-branch",25:"diagnose",26:"research",27:"write-spec",28:"create-tasks",29:"implement",30:"commit",31:"sync",32:"create-pr",33:"review",34:"merge",35:"fix-blocked",36:"finalize-epic",37:"resolve-conflicts",38:"update-memory",39:"refactor",40:"cleanup",41:"audit",42:"tech-debt",43:"menu",44:"plans",45:"billing",46:"subscribe",47:"qa-scan",48:"yoloop",49:"migrate-state",50:"policy-audit",51:"mutation-test",52:"sync-openapi",53:"generate-pacts",54:"verify-pacts",55:"property-test",56:"chaos-plan",57:"ui-ux-review",58:"solyd-system",59:"goal",60:"loop",61:"jobs",62:"runner"});function d(r,e=120){if(typeof r!="string")return;const t=r.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,e)}function w(r,e=120){if(typeof r!="string")return;const t=r.trim(),i=d(r,e);return i===t?i:void 0}function T(r){if(typeof r!="string")return;const e=r.trim();if(!(!e||e.length>240||!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(e)||e.includes("..")||e.includes("//")||e.includes("@{")||e.endsWith("/")||e.endsWith(".")||e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))))return e}function re(r){if(typeof r!="string")return;const e=r.replace(/\\/g,"/");if(!(!e||e.length>240||e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.includes("..")||e.includes("//")||e.split("/").includes(".")||!/^[A-Za-z0-9._/:@#-]+$/.test(e)))return e}function S(r){if(r===void 0||!Array.isArray(r)||r.length>128)return;const e=r.map(re);if(!e.some(t=>t===void 0))return[...new Set(e)].sort((t,i)=>t.localeCompare(i,"en"))}function ie(r){return typeof r=="string"&&X.has(r.trim().toLowerCase().replace(/_/g,"-"))}function v(r,e){const t={};for(const i of e){const c=r[i];typeof c=="string"||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)?t[i]=c:Array.isArray(c)&&c.every(o=>typeof o=="string")&&(t[i]=[...c])}return t}function ce(r,e){const t=e.checkpoint;if(!h(t)||t.schemaVersion!==1||t.storyId!==r||t.epicId!==e.epic_id||!T(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.headSha)||t.baseSha===t.headSha||!w(t.idempotencyKey)||typeof t.recordedAt!="string"||!Number.isFinite(Date.parse(t.recordedAt))||!Array.isArray(t.commits)||t.commits.length===0||t.commits.length>256||t.commits.some(c=>typeof c!="string"||!/^[0-9a-f]{7,64}$/i.test(c))||!Array.isArray(t.receiptRefs)||t.receiptRefs.length===0||t.receiptRefs.length>256||t.receiptRefs.some(c=>typeof c!="string"||c.length>240||c.includes("..")||!/^[A-Za-z0-9._:/#\-[\]]+$/.test(c))||!h(t.qaReceipt)||t.qaReceipt.kind!=="story_qa_evidence"||t.qaReceipt.producer!=="local-yolo-tdd"||!["passed","blocked"].includes(String(t.qaVerdict))||!["approved","changes-requested","pending"].includes(String(t.reviewVerdict))||(t.reviewVerdict==="pending"?t.reviewReceipt!==void 0:!h(t.reviewReceipt)))return;const i=v(t,["schemaVersion","storyId","epicId","branch","baseSha","headSha","idempotencyKey","dispatchId","bundleId","bundleDigest","graphRevision","claimRevision","qaVerdict","reviewVerdict","recordedAt","commits","receiptRefs"]);return i.qaReceipt=v(t.qaReceipt,["schemaVersion","kind","producer","evidenceVersion","storyId","epicId","contract","command","manifestDigest","gateIds","resultDigest","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","verdict","checkedAt","receiptRef"]),h(t.reviewReceipt)&&(i.reviewReceipt=v(t.reviewReceipt,["schemaVersion","kind","producer","storyId","epicId","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","qaReceiptRef","verdict","reviewedAt","receiptRef"])),i}function oe(r,e){const t=e.checkpoint_verification;if(!(!h(t)||t.schemaVersion!==1||t.kind!=="story_checkpoint_physical_verification"||t.producer!=="client-p205-transient-v1"||t.publicSafe!==!0||t.storyId!==r||t.epicId!==e.epic_id||!["verified","rejected"].includes(String(t.verdict))))return v(t,["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","aggregateHeadSha","commitBodyDigest","changedPathsDigest","claimVerification","effectiveClaimRevision","command","manifestDigest","gateIds","resultDigest","graphRevision","executionEvidenceDigest","sourceEvidenceDigest","verifiedAt","verdict","reasonCodes","publicSafe"])}function M(r,e){const t=e.scheduling_checkpoint_evidence,i=new Set(["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"]);if(!(!h(t)||Object.keys(t).some(c=>!i.has(c))||t.schemaVersion!==1||t.kind!=="story_scheduling_checkpoint_evidence"||t.producer!=="client-git-physical-v1"||t.publicSafe!==!0||t.integrationAuthorized!==!1||t.storyId!==r||t.epicId!==e.epic_id||!T(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{40,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{40,64}$/i.test(t.headSha)||typeof t.graphRevision!="string"||!/^[0-9a-f]{64}$/i.test(t.graphRevision)||typeof t.effectiveClaimRevision!="string"||!/^[0-9a-f]{64}$/i.test(t.effectiveClaimRevision)||typeof t.sourceEvidenceDigest!="string"||!/^[0-9a-f]{64}$/i.test(t.sourceEvidenceDigest)||typeof t.verifiedAt!="string"||!Number.isFinite(Date.parse(t.verifiedAt))||!Array.isArray(t.reasonCodes)||t.reasonCodes.length!==1||t.reasonCodes[0]!=="checkpoint-git-scheduling-verified"))return v(t,[...i])}function ne(r,e){const t={...e},i=M(r,e);return i?(t.scheduling_checkpoint_evidence=i,delete t.checkpoint,delete t.checkpoint_verification):delete t.scheduling_checkpoint_evidence,t}function h(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function _(...r){const e=new Set,t=[];for(const i of r)for(const c of i??[]){const o=d(c,80);if(!(!o||e.has(o))&&(e.add(o),t.push(o),t.length>=J))return t}return t}function se(r){return r.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function ae(r){return r.trim().split(/\s+/,1)[0]??""}function z(r){if(/^@epic-P[0-9]{1,12}$/.test(r.trim()))return A.epic;const e=ae(r);if(!e)return A.menu;const t=se(e),i=te[t]??ee[t]??t;return A[i]??null}function de(r,e,t,i="full-compatible",c=["full-state"]){return{kind:"full",commandId:t?.commandId??null,stateProjectionPolicy:t?.stateProjectionPolicy??null,projectionMode:i,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(e.stories).length,includedEpicCount:Object.keys(e.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",reasonCodes:_(c)}}function Le(r,e,t,i="full-compatible",c=["full-state"]){const o=de(r,e,t,i,c);return I({...e,scope:o},e,o)}function ue(r){const[e]=r.trim().split(/\s+/,1);return e?/^[A-Z]?\d+(?:\.\d+)+$/i.test(e.replace(/^@/,""))||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(e.replace(/^@/,"")):!1}function F(r){const e=r.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return e?.[1]?e[1]:r.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function le(r){const e=r.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function q(r){return le(r).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function $e(r){return q(r)[0]??null}function P(r,e){const i=r.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),c=[i,i.toUpperCase(),/^p\d+$/i.test(i)?`P${i.replace(/^p/i,"")}`:null,/^\d+$/.test(i)?`P${i}`:null].filter(o=>typeof o=="string"&&o.length>0);for(const o of c)if(e.epics[o])return o;return null}function pe(r,e){const t=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?P(t[1],e):null}function R(r,e){const t=r.trim().match(/^@epic-(P[0-9]{1,12})$/);if(t)return P(t[1],e);const i=pe(r,e);if(i)return i;for(const c of q(r)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(c))continue;const o=P(c,e);if(o)return o}return null}function fe(r,e){const t=R(r,e);if(t)return t;const i=e.yoloop,c=i?.state?.currentSession?.currentEpicId;if(typeof c=="string"&&e.epics[c])return c;const o=i?.lock?.currentEpicId??i?.lock?.epicId;return typeof o=="string"&&e.epics[o]?o:null}function ye(r){const e=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];if(e)return/^P/i.test(e)?e.toUpperCase():`P${e}`;for(const t of q(r)){if(/^P\d+$/i.test(t))return t.toUpperCase();if(/^\d+$/.test(t))return`P${t}`}return null}function j(r,e){if(typeof r.epic_id=="string"&&r.epic_id.length>0)return r.epic_id;const t=e.split(".").slice(0,-1).join(".");return t.length>0?t:null}function L(r){return typeof r=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(r.toLowerCase())}function x(r,e,t){if(t.has(r))return;const i=e.stories[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const o of c)typeof o=="string"&&x(o,e,t)}function me(r,e){const t=C(e.stories,[r]),i={};for(const c of t.orderedIds){const o=e.stories[c];o&&(i[c]=o)}return i}function $(r,e,t=[]){const i={};for(const c of t)e.epics[c]&&(i[c]=e.epics[c]);for(const[c,o]of Object.entries(r)){const s=j(o,c);s&&e.epics[s]&&(i[s]=e.epics[s])}return i}function ge(r,e,t){if(t.has(r))return;const i=e.epics[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const o of c)typeof o=="string"&&o.length>0&&ge(o,e,t)}function V(r,e,t){const i=C(t.epics,[r]),c=new Set(i.orderedIds);for(const[s,a]of Object.entries(e)){const u=j(a,s);u&&t.epics[u]&&c.add(u)}const o={};for(const s of[...c].sort((a,u)=>a.localeCompare(u,"en"))){const a=t.epics[s];a&&(o[s]=s===r?a:H(s,a))}return o}function G(r,e,t){const i=e.stories;if(!Array.isArray(i)||i.some(s=>typeof s!="string"||s.length===0))throw new y("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedStoryMemberships:1});const c=C(t.stories,i),o={};for(const s of c.orderedIds){const a=t.stories[s];a&&(o[s]=j(a,s)===r?ne(s,a):Y(s,a))}return o}function he(r,e,t){const i=[...e.stories].sort((s,a)=>s.localeCompare(a,"en")),c=Object.entries(t).filter(([s,a])=>j(a,s)===r).map(([s])=>s).sort((s,a)=>s.localeCompare(a,"en")),o=W("sha256").update(`target-epic-coverage-v1\0${JSON.stringify({targetEpicId:r,declaredStoryIds:i,includedStoryIds:c})}`).digest("hex");return{schemaVersion:"TargetEpicCoverage/1.0",targetEpicId:r,declaredStoryIds:i,includedStoryIds:c,membershipSha256:o,publicSafe:!0}}function Y(r,e){const t=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(m=>typeof m=="string"&&m.length>0))].sort((m,E)=>m.localeCompare(E,"en")):void 0,i={id:d(e.id)??r,...d(e.epic_id)?{epic_id:d(e.epic_id)}:{},...d(e.status,40)?{status:d(e.status,40)}:{},...t?{depends_on:t}:{},...h(e.supersededBy)?{supersededBy:e.supersededBy}:{}},c=M(r,e);if(!ie(e.status))return{...i,...c?{scheduling_checkpoint_evidence:c}:{}};const o=e.source==="create-epic"||e.source==="discovered"?e.source:void 0,s=T(e.branch_name),a=w(e.last_step,120),u=Array.isArray(e.steps_completed)&&e.steps_completed.length<=64?e.steps_completed.map(m=>w(m,120)):[],l=u.length>0&&u.every(m=>m!==void 0)?u:void 0,f=typeof e.pr_number=="number"&&Number.isSafeInteger(e.pr_number)&&e.pr_number>0?e.pr_number:void 0,p=ce(r,e),g=p?oe(r,e):void 0;return{...i,...o?{source:o}:{},...s?{branch_name:s}:{},...a?{last_step:a}:{},...l?{steps_completed:l}:{},...f?{pr_number:f}:{},...p?{checkpoint:p}:{},...g?{checkpoint_verification:g}:{},...c?{scheduling_checkpoint_evidence:c}:{},...S(e.files_to_modify)!==void 0?{files_to_modify:S(e.files_to_modify)}:{},...S(e.contracts)!==void 0?{contracts:S(e.contracts)}:{},...S(e.contract_refs)!==void 0?{contract_refs:S(e.contract_refs)}:{},...S(e.shared_surfaces)!==void 0?{shared_surfaces:S(e.shared_surfaces)}:{}}}function H(r,e){const t=Array.isArray(e.stories)?[...new Set(e.stories.filter(c=>typeof c=="string"&&c.length>0))].sort((c,o)=>c.localeCompare(o,"en")):[],i=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(c=>typeof c=="string"&&c.length>0))].sort((c,o)=>c.localeCompare(o,"en")):[];return{id:d(e.id)??r,...d(e.status,40)?{status:d(e.status,40)}:{},...d(e.lifecycle_classification,40)?{lifecycle_classification:d(e.lifecycle_classification,40)}:{},stories:t,depends_on:i}}function be(r,e,t){const i=C(e.stories),c=C(e.epics),o=Object.fromEntries(i.orderedIds.map(u=>[u,Y(u,e.stories[u])])),s=Object.fromEntries(c.orderedIds.map(u=>[u,H(u,e.epics[u])])),a={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"yoloop-discovery",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:i.orderedIds.length,includedEpicCount:c.orderedIds.length,omittedStoryCount:0,omittedEpicCount:0,reason:"targeted-invocation",reasonCodes:_(["structural-required","yoloop-discovery",`structural-edges-${i.edgeCount+c.edgeCount}`,"content-fields-omitted"])};return I({...e,stories:o,epics:s,scope:a},e,a)}function _e(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const o of i)typeof o=="string"&&x(o,e,t);const c={};for(const o of t){const s=e.stories[o];s&&(c[o]=s)}return c}function Se(r){const e={};for(const[t,i]of Object.entries(r.epics))e[t]={id:d(i.id)??t,...d(i.status)?{status:d(i.status)}:{},...k.includes(i.lifecycle_classification)?{lifecycle_classification:i.lifecycle_classification}:{},...typeof i.total_stories=="number"&&Number.isFinite(i.total_stories)?{total_stories:i.total_stories}:{},...typeof i.completed_stories=="number"&&Number.isFinite(i.completed_stories)?{completed_stories:i.completed_stories}:{}};return e}function K(r){const e={};for(const t of Object.values(r)){const i=d(t.status,40)??"unknown";e[i]=(e[i]??0)+1}return e}function je(r){const e=Object.fromEntries(k.map(t=>[t,0]));for(const t of Object.values(r)){const i=k.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[i]=(e[i]??0)+1}return e}function N(r,e){if(!e)return!0;const t=r.epics[e];return t?!k.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function Z(r){for(const e of["last_updated","updated_at","completed_at","created_at","discovered_at"]){const t=r[e];if(typeof t!="string")continue;const i=Date.parse(t);if(Number.isFinite(i))return i}return 0}function Ie(r){return Object.entries(r.stories).map(([e,t])=>({id:e,story:t,timestamp:Z(t)})).sort((e,t)=>t.timestamp-e.timestamp||e.id.localeCompare(t.id)).slice(0,U).map(({id:e,story:t})=>({id:e,...d(t.epic_id)?{epicId:d(t.epic_id)}:{},...d(t.status,40)?{status:d(t.status,40)}:{},...d(t.last_step??t.lastStep)?{lastStep:d(t.last_step??t.lastStep)}:{},...d(t.last_updated??t.updated_at??t.completed_at??t.created_at)?{lastUpdated:d(t.last_updated??t.updated_at??t.completed_at??t.created_at)}:{}}))}function Ce(r){const e=r.current_session;if(!e)return;const t={activeEpicId:d(e.active_epic_id)??null,activeStoryId:d(e.active_story_id)??null,activeStepId:d(e.active_step_id)??null,sessionId:d(e.session_id)??null,startedAt:d(e.started_at)??null};return Object.values(t).some(i=>i!=null)?t:void 0}function ke(r){const e=r.yoloop;if(!h(e))return;const t=h(e.state)?e.state:void 0,i=h(t?.currentSession)?t.currentSession:void 0,c=h(e.lock)?e.lock:void 0,o={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:d(i?.currentEpicId??e.currentEpicId)??null,currentStoryId:d(i?.currentStoryId??e.currentStoryId)??null,sessionId:d(i?.sessionId??e.sessionId)??null,lockEpicId:d(c?.currentEpicId??c?.epicId)??null};return Object.keys(o).length>0?o:void 0}function ve(r){const e=r.continuity;if(!h(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(i=>typeof i=="string"):void 0;return{present:!0,activeJobId:d(e.activeJobId??e.jobId)??null,activeGoalId:d(e.activeGoalId??e.goalId)??null,activeLoopId:d(e.activeLoopId??e.loopId)??null,...t&&t.length>0?{reasonCodes:_(t)}:{}}}function Ee(r,e,t){const i=d(e?.activeStoryId),c=d(e?.activeEpicId),o=d(e?.activeStepId),s=i&&r.stories[i]?j(r.stories[i],i):null;if((i||c||o)&&N(r,c??s))return{epicId:c??null,storyId:i??null,stepId:o??null};const a=d(t?.currentStoryId),u=d(t?.currentEpicId??t?.lockEpicId);if((a||u)&&N(r,u))return{epicId:u??null,storyId:a??null,stepId:null};const l=Object.entries(r.stories).map(([f,p])=>({id:f,story:p,timestamp:Z(p)})).filter(({id:f,story:p})=>!L(p.status)&&N(r,j(p,f))).sort((f,p)=>p.timestamp-f.timestamp||f.id.localeCompare(p.id))[0];return l?{epicId:j(l.story,l.id),storyId:l.id,stepId:d(l.story.last_step??l.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function Re(r,e){const t=K(r.stories),i=K(r.epics),c=je(r.epics),o=Object.values(r.epics).filter(g=>(k.includes(g.lifecycle_classification)?g.lifecycle_classification:"active")==="active"&&!L(g.status)).length,s=Ce(r),a=ke(r),u=ve(r),l=Ee(r,s,a),f=Ie(r),p=_(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",f.length>=U?"recent-stories-capped":"recent-stories-bounded",l.storyId||l.epicId?"active-ref-derived":"active-ref-empty",a?"yoloop-session-present":"yoloop-session-absent",u?"continuity-session-present":"continuity-session-absent"]);return{schemaVersion:1,totals:{stories:Object.keys(r.stories).length,epics:Object.keys(r.epics).length,storyStatus:t,epicStatus:i,epicLifecycle:c,activeEpics:o,blockedStories:t.blocked??0},active:l,blockedCount:t.blocked??0,recentStories:f,...s?{currentSession:s}:{},...a?{currentYoloopSession:a}:{},...u?{currentContinuitySession:u}:{},projection:{commandId:e.commandId??null,stateProjectionPolicy:e.stateProjectionPolicy??null,projectionMode:e.projectionMode,scopeKind:e.kind,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??Object.keys(r.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:p,publicSafe:!0}}function I(r,e,t){return{...r,stateSummary:Re(e,t)}}function Oe(r,e,t){const i={};for(const o of Object.keys(e.epics))i[o]={id:o};const c={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"summary-only",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(i).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:0,reason:"epic-summary",reasonCodes:["epic-summary","stories-omitted","epic-stubs-only"]};return I({...e,stories:{},epics:i,scope:c},e,c)}function b(r,e,t,i=["summary-only","stories-omitted"],c="summary-only"){const o=Se(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(o).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(o).length),reason:"summary-only",reasonCodes:_(i)};return I({...e,stories:{},epics:o,scope:s},e,s)}function D(r,e,t,i,c,o){const s=e.stories[i];if(!s)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"});const a=j(s,i);if(!a)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=e.epics[a];if(!u)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const l=c==="yolo-story",f=l?G(a,u,e):me(i,e),p=l?V(a,f,e):$(f,e);if(!f[i]||!p[a])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(f).length,epics:Object.keys(p).length,targetKind:"story"});const g={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:a,targetStoryId:i,includedStoryCount:Object.keys(f).length,includedEpicCount:Object.keys(p).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(f).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(p).length),reason:"targeted-invocation",reasonCodes:_(o,l?["epic-graph-authority-complete"]:[])};return I({...e,stories:f,epics:p,scope:g},e,g)}function B(r,e,t,i,c,o){const s=e.epics[i];if(!s)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=_e(s,e),u=$(a,e,[i]);if(!u[i])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(a).length,epics:Object.keys(u).length,targetKind:"epic"});const l={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:i,targetStoryId:null,includedStoryCount:Object.keys(a).length,includedEpicCount:Object.keys(u).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(a).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(u).length),reason:"targeted-invocation",reasonCodes:_(o)};return I({...e,stories:a,epics:u,scope:l},e,l)}function Ae(r,e,t){const i=ye(r),c=R(r,e);if(i&&!c)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const o=fe(r,e),s=O({commandId:t.commandId,explicitYoloopEpicId:c,sessionYoloopEpicId:c?null:o});if(s==="yoloop-discovery")return be(r,e,t);if(!o||s!=="yoloop-target"&&s!=="yoloop-session")throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=e.epics[o];if(!a)throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=G(o,a,e),l=V(o,u,e);if(!l[o])throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(u).length,epics:Object.keys(l).length,targetKind:"epic"});const f=s,p={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:f,trigger:r,targetEpicId:o,targetStoryId:null,targetEpicCoverage:he(o,a,u),includedStoryCount:Object.keys(u).length,includedEpicCount:Object.keys(l).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(u).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(l).length),reason:"targeted-invocation",reasonCodes:["structural-required",f,"yoloop-targeted"]};return I({...e,stories:u,epics:l,scope:p},e,p)}function we(r,e){const t={};for(const[i,c]of Object.entries(r.epics)){const o=Array.isArray(c.stories)?c.stories.filter(s=>typeof s=="string"&&e.has(s)):[];t[i]={id:d(c.id)??i,...d(c.status,40)?{status:d(c.status,40)}:{},...typeof c.total_stories=="number"&&Number.isFinite(c.total_stories)?{total_stories:c.total_stories}:{},...typeof c.completed_stories=="number"&&Number.isFinite(c.completed_stories)?{completed_stories:c.completed_stories}:{},...o.length>0?{stories:o}:{},...o.length>0&&Array.isArray(c.depends_on)?{depends_on:c.depends_on.filter(s=>typeof s=="string"&&s.length>0)}:{},...o.length>0&&(c.branch_mode==="epic"||c.branch_mode==="story")?{branch_mode:c.branch_mode}:{},...o.length>0&&typeof c.execution_branch=="string"?{execution_branch:c.execution_branch}:{},...o.length>0&&typeof c.origin_branch=="string"?{origin_branch:c.origin_branch}:{},...o.length>0&&(c.branch_lease===null||typeof c.branch_lease=="object")?{branch_lease:c.branch_lease}:{},...o.length>0&&(c.origin_binding===null||typeof c.origin_binding=="object")?{origin_binding:c.origin_binding}:{},...o.length>0&&(c.aggregate_qa_receipt===null||typeof c.aggregate_qa_receipt=="object")?{aggregate_qa_receipt:c.aggregate_qa_receipt}:{},...o.length>0&&(c.head_reconciliation_receipt===null||typeof c.head_reconciliation_receipt=="object")?{head_reconciliation_receipt:c.head_reconciliation_receipt}:{},...o.length>0&&c.story_worktree_evidence!==null&&typeof c.story_worktree_evidence=="object"?{story_worktree_evidence:c.story_worktree_evidence}:{},...o.length>0&&Array.isArray(c.story_worktree_leases)&&c.story_worktree_leases.length>0?{story_worktree_leases:c.story_worktree_leases}:{},...o.length>0&&c.branch_mode_conversion_receipt!==null&&typeof c.branch_mode_conversion_receipt=="object"&&!Array.isArray(c.branch_mode_conversion_receipt)?{branch_mode_conversion_receipt:c.branch_mode_conversion_receipt}:{}}}return t}function Te(r){return r.stateSummary?.totals.stories??(r.scope?.includedStoryCount??Object.keys(r.stories).length)+(r.scope?.omittedStoryCount??0)}function qe(r){return r.stateSummary?.totals.epics??(r.scope?.includedEpicCount??Object.keys(r.epics).length)+(r.scope?.omittedEpicCount??0)}function Pe(r,e){if(r.stateSummary)return{...r.stateSummary,projection:{...r.stateSummary.projection,scopeKind:"projected",projectionMode:e.projectionMode,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??r.stateSummary.projection.includedEpicCount,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:"body-size"},reasonCodes:_(r.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function Ve(r){const e=r.scope,t=new Set,i=e?.projectionMode==="structural-required"||e?.projectionMode==="yolo-story"||e?.projectionMode==="yoloop-target"||e?.projectionMode==="yoloop-session"||e?.projectionMode==="yoloop-discovery";if(i)for(const m of Object.keys(r.stories))t.add(m);else e?.targetStoryId&&x(e.targetStoryId,r,t);const c={};for(const m of t){const E=r.stories[m];E&&(c[m]=E)}const o=we(r,t),s=Object.keys(c).length,a=Object.keys(o).length,u=Math.max(0,Te(r)-s),l=Math.max(0,qe(r)-a),f=i?e?.projectionMode??"structural-required":e?.projectionMode==="yolo-story"?"yolo-story":"summary-only",p={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:f,targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,...e?.targetEpicCoverage?{targetEpicCoverage:e.targetEpicCoverage}:{},includedStoryCount:s,includedEpicCount:a,omittedStoryCount:u,omittedEpicCount:l,reason:"body-size",reasonCodes:_(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved","redundant-trigger-omitted"])},g=Pe(r,p);return{...r,stories:c,epics:o,scope:p,...g?{stateSummary:g}:{}}}function xe(r,e){const t=r.trim(),i=z(t);try{if(!i){if(ue(t)){const o=n("story-reference","story-targeted"),s=F(t);if(s)return D(t,e,o,s,"targeted-story",["story-reference-targeted"])}return b(t,e,n("unknown","adaptive-targeted"),["unknown-command-summary-only"])}if(i.stateProjectionPolicy==="epic-summary")return Oe(t,e,i);if(i.stateProjectionPolicy==="yoloop-targeted")return Ae(t,e,i);const c=F(t);if(i.stateProjectionPolicy==="story-targeted"){if(c){const s=O({commandId:i.commandId,targetStoryId:c})==="yolo-story";return D(t,e,i,c,s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story",[s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story"])}if(i.commandId==="yolo"||i.commandId==="yolo-inline"){const o=O({commandId:i.commandId});return b(t,e,i,["yolo-inline","stories-omitted","historical-content-omitted"],o??"yolo-inline")}return i.commandId==="commit"&&/^\*?(?:commit|commit-push)$/i.test(t)?b(t,e,i,["working-tree-commit","stories-omitted","historical-content-omitted"]):i.structuralRequired?(()=>{throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"})})():b(t,e,i,["story-target-missing-summary-only"])}if(i.stateProjectionPolicy==="adaptive-targeted"){if(c&&e.stories[c])return D(t,e,i,c,"targeted-story",["adaptive-story-targeted"]);const o=R(t,e);return o?B(t,e,i,o,"targeted-epic",["adaptive-epic-targeted"]):b(t,e,i,["adaptive-summary-only","target-unresolved-summary-only"])}if(i.stateProjectionPolicy==="epic-targeted"){if(i.commandId.startsWith("arch-")&&/(?:^|\s)epic-arch\s*$/i.test(t)&&e.archPlan?.execution?.currentStageCommand===i.commandId)return b(t,e,i,["architecture-root-delegated"]);const o=R(t,e);return o?B(t,e,i,o,i.structuralRequired?"structural-required":"targeted-epic",[i.structuralRequired?"structural-required":"targeted-epic"]):i.structuralRequired?(()=>{throw new y("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"})})():b(t,e,i,["epic-target-missing-summary-only"])}return i.stateProjectionPolicy==="continuity-scoped"?b(t,e,i,["continuity-scoped-summary-only"]):b(t,e,i,["policy-full-summary-only"])}catch(c){if(c instanceof y)throw c;if(i?.structuralRequired)throw new y("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,projectionErrors:1});return b(t,e,i??n("unknown","adaptive-targeted"),["projection-error-summary-only"])}}const Ne=new Set(["yolo-story","yolo-inline","yoloop-target","yoloop-session","yoloop-discovery"]);function De(r){let e=0;for(const t of[r.stories,r.epics])for(const i of Object.values(t))Array.isArray(i.depends_on)&&(e+=i.depends_on.filter(c=>typeof c=="string").length);return e}function Ge(r,e){const t=z(r.trim());if(!t||!["yolo","yolo-inline","yoloop"].includes(t.commandId))return null;try{const i=xe(r,e),c=i.scope?.projectionMode;if(!c||!Ne.has(c))throw new y("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(i.stories).length,epics:Object.keys(i.epics).length,projectionShapeErrors:1});return Object.freeze({ok:!0,version:2,shape:c,snapshot:i,included:{epics:i.scope?.includedEpicCount??Object.keys(i.epics).length,stories:i.scope?.includedStoryCount??Object.keys(i.stories).length,edges:De(i)},omitted:{epics:i.scope?.omittedEpicCount??0,stories:i.scope?.omittedStoryCount??0},cycleCount:0})}catch(i){if(!(i instanceof y))throw i;return Object.freeze({ok:!1,code:i.code,publicDetails:{...i.publicDetails,...i.code==="STRUCTURAL_CONTEXT_TOO_LARGE"?{}:{planningCause:Q(i.code)}}})}}export{Ve as degradeStateSnapshotForPayloadLimit,Q as planningProjectionCauseForStructuralCode,Fe as projectEpicOperationalEvidenceForRequest,xe as projectStateSnapshotForInvoke,Ge as projectStateSnapshotResultV2ForInvoke};
|
|
@@ -24,9 +24,12 @@ neocortex install --local
|
|
|
24
24
|
`isolation: "worktree"` only when the server plan is v4 with that mechanism;
|
|
25
25
|
phase-2 children run without `isolation` in the already adopted worktree.
|
|
26
26
|
- Each child registers its worktree with `neocortex-client story-worktree adopt`;
|
|
27
|
-
adopt fails closed on a base mismatch or a dirty checkout.
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
adopt fails closed on a base mismatch or a dirty checkout.
|
|
28
|
+
- The installer and `neocortex` refresh set `worktree.baseRef: "head"` in
|
|
29
|
+
`~/.claude/settings.json` when it is absent (never overwriting a value you
|
|
30
|
+
chose), so native worktrees start from the epic checkout instead of the
|
|
31
|
+
remote default branch. `neocortex-client doctor` reports
|
|
32
|
+
`claude-worktree-baseref-not-head` otherwise, and `*yoloop` applies it.
|
|
30
33
|
- Cleanup is always `neocortex-client`; the harness branch is preserved. A
|
|
31
34
|
worktree the harness removed on its own (no changes) is reconciled by the
|
|
32
35
|
client orphan recovery (`neocortex-client story-worktree recover`).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex Root Agent v4.
|
|
3
|
+
description: "🧠 Neocortex Root Agent v4.65.0 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
tools:
|
|
@@ -108,7 +108,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
108
108
|
┌────────────────────────────────────────────────────────────┐
|
|
109
109
|
│ │
|
|
110
110
|
│ ####### N E O C O R T E X │
|
|
111
|
-
│ ### ######## v4.
|
|
111
|
+
│ ### ######## v4.65.0 │
|
|
112
112
|
│ ######### ##### │
|
|
113
113
|
│ ## ############## Development Orchestrator │
|
|
114
114
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.
|
|
3
|
+
description: "🧠 Neocortex v4.65.0 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
permissionMode: bypassPermissions
|
|
@@ -106,7 +106,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
106
106
|
┌────────────────────────────────────────────────────────────┐
|
|
107
107
|
│ │
|
|
108
108
|
│ ####### N E O C O R T E X │
|
|
109
|
-
│ ### ######## v4.
|
|
109
|
+
│ ### ######## v4.65.0 │
|
|
110
110
|
│ ######### ##### │
|
|
111
111
|
│ ## ############## Development Orchestrator │
|
|
112
112
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -32,7 +32,7 @@ Codex built-in commands or actions.
|
|
|
32
32
|
|
|
33
33
|
<!-- END: Plugin Conflict Prevention -->
|
|
34
34
|
|
|
35
|
-
# Neocortex v4.
|
|
35
|
+
# Neocortex v4.65.0 | OrNexus Team
|
|
36
36
|
|
|
37
37
|
You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
|
|
38
38
|
|