@ornexus/neocortex 4.62.0 → 4.64.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1193 -1193
- package/install.ps1 +1 -1
- package/install.sh +28 -5
- package/package.json +3 -4
- package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/commands/invoke.d.ts +7 -0
- package/packages/client/dist/commands/invoke.js +50 -50
- package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
- package/packages/client/dist/commands/refresh-memory.js +5 -3
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +86 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -3
- package/packages/client/dist/git/git-lifecycle-store.d.ts +30 -2
- package/packages/client/dist/git/git-lifecycle-store.js +7 -7
- package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
- package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
- package/packages/client/dist/git/release-gate-env.d.ts +2 -41
- package/packages/client/dist/git/release-gate-env.js +1 -1
- package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
- package/packages/client/dist/git/state-json-field-merge.js +2 -0
- package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
- package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
- package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
- package/packages/client/dist/git/story-worktree-manager.js +3 -3
- package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
- package/packages/client/dist/git/story-worktree-paths.js +1 -1
- package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
- package/packages/client/dist/git/story-write-set-extension.js +1 -1
- package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +30 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -8
- package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
- package/packages/client/dist/runner/headless/run-yolo.js +1 -1
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
- package/packages/client/dist/runner/headless/types.d.ts +9 -1
- package/packages/client/dist/runner/headless/types.js +2 -2
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/state/state-json-repair.d.ts +23 -0
- package/packages/client/dist/state/state-json-repair.js +4 -3
- package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
- package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
- package/packages/client/dist/yoloop/discovery-hook.js +2 -2
- package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
- package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
- package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
- package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
- package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
- package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
- package/packages/client/dist/yoloop/shared-discover-epics.d.ts +46 -1
- package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +94 -0
- package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
- package/packages/shared/dist/compatibility/index.js +6 -0
- package/packages/shared/dist/project-manifest-projection.js +6 -3
- package/packages/shared/dist/release-gate-env-contract.js +129 -0
- package/packages/shared/dist/yoloop/branch-unit.js +119 -3
- package/packages/shared/dist/yoloop/epic-terminal-git.js +4 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/install-codex.sh +12 -4
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/lib/managed-config-merge.js +385 -7
- package/targets-stubs/lib/managed-profile.sh +47 -7
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,41 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
3
|
-
export declare const RELEASE_GATE_ENV_CONTRACT_MAX_BYTES: number;
|
|
4
|
-
export declare const RELEASE_GATE_ENV_MAX_NAMES_PER_LIST = 64;
|
|
5
|
-
export declare const RELEASE_GATE_ENV_NAME_PATTERN: RegExp;
|
|
6
|
-
export declare const RELEASE_GATE_MINIMAL_ENV: readonly string[];
|
|
7
|
-
export declare const P205_GATE_ENV_CONTRACT_INVALID: "p205-gate-env-contract-invalid";
|
|
8
|
-
export declare const P205_GATE_ENV_CONTRACT_UNDECLARED: "p205-gate-env-contract-undeclared";
|
|
9
|
-
export declare const P205_DATASOURCE_MISSING_PREFIX: "p205-datasource-missing:";
|
|
10
|
-
export type P205DatasourceMissingReason = `${typeof P205_DATASOURCE_MISSING_PREFIX}${string}`;
|
|
11
|
-
export interface ReleaseGateEnvContract {
|
|
12
|
-
readonly schemaVersion: 1;
|
|
13
|
-
readonly contract: typeof RELEASE_GATE_ENV_CONTRACT_ID;
|
|
14
|
-
readonly required: readonly string[];
|
|
15
|
-
readonly optional: readonly string[];
|
|
16
|
-
}
|
|
17
|
-
export type ReleaseGateEnvContractValidation = {
|
|
18
|
-
readonly ok: true;
|
|
19
|
-
readonly contract: ReleaseGateEnvContract;
|
|
20
|
-
} | {
|
|
21
|
-
readonly ok: false;
|
|
22
|
-
readonly reason: typeof P205_GATE_ENV_CONTRACT_INVALID;
|
|
23
|
-
};
|
|
24
|
-
export type ReleaseGateEnvProjection = {
|
|
25
|
-
readonly ok: true;
|
|
26
|
-
readonly env: Readonly<Record<string, string>>;
|
|
27
|
-
readonly forwardedNames: readonly string[];
|
|
28
|
-
readonly debt: readonly (typeof P205_GATE_ENV_CONTRACT_UNDECLARED)[];
|
|
29
|
-
} | {
|
|
30
|
-
readonly ok: false;
|
|
31
|
-
readonly reason: P205DatasourceMissingReason;
|
|
32
|
-
readonly missing: readonly string[];
|
|
33
|
-
};
|
|
34
|
-
export interface ProjectReleaseGateEnvInput {
|
|
35
|
-
readonly contract: ReleaseGateEnvContract | null;
|
|
36
|
-
readonly parentEnv: Readonly<Record<string, string | undefined>>;
|
|
37
|
-
readonly platform: string;
|
|
38
|
-
}
|
|
1
|
+
import { P205_GATE_ENV_CONTRACT_INVALID, type ReleaseGateEnvContract, type ReleaseGateEnvProjection } from '../../../shared/dist/release-gate-env-contract.js';
|
|
2
|
+
export { P205_DATASOURCE_MISSING_PREFIX, P205_GATE_ENV_CONTRACT_INVALID, P205_GATE_ENV_CONTRACT_UNDECLARED, RELEASE_GATE_ENV_CONTRACT_ID, RELEASE_GATE_ENV_CONTRACT_MAX_BYTES, RELEASE_GATE_ENV_CONTRACT_PATH, RELEASE_GATE_ENV_MAX_NAMES_PER_LIST, RELEASE_GATE_ENV_NAME_PATTERN, RELEASE_GATE_MINIMAL_ENV, parseReleaseGateEnvContract, projectReleaseGateEnv, validateReleaseGateEnvContract, type P205DatasourceMissingReason, type ProjectReleaseGateEnvInput, type ReleaseGateEnvContract, type ReleaseGateEnvContractValidation, type ReleaseGateEnvProjection, } from '../../../shared/dist/release-gate-env-contract.js';
|
|
39
3
|
export type ReleaseGateEnvContractRead = {
|
|
40
4
|
readonly kind: 'absent';
|
|
41
5
|
} | {
|
|
@@ -49,9 +13,6 @@ export type ResolvedReleaseGateEnv = ReleaseGateEnvProjection | {
|
|
|
49
13
|
readonly ok: false;
|
|
50
14
|
readonly reason: typeof P205_GATE_ENV_CONTRACT_INVALID;
|
|
51
15
|
};
|
|
52
|
-
export declare function validateReleaseGateEnvContract(value: unknown): ReleaseGateEnvContractValidation;
|
|
53
|
-
export declare function parseReleaseGateEnvContract(text: string): ReleaseGateEnvContractValidation;
|
|
54
|
-
export declare function projectReleaseGateEnv(input: ProjectReleaseGateEnvInput): ReleaseGateEnvProjection;
|
|
55
16
|
/**
|
|
56
17
|
* Reads `config/release-gates.env.v1.json` under `projectRoot` with a fixed
|
|
57
18
|
* relative path. Absent -> `absent`; symlink, non-regular file, oversize,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{closeSync as N,constants as
|
|
1
|
+
import{closeSync as N,constants as i,fstatSync as R,lstatSync as f,openSync as C,readSync as O}from"node:fs";import{join as u}from"node:path";import{P205_GATE_ENV_CONTRACT_INVALID as T,RELEASE_GATE_ENV_CONTRACT_MAX_BYTES as o,RELEASE_GATE_ENV_CONTRACT_PATH as S,parseReleaseGateEnvContract as d,projectReleaseGateEnv as G}from"../../../shared/dist/release-gate-env-contract.js";import{P205_DATASOURCE_MISSING_PREFIX as D,P205_GATE_ENV_CONTRACT_INVALID as m,P205_GATE_ENV_CONTRACT_UNDECLARED as P,RELEASE_GATE_ENV_CONTRACT_ID as h,RELEASE_GATE_ENV_CONTRACT_MAX_BYTES as j,RELEASE_GATE_ENV_CONTRACT_PATH as M,RELEASE_GATE_ENV_MAX_NAMES_PER_LIST as z,RELEASE_GATE_ENV_NAME_PATTERN as x,RELEASE_GATE_MINIMAL_ENV as F,parseReleaseGateEnvContract as X,projectReleaseGateEnv as B,validateReleaseGateEnvContract as Y}from"../../../shared/dist/release-gate-env-contract.js";const p=Object.freeze({ok:!1,reason:T});function l(E){const e=E?.code;return e==="ENOENT"||e==="ENOTDIR"}function L(E){const e=Object.freeze({kind:"invalid",reason:T}),a=u(E,...S.split("/"));try{const t=f(a);if(t.isSymbolicLink()||!t.isFile()||t.size>o)return e}catch(t){return l(t)?Object.freeze({kind:"absent"}):e}let r;try{r=C(a,i.O_RDONLY|(i.O_NOFOLLOW??0))}catch(t){return l(t)?Object.freeze({kind:"absent"}):e}try{const t=R(r);if(!t.isFile()||t.size>o)return e;const c=Buffer.alloc(o+1);let n=0;for(;n<c.length;){const A=O(r,c,n,c.length-n,n);if(A===0)break;n+=A}if(n>o)return e;let _;try{_=new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,n))}catch{return e}const s=d(_);return s.ok?Object.freeze({kind:"present",contract:s.contract}):e}catch{return e}finally{N(r)}}function b(E,e=process.env,a=process.platform){const r=L(E);return r.kind==="invalid"?p:G({contract:r.kind==="present"?r.contract:null,parentEnv:e,platform:a})}export{D as P205_DATASOURCE_MISSING_PREFIX,m as P205_GATE_ENV_CONTRACT_INVALID,P as P205_GATE_ENV_CONTRACT_UNDECLARED,h as RELEASE_GATE_ENV_CONTRACT_ID,j as RELEASE_GATE_ENV_CONTRACT_MAX_BYTES,M as RELEASE_GATE_ENV_CONTRACT_PATH,z as RELEASE_GATE_ENV_MAX_NAMES_PER_LIST,x as RELEASE_GATE_ENV_NAME_PATTERN,F as RELEASE_GATE_MINIMAL_ENV,X as parseReleaseGateEnvContract,B as projectReleaseGateEnv,L as readReleaseGateEnvContract,b as resolveReleaseGateEnv,Y as validateReleaseGateEnvContract};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license FSL-1.1
|
|
3
|
+
* Copyright (c) 2026 OrNexus AI
|
|
4
|
+
*
|
|
5
|
+
* This file is part of Neocortex CLI, licensed under the
|
|
6
|
+
* Functional Source License, Version 1.1 (FSL-1.1).
|
|
7
|
+
*
|
|
8
|
+
* Change Date: February 20, 2029
|
|
9
|
+
* Change License: MIT
|
|
10
|
+
*
|
|
11
|
+
* See the LICENSE file in the project root for full license text.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* P227.01 -- pure 3-way field merge of `.neocortex/state.json` for root
|
|
15
|
+
* story-worktree integration (P227-CON-STATE-MERGE, ADR-P227-01).
|
|
16
|
+
*
|
|
17
|
+
* Inputs are the three blobs (merge-base, epic head, story tip). Only the
|
|
18
|
+
* integrated story's `stories.<storyId>` entry and the P189 epic aggregates
|
|
19
|
+
* (recomputed, never copied) may change; top-level `last_updated` is derived
|
|
20
|
+
* metadata (later instant wins). Every other divergence from the epic line
|
|
21
|
+
* fails closed with a stable reason code. The function has no I/O and no
|
|
22
|
+
* clock: identical inputs always yield identical bytes.
|
|
23
|
+
*/
|
|
24
|
+
/** Per-blob cap; the integration reads blobs with exactly this Git buffer (review note 3). */
|
|
25
|
+
export declare const STATE_JSON_FIELD_MERGE_MAX_BYTES: number;
|
|
26
|
+
export declare const STATE_JSON_FIELD_MERGE_REASON_CODES: Readonly<{
|
|
27
|
+
readonly inputInvalid: "state-merge-input-invalid";
|
|
28
|
+
readonly outsideAllowlist: "state-merge-outside-allowlist";
|
|
29
|
+
readonly storyEntryInvalid: "state-merge-story-entry-invalid";
|
|
30
|
+
readonly storyEntryConflict: "state-merge-story-entry-conflict";
|
|
31
|
+
readonly aggregateInvalid: "state-merge-aggregate-invalid";
|
|
32
|
+
}>;
|
|
33
|
+
export type StateJsonFieldMergeReasonCode = typeof STATE_JSON_FIELD_MERGE_REASON_CODES[keyof typeof STATE_JSON_FIELD_MERGE_REASON_CODES];
|
|
34
|
+
/** Epic fields owned by the P189 writer: never taken from the story side (R4). */
|
|
35
|
+
export declare const STATE_JSON_EPIC_AGGREGATE_FIELDS: readonly ["total_stories", "completed_stories", "status", "completed_at"];
|
|
36
|
+
export interface StateJsonFieldMergeInput {
|
|
37
|
+
readonly base: string | Buffer;
|
|
38
|
+
readonly epic: string | Buffer;
|
|
39
|
+
readonly story: string | Buffer;
|
|
40
|
+
readonly storyId: string;
|
|
41
|
+
readonly epicId: string;
|
|
42
|
+
/** Deterministic instant for a newly set `completed_at` (story tip committer date). */
|
|
43
|
+
readonly aggregateTimestamp: string;
|
|
44
|
+
}
|
|
45
|
+
export type StateJsonFieldMergeResult = {
|
|
46
|
+
readonly ok: true;
|
|
47
|
+
readonly bytes: string;
|
|
48
|
+
/** False exactly when the merged value equals the epic side (epic bytes returned). */
|
|
49
|
+
readonly changed: boolean;
|
|
50
|
+
readonly aggregatesRecomputed: boolean;
|
|
51
|
+
} | {
|
|
52
|
+
readonly ok: false;
|
|
53
|
+
readonly reasonCode: StateJsonFieldMergeReasonCode;
|
|
54
|
+
/** Dotted state key path for diagnostics/tests; never part of integration output. */
|
|
55
|
+
readonly pointer?: string;
|
|
56
|
+
};
|
|
57
|
+
type JsonObject = Record<string, unknown>;
|
|
58
|
+
/** Structural JSON equality; key order is ignored, absence is a distinct value. */
|
|
59
|
+
export declare function stateJsonValuesEqual(left: unknown, right: unknown): boolean;
|
|
60
|
+
export interface StateJsonEpicAggregateResult {
|
|
61
|
+
readonly epic: JsonObject;
|
|
62
|
+
readonly totalStories: number;
|
|
63
|
+
readonly completedStories: number;
|
|
64
|
+
readonly promotedDone: boolean;
|
|
65
|
+
readonly completedAtSet: boolean;
|
|
66
|
+
}
|
|
67
|
+
/** Client mirror of the P189 writer; throws `state-merge-aggregate-invalid` on every P189 hard stop. */
|
|
68
|
+
export declare function recomputeStateJsonEpicAggregates(input: {
|
|
69
|
+
readonly epicId: string;
|
|
70
|
+
readonly epic: unknown;
|
|
71
|
+
readonly stories: Readonly<Record<string, unknown>>;
|
|
72
|
+
readonly nowIso: string;
|
|
73
|
+
}): StateJsonEpicAggregateResult;
|
|
74
|
+
/** P227-CON-STATE-MERGE: pure, deterministic 3-way field merge (R1-R7). */
|
|
75
|
+
export declare function mergeStateJsonFields(input: StateJsonFieldMergeInput): StateJsonFieldMergeResult;
|
|
76
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const M=33554432,l=Object.freeze({inputInvalid:"state-merge-input-invalid",outsideAllowlist:"state-merge-outside-allowlist",storyEntryInvalid:"state-merge-story-entry-invalid",storyEntryConflict:"state-merge-story-entry-conflict",aggregateInvalid:"state-merge-aggregate-invalid"}),C=Object.freeze(["total_stories","completed_stories","status","completed_at"]),x=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,J=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,S=Symbol("absent");class j extends Error{reasonCode;pointer;constructor(t,s){super(t),this.reasonCode=t,this.pointer=s}}function g(e,t){throw new j(e,t)}function E(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function r(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:S}function d(e,t){if(e===t)return!0;if(e===S||t===S)return!1;if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((s,n)=>d(s,t[n]));if(E(e)){if(!E(t))return!1;const s=Object.keys(e);return s.length!==Object.keys(t).length?!1:s.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&d(e[n],t[n]))}return!1}function k(e){const t=typeof e=="string"?e:e.toString("utf8");Buffer.byteLength(t,"utf8")>33554432&&g(l.inputInvalid);let s;try{s=JSON.parse(t)}catch{g(l.inputInvalid)}E(s)||g(l.inputInvalid);for(const n of["stories","epics"]){const o=r(s,n);o!==S&&!E(o)&&g(l.inputInvalid,n)}return{text:t,value:s}}function N(...e){const t=[],s=new Set;for(const n of e)for(const o of Object.keys(n??{}))s.has(o)||(s.add(o),t.push(o));return t}function I(e,t,s){s===S?delete e[t]:Object.defineProperty(e,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}function F(e,t){const s=Object.keys(e).filter(i=>r(t,i)!==S),n=Object.keys(e).filter(i=>r(t,i)===S).sort(),o={};for(const i of[...s,...n])I(o,i,e[i]);return o}function w(e,t,s,n){if(d(s,e)||d(s,t))return t;g(l.outsideAllowlist,n)}function b(e){return E(e)?e:void 0}function L(e,t,s,n,o){if(d(s,e))return t;if(E(s)||g(l.storyEntryInvalid,`stories.${n}`),(r(s,"id")!==S&&s.id!==n||r(s,"epic_id")!==S&&s.epic_id!==o)&&g(l.storyEntryInvalid,`stories.${n}`),d(t,e))return s;t!==S&&!E(t)&&g(l.storyEntryInvalid,`stories.${n}`);const i=b(e),a=b(t),m={...a??{}};for(const u of N(a,s,i)){const O=r(i,u),f=r(a,u),_=r(s,u);d(_,O)||d(_,f)?I(m,u,f):d(f,O)?I(m,u,_):g(l.storyEntryConflict,`stories.${n}.${u}`)}return m}function P(e,t,s,n){if(d(s,e)||d(s,t))return t;(!E(s)||!E(t)||e!==S&&!E(e))&&g(l.outsideAllowlist,`epics.${n}`);const o=b(e),i={...t};for(const a of N(t,s,o))C.includes(a)||I(i,a,w(r(o,a),r(t,a),r(s,a),`epics.${n}.${a}`));return i}function R(e,t,s){if(d(s,e)||d(s,t))return t;const n=typeof s=="string"?Date.parse(s):Number.NaN;Number.isFinite(n)||g(l.outsideAllowlist,"last_updated");const o=typeof t=="string"?Date.parse(t):Number.NaN;return Number.isFinite(o)&&o>=n?t:s}const $=new Set(["done","completed","merged"]);function D(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function z(e){const t=()=>g(l.aggregateInvalid,`epics.${e.epicId}`);E(e.epic)||t();const s={...e.epic};(s.id!==e.epicId||!Array.isArray(s.stories))&&t();const n=new Set;let o=0;for(const f of s.stories){(typeof f!="string"||f.length===0||n.has(f))&&t(),n.add(f);const _=e.stories[f];(!E(_)||_.id!==f||_.epic_id!==e.epicId)&&t(),$.has(D(_.status))&&(o+=1)}const i=n.size,a=i>0&&o===i,m=$.has(D(s.status));m&&!a&&i>0&&t(),s.total_stories=i,s.completed_stories=o;let u=!1,O=!1;return!m&&a&&(s.status="done",u=!0,(s.completed_at===void 0||s.completed_at===null)&&(s.completed_at=e.nowIso,O=!0)),{epic:s,totalStories:i,completedStories:o,promotedDone:u,completedAtSet:O}}function G(e){return`${JSON.stringify(e,null,2)}
|
|
2
|
+
`}function B(e){try{(!x.test(e.storyId)||!J.test(e.epicId)||!Number.isFinite(Date.parse(e.aggregateTimestamp)))&&g(l.inputInvalid);const t=k(e.base).value,s=k(e.epic),n=s.value,o=k(e.story).value,i={...n};for(const c of N(n,o,t)){const p=r(t,c),y=r(n,c),A=r(o,c);c==="stories"||c==="epics"||(c==="last_updated"?I(i,c,R(p,y,A)):I(i,c,w(p,y,A,c)))}const a=b(r(t,"stories")),m=b(r(n,"stories")),u=b(r(o,"stories"));if(u||m||a){const c={...m??{}};for(const p of N(m,u,a)){const y=r(a,p),A=r(m,p),v=r(u,p);I(c,p,p===e.storyId?L(y,A,v,e.storyId,e.epicId):w(y,A,v,`stories.${p}`))}(m||Object.keys(c).length>0)&&I(i,"stories",F(c,a))}const O=b(r(t,"epics")),f=b(r(n,"epics")),_=b(r(o,"epics"));let h=!1;if(_||f||O){const c={...f??{}};for(const y of N(f,_,O)){const A=r(O,y),v=r(f,y),T=r(_,y);I(c,y,y===e.epicId?P(A,v,T,y):w(A,v,T,`epics.${y}`))}const p=r(c,e.epicId);E(p)&&Array.isArray(p.stories)&&(I(c,e.epicId,z({epicId:e.epicId,epic:p,stories:b(r(i,"stories"))??{},nowIso:e.aggregateTimestamp}).epic),h=!0),(f||Object.keys(c).length>0)&&I(i,"epics",c)}return d(i,n)?{ok:!0,bytes:s.text,changed:!1,aggregatesRecomputed:h}:{ok:!0,bytes:G(i),changed:!0,aggregatesRecomputed:h}}catch(t){return t instanceof j?t.pointer===void 0?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:t.reasonCode,pointer:t.pointer.slice(0,256)}:{ok:!1,reasonCode:l.inputInvalid}}}export{C as STATE_JSON_EPIC_AGGREGATE_FIELDS,M as STATE_JSON_FIELD_MERGE_MAX_BYTES,l as STATE_JSON_FIELD_MERGE_REASON_CODES,B as mergeStateJsonFields,z as recomputeStateJsonEpicAggregates,d as stateJsonValuesEqual};
|
|
@@ -103,6 +103,22 @@ export interface StoryWorktreeCleanupValue {
|
|
|
103
103
|
readonly receiptDigest?: string;
|
|
104
104
|
readonly bundleDigest?: string;
|
|
105
105
|
readonly preservedReasonCodes: readonly string[];
|
|
106
|
+
/** P227.07: present only when a vanished directory was recovered. */
|
|
107
|
+
readonly absenceProof?: StoryWorktreeAbsenceProof;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* P227.07 (P227-CON-ORPHAN): public proof that an orphan recovery removed
|
|
111
|
+
* nothing but the metadata of a definitely missing directory. Enums and a
|
|
112
|
+
* boolean only; never a path.
|
|
113
|
+
*/
|
|
114
|
+
export interface StoryWorktreeAbsenceProof {
|
|
115
|
+
readonly worktree: 'enoent';
|
|
116
|
+
/**
|
|
117
|
+
* `absent` only with proof (`show-ref --verify` exit 1); `unknown` when the
|
|
118
|
+
* ref could be neither read nor proven missing (C11 finding 3).
|
|
119
|
+
*/
|
|
120
|
+
readonly branch: 'absent' | 'present' | 'unknown';
|
|
121
|
+
readonly bundled: boolean;
|
|
106
122
|
}
|
|
107
123
|
export interface StoryWorktreeSweepItem {
|
|
108
124
|
readonly leaseId: string;
|
|
@@ -110,6 +126,7 @@ export interface StoryWorktreeSweepItem {
|
|
|
110
126
|
readonly reasonCode?: string;
|
|
111
127
|
readonly bundleDigest?: string;
|
|
112
128
|
readonly plannedActions?: readonly string[];
|
|
129
|
+
readonly absenceProof?: StoryWorktreeAbsenceProof;
|
|
113
130
|
}
|
|
114
131
|
export interface StoryWorktreeSweepValue {
|
|
115
132
|
readonly dryRun: boolean;
|
|
@@ -184,7 +201,11 @@ export declare class StoryWorktreeCleanup {
|
|
|
184
201
|
* (crash between `bundle create` and its record) older than the TTL.
|
|
185
202
|
*/
|
|
186
203
|
private expireBundles;
|
|
187
|
-
|
|
204
|
+
/**
|
|
205
|
+
* P227.07 (C11 finding 3): `show-ref --verify --quiet` exits 1 only when the
|
|
206
|
+
* ref does not exist; any other failure leaves the absence unproven.
|
|
207
|
+
*/
|
|
208
|
+
private branchAbsence;
|
|
188
209
|
private removeWithRetry;
|
|
189
210
|
private probe;
|
|
190
211
|
private facts;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createHash as ye,randomBytes as Q}from"node:crypto";import{existsSync as V}from"node:fs";import{chmod as Ie,lstat as ve,open as X,readFile as x,readdir as Z,rename as ke,rm as T,stat as H,unlink as De}from"node:fs/promises";import{hostname as Oe}from"node:os";import{join as D}from"node:path";import{GIT_LIFECYCLE_RUNTIME_DIRECTORY as F,STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as ee,assertGitLifecyclePrivateFile as te,compactStoryWorktreeJournal as Ae,ensureGitLifecyclePrivateChildDirectory as _e,ensureStoryWorktreeJournal as re,gitLifecycleRuntimeDirectory as se,isStoryWorktreeCleanupReceiptRecord as oe,mutateGitLifecycleRuntime as Se,readGitLifecycleRuntime as ne}from"./git-lifecycle-store.js";import{StoryWorktreeManager as Ne,digestStoryWorktreeReceiptLocal as ae,runStoryWorktreeGit as A}from"./story-worktree-manager.js";const j="story-worktree-cleanup.json",G="story-worktree-bundles",Te=256,ie=Object.freeze(["success","failure","abandon","orphan-recovery"]),be=Object.freeze(["active","integrated","failed","abandoned","bundled","remove-pending","removed"]),Ce=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=Ce,de=10080*60*1e3,Pe=600*1e3,Me=64,Le=512*1024*1024,ce=3,Be=50,Ue=/^swt-[a-f0-9]{24}$/,Y=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,le=/^[a-f0-9]{64}$/,Ve=/^[a-f0-9]{16}$/,ue=/^P[1-9][0-9]*$/,xe=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,he=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,me=/^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/,We=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,fe=/^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 l(u){throw new W(u)}function M(u){return ye("sha256").update(u).digest("hex")}function z(u){return new Promise(t=>setTimeout(t,u))}function pe(u){return[...new Set(u)]}function $e(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 Ee(u=Oe()){return M(`neocortex.p225.owner-host|${u}`)}function $(u){return u!==null&&typeof u=="object"&&!Array.isArray(u)?u:void 0}const we=["schemaVersion","leaseId","epicId","storyId","state","removeAttempts","updatedAt"],He=new Set([...we,"trigger","headSha","bundleDigest","bundleBytes","bundleExpiresAt","remotePush","remoteBranchRemoved","ownerPid","ownerHostDigest","claimToken","claimExpiresAt"]);function ge(u,t){const e=$(t);if(!e||Object.keys(e).some(o=>!He.has(o))||we.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"||!he.test(r.remote)||typeof r.branch!="string"||!me.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"&&We.test(e[o])&&Number.isFinite(Date.parse(e[o]));return e.schemaVersion===1&&e.leaseId===u&&Ue.test(u)&&typeof e.epicId=="string"&&ue.test(e.epicId)&&typeof e.storyId=="string"&&xe.test(e.storyId)&&e.storyId.startsWith(`${e.epicId}.`)&&be.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"&&Ve.test(e.claimToken))&&(e.trigger===void 0||ie.includes(e.trigger))&&(e.headSha===void 0||typeof e.headSha=="string"&&Y.test(e.headSha))&&(e.bundleDigest===void 0||typeof e.bundleDigest=="string"&&le.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"&&le.test(e.ownerHostDigest))}function J(u){let t;try{t=JSON.parse(u)}catch{l(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])=>ge(s,o)))&&l(a.STATE_INVALID),{schemaVersion:1,records:r}}async function Re(u){const t=D(u,F),e=D(t,j);if(!V(e))return{schemaVersion:1,records:{}};try{await te(e,t)}catch{l(a.STATE_INVALID)}return J(await x(e,"utf8"))}function b(u,t){return u?.claimToken!==void 0&&u.claimExpiresAt!==void 0&&Date.parse(u.claimExpiresAt)>t}async function et(u,t,e=Date.now()){try{const r=(await Re(u)).records[t];return r!==void 0&&(K.includes(r.state)||b(r,e))}catch{return!0}}class Fe{options;manager;now;isProcessAlive;constructor(t){this.options=t,this.manager=t.manager??new Ne({projectRoot:t.projectRoot,...t.worktreeRoot?{worktreeRoot:t.worktreeRoot}:{},...t.now?{now:t.now}:{}}),this.now=t.now??(()=>new Date),this.isProcessAlive=t.isProcessAlive??$e}async readState(t){return Re(t?.commonDir??(await this.facts()).commonDir)}async recordPush(t){return this.guard(async()=>{(typeof t.remote!="string"||!he.test(t.remote))&&l("story-worktree-remote-invalid");const e=await this.probe(t.leaseId);(e.ownership!=="proven"||!e.headSha)&&l("story-worktree-ownership-unproven"),(e.entry.workspaceMechanism!=="client_managed_worktree"||!me.test(e.entry.temporaryBranch))&&l(a.ADOPTED_BRANCH),await this.gitOk(e.facts.mainRoot,["config","--get",`remote.${t.remote}.url`])||l(a.REMOTE_UNKNOWN);const r=await this.lsRemote(e.facts.mainRoot,t.remote,e.entry.temporaryBranch);r===null&&l(a.REMOTE_UNVERIFIED),r===void 0&&l(a.REMOTE_ABSENT),r!==e.headSha&&l(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)&&l("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:Ee()})),{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&&!ue.test(t.epicId)&&l("story-worktree-identity-invalid");const e=t.dryRun===!0,r=await this.facts(),s=await ne(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=Ee(),i=[],c=[];for(const d of n){const E=h.records[d.leaseId],I=E!==void 0&&K.includes(E.state),S=Date.parse(d.expiresAt)<=m,k=E?.ownerPid!==void 0&&E.ownerHostDigest===f&&this.isProcessAlive(E.ownerPid);if(k||b(E,m)||!I&&!S){const N=k?a.OWNER_ALIVE:b(E,m)?a.CLAIMED:a.LEASE_LIVE;i.push({leaseId:d.leaseId,action:"skipped",reasonCode:N});continue}const L=I?E?.trigger==="success"&&S?"orphan-recovery":E?.trigger??"orphan-recovery":"orphan-recovery";let _;try{_={ok:!0,value:await this.cleanupUnguarded({leaseId:d.leaseId,trigger:L,dryRun:e})}}catch(N){_={ok:!1,reasonCode:N instanceof W?N.reasonCode:a.SWEEP_FAILED}}if(!_.ok){i.push({leaseId:d.leaseId,action:"preserved",reasonCode:_.reasonCode}),c.push(_.reasonCode);continue}const y=_.value;y.outcome==="dry-run"?i.push({leaseId:d.leaseId,action:"planned",plannedActions:y.plannedActions??[]}):y.outcome==="remove-pending"?(i.push({leaseId:d.leaseId,action:"remove-pending",reasonCode:a.REMOVE_PENDING,...y.bundleDigest?{bundleDigest:y.bundleDigest}:{}}),c.push(a.REMOVE_PENDING)):(i.push({leaseId:d.leaseId,action:"recovered",reasonCode:a.ORPHAN_RECOVERED,...y.bundleDigest?{bundleDigest:y.bundleDigest}:{}}),c.push(a.ORPHAN_RECOVERED))}const g=new Set(o.map(d=>d.leaseId));for(const d of Object.values(h.records).sort((E,I)=>E.leaseId.localeCompare(I.leaseId))){if(g.has(d.leaseId)||d.state==="removed"||b(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&&c.push(E)}const R=await this.expireBundles(h,r,m,e),v=await this.manager.registeredWorktrees();v.ok||l(v.reasonCode);const C=v.value.worktrees.filter(d=>!o.some(E=>this.manager.sameWorktreePath(E.worktreePath,d.path))).length;return C>0&&c.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:C,bundlesExpired:R,items:i,reasonCodes:pe(c)}}})}async cleanupUnguarded(t){ie.includes(t.trigger)||l("story-worktree-trigger-invalid");const e=await this.probe(t.leaseId),{entry:r,facts:s}=e,n=(await this.readState(s)).records[r.leaseId];if(r.state==="creating")return t.trigger!=="orphan-recovery"&&l("story-worktree-ownership-unproven"),this.recoverCreating(e,t.dryRun===!0);const h=n!==void 0&&K.includes(n.state);let m=!1;e.pathExists||(await this.definitelyMissing(r.worktreePath)||l(a.ORPHAN_UNPROVEN),t.trigger!=="orphan-recovery"&&!h&&l("story-worktree-ownership-unproven"),m=!0),!m&&e.ownership!=="proven"&&l("story-worktree-ownership-unproven"),!m&&e.clean!==!0&&l(t.trigger==="success"?"story-worktree-dirty":a.DIRTY_PRESERVED),e.epicHead||l("story-worktree-epic-branch-missing");const f=e.epicHead,i=m?e.branchSha:e.headSha;!m&&!i&&l("story-worktree-git-failed");const c=e.integrated===!0;t.trigger==="success"&&!c&&l("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=!c&&i!==void 0&&g&&!R,C=n?.remotePush!==void 0&&n.remoteBranchRemoved!==!0;if(t.dryRun===!0){const I=[...v?["bundle-unintegrated-range"]:[],m?"drop-worktree-metadata":"remove-worktree",...g&&e.branchSha?["delete-local-branch"]:[],...C?["delete-remote-branch"]:[]];return{leaseId:r.leaseId,outcome:"dry-run",trigger:t.trigger,state:n?.state??"active",plannedActions:I,preservedReasonCodes:[]}}const d=await this.claim(r);let E=!1;try{let I=R?n?.bundleDigest:void 0;if(v){const w=await this.createBundle(e,i,f);I=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??de)).toISOString()}))}else if(!R){const w=c?"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 A(s.mainRoot,["worktree","remove",r.worktreePath]);else{const w=this.options.removeAttempts??ce;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",...I?{bundleDigest:I}:{},preservedReasonCodes:[a.REMOVE_PENDING]}}await A(s.mainRoot,["worktree","prune"]);const S=await this.manager.registeredWorktrees();S.ok||l(S.reasonCode),S.value.worktrees.some(w=>this.manager.sameWorktreePath(w.path,r.worktreePath))&&l(a.ORPHAN_UNPROVEN);const k=[];let L=!1;if(!g)k.push(a.ADOPTED_BRANCH);else if(e.branchSha){const w=i??e.branchSha,p=c||I!==void 0,O=S.value.worktrees.some(P=>P.branch===r.temporaryBranch);p?O?k.push(a.BRANCH_CHECKED_OUT):await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,w])?L=!0:k.push(a.BRANCH_MOVED):k.push(a.ORPHAN_UNPROVEN)}const _=(await this.readState(s)).records[r.leaseId]??n,y=await this.deleteRemote(r,s,_,d,{epicHead:f,...i?{tip:i}:{},bundled:I!==void 0});y.reasonCode&&k.push(y.reasonCode);const N=_?.remotePush!==void 0&&!y.removed&&(y.reasonCode===a.REMOTE_UNVERIFIED||y.reasonCode===a.REMOTE_UNPRESERVED),B=this.now().toISOString(),U={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${M(`${r.leaseId}|${r.nonceDigest}|${t.trigger}|${B}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:t.trigger,worktreeRemoved:!0,localBranchRemoved:L,remoteBranchRemoved:y.removed,...k[0]?{preservedReasonCode:k[0]}:{},cleanedAt:B};return oe(U)||l("story-worktree-receipt-invalid"),await this.mutate(w=>{const p=re(w),O=p.entries[r.leaseId];for((!O||O.nonceDigest!==r.nonceDigest)&&l(a.ENTRY_CONFLICT),delete p.entries[r.leaseId],p.cleanupReceipts.push({...U});p.cleanupReceipts.length>ee;)p.cleanupReceipts.shift()},w=>{const p=w.records[r.leaseId];if(p)if(N&&p.remotePush!==void 0){const O=p.state==="removed"||p.state==="remove-pending"||p.state==="active"?p.bundleDigest?"bundled":"integrated":p.state,P={...p,state:O,updatedAt:B,remoteBranchRemoved:!1};delete P.claimToken,delete P.claimExpiresAt,w.records[r.leaseId]=P}else if(p.bundleDigest){const O={...p,state:"removed",updatedAt:B,remoteBranchRemoved:y.removed};delete O.claimToken,delete O.claimExpiresAt,w.records[r.leaseId]=O}else delete w.records[r.leaseId]}),E=!0,{leaseId:r.leaseId,outcome:"removed",trigger:t.trigger,state:"removed",receipt:U,receiptDigest:ae(U),...I?{bundleDigest:I}:{},preservedReasonCodes:pe(k)}}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 A(r.worktreePath,["rev-parse","HEAD"]),i=await A(r.worktreePath,["symbolic-ref","--quiet","--short","HEAD"]),c=await A(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&&c.ok&&c.stdout.length===0||l(a.ORPHAN_UNPROVEN),n=!0}else await this.definitelyMissing(r.worktreePath)||l(a.ORPHAN_UNPROVEN),t.branchCheckedOut&&l(a.ORPHAN_UNPROVEN);if(t.branchSha!==void 0&&t.branchSha!==r.baseSha&&l(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??ce)&&l(a.REMOVE_PENDING),n&&await A(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(),c={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 oe(c)||l("story-worktree-receipt-invalid"),await this.mutate(g=>{const R=re(g),v=R.entries[r.leaseId];for((!v||v.state!=="creating"||v.nonceDigest!==r.nonceDigest)&&l(a.ENTRY_CONFLICT),delete R.entries[r.leaseId],R.cleanupReceipts.push({...c});R.cleanupReceipts.length>ee;)R.cleanupReceipts.shift()},g=>{delete g.records[r.leaseId]}),m=!0,{...o,outcome:"reclaimed",state:"removed",receipt:c,receiptDigest:ae(c),preservedReasonCodes:c.preservedReasonCode?[c.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 A(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 A(t,["ls-remote","--heads",e,`refs/heads/${r}`]);if(!s.ok)return null;const o=s.stdout.split(`
|
|
2
|
-
`).map(h=>h.trim()).find(h=>h.endsWith(` refs/heads/${r}`));if(!o)return;const n=o.split(" ")[0]??"";return Y.test(n)?n:null}async createBundle(t,e,r){const{entry:s,facts:o}=t,n=await _e(await
|
|
3
|
-
`).some(d=>d.trim()===`${e} ${g}`))&&(await
|
|
4
|
-
`;J(f),await
|
|
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(h=>h.trim()).find(h=>h.endsWith(` refs/heads/${r}`));if(!o)return;const n=o.split(" ")[0]??"";return Y.test(n)?n:null}async createBundle(t,e,r){const{entry:s,facts:o}=t,n=await _e(await oe(this.options.projectRoot),G),h=q(s.leaseId,e),f=(await ee(n)).filter(d=>pe.test(d)).filter(d=>d!==h);f.length>=(this.options.maxBundles??Me)&&c(a.BUNDLE_QUOTA);let i=0;for(const d of f)i+=(await H(A(n,d))).size;const l=A(n,h);await C(l,{force:!0});const g=`refs/heads/${s.temporaryBranch}`;await this.gitOk(o.mainRoot,["bundle","create",l,g,`^${r}`])||(await C(l,{force:!0}),c(a.BUNDLE_FAILED)),process.platform!=="win32"&&await ve(l,384);const R=(await H(l)).size;i+R>(this.options.maxBundleBytes??Be)&&(await C(l,{force:!0}),c(a.BUNDLE_QUOTA));const v=await O(o.mainRoot,["bundle","list-heads",l]);return(!await this.gitOk(o.mainRoot,["bundle","verify","--quiet",l])||!v.ok||!v.stdout.split(`
|
|
3
|
+
`).some(d=>d.trim()===`${e} ${g}`))&&(await C(l,{force:!0}),c(a.BUNDLE_UNVERIFIED)),{digest:M(await x(l)),bytes:R}}async bundleMatches(t,e,r,s){try{const o=A(t.commonDir,F,G,q(e,r));return M(await x(o))===s}catch{return!1}}async expireBundles(t,e,r,s){const o=A(e.commonDir,F,G),n=Object.values(t.records).filter(i=>i.state==="removed"&&i.bundleExpiresAt!==void 0&&Date.parse(i.bundleExpiresAt)<=r),h=new Set(Object.values(t.records).filter(i=>i.bundleDigest!==void 0&&i.headSha!==void 0&&!n.some(l=>l.leaseId===i.leaseId)).map(i=>q(i.leaseId,i.headSha))),m=this.options.bundleTtlMs??ce,f=[];if(U(o))for(const i of(await ee(o)).filter(l=>pe.test(l)&&!h.has(l))){const l=i.slice(0,28),g=t.records[l];(n.some(R=>R.leaseId===l)||!g&&r-(await H(A(o,i))).mtimeMs>=m)&&f.push(i)}if(s||f.length===0&&n.length===0)return f.length;await this.mutate(void 0,i=>{for(const l of n){const g=i.records[l.leaseId];g?.state==="removed"&&g.bundleExpiresAt===l.bundleExpiresAt&&delete i.records[l.leaseId]}});for(const i of f)await C(A(o,i),{force:!0});return f.length}async branchAbsence(t,e){const r=await O(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e}`]);return r.ok?"present":r.exitCode===1?"absent":"unknown"}async removeWithRetry(t,e,r){const s=this.options.removeWorktree??((n,h)=>this.gitOk(n,["worktree","remove",h])),o=this.options.removeDelayMs??Ve;for(let n=1;n<=r;n++){if(await s(t,e))return!0;n<r&&await z(o*n)}return!1}async probe(t){const e=await this.manager.probe(t);return e.ok||c(e.reasonCode),e.value}async facts(){const t=await this.manager.registeredWorktrees();return t.ok||c(t.reasonCode),t.value.facts}async gitOk(t,e){return(await O(t,e)).ok}async claim(t){const e=X(8).toString("hex");return await this.mutate(r=>{const s=r.storyWorktrees?.entries[t.leaseId];(!s||s.nonceDigest!==t.nonceDigest)&&c(a.ENTRY_CONFLICT)},r=>{const s=this.now().getTime(),o=r.records[t.leaseId]??this.emptyRecord(t);N(o,s)&&c(a.CLAIMED),r.records[t.leaseId]={...o,claimToken:e,claimExpiresAt:new Date(s+(this.options.claimTtlMs??Le)).toISOString(),updatedAt:new Date(s).toISOString()}}),e}async releaseClaim(t,e){await this.mutate(void 0,r=>{const s=r.records[t.leaseId];if(!s||s.claimToken!==e)return;const o={...s};delete o.claimToken,delete o.claimExpiresAt,s.state!=="active"||s.remotePush!==void 0||s.ownerPid!==void 0||s.bundleDigest!==void 0||s.removeAttempts>0?r.records[t.leaseId]=o:delete r.records[t.leaseId]})}emptyRecord(t){return{schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,state:"active",removeAttempts:0,updatedAt:this.now().toISOString()}}async update(t,e,r){await this.mutate(s=>{const o=s.storyWorktrees?.entries[t.leaseId];(!o||o.nonceDigest!==t.nonceDigest)&&c(a.ENTRY_CONFLICT)},s=>{const o=s.records[t.leaseId]??this.emptyRecord(t);N(o,this.now().getTime())&&o.claimToken!==e&&c(a.CLAIMED);const n={...r(o),updatedAt:this.now().toISOString()};Re(t.leaseId,n)||c(a.STATE_INVALID),s.records[t.leaseId]=n})}async mutate(t,e){const r=this.options.lockRetry?.attempts??40,s=this.options.lockRetry?.delayMs??25;for(let o=1;;o++)try{await Se(this.options.projectRoot,n=>{t?.(n),Oe(n)},{preCommit:async()=>{const n=await oe(this.options.projectRoot),h=A(n,j);let m={schemaVersion:1,records:{}};if(U(h)&&(await re(h,n),m={schemaVersion:1,records:{...J(await x(h,"utf8")).records}}),e(m),Object.keys(m.records).length===0){U(h)&&await De(h);return}const f=`${JSON.stringify(m,null,2)}
|
|
4
|
+
`;J(f),await Ge(n,j,f)}});return}catch(n){if(!(n instanceof Error&&(n.message==="git-lifecycle-runtime-lock-active"||n.code==="ENOENT"&&n.message.includes("runtime.lock")))||o>=r)throw n;await z(s*Math.min(o,8)+Math.floor(Math.random()*s))}}async guard(t){try{return await t()}catch(e){if(e instanceof W)return{ok:!1,reasonCode:e.reasonCode};const r=e instanceof Error?e.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(r)?{ok:!1,reasonCode:r}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}}async function Ge(u,t,e){const r=A(u,`.${t}.${X(6).toString("hex")}.tmp`),s=await Z(r,"wx",384);try{await s.writeFile(e,"utf8"),await s.sync()}finally{await s.close()}try{await ke(r,A(u,t))}catch(o){throw await C(r,{force:!0}),o}try{const o=await Z(u,"r");try{await o.sync()}finally{await o.close()}}catch(o){if(process.platform!=="win32")throw o}}const Ye=new Set([a.MANUAL_PRESERVED]);async function Ke(u,t={}){let e;try{const s=await ae(u);if(e=new je({...t,projectRoot:u}),!(Object.keys(s.storyWorktrees?.entries??{}).length>0)&&Object.keys((await e.readState()).records).length===0)return{reasonCodes:[]}}catch(s){return{reasonCodes:s instanceof W?[s.reasonCode]:[]}}const r=await e.sweep({...t.epicId?{epicId:t.epicId}:{},...t.dryRun?{dryRun:!0}:{}});return r.ok?{reasonCodes:r.value.reasonCodes.filter(s=>!Ye.has(s)),value:r.value}:{reasonCodes:[r.reasonCode]}}function rt(u,t=r=>Ke(r),e=r=>{process.kill(process.pid,r)}){let r=!1;const s=n=>{r||(r=!0,o(),Promise.race([t(u),z(25e3)]).catch(()=>{}).finally(()=>e(n)))},o=()=>{process.removeListener("SIGINT",s),process.removeListener("SIGTERM",s)};return process.once("SIGINT",s),process.once("SIGTERM",s),o}export{G as STORY_WORKTREE_BUNDLE_DIRECTORY,j as STORY_WORKTREE_CLEANUP_FILE,Te as STORY_WORKTREE_CLEANUP_MAX_RECORDS,Pe as STORY_WORKTREE_CLEANUP_REASON_CODES,Ce as STORY_WORKTREE_CLEANUP_STATES,de as STORY_WORKTREE_CLEANUP_TRIGGERS,je as StoryWorktreeCleanup,rt as installStoryWorktreeSignalSweep,Re as isStoryWorktreeCleanupRecord,J as parseStoryWorktreeCleanupDocument,q as storyWorktreeBundleFileName,tt as storyWorktreeCleanupInProgress,we as storyWorktreeOwnerHostDigest,Ke as sweepStoryWorktreeOrphans};
|
|
@@ -53,7 +53,53 @@ export interface IntegrateStoryWorktreeOptions {
|
|
|
53
53
|
export declare function digestStoryWorktreeIntegrationReceipt(receipt: IntegrationReceipt): string;
|
|
54
54
|
/** Integrate one story worktree into `epic/<ID>` (P225.07-ADR-1..6). */
|
|
55
55
|
export declare function integrateStoryWorktree(options: IntegrateStoryWorktreeOptions): Promise<StoryWorktreeIntegrationResult>;
|
|
56
|
+
export declare const STORY_WORKTREE_STATE_JSON_PATH: ".neocortex/state.json";
|
|
57
|
+
export interface ResolveStoryWorktreeStateJsonMergeInput {
|
|
58
|
+
readonly projectRoot: string;
|
|
59
|
+
readonly mergeBase: string;
|
|
60
|
+
readonly epicHead: string;
|
|
61
|
+
readonly tip: string;
|
|
62
|
+
/** Tree written by `merge-tree --write-tree` (may contain conflict markers). */
|
|
63
|
+
readonly tree: string;
|
|
64
|
+
readonly storyId: string;
|
|
65
|
+
readonly epicId: string;
|
|
66
|
+
/** Raw conflicting paths reported by `merge-tree`. */
|
|
67
|
+
readonly conflictPaths: readonly string[];
|
|
68
|
+
}
|
|
69
|
+
export type ResolveStoryWorktreeStateJsonMergeResult = {
|
|
70
|
+
readonly ok: true;
|
|
71
|
+
readonly tree: string;
|
|
72
|
+
readonly conflictPaths: readonly string[];
|
|
73
|
+
readonly merged: boolean;
|
|
74
|
+
} | {
|
|
75
|
+
readonly ok: false;
|
|
76
|
+
readonly reasonCode: string;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* P227.01 R8/R9: when the story changed `.neocortex/state.json`, replace that
|
|
80
|
+
* entry of the `merge-tree` result with the pure field merge of the three
|
|
81
|
+
* blobs, using object commands only (`hash-object`, `ls-tree`, `mktree`): no
|
|
82
|
+
* index, checkout, temporary file or ref effect. The path leaves the conflict
|
|
83
|
+
* list; other conflicts are returned unchanged. Refusals are reason codes only.
|
|
84
|
+
*/
|
|
85
|
+
export declare function resolveStoryWorktreeStateJsonMerge(input: ResolveStoryWorktreeStateJsonMergeInput): Promise<ResolveStoryWorktreeStateJsonMergeResult>;
|
|
56
86
|
export declare const STORY_WORKTREE_WAVE_MAX_STORIES = 64;
|
|
87
|
+
/**
|
|
88
|
+
* P227.03 (ADR-1): closed, client-declared build outputs cleaned between
|
|
89
|
+
* bisection probes. Not configurable by callers, manifests, env or stories.
|
|
90
|
+
* C11 F5 (DEC-04): this is the neocortex repository's own layout. It applies
|
|
91
|
+
* only to a project whose committed root `package.json` is named
|
|
92
|
+
* `STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT`; any other project declares
|
|
93
|
+
* nothing and gets no cleanup.
|
|
94
|
+
*/
|
|
95
|
+
export declare const STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT = "@ornexus/neocortex";
|
|
96
|
+
export declare const STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS: readonly string[];
|
|
97
|
+
/**
|
|
98
|
+
* C11 F5 (DEC-04): build outputs the project explicitly declares, read from the
|
|
99
|
+
* committed root `package.json` at `headSha` (never the working tree). An
|
|
100
|
+
* absent, unreadable or foreign manifest declares nothing: no cleanup.
|
|
101
|
+
*/
|
|
102
|
+
export declare function storyWorktreeWaveBuildOutputPaths(projectRoot: string, headSha: string): Promise<readonly string[]>;
|
|
57
103
|
export type StoryWorktreeWaveStoryOutcome = 'integrated' | 'already-integrated' | 'conflict-reopened' | 'gate-failed' | 'not-integrated';
|
|
58
104
|
export interface StoryWorktreeWaveStoryResult {
|
|
59
105
|
readonly storyId: string;
|
|
@@ -101,6 +147,8 @@ export interface IntegrateStoryWorktreeWaveOptions {
|
|
|
101
147
|
readonly afterWaveFastForward?: () => Promise<void>;
|
|
102
148
|
/** Test seam after one story checkpoint + receipt was persisted (crash window). */
|
|
103
149
|
readonly afterWaveStoryPersist?: (storyId: string) => Promise<void>;
|
|
150
|
+
/** Test seam replacing the declared build-output cleanup (P227.03 EX-03e); `false` means failure. */
|
|
151
|
+
readonly cleanBuildOutputs?: (projectRoot: string) => Promise<boolean>;
|
|
104
152
|
}
|
|
105
153
|
/** Gate-run cap: one run at W, ceil(log2 n) bisection runs, one spare. */
|
|
106
154
|
export declare function storyWorktreeWaveGateRunCap(storyCount: number): number;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`).map(r=>r.trim()).filter(r=>r.startsWith(c));return d.length===1?d[0].slice(c.length):void 0}function He(e){return ot(wt,e)}function F(e,a){return(Ke(e,a)?.receipts??[]).filter(lt)}function we(e){const a=[...e].sort((c,d)=>c.integrationIndex-d.integrationIndex);a.forEach((c,d)=>{(c.integrationIndex!==d+1||d>0&&c.epicHeadBeforeSha!==a[d-1].epicHeadAfterSha)&&o("story-worktree-integration-chain-invalid")})}function se(e,a){const c=[...e].sort((d,r)=>r.integrationIndex-d.integrationIndex)[0];c&&c.epicHeadAfterSha!==a&&o("story-worktree-integration-chain-invalid")}const It=new Set(["done","merged","completed","released"]);function Fe(e,a,c,d,r,w=new Set){(Ke(e,c)?.receipts??[]).some(s=>s.kind==="phase-one-receipt"&&s.storyId===d||s.kind==="spec-barrier-receipt"&&Array.isArray(s.storyIds)&&s.storyIds.includes(d))||o("story-worktree-integration-unbound");const u=new Set(F(e,c).filter(s=>s.outcome==="integrated").map(s=>s.storyId));for(const s of r){if(!s.startsWith(`${c}.`))continue;const v=a[s],k=!!e.stories[s]?.checkpoint||typeof v?.status=="string"&&It.has(v.status);!u.has(s)&&!w.has(s)&&!k&&o("story-worktree-integration-dependency-waiting")}}function vt(e){const a=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",c=`int-${ne(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:c,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:a,integratedAt:e.integratedAt})}function Te(e){return ne(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Re(e){let a;return await ye(e.projectRoot,c=>{const d=F(c,e.epicId);we(d);const r=[...d].sort((i,f)=>f.integrationIndex-i.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&o("story-worktree-integration-chain-invalid"),[...d].filter(i=>i.storyId===e.storyId).sort((i,f)=>f.integrationIndex-i.integrationIndex)[0]?.outcome==="integrated"&&o("story-worktree-integration-already-integrated"),a=vt({epicId:e.epicId,storyId:e.storyId,index:d.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),ft(c,e.epicId,{receipts:[a]})},{preCommit:async()=>{await h(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&o("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await R(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&o("story-worktree-integration-epic-head-raced")}}),a}function pe(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:He(e.receipt)})}}async function St(e){let a,c,d="";const r=Se(e.projectRoot);try{(typeof e.storyId!="string"||!xe.test(e.storyId))&&o("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!mt.test(e.leaseId)&&o("story-worktree-integration-lease-invalid");const w=await ve(await h(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),i=await ve(await h(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));w!==i&&o("story-worktree-integration-not-root");let f;try{f=await Ge(r,e.storyId)}catch(l){o(l instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(l.message)?l.message:"story-worktree-integration-authority-invalid")}const{epicId:g,executionBranch:u,storyId:s}=f;d=g;const v=new Date(e.nowIso??Date.now()).toISOString(),k=`refs/heads/${u}`,p=await h(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing");await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p&&o("story-worktree-integration-root-head-mismatch");const _=f.originBinding;(!_||!await R(r,["merge-base","--is-ancestor",_.originHeadSha,p]))&&o("story-worktree-integration-origin-binding-invalid");const A=await Y(r,{required:!0}),S=F(A,g);we(S);const z=S.filter(l=>l.storyId===s).sort((l,b)=>b.integrationIndex-l.integrationIndex),E=A.stories[s]?.checkpoint;if(z[0]?.outcome==="integrated")return pe({storyId:s,epicId:g,outcome:"already-integrated",receipt:z[0],...E?.headSha?{checkpointHeadSha:E.headSha}:{}});const ce=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(l=>typeof l=="string"):[],T=await Ue(r,A);Fe(A,T,g,s,ce);const D=Object.values(A.storyWorktrees?.entries??{}).filter(l=>l.storyId===s&&l.epicId===g&&l.state==="active"&&(e.leaseId===void 0||l.leaseId===e.leaseId));if(E&&typeof E.headSha=="string"){const l=E.headSha,b=await h(r,["show","--no-patch","--format=%B",l],"story-worktree-integration-git-failed");(N(b,"Neocortex-Story")!==s||!N(b,he))&&o("story-worktree-integration-checkpoint-not-worktree"),l!==p&&o("story-worktree-integration-epic-head-raced"),se(S,E.baseSha);const X=await Ve(r,s,`recover-${l.slice(0,40)}`,()=>Re({projectRoot:r,epicId:g,storyId:s,executionBranch:u,before:E.baseSha,after:l,checkpointDigest:Te(E),outcome:"integrated",integratedAt:v})),oe=D.length===1?await Pe(r,D[0].leaseId,l):!1;return pe({storyId:s,epicId:g,outcome:"integrated",receipt:X,checkpointHeadSha:l,worktreeRealigned:oe})}const q=Object.values(A.storyWorktrees?.entries??{}).filter(l=>l.storyId===s&&l.epicId===g&&l.state==="active"&&(e.leaseId===void 0||l.leaseId===e.leaseId));q.length===0&&o("story-worktree-integration-lease-missing"),q.length>1&&o("story-worktree-integration-lease-ambiguous");const C=q[0];C.executionBranch!==u&&o("story-worktree-integration-lease-invalid");const M=await new Ae({projectRoot:r}).probe(C.leaseId);(!M.ok||M.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),M.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const ee=await h(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");M.value.headSha!==ee&&o("story-worktree-integration-worktree-dirty");const O=await h(r,["show","--no-patch","--format=%B",p],"story-worktree-integration-git-failed"),J=N(O,he)===ee&&N(O,"Neocortex-Story")===s;let x,P,m,K=!1;if(J){x=await h(r,["rev-parse",`${p}^`],"story-worktree-integration-git-failed"),P=p;const l=N(O,"Neocortex-Bundle-Digest")??"",b=N(O,"Neocortex-Claim-Revision")??"";m=Le({storyId:s,epicId:g,executionBranch:u,baseSha:x,bundleDigest:l,graphRevision:f.graphRevision,claimRevision:b}),se(S,x)}else{se(S,p);const l=await Je(r,f,s,p,ee);if(l.kind==="conflict")return await je({projectRoot:r,epicId:g,storyId:s,executionBranch:u,epicHead:p,tip:ee,conflictPaths:l.conflictPaths,integratedAt:v,chain:z});const b=l.changedPaths;P=l.commitSha,m=l.idempotencyKey,x=p,K=!0,(!await R(r,["diff","--cached","--quiet"])||!await R(r,["diff","--quiet","HEAD","--",...b]))&&o("story-worktree-integration-root-dirty")}const U=await Y(r,{required:!0}),B=U.epics[g]?.branch_lease,te=B&&B.ownerStoryId===s&&B.sessionId===m&&B.idempotencyKey===m&&Date.parse(String(B.expiresAt))>Date.now()?B:void 0;B&&!te&&Date.parse(String(B.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const W=te??{schemaVersion:1,ownerStoryId:s,sessionId:m,idempotencyKey:m,acquiredAt:v,expiresAt:new Date(Date.parse(v)+$e).toISOString()};a=await Ce(r,{kind:"direct",storyId:s,sessionId:m,idempotencyKey:m,expiresAt:String(W.expiresAt),persistent:!0,createdAt:String(W.acquiredAt)}),a.ok||o(a.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const $=a;te||(await ye(r,l=>{const b=be(l,g),X=b.branch_lease;X&&Date.parse(String(X.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(b.origin_binding)!==JSON.stringify(_)&&o("story-worktree-integration-origin-binding-invalid"),b.graph_revision!==f.graphRevision&&o("story-worktree-integration-graph-revision-raced"),b.branch_lease=W},{expectedRevision:U.revision,preCommit:async l=>{await Ye($.path,$.owner)||o("story-worktree-integration-lock-raced");const b=F(l,g);we(b),se(b,x),await h(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing")!==p&&o("story-worktree-integration-epic-head-raced")}}),c=W),K&&((await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p||await h(r,["rev-parse",k],"story-worktree-integration-git-failed")!==p)&&o("story-worktree-integration-epic-head-raced"),await R(r,["merge","--ff-only","--no-edit",P])||o("story-worktree-integration-ff-refused"),await h(r,["rev-parse",k],"story-worktree-integration-git-failed")!==P&&o("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let V;const re=await at({projectRoot:r,storyId:s,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const l=(await Y(r,{required:!0})).stories[s]?.checkpoint;(!l||l.headSha!==P||l.baseSha!==x)&&o("story-worktree-integration-checkpoint-mismatch"),V=await Re({projectRoot:r,epicId:g,storyId:s,executionBranch:u,before:x,after:P,checkpointDigest:Te(l),outcome:"integrated",integratedAt:v})}});if(!re.ok)return{ok:!1,reasonCode:re.reasonCode};const j=re.value;(j.headSha!==P||j.baseSha!==x||!V)&&o("story-worktree-integration-checkpoint-mismatch");const de=await Pe(r,C.leaseId,P);return pe({storyId:s,epicId:g,outcome:"integrated",receipt:V,checkpointHeadSha:P,worktreeRealigned:de})}catch(w){if(w instanceof _e)return{ok:!1,reasonCode:w.reasonCode};const i=w instanceof Error?w.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(i)?{ok:!1,reasonCode:i}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(a?.ok&&await Ee(a.path,a.owner).catch(()=>{}),c&&d){const w=c;await ye(r,i=>{const f=be(i,d),g=f.branch_lease;g&&g.sessionId===w.sessionId&&g.idempotencyKey===w.idempotencyKey&&g.acquiredAt===w.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}async function Je(e,a,c,d,r){const{epicId:w,executionBranch:i}=a;await R(e,["merge-base","--is-ancestor",r,d])&&o("story-worktree-integration-range-empty");const f=await h(e,["merge-base",d,r],"story-worktree-integration-unrelated-history"),g=await Z(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,d,r]);g.code!==0&&g.code!==1&&o("story-worktree-integration-git-unsupported");const u=g.stdout.split("\0"),s=u[0]?.trim()??"";if(Oe.test(s)||o("story-worktree-integration-git-unsupported"),g.code===1){const C=[...new Set(u.slice(1).filter(kt))].sort().slice(0,pt);return C.length===0&&o("story-worktree-integration-git-failed"),{kind:"conflict",conflictPaths:C}}const v=(await h(e,["diff","--name-only","-z",d,s],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),k=dt(v,a.authorizedWriteSet,c,a.rootMemoryEffect);k.ok||o(k.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":"story-worktree-integration-write-set-invalid");const p=yt(e,c,s);p?.verdict!=="approved"&&o("story-worktree-integration-review-not-approved");const _=await Z(e,["diff","--binary","--full-index",d,s]);_.code!==0&&o("story-worktree-integration-git-failed");const A=_.stdout;A||o("story-worktree-integration-range-empty");const S=ne(A),z=ne([...a.authorizedWriteSet].sort().join("\0")),E=Le({storyId:c,epicId:w,executionBranch:i,baseSha:d,bundleDigest:S,graphRevision:a.graphRevision,claimRevision:z}),ce=(await h(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${c}): integrate story worktree`,T=[`Neocortex-Story: ${c}`,`Neocortex-Epic: ${w}`,`Neocortex-Execution-Branch: ${i}`,`Neocortex-Prepared-Base: ${d}`,`Neocortex-Bundle-Digest: ${S}`,`Neocortex-Review-Artifact-Digest: ${p.digest}`,`Neocortex-Graph-Revision: ${a.graphRevision}`,`Neocortex-Claim-Revision: ${z}`,...a.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${ht(a.rootMemoryEffect)}`]:[],`${he}: ${r}`],D=(await h(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");D.length!==6&&o("story-worktree-integration-git-failed");const q=await h(e,["commit-tree",s,"-p",d,"-m",ce,"-m",`Story: ${c}`,"-m",T.join(`
|
|
3
|
-
`)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:D[0],GIT_AUTHOR_EMAIL:D[1],GIT_AUTHOR_DATE:D[2],GIT_COMMITTER_NAME:D[3],GIT_COMMITTER_EMAIL:D[4],GIT_COMMITTER_DATE:D[5]});return Oe.test(q)||o("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:q,changedPaths:v,idempotencyKey:E}}async function Ue(e,a){const c=JSON.parse(await tt(rt(e,".neocortex","state.json"),"utf8")),r=gt(c,a).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function Ve(e,a,c,d){const r=await Ce(e,{kind:"direct",storyId:a,sessionId:c,idempotencyKey:c,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||o(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await d()}finally{await Ee(r.path,r.owner).catch(()=>{})}}async function Pe(e,a,c){const d=await new Ae({projectRoot:e}).probe(a);return!d.ok||d.value.ownership!=="proven"||d.value.clean!==!0?!1:R(d.value.entry.worktreePath,["reset","--keep",c])}async function je(e){const a=ne(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),c=e.chain[0];if(c?.outcome==="conflict-reopened"&&c.epicHeadAfterSha===e.epicHead&&c.checkpointDigest===a)return pe({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:c,conflictPaths:Object.freeze([...e.conflictPaths])});const d=()=>Re({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:a,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await d():await Ve(e.projectRoot,e.storyId,`conflict-${a.slice(0,48)}`,d);return pe({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const bt=64;function At(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function Pt(e){let a,c,d="",r=0,w;const i=Se(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>bt||new Set(f).size!==f.length||f.some(t=>typeof t!="string"||!xe.test(t)))&&o("story-worktree-wave-stories-invalid");const g=await ve(await h(i,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await ve(await h(i,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==u&&o("story-worktree-integration-not-root");const s=new Map;for(const t of f)try{s.set(t,await Ge(i,t))}catch(n){o(n instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(n.message)?n.message:"story-worktree-integration-authority-invalid")}const v=s.get(f[0]),{epicId:k,executionBranch:p}=v;for(const t of s.values())(t.epicId!==k||t.executionBranch!==p||t.graphRevision!==v.graphRevision||JSON.stringify(t.originBinding)!==JSON.stringify(v.originBinding))&&o("story-worktree-wave-epic-mixed");d=k;const _=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${p}`,S=await h(i,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==S||await h(i,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==p)&&o("story-worktree-integration-root-head-mismatch");const z=v.originBinding;(!z||!await R(i,["merge-base","--is-ancestor",z.originHeadSha,S]))&&o("story-worktree-integration-origin-binding-invalid");const E=t=>{const n=s.get(t).story;return Array.isArray(n.depends_on)?n.depends_on.filter(y=>typeof y=="string"):[]},ce=new Map(f.map((t,n)=>[t,n]));f.forEach((t,n)=>{for(const y of E(t)){const I=ce.get(y);I!==void 0&&I>=n&&o("story-worktree-wave-order-invalid")}});const T=await Y(i,{required:!0}),D=F(T,k);we(D);const q=t=>D.filter(n=>n.storyId===t).sort((n,y)=>y.integrationIndex-n.integrationIndex)[0],C=f.filter(t=>q(t)?.outcome!=="integrated"),G=new Map(f.filter(t=>!C.includes(t)).map(t=>{const n=q(t),y=T.stories[t]?.checkpoint;return[t,Object.freeze({storyId:t,outcome:"already-integrated",receiptDigest:He(n),...y?.headSha?{checkpointHeadSha:y.headSha}:{}})]})),M=t=>({ok:!0,value:Object.freeze({epicId:k,...t,gateRuns:r,stories:Object.freeze(f.map(n=>G.get(n)??Object.freeze({storyId:n,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return M({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0});const ee=new Set(C),O=[];let J=S;for(let t=0;t<C.length;t++){const n=await h(i,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed"),y=N(n,"Neocortex-Story");if(!y||!ee.has(y)||!N(n,he))break;O.unshift(J),J=await h(i,["rev-parse",`${J}^`],"story-worktree-integration-git-failed")}const x=J;se(D,x);const P=await Ue(i,T),m=[];let K,U=x;for(const[t,n]of C.entries()){const y=s.get(n);Fe(T,P,k,n,E(n),new Set(C.slice(0,t)));const I=Object.values(T.storyWorktrees?.entries??{}).filter(L=>L.storyId===n&&L.epicId===k&&L.state==="active"),H=T.stories[n]?.checkpoint;if(H&&typeof H.headSha=="string"){const L=H.headSha,We=await h(i,["show","--no-patch","--format=%B",L],"story-worktree-integration-git-failed");(N(We,"Neocortex-Story")!==n||!N(We,he))&&o("story-worktree-integration-checkpoint-not-worktree"),(H.baseSha!==U||O[t]!==L)&&o("story-worktree-integration-checkpoint-mismatch");const Qe=(await h(i,["diff-tree","--no-commit-id","--name-only","-r","-z",L],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);m.push({storyId:n,sha:L,changedPaths:Qe,...I.length===1?{leaseId:I[0].leaseId}:{}}),U=L;continue}I.length===0&&o("story-worktree-integration-lease-missing"),I.length>1&&o("story-worktree-integration-lease-ambiguous");const ke=I[0];ke.executionBranch!==p&&o("story-worktree-integration-lease-invalid");const Ie=await new Ae({projectRoot:i}).probe(ke.leaseId);(!Ie.ok||Ie.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),Ie.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const De=await h(i,["rev-parse",`refs/heads/${ke.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Ie.value.headSha!==De&&o("story-worktree-integration-worktree-dirty");const ae=await Je(i,y,n,U,De);if(ae.kind==="conflict"){t<O.length&&o("story-worktree-wave-resume-mismatch"),K={storyId:n,tip:De,conflictPaths:ae.conflictPaths};break}t<O.length&&O[t]!==ae.commitSha&&o("story-worktree-wave-resume-mismatch"),m.push({storyId:n,sha:ae.commitSha,changedPaths:ae.changedPaths,leaseId:ke.leaseId}),U=ae.commitSha}if(m.length<O.length&&o("story-worktree-wave-resume-mismatch"),m.length===0){const t=K,n=await je({projectRoot:i,epicId:k,storyId:t.storyId,executionBranch:p,epicHead:S,tip:t.tip,conflictPaths:t.conflictPaths,integratedAt:_,chain:D.filter(y=>y.storyId===t.storyId).sort((y,I)=>I.integrationIndex-y.integrationIndex)});return n.ok?(G.set(t.storyId,Object.freeze({storyId:t.storyId,outcome:"conflict-reopened",receiptDigest:n.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...t.conflictPaths])})),M({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0})):{ok:!1,reasonCode:n.reasonCode,gateRuns:r}}const B=m[m.length-1].sha,te=[...new Set(m.flatMap(t=>t.changedPaths))].sort();(!await R(i,["diff","--cached","--quiet"])||!await R(i,["diff","--quiet","HEAD","--",...te]))&&o("story-worktree-integration-root-dirty");const W=At(m.length),$=ne(["p205-wave-lease-v1",k,p,x,...m.map(t=>t.sha)].join("\0")),V=m[0].storyId,re=await Y(i,{required:!0}),j=re.epics[k]?.branch_lease,de=j&&j.ownerStoryId===V&&j.sessionId===$&&j.idempotencyKey===$&&Date.parse(String(j.expiresAt))>Date.now()?j:void 0;j&&!de&&Date.parse(String(j.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const l=de??{schemaVersion:1,ownerStoryId:V,sessionId:$,idempotencyKey:$,acquiredAt:_,expiresAt:new Date(Date.parse(_)+$e*W).toISOString()};a=await Ce(i,{kind:"direct",storyId:V,sessionId:$,idempotencyKey:$,expiresAt:String(l.expiresAt),persistent:!0,createdAt:String(l.acquiredAt)}),a.ok||o(a.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const b=a;de||await ye(i,t=>{const n=be(t,k),y=n.branch_lease;y&&Date.parse(String(y.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(n.origin_binding)!==JSON.stringify(z)&&o("story-worktree-integration-origin-binding-invalid"),n.graph_revision!==v.graphRevision&&o("story-worktree-integration-graph-revision-raced"),n.branch_lease=l},{expectedRevision:re.revision,preCommit:async t=>{await Ye(b.path,b.owner)||o("story-worktree-integration-lock-raced");const n=F(t,k);we(n),se(n,x),await h(i,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==S&&o("story-worktree-integration-epic-head-raced")}}),c=l;const X=new Set(m.map(t=>t.sha));let oe=!0;if(e.push&&O.length>0){const t=(await Z(i,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";Oe.test(t)&&await R(i,["merge-base","--is-ancestor",O[0],t])&&(oe=!1)}let ie=S;const ue=async t=>{if((await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==ie||await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ie||await h(i,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==p)&&o("story-worktree-integration-epic-head-raced"),ie===t)return;const n=await R(i,["merge-base","--is-ancestor",ie,t]);!n&&(!oe||!X.has(ie))&&o("story-worktree-wave-pushed-immovable"),(!(n?await R(i,["merge","--ff-only","--no-edit",t]):await R(i,["reset","--keep",t]))||await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==t||await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==t)&&o("story-worktree-integration-ff-refused"),ie=t};w=oe?{epicRef:A,base:x,owned:X}:void 0,await ue(B),await e.afterWaveFastForward?.();const Xe=[...new Set([v.graphRevision,...m.map(t=>T.stories[t.storyId]?.checkpoint?.graphRevision).filter(t=>typeof t=="string")])],ze=async t=>{const n=m[t];await ue(n.sha),r>=W&&o("story-worktree-wave-gate-cap-exceeded"),r++;const y=await ct({projectRoot:i,headSha:n.sha,storyId:n.storyId,graphRevisions:Xe,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==n.sha||await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==n.sha||!await R(i,["diff","--cached","--quiet"])||!await R(i,["diff","--quiet","HEAD","--",...te]))&&o("story-worktree-integration-epic-head-raced"),!y.ok&&y.kind==="infrastructure"&&o(y.reasonCode),y},me=await ze(m.length-1);let Be=m.length-1,Ne=me.ok?me.authorities:void 0,fe,ge;if(!me.ok){oe||o("story-worktree-wave-gate-failed-pushed");let t=-1,n=m.length-1;for(ge=me.reasonCode;n-t>1;){const I=Math.floor((t+n)/2),H=await ze(I);H.ok?(t=I,Ne=H.authorities):(n=I,ge=H.reasonCode)}fe=n,Be=t;const y=m[n].storyId;if(G.set(y,Object.freeze({storyId:y,outcome:"gate-failed",reasonCode:ge})),t<0)return await ue(x),w=void 0,M({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:y,failureReasonCode:ge,epicHeadBeforeSha:S,epicHeadAfterSha:x,gateRunCap:W});await ue(m[t].sha)}const Q=m.slice(0,Be+1),le=Q[Q.length-1].sha,qe=it({epicId:k,executionBranch:p,waveHeadSha:le,waveStoryIds:Q.map(t=>t.storyId),waveCommitShas:Q.map(t=>t.sha)});e.push&&(w=void 0,await st(i,e.remote??"origin",p,le)||o("story-worktree-wave-remote-head-mismatch")),w=void 0;const Me=[];for(const[t,n]of Q.entries()){const y=t===0?x:Q[t-1].sha,I=await nt({projectRoot:i,storyId:n.storyId,headSha:n.sha,coverage:qe,authorities:Ne,expectedLease:l,physicalLock:b,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||o(I.reasonCode),(I.value.headSha!==n.sha||I.value.baseSha!==y)&&o("story-worktree-integration-checkpoint-mismatch");const H=await Re({projectRoot:i,epicId:k,storyId:n.storyId,executionBranch:p,before:y,after:n.sha,checkpointDigest:Te(I.value),outcome:"integrated",integratedAt:_,expectedEpicHead:le});Me.push(n.storyId),G.set(n.storyId,Object.freeze({storyId:n.storyId,outcome:"integrated",checkpointHeadSha:n.sha,receiptDigest:He(H)})),await e.afterWaveStoryPersist?.(n.storyId)}if(K&&fe===void 0){const t=K,n=await Y(i,{required:!0}),y=await je({projectRoot:i,epicId:k,storyId:t.storyId,executionBranch:p,epicHead:le,tip:t.tip,conflictPaths:t.conflictPaths,integratedAt:_,chain:F(n,k).filter(I=>I.storyId===t.storyId).sort((I,H)=>H.integrationIndex-I.integrationIndex),lockHeld:!0});y.ok||o(y.reasonCode),G.set(t.storyId,Object.freeze({storyId:t.storyId,outcome:"conflict-reopened",receiptDigest:y.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...t.conflictPaths])}))}for(const t of Q){if(!t.leaseId)continue;const n=await Pe(i,t.leaseId,t.sha);G.set(t.storyId,Object.freeze({...G.get(t.storyId),worktreeRealigned:n}))}return M({outcome:fe!==void 0?"gate-failed":K?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Me),...fe!==void 0?{failedStoryId:m[fe].storyId,failureReasonCode:ge}:{},epicHeadBeforeSha:S,epicHeadAfterSha:le,qaCoverage:qe,gateRunCap:W})}catch(f){let g=f instanceof _e?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(w){const u=w,s=(await Z(i,["rev-parse",u.epicRef])).stdout.trim(),v=(await Z(i,["rev-parse","HEAD"])).stdout.trim();s!==u.base&&(s!==v||!u.owned.has(s)||!await R(i,["reset","--keep",u.base]))&&(g="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:g,gateRuns:r}}finally{if(a?.ok&&await Ee(a.path,a.owner).catch(()=>{}),c&&d){const f=c;await ye(i,g=>{const u=be(g,d),s=u.branch_lease;s&&s.sessionId===f.sessionId&&s.idempotencyKey===f.idempotencyKey&&s.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function jt(e){const a=e.integrationOrder;if(!Array.isArray(a)||a.length===0||new Set(a).size!==a.length||a.some(g=>typeof g!="string"||!xe.test(g)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const c=e.integrate??St,d=new Set(e.readyStoryIds),r=Se(e.projectRoot);let w;try{const g=await Y(r,{required:!0}),u=new Set(a.map(s=>s.split(".")[0]));w=new Set([...u].flatMap(s=>F(g,s)).filter(s=>s.outcome==="integrated").map(s=>s.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const i=[],f=[];for(const g of a){if(w.has(g))continue;if(!d.has(g))return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:s,integrate:v,...k}=e,p=await c({...k,projectRoot:r,storyId:g});if(i.push({storyId:g,result:p}),!p.ok)return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:p.reasonCode};if(p.value.outcome==="conflict-reopened")return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:"integration-conflict-reopened"};f.push(g),w.add(g)}return{results:i,integratedStoryIds:f}}async function zt(e){const a=Se(e.projectRoot),c=e.manager??new Ae({projectRoot:a});let d;try{d=await Y(a,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const w of e.directives){const i=w&&typeof w=="object"&&!Array.isArray(w)?w:void 0,f=typeof i?.storyId=="string"&&xe.test(i.storyId)?i.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const g=Object.values(d.storyWorktrees?.entries??{}).filter(s=>s.storyId===f&&s.state==="active");if(g.length!==1){r.push({storyId:f,ok:!1,reasonCode:g.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await c.sync({leaseId:g[0].leaseId,directive:w});r.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return r}export{pt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,wt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,bt as STORY_WORKTREE_WAVE_MAX_STORIES,He as digestStoryWorktreeIntegrationReceipt,St as integrateStoryWorktree,Pt as integrateStoryWorktreeWave,jt as integrateStoryWorktreesInOrder,At as storyWorktreeWaveGateRunCap,zt as syncReleasedDependents};
|
|
1
|
+
import{execFile as Xe}from"node:child_process";import{createHash as wt}from"node:crypto";import{readFile as pt,realpath as be}from"node:fs/promises";import{join as ut,resolve as Ae}from"node:path";import{yoloopDomainHash as mt}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as Qe,directYoloCommitIdempotencyKey as Ze,directYoloWaveQaCoverage as kt,finalizeDirectYoloStoryCheckpoint as It,persistDirectYoloWaveStoryCheckpoint as vt,pushDirectYoloWaveHead as St,resolveDirectYoloIntegrationAuthority as et,runDirectYoloWaveP205 as bt,validateDirectYoloWriteSet as At}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Be,appendStoryWorktreeEvidence as xt,applyGitLifecycleRuntimeOverlay as Rt,ensureRuntimeEpic as xe,isStoryWorktreeIntegrationReceiptRecord as Et,mutateGitLifecycleRuntime as we,publicStoryReviewArtifactFromGit as _t,readGitLifecycleRuntime as U,readStoryWorktreeEvidence as tt,releaseGitLifecyclePhysicalIntegrationLock as je,verifyGitLifecyclePhysicalIntegrationLock as rt}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ot,STATE_JSON_FIELD_MERGE_MAX_BYTES as Tt}from"./state-json-field-merge.js";import{StoryWorktreeManager as Re}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as Ct}from"../private-execution/root-memory-git-evidence.js";const Dt="neocortex.p225.story-worktree-receipt.v1",Pt=200,pe="Neocortex-Story-Worktree-Tip",ot=3e4,ce=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Ht=/^swt-[a-f0-9]{24}$/,Ee=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class _e extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new _e(e)}const it=32*1024*1024;function P(e,t,s){return new Promise(a=>{Xe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:it,timeout:ot,env:{...process.env,...s,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,g)=>{const n=r?typeof r.code=="number"?r.code:128:0;a({code:n,stdout:String(g??"")})})})}function nt(e,t,s){return new Promise(a=>{const r=Xe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:it,timeout:ot,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(g,n)=>{const f=g?typeof g.code=="number"?g.code:128:0;a({code:f,stdout:String(n??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(s)})}async function p(e,t,s,a){const r=await P(e,t,a);return r.code!==0&&i(s),r.stdout.trim()}async function O(e,t){return(await P(e,t)).code===0}function de(e){return wt("sha256").update(e).digest("hex")}function at(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function q(e,t){const s=`${t}: `,a=e.split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r.startsWith(s));return a.length===1?a[0].slice(s.length):void 0}function Ne(e){return mt(Dt,e)}function V(e,t){return(tt(e,t)?.receipts??[]).filter(Et)}function ue(e){const t=[...e].sort((s,a)=>s.integrationIndex-a.integrationIndex);t.forEach((s,a)=>{(s.integrationIndex!==a+1||a>0&&s.epicHeadBeforeSha!==t[a-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function fe(e,t){const s=[...e].sort((a,r)=>r.integrationIndex-a.integrationIndex)[0];s&&s.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const Bt=new Set(["done","merged","completed","released"]);function st(e,t,s,a,r,g=new Set){(tt(e,s)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===a||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(a))||i("story-worktree-integration-unbound");const u=new Set(V(e,s).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of r){if(!d.startsWith(`${s}.`))continue;const S=t[d],m=!!e.stories[d]?.checkpoint||typeof S?.status=="string"&&Bt.has(S.status);!u.has(d)&&!g.has(d)&&!m&&i("story-worktree-integration-dependency-waiting")}}function jt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",s=`int-${de(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:s,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function ze(e){return de(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Oe(e){let t;return await we(e.projectRoot,s=>{const a=V(s,e.epicId);ue(a);const r=[...a].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...a].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=jt({epicId:e.epicId,storyId:e.storyId,index:a.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),xt(s,e.epicId,{receipts:[t]})},{preCommit:async()=>{await p(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await O(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&i("story-worktree-integration-epic-head-raced")}}),t}function me(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:Ne(e.receipt)})}}async function Nt(e){let t,s,a="";const r=Ae(e.projectRoot);try{(typeof e.storyId!="string"||!Ee.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!Ht.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const g=await be(await p(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await be(await p(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==n&&i("story-worktree-integration-not-root");let f;try{f=await et(r,e.storyId)}catch(y){i(y instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(y.message)?y.message:"story-worktree-integration-authority-invalid")}const{epicId:l,executionBranch:u,storyId:d}=f;a=l;const S=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,h=await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==h&&i("story-worktree-integration-root-head-mismatch");const D=f.originBinding;(!D||!await O(r,["merge-base","--is-ancestor",D.originHeadSha,h]))&&i("story-worktree-integration-origin-binding-invalid");const b=await U(r,{required:!0}),I=V(b,l);ue(I);const H=I.filter(y=>y.storyId===d).sort((y,x)=>x.integrationIndex-y.integrationIndex),A=b.stories[d]?.checkpoint;if(H[0]?.outcome==="integrated")return me({storyId:d,epicId:l,outcome:"already-integrated",receipt:H[0],...A?.headSha?{checkpointHeadSha:A.headSha}:{}});const G=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(y=>typeof y=="string"):[],R=await ft(r,b);st(b,R,l,d,G);const j=Object.values(b.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));if(A&&typeof A.headSha=="string"){const y=A.headSha,x=await p(r,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed");(q(x,"Neocortex-Story")!==d||!q(x,pe))&&i("story-worktree-integration-checkpoint-not-worktree"),y!==h&&i("story-worktree-integration-epic-head-raced"),fe(I,A.baseSha);const ee=await lt(r,d,`recover-${y.slice(0,40)}`,()=>Oe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:A.baseSha,after:y,checkpointDigest:ze(A),outcome:"integrated",integratedAt:S})),ne=j.length===1?await $e(r,j[0].leaseId,y):!1;return me({storyId:d,epicId:l,outcome:"integrated",receipt:ee,checkpointHeadSha:y,worktreeRealigned:ne})}const N=Object.values(b.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));N.length===0&&i("story-worktree-integration-lease-missing"),N.length>1&&i("story-worktree-integration-lease-ambiguous");const C=N[0];C.executionBranch!==u&&i("story-worktree-integration-lease-invalid");const E=await new Re({projectRoot:r}).probe(C.leaseId);(!E.ok||E.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),E.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const re=await p(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");E.value.headSha!==re&&i("story-worktree-integration-worktree-dirty");const B=await p(r,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed"),X=q(B,pe)===re&&q(B,"Neocortex-Story")===d;let _,M,k,J=!1;if(X){_=await p(r,["rev-parse",`${h}^`],"story-worktree-integration-git-failed"),M=h;const y=q(B,"Neocortex-Bundle-Digest")??"",x=q(B,"Neocortex-Claim-Revision")??"";k=Ze({storyId:d,epicId:l,executionBranch:u,baseSha:_,bundleDigest:y,graphRevision:f.graphRevision,claimRevision:x}),fe(I,_)}else{fe(I,h);const y=await dt(r,f,d,h,re);if(y.kind==="conflict")return await qe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,epicHead:h,tip:re,conflictPaths:y.conflictPaths,integratedAt:S,chain:H});const x=y.changedPaths;M=y.commitSha,k=y.idempotencyKey,_=h,J=!0,(!await O(r,["diff","--cached","--quiet"])||!await O(r,["diff","--quiet","HEAD","--",...x]))&&i("story-worktree-integration-root-dirty")}const Q=await U(r,{required:!0}),$=Q.epics[l]?.branch_lease,oe=$&&$.ownerStoryId===d&&$.sessionId===k&&$.idempotencyKey===k&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!oe&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const K=oe??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:S,expiresAt:new Date(Date.parse(S)+Qe).toISOString()};t=await Be(r,{kind:"direct",storyId:d,sessionId:k,idempotencyKey:k,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;oe||(await we(r,y=>{const x=xe(y,l),ee=x.branch_lease;ee&&Date.parse(String(ee.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(x.origin_binding)!==JSON.stringify(D)&&i("story-worktree-integration-origin-binding-invalid"),x.graph_revision!==f.graphRevision&&i("story-worktree-integration-graph-revision-raced"),x.branch_lease=K},{expectedRevision:Q.revision,preCommit:async y=>{await rt(Y.path,Y.owner)||i("story-worktree-integration-lock-raced");const x=V(y,l);ue(x),fe(x,_),await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==h&&i("story-worktree-integration-epic-head-raced")}}),s=K),J&&((await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==h||await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==h)&&i("story-worktree-integration-epic-head-raced"),await O(r,["merge","--ff-only","--no-edit",M])||i("story-worktree-integration-ff-refused"),await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==M&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let Z;const ie=await It({projectRoot:r,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const y=(await U(r,{required:!0})).stories[d]?.checkpoint;(!y||y.headSha!==M||y.baseSha!==_)&&i("story-worktree-integration-checkpoint-mismatch"),Z=await Oe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:_,after:M,checkpointDigest:ze(y),outcome:"integrated",integratedAt:S})}});if(!ie.ok)return{ok:!1,reasonCode:ie.reasonCode};const L=ie.value;(L.headSha!==M||L.baseSha!==_||!Z)&&i("story-worktree-integration-checkpoint-mismatch");const le=await $e(r,C.leaseId,M);return me({storyId:d,epicId:l,outcome:"integrated",receipt:Z,checkpointHeadSha:M,worktreeRealigned:le})}catch(g){if(g instanceof _e)return{ok:!1,reasonCode:g.reasonCode};const n=g instanceof Error?g.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),s&&a){const g=s;await we(r,n=>{const f=xe(n,a),l=f.branch_lease;l&&l.sessionId===g.sessionId&&l.idempotencyKey===g.idempotencyKey&&l.acquiredAt===g.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const We=".neocortex/state.json",Te=".neocortex",Ce="state.json",W="story-worktree-integration-state-merge-git-failed";function De(e){const t=[];for(const s of e.split("\0")){if(!s)continue;const a=s.indexOf(" "),[r,g,n]=s.slice(0,a).split(" ");(a<0||!r||!g||!n)&&i(W),t.push({mode:r,type:g,oid:n,name:s.slice(a+1)})}return t}function zt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function ct(e,t,s,a){const r=await P(e,["ls-tree","-z",t]);r.code!==0&&i(W);const g=De(r.stdout).filter(l=>l.name!==s),n=await nt(e,["mktree","-z"],zt([...g,a])),f=n.stdout.trim();return(n.code!==0||!ce.test(f))&&i(W),f}async function Me(e,t){const s=await P(e,["ls-tree","-z",t,"--",We]);s.code!==0&&i(W);const a=De(s.stdout).find(r=>r.name===We);return a?((a.type!=="blob"||a.mode!=="100644"&&a.mode!=="100755")&&i("state-merge-input-invalid"),ce.test(a.oid)||i(W),a.oid):null}async function Le(e,t){t===null&&i("state-merge-input-invalid");const s=await P(e,["cat-file","-s",t]),a=Number.parseInt(s.stdout.trim(),10);(s.code!==0||!Number.isSafeInteger(a)||a<0||a>Tt)&&i(W);const r=await P(e,["cat-file","blob",t]);return r.code!==0&&i(W),r.stdout}async function Wt(e){try{const{projectRoot:t,mergeBase:s,epicHead:a,tip:r,tree:g,storyId:n,epicId:f}=e,l={ok:!0,tree:g,conflictPaths:[...e.conflictPaths],merged:!1},u=await Me(t,s),d=await Me(t,r);if(u===d)return l;const S=await Le(t,u),m=await Le(t,await Me(t,a)),h=await Le(t,d),D=await p(t,["show","--no-patch","--format=%cI",r],W),b=Ot({base:S,epic:m,story:h,storyId:n,epicId:f,aggregateTimestamp:D});if(!b.ok)return{ok:!1,reasonCode:b.reasonCode};const I=e.conflictPaths.filter(E=>E!==We),H=await P(t,["ls-tree","-z",g,"--",Te]);H.code!==0&&i(W);const A=De(H.stdout).find(E=>E.name===Te);if(!A||A.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const G=await P(t,["ls-tree","-z",A.oid,"--",Ce]);G.code!==0&&i(W);const R=De(G.stdout).find(E=>E.name===Ce);if(R&&(R.type!=="blob"||R.mode!=="100644"&&R.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const j=await nt(t,["hash-object","-w","--stdin"],b.bytes),N=j.stdout.trim();if((j.code!==0||!ce.test(N))&&i(W),R?.oid===N)return{ok:!0,tree:g,conflictPaths:I,merged:!0};const C=await ct(t,A.oid,Ce,{mode:R?.mode??"100644",type:"blob",oid:N,name:Ce});return{ok:!0,tree:await ct(t,g,Te,{mode:A.mode,type:"tree",oid:C,name:Te}),conflictPaths:I,merged:!0}}catch(t){return t instanceof _e?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:W}}}async function dt(e,t,s,a,r){const{epicId:g,executionBranch:n}=t;await O(e,["merge-base","--is-ancestor",r,a])&&i("story-worktree-integration-range-empty");const f=await p(e,["merge-base",a,r],"story-worktree-integration-unrelated-history"),l=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,a,r]);l.code!==0&&l.code!==1&&i("story-worktree-integration-git-unsupported");const u=l.stdout.split("\0"),d=u[0]?.trim()??"";ce.test(d)||i("story-worktree-integration-git-unsupported");const S=l.code===1?[...new Set(u.slice(1).filter(at))].sort():[];l.code===1&&S.length===0&&i("story-worktree-integration-git-failed");const m=await Wt({projectRoot:e,mergeBase:f,epicHead:a,tip:r,tree:d,storyId:s,epicId:g,conflictPaths:S});m.ok||i(m.reasonCode);const h=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,Pt)};const D=(await p(e,["diff","--name-only","-z",a,h],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),b=At(D,t.authorizedWriteSet,s,t.rootMemoryEffect);b.ok||i(b.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":"story-worktree-integration-write-set-invalid");const I=_t(e,s,h);I?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const H=await P(e,["diff","--binary","--full-index",a,h]);H.code!==0&&i("story-worktree-integration-git-failed");const A=H.stdout;A||i("story-worktree-integration-range-empty");const G=de(A),R=de([...t.authorizedWriteSet].sort().join("\0")),j=Ze({storyId:s,epicId:g,executionBranch:n,baseSha:a,bundleDigest:G,graphRevision:t.graphRevision,claimRevision:R}),N=(await p(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${s}): integrate story worktree`,C=[`Neocortex-Story: ${s}`,`Neocortex-Epic: ${g}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${a}`,`Neocortex-Bundle-Digest: ${G}`,`Neocortex-Review-Artifact-Digest: ${I.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${R}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Ct(t.rootMemoryEffect)}`]:[],`${pe}: ${r}`],T=(await p(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");T.length!==6&&i("story-worktree-integration-git-failed");const E=await p(e,["commit-tree",h,"-p",a,"-m",N,"-m",`Story: ${s}`,"-m",C.join(`
|
|
3
|
+
`)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:T[0],GIT_AUTHOR_EMAIL:T[1],GIT_AUTHOR_DATE:T[2],GIT_COMMITTER_NAME:T[3],GIT_COMMITTER_EMAIL:T[4],GIT_COMMITTER_DATE:T[5]});return ce.test(E)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:E,changedPaths:D,idempotencyKey:j}}async function ft(e,t){const s=JSON.parse(await pt(ut(e,".neocortex","state.json"),"utf8")),r=Rt(s,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function lt(e,t,s,a){const r=await Be(e,{kind:"direct",storyId:t,sessionId:s,idempotencyKey:s,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||i(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await a()}finally{await je(r.path,r.owner).catch(()=>{})}}async function $e(e,t,s){const a=await new Re({projectRoot:e}).probe(t);return!a.ok||a.value.ownership!=="proven"||a.value.clean!==!0?!1:O(a.value.entry.worktreePath,["reset","--keep",s])}async function qe(e){const t=de(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),s=e.chain[0];if(s?.outcome==="conflict-reopened"&&s.epicHeadAfterSha===e.epicHead&&s.checkpointDigest===t)return me({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:s,conflictPaths:Object.freeze([...e.conflictPaths])});const a=()=>Oe({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await a():await lt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,a);return me({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Mt=64,Lt="@ornexus/neocortex",Ge=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Ge)if(!at(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function $t(e){return O(e,["clean","-X","-f","-q","--",...Ge])}async function qt(e,t){const s=await P(e,["show",`${t}:package.json`]);if(s.code!==0)return[];try{return JSON.parse(s.stdout)?.name===Lt?Ge:[]}catch{return[]}}function Gt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function tr(e){let t,s,a="",r=0,g;const n=Ae(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Mt||new Set(f).size!==f.length||f.some(o=>typeof o!="string"||!Ee.test(o)))&&i("story-worktree-wave-stories-invalid");const l=await be(await p(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await be(await p(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==u&&i("story-worktree-integration-not-root");const d=new Map;for(const o of f)try{d.set(o,await et(n,o))}catch(c){i(c instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(c.message)?c.message:"story-worktree-integration-authority-invalid")}const S=d.get(f[0]),{epicId:m,executionBranch:h}=S;for(const o of d.values())(o.epicId!==m||o.executionBranch!==h||o.graphRevision!==S.graphRevision||JSON.stringify(o.originBinding)!==JSON.stringify(S.originBinding))&&i("story-worktree-wave-epic-mixed");a=m;const D=new Date(e.nowIso??Date.now()).toISOString(),b=`refs/heads/${h}`,I=await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing");(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==I||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==h)&&i("story-worktree-integration-root-head-mismatch");const H=S.originBinding;(!H||!await O(n,["merge-base","--is-ancestor",H.originHeadSha,I]))&&i("story-worktree-integration-origin-binding-invalid");const A=o=>{const c=d.get(o).story;return Array.isArray(c.depends_on)?c.depends_on.filter(w=>typeof w=="string"):[]},G=new Map(f.map((o,c)=>[o,c]));f.forEach((o,c)=>{for(const w of A(o)){const v=G.get(w);v!==void 0&&v>=c&&i("story-worktree-wave-order-invalid")}});const R=await U(n,{required:!0}),j=V(R,m);ue(j);const N=o=>j.filter(c=>c.storyId===o).sort((c,w)=>w.integrationIndex-c.integrationIndex)[0],C=f.filter(o=>N(o)?.outcome!=="integrated"),T=new Map(f.filter(o=>!C.includes(o)).map(o=>{const c=N(o),w=R.stories[o]?.checkpoint;return[o,Object.freeze({storyId:o,outcome:"already-integrated",receiptDigest:Ne(c),...w?.headSha?{checkpointHeadSha:w.headSha}:{}})]})),E=o=>({ok:!0,value:Object.freeze({epicId:m,...o,gateRuns:r,stories:Object.freeze(f.map(c=>T.get(c)??Object.freeze({storyId:c,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return E({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0});const re=new Set(C),B=[];let X=I;for(let o=0;o<C.length;o++){const c=await p(n,["show","--no-patch","--format=%B",X],"story-worktree-integration-git-failed"),w=q(c,"Neocortex-Story");if(!w||!re.has(w)||!q(c,pe))break;B.unshift(X),X=await p(n,["rev-parse",`${X}^`],"story-worktree-integration-git-failed")}const _=X;fe(j,_);const M=await ft(n,R),k=[];let J,Q=_;for(const[o,c]of C.entries()){const w=d.get(c);st(R,M,m,c,A(c),new Set(C.slice(0,o)));const v=Object.values(R.storyWorktrees?.entries??{}).filter(F=>F.storyId===c&&F.epicId===m&&F.state==="active"),z=R.stories[c]?.checkpoint;if(z&&typeof z.headSha=="string"){const F=z.headSha,Ve=await p(n,["show","--no-patch","--format=%B",F],"story-worktree-integration-git-failed");(q(Ve,"Neocortex-Story")!==c||!q(Ve,pe))&&i("story-worktree-integration-checkpoint-not-worktree"),(z.baseSha!==Q||B[o]!==F)&&i("story-worktree-integration-checkpoint-mismatch");const ht=(await p(n,["diff-tree","--no-commit-id","--name-only","-r","-z",F],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:c,sha:F,changedPaths:ht,...v.length===1?{leaseId:v[0].leaseId}:{}}),Q=F;continue}v.length===0&&i("story-worktree-integration-lease-missing"),v.length>1&&i("story-worktree-integration-lease-ambiguous");const ve=v[0];ve.executionBranch!==h&&i("story-worktree-integration-lease-invalid");const Se=await new Re({projectRoot:n}).probe(ve.leaseId);(!Se.ok||Se.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Se.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const He=await p(n,["rev-parse",`refs/heads/${ve.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Se.value.headSha!==He&&i("story-worktree-integration-worktree-dirty");const se=await dt(n,w,c,Q,He);if(se.kind==="conflict"){o<B.length&&i("story-worktree-wave-resume-mismatch"),J={storyId:c,tip:He,conflictPaths:se.conflictPaths};break}o<B.length&&B[o]!==se.commitSha&&i("story-worktree-wave-resume-mismatch"),k.push({storyId:c,sha:se.commitSha,changedPaths:se.changedPaths,leaseId:ve.leaseId}),Q=se.commitSha}if(k.length<B.length&&i("story-worktree-wave-resume-mismatch"),k.length===0){const o=J,c=await qe({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:h,epicHead:I,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:D,chain:j.filter(w=>w.storyId===o.storyId).sort((w,v)=>v.integrationIndex-w.integrationIndex)});return c.ok?(T.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:c.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])})),E({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0})):{ok:!1,reasonCode:c.reasonCode,gateRuns:r}}const $=k[k.length-1].sha,oe=[...new Set(k.flatMap(o=>o.changedPaths))].sort();(!await O(n,["diff","--cached","--quiet"])||!await O(n,["diff","--quiet","HEAD","--",...oe]))&&i("story-worktree-integration-root-dirty");const K=Gt(k.length),Y=de(["p205-wave-lease-v1",m,h,_,...k.map(o=>o.sha)].join("\0")),Z=k[0].storyId,ie=await U(n,{required:!0}),L=ie.epics[m]?.branch_lease,le=L&&L.ownerStoryId===Z&&L.sessionId===Y&&L.idempotencyKey===Y&&Date.parse(String(L.expiresAt))>Date.now()?L:void 0;L&&!le&&Date.parse(String(L.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const y=le??{schemaVersion:1,ownerStoryId:Z,sessionId:Y,idempotencyKey:Y,acquiredAt:D,expiresAt:new Date(Date.parse(D)+Qe*K).toISOString()};t=await Be(n,{kind:"direct",storyId:Z,sessionId:Y,idempotencyKey:Y,expiresAt:String(y.expiresAt),persistent:!0,createdAt:String(y.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const x=t;le||await we(n,o=>{const c=xe(o,m),w=c.branch_lease;w&&Date.parse(String(w.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(c.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),c.graph_revision!==S.graphRevision&&i("story-worktree-integration-graph-revision-raced"),c.branch_lease=y},{expectedRevision:ie.revision,preCommit:async o=>{await rt(x.path,x.owner)||i("story-worktree-integration-lock-raced");const c=V(o,m);ue(c),fe(c,_),await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing")!==I&&i("story-worktree-integration-epic-head-raced")}}),s=y;const ee=new Set(k.map(o=>o.sha));let ne=!0;if(e.push&&B.length>0){const o=(await P(n,["ls-remote","--heads",e.remote??"origin",b])).stdout.split(/\s+/)[0]??"";ce.test(o)&&await O(n,["merge-base","--is-ancestor",B[0],o])&&(ne=!1)}let ae=I;const ke=async o=>{if((await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==ae||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ae||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==h)&&i("story-worktree-integration-epic-head-raced"),ae===o)return;const c=await O(n,["merge-base","--is-ancestor",ae,o]);!c&&(!ne||!ee.has(ae))&&i("story-worktree-wave-pushed-immovable"),(!(c?await O(n,["merge","--ff-only","--no-edit",o]):await O(n,["reset","--keep",o]))||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==o||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==o)&&i("story-worktree-integration-ff-refused"),ae=o};g=ne?{epicRef:b,base:_,owned:ee}:void 0,await ke($),await e.afterWaveFastForward?.();const gt=[...new Set([S.graphRevision,...k.map(o=>R.stories[o.storyId]?.checkpoint?.graphRevision).filter(o=>typeof o=="string")])],yt=await qt(n,_),Pe=async()=>{yt.length!==0&&(await(e.cleanBuildOutputs??$t)(n)||i("story-worktree-wave-clean-failed"))},Ke=async o=>{const c=k[o];await ke(c.sha),r>=K&&i("story-worktree-wave-gate-cap-exceeded"),r>0&&await Pe(),r++;const w=await bt({projectRoot:n,headSha:c.sha,storyId:c.storyId,graphRevisions:gt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==c.sha||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==c.sha||!await O(n,["diff","--cached","--quiet"])||!await O(n,["diff","--quiet","HEAD","--",...oe]))&&i("story-worktree-integration-epic-head-raced"),!w.ok&&w.kind==="infrastructure"&&i(w.reasonCode),w},Ie=await Ke(k.length-1);let Ye=k.length-1,Fe=Ie.ok?Ie.authorities:void 0,ge,ye;if(!Ie.ok){ne||i("story-worktree-wave-gate-failed-pushed");let o=-1,c=k.length-1;for(ye=Ie.reasonCode;c-o>1;){const v=Math.floor((o+c)/2),z=await Ke(v);z.ok?(o=v,Fe=z.authorities):(c=v,ye=z.reasonCode)}ge=c,Ye=o;const w=k[c].storyId;if(T.set(w,Object.freeze({storyId:w,outcome:"gate-failed",reasonCode:ye})),o<0)return await ke(_),await Pe(),g=void 0,E({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:w,failureReasonCode:ye,epicHeadBeforeSha:I,epicHeadAfterSha:_,gateRunCap:K});await ke(k[o].sha),await Pe()}const te=k.slice(0,Ye+1),he=te[te.length-1].sha,Je=kt({epicId:m,executionBranch:h,waveHeadSha:he,waveStoryIds:te.map(o=>o.storyId),waveCommitShas:te.map(o=>o.sha)});e.push&&(g=void 0,await St(n,e.remote??"origin",h,he)||i("story-worktree-wave-remote-head-mismatch")),g=void 0;const Ue=[];for(const[o,c]of te.entries()){const w=o===0?_:te[o-1].sha,v=await vt({projectRoot:n,storyId:c.storyId,headSha:c.sha,coverage:Je,authorities:Fe,expectedLease:y,physicalLock:x,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});v.ok||i(v.reasonCode),(v.value.headSha!==c.sha||v.value.baseSha!==w)&&i("story-worktree-integration-checkpoint-mismatch");const z=await Oe({projectRoot:n,epicId:m,storyId:c.storyId,executionBranch:h,before:w,after:c.sha,checkpointDigest:ze(v.value),outcome:"integrated",integratedAt:D,expectedEpicHead:he});Ue.push(c.storyId),T.set(c.storyId,Object.freeze({storyId:c.storyId,outcome:"integrated",checkpointHeadSha:c.sha,receiptDigest:Ne(z)})),await e.afterWaveStoryPersist?.(c.storyId)}if(J&&ge===void 0){const o=J,c=await U(n,{required:!0}),w=await qe({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:h,epicHead:he,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:D,chain:V(c,m).filter(v=>v.storyId===o.storyId).sort((v,z)=>z.integrationIndex-v.integrationIndex),lockHeld:!0});w.ok||i(w.reasonCode),T.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:w.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])}))}for(const o of te){if(!o.leaseId)continue;const c=await $e(n,o.leaseId,o.sha);T.set(o.storyId,Object.freeze({...T.get(o.storyId),worktreeRealigned:c}))}return E({outcome:ge!==void 0?"gate-failed":J?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ue),...ge!==void 0?{failedStoryId:k[ge].storyId,failureReasonCode:ye}:{},epicHeadBeforeSha:I,epicHeadAfterSha:he,qaCoverage:Je,gateRunCap:K})}catch(f){let l=f instanceof _e?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(g){const u=g,d=(await P(n,["rev-parse",u.epicRef])).stdout.trim(),S=(await P(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==S||!u.owned.has(d)||!await O(n,["reset","--keep",u.base]))&&(l="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:l,gateRuns:r}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),s&&a){const f=s;await we(n,l=>{const u=xe(l,a),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function rr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(l=>typeof l!="string"||!Ee.test(l)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const s=e.integrate??Nt,a=new Set(e.readyStoryIds),r=Ae(e.projectRoot);let g;try{const l=await U(r,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));g=new Set([...u].flatMap(d=>V(l,d)).filter(d=>d.outcome==="integrated").map(d=>d.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const n=[],f=[];for(const l of t){if(g.has(l))continue;if(!a.has(l))return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:S,...m}=e,h=await s({...m,projectRoot:r,storyId:l});if(n.push({storyId:l,result:h}),!h.ok)return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:h.reasonCode};if(h.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"integration-conflict-reopened"};f.push(l),g.add(l)}return{results:n,integratedStoryIds:f}}async function or(e){const t=Ae(e.projectRoot),s=e.manager??new Re({projectRoot:t});let a;try{a=await U(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const g of e.directives){const n=g&&typeof g=="object"&&!Array.isArray(g)?g:void 0,f=typeof n?.storyId=="string"&&Ee.test(n.storyId)?n.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const l=Object.values(a.storyWorktrees?.entries??{}).filter(d=>d.storyId===f&&d.state==="active");if(l.length!==1){r.push({storyId:f,ok:!1,reasonCode:l.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await s.sync({leaseId:l[0].leaseId,directive:g});r.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return r}export{Pt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,Dt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,We as STORY_WORKTREE_STATE_JSON_PATH,Ge as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Lt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Mt as STORY_WORKTREE_WAVE_MAX_STORIES,Ne as digestStoryWorktreeIntegrationReceipt,Nt as integrateStoryWorktree,tr as integrateStoryWorktreeWave,rr as integrateStoryWorktreesInOrder,Wt as resolveStoryWorktreeStateJsonMerge,qt as storyWorktreeWaveBuildOutputPaths,Gt as storyWorktreeWaveGateRunCap,or as syncReleasedDependents};
|