@ornexus/neocortex 4.60.74 → 4.60.75

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.
Files changed (55) hide show
  1. package/dist/release-source.json +1 -1
  2. package/install.ps1 +1 -1
  3. package/install.sh +1 -1
  4. package/package.json +2 -2
  5. package/packages/client/dist/cache/encrypted-cache.d.ts +27 -0
  6. package/packages/client/dist/cache/encrypted-cache.js +1 -1
  7. package/packages/client/dist/commands/invoke.d.ts +38 -1
  8. package/packages/client/dist/commands/invoke.js +79 -79
  9. package/packages/client/dist/config/host-auth-broker.d.ts +31 -0
  10. package/packages/client/dist/config/host-auth-broker.js +1 -0
  11. package/packages/client/dist/config/host-auth-reference.d.ts +32 -0
  12. package/packages/client/dist/config/host-auth-reference.js +1 -0
  13. package/packages/client/dist/config/secure-config.js +1 -1
  14. package/packages/client/dist/continuity/native-agent-types.d.ts +11 -0
  15. package/packages/client/dist/continuity/native-agent-types.js +1 -1
  16. package/packages/client/dist/errors/error-messages.d.ts +3 -0
  17. package/packages/client/dist/errors/error-messages.js +2 -2
  18. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +11 -1
  19. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  20. package/packages/client/dist/index.d.ts +2 -0
  21. package/packages/client/dist/index.js +1 -1
  22. package/packages/client/dist/license/host-auth-recovery.d.ts +158 -0
  23. package/packages/client/dist/license/host-auth-recovery.js +1 -0
  24. package/packages/client/dist/license/license-client.d.ts +10 -1
  25. package/packages/client/dist/license/license-client.js +1 -1
  26. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +61 -0
  27. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -0
  28. package/packages/client/dist/runner/headless/background-root.d.ts +65 -0
  29. package/packages/client/dist/runner/headless/background-root.js +1 -0
  30. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +9 -0
  31. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -2
  32. package/packages/client/dist/runner/headless/managed-environment-cleanup.d.ts +95 -0
  33. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -0
  34. package/packages/client/dist/state/project-state-snapshot.d.ts +7 -0
  35. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  36. package/packages/client/dist/yolo/change-evidence-collector.d.ts +21 -1
  37. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  38. package/packages/shared/dist/invocation/explicit-intent-recovery.d.ts +83 -0
  39. package/packages/shared/dist/invocation/explicit-intent-recovery.js +187 -0
  40. package/packages/shared/dist/invocation/index.d.ts +7 -0
  41. package/packages/shared/dist/invocation/index.js +22 -0
  42. package/targets-stubs/antigravity/gemini.md +1 -1
  43. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  44. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  45. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  46. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  47. package/targets-stubs/claude-code/neocortex.md +2 -2
  48. package/targets-stubs/codex/AGENTS.md +24 -21
  49. package/targets-stubs/codex/README.md +6 -1
  50. package/targets-stubs/codex/neocortex.toml +7 -2
  51. package/targets-stubs/cursor/agent.md +2 -2
  52. package/targets-stubs/gemini-cli/agent.md +2 -2
  53. package/targets-stubs/opencode/neocortex-root.md +16 -1
  54. package/targets-stubs/opencode/neocortex.md +6 -0
  55. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -0,0 +1,31 @@
1
+ import { type HostAuthOperation, type HostAuthReferenceV1 } from './host-auth-reference.js';
2
+ export interface HostAuthPublicResult {
3
+ readonly status: 'available' | 'unavailable' | 'denied';
4
+ readonly reasonCode: string;
5
+ readonly generation?: number;
6
+ readonly expiresAt?: string;
7
+ }
8
+ export interface HostAuthAdapter {
9
+ readonly provider: 'codex' | 'opencode';
10
+ readonly target: string;
11
+ readonly operations: Readonly<Partial<Record<HostAuthOperation, (reference: HostAuthReferenceV1) => Promise<HostAuthPublicResult>>>>;
12
+ }
13
+ export interface HostAuthBrokerRequest {
14
+ readonly capability: object;
15
+ readonly reference: unknown;
16
+ readonly caller: 'host-runtime';
17
+ readonly expectedSubjectDigest: string;
18
+ readonly expectedPolicyDigest: string;
19
+ readonly expectedDispatchDigest: string;
20
+ readonly requiredScopes: readonly string[];
21
+ readonly minimumRevocationEpoch: number;
22
+ }
23
+ export interface HostAuthBroker {
24
+ execute(request: HostAuthBrokerRequest): Promise<HostAuthPublicResult>;
25
+ }
26
+ export interface HostAuthBrokerHandle {
27
+ readonly broker: HostAuthBroker;
28
+ /** Process-local authority. Never serialize or pass this object to a child. */
29
+ readonly capability: object;
30
+ }
31
+ export declare function createHostAuthBroker(adapter?: HostAuthAdapter): HostAuthBrokerHandle;
@@ -0,0 +1 @@
1
+ import{timingSafeEqual as f}from"node:crypto";import{parseHostAuthReference as c}from"./host-auth-reference.js";function n(r,a){return!/^[a-f0-9]{64}$/.test(r)||!/^[a-f0-9]{64}$/.test(a)?!1:f(Buffer.from(r,"hex"),Buffer.from(a,"hex"))}function p(r){const a=Object.freeze(Object.create(null)),u=new WeakSet([a]);let o=!1;const d=Object.freeze({async execute(t){if(!t.capability||!u.has(t.capability)||t.caller!=="host-runtime")return{status:"denied",reasonCode:"host-auth-origin-denied"};let e;try{e=c(t.reference)}catch(i){return{status:"denied",reasonCode:i instanceof Error?i.message:"host-auth-reference-invalid"}}if(!n(e.subjectDigest,t.expectedSubjectDigest)||!n(e.policyDigest,t.expectedPolicyDigest)||!n(e.dispatchDigest,t.expectedDispatchDigest))return{status:"denied",reasonCode:"host-auth-reference-invalid"};if(e.revocationEpoch<t.minimumRevocationEpoch)return{status:"denied",reasonCode:"host-auth-reference-revoked"};if(!t.requiredScopes.every(i=>e.scopes.includes(i)))return{status:"denied",reasonCode:"host-auth-scope-denied"};if(!r)return{status:"unavailable",reasonCode:"host-auth-capability-unavailable"};if(r.provider!==e.provider||r.target!==e.target)return{status:"denied",reasonCode:"host-auth-target-denied"};const s=r.operations[e.operation];if(!s)return{status:"denied",reasonCode:"host-auth-operation-denied"};if(o)return{status:"unavailable",reasonCode:"host-auth-capability-unavailable"};o=!0;try{return c(e),e.revocationEpoch<t.minimumRevocationEpoch?{status:"denied",reasonCode:"host-auth-reference-revoked"}:await s(e)}finally{o=!1}}});return Object.freeze({broker:d,capability:a})}export{p as createHostAuthBroker};
@@ -0,0 +1,32 @@
1
+ export declare const HOST_AUTH_REFERENCE_SCHEMA: "HostAuthReference/1.0";
2
+ export declare const HOST_AUTH_REFERENCE_MAX_BYTES = 4096;
3
+ export declare const HOST_AUTH_REFERENCE_MAX_TTL_MS = 60000;
4
+ export type HostAuthProvider = 'codex' | 'opencode';
5
+ export type HostAuthOperation = 'inspect-session' | 'prepare-license-auth' | 'reconcile-license-auth' | 'authorize-business-replay';
6
+ export interface HostAuthReferenceV1 {
7
+ readonly schemaVersion: typeof HOST_AUTH_REFERENCE_SCHEMA;
8
+ readonly referenceId: string;
9
+ readonly provider: HostAuthProvider;
10
+ readonly authDomain: 'model-provider';
11
+ readonly target: string;
12
+ readonly operation: HostAuthOperation;
13
+ readonly scopes: readonly string[];
14
+ readonly issuedAt: string;
15
+ readonly expiresAt: string;
16
+ readonly revocationEpoch: number;
17
+ readonly subjectDigest: string;
18
+ readonly policyDigest: string;
19
+ readonly dispatchDigest: string;
20
+ }
21
+ export declare class HostAuthReferenceError extends Error {
22
+ readonly reasonCode: string;
23
+ constructor(reasonCode: string);
24
+ }
25
+ export declare function parseHostAuthReference(input: unknown, options?: {
26
+ readonly now?: number;
27
+ readonly allowExpired?: boolean;
28
+ }): HostAuthReferenceV1;
29
+ export declare function createHostAuthReference(input: Omit<HostAuthReferenceV1, 'schemaVersion' | 'referenceId' | 'issuedAt' | 'expiresAt'> & {
30
+ readonly ttlMs?: number;
31
+ readonly now?: number;
32
+ }): HostAuthReferenceV1;
@@ -0,0 +1 @@
1
+ import{randomBytes as l}from"node:crypto";const p="HostAuthReference/1.0",u=4096,E=6e4,f=/^[a-f0-9]{64}$/,y=/^[A-Za-z0-9_-]{16,128}$/,A=/^[a-z0-9][a-z0-9._:-]{0,127}$/,S=/^[a-z][a-z0-9._:-]{0,79}$/,_=new Set(["codex","opencode"]),D=new Set(["inspect-session","prepare-license-auth","reconcile-license-auth","authorize-business-replay"]),d=["schemaVersion","referenceId","provider","authDomain","target","operation","scopes","issuedAt","expiresAt","revocationEpoch","subjectDigest","policyDigest","dispatchDigest"];class v extends Error{reasonCode;constructor(r){super(r),this.reasonCode=r,this.name="HostAuthReferenceError"}}function t(s){throw new v(s)}function w(s,r={}){let o=s;if(typeof s=="string"){Buffer.byteLength(s,"utf8")>u&&t("host-auth-reference-oversized");try{o=JSON.parse(s)}catch{t("host-auth-reference-invalid")}}(!o||typeof o!="object"||Array.isArray(o))&&t("host-auth-reference-invalid");const e=o,a=Object.keys(e);(a.length!==d.length||a.some(c=>!d.includes(c)))&&t("host-auth-reference-invalid"),(e.schemaVersion!==p||e.authDomain!=="model-provider")&&t("host-auth-reference-invalid"),(typeof e.provider!="string"||!_.has(e.provider))&&t("host-auth-reference-invalid"),(typeof e.operation!="string"||!D.has(e.operation))&&t("host-auth-operation-denied"),(typeof e.referenceId!="string"||!y.test(e.referenceId)||typeof e.target!="string"||!A.test(e.target)||typeof e.subjectDigest!="string"||!f.test(e.subjectDigest)||typeof e.policyDigest!="string"||!f.test(e.policyDigest)||typeof e.dispatchDigest!="string"||!f.test(e.dispatchDigest))&&t("host-auth-reference-invalid"),(!Array.isArray(e.scopes)||e.scopes.length===0||e.scopes.length>16||e.scopes.some(c=>typeof c!="string"||!S.test(c))||new Set(e.scopes).size!==e.scopes.length)&&t("host-auth-scope-denied"),(!Number.isSafeInteger(e.revocationEpoch)||e.revocationEpoch<0)&&t("host-auth-reference-invalid");const n=Date.parse(String(e.issuedAt)),i=Date.parse(String(e.expiresAt));(!Number.isFinite(n)||!Number.isFinite(i)||i<=n||i-n>E)&&t("host-auth-reference-invalid");const h=r.now??Date.now();(n>h+3e4||!r.allowExpired&&i<=h)&&t("host-auth-reference-expired");const g=JSON.stringify(e);return Buffer.byteLength(g,"utf8")>u&&t("host-auth-reference-oversized"),Object.freeze({...e,scopes:Object.freeze([...e.scopes])})}function R(s){const r=s.now??Date.now(),o=s.ttlMs??3e4,{now:e,ttlMs:a,...n}=s;return w({schemaVersion:p,referenceId:l(18).toString("base64url"),...n,issuedAt:new Date(r).toISOString(),expiresAt:new Date(r+o).toISOString()},{now:r})}export{u as HOST_AUTH_REFERENCE_MAX_BYTES,E as HOST_AUTH_REFERENCE_MAX_TTL_MS,p as HOST_AUTH_REFERENCE_SCHEMA,v as HostAuthReferenceError,R as createHostAuthReference,w as parseHostAuthReference};
@@ -2,7 +2,7 @@ import{existsSync as p,readFileSync as R,writeFileSync as S,mkdirSync as L,chmod
2
2
  [!] Warning: connected to local server (`+t+`).
3
3
  To use production, run: neocortex activate YOUR-LICENSE-KEY
4
4
  Get yours at https://neocortex.sh/portal/login
5
- `))}function w(r){const t=r.match(/^(https?:\/\/)([^/]+)(.*)$/i);if(!t)return null;const[,e,o,n=""]=t;return o.toLowerCase()!==C?null:`${e}api.neocortex.sh${n}`}function D(r={}){try{if(!p(a))return null;const t=R(a,"utf-8"),e=JSON.parse(t.replace(/^\uFEFF/,""));if(e.licenseKey&&!e.encryptedLicenseKey){const c=m(e.licenseKey,r),i={...e},U=i.licenseKey;return delete i.licenseKey,i.encryptedLicenseKey=c,i.configVersion||(i.configVersion=f),r.strictReadOnly||E(i),{serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:U,keyType:e.keyType}}let o;if(e.encryptedLicenseKey){const c=O(e.encryptedLicenseKey,r);c&&(o=c)}const n={serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:o,keyType:e.keyType};if(e.machineId&&!o&&e.encryptedLicenseKey){const c=l();e.machineId!==c&&console.warn(`
5
+ `))}function w(r){const t=r.match(/^(https?:\/\/)([^/]+)(.*)$/i);if(!t)return null;const[,e,o,n=""]=t;return o.toLowerCase()!==C?null:`${e}api.neocortex.sh${n}`}function D(r={}){try{if(!p(a))return null;const t=R(a,"utf-8"),e=JSON.parse(t.replace(/^\uFEFF/,""));if(e.licenseKey&&!e.encryptedLicenseKey){const c=m(e.licenseKey,r),i={...e},U=i.licenseKey;return delete i.licenseKey,i.encryptedLicenseKey=c,i.configVersion||(i.configVersion=f),r.strictReadOnly||E(i),{serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:U,keyType:e.keyType}}let o;if(e.encryptedLicenseKey){const c=O(e.encryptedLicenseKey,r);c&&(o=c)}const n={serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:o,keyType:e.keyType};if(e.machineId&&!o&&e.encryptedLicenseKey){const c=l(r);e.machineId!==c&&console.warn(`
6
6
  [!] Machine fingerprint changed (was: ${e.machineId.slice(0,12)}..., now: ${c.slice(0,12)}...).
7
7
  Your encrypted credentials are no longer valid.
8
8
  Re-activate with: neocortex activate YOUR-LICENSE-KEY
@@ -24,6 +24,16 @@ export interface NativeDispatchBindingV1 {
24
24
  readonly maxDepth: 1;
25
25
  readonly publicSafe: true;
26
26
  }
27
+ export interface NativeBackgroundDispatchContractV1 {
28
+ readonly schemaVersion: 1;
29
+ readonly contractVersion: 'native-background-dispatch-v1';
30
+ readonly topology: 'native-agent';
31
+ readonly launchPolicy: 'all-eligible-before-settlement';
32
+ readonly settlementPolicy: 'first-admissible-to-root';
33
+ readonly integrationOwner: 'root';
34
+ readonly maxDepth: 1;
35
+ readonly publicSafe: true;
36
+ }
27
37
  export type NativeAgentState = 'requested' | 'spawned' | 'running' | 'completed' | 'failed' | 'interrupted' | 'unknown' | 'lost';
28
38
  export type NativeAgentTopology = 'native-agent' | 'headless-process' | 'inline';
29
39
  export type NativeAgentFreshness = 'fresh' | 'stale' | 'unknown';
@@ -49,6 +59,7 @@ export interface NativeAgentDispatchReceiptV1 {
49
59
  }
50
60
  export declare const NATIVE_AGENT_TERMINAL_STATES: ReadonlySet<NativeAgentState>;
51
61
  export declare function isNativeHostAttestationV1(value: unknown): value is NativeHostAttestationV1;
62
+ export declare function isNativeBackgroundDispatchContractV1(value: unknown): value is NativeBackgroundDispatchContractV1;
52
63
  export declare function isNativeDispatchBindingV1(value: unknown): value is NativeDispatchBindingV1;
53
64
  export declare function isNativeAgentDispatchReceiptV1(value: unknown): value is NativeAgentDispatchReceiptV1;
54
65
  export declare function isNativeAgentStateTransitionAllowed(previous: NativeAgentState, next: NativeAgentState): boolean;
@@ -1 +1 @@
1
- const S=["requested","spawned","running","completed","failed","interrupted","unknown","lost"],l=["native-agent","headless-process","inline"],g=["fresh","stale","unknown"],y=["host-event","host-list","bounded-poll","local-reservation"],m=["codex-cli","codex-desktop","unknown"],A=["runtime-attested","host-observed","environment","explicit-override","unknown"],u=["attested","observed","inferred","unknown"],w=new Set(["completed","failed","interrupted"]),d=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/,c=/^(?:sha256:)?[a-f0-9]{64}$/i,p=/^sha256:[a-f0-9]{64}$/i,f=/^agt_[a-f0-9]{24,64}$/i,b=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/,I=/^[a-z0-9][a-z0-9-]{0,95}$/;function n(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function s(e,t){const o=Object.keys(e).sort(),i=[...t].sort();return o.length===i.length&&o.every((a,h)=>a===i[h])}function r(e){return typeof e=="string"&&e.length>=20&&e.length<=40&&Number.isFinite(Date.parse(e))}function T(e){return!n(e)||!s(e,["schemaVersion","platformTarget","hostKind","hostVersion","origin","confidence","publicSafe"])?!1:e.schemaVersion===1&&e.platformTarget==="codex"&&m.includes(e.hostKind)&&(e.hostVersion===null||typeof e.hostVersion=="string"&&b.test(e.hostVersion))&&A.includes(e.origin)&&u.includes(e.confidence)&&e.publicSafe===!0}function E(e){return!n(e)||!s(e,["schemaVersion","storyId","graphRevision","dispatchKey","requiredCapability","maxDepth","publicSafe"])?!1:e.schemaVersion===1&&typeof e.storyId=="string"&&d.test(e.storyId)&&typeof e.graphRevision=="string"&&c.test(e.graphRevision)&&typeof e.dispatchKey=="string"&&p.test(e.dispatchKey)&&e.requiredCapability==="native_safe"&&e.maxDepth===1&&e.publicSafe===!0}function R(e){if(!n(e)||!s(e,["schemaVersion","storyId","graphRevision","dispatchKey","profile","parentHandle","handle","topology","state","requestedAt","observedAt","terminalAt","freshness","observationSource","reasonCode","revision","publicSafe"]))return!1;const t=e.state;return e.schemaVersion!==1||typeof e.storyId!="string"||!d.test(e.storyId)||typeof e.graphRevision!="string"||!c.test(e.graphRevision)||typeof e.dispatchKey!="string"||!p.test(e.dispatchKey)||e.profile!=="neocortex"||e.parentHandle!==null&&(typeof e.parentHandle!="string"||!f.test(e.parentHandle))||e.handle!==null&&(typeof e.handle!="string"||!f.test(e.handle))||!l.includes(e.topology)||!S.includes(t)||!r(e.requestedAt)||e.observedAt!==null&&!r(e.observedAt)||e.terminalAt!==null&&!r(e.terminalAt)||!g.includes(e.freshness)||!y.includes(e.observationSource)||typeof e.reasonCode!="string"||!I.test(e.reasonCode)||typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<0||e.publicSafe!==!0?!1:t==="requested"?e.handle===null&&e.observedAt===null&&e.terminalAt===null&&e.freshness==="unknown"&&e.observationSource==="local-reservation":!(e.observationSource==="local-reservation"||(t==="spawned"||t==="running")&&(e.handle===null||e.freshness!=="fresh")||w.has(t)!==(e.terminalAt!==null))}const N={requested:new Set(["requested","spawned","failed","interrupted","unknown"]),spawned:new Set(["spawned","running","completed","failed","interrupted","unknown","lost"]),running:new Set(["running","completed","failed","interrupted","unknown","lost"]),unknown:new Set(["unknown","spawned","running","completed","failed","interrupted","lost"]),lost:new Set(["lost","running","completed","failed","interrupted"]),completed:new Set(["completed"]),failed:new Set(["failed"]),interrupted:new Set(["interrupted"])};function V(e,t){return N[e].has(t)}export{w as NATIVE_AGENT_TERMINAL_STATES,R as isNativeAgentDispatchReceiptV1,V as isNativeAgentStateTransitionAllowed,E as isNativeDispatchBindingV1,T as isNativeHostAttestationV1};
1
+ const l=["requested","spawned","running","completed","failed","interrupted","unknown","lost"],g=["native-agent","headless-process","inline"],S=["fresh","stale","unknown"],y=["host-event","host-list","bounded-poll","local-reservation"],m=["codex-cli","codex-desktop","unknown"],b=["runtime-attested","host-observed","environment","explicit-override","unknown"],w=["attested","observed","inferred","unknown"],A=new Set(["completed","failed","interrupted"]),c=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/,d=/^(?:sha256:)?[a-f0-9]{64}$/i,p=/^sha256:[a-f0-9]{64}$/i,a=/^agt_[a-f0-9]{24,64}$/i,u=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/,I=/^[a-z0-9][a-z0-9-]{0,95}$/;function n(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function r(t,e){const o=Object.keys(t).sort(),i=[...e].sort();return o.length===i.length&&o.every((f,h)=>f===i[h])}function s(t){return typeof t=="string"&&t.length>=20&&t.length<=40&&Number.isFinite(Date.parse(t))}function V(t){return!n(t)||!r(t,["schemaVersion","platformTarget","hostKind","hostVersion","origin","confidence","publicSafe"])?!1:t.schemaVersion===1&&t.platformTarget==="codex"&&m.includes(t.hostKind)&&(t.hostVersion===null||typeof t.hostVersion=="string"&&u.test(t.hostVersion))&&b.includes(t.origin)&&w.includes(t.confidence)&&t.publicSafe===!0}function T(t){return!n(t)||!r(t,["schemaVersion","contractVersion","topology","launchPolicy","settlementPolicy","integrationOwner","maxDepth","publicSafe"])?!1:t.schemaVersion===1&&t.contractVersion==="native-background-dispatch-v1"&&t.topology==="native-agent"&&t.launchPolicy==="all-eligible-before-settlement"&&t.settlementPolicy==="first-admissible-to-root"&&t.integrationOwner==="root"&&t.maxDepth===1&&t.publicSafe===!0}function O(t){return!n(t)||!r(t,["schemaVersion","storyId","graphRevision","dispatchKey","requiredCapability","maxDepth","publicSafe"])?!1:t.schemaVersion===1&&typeof t.storyId=="string"&&c.test(t.storyId)&&typeof t.graphRevision=="string"&&d.test(t.graphRevision)&&typeof t.dispatchKey=="string"&&p.test(t.dispatchKey)&&t.requiredCapability==="native_safe"&&t.maxDepth===1&&t.publicSafe===!0}function k(t){if(!n(t)||!r(t,["schemaVersion","storyId","graphRevision","dispatchKey","profile","parentHandle","handle","topology","state","requestedAt","observedAt","terminalAt","freshness","observationSource","reasonCode","revision","publicSafe"]))return!1;const e=t.state;return t.schemaVersion!==1||typeof t.storyId!="string"||!c.test(t.storyId)||typeof t.graphRevision!="string"||!d.test(t.graphRevision)||typeof t.dispatchKey!="string"||!p.test(t.dispatchKey)||t.profile!=="neocortex"||t.parentHandle!==null&&(typeof t.parentHandle!="string"||!a.test(t.parentHandle))||t.handle!==null&&(typeof t.handle!="string"||!a.test(t.handle))||!g.includes(t.topology)||!l.includes(e)||!s(t.requestedAt)||t.observedAt!==null&&!s(t.observedAt)||t.terminalAt!==null&&!s(t.terminalAt)||!S.includes(t.freshness)||!y.includes(t.observationSource)||typeof t.reasonCode!="string"||!I.test(t.reasonCode)||typeof t.revision!="number"||!Number.isSafeInteger(t.revision)||t.revision<0||t.publicSafe!==!0?!1:e==="requested"?t.handle===null&&t.observedAt===null&&t.terminalAt===null&&t.freshness==="unknown"&&t.observationSource==="local-reservation":!(t.observationSource==="local-reservation"||(e==="spawned"||e==="running")&&(t.handle===null||t.freshness!=="fresh")||A.has(e)!==(t.terminalAt!==null))}const N={requested:new Set(["requested","spawned","failed","interrupted","unknown"]),spawned:new Set(["spawned","running","completed","failed","interrupted","unknown","lost"]),running:new Set(["running","completed","failed","interrupted","unknown","lost"]),unknown:new Set(["unknown","spawned","running","completed","failed","interrupted","lost"]),lost:new Set(["lost","running","completed","failed","interrupted"]),completed:new Set(["completed"]),failed:new Set(["failed"]),interrupted:new Set(["interrupted"])};function x(t,e){return N[t].has(e)}export{A as NATIVE_AGENT_TERMINAL_STATES,k as isNativeAgentDispatchReceiptV1,x as isNativeAgentStateTransitionAllowed,T as isNativeBackgroundDispatchContractV1,O as isNativeDispatchBindingV1,V as isNativeHostAttestationV1};
@@ -21,6 +21,7 @@ export interface HumanizedError {
21
21
  /** URL the user can visit for more context. */
22
22
  readonly url?: string;
23
23
  }
24
+ export type AuthRefreshMessageCause = 'near-expiry' | 'expired' | 'store-unavailable' | 'store-corrupt' | 'keychain-unavailable' | 'transport-error' | 'timeout' | 'rate-limited' | 'service-unavailable' | 'revoked' | 'scope-denied' | 'client-denied' | 'protocol-invalid' | 'persistence-failed' | 'rotation-uncertain' | 'capability-unavailable' | 'revision-conflict';
24
25
  /** Detect the best locale from LC_ALL / LANG. Falls back to 'en'. */
25
26
  export declare function detectErrorLocale(env?: NodeJS.ProcessEnv): ErrorMessageLocale;
26
27
  /**
@@ -29,6 +30,8 @@ export declare function detectErrorLocale(env?: NodeJS.ProcessEnv): ErrorMessage
29
30
  * raw server message.
30
31
  */
31
32
  export declare function humanizeError(code: string, locale?: ErrorMessageLocale): HumanizedError | null;
33
+ /** Cause-specific AUTH_REFRESH_REQUIRED copy. Only confirmed revocation recommends activation. */
34
+ export declare function humanizeAuthRefreshRequired(cause: AuthRefreshMessageCause, locale?: ErrorMessageLocale): HumanizedError;
32
35
  /**
33
36
  * Format a humanized error for stderr. Always ends with the support email.
34
37
  */
@@ -1,2 +1,2 @@
1
- const t="support@neocortex.sh",u={AUTH_REFRESH_REQUIRED:{en:{summary:"Authentication must be refreshed.",whatHappened:"Credentials are configured, but a valid authentication token is unavailable. The token may have expired or the authentication service may be unreachable. Strict read-only commands do not refresh tokens.",whatToDo:"Check the server connection and retry. If authentication remains unavailable, re-activate outside strict read-only mode.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"A autentica\xE7\xE3o precisa ser renovada.",whatHappened:"As credenciais est\xE3o configuradas, mas n\xE3o h\xE1 um token de autentica\xE7\xE3o v\xE1lido dispon\xEDvel. O token pode ter expirado ou o servi\xE7o de autentica\xE7\xE3o pode estar inacess\xEDvel. Comandos estritamente somente leitura n\xE3o renovam tokens.",whatToDo:"Verifique a conex\xE3o com o servidor e tente novamente. Se a autentica\xE7\xE3o continuar indispon\xEDvel, reative fora do modo estritamente somente leitura.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},AUTH_EXPIRED:{en:{summary:"Your session has expired.",whatHappened:"The token we use to authenticate your CLI has expired. This is normal and happens every few hours.",whatToDo:"Re-activate with the license key that was emailed to you.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Sua sess\xE3o expirou.",whatHappened:"O token de autentica\xE7\xE3o do CLI expirou. Isso \xE9 normal e acontece a cada poucas horas.",whatToDo:"Reative o CLI com a license key que voc\xEA recebeu por email.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},UPGRADE_REQUIRED:{en:{summary:"Your CLI version is outdated.",whatHappened:"The server requires a newer CLI version. Older versions are not allowed for security and compatibility reasons.",whatToDo:"Install the latest CLI globally with npm.",command:"npm install -g @ornexus/neocortex@latest"},"pt-BR":{summary:"Sua vers\xE3o do CLI est\xE1 desatualizada.",whatHappened:"O servidor exige uma vers\xE3o mais recente do CLI. Vers\xF5es antigas n\xE3o s\xE3o permitidas por motivos de seguran\xE7a e compatibilidade.",whatToDo:"Instale a vers\xE3o mais recente globalmente via npm.",command:"npm install -g @ornexus/neocortex@latest"}},RATE_LIMITED:{en:{summary:"You sent too many requests in a short window.",whatHappened:"You hit the rate limit for your plan. This protects the service from abuse and keeps it fast for everyone.",whatToDo:"Wait a few seconds and try again. If you hit this often, upgrading your plan raises the limit.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Voc\xEA fez muitas requisi\xE7\xF5es em pouco tempo.",whatHappened:"O limite de taxa do seu plano foi atingido. Isso protege o servi\xE7o contra abuso e mant\xE9m a velocidade para todos.",whatToDo:"Espere alguns segundos e tente novamente. Se isso acontece com frequ\xEAncia, fazer upgrade do seu plano aumenta o limite.",url:"https://neocortex.sh/portal/plans"}},TRIGGER_NOT_ALLOWED:{en:{summary:"This command is not available on your current plan.",whatHappened:"You tried to use a trigger that requires a paid plan (Pro or Enterprise).",whatToDo:"See the full comparison and upgrade in the portal.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Este comando n\xE3o est\xE1 dispon\xEDvel no seu plano atual.",whatHappened:"Voc\xEA tentou usar um trigger que requer um plano pago (Pro ou Enterprise).",whatToDo:"Veja a compara\xE7\xE3o completa e fa\xE7a upgrade no portal.",url:"https://neocortex.sh/portal/plans"}},QUOTA_EXCEEDED:{en:{summary:"Daily quota reached.",whatHappened:"You have used all invocations allowed by your plan today. Quotas reset at midnight UTC.",whatToDo:"Wait for the daily reset, or upgrade your plan for a higher quota.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Quota di\xE1ria atingida.",whatHappened:"Voc\xEA usou todas as invoca\xE7\xF5es permitidas pelo seu plano hoje. As quotas s\xE3o resetadas \xE0 meia-noite UTC.",whatToDo:"Aguarde o reset di\xE1rio ou fa\xE7a upgrade do plano para uma quota maior.",url:"https://neocortex.sh/portal/plans"}},SERVER_ERROR:{en:{summary:"Server error.",whatHappened:"Something went wrong on our side. We have logged the error and will investigate.",whatToDo:`Try again in a minute. If the problem persists, please contact ${t} with the details.`},"pt-BR":{summary:"Erro do servidor.",whatHappened:"Algo deu errado no nosso lado. O erro foi registrado e vamos investigar.",whatToDo:`Tente novamente em um minuto. Se o problema persistir, entre em contato: ${t}.`}},ECONNREFUSED:{en:{summary:"Cannot reach the Neocortex server.",whatHappened:"We could not open a connection to the server. This is usually a network problem on your side.",whatToDo:"Check your internet connection, any VPN or corporate proxy, and try again."},"pt-BR":{summary:"N\xE3o foi poss\xEDvel alcan\xE7ar o servidor Neocortex.",whatHappened:"N\xE3o conseguimos abrir uma conex\xE3o com o servidor. Isso geralmente \xE9 um problema de rede do seu lado.",whatToDo:"Verifique sua conex\xE3o, qualquer VPN ou proxy corporativo, e tente novamente."}},MACHINE_LIMIT_EXCEEDED:{en:{summary:"Machine limit reached.",whatHappened:"Your plan allows a limited number of active machines, and this one would exceed it.",whatToDo:"Deactivate a machine you no longer use from the portal, then re-run activate here.",url:"https://neocortex.sh/portal/machines"},"pt-BR":{summary:"Limite de m\xE1quinas atingido.",whatHappened:"Seu plano permite um n\xFAmero limitado de m\xE1quinas ativas, e esta ultrapassaria o limite.",whatToDo:"Desative uma m\xE1quina que voc\xEA n\xE3o usa mais no portal e rode activate aqui de novo.",url:"https://neocortex.sh/portal/machines"}},NOT_CONFIGURED:{en:{summary:"Neocortex is not configured on this machine.",whatHappened:"No license key was found. You need to run `neocortex activate` once before using the CLI.",whatToDo:"Get a license key from the portal and activate.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Neocortex n\xE3o est\xE1 configurado nesta m\xE1quina.",whatHappened:"Nenhuma license key encontrada. Voc\xEA precisa rodar `neocortex activate` uma vez antes de usar o CLI.",whatToDo:"Pegue uma license key no portal e ative.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}}};function r(o=process.env){return(o.LC_ALL??o.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function p(o,a=r()){const e=u[o];return e?e[a]??e.en??null:null}function c(o,a=r()){const e=[];e.push(""),e.push(`[Neocortex] ${o.summary}`),e.push("");const n=a==="pt-BR"?"O que aconteceu":"What happened",s=a==="pt-BR"?"O que fazer":"What to do",i=a==="pt-BR"?`Precisa de ajuda? ${t}`:`Need help? ${t}`;return e.push(`${n}: ${o.whatHappened}`),e.push(`${s}: ${o.whatToDo}`),o.command&&(e.push(""),e.push(` ${o.command}`)),o.url&&(e.push(""),e.push(` ${o.url}`)),e.push(""),e.push(i),e.push(""),e.join(`
2
- `)}function m(o){if(!o||typeof o!="object")return null;const a=o;return typeof a.code=="string"&&(a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"||a.code==="ETIMEDOUT"||a.code==="ECONNRESET")||typeof a.message=="string"&&(/connect/i.test(a.message)&&/refus/i.test(a.message)||/fetch failed/i.test(a.message))?"ECONNREFUSED":null}export{r as detectErrorLocale,c as formatHumanizedError,p as humanizeError,m as inferErrorCodeFromException};
1
+ const r="support@neocortex.sh",c={AUTH_REFRESH_REQUIRED:{en:{summary:"Authentication must be refreshed.",whatHappened:"Credentials are configured, but a valid authentication token is unavailable. The token may have expired or the authentication service may be unreachable. Strict read-only commands do not refresh tokens.",whatToDo:"Check the server connection and retry. If authentication remains unavailable, re-activate outside strict read-only mode.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"A autentica\xE7\xE3o precisa ser renovada.",whatHappened:"As credenciais est\xE3o configuradas, mas n\xE3o h\xE1 um token de autentica\xE7\xE3o v\xE1lido dispon\xEDvel. O token pode ter expirado ou o servi\xE7o de autentica\xE7\xE3o pode estar inacess\xEDvel. Comandos estritamente somente leitura n\xE3o renovam tokens.",whatToDo:"Verifique a conex\xE3o com o servidor e tente novamente. Se a autentica\xE7\xE3o continuar indispon\xEDvel, reative fora do modo estritamente somente leitura.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},AUTH_EXPIRED:{en:{summary:"Your session has expired.",whatHappened:"The token we use to authenticate your CLI has expired. This is normal and happens every few hours.",whatToDo:"Re-activate with the license key that was emailed to you.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Sua sess\xE3o expirou.",whatHappened:"O token de autentica\xE7\xE3o do CLI expirou. Isso \xE9 normal e acontece a cada poucas horas.",whatToDo:"Reative o CLI com a license key que voc\xEA recebeu por email.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},UPGRADE_REQUIRED:{en:{summary:"Your CLI version is outdated.",whatHappened:"The server requires a newer CLI version. Older versions are not allowed for security and compatibility reasons.",whatToDo:"Install the latest CLI globally with npm.",command:"npm install -g @ornexus/neocortex@latest"},"pt-BR":{summary:"Sua vers\xE3o do CLI est\xE1 desatualizada.",whatHappened:"O servidor exige uma vers\xE3o mais recente do CLI. Vers\xF5es antigas n\xE3o s\xE3o permitidas por motivos de seguran\xE7a e compatibilidade.",whatToDo:"Instale a vers\xE3o mais recente globalmente via npm.",command:"npm install -g @ornexus/neocortex@latest"}},RATE_LIMITED:{en:{summary:"You sent too many requests in a short window.",whatHappened:"You hit the rate limit for your plan. This protects the service from abuse and keeps it fast for everyone.",whatToDo:"Wait a few seconds and try again. If you hit this often, upgrading your plan raises the limit.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Voc\xEA fez muitas requisi\xE7\xF5es em pouco tempo.",whatHappened:"O limite de taxa do seu plano foi atingido. Isso protege o servi\xE7o contra abuso e mant\xE9m a velocidade para todos.",whatToDo:"Espere alguns segundos e tente novamente. Se isso acontece com frequ\xEAncia, fazer upgrade do seu plano aumenta o limite.",url:"https://neocortex.sh/portal/plans"}},TRIGGER_NOT_ALLOWED:{en:{summary:"This command is not available on your current plan.",whatHappened:"You tried to use a trigger that requires a paid plan (Pro or Enterprise).",whatToDo:"See the full comparison and upgrade in the portal.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Este comando n\xE3o est\xE1 dispon\xEDvel no seu plano atual.",whatHappened:"Voc\xEA tentou usar um trigger que requer um plano pago (Pro ou Enterprise).",whatToDo:"Veja a compara\xE7\xE3o completa e fa\xE7a upgrade no portal.",url:"https://neocortex.sh/portal/plans"}},QUOTA_EXCEEDED:{en:{summary:"Daily quota reached.",whatHappened:"You have used all invocations allowed by your plan today. Quotas reset at midnight UTC.",whatToDo:"Wait for the daily reset, or upgrade your plan for a higher quota.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Quota di\xE1ria atingida.",whatHappened:"Voc\xEA usou todas as invoca\xE7\xF5es permitidas pelo seu plano hoje. As quotas s\xE3o resetadas \xE0 meia-noite UTC.",whatToDo:"Aguarde o reset di\xE1rio ou fa\xE7a upgrade do plano para uma quota maior.",url:"https://neocortex.sh/portal/plans"}},SERVER_ERROR:{en:{summary:"Server error.",whatHappened:"Something went wrong on our side. We have logged the error and will investigate.",whatToDo:`Try again in a minute. If the problem persists, please contact ${r} with the details.`},"pt-BR":{summary:"Erro do servidor.",whatHappened:"Algo deu errado no nosso lado. O erro foi registrado e vamos investigar.",whatToDo:`Tente novamente em um minuto. Se o problema persistir, entre em contato: ${r}.`}},ECONNREFUSED:{en:{summary:"Cannot reach the Neocortex server.",whatHappened:"We could not open a connection to the server. This is usually a network problem on your side.",whatToDo:"Check your internet connection, any VPN or corporate proxy, and try again."},"pt-BR":{summary:"N\xE3o foi poss\xEDvel alcan\xE7ar o servidor Neocortex.",whatHappened:"N\xE3o conseguimos abrir uma conex\xE3o com o servidor. Isso geralmente \xE9 um problema de rede do seu lado.",whatToDo:"Verifique sua conex\xE3o, qualquer VPN ou proxy corporativo, e tente novamente."}},MACHINE_LIMIT_EXCEEDED:{en:{summary:"Machine limit reached.",whatHappened:"Your plan allows a limited number of active machines, and this one would exceed it.",whatToDo:"Deactivate a machine you no longer use from the portal, then re-run activate here.",url:"https://neocortex.sh/portal/machines"},"pt-BR":{summary:"Limite de m\xE1quinas atingido.",whatHappened:"Seu plano permite um n\xFAmero limitado de m\xE1quinas ativas, e esta ultrapassaria o limite.",whatToDo:"Desative uma m\xE1quina que voc\xEA n\xE3o usa mais no portal e rode activate aqui de novo.",url:"https://neocortex.sh/portal/machines"}},NOT_CONFIGURED:{en:{summary:"Neocortex is not configured on this machine.",whatHappened:"No license key was found. You need to run `neocortex activate` once before using the CLI.",whatToDo:"Get a license key from the portal and activate.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Neocortex n\xE3o est\xE1 configurado nesta m\xE1quina.",whatHappened:"Nenhuma license key encontrada. Voc\xEA precisa rodar `neocortex activate` uma vez antes de usar o CLI.",whatToDo:"Pegue uma license key no portal e ative.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}}};function n(t=process.env){return(t.LC_ALL??t.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function u(t,o=n()){const e=c[t];return e?e[o]??e.en??null:null}function p(t,o=n()){const e=o==="pt-BR",a={"near-expiry":{en:"Prepare authentication outside strict read-only mode, then retry once.",pt:"Prepare a autentica\xE7\xE3o fora do modo estritamente somente leitura e tente uma vez."},expired:{en:"Prepare authentication outside strict read-only mode.",pt:"Prepare a autentica\xE7\xE3o fora do modo estritamente somente leitura."},"store-unavailable":{en:"Restore access to the local credential store; do not delete it.",pt:"Restaure o acesso ao store local; n\xE3o o apague."},"store-corrupt":{en:"Stop and recover the credential store explicitly; do not overwrite it.",pt:"Pare e recupere o store de credenciais explicitamente; n\xE3o o sobrescreva."},"keychain-unavailable":{en:"Unlock or restore the system keychain, then retry.",pt:"Desbloqueie ou restaure o keychain do sistema e tente novamente."},"transport-error":{en:"Check connectivity and retry later; the current login was preserved.",pt:"Verifique a conex\xE3o e tente depois; o login atual foi preservado."},timeout:{en:"Stop the current recovery and retry only after its outcome is known.",pt:"Pare a recupera\xE7\xE3o atual e tente novamente somente ap\xF3s conhecer o resultado."},"rate-limited":{en:"Wait for the retry window while preserving the current login.",pt:"Aguarde a janela de nova tentativa preservando o login atual."},"service-unavailable":{en:"Retry later; do not clear local authentication.",pt:"Tente novamente depois; n\xE3o limpe a autentica\xE7\xE3o local."},revoked:{en:"Re-activate with an authorized license credential.",pt:"Reative com uma credencial de licen\xE7a autorizada.",command:e?"neocortex activate SUA-LICENSE-KEY":"neocortex activate YOUR-LICENSE-KEY"},"scope-denied":{en:"Request the required scope; do not elevate it locally.",pt:"Solicite o escopo necess\xE1rio; n\xE3o o eleve localmente."},"client-denied":{en:"Stop and restore the authorized client policy.",pt:"Pare e restaure a pol\xEDtica de cliente autorizada."},"protocol-invalid":{en:"Stop and inspect the supported authentication contract.",pt:"Pare e inspecione o contrato de autentica\xE7\xE3o suportado."},"persistence-failed":{en:"Recover explicitly; do not repeat refresh or restore an older credential.",pt:"Recupere explicitamente; n\xE3o repita o refresh nem restaure uma credencial anterior."},"rotation-uncertain":{en:"Stop and recover explicitly; do not repeat refresh.",pt:"Pare e fa\xE7a recupera\xE7\xE3o expl\xEDcita; n\xE3o repita o refresh."},"capability-unavailable":{en:"Use a supported host capability; do not export credentials.",pt:"Use uma capability de host suportada; n\xE3o exporte credenciais."},"revision-conflict":{en:"Wait for the current owner and re-read the accepted generation.",pt:"Aguarde o owner atual e releia a gera\xE7\xE3o aceita."}}[t];return{summary:e?"A autentica\xE7\xE3o requer uma a\xE7\xE3o causal.":"Authentication requires a causal action.",whatHappened:e?`A causa confirmada \xE9 ${t}; nenhum segredo ou corpo bruto foi exibido.`:`The confirmed cause is ${t}; no secret or raw response body was exposed.`,whatToDo:e?a.pt:a.en,...a.command?{command:a.command}:{}}}function d(t,o=n()){const e=[];e.push(""),e.push(`[Neocortex] ${t.summary}`),e.push("");const i=o==="pt-BR"?"O que aconteceu":"What happened",a=o==="pt-BR"?"O que fazer":"What to do",s=o==="pt-BR"?`Precisa de ajuda? ${r}`:`Need help? ${r}`;return e.push(`${i}: ${t.whatHappened}`),e.push(`${a}: ${t.whatToDo}`),t.command&&(e.push(""),e.push(` ${t.command}`)),t.url&&(e.push(""),e.push(` ${t.url}`)),e.push(""),e.push(s),e.push(""),e.join(`
2
+ `)}function l(t){if(!t||typeof t!="object")return null;const o=t;return typeof o.code=="string"&&(o.code==="ECONNREFUSED"||o.code==="ENOTFOUND"||o.code==="ETIMEDOUT"||o.code==="ECONNRESET")||typeof o.message=="string"&&(/connect/i.test(o.message)&&/refus/i.test(o.message)||/fetch failed/i.test(o.message))?"ECONNREFUSED":null}export{n as detectErrorLocale,d as formatHumanizedError,p as humanizeAuthRefreshRequired,u as humanizeError,l as inferErrorCodeFromException};
@@ -56,6 +56,16 @@ export interface DirectYoloCheckpointOptions {
56
56
  readonly push?: boolean;
57
57
  readonly remote?: string;
58
58
  readonly nowIso?: string;
59
+ /**
60
+ * Compare-bound authority used only by the change-evidence preflight to
61
+ * reacquire this exact expired setup lease after the origin checkout advanced.
62
+ * Normal setup calls never infer or enable this recovery.
63
+ */
64
+ readonly expiredSetupRecovery?: {
65
+ readonly schemaVersion: 1;
66
+ readonly expectedRuntimeRevision: number;
67
+ readonly expectedLease: Readonly<Record<string, unknown>>;
68
+ };
59
69
  /** One-time setup-owner grant required to transfer a still-live setup lease. */
60
70
  readonly setupLeaseHandoff?: {
61
71
  readonly sessionId: string;
@@ -79,7 +89,7 @@ export interface DirectYoloCheckpointOptions {
79
89
  * epic branch; it never creates, removes or repositions a worktree. Existing
80
90
  * staged and unstaged bytes must remain identical across the branch switch.
81
91
  */
82
- export declare function prepareDirectYoloSetup(options: Pick<DirectYoloCheckpointOptions, 'projectRoot' | 'storyId' | 'nowIso'>): Promise<DirectYoloCheckpointResult<DirectYoloSetupReceipt>>;
92
+ export declare function prepareDirectYoloSetup(options: Pick<DirectYoloCheckpointOptions, 'projectRoot' | 'storyId' | 'nowIso' | 'expiredSetupRecovery'>): Promise<DirectYoloCheckpointResult<DirectYoloSetupReceipt>>;
83
93
  /** Accept C01 only from the root after its own physical setup and live lease. */
84
94
  export declare function acceptDirectYoloSetupCheckpoint(options: Pick<DirectYoloCheckpointOptions, 'projectRoot' | 'storyId' | 'nowIso'>): Promise<DirectYoloCheckpointResult<DirectYoloSetupAcceptanceReceipt>>;
85
95
  /**
@@ -1,4 +1,4 @@
1
- import{execFile as _e}from"node:child_process";import{createHash as Le,randomBytes as le,timingSafeEqual as He}from"node:crypto";import{readFile as J}from"node:fs/promises";import{join as te,resolve as Z}from"node:path";import{promisify as Ce}from"node:util";import{readRootMemoryEffectForCheckpoint as qe}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as Oe,verifyRootMemoryPhysicalWriteSet as re}from"../private-execution/root-memory-git-evidence.js";import{acquireGitLifecyclePhysicalIntegrationLock as W,applyGitLifecycleRuntimeOverlay as $e,computeImmutableStoryQaEvidenceDigest as ze,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as ge,computeP205StoryQaEvidenceDigest as Pe,computeLegacyDirectYoloRecoveryReceiptRef as Ne,ensureRuntimeEpic as P,ensureRuntimeStory as me,ensureGitLifecyclePrivateChildDirectory as We,executeP205TransientAuthority as Ge,projectP205TransientExecutionEvidence as Me,publicStoryReviewArtifactFromGit as Q,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Ke,mutateGitLifecycleRuntime as $,P205_COMPLETE_COMMAND as Ve,readGitLifecycleRuntime as C,gitLifecycleRuntimeDirectory as Fe,assertGitLifecyclePrivateFile as we,releaseGitLifecyclePhysicalIntegrationLock as G,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as Te,verifyGitLifecyclePhysicalIntegrationLock as U,verifyAcceptedGitLifecycleStoryCheckpoint as Ie}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as Ye}from"./secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Je,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as Re,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as X}from"./git-lifecycle-step-ids.js";const oe=Ce(_e);async function yt(e){try{const t=await ve(e.projectRoot,e.storyId),r=N(e.nowIso),o=Date.parse(r),i=await l(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),n=await l(t.projectRoot,["rev-parse","HEAD"]),y=await C(t.projectRoot,{required:!0}),h=m(y.epics[t.epicId]),d=m(h?.branch_lease),a=d&&Number.isFinite(Date.parse(String(d.expiresAt)))&&Date.parse(String(d.expiresAt))>o;if(a&&d?.ownerStoryId!==e.storyId)return c("direct-yolo-writer-active");let s=he(h?.origin_binding,t.executionBranch,t.originBranch);if(i===t.executionBranch){if(!s)return c("direct-yolo-origin-binding-invalid")}else{if(i!==t.originBranch)return c("direct-yolo-current-branch-mismatch");if(s&&s.originHeadSha!==n)return c("direct-yolo-origin-binding-conflict");if(s??={schemaVersion:1,originBranch:t.originBranch,originHeadSha:n,executionBranch:t.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:r},(await Ee(t.projectRoot)).some(u=>u.branch===t.executionBranch&&Z(u.path)!==t.projectRoot))return c("direct-yolo-execution-branch-checked-out-elsewhere");const w=await T(t.projectRoot),j=`refs/heads/${t.executionBranch}`;if(await L(t.projectRoot,["show-ref","--verify","--quiet",j])){const u=await l(t.projectRoot,["rev-parse",j]);if(u!==n){if(!await L(t.projectRoot,["merge-base","--is-ancestor",u,n]))return c("direct-yolo-execution-branch-diverged");await l(t.projectRoot,["update-ref",j,n,u])}await l(t.projectRoot,["switch",t.executionBranch])}else await l(t.projectRoot,["switch","-c",t.executionBranch]);if(await T(t.projectRoot)!==w)return c("direct-yolo-checkout-payload-raced")}const p=await l(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),f=await l(t.projectRoot,["rev-parse","HEAD"]);if(p!==t.executionBranch)return c("direct-yolo-current-branch-mismatch");if(a&&d?.ownerStoryId===e.storyId)return d.setupHeadSha!==f?c("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:ue(t,s,String(d.expiresAt),!0)};const R=r,k=new Date(o+3600*1e3).toISOString(),I=`setup-${le(32).toString("hex")}`,v=await C(t.projectRoot,{required:!0});return await $(t.projectRoot,x=>{const w=P(x,t.epicId),j=m(w.branch_lease);if(j&&Date.parse(String(j.expiresAt))>o&&j.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const u=he(w.origin_binding,t.executionBranch,t.originBranch);if(w.origin_binding&&!u)throw new Error("direct-yolo-origin-binding-conflict");if(u&&JSON.stringify(u)!==JSON.stringify(s))throw new Error("direct-yolo-origin-binding-conflict");w.branch_mode="epic",w.execution_branch=t.executionBranch,w.origin_branch=t.originBranch,w.graph_revision=t.graphRevision,w.origin_binding=s,w.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:I,idempotencyKey:I,acquiredAt:R,expiresAt:k,setupHeadSha:f}},{expectedRevision:v.revision,preCommit:async()=>{if(await l(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.executionBranch||await l(t.projectRoot,["rev-parse","HEAD"])!==f)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:ue(t,s,k,!1)}}catch(t){return c(Y(t,"direct-yolo-setup-failed"))}}async function pt(e){let t;try{const r=await K(e.projectRoot,e.storyId),o=N(e.nowIso),i=te(r.projectRoot,".neocortex/state.json"),n=await J(i,"utf8"),y=await T(r.projectRoot),h=await l(r.projectRoot,["rev-parse","HEAD"]),d=`refs/heads/${r.executionBranch}`,a=await C(r.projectRoot,{required:!0}),s=m(a.epics[r.epicId]),p=he(s?.origin_binding,r.executionBranch,r.originBranch),f=m(s?.branch_lease);if(!p)return c("direct-yolo-origin-binding-invalid");if(!f||!ie(f,e.storyId,o)||f?.sessionId!==f?.idempotencyKey)return c("direct-yolo-setup-lease-invalid");const R=await W(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(f.sessionId),idempotencyKey:String(f.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!R.ok)return c(R.reasonCode);if(t=R,h!==f.setupHeadSha||!await L(r.projectRoot,["merge-base","--is-ancestor",p.originHeadSha,h])||await l(r.projectRoot,["rev-parse",d])!==h)return c("direct-yolo-setup-head-mismatch");if((await Ee(r.projectRoot)).some(u=>u.branch===r.executionBranch&&Z(u.path)!==r.projectRoot))return c("direct-yolo-execution-branch-checked-out-elsewhere");const I=m(JSON.parse(n)),v=m(m(I?.stories)?.[e.storyId]),x=m(a.stories[e.storyId]);if(!v||!["backlog","ready_to_start"].includes(String(v.status))||v.steps_completed!==void 0&&(!Array.isArray(v.steps_completed)||v.steps_completed.length>0)||v.branch_name||v.checkpoint)return c("direct-yolo-setup-story-progress-conflict");const w=x?.status==="branch-ready"&&x.last_step===X&&Array.isArray(x.steps_completed)&&x.steps_completed.length===1&&x.steps_completed[0]===X&&Object.keys(x).sort().join(",")==="last_step,status,steps_completed";if(x&&Object.keys(x).length>0&&!w)return c("direct-yolo-setup-story-progress-conflict");const j=async()=>{if(Date.parse(String(f.expiresAt))<=(e.nowIso?Date.parse(o):Date.now())||!t||!await U(t.path,t.owner)||await J(i,"utf8")!==n||await T(r.projectRoot)!==y||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==h||!await L(r.projectRoot,["merge-base","--is-ancestor",p.originHeadSha,h])||await l(r.projectRoot,["rev-parse",d])!==h)throw new Error("direct-yolo-setup-physical-state-raced")};return w?await j():await $(r.projectRoot,u=>{const b=m(u.epics[r.epicId]),g=me(u,e.storyId);if(JSON.stringify(b?.branch_lease)!==JSON.stringify(f)||JSON.stringify(b?.origin_binding)!==JSON.stringify(p)||b?.graph_revision!==r.graphRevision||Object.keys(g).length>0)throw new Error("direct-yolo-setup-runtime-raced");g.status="branch-ready",g.last_step=X,g.steps_completed=[X]},{expectedRevision:a.revision,preCommit:j}),{ok:!0,value:Object.freeze({...ue(r,p,String(f.expiresAt),w),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:h})}}catch(r){return c(Y(r,"direct-yolo-setup-acceptance-failed"))}finally{t&&await G(t.path,t.owner).catch(()=>{})}}async function lt(e){try{const t=await K(e.projectRoot,e.storyId),r=q(await A(t.projectRoot,["diff","--cached","--name-only","-z"])),o=V(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!o.ok)return c(o.reasonCode);if(t.rootMemoryEffect&&re(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await l(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),Q(t.projectRoot,e.storyId,":")?.verdict!=="approved")return c("direct-yolo-review-artifact-not-approved");if(q(await A(t.projectRoot,["diff","--name-only","-z"])).some(S=>r.includes(S)))return c("direct-yolo-user-overlap");const y=await A(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!y)return c("direct-yolo-staged-diff-empty");const h=D(y),d=D([...t.authorizedWriteSet].sort().join("\0")),a=N(e.nowIso),s=await C(t.projectRoot,{required:!0}),p=m(s.epics[t.epicId]?.branch_lease);if(!ie(p,e.storyId,a))return c("direct-yolo-setup-handoff-owner-invalid");const f=String(p.sessionId),R=String(p.expiresAt),k=new Date(Math.min(Date.parse(R),Date.parse(a)+300*1e3)).toISOString(),I=await M(t.projectRoot,e.storyId),v=I?.state==="issued"&&I.fromSessionId===f&&I.bundleDigest===h&&I.claimRevision===d&&Date.parse(I.expiresAt)>Date.parse(a),x=v?I.expiresAt:k,w=v?I.token:le(32).toString("base64url"),j=D(w),u=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:f,tokenDigest:j,bundleDigest:h,claimRevision:d,expiresAt:x}),b=D(JSON.stringify(u)),g=await W(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:f,idempotencyKey:f,expiresAt:x,persistent:!1,createdAt:a});if(!g.ok)return c(g.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await ne(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:f,token:w,tokenDigest:j,bundleDigest:h,claimRevision:d,grantDigest:b,expiresAt:x}),await $(t.projectRoot,S=>{const E=m(P(S,t.epicId).branch_lease);if(!ie(E,e.storyId,a)||E?.sessionId!==f||E.idempotencyKey!==f)throw new Error("direct-yolo-setup-handoff-owner-raced");E.handoffGrant=u},{expectedRevision:s.revision,preCommit:async()=>{if(!await U(g.path,g.owner))throw new Error("direct-yolo-integration-lock-raced");const S=await M(t.projectRoot,e.storyId);if(!S||S.state!=="issued"||S.grantDigest!==b||S.tokenDigest!==j)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await G(g.path,g.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:f,bundleDigest:h,claimRevision:d,grantDigest:b,expiresAt:x,reused:v,publicSafe:!0})}}catch(t){return c(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function gt(e){try{const t=await K(e.projectRoot,e.storyId),r=await l(t.projectRoot,["rev-parse","HEAD"]),o=q(await A(t.projectRoot,["diff","--cached","--name-only","-z"])),i=V(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return c(i.reasonCode);t.rootMemoryEffect&&re(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:r,headRef:":",childPaths:t.authorizedWriteSet});const n=Q(t.projectRoot,e.storyId,":");if(n?.verdict!=="approved")return c("direct-yolo-review-artifact-not-approved");if(q(await A(t.projectRoot,["diff","--name-only","-z"])).some(u=>o.includes(u)))return c("direct-yolo-user-overlap");const h=await A(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!h)return c("direct-yolo-staged-diff-empty");const d=D(h),a=D([...t.authorizedWriteSet].sort().join("\0")),s=D(["direct-yolo-commit-v1",e.storyId,t.epicId,t.executionBranch,r,d,t.graphRevision,a].join("\0")),p=N(e.nowIso);let f=e.setupLeaseHandoff??await Ze(t.projectRoot,e.storyId,d,a,p);const R=await C(t.projectRoot,{required:!0}),k=m(R.epics[t.epicId]?.branch_lease),I=k?.ownerStoryId===e.storyId&&k.sessionId===s&&k.idempotencyKey===s&&typeof k.expiresAt=="string"&&Date.parse(k.expiresAt)>Date.parse(p)?k:void 0;if(I&&e.setupLeaseHandoff)return c("direct-yolo-setup-handoff-replayed");const v=m(I?.handoffConsumption);if(v){const u=await M(t.projectRoot,e.storyId);if(!u||!["consuming","consumed"].includes(u.state)||u.fromSessionId!==v.fromSessionId||u.tokenDigest!==v.tokenDigest||u.bundleDigest!==d||u.claimRevision!==a||v.bundleDigest!==d||v.claimRevision!==a||u.consumedBySessionId!==s||v.consumedBySessionId!==s)return c("direct-yolo-setup-handoff-consume-invalid");if(u.state==="consuming"){if(!u.token||D(u.token)!==u.tokenDigest)return c("direct-yolo-setup-handoff-consume-invalid");f={sessionId:u.fromSessionId,token:u.token}}}const x=I?String(I.expiresAt):new Date(Date.parse(p)+1800*1e3).toISOString(),w=await W(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:s,idempotencyKey:s,expiresAt:x,persistent:!0,createdAt:I&&typeof I.acquiredAt=="string"?I.acquiredAt:p});if(!w.ok)return c(w.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{f&&e.setupLeaseHandoff===void 0&&(await Qe(t.projectRoot,e.storyId,f.sessionId,f.token,s,p),await e.setupHandoffFault?.("after-consuming-persisted")),await $(t.projectRoot,u=>{const b=P(u,t.epicId),g=m(b.branch_lease),S=g&&Date.parse(String(g.expiresAt))>Date.parse(p),E=g?.ownerStoryId===e.storyId&&g.sessionId===s&&g.idempotencyKey===s,O=g?.ownerStoryId===e.storyId&&g.sessionId===g.idempotencyKey&&typeof g.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(g.idempotencyKey),B=S&&O&&Xe({current:g,handoff:f,storyId:e.storyId,bundleDigest:d,claimRevision:a,nowIso:p});if(f&&S&&!E&&!B)throw new Error("direct-yolo-setup-handoff-invalid");if(S&&!E&&!B)throw new Error("direct-yolo-writer-active");const _=B?m(g?.handoffGrant):void 0,H=_?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(g?.sessionId),tokenDigest:String(_.tokenDigest),bundleDigest:d,claimRevision:a,consumedBySessionId:s,consumedAt:p}:void 0;b.branch_mode="epic",b.execution_branch=t.executionBranch,b.origin_branch=t.originBranch,b.graph_revision=t.graphRevision,b.branch_lease=S&&E?g:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:s,idempotencyKey:s,acquiredAt:p,expiresAt:x,...H?{handoffConsumption:H}:{}}},{expectedRevision:R.revision,preCommit:async()=>{if(!await U(w.path,w.owner))throw new Error("direct-yolo-integration-lock-raced")}})}catch(u){throw await G(w.path,w.owner).catch(()=>{}),u}f&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Ue(t.projectRoot,t.epicId,e.storyId,f.sessionId,f.token,d,a,s,p));const j=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${r}`,`Neocortex-Bundle-Digest: ${d}`,`Neocortex-Review-Artifact-Digest: ${n.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${a}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Oe(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,bundleDigest:d,reviewArtifactDigest:n.digest,graphRevision:t.graphRevision,claimRevision:a,idempotencyKey:s,changedPaths:Object.freeze(o),trailers:j})}}catch(t){return c(Y(t,"direct-yolo-begin-failed"))}}async function mt(e){let t,r,o;try{const i=await K(e.projectRoot,e.storyId);t=i;const n=await l(i.projectRoot,["rev-parse","HEAD"]);let y=await C(i.projectRoot,{required:!0});const h=m(y.stories[e.storyId]?.checkpoint);if(h){const B=typeof h.headSha=="string"?h.headSha:"",_=typeof h.graphRevision=="string"?h.graphRevision:"",H=/^[a-f0-9]{40,64}$/.test(B)?q(await A(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",B])):[],z=V(H,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(B)&&await L(i.projectRoot,["merge-base","--is-ancestor",B,n]))||!/^[a-f0-9]{64}$/.test(_)||!z.ok)return c("direct-yolo-replay-invalid");const Be=await se(e,i.projectRoot,n,_);if(!await Ie(i.projectRoot,h,e.storyId,i.epicId,i.executionBranch,Be.transientAuthority,i.authorizedWriteSet))return c("direct-yolo-replay-invalid");if(!await de(i.projectRoot,i.executionBranch,n,H))return c("direct-yolo-replay-head-raced");if(e.push&&!await ke(i.projectRoot,e.remote??"origin",i.executionBranch,B))return c("direct-yolo-remote-head-mismatch");const ye=Array.isArray(h.receiptRefs)?h.receiptRefs.find(pe=>typeof pe=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(pe)):void 0;return ye&&typeof h.idempotencyKey=="string"&&await Te(i.projectRoot,{storyId:e.storyId,idempotencyKey:h.idempotencyKey,ownerDigest:ye.slice(20)}),{ok:!0,value:h}}const d=n,a=await l(i.projectRoot,["rev-parse",`${d}^`]),s=await A(i.projectRoot,["show","--no-patch","--format=%B",d]),p=q(await A(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",d])),f=V(p,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!f.ok)return c(f.reasonCode);i.rootMemoryEffect&&re(i.projectRoot,i.rootMemoryEffect,{storyId:e.storyId,executionBranch:i.executionBranch,baseSha:a,headRef:d,childPaths:i.authorizedWriteSet});const R=F(s,"Neocortex-Bundle-Digest"),k=F(s,"Neocortex-Graph-Revision"),I=F(s,"Neocortex-Claim-Revision"),v=new Map([["Neocortex-Story",e.storyId],["Neocortex-Epic",i.epicId],["Neocortex-Execution-Branch",i.executionBranch],["Neocortex-Prepared-Base",a],["Neocortex-Graph-Revision",i.graphRevision],["Neocortex-Claim-Revision",D([...i.authorizedWriteSet].sort().join("\0"))]]);if(!R||!/^[a-f0-9]{64}$/.test(R)||!k||!I||[...v].some(([B,_])=>F(s,B)!==_))return c("direct-yolo-trailers-invalid");const x=Q(i.projectRoot,e.storyId,d);if(x?.verdict!=="approved")return c("direct-yolo-review-artifact-not-approved");const w=F(s,"Neocortex-Review-Artifact-Digest");if(w!==void 0&&w!==x.digest)return c("direct-yolo-review-artifact-digest-mismatch");const j=D(await A(i.projectRoot,["diff","--binary","--full-index",`${a}..${d}`]));if(R!==j)return c("direct-yolo-bundle-digest-mismatch");const u=D(["direct-yolo-commit-v1",e.storyId,i.epicId,i.executionBranch,a,R,k,I].join("\0")),b=m(y.epics[i.epicId]?.branch_lease),g=N(e.nowIso),S=b?.ownerStoryId===e.storyId&&b.idempotencyKey===u&&b.sessionId===u&&Date.parse(String(b.expiresAt))>Date.now()?b:void 0;if(b&&Date.parse(String(b.expiresAt))>Date.now()&&!S)return c("direct-yolo-writer-active");const E=S??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:u,idempotencyKey:u,acquiredAt:g,expiresAt:new Date(Date.parse(g)+1800*1e3).toISOString()},O=await W(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:u,idempotencyKey:u,expiresAt:String(E.expiresAt),persistent:!0,createdAt:String(E.acquiredAt)});if(!O.ok)return c(O.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");o=O,S||(y=(await $(i.projectRoot,_=>{const H=P(_,i.epicId),z=m(H.branch_lease);if(z&&Date.parse(String(z.expiresAt))>Date.parse(g))throw new Error("direct-yolo-writer-active");if(H.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");H.branch_lease=E},{expectedRevision:y.revision})).document),r=E;{const B=await se(e,i.projectRoot,d,i.graphRevision);if(!await de(i.projectRoot,i.executionBranch,d,p))return c("direct-yolo-head-raced");if(e.push){const z=ee(e.remote??"origin");if(await l(i.projectRoot,["push",z,i.executionBranch]),!await De(i.projectRoot,z,i.executionBranch,d))return c("direct-yolo-remote-head-mismatch")}const _=await Se({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:a,headSha:d,bundleDigest:R,graphRevision:k,claimRevision:I,idempotencyKey:u,qaExecution:B,physicalLockOwnerDigest:ge(O.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await xe({projectRoot:i.projectRoot,checkpoint:_,remote:e.push?e.remote??"origin":void 0,expectedRevision:y.revision,expectedLease:E,expectedGraphRevision:i.graphRevision,physicalLockPath:O.path,physicalLockOwner:O.owner,transientAuthority:B.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await e.afterCheckpointPersist?.(),{ok:!0,value:_}):c("direct-yolo-checkpoint-persist-failed")}}catch(i){return c(Y(i,"direct-yolo-finalize-failed"))}finally{o&&await G(o.path,o.owner).catch(()=>{}),t&&r?await ce(t.projectRoot,t.epicId,r).catch(()=>{}):t&&await tt(t,e.storyId).catch(()=>{})}}async function wt(e){try{const t=await K(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return c("direct-yolo-recovery-commit-invalid");const r=await l(t.projectRoot,["rev-parse",e.commitSha]);if(Ke[e.storyId]!==r)return c("direct-yolo-recovery-not-allowlisted");if(await l(t.projectRoot,["rev-parse","HEAD"])!==r)return c("direct-yolo-recovery-head-mismatch");await l(t.projectRoot,["merge-base","--is-ancestor",r,`refs/heads/${t.executionBranch}`]);const o=await l(t.projectRoot,["rev-parse",`${r}^`]),i=await A(t.projectRoot,["diff","--binary","--full-index",`${o}..${r}`]),n=q(await A(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",r]));if(!V(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return c("direct-yolo-recovery-write-set-invalid");const h=D(i),d=D([...n].sort().join("\0")),a=D(["legacy-direct-yolo-recovery-v1",e.storyId,r].join("\0")),s=N(e.nowIso),p=new Date(Date.parse(s)+1800*1e3).toISOString(),f=await C(t.projectRoot,{required:!0}),R=await W(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:a,idempotencyKey:a,expiresAt:p,persistent:!0,createdAt:s});if(!R.ok)return c(R.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const k={schemaVersion:1,ownerStoryId:e.storyId,sessionId:a,idempotencyKey:a,acquiredAt:s,expiresAt:p};let I=!1;try{const v=await $(t.projectRoot,g=>{const S=P(g,t.epicId),E=m(S.branch_lease);if(E&&Date.parse(String(E.expiresAt))>Date.parse(s)&&!ae(E,k))throw new Error("direct-yolo-recovery-writer-active");if(S.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");S.branch_mode="epic",S.execution_branch=t.executionBranch,S.origin_branch=t.originBranch,S.branch_lease=k},{expectedRevision:f.revision});I=!0;const x=await se(e,t.projectRoot,r,t.graphRevision);if(!await de(t.projectRoot,t.executionBranch,r,n))return c("direct-yolo-recovery-head-raced");if(e.push){const g=ee(e.remote??"origin"),S=(await l(t.projectRoot,["ls-remote","--heads",g,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!S||!await L(t.projectRoot,["merge-base","--is-ancestor",r,S]))return c("direct-yolo-recovery-remote-proof-missing")}const w=await Se({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,headSha:r,bundleDigest:h,graphRevision:t.graphRevision,claimRevision:d,idempotencyKey:a,qaExecution:x,physicalLockOwnerDigest:ge(R.owner),nowIso:s,legacyReceiptRef:void 0}),j=await Ne(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,headSha:r,bundleDigest:h,graphRevision:t.graphRevision});if(!j)return c("direct-yolo-recovery-evidence-invalid");const u=Object.freeze({...w,receiptRefs:Object.freeze([...w.receiptRefs,j])});return await xe({projectRoot:t.projectRoot,checkpoint:u,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:v.document.revision,expectedLease:k,expectedGraphRevision:t.graphRevision,physicalLockPath:R.path,physicalLockOwner:R.owner,transientAuthority:x.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:u}:c("direct-yolo-recovery-persist-failed")}finally{await G(R.path,R.owner).catch(()=>{}),I&&await ce(t.projectRoot,t.epicId,k).catch(()=>{})}}catch(t){return c(Y(t,"direct-yolo-recovery-failed"))}}async function ve(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const r=Z(e),o=m(JSON.parse(await J(te(r,".neocortex/state.json"),"utf8"))),i=await C(r,{required:!0}),n=$e(o,i),y=m(n.stories),h=m(n.epics),d=m(y?.[t]),a=String(d?.epic_id??t.split(".")[0]),s=m(h?.[a]),p=String(s?.execution_branch??""),f=String(s?.origin_branch??""),R=String(s?.graph_revision??""),k=Array.isArray(d?.files_to_modify)?[...new Set(d.files_to_modify.filter(v=>typeof v=="string"&&fe(v)))].sort():[];if(!d)throw new Error("direct-yolo-story-state-missing");if(s?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Ae(p)||!await L(r,["check-ref-format","--branch",p]))throw new Error("direct-yolo-execution-branch-invalid");if(!Ae(f)||!await L(r,["check-ref-format","--branch",f]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(R))throw new Error("direct-yolo-graph-revision-invalid");const I=await qe({projectRoot:r,storyId:t,graphRevision:R,executionBranch:p,childPaths:k});return{projectRoot:r,storyId:t,story:d,epicId:a,executionBranch:p,originBranch:f,graphRevision:R,authorizedWriteSet:k,rootMemoryEffect:I}}async function K(e,t){const r=await ve(e,t);if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return r}async function Se(e){const t=e.nowIso,r=await A(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),o=q(await A(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=ze({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:r,changedPaths:o}),n=Pe({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),y=`story-qa:${n}`,h=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:y}),d=Q(e.projectRoot,e.storyId,e.headSha);if(d?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const a=D(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,y,D(r),[...o].sort().join(","),d.digest].join("\0")),s=`story-review:${a}`,p=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:a,reviewArtifactDigest:d.digest,qaReceiptRef:y,verdict:"approved",reviewedAt:t,receiptRef:s}),f=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,y,s,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(f),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:h,reviewReceipt:p,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function xe(e){const{projectRoot:t,checkpoint:r,remote:o}=e;let i=!1;return await $(t,n=>{const y=P(n,r.epicId);if(e.expectedLease){const s=m(y.branch_lease);if(!ae(s,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(s?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(y.graph_revision!==e.expectedGraphRevision||r.graphRevision!==e.expectedGraphRevision)throw new Error("direct-yolo-graph-revision-raced")}const h=me(n,r.storyId),d=m(h.checkpoint);if(d&&d.headSha!==r.headSha){i=!0;return}h.checkpoint=r,h.status="done",h.last_step=Re;const a=Array.isArray(h.steps_completed)?h.steps_completed.filter(s=>typeof s=="string"):[];h.steps_completed=[...new Set([...a,Je,Re])],y.branch_lease=null},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");if(await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==r.branch||await l(t,["rev-parse","HEAD"])!==r.headSha)throw new Error("direct-yolo-checkpoint-head-raced");if(!await Ie(t,r,r.storyId,r.epicId,r.branch,e.transientAuthority,e.authorizedWriteSet))throw new Error("direct-yolo-checkpoint-physical-invalid");if(e.physicalLockPath&&e.physicalLockOwner&&!await U(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(o&&!(e.remotePolicy==="ancestor-recovery"?await ke(t,o,r.branch,r.headSha):await De(t,o,r.branch,r.headSha)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function ke(e,t,r,o){const i=ee(t),n=(await l(e,["ls-remote","--heads",i,`refs/heads/${r}`])).split(/\s+/)[0];return!!(n&&await L(e,["merge-base","--is-ancestor",o,n]))}function ie(e,t,r){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(r))}async function be(e,t){const r=await Fe(e),o=await We(r,"handoffs"),i=`direct-${D(t)}.json`;return{parent:o,name:i,path:te(o,i)}}async function ne(e,t){const r=await be(e,t.storyId);await Ye(r.parent,r.name,`${JSON.stringify(t,null,2)}
2
- `),await we(r.path,r.parent)}async function M(e,t){try{const r=await be(e,t);await we(r.path,r.parent);const o=JSON.parse(await J(r.path,"utf8")),i=o.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:o.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(o).sort().join("\0")!==[...i].sort().join("\0")||o.schemaVersion!==1||o.kind!=="direct-yolo-setup-handoff-token"||o.state!=="issued"&&o.state!=="consuming"&&o.state!=="consumed"||o.storyId!==t||typeof o.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(o.fromSessionId)||![o.tokenDigest,o.bundleDigest,o.claimRevision,o.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof o.expiresAt!="string"||!Number.isFinite(Date.parse(o.expiresAt))||(o.state==="issued"||o.state==="consuming")&&(typeof o.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(o.token))||o.state==="consuming"&&(typeof o.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(o.consumedBySessionId)||typeof o.consumeStartedAt!="string"||!Number.isFinite(Date.parse(o.consumeStartedAt)))||o.state==="consumed"&&(typeof o.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(o.consumedBySessionId)||typeof o.consumedAt!="string"||!Number.isFinite(Date.parse(o.consumedAt)))?void 0:o}catch{return}}async function Ze(e,t,r,o,i){const n=await M(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==r||n.claimRevision!==o||Date.parse(n.expiresAt)<=Date.parse(i)||D(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function Qe(e,t,r,o,i,n){const y=await M(e,t);if(!y||y.state==="consumed"||y.fromSessionId!==r||y.token!==o||y.tokenDigest!==D(o))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(y.state==="consuming"){if(y.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await ne(e,{...y,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function Ue(e,t,r,o,i,n,y,h,d){const a=await M(e,r);if(a?.state==="consumed"&&a.fromSessionId===o&&a.consumedBySessionId===h)return;const s=await C(e,{required:!0}),p=m(s.epics[t]?.branch_lease),f=m(p?.handoffConsumption);if(!a||a.state!=="consuming"||a.fromSessionId!==o||a.token!==i||a.tokenDigest!==D(i)||a.bundleDigest!==n||a.claimRevision!==y||a.consumedBySessionId!==h||p?.ownerStoryId!==r||p.sessionId!==h||f?.kind!=="direct-yolo-setup-handoff-consumption"||f.state!=="consumed"||f.fromSessionId!==o||f.tokenDigest!==a.tokenDigest||f.bundleDigest!==n||f.claimRevision!==y||f.consumedBySessionId!==h)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await ne(e,{schemaVersion:1,kind:a.kind,state:"consumed",storyId:r,fromSessionId:o,tokenDigest:a.tokenDigest,bundleDigest:a.bundleDigest,claimRevision:a.claimRevision,grantDigest:a.grantDigest,expiresAt:a.expiresAt,consumedBySessionId:h,consumedAt:d})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function Xe(e){const t=m(e.current?.handoffGrant),r=e.handoff?.token,o=typeof r=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(r)?D(r):void 0;return!!(t&&o&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&et(t.tokenDigest,o))}function et(e,t){const r=Buffer.from(e,"hex"),o=Buffer.from(t,"hex");return r.length===32&&o.length===32&&He(r,o)}function ae(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(r=>e[r]===t[r]))}async function ce(e,t,r){await $(e,o=>{const i=P(o,t),n=m(i.branch_lease);ae(n,r)&&(i.branch_lease=null)})}async function tt(e,t){const r=await C(e.projectRoot,{required:!0}),o=m(r.epics[e.epicId]?.branch_lease);if(!o||o.ownerStoryId!==t||!je(o.sessionId)||!je(o.idempotencyKey)||!Number.isFinite(Date.parse(String(o.acquiredAt)))||!Number.isFinite(Date.parse(String(o.expiresAt))))return;const i=await W(e.projectRoot,{kind:"direct",storyId:t,sessionId:String(o.sessionId),idempotencyKey:String(o.idempotencyKey),createdAt:String(o.acquiredAt),expiresAt:String(o.expiresAt),persistent:!0});if(!i.ok)return;await G(i.path,i.owner)&&await ce(e.projectRoot,e.epicId,o)}async function se(e,t,r,o){const i=await Ge(t,{headSha:r,graphRevision:o,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:r});const n=Me(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Ve,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function de(e,t,r,o){return await l(e,["rev-parse","HEAD"])!==r||await l(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await L(e,["diff","--cached","--quiet"])?!1:L(e,["diff","--quiet","HEAD","--",...o])}async function De(e,t,r,o){const i=ee(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${r}`])).split(/\s+/)[0]===o}function V(e,t,r,o){if(e.length===0||e.some(n=>!fe(n)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=[".neocortex/state.json",`docs/stories/${r}.story.md`,`.neocortex/stories/${r}/qa-gate-result.json`,`.neocortex/stories/${r}/validation-evidence.md`,`.neocortex/stories/${r}/review.md`];return!i.every(n=>e.includes(n))||!i.every(n=>t.includes(n))?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:o&&(o.storyId!==r||o.childClaimRevision!==D([...t].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(n=>!t.includes(n)&&!o?.files.some(y=>y.path===n))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function fe(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function je(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Ae(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function ee(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function F(e,t){const r=`${t}: `,o=e.split(`
3
- `).map(i=>i.trim()).filter(i=>i.startsWith(r)).map(i=>i.slice(r.length));return o.length===1?o[0]:void 0}function D(e){return Le("sha256").update(e).digest("hex")}function q(e){return e.split("\0").filter(Boolean)}function N(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function m(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function he(e,t,r){const o=m(e);if(!(!o||o.schemaVersion!==1||o.originBranch!==r||o.executionBranch!==t||o.capturedFromCurrentCheckout!==!0||typeof o.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(o.originHeadSha)||typeof o.capturedAt!="string"||!Number.isFinite(Date.parse(o.capturedAt))))return o}function ue(e,t,r,o){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:r,reused:o,publicSafe:!0})}async function T(e){const t=q(await A(e,["ls-files","--others","--exclude-standard","-z"])).sort(),r=await Promise.all(t.map(async o=>{if(!fe(o))throw new Error("direct-yolo-checkout-payload-invalid");return`${o}\0${await l(e,["hash-object","--no-filters","--",o])}`}));return D([await A(e,["diff","--cached","--binary","--full-index"]),await A(e,["diff","--binary","--full-index"]),await A(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...r].join("\0"))}async function It(e){const t=Z(e),r=await l(t,["rev-parse","HEAD"]),o=await l(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await T(t);if(await l(t,["rev-parse","HEAD"])!==r||await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==o)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:r,branch:o,payloadDigest:i})}async function Ee(e){const t=[];let r;for(const o of(await A(e,["worktree","list","--porcelain"])).split(`
4
- `))o.startsWith("worktree ")?(r={path:o.slice(9)},t.push(r)):r&&o.startsWith("branch refs/heads/")&&(r.branch=o.slice(18));return t}function Y(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(e.message)?e.message:t}function c(e){return{ok:!1,reasonCode:e}}async function l(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function A(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function L(e,t){try{return await oe("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{pt as acceptDirectYoloSetupCheckpoint,gt as beginDirectYoloStoryCommit,It as captureDirectYoloCheckoutEvidence,mt as finalizeDirectYoloStoryCheckpoint,lt as issueDirectYoloSetupLeaseHandoff,yt as prepareDirectYoloSetup,wt as recoverLegacyDirectYoloStoryCheckpoint};
1
+ import{execFile as He}from"node:child_process";import{createHash as Le,randomBytes as me,timingSafeEqual as Ce}from"node:crypto";import{readFile as Z}from"node:fs/promises";import{join as te,resolve as M}from"node:path";import{promisify as Oe}from"node:util";import{readRootMemoryEffectForCheckpoint as qe}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as $e,verifyRootMemoryPhysicalWriteSet as re}from"../private-execution/root-memory-git-evidence.js";import{acquireGitLifecyclePhysicalIntegrationLock as V,applyGitLifecycleRuntimeOverlay as Pe,computeImmutableStoryQaEvidenceDigest as ze,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as we,computeP205StoryQaEvidenceDigest as Ne,computeLegacyDirectYoloRecoveryReceiptRef as Ke,ensureRuntimeEpic as N,ensureRuntimeStory as Re,ensureGitLifecyclePrivateChildDirectory as Me,executeP205TransientAuthority as Ve,projectP205TransientExecutionEvidence as We,publicStoryReviewArtifactFromGit as Q,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Ge,mutateGitLifecycleRuntime as P,P205_COMPLETE_COMMAND as Fe,readGitLifecycleRuntime as C,gitLifecycleRuntimeDirectory as Te,assertGitLifecyclePrivateFile as Ie,releaseGitLifecyclePhysicalIntegrationLock as W,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as Je,verifyGitLifecyclePhysicalIntegrationLock as U,verifyAcceptedGitLifecycleStoryCheckpoint as ve}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as Ye}from"./secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ze,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as xe,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as X}from"./git-lifecycle-step-ids.js";const oe=Oe(He),ie=3600*1e3;async function gt(e){let t,o=!1;try{const r=await Se(e.projectRoot,e.storyId),i=K(e.nowIso),n=Date.parse(i),g=await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),s=await y(r.projectRoot,["rev-parse","HEAD"]),h=await C(r.projectRoot,{required:!0}),c=w(h.epics[r.epicId]),d=w(c?.branch_lease),l=e.expiredSetupRecovery;if(l&&!ot(l,h.revision,d,e.storyId,n))return a("direct-yolo-expired-setup-recovery-invalid");const u=d&&Number.isFinite(Date.parse(String(d.expiresAt)))&&Date.parse(String(d.expiresAt))>n;if(u&&d?.ownerStoryId!==e.storyId)return a("direct-yolo-writer-active");let m=he(c?.origin_binding,r.executionBranch,r.originBranch);if(g===r.executionBranch){if(!m)return a("direct-yolo-origin-binding-invalid")}else{if(g!==r.originBranch)return a("direct-yolo-current-branch-mismatch");if(m&&m.originHeadSha!==s){if(!l||!await B(r.projectRoot,["merge-base","--is-ancestor",m.originHeadSha,s]))return a("direct-yolo-origin-binding-conflict");const p=`refs/heads/${r.executionBranch}`;if(!await B(r.projectRoot,["show-ref","--verify","--quiet",p]))return a("direct-yolo-execution-branch-missing");const I=await y(r.projectRoot,["rev-parse",p]);if(!await B(r.projectRoot,["merge-base","--is-ancestor",I,s]))return a("direct-yolo-execution-branch-diverged")}if(m??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:s,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await ye(r.projectRoot)).some(p=>p.branch===r.executionBranch&&M(p.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const f=await q(r.projectRoot),R=`refs/heads/${r.executionBranch}`;if(await B(r.projectRoot,["show-ref","--verify","--quiet",R])){const p=await y(r.projectRoot,["rev-parse",R]);if(p!==s){if(!await B(r.projectRoot,["merge-base","--is-ancestor",p,s]))return a("direct-yolo-execution-branch-diverged");l||await y(r.projectRoot,["update-ref",R,s,p])}l?t={checkoutBefore:f,executionRef:R,executionBranch:r.executionBranch,executionHead:p,originBranch:r.originBranch,originHead:s}:await y(r.projectRoot,["switch",r.executionBranch])}else{if(l)return a("direct-yolo-execution-branch-missing");await y(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await q(r.projectRoot)!==f)return a("direct-yolo-checkout-payload-raced")}const S=t?.originHead??await y(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return a("direct-yolo-current-branch-mismatch");if(u&&d?.ownerStoryId===e.storyId)return d.setupHeadSha!==S?a("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:pe(r,m,String(d.expiresAt),!0)};const v=i,x=new Date(n+3600*1e3).toISOString(),b=`setup-${me(32).toString("hex")}`,D=l?h:await C(r.projectRoot,{required:!0});return await P(r.projectRoot,A=>{const f=N(A,r.epicId),R=w(f.branch_lease);if(l&&JSON.stringify(R)!==JSON.stringify(l.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(R&&Date.parse(String(R.expiresAt))>n&&R.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const p=he(f.origin_binding,r.executionBranch,r.originBranch);if(f.origin_binding&&!p)throw new Error("direct-yolo-origin-binding-conflict");if(p&&JSON.stringify(p)!==JSON.stringify(m))throw new Error("direct-yolo-origin-binding-conflict");f.branch_mode="epic",f.execution_branch=r.executionBranch,f.origin_branch=r.originBranch,f.graph_revision=r.graphRevision,f.origin_binding=m,f.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:b,idempotencyKey:b,acquiredAt:v,expiresAt:x,setupHeadSha:S}},{expectedRevision:l?.expectedRuntimeRevision??D.revision,preCommit:async()=>{if(t){if((await ye(r.projectRoot)).some(f=>f.branch===r.executionBranch&&M(f.path)!==r.projectRoot)||await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await y(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await q(r.projectRoot)!==t.checkoutBefore||!await B(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await y(r.projectRoot,["rev-parse",t.executionRef])!==t.executionHead)throw new Error("direct-yolo-expired-setup-recovery-raced");if(o=!0,t.executionHead!==t.originHead&&await y(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await y(r.projectRoot,["switch",r.executionBranch]),await q(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await y(r.projectRoot,["rev-parse","HEAD"])!==S)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:pe(r,m,x,!1)}}catch(r){return o&&t&&await it(M(e.projectRoot),t).catch(()=>{}),a(Y(r,"direct-yolo-setup-failed"))}}async function mt(e){let t;try{const o=await F(e.projectRoot,e.storyId),r=K(e.nowIso),i=te(o.projectRoot,".neocortex/state.json"),n=await Z(i,"utf8"),g=await q(o.projectRoot),s=await y(o.projectRoot,["rev-parse","HEAD"]),h=`refs/heads/${o.executionBranch}`,c=await C(o.projectRoot,{required:!0}),d=w(c.epics[o.epicId]),l=he(d?.origin_binding,o.executionBranch,o.originBranch),u=w(d?.branch_lease);if(!l)return a("direct-yolo-origin-binding-invalid");if(!u||!ne(u,e.storyId,r)||u?.sessionId!==u?.idempotencyKey)return a("direct-yolo-setup-lease-invalid");const m=await V(o.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(u.sessionId),idempotencyKey:String(u.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!m.ok)return a(m.reasonCode);if(t=m,s!==u.setupHeadSha||!await B(o.projectRoot,["merge-base","--is-ancestor",l.originHeadSha,s])||await y(o.projectRoot,["rev-parse",h])!==s)return a("direct-yolo-setup-head-mismatch");if((await ye(o.projectRoot)).some(f=>f.branch===o.executionBranch&&M(f.path)!==o.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const v=w(JSON.parse(n)),x=w(w(v?.stories)?.[e.storyId]),b=w(c.stories[e.storyId]);if(!x||!["backlog","ready_to_start"].includes(String(x.status))||x.steps_completed!==void 0&&(!Array.isArray(x.steps_completed)||x.steps_completed.length>0)||x.branch_name||x.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const D=b?.status==="branch-ready"&&b.last_step===X&&Array.isArray(b.steps_completed)&&b.steps_completed.length===1&&b.steps_completed[0]===X&&Object.keys(b).sort().join(",")==="last_step,status,steps_completed";if(b&&Object.keys(b).length>0&&!D)return a("direct-yolo-setup-story-progress-conflict");const A=async()=>{if(Date.parse(String(u.expiresAt))<=(e.nowIso?Date.parse(r):Date.now())||!t||!await U(t.path,t.owner)||await Z(i,"utf8")!==n||await q(o.projectRoot)!==g||await y(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch||await y(o.projectRoot,["rev-parse","HEAD"])!==s||!await B(o.projectRoot,["merge-base","--is-ancestor",l.originHeadSha,s])||await y(o.projectRoot,["rev-parse",h])!==s)throw new Error("direct-yolo-setup-physical-state-raced")};return D?await A():await P(o.projectRoot,f=>{const R=w(f.epics[o.epicId]),p=Re(f,e.storyId);if(JSON.stringify(R?.branch_lease)!==JSON.stringify(u)||JSON.stringify(R?.origin_binding)!==JSON.stringify(l)||R?.graph_revision!==o.graphRevision||Object.keys(p).length>0)throw new Error("direct-yolo-setup-runtime-raced");p.status="branch-ready",p.last_step=X,p.steps_completed=[X]},{expectedRevision:c.revision,preCommit:A}),{ok:!0,value:Object.freeze({...pe(o,l,String(u.expiresAt),D),checkpointAccepted:!0,graphRevision:o.graphRevision,headSha:s})}}catch(o){return a(Y(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await W(t.path,t.owner).catch(()=>{})}}async function wt(e){try{const t=await F(e.projectRoot,e.storyId),o=O(await j(t.projectRoot,["diff","--cached","--name-only","-z"])),r=T(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return a(r.reasonCode);if(t.rootMemoryEffect&&re(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await y(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),Q(t.projectRoot,e.storyId,":")?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(O(await j(t.projectRoot,["diff","--name-only","-z"])).some(I=>o.includes(I)))return a("direct-yolo-user-overlap");const g=await j(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!g)return a("direct-yolo-staged-diff-empty");const s=k(g),h=k([...t.authorizedWriteSet].sort().join("\0")),c=K(e.nowIso),d=await C(t.projectRoot,{required:!0}),l=w(d.epics[t.epicId]?.branch_lease);if(!ne(l,e.storyId,c))return a("direct-yolo-setup-handoff-owner-invalid");const u=String(l.sessionId),m=String(l.expiresAt),S=new Date(Math.min(Date.parse(m),Date.parse(c)+300*1e3)).toISOString(),v=await G(t.projectRoot,e.storyId),x=v?.state==="issued"&&v.fromSessionId===u&&v.bundleDigest===s&&v.claimRevision===h&&Date.parse(v.expiresAt)>Date.parse(c),b=x?v.expiresAt:S,D=x?v.token:me(32).toString("base64url"),A=k(D),f=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:u,tokenDigest:A,bundleDigest:s,claimRevision:h,expiresAt:b}),R=k(JSON.stringify(f)),p=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:u,idempotencyKey:u,expiresAt:b,persistent:!1,createdAt:c});if(!p.ok)return a(p.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await ae(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:u,token:D,tokenDigest:A,bundleDigest:s,claimRevision:h,grantDigest:R,expiresAt:b}),await P(t.projectRoot,I=>{const E=w(N(I,t.epicId).branch_lease);if(!ne(E,e.storyId,c)||E?.sessionId!==u||E.idempotencyKey!==u)throw new Error("direct-yolo-setup-handoff-owner-raced");E.handoffGrant=f},{expectedRevision:d.revision,preCommit:async()=>{if(!await U(p.path,p.owner))throw new Error("direct-yolo-integration-lock-raced");const I=await G(t.projectRoot,e.storyId);if(!I||I.state!=="issued"||I.grantDigest!==R||I.tokenDigest!==A)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await W(p.path,p.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:u,bundleDigest:s,claimRevision:h,grantDigest:R,expiresAt:b,reused:x,publicSafe:!0})}}catch(t){return a(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function Rt(e){try{const t=await F(e.projectRoot,e.storyId),o=await y(t.projectRoot,["rev-parse","HEAD"]),r=O(await j(t.projectRoot,["diff","--cached","--name-only","-z"])),i=T(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return a(i.reasonCode);t.rootMemoryEffect&&re(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=Q(t.projectRoot,e.storyId,":");if(n?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(O(await j(t.projectRoot,["diff","--name-only","-z"])).some(f=>r.includes(f)))return a("direct-yolo-user-overlap");const s=await j(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!s)return a("direct-yolo-staged-diff-empty");const h=k(s),c=k([...t.authorizedWriteSet].sort().join("\0")),d=k(["direct-yolo-commit-v1",e.storyId,t.epicId,t.executionBranch,o,h,t.graphRevision,c].join("\0")),l=K(e.nowIso);let u=e.setupLeaseHandoff??await Qe(t.projectRoot,e.storyId,h,c,l);const m=await C(t.projectRoot,{required:!0}),S=w(m.epics[t.epicId]?.branch_lease),v=S?.ownerStoryId===e.storyId&&S.sessionId===d&&S.idempotencyKey===d&&typeof S.expiresAt=="string"&&Date.parse(S.expiresAt)>Date.parse(l)?S:void 0;if(v&&e.setupLeaseHandoff)return a("direct-yolo-setup-handoff-replayed");const x=w(v?.handoffConsumption);if(x){const f=await G(t.projectRoot,e.storyId);if(!f||!["consuming","consumed"].includes(f.state)||f.fromSessionId!==x.fromSessionId||f.tokenDigest!==x.tokenDigest||f.bundleDigest!==h||f.claimRevision!==c||x.bundleDigest!==h||x.claimRevision!==c||f.consumedBySessionId!==d||x.consumedBySessionId!==d)return a("direct-yolo-setup-handoff-consume-invalid");if(f.state==="consuming"){if(!f.token||k(f.token)!==f.tokenDigest)return a("direct-yolo-setup-handoff-consume-invalid");u={sessionId:f.fromSessionId,token:f.token}}}const b=v?String(v.expiresAt):new Date(Date.parse(l)+ie).toISOString(),D=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:d,idempotencyKey:d,expiresAt:b,persistent:!0,createdAt:v&&typeof v.acquiredAt=="string"?v.acquiredAt:l});if(!D.ok)return a(D.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{u&&e.setupLeaseHandoff===void 0&&(await Ue(t.projectRoot,e.storyId,u.sessionId,u.token,d,l),await e.setupHandoffFault?.("after-consuming-persisted")),await P(t.projectRoot,f=>{const R=N(f,t.epicId),p=w(R.branch_lease),I=p&&Date.parse(String(p.expiresAt))>Date.parse(l),E=p?.ownerStoryId===e.storyId&&p.sessionId===d&&p.idempotencyKey===d,$=p?.ownerStoryId===e.storyId&&p.sessionId===p.idempotencyKey&&typeof p.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(p.idempotencyKey),_=I&&$&&et({current:p,handoff:u,storyId:e.storyId,bundleDigest:h,claimRevision:c,nowIso:l});if(u&&I&&!E&&!_)throw new Error("direct-yolo-setup-handoff-invalid");if(I&&!E&&!_)throw new Error("direct-yolo-writer-active");const H=_?w(p?.handoffGrant):void 0,L=H?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(p?.sessionId),tokenDigest:String(H.tokenDigest),bundleDigest:h,claimRevision:c,consumedBySessionId:d,consumedAt:l}:void 0;R.branch_mode="epic",R.execution_branch=t.executionBranch,R.origin_branch=t.originBranch,R.graph_revision=t.graphRevision,R.branch_lease=I&&E?p:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:d,idempotencyKey:d,acquiredAt:l,expiresAt:b,...L?{handoffConsumption:L}:{}}},{expectedRevision:m.revision,preCommit:async()=>{if(!await U(D.path,D.owner))throw new Error("direct-yolo-integration-lock-raced")}})}catch(f){throw await W(D.path,D.owner).catch(()=>{}),f}u&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Xe(t.projectRoot,t.epicId,e.storyId,u.sessionId,u.token,h,c,d,l));const A=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${h}`,`Neocortex-Review-Artifact-Digest: ${n.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${c}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${$e(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:h,reviewArtifactDigest:n.digest,graphRevision:t.graphRevision,claimRevision:c,idempotencyKey:d,changedPaths:Object.freeze(r),trailers:A})}}catch(t){return a(Y(t,"direct-yolo-begin-failed"))}}async function It(e){let t,o,r;try{const i=await F(e.projectRoot,e.storyId);t=i;const n=await y(i.projectRoot,["rev-parse","HEAD"]);let g=await C(i.projectRoot,{required:!0});const s=w(g.stories[e.storyId]?.checkpoint);if(s){const _=typeof s.headSha=="string"?s.headSha:"",H=typeof s.graphRevision=="string"?s.graphRevision:"",L=/^[a-f0-9]{40,64}$/.test(_)?O(await j(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",_])):[],z=T(L,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(_)&&await B(i.projectRoot,["merge-base","--is-ancestor",_,n]))||!/^[a-f0-9]{64}$/.test(H)||!z.ok)return a("direct-yolo-replay-invalid");const _e=await de(e,i.projectRoot,n,H);if(!await ve(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,_e.transientAuthority,i.authorizedWriteSet))return a("direct-yolo-replay-invalid");if(!await fe(i.projectRoot,i.executionBranch,n,L))return a("direct-yolo-replay-head-raced");if(e.push&&!await De(i.projectRoot,e.remote??"origin",i.executionBranch,_))return a("direct-yolo-remote-head-mismatch");const le=Array.isArray(s.receiptRefs)?s.receiptRefs.find(ge=>typeof ge=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(ge)):void 0;return le&&typeof s.idempotencyKey=="string"&&await Je(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:le.slice(20)}),{ok:!0,value:s}}const h=n,c=await y(i.projectRoot,["rev-parse",`${h}^`]),d=await j(i.projectRoot,["show","--no-patch","--format=%B",h]),l=O(await j(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",h])),u=T(l,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!u.ok)return a(u.reasonCode);i.rootMemoryEffect&&re(i.projectRoot,i.rootMemoryEffect,{storyId:e.storyId,executionBranch:i.executionBranch,baseSha:c,headRef:h,childPaths:i.authorizedWriteSet});const m=J(d,"Neocortex-Bundle-Digest"),S=J(d,"Neocortex-Graph-Revision"),v=J(d,"Neocortex-Claim-Revision"),x=new Map([["Neocortex-Story",e.storyId],["Neocortex-Epic",i.epicId],["Neocortex-Execution-Branch",i.executionBranch],["Neocortex-Prepared-Base",c],["Neocortex-Graph-Revision",i.graphRevision],["Neocortex-Claim-Revision",k([...i.authorizedWriteSet].sort().join("\0"))]]);if(!m||!/^[a-f0-9]{64}$/.test(m)||!S||!v||[...x].some(([_,H])=>J(d,_)!==H))return a("direct-yolo-trailers-invalid");const b=Q(i.projectRoot,e.storyId,h);if(b?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");const D=J(d,"Neocortex-Review-Artifact-Digest");if(D!==void 0&&D!==b.digest)return a("direct-yolo-review-artifact-digest-mismatch");const A=k(await j(i.projectRoot,["diff","--binary","--full-index",`${c}..${h}`]));if(m!==A)return a("direct-yolo-bundle-digest-mismatch");const f=k(["direct-yolo-commit-v1",e.storyId,i.epicId,i.executionBranch,c,m,S,v].join("\0")),R=w(g.epics[i.epicId]?.branch_lease),p=K(e.nowIso),I=R?.ownerStoryId===e.storyId&&R.idempotencyKey===f&&R.sessionId===f&&Date.parse(String(R.expiresAt))>Date.now()?R:void 0;if(R&&Date.parse(String(R.expiresAt))>Date.now()&&!I)return a("direct-yolo-writer-active");const E=I??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:f,idempotencyKey:f,acquiredAt:p,expiresAt:new Date(Date.parse(p)+ie).toISOString()},$=await V(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:f,idempotencyKey:f,expiresAt:String(E.expiresAt),persistent:!0,createdAt:String(E.acquiredAt)});if(!$.ok)return a($.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=$,I||(g=(await P(i.projectRoot,H=>{const L=N(H,i.epicId),z=w(L.branch_lease);if(z&&Date.parse(String(z.expiresAt))>Date.parse(p))throw new Error("direct-yolo-writer-active");if(L.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");L.branch_lease=E},{expectedRevision:g.revision})).document),o=E;{const _=await de(e,i.projectRoot,h,i.graphRevision);if(!await fe(i.projectRoot,i.executionBranch,h,l))return a("direct-yolo-head-raced");if(e.push){const z=ee(e.remote??"origin");if(await y(i.projectRoot,["push",z,i.executionBranch]),!await Ae(i.projectRoot,z,i.executionBranch,h))return a("direct-yolo-remote-head-mismatch")}const H=await be({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:c,headSha:h,bundleDigest:m,graphRevision:S,claimRevision:v,idempotencyKey:f,qaExecution:_,physicalLockOwnerDigest:we($.owner),nowIso:K(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await ke({projectRoot:i.projectRoot,checkpoint:H,remote:e.push?e.remote??"origin":void 0,expectedRevision:g.revision,expectedLease:E,expectedGraphRevision:i.graphRevision,physicalLockPath:$.path,physicalLockOwner:$.owner,transientAuthority:_.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await e.afterCheckpointPersist?.(),{ok:!0,value:H}):a("direct-yolo-checkpoint-persist-failed")}}catch(i){return a(Y(i,"direct-yolo-finalize-failed"))}finally{r&&await W(r.path,r.owner).catch(()=>{}),t&&o?await se(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await rt(t,e.storyId).catch(()=>{})}}async function vt(e){try{const t=await F(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return a("direct-yolo-recovery-commit-invalid");const o=await y(t.projectRoot,["rev-parse",e.commitSha]);if(Ge[e.storyId]!==o)return a("direct-yolo-recovery-not-allowlisted");if(await y(t.projectRoot,["rev-parse","HEAD"])!==o)return a("direct-yolo-recovery-head-mismatch");await y(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await y(t.projectRoot,["rev-parse",`${o}^`]),i=await j(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=O(await j(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!T(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return a("direct-yolo-recovery-write-set-invalid");const s=k(i),h=k([...n].sort().join("\0")),c=k(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),d=K(e.nowIso),l=new Date(Date.parse(d)+ie).toISOString(),u=await C(t.projectRoot,{required:!0}),m=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:c,idempotencyKey:c,expiresAt:l,persistent:!0,createdAt:d});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const S={schemaVersion:1,ownerStoryId:e.storyId,sessionId:c,idempotencyKey:c,acquiredAt:d,expiresAt:l};let v=!1;try{const x=await P(t.projectRoot,p=>{const I=N(p,t.epicId),E=w(I.branch_lease);if(E&&Date.parse(String(E.expiresAt))>Date.parse(d)&&!ce(E,S))throw new Error("direct-yolo-recovery-writer-active");if(I.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");I.branch_mode="epic",I.execution_branch=t.executionBranch,I.origin_branch=t.originBranch,I.branch_lease=S},{expectedRevision:u.revision});v=!0;const b=await de(e,t.projectRoot,o,t.graphRevision);if(!await fe(t.projectRoot,t.executionBranch,o,n))return a("direct-yolo-recovery-head-raced");if(e.push){const p=ee(e.remote??"origin"),I=(await y(t.projectRoot,["ls-remote","--heads",p,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!I||!await B(t.projectRoot,["merge-base","--is-ancestor",o,I]))return a("direct-yolo-recovery-remote-proof-missing")}const D=await be({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision,claimRevision:h,idempotencyKey:c,qaExecution:b,physicalLockOwnerDigest:we(m.owner),nowIso:d,legacyReceiptRef:void 0}),A=await Ke(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision});if(!A)return a("direct-yolo-recovery-evidence-invalid");const f=Object.freeze({...D,receiptRefs:Object.freeze([...D.receiptRefs,A])});return await ke({projectRoot:t.projectRoot,checkpoint:f,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:x.document.revision,expectedLease:S,expectedGraphRevision:t.graphRevision,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:b.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:f}:a("direct-yolo-recovery-persist-failed")}finally{await W(m.path,m.owner).catch(()=>{}),v&&await se(t.projectRoot,t.epicId,S).catch(()=>{})}}catch(t){return a(Y(t,"direct-yolo-recovery-failed"))}}async function Se(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const o=M(e),r=w(JSON.parse(await Z(te(o,".neocortex/state.json"),"utf8"))),i=await C(o,{required:!0}),n=Pe(r,i),g=w(n.stories),s=w(n.epics),h=w(g?.[t]),c=String(h?.epic_id??t.split(".")[0]),d=w(s?.[c]),l=String(d?.execution_branch??""),u=String(d?.origin_branch??""),m=String(d?.graph_revision??""),S=Array.isArray(h?.files_to_modify)?[...new Set(h.files_to_modify.filter(x=>typeof x=="string"&&ue(x)))].sort():[];if(!h)throw new Error("direct-yolo-story-state-missing");if(d?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Be(l)||!await B(o,["check-ref-format","--branch",l]))throw new Error("direct-yolo-execution-branch-invalid");if(!Be(u)||!await B(o,["check-ref-format","--branch",u]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(m))throw new Error("direct-yolo-graph-revision-invalid");const v=await qe({projectRoot:o,storyId:t,graphRevision:m,executionBranch:l,childPaths:S});return{projectRoot:o,storyId:t,story:h,epicId:c,executionBranch:l,originBranch:u,graphRevision:m,authorizedWriteSet:S,rootMemoryEffect:v}}async function F(e,t){const o=await Se(e,t);if(await y(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function be(e){const t=e.nowIso,o=await j(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=O(await j(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=ze({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Ne({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),g=`story-qa:${n}`,s=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:g}),h=Q(e.projectRoot,e.storyId,e.headSha);if(h?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const c=k(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,g,k(o),[...r].sort().join(","),h.digest].join("\0")),d=`story-review:${c}`,l=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:c,reviewArtifactDigest:h.digest,qaReceiptRef:g,verdict:"approved",reviewedAt:t,receiptRef:d}),u=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,g,d,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(u),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:s,reviewReceipt:l,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function ke(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await P(t,n=>{const g=N(n,o.epicId);if(e.expectedLease){const d=w(g.branch_lease);if(!ce(d,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(d?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(g.graph_revision!==e.expectedGraphRevision||o.graphRevision!==e.expectedGraphRevision)throw new Error("direct-yolo-graph-revision-raced")}const s=Re(n,o.storyId),h=w(s.checkpoint);if(h&&h.headSha!==o.headSha){i=!0;return}s.checkpoint=o,s.status="done",s.last_step=xe;const c=Array.isArray(s.steps_completed)?s.steps_completed.filter(d=>typeof d=="string"):[];s.steps_completed=[...new Set([...c,Ze,xe])],g.branch_lease=null},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");if(await y(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await y(t,["rev-parse","HEAD"])!==o.headSha)throw new Error("direct-yolo-checkpoint-head-raced");if(!await ve(t,o,o.storyId,o.epicId,o.branch,e.transientAuthority,e.authorizedWriteSet))throw new Error("direct-yolo-checkpoint-physical-invalid");if(e.physicalLockPath&&e.physicalLockOwner&&!await U(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await De(t,r,o.branch,o.headSha):await Ae(t,r,o.branch,o.headSha)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function De(e,t,o,r){const i=ee(t),n=(await y(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await B(e,["merge-base","--is-ancestor",r,n]))}function ne(e,t,o){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(o))}async function je(e,t){const o=await Te(e),r=await Me(o,"handoffs"),i=`direct-${k(t)}.json`;return{parent:r,name:i,path:te(r,i)}}async function ae(e,t){const o=await je(e,t.storyId);await Ye(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
+ `),await Ie(o.path,o.parent)}async function G(e,t){try{const o=await je(e,t);await Ie(o.path,o.parent);const r=JSON.parse(await Z(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function Qe(e,t,o,r,i){const n=await G(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||k(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function Ue(e,t,o,r,i,n){const g=await G(e,t);if(!g||g.state==="consumed"||g.fromSessionId!==o||g.token!==r||g.tokenDigest!==k(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(g.state==="consuming"){if(g.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await ae(e,{...g,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function Xe(e,t,o,r,i,n,g,s,h){const c=await G(e,o);if(c?.state==="consumed"&&c.fromSessionId===r&&c.consumedBySessionId===s)return;const d=await C(e,{required:!0}),l=w(d.epics[t]?.branch_lease),u=w(l?.handoffConsumption);if(!c||c.state!=="consuming"||c.fromSessionId!==r||c.token!==i||c.tokenDigest!==k(i)||c.bundleDigest!==n||c.claimRevision!==g||c.consumedBySessionId!==s||l?.ownerStoryId!==o||l.sessionId!==s||u?.kind!=="direct-yolo-setup-handoff-consumption"||u.state!=="consumed"||u.fromSessionId!==r||u.tokenDigest!==c.tokenDigest||u.bundleDigest!==n||u.claimRevision!==g||u.consumedBySessionId!==s)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await ae(e,{schemaVersion:1,kind:c.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:c.tokenDigest,bundleDigest:c.bundleDigest,claimRevision:c.claimRevision,grantDigest:c.grantDigest,expiresAt:c.expiresAt,consumedBySessionId:s,consumedAt:h})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function et(e){const t=w(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?k(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&tt(t.tokenDigest,r))}function tt(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&Ce(o,r)}function ce(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function se(e,t,o){await P(e,r=>{const i=N(r,t),n=w(i.branch_lease);ce(n,o)&&(i.branch_lease=null)})}async function rt(e,t){const o=await C(e.projectRoot,{required:!0}),r=w(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Ee(r.sessionId)||!Ee(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await V(e.projectRoot,{kind:"direct",storyId:t,sessionId:String(r.sessionId),idempotencyKey:String(r.idempotencyKey),createdAt:String(r.acquiredAt),expiresAt:String(r.expiresAt),persistent:!0});if(!i.ok)return;await W(i.path,i.owner)&&await se(e.projectRoot,e.epicId,r)}async function de(e,t,o,r){const i=await Ve(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=We(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Fe,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function fe(e,t,o,r){return await y(e,["rev-parse","HEAD"])!==o||await y(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await B(e,["diff","--cached","--quiet"])?!1:B(e,["diff","--quiet","HEAD","--",...r])}async function Ae(e,t,o,r){const i=ee(t);return(await y(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function T(e,t,o,r){if(e.length===0||e.some(n=>!ue(n)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`];return!i.every(n=>e.includes(n))||!i.every(n=>t.includes(n))?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==k([...t].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(n=>!t.includes(n)&&!r?.files.some(g=>g.path===n))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function ue(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Ee(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Be(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function ee(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function J(e,t){const o=`${t}: `,r=e.split(`
3
+ `).map(i=>i.trim()).filter(i=>i.startsWith(o)).map(i=>i.slice(o.length));return r.length===1?r[0]:void 0}function k(e){return Le("sha256").update(e).digest("hex")}function O(e){return e.split("\0").filter(Boolean)}function K(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ot(e,t,o,r,i){const n=w(e.expectedLease),g=n?.sessionId,s=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof g=="string"&&/^setup-[a-f0-9]{64}$/.test(g)&&n.idempotencyKey===g&&Number.isFinite(s)&&s<=i}async function it(e,t){let o=await y(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await y(e,["rev-parse","HEAD"])!==t.originHead||await q(e)!==t.checkoutBefore)return;await y(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await y(e,["rev-parse","HEAD"])!==t.originHead||await q(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await B(e,["show-ref","--verify","--quiet",t.executionRef]))return;await y(e,["rev-parse",t.executionRef])===t.originHead&&await y(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}function he(e,t,o){const r=w(e);if(!(!r||r.schemaVersion!==1||r.originBranch!==o||r.executionBranch!==t||r.capturedFromCurrentCheckout!==!0||typeof r.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.originHeadSha)||typeof r.capturedAt!="string"||!Number.isFinite(Date.parse(r.capturedAt))))return r}function pe(e,t,o,r){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:o,reused:r,publicSafe:!0})}async function q(e){const t=O(await j(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!ue(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await y(e,["hash-object","--no-filters","--",r])}`}));return k([await j(e,["diff","--cached","--binary","--full-index"]),await j(e,["diff","--binary","--full-index"]),await j(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function xt(e){const t=M(e),o=await y(t,["rev-parse","HEAD"]),r=await y(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await q(t);if(await y(t,["rev-parse","HEAD"])!==o||await y(t,["symbolic-ref","--quiet","--short","HEAD"])!==r)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:o,branch:r,payloadDigest:i})}async function ye(e){const t=[];let o;for(const r of(await j(e,["worktree","list","--porcelain"])).split(`
4
+ `))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}function Y(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(e.message)?e.message:t}function a(e){return{ok:!1,reasonCode:e}}async function y(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function j(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function B(e,t){try{return await oe("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{mt as acceptDirectYoloSetupCheckpoint,Rt as beginDirectYoloStoryCommit,xt as captureDirectYoloCheckoutEvidence,It as finalizeDirectYoloStoryCheckpoint,wt as issueDirectYoloSetupLeaseHandoff,gt as prepareDirectYoloSetup,vt as recoverLegacyDirectYoloStoryCheckpoint};
@@ -53,6 +53,8 @@ export { ClientCircuitBreaker, type CircuitState, type CircuitBreakerConfig, typ
53
53
  export { OfflineTelemetryQueue, type TelemetryEvent, type QueueConfig, type QueueStats, type FlushResult, } from './telemetry/index.js';
54
54
  export { getCacheStatus, formatCacheStatus, type CacheStatusInfo, type CacheStatusOptions, } from './commands/cache-status.js';
55
55
  export { getSubagentApprovalPolicy, ensureManagedSubagentApprovalPolicy, setSubagentApprovalMode, resetSubagentApprovalMode, ApprovalPolicyConfigError, type ApprovalPolicyConfigOptions, type ApprovalPolicyConfigResult, } from './config.js';
56
+ export { NATIVE_BACKGROUND_REASON_CODES, planEpicBackgroundDispatch, type AuthorizedNativeBackgroundEntryV1, type EpicBackgroundDispatchDecisionV1, type NativeBackgroundAdmissionInput, type NativeBackgroundTaskDirectiveV1, } from './runner/epic-background-dispatcher.js';
57
+ export { NATIVE_BACKGROUND_MAX_POLLS, NativeBackgroundRootError, boundedNativeBackgroundPoll, runNativeBackgroundRoot, type BoundedNativeBackgroundPollResultV1, type NativeBackgroundReservationV1, type NativeBackgroundRootPorts, type NativeBackgroundRootResultV1, } from './runner/headless/background-root.js';
56
58
  export { deriveOpaqueNativeAgentHandle, openNativeAgentPrivateStore, resolveNativeAgentPrivateRuntimePaths, } from './continuity/native-agent-store.js';
57
59
  export { configCliHandler, type ConfigCliDependencies, } from './commands/config.js';
58
60
  export { storyCheckpointCliHandler, parseStoryCheckpointArgs, } from './commands/story-checkpoint.js';
@@ -1 +1 @@
1
- import{ResolverMode as o,NoOpCache as t}from"./types/index.js";import{PUBLIC_PROJECTION_BUNDLE as i,PUBLIC_PROJECTION_GENERATION_ID as n,PUBLIC_PROJECTION_BUNDLE_HASH as p}from"./generated/public-projections.generated.js";import{LocalResolver as c}from"./resolvers/local-resolver.js";import{RemoteResolver as s,RemoteResolverError as f}from"./resolvers/remote-resolver.js";import{EncryptedCache as d}from"./cache/index.js";import{createResolver as A,selectResolver as x}from"./config/resolver-selection.js";import{collectContext as R}from"./context/context-collector.js";import{sanitizeValue as u,sanitizeRecord as y,sanitizeObject as O}from"./context/context-sanitizer.js";import{getMachineFingerprint as D}from"./machine/index.js";import{LicenseClient as N}from"./license/index.js";import{ClaudeCodeAdapter as I,CursorAdapter as _,VSCodeAdapter as h,GeminiAdapter as M,CodexAdapter as L,AntigravityAdapter as k,AdapterRegistry as F,UnknownTargetError as b,createDefaultRegistry as H,detectPlatform as B,isValidTargetId as U}from"./adapters/index.js";import{ClientCircuitBreaker as G,DegradationManager as Y,DegradationLevel as w,FreshnessIndicator as z,RecoveryDetector as J}from"./resilience/index.js";import{OfflineTelemetryQueue as q}from"./telemetry/index.js";import{getCacheStatus as K,formatCacheStatus as W}from"./commands/cache-status.js";import{getSubagentApprovalPolicy as Z,ensureManagedSubagentApprovalPolicy as $,setSubagentApprovalMode as ee,resetSubagentApprovalMode as re,ApprovalPolicyConfigError as oe}from"./config.js";import{deriveOpaqueNativeAgentHandle as ae,openNativeAgentPrivateStore as ie,resolveNativeAgentPrivateRuntimePaths as ne}from"./continuity/native-agent-store.js";import{configCliHandler as le}from"./commands/config.js";import{storyCheckpointCliHandler as me,parseStoryCheckpointArgs as se}from"./commands/story-checkpoint.js";import{beginDirectYoloStoryCommit as Ce,finalizeDirectYoloStoryCheckpoint as de,issueDirectYoloSetupLeaseHandoff as ge,prepareDirectYoloSetup as Ae,recoverLegacyDirectYoloStoryCheckpoint as xe}from"./git/direct-yolo-checkpoint.js";import{FRONTMATTER_DIAGNOSTIC_CATEGORIES as Re,FRONTMATTER_DIAGNOSTIC_REASON_CODES as Se,getFrontmatterDiagnostic as ue,formatFrontmatterDiagnostic as ye}from"./errors/frontmatter-diagnostics.js";import{invoke as Te,invokeCliHandler as De,collectStateSnapshot as Ee}from"./commands/invoke.js";import{TierAwareClient as Pe}from"./tier/index.js";import{buildProjectMemoryContent as _e,createNodeProjectMemoryFs as he,writeProjectMemory as Me,writeProjectMemoryTargetFiles as Le}from"./memory/project-memory-writer.js";export{F as AdapterRegistry,k as AntigravityAdapter,oe as ApprovalPolicyConfigError,I as ClaudeCodeAdapter,G as ClientCircuitBreaker,L as CodexAdapter,_ as CursorAdapter,w as DegradationLevel,Y as DegradationManager,d as EncryptedCache,Re as FRONTMATTER_DIAGNOSTIC_CATEGORIES,Se as FRONTMATTER_DIAGNOSTIC_REASON_CODES,z as FreshnessIndicator,M as GeminiAdapter,N as LicenseClient,c as LocalResolver,t as NoOpCache,q as OfflineTelemetryQueue,i as PUBLIC_PROJECTION_BUNDLE,p as PUBLIC_PROJECTION_BUNDLE_HASH,n as PUBLIC_PROJECTION_GENERATION_ID,J as RecoveryDetector,s as RemoteResolver,f as RemoteResolverError,o as ResolverMode,Pe as TierAwareClient,b as UnknownTargetError,h as VSCodeAdapter,Ce as beginDirectYoloStoryCommit,_e as buildProjectMemoryContent,R as collectContext,Ee as collectStateSnapshot,le as configCliHandler,H as createDefaultRegistry,he as createNodeProjectMemoryFs,A as createResolver,ae as deriveOpaqueNativeAgentHandle,B as detectPlatform,$ as ensureManagedSubagentApprovalPolicy,de as finalizeDirectYoloStoryCheckpoint,W as formatCacheStatus,ye as formatFrontmatterDiagnostic,K as getCacheStatus,ue as getFrontmatterDiagnostic,D as getMachineFingerprint,Z as getSubagentApprovalPolicy,Te as invoke,De as invokeCliHandler,U as isValidTargetId,ge as issueDirectYoloSetupLeaseHandoff,ie as openNativeAgentPrivateStore,se as parseStoryCheckpointArgs,Ae as prepareDirectYoloSetup,xe as recoverLegacyDirectYoloStoryCheckpoint,re as resetSubagentApprovalMode,ne as resolveNativeAgentPrivateRuntimePaths,O as sanitizeObject,y as sanitizeRecord,u as sanitizeValue,x as selectResolver,ee as setSubagentApprovalMode,me as storyCheckpointCliHandler,Me as writeProjectMemory,Le as writeProjectMemoryTargetFiles};
1
+ import{ResolverMode as o,NoOpCache as t}from"./types/index.js";import{PUBLIC_PROJECTION_BUNDLE as i,PUBLIC_PROJECTION_GENERATION_ID as n,PUBLIC_PROJECTION_BUNDLE_HASH as p}from"./generated/public-projections.generated.js";import{LocalResolver as l}from"./resolvers/local-resolver.js";import{RemoteResolver as d,RemoteResolverError as s}from"./resolvers/remote-resolver.js";import{EncryptedCache as f}from"./cache/index.js";import{createResolver as A,selectResolver as R}from"./config/resolver-selection.js";import{collectContext as x}from"./context/context-collector.js";import{sanitizeValue as N,sanitizeRecord as S,sanitizeObject as E}from"./context/context-sanitizer.js";import{getMachineFingerprint as D}from"./machine/index.js";import{LicenseClient as y}from"./license/index.js";import{ClaudeCodeAdapter as _,CursorAdapter as I,VSCodeAdapter as h,GeminiAdapter as M,CodexAdapter as k,AntigravityAdapter as B,AdapterRegistry as L,UnknownTargetError as b,createDefaultRegistry as F,detectPlatform as U,isValidTargetId as G}from"./adapters/index.js";import{ClientCircuitBreaker as j,DegradationManager as V,DegradationLevel as Y,FreshnessIndicator as w,RecoveryDetector as z}from"./resilience/index.js";import{OfflineTelemetryQueue as K}from"./telemetry/index.js";import{getCacheStatus as Q,formatCacheStatus as X}from"./commands/cache-status.js";import{getSubagentApprovalPolicy as Z,ensureManagedSubagentApprovalPolicy as $,setSubagentApprovalMode as ee,resetSubagentApprovalMode as re,ApprovalPolicyConfigError as oe}from"./config.js";import{NATIVE_BACKGROUND_REASON_CODES as ae,planEpicBackgroundDispatch as ie}from"./runner/epic-background-dispatcher.js";import{NATIVE_BACKGROUND_MAX_POLLS as pe,NativeBackgroundRootError as ce,boundedNativeBackgroundPoll as le,runNativeBackgroundRoot as me}from"./runner/headless/background-root.js";import{deriveOpaqueNativeAgentHandle as se,openNativeAgentPrivateStore as Ce,resolveNativeAgentPrivateRuntimePaths as fe}from"./continuity/native-agent-store.js";import{configCliHandler as Ae}from"./commands/config.js";import{storyCheckpointCliHandler as ve,parseStoryCheckpointArgs as xe}from"./commands/story-checkpoint.js";import{beginDirectYoloStoryCommit as Ne,finalizeDirectYoloStoryCheckpoint as Se,issueDirectYoloSetupLeaseHandoff as Ee,prepareDirectYoloSetup as Oe,recoverLegacyDirectYoloStoryCheckpoint as De}from"./git/direct-yolo-checkpoint.js";import{FRONTMATTER_DIAGNOSTIC_CATEGORIES as ye,FRONTMATTER_DIAGNOSTIC_REASON_CODES as Pe,getFrontmatterDiagnostic as _e,formatFrontmatterDiagnostic as Ie}from"./errors/frontmatter-diagnostics.js";import{invoke as Me,invokeCliHandler as ke,collectStateSnapshot as Be}from"./commands/invoke.js";import{TierAwareClient as be}from"./tier/index.js";import{buildProjectMemoryContent as Ue,createNodeProjectMemoryFs as Ge,writeProjectMemory as He,writeProjectMemoryTargetFiles as je}from"./memory/project-memory-writer.js";export{L as AdapterRegistry,B as AntigravityAdapter,oe as ApprovalPolicyConfigError,_ as ClaudeCodeAdapter,j as ClientCircuitBreaker,k as CodexAdapter,I as CursorAdapter,Y as DegradationLevel,V as DegradationManager,f as EncryptedCache,ye as FRONTMATTER_DIAGNOSTIC_CATEGORIES,Pe as FRONTMATTER_DIAGNOSTIC_REASON_CODES,w as FreshnessIndicator,M as GeminiAdapter,y as LicenseClient,l as LocalResolver,pe as NATIVE_BACKGROUND_MAX_POLLS,ae as NATIVE_BACKGROUND_REASON_CODES,ce as NativeBackgroundRootError,t as NoOpCache,K as OfflineTelemetryQueue,i as PUBLIC_PROJECTION_BUNDLE,p as PUBLIC_PROJECTION_BUNDLE_HASH,n as PUBLIC_PROJECTION_GENERATION_ID,z as RecoveryDetector,d as RemoteResolver,s as RemoteResolverError,o as ResolverMode,be as TierAwareClient,b as UnknownTargetError,h as VSCodeAdapter,Ne as beginDirectYoloStoryCommit,le as boundedNativeBackgroundPoll,Ue as buildProjectMemoryContent,x as collectContext,Be as collectStateSnapshot,Ae as configCliHandler,F as createDefaultRegistry,Ge as createNodeProjectMemoryFs,A as createResolver,se as deriveOpaqueNativeAgentHandle,U as detectPlatform,$ as ensureManagedSubagentApprovalPolicy,Se as finalizeDirectYoloStoryCheckpoint,X as formatCacheStatus,Ie as formatFrontmatterDiagnostic,Q as getCacheStatus,_e as getFrontmatterDiagnostic,D as getMachineFingerprint,Z as getSubagentApprovalPolicy,Me as invoke,ke as invokeCliHandler,G as isValidTargetId,Ee as issueDirectYoloSetupLeaseHandoff,Ce as openNativeAgentPrivateStore,xe as parseStoryCheckpointArgs,ie as planEpicBackgroundDispatch,Oe as prepareDirectYoloSetup,De as recoverLegacyDirectYoloStoryCheckpoint,re as resetSubagentApprovalMode,fe as resolveNativeAgentPrivateRuntimePaths,me as runNativeBackgroundRoot,E as sanitizeObject,S as sanitizeRecord,N as sanitizeValue,R as selectResolver,ee as setSubagentApprovalMode,ve as storyCheckpointCliHandler,He as writeProjectMemory,je as writeProjectMemoryTargetFiles};