@ornexus/neocortex 4.61.6 → 4.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +1 -1
  5. package/package.json +5 -2
  6. package/packages/client/dist/agent/update-description.d.ts +8 -1
  7. package/packages/client/dist/agent/update-description.js +2 -1
  8. package/packages/client/dist/commands/invoke.d.ts +17 -0
  9. package/packages/client/dist/commands/invoke.js +72 -72
  10. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  11. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  12. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +24 -9
  13. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
  14. package/packages/client/dist/git/git-lifecycle-store.d.ts +66 -0
  15. package/packages/client/dist/git/git-lifecycle-store.js +8 -7
  16. package/packages/client/dist/git/release-gate-env.d.ts +62 -0
  17. package/packages/client/dist/git/release-gate-env.js +1 -0
  18. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  19. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
  20. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  21. package/packages/client/dist/runner/headless/child-env.js +1 -0
  22. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
  23. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
  24. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
  25. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  26. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  27. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
  28. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  29. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  30. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  31. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  32. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
  33. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  34. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  35. package/packages/shared/dist/project-manifest-projection.js +199 -0
  36. package/packages/shared/dist/project-validation-commands.js +14 -6
  37. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  38. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  39. package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
  40. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  41. package/targets-stubs/antigravity/gemini.md +1 -1
  42. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  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 +5 -5
  48. package/targets-stubs/codex/AGENTS.md +1 -1
  49. package/targets-stubs/cursor/agent.md +2 -2
  50. package/targets-stubs/gemini-cli/agent.md +2 -2
  51. package/targets-stubs/lib/managed-config-merge.js +77 -1
  52. package/targets-stubs/lib/managed-profile.sh +7 -0
  53. package/targets-stubs/opencode/neocortex-root.md +1 -1
  54. package/targets-stubs/vscode/install-vscode.sh +21 -0
  55. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -9,9 +9,18 @@ export declare const FRONTMATTER_DIAGNOSTIC_CATEGORIES: readonly ["payload-selec
9
9
  export type FrontmatterDiagnosticCategory = (typeof FRONTMATTER_DIAGNOSTIC_CATEGORIES)[number];
10
10
  export declare const FRONTMATTER_DIAGNOSTIC_REASON_CODES: readonly ["payload-selection-ambiguous", "payload-selection-unavailable", "markdown-link-target-malformed", "markdown-link-target-ambiguous", "markdown-link-target-external", "markdown-link-target-unsafe-path", "raw-target-malformed", "raw-target-external", "raw-target-unsafe-path", "frontmatter-malformed", "frontmatter-oversized", "frontmatter-unsupported-value", "frontmatter-explicit-selection-required"];
11
11
  export type FrontmatterDiagnosticReasonCode = (typeof FRONTMATTER_DIAGNOSTIC_REASON_CODES)[number];
12
+ /**
13
+ * P226.04: dynamic per-field list limit code emitted by the shared frontmatter
14
+ * contract. Only known list-field names (or a fixed label) and integers can
15
+ * match, so a matching code never carries rejected values. The standalone
16
+ * client cannot import `@neocortex/shared` here; this pattern mirrors
17
+ * `FRONTMATTER_LIST_TOO_LONG_PATTERN` and is pinned by tests.
18
+ */
19
+ export type FrontmatterListTooLongDiagnosticCode = `frontmatter-list-too-long:${string}:${number}>${number}`;
20
+ export declare const FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN: RegExp;
12
21
  export interface PublicFrontmatterDiagnostic {
13
22
  readonly category: FrontmatterDiagnosticCategory;
14
- readonly reasonCode: FrontmatterDiagnosticReasonCode | 'frontmatter-diagnostic-unclassified';
23
+ readonly reasonCode: FrontmatterDiagnosticReasonCode | FrontmatterListTooLongDiagnosticCode | 'frontmatter-diagnostic-unclassified';
15
24
  readonly summary: string;
16
25
  readonly remediation: string;
17
26
  readonly example?: string;
@@ -1 +1 @@
1
- const l=["payload-selection","target-normalization","metadata-frontmatter"],d=["payload-selection-ambiguous","payload-selection-unavailable","markdown-link-target-malformed","markdown-link-target-ambiguous","markdown-link-target-external","markdown-link-target-unsafe-path","raw-target-malformed","raw-target-external","raw-target-unsafe-path","frontmatter-malformed","frontmatter-oversized","frontmatter-unsupported-value","frontmatter-explicit-selection-required"],t="*yoloop @docs/epics/epic-P204.md",a="docs/epics/epic-P204.md",n=Object.freeze({"payload-selection-ambiguous":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected unambiguously.",remediation:"Pass exactly one explicit trigger and its project-local arguments; keep host wrapper metadata outside the selected payload."}),"payload-selection-unavailable":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected safely.",remediation:"Retry with one explicit trigger. Do not include wrapper frontmatter, conversation history or delegated prompt text."}),"markdown-link-target-malformed":Object.freeze({category:"target-normalization",summary:"The Markdown target is malformed or is not a supported Markdown path.",remediation:"Use one complete Markdown link to a project-relative .md file or a trailing-slash directory.",example:t}),"markdown-link-target-ambiguous":Object.freeze({category:"target-normalization",summary:"More than one target or mixed target syntax was supplied.",remediation:"Pass exactly one raw path or one Markdown link target.",example:t}),"markdown-link-target-external":Object.freeze({category:"target-normalization",summary:"External Markdown targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:t}),"markdown-link-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The Markdown target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:t}),"raw-target-malformed":Object.freeze({category:"target-normalization",summary:"The raw target is not a supported Markdown path.",remediation:"Use one project-relative .md file or a trailing-slash directory.",example:t}),"raw-target-external":Object.freeze({category:"target-normalization",summary:"External raw targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:t}),"raw-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The raw target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:t}),"frontmatter-malformed":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter envelope is malformed.",remediation:"Repair the bounded leading --- envelope and keep generated metadata fields scalar or string-list values.",example:a}),"frontmatter-oversized":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter exceeds the public parsing limits.",remediation:"Reduce the metadata header and keep descriptive content in the Markdown body.",example:a}),"frontmatter-unsupported-value":Object.freeze({category:"metadata-frontmatter",summary:"A frontmatter field uses an unsupported value shape.",remediation:"Use allowlisted scalar fields and bounded string lists only.",example:a}),"frontmatter-explicit-selection-required":Object.freeze({category:"metadata-frontmatter",summary:"Target metadata cannot be projected before explicit file selection.",remediation:"Select one project-relative epic or story target before metadata discovery.",example:a})}),i=Object.freeze({category:"metadata-frontmatter",reasonCode:"frontmatter-diagnostic-unclassified",summary:"The frontmatter operation could not be classified safely.",remediation:"Retry with one explicit project-relative target and a bounded YAML header.",example:a});function m(r){const e=n[r];return e?Object.freeze({reasonCode:r,...e}):i}function s(r){const e=m(r),o=e.example?` Example: ${e.example}.`:"";return`${e.reasonCode} [${e.category}]: ${e.summary} Remediation: ${e.remediation}${o}`}export{l as FRONTMATTER_DIAGNOSTIC_CATEGORIES,d as FRONTMATTER_DIAGNOSTIC_REASON_CODES,s as formatFrontmatterDiagnostic,m as getFrontmatterDiagnostic};
1
+ const d=["payload-selection","target-normalization","metadata-frontmatter"],c=["payload-selection-ambiguous","payload-selection-unavailable","markdown-link-target-malformed","markdown-link-target-ambiguous","markdown-link-target-external","markdown-link-target-unsafe-path","raw-target-malformed","raw-target-external","raw-target-unsafe-path","frontmatter-malformed","frontmatter-oversized","frontmatter-unsupported-value","frontmatter-explicit-selection-required"],i=/^frontmatter-list-too-long:(files_to_modify|depends_on|related_epics|unlisted-field):[0-9]{1,6}>[0-9]{1,6}$/,a="*yoloop @docs/epics/epic-P204.md",r="docs/epics/epic-P204.md",n=Object.freeze({"payload-selection-ambiguous":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected unambiguously.",remediation:"Pass exactly one explicit trigger and its project-local arguments; keep host wrapper metadata outside the selected payload."}),"payload-selection-unavailable":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected safely.",remediation:"Retry with one explicit trigger. Do not include wrapper frontmatter, conversation history or delegated prompt text."}),"markdown-link-target-malformed":Object.freeze({category:"target-normalization",summary:"The Markdown target is malformed or is not a supported Markdown path.",remediation:"Use one complete Markdown link to a project-relative .md file or a trailing-slash directory.",example:a}),"markdown-link-target-ambiguous":Object.freeze({category:"target-normalization",summary:"More than one target or mixed target syntax was supplied.",remediation:"Pass exactly one raw path or one Markdown link target.",example:a}),"markdown-link-target-external":Object.freeze({category:"target-normalization",summary:"External Markdown targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:a}),"markdown-link-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The Markdown target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:a}),"raw-target-malformed":Object.freeze({category:"target-normalization",summary:"The raw target is not a supported Markdown path.",remediation:"Use one project-relative .md file or a trailing-slash directory.",example:a}),"raw-target-external":Object.freeze({category:"target-normalization",summary:"External raw targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:a}),"raw-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The raw target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:a}),"frontmatter-malformed":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter envelope is malformed.",remediation:"Repair the bounded leading --- envelope and keep generated metadata fields scalar or string-list values.",example:r}),"frontmatter-oversized":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter exceeds the public parsing limits.",remediation:"Reduce the metadata header and keep descriptive content in the Markdown body.",example:r}),"frontmatter-unsupported-value":Object.freeze({category:"metadata-frontmatter",summary:"A frontmatter field uses an unsupported value shape.",remediation:"Use allowlisted scalar fields and bounded string lists only.",example:r}),"frontmatter-explicit-selection-required":Object.freeze({category:"metadata-frontmatter",summary:"Target metadata cannot be projected before explicit file selection.",remediation:"Select one project-relative epic or story target before metadata discovery.",example:r})}),m=Object.freeze({category:"metadata-frontmatter",reasonCode:"frontmatter-diagnostic-unclassified",summary:"The frontmatter operation could not be classified safely.",remediation:"Retry with one explicit project-relative target and a bounded YAML header.",example:r}),l=Object.freeze({category:"metadata-frontmatter",summary:"A frontmatter list exceeds its per-field item limit; the code reports the field, the item count and the limit.",remediation:"Trim the list to the reported limit (files_to_modify allows 256 items, other lists allow 32) and keep descriptive content in the Markdown body.",example:r});function s(t){if(typeof t=="string"&&i.test(t))return Object.freeze({reasonCode:t,...l});const e=n[t];return e?Object.freeze({reasonCode:t,...e}):m}function p(t){const e=s(t),o=e.example?` Example: ${e.example}.`:"";return`${e.reasonCode} [${e.category}]: ${e.summary} Remediation: ${e.remediation}${o}`}export{d as FRONTMATTER_DIAGNOSTIC_CATEGORIES,c as FRONTMATTER_DIAGNOSTIC_REASON_CODES,i as FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN,p as formatFrontmatterDiagnostic,s as getFrontmatterDiagnostic};
@@ -1,12 +1,15 @@
1
1
  import type { RootProjectMemoryEffect } from '@neocortex/shared';
2
2
  import type { StoryCommitCheckpoint } from '../../../shared/dist/yoloop/branch-unit.js';
3
3
  import { type GitLifecyclePhysicalIntegrationLockOwner, type P205TransientExecutionAuthority } from './git-lifecycle-store.js';
4
+ /** P226.08 CON-ORIGIN-08-03: closed public remediation hints; never free text. */
5
+ export type DirectYoloFailureHint = 'fetch-origin-branch' | 'checkout-origin-or-rebase';
4
6
  export type DirectYoloCheckpointResult<T> = {
5
7
  readonly ok: true;
6
8
  readonly value: T;
7
9
  } | {
8
10
  readonly ok: false;
9
11
  readonly reasonCode: string;
12
+ readonly hint?: DirectYoloFailureHint;
10
13
  };
11
14
  export interface DirectYoloCommitPlan {
12
15
  readonly schemaVersion: 1;
@@ -113,14 +116,7 @@ export declare function recoverLegacyDirectYoloStoryCheckpoint(options: DirectYo
113
116
  * C08, required from the root checkout on the execution branch.
114
117
  */
115
118
  export declare function resolveDirectYoloIntegrationAuthority(projectRootInput: string, storyId: string): Promise<{
116
- originBinding: {
117
- schemaVersion: 1;
118
- originBranch: string;
119
- originHeadSha: string;
120
- executionBranch: string;
121
- capturedFromCurrentCheckout: true;
122
- capturedAt: string;
123
- } | undefined;
119
+ originBinding: OriginBinding | undefined;
124
120
  projectRoot: string;
125
121
  storyId: string;
126
122
  story: Record<string, unknown>;
@@ -128,7 +124,7 @@ export declare function resolveDirectYoloIntegrationAuthority(projectRootInput:
128
124
  executionBranch: string;
129
125
  originBranch: string;
130
126
  graphRevision: string;
131
- authorizedWriteSet: string[];
127
+ authorizedWriteSet: readonly string[];
132
128
  rootMemoryEffect: import("../private-execution/shared-root-memory-types.js").RootProjectMemoryEffect | undefined;
133
129
  }>;
134
130
  /** P225.07: the direct C08 write-set rule, shared with root integration. */
@@ -218,9 +214,28 @@ export declare function persistDirectYoloWaveStoryCheckpoint(input: {
218
214
  readonly remote?: string;
219
215
  readonly nowIso?: string;
220
216
  }): Promise<DirectYoloCheckpointResult<StoryCommitCheckpoint>>;
217
+ /** P226.08 CON-ORIGIN-08-01: v1 is unchanged; v2 is additive and closed. */
218
+ interface OriginBindingV1 {
219
+ schemaVersion: 1;
220
+ originBranch: string;
221
+ originHeadSha: string;
222
+ executionBranch: string;
223
+ capturedFromCurrentCheckout: true;
224
+ capturedAt: string;
225
+ }
226
+ interface OriginBindingV2 {
227
+ schemaVersion: 2;
228
+ originBranch: string;
229
+ originHeadSha: string;
230
+ executionBranch: string;
231
+ capturedFrom: 'current-checkout' | 'branch-ref';
232
+ capturedAt: string;
233
+ }
234
+ type OriginBinding = OriginBindingV1 | OriginBindingV2;
221
235
  /** Physical observation for a private YOLO agent step; this is not actor attribution. */
222
236
  export declare function captureDirectYoloCheckoutEvidence(projectRootInput: string): Promise<{
223
237
  readonly headSha: string;
224
238
  readonly branch: string;
225
239
  readonly payloadDigest: string;
226
240
  }>;
241
+ export {};
@@ -1,4 +1,3 @@
1
- import{execFile as Je}from"node:child_process";import{createHash as Ze,randomBytes as He,timingSafeEqual as Qe}from"node:crypto";import{existsSync as Ce}from"node:fs";import{readFile as N,realpath as ce}from"node:fs/promises";import{join as Q,resolve as M}from"node:path";import{promisify as Ue}from"node:util";import{readRootMemoryEffectForCheckpoint as Xe}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as et,verifyRootMemoryPhysicalWriteSet as se}from"../private-execution/root-memory-git-evidence.js";import{acquireGitLifecyclePhysicalIntegrationLock as V,applyGitLifecycleRuntimeOverlay as tt,computeImmutableStoryQaEvidenceDigest as rt,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as de,computeP205StoryQaEvidenceDigest as ot,computeLegacyDirectYoloRecoveryReceiptRef as it,ensureRuntimeEpic as W,ensureRuntimeStory as he,ensureGitLifecyclePrivateChildDirectory as Le,executeP205TransientAuthorities as at,executeP205TransientAuthority as nt,projectP205TransientExecutionEvidence as Oe,publicStoryReviewArtifactFromGit as ee,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as ct,mutateGitLifecycleRuntime as C,P205_COMPLETE_COMMAND as Pe,readGitLifecycleRuntime as H,gitLifecycleRuntimeDirectory as $e,STORY_WRITE_SET_MAX_ENTRIES as st,storyWriteSetExtensionPaths as dt,assertGitLifecyclePrivateFile as te,releaseGitLifecyclePhysicalIntegrationLock as G,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as ht,verifyGitLifecyclePhysicalIntegrationLock as re,verifyAcceptedGitLifecycleStoryCheckpoint as fe}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as qe,anchoredRemoveFile as ft}from"./secure-filesystem-boundary.js";import{parseNeocortexTrailers as pt,trailerReasonKey as pe,trailerValue as le}from"./neocortex-trailers.js";import{StoryWorktreeManager as lt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as ut,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ze,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as P}from"./git-lifecycle-step-ids.js";const ue=Ue(Je),oe=3600*1e3;async function Wt(e){let t,o=!1;try{const r=await ye(e.projectRoot,e.storyId);if(await We(r.projectRoot)){if(e.expiredSetupRecovery)return n("direct-yolo-expired-setup-recovery-invalid");const b=await Ke(r);return{ok:!0,value:Te(r,b,!1)}}const i=$(e.nowIso),a=Date.parse(i),h=await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),s=await p(r.projectRoot,["rev-parse","HEAD"]),d=await H(r.projectRoot,{required:!0}),c=g(d.epics[r.epicId]),l=g(c?.branch_lease),m=e.expiredSetupRecovery;if(m&&!Dt(m,d.revision,l,e.storyId,a))return n("direct-yolo-expired-setup-recovery-invalid");const y=l&&Number.isFinite(Date.parse(String(l.expiresAt)))&&Date.parse(String(l.expiresAt))>a;if(y&&l?.ownerStoryId!==e.storyId)return n("direct-yolo-writer-active");let f=X(c?.origin_binding,r.executionBranch,r.originBranch);if(h===r.executionBranch){if(!f)return n("direct-yolo-origin-binding-invalid")}else{if(h!==r.originBranch)return n("direct-yolo-current-branch-mismatch");if(f&&f.originHeadSha!==s){if(!m||!await B(r.projectRoot,["merge-base","--is-ancestor",f.originHeadSha,s]))return n("direct-yolo-origin-binding-conflict");const u=`refs/heads/${r.executionBranch}`;if(!await B(r.projectRoot,["show-ref","--verify","--quiet",u]))return n("direct-yolo-execution-branch-missing");const S=await p(r.projectRoot,["rev-parse",u]);if(!await B(r.projectRoot,["merge-base","--is-ancestor",S,s]))return n("direct-yolo-execution-branch-diverged")}if(f??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:s,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await Ae(r.projectRoot)).some(u=>u.branch===r.executionBranch&&M(u.path)!==r.projectRoot))return n("direct-yolo-execution-branch-checked-out-elsewhere");const w=await O(r.projectRoot),I=`refs/heads/${r.executionBranch}`;if(await B(r.projectRoot,["show-ref","--verify","--quiet",I])){const u=await p(r.projectRoot,["rev-parse",I]);if(u!==s){if(!await B(r.projectRoot,["merge-base","--is-ancestor",u,s]))return n("direct-yolo-execution-branch-diverged");m||await p(r.projectRoot,["update-ref",I,s,u])}m?t={checkoutBefore:w,executionRef:I,executionBranch:r.executionBranch,executionHead:u,originBranch:r.originBranch,originHead:s}:await p(r.projectRoot,["switch",r.executionBranch])}else{if(m)return n("direct-yolo-execution-branch-missing");await p(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await O(r.projectRoot)!==w)return n("direct-yolo-checkout-payload-raced")}const v=t?.originHead??await p(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return n("direct-yolo-current-branch-mismatch");if(y&&l?.ownerStoryId===e.storyId)return l.setupHeadSha!==v?n("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:ae(r,f,String(l.expiresAt),!0)};const x=i,k=new Date(a+3600*1e3).toISOString(),D=`setup-${He(32).toString("hex")}`,j=m?d:await H(r.projectRoot,{required:!0});return await C(r.projectRoot,b=>{const w=W(b,r.epicId),I=g(w.branch_lease);if(m&&JSON.stringify(I)!==JSON.stringify(m.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(I&&Date.parse(String(I.expiresAt))>a&&I.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const u=X(w.origin_binding,r.executionBranch,r.originBranch);if(w.origin_binding&&!u)throw new Error("direct-yolo-origin-binding-conflict");if(u&&JSON.stringify(u)!==JSON.stringify(f))throw new Error("direct-yolo-origin-binding-conflict");w.branch_mode="epic",w.execution_branch=r.executionBranch,w.origin_branch=r.originBranch,w.graph_revision=r.graphRevision,w.origin_binding=f,w.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:D,idempotencyKey:D,acquiredAt:x,expiresAt:k,setupHeadSha:v}},{expectedRevision:m?.expectedRuntimeRevision??j.revision,preCommit:async()=>{if(t){if((await Ae(r.projectRoot)).some(w=>w.branch===r.executionBranch&&M(w.path)!==r.projectRoot)||await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await O(r.projectRoot)!==t.checkoutBefore||!await B(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await p(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 p(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await p(r.projectRoot,["switch",r.executionBranch]),await O(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==v)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:ae(r,f,k,!1)}}catch(r){return o&&t&&await jt(M(e.projectRoot),t).catch(()=>{}),n(Z(r,"direct-yolo-setup-failed"))}}async function Kt(e){let t;try{const o=await ye(e.projectRoot,e.storyId);if(await We(o.projectRoot))return await yt(o);const r=await K(e.projectRoot,e.storyId),i=$(e.nowIso),a=Q(r.projectRoot,".neocortex/state.json"),h=await N(a,"utf8"),s=await O(r.projectRoot),d=await p(r.projectRoot,["rev-parse","HEAD"]),c=`refs/heads/${r.executionBranch}`,l=await H(r.projectRoot,{required:!0}),m=g(l.epics[r.epicId]),y=X(m?.origin_binding,r.executionBranch,r.originBranch),f=g(m?.branch_lease);if(!y)return n("direct-yolo-origin-binding-invalid");if(!f||!Re(f,e.storyId,i)||f?.sessionId!==f?.idempotencyKey)return n("direct-yolo-setup-lease-invalid");const v=await V(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(!v.ok)return n(v.reasonCode);if(t=v,d!==f.setupHeadSha||!await B(r.projectRoot,["merge-base","--is-ancestor",y.originHeadSha,d])||await p(r.projectRoot,["rev-parse",c])!==d)return n("direct-yolo-setup-head-mismatch");if((await Ae(r.projectRoot)).some(I=>I.branch===r.executionBranch&&M(I.path)!==r.projectRoot))return n("direct-yolo-execution-branch-checked-out-elsewhere");const k=g(JSON.parse(h)),D=g(g(k?.stories)?.[e.storyId]),j=g(l.stories[e.storyId]);if(!D||!["backlog","ready_to_start"].includes(String(D.status))||D.steps_completed!==void 0&&(!Array.isArray(D.steps_completed)||D.steps_completed.length>0)||D.branch_name||D.checkpoint)return n("direct-yolo-setup-story-progress-conflict");const b=j?.status==="branch-ready"&&j.last_step===P&&Array.isArray(j.steps_completed)&&j.steps_completed.length===1&&j.steps_completed[0]===P&&J(j).sort().join(",")==="last_step,status,steps_completed";if(j&&J(j).length>0&&!b)return n("direct-yolo-setup-story-progress-conflict");const w=async()=>{if(Date.parse(String(f.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await re(t.path,t.owner)||await N(a,"utf8")!==h||await O(r.projectRoot)!==s||await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==d||!await B(r.projectRoot,["merge-base","--is-ancestor",y.originHeadSha,d])||await p(r.projectRoot,["rev-parse",c])!==d)throw new Error("direct-yolo-setup-physical-state-raced")};return b?await w():await C(r.projectRoot,I=>{const u=g(I.epics[r.epicId]),S=he(I,e.storyId);if(JSON.stringify(u?.branch_lease)!==JSON.stringify(f)||JSON.stringify(u?.origin_binding)!==JSON.stringify(y)||u?.graph_revision!==r.graphRevision||J(S).length>0)throw new Error("direct-yolo-setup-runtime-raced");S.status="branch-ready",S.last_step=P,S.steps_completed=[P]},{expectedRevision:l.revision,preCommit:w}),{ok:!0,value:Object.freeze({...ae(r,y,String(f.expiresAt),b),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:d})}}catch(o){return n(Z(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await G(t.path,t.owner).catch(()=>{})}}async function Tt(e){try{const t=await K(e.projectRoot,e.storyId),o=L(await A(t.projectRoot,["diff","--cached","--name-only","-z"])),r=Y(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return n(r.reasonCode);if(t.rootMemoryEffect&&se(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await p(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),ee(t.projectRoot,e.storyId,":")?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");if(L(await A(t.projectRoot,["diff","--name-only","-z"])).some(S=>o.includes(S)))return n("direct-yolo-user-overlap");const h=await A(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!h)return n("direct-yolo-staged-diff-empty");const s=E(h),d=E([...t.authorizedWriteSet].sort().join("\0")),c=$(e.nowIso),l=await H(t.projectRoot,{required:!0}),m=g(l.epics[t.epicId]?.branch_lease);if(!Re(m,e.storyId,c))return n("direct-yolo-setup-handoff-owner-invalid");const y=String(m.sessionId),f=String(m.expiresAt),v=new Date(Math.min(Date.parse(f),Date.parse(c)+300*1e3)).toISOString(),x=await F(t.projectRoot,e.storyId),k=x?.state==="issued"&&x.fromSessionId===y&&x.bundleDigest===s&&x.claimRevision===d&&Date.parse(x.expiresAt)>Date.parse(c),D=k?x.expiresAt:v,j=k?x.token:He(32).toString("base64url"),b=E(j),w=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:y,tokenDigest:b,bundleDigest:s,claimRevision:d,expiresAt:D}),I=E(JSON.stringify(w)),u=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:y,idempotencyKey:y,expiresAt:D,persistent:!1,createdAt:c});if(!u.ok)return n(u.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Ie(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:y,token:j,tokenDigest:b,bundleDigest:s,claimRevision:d,grantDigest:I,expiresAt:D}),await C(t.projectRoot,S=>{const R=g(W(S,t.epicId).branch_lease);if(!Re(R,e.storyId,c)||R?.sessionId!==y||R.idempotencyKey!==y)throw new Error("direct-yolo-setup-handoff-owner-raced");R.handoffGrant=w},{expectedRevision:l.revision,preCommit:async()=>{if(!await re(u.path,u.owner))throw new Error("direct-yolo-integration-lock-raced");const S=await F(t.projectRoot,e.storyId);if(!S||S.state!=="issued"||S.grantDigest!==I||S.tokenDigest!==b)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await G(u.path,u.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:y,bundleDigest:s,claimRevision:d,grantDigest:I,expiresAt:D,reused:k,publicSafe:!0})}}catch(t){return n(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function Mt(e){try{const t=await K(e.projectRoot,e.storyId),o=await p(t.projectRoot,["rev-parse","HEAD"]),r=L(await A(t.projectRoot,["diff","--cached","--name-only","-z"])),i=Y(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return n(i.reasonCode);t.rootMemoryEffect&&se(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const a=ee(t.projectRoot,e.storyId,":");if(a?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");if(L(await A(t.projectRoot,["diff","--name-only","-z"])).some(R=>r.includes(R)))return n("direct-yolo-user-overlap");const s=await A(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!s)return n("direct-yolo-staged-diff-empty");const d=E(s),c=E([...t.authorizedWriteSet].sort().join("\0")),l=await Ve(t.projectRoot,e.storyId),m=l.state==="valid"&&l.plan.epicId===t.epicId&&l.plan.executionBranch===t.executionBranch&&l.plan.preparedBase===o&&l.plan.bundleDigest===d&&l.plan.claimRevision===c?l.plan:void 0,y=m?.graphRevision??t.graphRevision,f=ge({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,graphRevision:y,claimRevision:c}),v=$(e.nowIso),x={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:y,preparedBase:o,bundleDigest:d,claimRevision:c,idempotencyKey:f,issuedAt:m?.issuedAt??v};let k=e.setupLeaseHandoff??await Rt(t.projectRoot,e.storyId,d,c,v);const D=await H(t.projectRoot,{required:!0}),j=g(D.epics[t.epicId]?.branch_lease),b=j?.ownerStoryId===e.storyId&&j.sessionId===f&&j.idempotencyKey===f&&typeof j.expiresAt=="string"&&Date.parse(j.expiresAt)>Date.parse(v)?j:void 0;if(b&&e.setupLeaseHandoff)return n("direct-yolo-setup-handoff-replayed");const w=g(b?.handoffConsumption);if(w){const R=await F(t.projectRoot,e.storyId);if(!R||!["consuming","consumed"].includes(R.state)||R.fromSessionId!==w.fromSessionId||R.tokenDigest!==w.tokenDigest||R.bundleDigest!==d||R.claimRevision!==c||w.bundleDigest!==d||w.claimRevision!==c||R.consumedBySessionId!==f||w.consumedBySessionId!==f)return n("direct-yolo-setup-handoff-consume-invalid");if(R.state==="consuming"){if(!R.token||E(R.token)!==R.tokenDigest)return n("direct-yolo-setup-handoff-consume-invalid");k={sessionId:R.fromSessionId,token:R.token}}}const I=b?String(b.expiresAt):new Date(Date.parse(v)+oe).toISOString(),u=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:f,idempotencyKey:f,expiresAt:I,persistent:!0,createdAt:b&&typeof b.acquiredAt=="string"?b.acquiredAt:v});if(!u.ok)return n(u.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{k&&e.setupLeaseHandoff===void 0&&(await It(t.projectRoot,e.storyId,k.sessionId,k.token,f,v),await e.setupHandoffFault?.("after-consuming-persisted")),await C(t.projectRoot,R=>{const q=W(R,t.epicId),_=g(q.branch_lease),z=_&&Date.parse(String(_.expiresAt))>Date.parse(v),T=_?.ownerStoryId===e.storyId&&_.sessionId===f&&_.idempotencyKey===f,Ye=_?.ownerStoryId===e.storyId&&_.sessionId===_.idempotencyKey&&typeof _.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(_.idempotencyKey),ne=z&&Ye&&xt({current:_,handoff:k,storyId:e.storyId,bundleDigest:d,claimRevision:c,nowIso:v});if(k&&z&&!T&&!ne)throw new Error("direct-yolo-setup-handoff-invalid");if(z&&!T&&!ne)throw new Error("direct-yolo-writer-active");const Be=ne?g(_?.handoffGrant):void 0,_e=Be?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(_?.sessionId),tokenDigest:String(Be.tokenDigest),bundleDigest:d,claimRevision:c,consumedBySessionId:f,consumedAt:v}:void 0;q.branch_mode="epic",q.execution_branch=t.executionBranch,q.origin_branch=t.originBranch,q.graph_revision=t.graphRevision,q.branch_lease=z&&T?_:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:f,idempotencyKey:f,acquiredAt:v,expiresAt:I,..._e?{handoffConsumption:_e}:{}}},{expectedRevision:D.revision,preCommit:async()=>{if(!await re(u.path,u.owner))throw new Error("direct-yolo-integration-lock-raced");await vt(t.projectRoot,x)}})}catch(R){throw await G(u.path,u.owner).catch(()=>{}),R}k&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await St(t.projectRoot,t.epicId,e.storyId,k.sessionId,k.token,d,c,f,v));const S=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${d}`,`Neocortex-Review-Artifact-Digest: ${a.digest}`,`Neocortex-Graph-Revision: ${y}`,`Neocortex-Claim-Revision: ${c}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${et(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,reviewArtifactDigest:a.digest,graphRevision:y,claimRevision:c,idempotencyKey:f,changedPaths:Object.freeze(r),trailers:S})}}catch(t){return n(Z(t,"direct-yolo-begin-failed"))}}async function Vt(e){let t,o,r;try{const i=await K(e.projectRoot,e.storyId);t=i;const a=await p(i.projectRoot,["rev-parse","HEAD"]);let h=await H(i.projectRoot,{required:!0});const s=g(h.stories[e.storyId]?.checkpoint);if(s){const I=typeof s.headSha=="string"?s.headSha:"",u=typeof s.graphRevision=="string"?s.graphRevision:"",S=/^[a-f0-9]{40,64}$/.test(I)?L(await A(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",I])):[],R=Y(S,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(I)&&await B(i.projectRoot,["merge-base","--is-ancestor",I,a]))||!/^[a-f0-9]{64}$/.test(u)||!R.ok)return n("direct-yolo-replay-invalid");const _=await ke(e,i.projectRoot,a,u);if(!await fe(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,_.transientAuthority,i.authorizedWriteSet))return n("direct-yolo-replay-invalid");if(!await be(i.projectRoot,i.executionBranch,a,S))return n("direct-yolo-replay-head-raced");if(e.push&&!await Me(i.projectRoot,e.remote??"origin",i.executionBranch,I))return n("direct-yolo-remote-head-mismatch");const z=Array.isArray(s.receiptRefs)?s.receiptRefs.find(T=>typeof T=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(T)):void 0;return z&&typeof s.idempotencyKey=="string"&&await ht(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:z.slice(20)}),await ie(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const d=a,c=await Ne(i,e.storyId,d);if(!c.ok)return n(c.reasonCode);const{baseSha:l,changedPaths:m,bundleDigest:y,graphRevision:f,claimRevision:v,idempotencyKey:x}=c.value,k=g(h.epics[i.epicId]?.branch_lease),D=$(e.nowIso),j=k?.ownerStoryId===e.storyId&&k.idempotencyKey===x&&k.sessionId===x&&Date.parse(String(k.expiresAt))>Date.now()?k:void 0;if(k&&Date.parse(String(k.expiresAt))>Date.now()&&!j)return n("direct-yolo-writer-active");const b=j??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:x,idempotencyKey:x,acquiredAt:D,expiresAt:new Date(Date.parse(D)+oe).toISOString()},w=await V(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:x,idempotencyKey:x,expiresAt:String(b.expiresAt),persistent:!0,createdAt:String(b.acquiredAt)});if(!w.ok)return n(w.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=w,j||(h=(await C(i.projectRoot,u=>{const S=W(u,i.epicId),R=g(S.branch_lease);if(R&&Date.parse(String(R.expiresAt))>Date.parse(D))throw new Error("direct-yolo-writer-active");if(S.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");S.branch_lease=b},{expectedRevision:h.revision})).document),o=b;{const I=await ke(e,i.projectRoot,d,f);if(!await be(i.projectRoot,i.executionBranch,d,m))return n("direct-yolo-head-raced");if(e.push){const R=U(e.remote??"origin");if(await p(i.projectRoot,["push",R,i.executionBranch]),!await De(i.projectRoot,R,i.executionBranch,d))return n("direct-yolo-remote-head-mismatch")}const u=await me({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:l,headSha:d,bundleDigest:y,graphRevision:f,claimRevision:v,idempotencyKey:x,qaExecution:I,physicalLockOwnerDigest:de(w.owner),nowIso:$(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await we({projectRoot:i.projectRoot,checkpoint:u,remote:e.push?e.remote??"origin":void 0,expectedRevision:h.revision,expectedLease:b,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:f,physicalLockPath:w.path,physicalLockOwner:w.owner,transientAuthority:I.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await ie(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:u}):n("direct-yolo-checkpoint-persist-failed")}}catch(i){return n(Z(i,"direct-yolo-finalize-failed"))}finally{r&&await G(r.path,r.owner).catch(()=>{}),t&&o?await xe(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await bt(t,e.storyId).catch(()=>{})}}async function Ne(e,t,o){const r=await p(e.projectRoot,["rev-parse",`${o}^`]),i=await A(e.projectRoot,["show","--no-patch","--format=%B",o]),a=L(await A(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),h=Y(a,e.authorizedWriteSet,t,e.rootMemoryEffect);if(!h.ok)return n(h.reasonCode);e.rootMemoryEffect&&se(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:r,headRef:o,childPaths:e.authorizedWriteSet});const s=E([...e.authorizedWriteSet].sort().join("\0")),d=await Ve(e.projectRoot,t);if(d.state==="invalid")return n("direct-yolo-commit-plan-invalid");const c=d.state==="valid"?d.plan:void 0;if(c&&(c.epicId!==e.epicId||c.executionBranch!==e.executionBranch))return n("direct-yolo-commit-plan-invalid");if(c&&c.claimRevision!==s)return n("direct-yolo-commit-plan-claim-changed");if(c&&c.preparedBase!==r)return n("direct-yolo-commit-plan-base-mismatch");const l=pt(i);if(!l.ok)return n(`direct-yolo-trailer-duplicate:${l.key}`);const m=l.values,y=c?.graphRevision??e.graphRevision,f=s,v=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",r],["Neocortex-Bundle-Digest",c?.bundleDigest??""],["Neocortex-Graph-Revision",y],["Neocortex-Claim-Revision",f]];for(const[w,I]of v){const u=le(m,w);if(u===void 0)return n(`direct-yolo-trailer-missing:${pe(w)}`);if(w==="Neocortex-Bundle-Digest"&&!c){if(!/^[a-f0-9]{64}$/.test(u))return n(`direct-yolo-trailer-mismatch:${pe(w)}`);continue}if(u!==I)return n(`direct-yolo-trailer-mismatch:${pe(w)}`)}const x=le(m,"Neocortex-Bundle-Digest"),k=ee(e.projectRoot,t,o);if(k?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");const D=le(m,"Neocortex-Review-Artifact-Digest");if(D!==void 0&&D!==k.digest)return n("direct-yolo-review-artifact-digest-mismatch");const j=E(await A(e.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]));if(x!==j)return n("direct-yolo-bundle-digest-mismatch");const b=ge({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:r,bundleDigest:x,graphRevision:y,claimRevision:f});return c&&c.idempotencyKey!==b?n("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:r,changedPaths:a,bundleDigest:x,graphRevision:y,claimRevision:f,idempotencyKey:b}}}async function Gt(e){try{const t=await K(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return n("direct-yolo-recovery-commit-invalid");const o=await p(t.projectRoot,["rev-parse",e.commitSha]);if(ct[e.storyId]!==o)return n("direct-yolo-recovery-not-allowlisted");if(await p(t.projectRoot,["rev-parse","HEAD"])!==o)return n("direct-yolo-recovery-head-mismatch");await p(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await p(t.projectRoot,["rev-parse",`${o}^`]),i=await A(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),a=L(await A(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!Y(a,t.authorizedWriteSet.length>0?t.authorizedWriteSet:a,e.storyId).ok)return n("direct-yolo-recovery-write-set-invalid");const s=E(i),d=E([...a].sort().join("\0")),c=E(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),l=$(e.nowIso),m=new Date(Date.parse(l)+oe).toISOString(),y=await H(t.projectRoot,{required:!0}),f=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:c,idempotencyKey:c,expiresAt:m,persistent:!0,createdAt:l});if(!f.ok)return n(f.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:c,idempotencyKey:c,acquiredAt:l,expiresAt:m};let x=!1;try{const k=await C(t.projectRoot,u=>{const S=W(u,t.epicId),R=g(S.branch_lease);if(R&&Date.parse(String(R.expiresAt))>Date.parse(l)&&!Se(R,v))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=v},{expectedRevision:y.revision});x=!0;const D=await ke(e,t.projectRoot,o,t.graphRevision);if(!await be(t.projectRoot,t.executionBranch,o,a))return n("direct-yolo-recovery-head-raced");if(e.push){const u=U(e.remote??"origin"),S=(await p(t.projectRoot,["ls-remote","--heads",u,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!S||!await B(t.projectRoot,["merge-base","--is-ancestor",o,S]))return n("direct-yolo-recovery-remote-proof-missing")}const j=await me({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision,claimRevision:d,idempotencyKey:c,qaExecution:D,physicalLockOwnerDigest:de(f.owner),nowIso:l,legacyReceiptRef:void 0}),b=await it(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision});if(!b)return n("direct-yolo-recovery-evidence-invalid");const w=Object.freeze({...j,receiptRefs:Object.freeze([...j.receiptRefs,b])});return await we({projectRoot:t.projectRoot,checkpoint:w,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:k.document.revision,expectedLease:v,expectedGraphRevision:t.graphRevision,physicalLockPath:f.path,physicalLockOwner:f.owner,transientAuthority:D.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:w}:n("direct-yolo-recovery-persist-failed")}finally{await G(f.path,f.owner).catch(()=>{}),x&&await xe(t.projectRoot,t.epicId,v).catch(()=>{})}}catch(t){return n(Z(t,"direct-yolo-recovery-failed"))}}async function We(e){const t=await ce(await p(e,["rev-parse","--absolute-git-dir"])),o=await ce(await p(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function Ke(e){const t=await H(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(m=>m.storyId===e.storyId&&m.epicId===e.epicId&&m.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await ce(await p(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await p(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const h=await new lt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!h.ok||h.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const s=X(g(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!s)throw new Error("direct-yolo-origin-binding-invalid");const d=r.syncedSha??r.baseSha,c=await p(e.projectRoot,["rev-parse","HEAD"]),l=`refs/heads/${e.executionBranch}`;if(c!==d||!await B(e.projectRoot,["merge-base","--is-ancestor",d,l])||!await B(e.projectRoot,["merge-base","--is-ancestor",s.originHeadSha,d]))throw new Error("direct-yolo-worktree-base-divergent");if(h.value.clean!==!0||(await A(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-worktree-dirty");return{leaseId:r.leaseId,temporaryBranch:r.temporaryBranch,authorizedBase:d,headSha:c,expiresAt:r.expiresAt,binding:s}}function Te(e,t,o){return Object.freeze({...ae(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function yt(e){const t=await Ke(e),o=Q(e.projectRoot,".neocortex/state.json"),r=await N(o,"utf8"),i=g(JSON.parse(r)),a=g(g(i?.stories)?.[e.storyId]),h=await H(e.projectRoot,{required:!0}),s=g(h.stories[e.storyId]);if(!a||!["backlog","ready_to_start"].includes(String(a.status))||a.steps_completed!==void 0&&(!Array.isArray(a.steps_completed)||a.steps_completed.length>0)||a.branch_name||a.checkpoint)return n("direct-yolo-setup-story-progress-conflict");const d=s?.status==="branch-ready"&&s.last_step===P&&Array.isArray(s.steps_completed)&&s.steps_completed.length===1&&s.steps_completed[0]===P&&J(s).sort().join(",")==="last_step,status,steps_completed";return s&&J(s).length>0&&!d?n("direct-yolo-setup-story-progress-conflict"):(d||await C(e.projectRoot,c=>{const l=he(c,e.storyId);if(J(l).length>0)throw new Error("direct-yolo-setup-runtime-raced");l.status="branch-ready",l.last_step=P,l.steps_completed=[P]},{expectedRevision:h.revision,preCommit:async()=>{if(await N(o,"utf8")!==r||await p(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.temporaryBranch||await p(e.projectRoot,["rev-parse","HEAD"])!==t.headSha||(await A(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:Object.freeze({...Te(e,t,d),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:t.headSha})})}async function Ft(e,t){const o=await K(e,t),r=await H(o.projectRoot,{required:!0}),i=X(g(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Yt(e,t,o,r){return Y(e,t,o,r)}function Jt(e){return E(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Zt=oe,mt="p205-wave:";function Qt(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=E(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function wt(e){return`${mt}${e.waveHeadSha}:${e.waveDigest}`}async function Ut(e){let t;try{t=await at(e.projectRoot,{headSha:e.headSha,graphRevisions:e.graphRevisions,...e.nowIso!==void 0?{nowIso:e.nowIso}:{}})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:"p205-complete-gate-failed"}}try{await e.qaRunner?.({projectRoot:e.projectRoot,storyId:e.storyId,headSha:e.headSha})}catch(o){const r=o instanceof Error?o.message:"";return{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Xt(e,t,o,r){const i=U(t);return await p(e,["push",i,o]),De(e,i,o,r)}async function er(e){try{const t=await K(e.projectRoot,e.storyId),o=e.coverage.waveHeadSha,r=e.coverage.waveStoryIds.indexOf(e.storyId);if(r<0||e.coverage.waveCommitShas[r]!==e.headSha)return n("direct-yolo-wave-coverage-invalid");if(await p(t.projectRoot,["rev-parse","HEAD"])!==o||await p(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==o||!await B(t.projectRoot,["merge-base","--is-ancestor",e.headSha,o]))return n("direct-yolo-wave-head-raced");const i=await H(t.projectRoot,{required:!0}),a=g(i.stories[e.storyId]?.checkpoint);if(a){if(a.headSha!==e.headSha)return n("direct-yolo-checkpoint-conflict");const D=e.authorities.get(String(a.graphRevision));return await fe(t.projectRoot,a,e.storyId,t.epicId,t.executionBranch,D??null,t.authorizedWriteSet)?(await ie(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:a}):n("direct-yolo-replay-invalid")}const h=await Ne(t,e.storyId,e.headSha);if(!h.ok)return n(h.reasonCode);const{baseSha:s,bundleDigest:d,graphRevision:c,claimRevision:l,idempotencyKey:m}=h.value,y=r===0?void 0:e.coverage.waveCommitShas[r-1];if(y!==void 0&&s!==y)return n("direct-yolo-wave-chain-invalid");const f=e.authorities.get(c),v=Oe(f);if(!f||!v||v.executionHeadSha!==o||v.graphRevision!==c)return n("direct-yolo-wave-qa-unbound");const x=await me({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:s,headSha:e.headSha,bundleDigest:d,graphRevision:c,claimRevision:l,idempotencyKey:m,qaExecution:{contract:"P205-CI-02",command:Pe,manifestDigest:v.manifestDigest,gateIds:v.gateIds,resultDigest:v.resultDigest,transientAuthority:f},physicalLockOwnerDigest:de(e.physicalLock.owner),nowIso:$(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[wt(e.coverage)]});return await we({projectRoot:t.projectRoot,checkpoint:x,remote:e.remote,expectedRevision:i.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:c,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:f,authorizedWriteSet:t.authorizedWriteSet,expectedHeadSha:o,keepLease:!0})?(await ie(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:x}):n("direct-yolo-checkpoint-persist-failed")}catch(t){return n(Z(t,"direct-yolo-wave-persist-failed"))}}async function ye(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=g(JSON.parse(await N(Q(o,".neocortex/state.json"),"utf8"))),i=await H(o,{required:!0}),a=tt(r,i),h=g(a.stories),s=g(a.epics),d=g(h?.[t]),c=String(d?.epic_id??t.split(".")[0]),l=g(s?.[c]),m=String(l?.execution_branch??""),y=String(l?.origin_branch??""),f=String(l?.graph_revision??""),v=dt(d),x=Array.isArray(d?.files_to_modify)||v.length>0?[...new Set([...Array.isArray(d?.files_to_modify)?d.files_to_modify:[],...v].filter(D=>typeof D=="string"&&je(D)))].sort():[];if(!d)throw new Error("direct-yolo-story-state-missing");if(v.length>0&&x.length>st)throw new Error("direct-yolo-write-set-too-large");if(l?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Ee(m)||!await B(o,["check-ref-format","--branch",m]))throw new Error("direct-yolo-execution-branch-invalid");if(!Ee(y)||!await B(o,["check-ref-format","--branch",y]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(f))throw new Error("direct-yolo-graph-revision-invalid");const k=await Xe({projectRoot:o,storyId:t,graphRevision:f,executionBranch:m,childPaths:x});return{projectRoot:o,storyId:t,story:d,epicId:c,executionBranch:m,originBranch:y,graphRevision:f,authorizedWriteSet:x,rootMemoryEffect:k}}async function K(e,t){const o=await ye(e,t);if(await p(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function me(e){const t=e.nowIso,o=await A(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=L(await A(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=rt({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),a=ot({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),h=`story-qa:${a}`,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:a,verdict:"passed",checkedAt:t,receiptRef:h}),d=ee(e.projectRoot,e.storyId,e.headSha);if(d?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const c=E(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,h,E(o),[...r].sort().join(","),d.digest].join("\0")),l=`story-review:${c}`,m=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:d.digest,qaReceiptRef:h,verdict:"approved",reviewedAt:t,receiptRef:l}),y=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,h,l,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[]];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(y),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:s,reviewReceipt:m,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function we(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await C(t,a=>{const h=W(a,o.epicId);if(e.expectedLease){const l=g(h.branch_lease);if(!Se(l,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(l?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(h.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const s=he(a,o.storyId),d=g(s.checkpoint);if(d&&d.headSha!==o.headSha){i=!0;return}s.checkpoint=o,s.status="done",s.last_step=ze;const c=Array.isArray(s.steps_completed)?s.steps_completed.filter(l=>typeof l=="string"):[];s.steps_completed=[...new Set([...c,ut,ze])],e.keepLease||(h.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const a=e.expectedHeadSha??o.headSha;if(await p(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await p(t,["rev-parse","HEAD"])!==a||await p(t,["rev-parse",`refs/heads/${o.branch}`])!==a||!await B(t,["merge-base","--is-ancestor",o.headSha,a]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await fe(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 re(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Me(t,r,o.branch,o.headSha):await De(t,r,o.branch,a)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Me(e,t,o,r){const i=U(t),a=(await p(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(a&&await B(e,["merge-base","--is-ancestor",r,a]))}function ge(e){return E(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const gt=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function ve(e,t){const o=await $e(e),r=await Le(o,"commit-plans"),i=`direct-${E(t)}.json`;return{parent:r,name:i,path:Q(r,i)}}async function vt(e,t){const o=await ve(e,t.storyId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
- `),await te(o.path,o.parent)}async function Ve(e,t){let o;try{o=await ve(e,t)}catch{return{state:"invalid"}}try{if(!Ce(o.path))return{state:"absent"};await te(o.path,o.parent);const r=await N(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=g(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...gt].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!Ee(i.executionBranch)||typeof i.preparedBase!="string"||!/^[a-f0-9]{40,64}$/.test(i.preparedBase)||![i.graphRevision,i.bundleDigest,i.claimRevision,i.idempotencyKey].every(h=>typeof h=="string"&&/^[a-f0-9]{64}$/.test(h))||typeof i.issuedAt!="string"||!Number.isFinite(Date.parse(i.issuedAt)))return{state:"invalid"};const a=i;return a.idempotencyKey!==ge({...a,baseSha:a.preparedBase})?{state:"invalid"}:{state:"valid",plan:a}}catch{return{state:"invalid"}}}async function ie(e,t){const o=await ve(e,t);Ce(o.path)&&await ft(o.parent,o.name)}function Re(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 Ge(e,t){const o=await $e(e),r=await Le(o,"handoffs"),i=`direct-${E(t)}.json`;return{parent:r,name:i,path:Q(r,i)}}async function Ie(e,t){const o=await Ge(e,t.storyId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
- `),await te(o.path,o.parent)}async function F(e,t){try{const o=await Ge(e,t);await te(o.path,o.parent);const r=JSON.parse(await N(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(a=>typeof a=="string"&&/^[a-f0-9]{64}$/.test(a))||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 Rt(e,t,o,r,i){const a=await F(e,t);if(!(!a||a.state==="consumed"||!a.token||a.bundleDigest!==o||a.claimRevision!==r||Date.parse(a.expiresAt)<=Date.parse(i)||E(a.token)!==a.tokenDigest))return{sessionId:a.fromSessionId,token:a.token}}async function It(e,t,o,r,i,a){const h=await F(e,t);if(!h||h.state==="consumed"||h.fromSessionId!==o||h.token!==r||h.tokenDigest!==E(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(h.state==="consuming"){if(h.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await Ie(e,{...h,state:"consuming",consumedBySessionId:i,consumeStartedAt:a})}async function St(e,t,o,r,i,a,h,s,d){const c=await F(e,o);if(c?.state==="consumed"&&c.fromSessionId===r&&c.consumedBySessionId===s)return;const l=await H(e,{required:!0}),m=g(l.epics[t]?.branch_lease),y=g(m?.handoffConsumption);if(!c||c.state!=="consuming"||c.fromSessionId!==r||c.token!==i||c.tokenDigest!==E(i)||c.bundleDigest!==a||c.claimRevision!==h||c.consumedBySessionId!==s||m?.ownerStoryId!==o||m.sessionId!==s||y?.kind!=="direct-yolo-setup-handoff-consumption"||y.state!=="consumed"||y.fromSessionId!==r||y.tokenDigest!==c.tokenDigest||y.bundleDigest!==a||y.claimRevision!==h||y.consumedBySessionId!==s)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Ie(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:d})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function xt(e){const t=g(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?E(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)&&kt(t.tokenDigest,r))}function kt(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&Qe(o,r)}function Se(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function xe(e,t,o){await C(e,r=>{const i=W(r,t),a=g(i.branch_lease);Se(a,o)&&(i.branch_lease=null)})}async function bt(e,t){const o=await H(e.projectRoot,{required:!0}),r=g(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Fe(r.sessionId)||!Fe(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 G(i.path,i.owner)&&await xe(e.projectRoot,e.epicId,r)}async function ke(e,t,o,r){const i=await nt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const a=Oe(i);if(!a)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Pe,manifestDigest:a.manifestDigest,gateIds:a.gateIds,resultDigest:a.resultDigest,transientAuthority:i}}async function be(e,t,o,r){return await p(e,["rev-parse","HEAD"])!==o||await p(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await B(e,["diff","--cached","--quiet"])?!1:B(e,["diff","--quiet","HEAD","--",...r])}async function De(e,t,o,r){const i=U(t);return(await p(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function Y(e,t,o,r){if(e.length===0||e.some(a=>!je(a)))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(a=>e.includes(a))||!i.every(a=>t.includes(a))?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==E([...t].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(a=>!t.includes(a)&&!r?.files.some(h=>h.path===a))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function J(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function je(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Fe(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Ee(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function U(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function E(e){return Ze("sha256").update(e).digest("hex")}function L(e){return e.split("\0").filter(Boolean)}function $(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Dt(e,t,o,r,i){const a=g(e.expectedLease),h=a?.sessionId,s=Date.parse(String(a?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(a)&&a?.schemaVersion===1&&a.ownerStoryId===r&&typeof h=="string"&&/^setup-[a-f0-9]{64}$/.test(h)&&a.idempotencyKey===h&&Number.isFinite(s)&&s<=i}async function jt(e,t){let o=await p(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await p(e,["rev-parse","HEAD"])!==t.originHead||await O(e)!==t.checkoutBefore)return;await p(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await p(e,["rev-parse","HEAD"])!==t.originHead||await O(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await B(e,["show-ref","--verify","--quiet",t.executionRef]))return;await p(e,["rev-parse",t.executionRef])===t.originHead&&await p(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}function X(e,t,o){const r=g(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 ae(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 O(e){const t=L(await A(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!je(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await p(e,["hash-object","--no-filters","--",r])}`}));return E([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"]),...o].join("\0"))}async function tr(e){const t=M(e),o=await p(t,["rev-parse","HEAD"]),r=await p(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await O(t);if(await p(t,["rev-parse","HEAD"])!==o||await p(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 Ae(e){const t=[];let o;for(const r of(await A(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 Z(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-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function n(e){return{ok:!1,reasonCode:e}}async function p(e,t){return String((await ue("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function A(e,t){return String((await ue("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function B(e,t){try{return await ue("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Zt as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,mt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,Kt as acceptDirectYoloSetupCheckpoint,Mt as beginDirectYoloStoryCommit,tr as captureDirectYoloCheckoutEvidence,Jt as directYoloCommitIdempotencyKey,Qt as directYoloWaveQaCoverage,wt as directYoloWaveReceiptRef,Vt as finalizeDirectYoloStoryCheckpoint,Tt as issueDirectYoloSetupLeaseHandoff,er as persistDirectYoloWaveStoryCheckpoint,Wt as prepareDirectYoloSetup,Xt as pushDirectYoloWaveHead,Gt as recoverLegacyDirectYoloStoryCheckpoint,Ft as resolveDirectYoloIntegrationAuthority,Ut as runDirectYoloWaveP205,Yt as validateDirectYoloWriteSet};
1
+ import{execFile as Qe}from"node:child_process";import{createHash as Ue,randomBytes as He,timingSafeEqual as Xe}from"node:crypto";import{existsSync as Ce}from"node:fs";import{readFile as N,realpath as de}from"node:fs/promises";import{join as Q,resolve as W}from"node:path";import{promisify as et}from"node:util";import{readRootMemoryEffectForCheckpoint as tt}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as rt,verifyRootMemoryPhysicalWriteSet as he}from"../private-execution/root-memory-git-evidence.js";import{expandStoryWriteScope as Le,storyWriteSetCovers as ot}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as T,applyGitLifecycleRuntimeOverlay as it,computeImmutableStoryQaEvidenceDigest as at,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as fe,computeP205StoryQaEvidenceDigest as nt,computeLegacyDirectYoloRecoveryReceiptRef as ct,ensureRuntimeEpic as K,ensureRuntimeStory as pe,ensureGitLifecyclePrivateChildDirectory as Oe,executeP205TransientAuthorities as st,executeP205TransientAuthority as dt,isP226GateReasonCode as ht,projectP205TransientExecutionEvidence as $e,publicStoryReviewArtifactFromGit as ee,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as ft,mutateGitLifecycleRuntime as C,P205_COMPLETE_COMMAND as Pe,readGitLifecycleRuntime as H,gitLifecycleRuntimeDirectory as qe,STORY_WRITE_SET_MAX_ENTRIES as pt,storyWriteSetExtensionPaths as lt,assertGitLifecyclePrivateFile as te,releaseGitLifecyclePhysicalIntegrationLock as M,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as ut,verifyGitLifecyclePhysicalIntegrationLock as re,verifyAcceptedGitLifecycleStoryCheckpoint as le}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as ze,anchoredRemoveFile as yt}from"./secure-filesystem-boundary.js";import{parseNeocortexTrailers as gt,trailerReasonKey as ue,trailerValue as ye}from"./neocortex-trailers.js";import{StoryWorktreeManager as mt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as wt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as Ne,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as $}from"./git-lifecycle-step-ids.js";const oe=et(Qe),ie=3600*1e3;async function Jt(e){let t,o=!1;try{const r=await ge(e.projectRoot,e.storyId);if(await Ke(r.projectRoot)){if(e.expiredSetupRecovery)return n("direct-yolo-expired-setup-recovery-invalid");const m=await Ve(r);return{ok:!0,value:Ge(r,m,!1)}}const i=P(e.nowIso),a=Date.parse(i),d=await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),s=await p(r.projectRoot,["rev-parse","HEAD"]),h=await H(r.projectRoot,{required:!0}),c=v(h.epics[r.epicId]),l=v(c?.branch_lease),g=e.expiredSetupRecovery;if(g&&!At(g,h.revision,l,e.storyId,a))return n("direct-yolo-expired-setup-recovery-invalid");const u=l&&Number.isFinite(Date.parse(String(l.expiresAt)))&&Date.parse(String(l.expiresAt))>a;if(u&&l?.ownerStoryId!==e.storyId)return n("direct-yolo-writer-active");let f=X(c?.origin_binding,r.executionBranch,r.originBranch),R;if(d===r.executionBranch){if(!f){if(c?.origin_binding!==void 0&&c?.origin_binding!==null||u)return n("direct-yolo-origin-binding-invalid");const m=await Lt(r,s,i);if(!m.ok)return m;f=m.value.binding,R={originRef:m.value.originRef,originHeadSha:m.value.binding.originHeadSha}}}else{if(d!==r.originBranch)return n("direct-yolo-current-branch-mismatch");if(f&&f.originHeadSha!==s){if(!g||!await A(r.projectRoot,["merge-base","--is-ancestor",f.originHeadSha,s]))return n("direct-yolo-origin-binding-conflict");const y=`refs/heads/${r.executionBranch}`;if(!await A(r.projectRoot,["show-ref","--verify","--quiet",y]))return n("direct-yolo-execution-branch-missing");const S=await p(r.projectRoot,["rev-parse",y]);if(!await A(r.projectRoot,["merge-base","--is-ancestor",S,s]))return n("direct-yolo-execution-branch-diverged")}if(f??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:s,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await ce(r.projectRoot)).some(y=>y.branch===r.executionBranch&&W(y.path)!==r.projectRoot))return n("direct-yolo-execution-branch-checked-out-elsewhere");const I=await O(r.projectRoot),w=`refs/heads/${r.executionBranch}`;if(await A(r.projectRoot,["show-ref","--verify","--quiet",w])){const y=await p(r.projectRoot,["rev-parse",w]);if(y!==s){if(!await A(r.projectRoot,["merge-base","--is-ancestor",y,s]))return n("direct-yolo-execution-branch-diverged");g||await p(r.projectRoot,["update-ref",w,s,y])}g?t={checkoutBefore:I,executionRef:w,executionBranch:r.executionBranch,executionHead:y,originBranch:r.originBranch,originHead:s}:await p(r.projectRoot,["switch",r.executionBranch])}else{if(g)return n("direct-yolo-execution-branch-missing");await p(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await O(r.projectRoot)!==I)return n("direct-yolo-checkout-payload-raced")}const x=t?.originHead??await p(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return n("direct-yolo-current-branch-mismatch");if(u&&l?.ownerStoryId===e.storyId)return l.setupHeadSha!==x?n("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:ne(r,f,String(l.expiresAt),!0)};const k=i,D=new Date(a+3600*1e3).toISOString(),b=`setup-${He(32).toString("hex")}`,j=g?h:await H(r.projectRoot,{required:!0});return await C(r.projectRoot,m=>{const I=K(m,r.epicId),w=v(I.branch_lease);if(g&&JSON.stringify(w)!==JSON.stringify(g.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(w&&Date.parse(String(w.expiresAt))>a&&w.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const y=X(I.origin_binding,r.executionBranch,r.originBranch);if(I.origin_binding&&!y)throw new Error("direct-yolo-origin-binding-conflict");if(y&&JSON.stringify(y)!==JSON.stringify(f))throw new Error("direct-yolo-origin-binding-conflict");I.branch_mode="epic",I.execution_branch=r.executionBranch,I.origin_branch=r.originBranch,I.graph_revision=r.graphRevision,I.origin_binding=f,I.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:b,idempotencyKey:b,acquiredAt:k,expiresAt:D,setupHeadSha:x}},{expectedRevision:g?.expectedRuntimeRevision??j.revision,preCommit:async()=>{if(t){if((await ce(r.projectRoot)).some(I=>I.branch===r.executionBranch&&W(I.path)!==r.projectRoot)||await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await O(r.projectRoot)!==t.checkoutBefore||!await A(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await p(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 p(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await p(r.projectRoot,["switch",r.executionBranch]),await O(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==x)throw new Error("direct-yolo-setup-physical-state-raced");if(R&&(await p(r.projectRoot,["rev-parse","--verify","--quiet",`${R.originRef}^{commit}`]).catch(()=>"")!==R.originHeadSha||await Je(r.projectRoot,["merge-base","--is-ancestor",R.originHeadSha,x])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:ne(r,f,D,!1)}}catch(r){return o&&t&&await _t(W(e.projectRoot),t).catch(()=>{}),n(Z(r,"direct-yolo-setup-failed"))}}async function Zt(e){let t;try{const o=await ge(e.projectRoot,e.storyId);if(await Ke(o.projectRoot))return await vt(o);const r=await V(e.projectRoot,e.storyId),i=P(e.nowIso),a=Q(r.projectRoot,".neocortex/state.json"),d=await N(a,"utf8"),s=await O(r.projectRoot),h=await p(r.projectRoot,["rev-parse","HEAD"]),c=`refs/heads/${r.executionBranch}`,l=await H(r.projectRoot,{required:!0}),g=v(l.epics[r.epicId]),u=X(g?.origin_binding,r.executionBranch,r.originBranch),f=v(g?.branch_lease);if(!u)return n("direct-yolo-origin-binding-invalid");if(!f||!Ie(f,e.storyId,i)||f?.sessionId!==f?.idempotencyKey)return n("direct-yolo-setup-lease-invalid");const R=await T(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 n(R.reasonCode);if(t=R,h!==f.setupHeadSha||!await A(r.projectRoot,["merge-base","--is-ancestor",u.originHeadSha,h])||await p(r.projectRoot,["rev-parse",c])!==h)return n("direct-yolo-setup-head-mismatch");if((await ce(r.projectRoot)).some(I=>I.branch===r.executionBranch&&W(I.path)!==r.projectRoot))return n("direct-yolo-execution-branch-checked-out-elsewhere");const k=v(JSON.parse(d)),D=v(v(k?.stories)?.[e.storyId]),b=v(l.stories[e.storyId]);if(!D||!["backlog","ready_to_start"].includes(String(D.status))||D.steps_completed!==void 0&&(!Array.isArray(D.steps_completed)||D.steps_completed.length>0)||D.branch_name||D.checkpoint)return n("direct-yolo-setup-story-progress-conflict");const j=b?.status==="branch-ready"&&b.last_step===$&&Array.isArray(b.steps_completed)&&b.steps_completed.length===1&&b.steps_completed[0]===$&&J(b).sort().join(",")==="last_step,status,steps_completed";if(b&&J(b).length>0&&!j)return n("direct-yolo-setup-story-progress-conflict");const m=async()=>{if(Date.parse(String(f.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await re(t.path,t.owner)||await N(a,"utf8")!==d||await O(r.projectRoot)!==s||await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==h||!await A(r.projectRoot,["merge-base","--is-ancestor",u.originHeadSha,h])||await p(r.projectRoot,["rev-parse",c])!==h)throw new Error("direct-yolo-setup-physical-state-raced")};return j?await m():await C(r.projectRoot,I=>{const w=v(I.epics[r.epicId]),y=pe(I,e.storyId);if(JSON.stringify(w?.branch_lease)!==JSON.stringify(f)||JSON.stringify(w?.origin_binding)!==JSON.stringify(u)||w?.graph_revision!==r.graphRevision||J(y).length>0)throw new Error("direct-yolo-setup-runtime-raced");y.status="branch-ready",y.last_step=$,y.steps_completed=[$]},{expectedRevision:l.revision,preCommit:m}),{ok:!0,value:Object.freeze({...ne(r,u,String(f.expiresAt),j),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:h})}}catch(o){return n(Z(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await M(t.path,t.owner).catch(()=>{})}}async function Qt(e){try{const t=await V(e.projectRoot,e.storyId),o=L(await B(t.projectRoot,["diff","--cached","--name-only","-z"])),r=Y(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return n(r.reasonCode);if(t.rootMemoryEffect&&he(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await p(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),ee(t.projectRoot,e.storyId,":")?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");if(L(await B(t.projectRoot,["diff","--name-only","-z"])).some(y=>o.includes(y)))return n("direct-yolo-user-overlap");const d=await B(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!d)return n("direct-yolo-staged-diff-empty");const s=E(d),h=E([...t.authorizedWriteSet].sort().join("\0")),c=P(e.nowIso),l=await H(t.projectRoot,{required:!0}),g=v(l.epics[t.epicId]?.branch_lease);if(!Ie(g,e.storyId,c))return n("direct-yolo-setup-handoff-owner-invalid");const u=String(g.sessionId),f=String(g.expiresAt),R=new Date(Math.min(Date.parse(f),Date.parse(c)+300*1e3)).toISOString(),x=await F(t.projectRoot,e.storyId),k=x?.state==="issued"&&x.fromSessionId===u&&x.bundleDigest===s&&x.claimRevision===h&&Date.parse(x.expiresAt)>Date.parse(c),D=k?x.expiresAt:R,b=k?x.token:He(32).toString("base64url"),j=E(b),m=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:u,tokenDigest:j,bundleDigest:s,claimRevision:h,expiresAt:D}),I=E(JSON.stringify(m)),w=await T(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:u,idempotencyKey:u,expiresAt:D,persistent:!1,createdAt:c});if(!w.ok)return n(w.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Se(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:u,token:b,tokenDigest:j,bundleDigest:s,claimRevision:h,grantDigest:I,expiresAt:D}),await C(t.projectRoot,y=>{const S=v(K(y,t.epicId).branch_lease);if(!Ie(S,e.storyId,c)||S?.sessionId!==u||S.idempotencyKey!==u)throw new Error("direct-yolo-setup-handoff-owner-raced");S.handoffGrant=m},{expectedRevision:l.revision,preCommit:async()=>{if(!await re(w.path,w.owner))throw new Error("direct-yolo-integration-lock-raced");const y=await F(t.projectRoot,e.storyId);if(!y||y.state!=="issued"||y.grantDigest!==I||y.tokenDigest!==j)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await M(w.path,w.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:I,expiresAt:D,reused:k,publicSafe:!0})}}catch(t){return n(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function Ut(e){try{const t=await V(e.projectRoot,e.storyId),o=await p(t.projectRoot,["rev-parse","HEAD"]),r=L(await B(t.projectRoot,["diff","--cached","--name-only","-z"])),i=Y(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return n(i.reasonCode);t.rootMemoryEffect&&he(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const a=ee(t.projectRoot,e.storyId,":");if(a?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");if(L(await B(t.projectRoot,["diff","--name-only","-z"])).some(S=>r.includes(S)))return n("direct-yolo-user-overlap");const s=await B(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!s)return n("direct-yolo-staged-diff-empty");const h=E(s),c=E([...t.authorizedWriteSet].sort().join("\0")),l=await Me(t.projectRoot,e.storyId),g=l.state==="valid"&&l.plan.epicId===t.epicId&&l.plan.executionBranch===t.executionBranch&&l.plan.preparedBase===o&&l.plan.bundleDigest===h&&l.plan.claimRevision===c?l.plan:void 0,u=g?.graphRevision??t.graphRevision,f=ve({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:h,graphRevision:u,claimRevision:c}),R=P(e.nowIso),x={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:u,preparedBase:o,bundleDigest:h,claimRevision:c,idempotencyKey:f,issuedAt:g?.issuedAt??R};let k=e.setupLeaseHandoff??await kt(t.projectRoot,e.storyId,h,c,R);const D=await H(t.projectRoot,{required:!0}),b=v(D.epics[t.epicId]?.branch_lease),j=b?.ownerStoryId===e.storyId&&b.sessionId===f&&b.idempotencyKey===f&&typeof b.expiresAt=="string"&&Date.parse(b.expiresAt)>Date.parse(R)?b:void 0;if(j&&e.setupLeaseHandoff)return n("direct-yolo-setup-handoff-replayed");const m=v(j?.handoffConsumption);if(m){const S=await F(t.projectRoot,e.storyId);if(!S||!["consuming","consumed"].includes(S.state)||S.fromSessionId!==m.fromSessionId||S.tokenDigest!==m.tokenDigest||S.bundleDigest!==h||S.claimRevision!==c||m.bundleDigest!==h||m.claimRevision!==c||S.consumedBySessionId!==f||m.consumedBySessionId!==f)return n("direct-yolo-setup-handoff-consume-invalid");if(S.state==="consuming"){if(!S.token||E(S.token)!==S.tokenDigest)return n("direct-yolo-setup-handoff-consume-invalid");k={sessionId:S.fromSessionId,token:S.token}}}const I=j?String(j.expiresAt):new Date(Date.parse(R)+ie).toISOString(),w=await T(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:f,idempotencyKey:f,expiresAt:I,persistent:!0,createdAt:j&&typeof j.acquiredAt=="string"?j.acquiredAt:R});if(!w.ok)return n(w.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{k&&e.setupLeaseHandoff===void 0&&(await bt(t.projectRoot,e.storyId,k.sessionId,k.token,f,R),await e.setupHandoffFault?.("after-consuming-persisted")),await C(t.projectRoot,S=>{const q=K(S,t.epicId),_=v(q.branch_lease),z=_&&Date.parse(String(_.expiresAt))>Date.parse(R),G=_?.ownerStoryId===e.storyId&&_.sessionId===f&&_.idempotencyKey===f,Ze=_?.ownerStoryId===e.storyId&&_.sessionId===_.idempotencyKey&&typeof _.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(_.idempotencyKey),se=z&&Ze&&jt({current:_,handoff:k,storyId:e.storyId,bundleDigest:h,claimRevision:c,nowIso:R});if(k&&z&&!G&&!se)throw new Error("direct-yolo-setup-handoff-invalid");if(z&&!G&&!se)throw new Error("direct-yolo-writer-active");const Ae=se?v(_?.handoffGrant):void 0,_e=Ae?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(_?.sessionId),tokenDigest:String(Ae.tokenDigest),bundleDigest:h,claimRevision:c,consumedBySessionId:f,consumedAt:R}:void 0;q.branch_mode="epic",q.execution_branch=t.executionBranch,q.origin_branch=t.originBranch,q.graph_revision=t.graphRevision,q.branch_lease=z&&G?_:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:f,idempotencyKey:f,acquiredAt:R,expiresAt:I,..._e?{handoffConsumption:_e}:{}}},{expectedRevision:D.revision,preCommit:async()=>{if(!await re(w.path,w.owner))throw new Error("direct-yolo-integration-lock-raced");await xt(t.projectRoot,x)}})}catch(S){throw await M(w.path,w.owner).catch(()=>{}),S}k&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Dt(t.projectRoot,t.epicId,e.storyId,k.sessionId,k.token,h,c,f,R));const y=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: ${a.digest}`,`Neocortex-Graph-Revision: ${u}`,`Neocortex-Claim-Revision: ${c}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${rt(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:h,reviewArtifactDigest:a.digest,graphRevision:u,claimRevision:c,idempotencyKey:f,changedPaths:Object.freeze(r),trailers:y})}}catch(t){return n(Z(t,"direct-yolo-begin-failed"))}}async function Xt(e){let t,o,r;try{const i=await V(e.projectRoot,e.storyId);t=i;const a=await p(i.projectRoot,["rev-parse","HEAD"]);let d=await H(i.projectRoot,{required:!0});const s=v(d.stories[e.storyId]?.checkpoint);if(s){const I=typeof s.headSha=="string"?s.headSha:"",w=typeof s.graphRevision=="string"?s.graphRevision:"",y=/^[a-f0-9]{40,64}$/.test(I)?L(await B(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",I])):[],S=Y(y,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(I)&&await A(i.projectRoot,["merge-base","--is-ancestor",I,a]))||!/^[a-f0-9]{64}$/.test(w)||!S.ok)return n("direct-yolo-replay-invalid");const _=await be(e,i.projectRoot,a,w);if(!await le(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,_.transientAuthority,i.authorizedWriteSet))return n("direct-yolo-replay-invalid");if(!await De(i.projectRoot,i.executionBranch,a,y))return n("direct-yolo-replay-head-raced");if(e.push&&!await Te(i.projectRoot,e.remote??"origin",i.executionBranch,I))return n("direct-yolo-remote-head-mismatch");const z=Array.isArray(s.receiptRefs)?s.receiptRefs.find(G=>typeof G=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(G)):void 0;return z&&typeof s.idempotencyKey=="string"&&await ut(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:z.slice(20)}),await ae(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const h=a,c=await We(i,e.storyId,h);if(!c.ok)return n(c.reasonCode);const{baseSha:l,changedPaths:g,bundleDigest:u,graphRevision:f,claimRevision:R,idempotencyKey:x}=c.value,k=v(d.epics[i.epicId]?.branch_lease),D=P(e.nowIso),b=k?.ownerStoryId===e.storyId&&k.idempotencyKey===x&&k.sessionId===x&&Date.parse(String(k.expiresAt))>Date.now()?k:void 0;if(k&&Date.parse(String(k.expiresAt))>Date.now()&&!b)return n("direct-yolo-writer-active");const j=b??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:x,idempotencyKey:x,acquiredAt:D,expiresAt:new Date(Date.parse(D)+ie).toISOString()},m=await T(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:x,idempotencyKey:x,expiresAt:String(j.expiresAt),persistent:!0,createdAt:String(j.acquiredAt)});if(!m.ok)return n(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,b||(d=(await C(i.projectRoot,w=>{const y=K(w,i.epicId),S=v(y.branch_lease);if(S&&Date.parse(String(S.expiresAt))>Date.parse(D))throw new Error("direct-yolo-writer-active");if(y.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");y.branch_lease=j},{expectedRevision:d.revision})).document),o=j;{const I=await be(e,i.projectRoot,h,f);if(!await De(i.projectRoot,i.executionBranch,h,g))return n("direct-yolo-head-raced");if(e.push){const S=U(e.remote??"origin");if(await p(i.projectRoot,["push",S,i.executionBranch]),!await je(i.projectRoot,S,i.executionBranch,h))return n("direct-yolo-remote-head-mismatch")}const w=await me({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:l,headSha:h,bundleDigest:u,graphRevision:f,claimRevision:R,idempotencyKey:x,qaExecution:I,physicalLockOwnerDigest:fe(m.owner),nowIso:P(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await we({projectRoot:i.projectRoot,checkpoint:w,remote:e.push?e.remote??"origin":void 0,expectedRevision:d.revision,expectedLease:j,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:f,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:I.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await ae(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:w}):n("direct-yolo-checkpoint-persist-failed")}}catch(i){return n(Z(i,"direct-yolo-finalize-failed"))}finally{r&&await M(r.path,r.owner).catch(()=>{}),t&&o?await ke(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await Bt(t,e.storyId).catch(()=>{})}}async function We(e,t,o){const r=await p(e.projectRoot,["rev-parse",`${o}^`]),i=await B(e.projectRoot,["show","--no-patch","--format=%B",o]),a=L(await B(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),d=Y(a,e.authorizedWriteSet,t,e.rootMemoryEffect);if(!d.ok)return n(d.reasonCode);e.rootMemoryEffect&&he(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:r,headRef:o,childPaths:e.authorizedWriteSet});const s=E([...e.authorizedWriteSet].sort().join("\0")),h=await Me(e.projectRoot,t);if(h.state==="invalid")return n("direct-yolo-commit-plan-invalid");const c=h.state==="valid"?h.plan:void 0;if(c&&(c.epicId!==e.epicId||c.executionBranch!==e.executionBranch))return n("direct-yolo-commit-plan-invalid");if(c&&c.claimRevision!==s)return n("direct-yolo-commit-plan-claim-changed");if(c&&c.preparedBase!==r)return n("direct-yolo-commit-plan-base-mismatch");const l=gt(i);if(!l.ok)return n(`direct-yolo-trailer-duplicate:${l.key}`);const g=l.values,u=c?.graphRevision??e.graphRevision,f=s,R=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",r],["Neocortex-Bundle-Digest",c?.bundleDigest??""],["Neocortex-Graph-Revision",u],["Neocortex-Claim-Revision",f]];for(const[m,I]of R){const w=ye(g,m);if(w===void 0)return n(`direct-yolo-trailer-missing:${ue(m)}`);if(m==="Neocortex-Bundle-Digest"&&!c){if(!/^[a-f0-9]{64}$/.test(w))return n(`direct-yolo-trailer-mismatch:${ue(m)}`);continue}if(w!==I)return n(`direct-yolo-trailer-mismatch:${ue(m)}`)}const x=ye(g,"Neocortex-Bundle-Digest"),k=ee(e.projectRoot,t,o);if(k?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");const D=ye(g,"Neocortex-Review-Artifact-Digest");if(D!==void 0&&D!==k.digest)return n("direct-yolo-review-artifact-digest-mismatch");const b=E(await B(e.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]));if(x!==b)return n("direct-yolo-bundle-digest-mismatch");const j=ve({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:r,bundleDigest:x,graphRevision:u,claimRevision:f});return c&&c.idempotencyKey!==j?n("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:r,changedPaths:a,bundleDigest:x,graphRevision:u,claimRevision:f,idempotencyKey:j}}}async function er(e){try{const t=await V(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return n("direct-yolo-recovery-commit-invalid");const o=await p(t.projectRoot,["rev-parse",e.commitSha]);if(ft[e.storyId]!==o)return n("direct-yolo-recovery-not-allowlisted");if(await p(t.projectRoot,["rev-parse","HEAD"])!==o)return n("direct-yolo-recovery-head-mismatch");await p(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await p(t.projectRoot,["rev-parse",`${o}^`]),i=await B(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),a=L(await B(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!Y(a,t.authorizedWriteSet.length>0?t.authorizedWriteSet:a,e.storyId).ok)return n("direct-yolo-recovery-write-set-invalid");const s=E(i),h=E([...a].sort().join("\0")),c=E(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),l=P(e.nowIso),g=new Date(Date.parse(l)+ie).toISOString(),u=await H(t.projectRoot,{required:!0}),f=await T(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:c,idempotencyKey:c,expiresAt:g,persistent:!0,createdAt:l});if(!f.ok)return n(f.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const R={schemaVersion:1,ownerStoryId:e.storyId,sessionId:c,idempotencyKey:c,acquiredAt:l,expiresAt:g};let x=!1;try{const k=await C(t.projectRoot,w=>{const y=K(w,t.epicId),S=v(y.branch_lease);if(S&&Date.parse(String(S.expiresAt))>Date.parse(l)&&!xe(S,R))throw new Error("direct-yolo-recovery-writer-active");if(y.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");y.branch_mode="epic",y.execution_branch=t.executionBranch,y.origin_branch=t.originBranch,y.branch_lease=R},{expectedRevision:u.revision});x=!0;const D=await be(e,t.projectRoot,o,t.graphRevision);if(!await De(t.projectRoot,t.executionBranch,o,a))return n("direct-yolo-recovery-head-raced");if(e.push){const w=U(e.remote??"origin"),y=(await p(t.projectRoot,["ls-remote","--heads",w,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!y||!await A(t.projectRoot,["merge-base","--is-ancestor",o,y]))return n("direct-yolo-recovery-remote-proof-missing")}const b=await me({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:D,physicalLockOwnerDigest:fe(f.owner),nowIso:l,legacyReceiptRef:void 0}),j=await ct(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision});if(!j)return n("direct-yolo-recovery-evidence-invalid");const m=Object.freeze({...b,receiptRefs:Object.freeze([...b.receiptRefs,j])});return await we({projectRoot:t.projectRoot,checkpoint:m,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:k.document.revision,expectedLease:R,expectedGraphRevision:t.graphRevision,physicalLockPath:f.path,physicalLockOwner:f.owner,transientAuthority:D.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:m}:n("direct-yolo-recovery-persist-failed")}finally{await M(f.path,f.owner).catch(()=>{}),x&&await ke(t.projectRoot,t.epicId,R).catch(()=>{})}}catch(t){return n(Z(t,"direct-yolo-recovery-failed"))}}async function Ke(e){const t=await de(await p(e,["rev-parse","--absolute-git-dir"])),o=await de(await p(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function Ve(e){const t=await H(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(g=>g.storyId===e.storyId&&g.epicId===e.epicId&&g.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await de(await p(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await p(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const d=await new mt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!d.ok||d.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const s=X(v(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!s)throw new Error("direct-yolo-origin-binding-invalid");const h=r.syncedSha??r.baseSha,c=await p(e.projectRoot,["rev-parse","HEAD"]),l=`refs/heads/${e.executionBranch}`;if(c!==h||!await A(e.projectRoot,["merge-base","--is-ancestor",h,l])||!await A(e.projectRoot,["merge-base","--is-ancestor",s.originHeadSha,h]))throw new Error("direct-yolo-worktree-base-divergent");if(d.value.clean!==!0||(await B(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-worktree-dirty");return{leaseId:r.leaseId,temporaryBranch:r.temporaryBranch,authorizedBase:h,headSha:c,expiresAt:r.expiresAt,binding:s}}function Ge(e,t,o){return Object.freeze({...ne(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function vt(e){const t=await Ve(e),o=Q(e.projectRoot,".neocortex/state.json"),r=await N(o,"utf8"),i=v(JSON.parse(r)),a=v(v(i?.stories)?.[e.storyId]),d=await H(e.projectRoot,{required:!0}),s=v(d.stories[e.storyId]);if(!a||!["backlog","ready_to_start"].includes(String(a.status))||a.steps_completed!==void 0&&(!Array.isArray(a.steps_completed)||a.steps_completed.length>0)||a.branch_name||a.checkpoint)return n("direct-yolo-setup-story-progress-conflict");const h=s?.status==="branch-ready"&&s.last_step===$&&Array.isArray(s.steps_completed)&&s.steps_completed.length===1&&s.steps_completed[0]===$&&J(s).sort().join(",")==="last_step,status,steps_completed";return s&&J(s).length>0&&!h?n("direct-yolo-setup-story-progress-conflict"):(h||await C(e.projectRoot,c=>{const l=pe(c,e.storyId);if(J(l).length>0)throw new Error("direct-yolo-setup-runtime-raced");l.status="branch-ready",l.last_step=$,l.steps_completed=[$]},{expectedRevision:d.revision,preCommit:async()=>{if(await N(o,"utf8")!==r||await p(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.temporaryBranch||await p(e.projectRoot,["rev-parse","HEAD"])!==t.headSha||(await B(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:Object.freeze({...Ge(e,t,h),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:t.headSha})})}async function tr(e,t){const o=await V(e,t),r=await H(o.projectRoot,{required:!0}),i=X(v(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function rr(e,t,o,r){return Y(e,t,o,r)}function or(e){return E(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const ir=ie,Rt="p205-wave:";function ar(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=E(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function It(e){return`${Rt}${e.waveHeadSha}:${e.waveDigest}`}async function nr(e){let t;try{t=await st(e.projectRoot,{headSha:e.headSha,graphRevisions:e.graphRevisions,...e.nowIso!==void 0?{nowIso:e.nowIso}:{}})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:"p205-complete-gate-failed"}}try{await e.qaRunner?.({projectRoot:e.projectRoot,storyId:e.storyId,headSha:e.headSha})}catch(o){const r=o instanceof Error?o.message:"";return{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function cr(e,t,o,r){const i=U(t);return await p(e,["push",i,o]),je(e,i,o,r)}async function sr(e){try{const t=await V(e.projectRoot,e.storyId),o=e.coverage.waveHeadSha,r=e.coverage.waveStoryIds.indexOf(e.storyId);if(r<0||e.coverage.waveCommitShas[r]!==e.headSha)return n("direct-yolo-wave-coverage-invalid");if(await p(t.projectRoot,["rev-parse","HEAD"])!==o||await p(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==o||!await A(t.projectRoot,["merge-base","--is-ancestor",e.headSha,o]))return n("direct-yolo-wave-head-raced");const i=await H(t.projectRoot,{required:!0}),a=v(i.stories[e.storyId]?.checkpoint);if(a){if(a.headSha!==e.headSha)return n("direct-yolo-checkpoint-conflict");const D=e.authorities.get(String(a.graphRevision));return await le(t.projectRoot,a,e.storyId,t.epicId,t.executionBranch,D??null,t.authorizedWriteSet)?(await ae(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:a}):n("direct-yolo-replay-invalid")}const d=await We(t,e.storyId,e.headSha);if(!d.ok)return n(d.reasonCode);const{baseSha:s,bundleDigest:h,graphRevision:c,claimRevision:l,idempotencyKey:g}=d.value,u=r===0?void 0:e.coverage.waveCommitShas[r-1];if(u!==void 0&&s!==u)return n("direct-yolo-wave-chain-invalid");const f=e.authorities.get(c),R=$e(f);if(!f||!R||R.executionHeadSha!==o||R.graphRevision!==c)return n("direct-yolo-wave-qa-unbound");const x=await me({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:s,headSha:e.headSha,bundleDigest:h,graphRevision:c,claimRevision:l,idempotencyKey:g,qaExecution:{contract:"P205-CI-02",command:Pe,manifestDigest:R.manifestDigest,gateIds:R.gateIds,resultDigest:R.resultDigest,transientAuthority:f},physicalLockOwnerDigest:fe(e.physicalLock.owner),nowIso:P(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[It(e.coverage)]});return await we({projectRoot:t.projectRoot,checkpoint:x,remote:e.remote,expectedRevision:i.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:c,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:f,authorizedWriteSet:t.authorizedWriteSet,expectedHeadSha:o,keepLease:!0})?(await ae(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:x}):n("direct-yolo-checkpoint-persist-failed")}catch(t){return n(Z(t,"direct-yolo-wave-persist-failed"))}}async function ge(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=W(e),r=v(JSON.parse(await N(Q(o,".neocortex/state.json"),"utf8"))),i=await H(o,{required:!0}),a=it(r,i),d=v(a.stories),s=v(a.epics),h=v(d?.[t]),c=String(h?.epic_id??t.split(".")[0]),l=v(s?.[c]),g=String(l?.execution_branch??""),u=String(l?.origin_branch??""),f=String(l?.graph_revision??""),R=Array.isArray(h?.files_to_modify)?h.files_to_modify:[],x=lt(h).filter(m=>Ee(m)&&!/[*?[\]{}!]/.test(m)&&!m.endsWith("/")),k=[...R,...x],D=k.length>0?Le(t,k):void 0,b=D?.ok?D.scopes:[];if(!h)throw new Error("direct-yolo-story-state-missing");if(x.length>0&&b.length>pt)throw new Error("direct-yolo-write-set-too-large");if(l?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Be(g)||!await A(o,["check-ref-format","--branch",g]))throw new Error("direct-yolo-execution-branch-invalid");if(!Be(u)||!await A(o,["check-ref-format","--branch",u]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(f))throw new Error("direct-yolo-graph-revision-invalid");const j=await tt({projectRoot:o,storyId:t,graphRevision:f,executionBranch:g,childPaths:b});return{projectRoot:o,storyId:t,story:h,epicId:c,executionBranch:g,originBranch:u,graphRevision:f,authorizedWriteSet:b,rootMemoryEffect:j}}async function V(e,t){const o=await ge(e,t);if(await p(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function me(e){const t=e.nowIso,o=await B(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=L(await B(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=at({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),a=nt({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),d=`story-qa:${a}`,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:a,verdict:"passed",checkedAt:t,receiptRef:d}),h=ee(e.projectRoot,e.storyId,e.headSha);if(h?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const c=E(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,d,E(o),[...r].sort().join(","),h.digest].join("\0")),l=`story-review:${c}`,g=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:d,verdict:"approved",reviewedAt:t,receiptRef:l}),u=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,d,l,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[]];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:g,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function we(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await C(t,a=>{const d=K(a,o.epicId);if(e.expectedLease){const l=v(d.branch_lease);if(!xe(l,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(l?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(d.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const s=pe(a,o.storyId),h=v(s.checkpoint);if(h&&h.headSha!==o.headSha){i=!0;return}s.checkpoint=o,s.status="done",s.last_step=Ne;const c=Array.isArray(s.steps_completed)?s.steps_completed.filter(l=>typeof l=="string"):[];s.steps_completed=[...new Set([...c,wt,Ne])],e.keepLease||(d.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const a=e.expectedHeadSha??o.headSha;if(await p(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await p(t,["rev-parse","HEAD"])!==a||await p(t,["rev-parse",`refs/heads/${o.branch}`])!==a||!await A(t,["merge-base","--is-ancestor",o.headSha,a]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await le(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 re(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Te(t,r,o.branch,o.headSha):await je(t,r,o.branch,a)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Te(e,t,o,r){const i=U(t),a=(await p(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(a&&await A(e,["merge-base","--is-ancestor",r,a]))}function ve(e){return E(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const St=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function Re(e,t){const o=await qe(e),r=await Oe(o,"commit-plans"),i=`direct-${E(t)}.json`;return{parent:r,name:i,path:Q(r,i)}}async function xt(e,t){const o=await Re(e,t.storyId);await ze(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
+ `),await te(o.path,o.parent)}async function Me(e,t){let o;try{o=await Re(e,t)}catch{return{state:"invalid"}}try{if(!Ce(o.path))return{state:"absent"};await te(o.path,o.parent);const r=await N(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=v(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...St].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!Be(i.executionBranch)||typeof i.preparedBase!="string"||!/^[a-f0-9]{40,64}$/.test(i.preparedBase)||![i.graphRevision,i.bundleDigest,i.claimRevision,i.idempotencyKey].every(d=>typeof d=="string"&&/^[a-f0-9]{64}$/.test(d))||typeof i.issuedAt!="string"||!Number.isFinite(Date.parse(i.issuedAt)))return{state:"invalid"};const a=i;return a.idempotencyKey!==ve({...a,baseSha:a.preparedBase})?{state:"invalid"}:{state:"valid",plan:a}}catch{return{state:"invalid"}}}async function ae(e,t){const o=await Re(e,t);Ce(o.path)&&await yt(o.parent,o.name)}function Ie(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 Fe(e,t){const o=await qe(e),r=await Oe(o,"handoffs"),i=`direct-${E(t)}.json`;return{parent:r,name:i,path:Q(r,i)}}async function Se(e,t){const o=await Fe(e,t.storyId);await ze(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
+ `),await te(o.path,o.parent)}async function F(e,t){try{const o=await Fe(e,t);await te(o.path,o.parent);const r=JSON.parse(await N(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(a=>typeof a=="string"&&/^[a-f0-9]{64}$/.test(a))||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 kt(e,t,o,r,i){const a=await F(e,t);if(!(!a||a.state==="consumed"||!a.token||a.bundleDigest!==o||a.claimRevision!==r||Date.parse(a.expiresAt)<=Date.parse(i)||E(a.token)!==a.tokenDigest))return{sessionId:a.fromSessionId,token:a.token}}async function bt(e,t,o,r,i,a){const d=await F(e,t);if(!d||d.state==="consumed"||d.fromSessionId!==o||d.token!==r||d.tokenDigest!==E(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(d.state==="consuming"){if(d.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await Se(e,{...d,state:"consuming",consumedBySessionId:i,consumeStartedAt:a})}async function Dt(e,t,o,r,i,a,d,s,h){const c=await F(e,o);if(c?.state==="consumed"&&c.fromSessionId===r&&c.consumedBySessionId===s)return;const l=await H(e,{required:!0}),g=v(l.epics[t]?.branch_lease),u=v(g?.handoffConsumption);if(!c||c.state!=="consuming"||c.fromSessionId!==r||c.token!==i||c.tokenDigest!==E(i)||c.bundleDigest!==a||c.claimRevision!==d||c.consumedBySessionId!==s||g?.ownerStoryId!==o||g.sessionId!==s||u?.kind!=="direct-yolo-setup-handoff-consumption"||u.state!=="consumed"||u.fromSessionId!==r||u.tokenDigest!==c.tokenDigest||u.bundleDigest!==a||u.claimRevision!==d||u.consumedBySessionId!==s)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Se(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 jt(e){const t=v(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?E(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)&&Et(t.tokenDigest,r))}function Et(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&Xe(o,r)}function xe(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function ke(e,t,o){await C(e,r=>{const i=K(r,t),a=v(i.branch_lease);xe(a,o)&&(i.branch_lease=null)})}async function Bt(e,t){const o=await H(e.projectRoot,{required:!0}),r=v(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Ye(r.sessionId)||!Ye(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await T(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 M(i.path,i.owner)&&await ke(e.projectRoot,e.epicId,r)}async function be(e,t,o,r){const i=await dt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const a=$e(i);if(!a)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Pe,manifestDigest:a.manifestDigest,gateIds:a.gateIds,resultDigest:a.resultDigest,transientAuthority:i}}async function De(e,t,o,r){return await p(e,["rev-parse","HEAD"])!==o||await p(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await A(e,["diff","--cached","--quiet"])?!1:A(e,["diff","--quiet","HEAD","--",...r])}async function je(e,t,o,r){const i=U(t);return(await p(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function Y(e,t,o,r){if(e.length===0||e.some(d=>!Ee(d)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=t.length>0?Le(o,t):void 0;return i?.ok?[".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`].every(d=>e.includes(d))?r&&(r.storyId!==o||r.childClaimRevision!==E([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(d=>!ot(i.scopes,d)&&!r?.files.some(s=>s.path===d))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}}function J(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function Ee(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Ye(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 U(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function E(e){return Ue("sha256").update(e).digest("hex")}function L(e){return e.split("\0").filter(Boolean)}function P(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function v(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function At(e,t,o,r,i){const a=v(e.expectedLease),d=a?.sessionId,s=Date.parse(String(a?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(a)&&a?.schemaVersion===1&&a.ownerStoryId===r&&typeof d=="string"&&/^setup-[a-f0-9]{64}$/.test(d)&&a.idempotencyKey===d&&Number.isFinite(s)&&s<=i}async function _t(e,t){let o=await p(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await p(e,["rev-parse","HEAD"])!==t.originHead||await O(e)!==t.checkoutBefore)return;await p(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await p(e,["rev-parse","HEAD"])!==t.originHead||await O(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await A(e,["show-ref","--verify","--quiet",t.executionRef]))return;await p(e,["rev-parse",t.executionRef])===t.originHead&&await p(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}const Ht=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],Ct=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function X(e,t,o){const r=v(e);if(!r||r.originBranch!==o||r.executionBranch!==t||typeof r.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.originHeadSha)||typeof r.capturedAt!="string"||!Number.isFinite(Date.parse(r.capturedAt)))return;const i=Object.keys(r).sort().join("\0");if(r.schemaVersion===1)return r.capturedFromCurrentCheckout!==!0||i!==Ht.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==Ct.join("\0")?void 0:r}async function Lt(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await A(e.projectRoot,["show-ref","--verify","--quiet",r]))return n("direct-yolo-origin-ref-missing","fetch-origin-branch");const i=await p(e.projectRoot,["rev-parse","--verify","--quiet",`${r}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(i))return n("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await ce(e.projectRoot)).some(h=>h.branch===e.executionBranch&&W(h.path)!==e.projectRoot))return n("direct-yolo-execution-branch-checked-out-elsewhere");const d=`refs/heads/${e.executionBranch}`;if(await p(e.projectRoot,["rev-parse","--verify","--quiet",d]).catch(()=>"")!==t)return n("direct-yolo-setup-physical-state-raced");const s=await Je(e.projectRoot,["merge-base","--is-ancestor",i,t]);return s===1?n("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):s!==0?n("direct-yolo-origin-ancestry-unverifiable"):{ok:!0,value:{originRef:r,binding:{schemaVersion:2,originBranch:e.originBranch,originHeadSha:i,executionBranch:e.executionBranch,capturedFrom:"branch-ref",capturedAt:o}}}}function ne(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 O(e){const t=L(await B(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Ee(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await p(e,["hash-object","--no-filters","--",r])}`}));return E([await B(e,["diff","--cached","--binary","--full-index"]),await B(e,["diff","--binary","--full-index"]),await B(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function dr(e){const t=W(e),o=await p(t,["rev-parse","HEAD"]),r=await p(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await O(t);if(await p(t,["rev-parse","HEAD"])!==o||await p(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 ce(e){const t=[];let o;for(const r of(await B(e,["worktree","list","--porcelain","-z"])).split("\0"))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 Z(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&ht(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function n(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function Je(e,t){try{return await oe("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),0}catch(o){const r=o.code;return typeof r=="number"?r:-1}}async function p(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function B(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function A(e,t){try{return await oe("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{ir as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Rt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,Zt as acceptDirectYoloSetupCheckpoint,Ut as beginDirectYoloStoryCommit,dr as captureDirectYoloCheckoutEvidence,or as directYoloCommitIdempotencyKey,ar as directYoloWaveQaCoverage,It as directYoloWaveReceiptRef,Xt as finalizeDirectYoloStoryCheckpoint,Qt as issueDirectYoloSetupLeaseHandoff,sr as persistDirectYoloWaveStoryCheckpoint,Jt as prepareDirectYoloSetup,cr as pushDirectYoloWaveHead,er as recoverLegacyDirectYoloStoryCheckpoint,tr as resolveDirectYoloIntegrationAuthority,nr as runDirectYoloWaveP205,rr as validateDirectYoloWriteSet};
@@ -1,5 +1,6 @@
1
1
  import { type EpicAggregateQaReceipt, type EpicHeadReconciliationReceiptV1 } from '../../../shared/dist/yoloop/epic-terminal-git.js';
2
2
  import { type AnchoredDirectoryIdentity } from './secure-filesystem-boundary.js';
3
+ import { type ReleaseGateEnvContract } from './release-gate-env.js';
3
4
  export declare const GIT_LIFECYCLE_RUNTIME_DIRECTORY = "neocortex-yoloop";
4
5
  export declare const GIT_LIFECYCLE_RUNTIME_FILE = "runtime.json";
5
6
  export declare const P205_COMPLETE_COMMAND: "node scripts/test-root.mjs --gate complete";
@@ -157,6 +158,63 @@ export interface EpicHeadReconciliationAuthority {
157
158
  readonly __epicHeadReconciliationOpaqueAuthority: never;
158
159
  }
159
160
  export type EpicTerminalReleaseAuthority = P205TransientExecutionAuthority | EpicHeadReconciliationAuthority;
161
+ /** Canonical P205-CI-02 gate budgets, used when a manifest omits `budgets` (P226.02 D3). */
162
+ export declare const P205_DEFAULT_COMPLETE_GATE_WORST_CASE_MS = 2700000;
163
+ export declare const P205_DEFAULT_CANCELLATION_GRACE_MS = 300000;
164
+ export interface P205GateBudget {
165
+ readonly completeGateWorstCaseMs: number;
166
+ readonly cancellationGraceMs: number;
167
+ }
168
+ /**
169
+ * P226-CON-GATE-REASONS closed allowlist. Only these typed gate reasons may
170
+ * cross `publicReason` and the invoke snapshot projection verbatim.
171
+ */
172
+ export declare function isP226GateReasonCode(value: unknown): value is string;
173
+ /**
174
+ * Strict gate stderr parser (P226.02 D4). Only the last non-empty line of the
175
+ * bounded tail is inspected; anything else is `p205-gate-failed:unknown`. The
176
+ * input is never echoed, persisted or included in the result.
177
+ */
178
+ export declare function parseP205GateFailureReason(stderrTail: string | undefined): string;
179
+ /** Budget from the committed manifest; absent → canonical defaults, invalid → fail closed. */
180
+ export declare function readP205GateBudget(raw: unknown): P205GateBudget;
181
+ /**
182
+ * Bind the working `P205-CI-02-ENV` contract to its committed bytes. Absent in
183
+ * both → `null` (minimal environment + undeclared debt); present only in the
184
+ * checkout, or differing from the commit → `p205-transient-producer-dirty`;
185
+ * unreadable/unsafe/malformed → `p205-gate-env-contract-invalid`.
186
+ */
187
+ export declare function bindCommittedReleaseGateEnvContract(projectRoot: string, committedContractText: string | null): ReleaseGateEnvContract | null;
188
+ /**
189
+ * Environment handed to the P205 gate process (P226.02 AC1, P226-CON-GATE-ENV).
190
+ * The P226.01 `P205-CI-02-ENV` sibling contract must be byte-for-byte the
191
+ * committed one at `headSha` (like the manifest and runner); its projection is
192
+ * the fixed minimal environment plus the declared names present in the parent
193
+ * environment. A missing required name throws `p205-datasource-missing:<NAME>`
194
+ * and an invalid contract `p205-gate-env-contract-invalid`, both before any
195
+ * gate process starts. Both execution paths receive exactly the returned object.
196
+ */
197
+ export declare function projectP205GateEnvironment(projectRoot: string, committedContractText: string | null, parentEnv?: Readonly<Record<string, string | undefined>>, platform?: string): Readonly<Record<string, string>>;
198
+ /** Names never handed to the gate: the fixed list above plus every `GIT_*` variable. */
199
+ export declare function isP205GateEnvDenied(name: string, caseInsensitive?: boolean): boolean;
200
+ /** Injectable process primitives for the gate terminator (tests only swap these). */
201
+ export interface P205GateTerminatorDeps {
202
+ readonly platform: NodeJS.Platform;
203
+ readonly killProcess: (pid: number, signal: NodeJS.Signals) => void;
204
+ readonly spawnDetached: (command: string, args: readonly string[]) => {
205
+ once(event: 'error', listener: () => void): unknown;
206
+ unref(): void;
207
+ };
208
+ readonly systemRoot?: string;
209
+ }
210
+ /**
211
+ * Terminate the gate process tree for one timeout phase (P226.02 AC3, D-001).
212
+ * POSIX signals the whole process group (`-pid`). win32 has no process groups,
213
+ * so the first (`term`) phase already runs `taskkill /PID <pid> /T /F` while
214
+ * the root is still alive and the tree is still reachable; the `kill` phase is
215
+ * a direct-child fallback.
216
+ */
217
+ export declare function terminateP205GateTree(pid: number, phase: 'term' | 'kill', deps?: P205GateTerminatorDeps): void;
160
218
  export declare function executeP205TransientAuthority(projectRoot: string, input: {
161
219
  readonly headSha: string;
162
220
  readonly graphRevision: string;
@@ -327,8 +385,16 @@ export declare function consumeEpicTerminalReleaseAuthority(authority: EpicTermi
327
385
  readonly aggregateQaReceipt: EpicAggregateQaReceipt;
328
386
  readonly headReconciliationReceipt?: EpicHeadReconciliationReceiptV1 | null;
329
387
  }): boolean;
388
+ /**
389
+ * P226.05 (WS-05/F2): ordered claim candidates for a story write-set -- the
390
+ * authored set first, then (when valid and different) its expansion with the
391
+ * five control files. Every claim verifier tries them in this order.
392
+ */
393
+ export declare function gitLifecycleStoryClaimCandidates(storyId: string, authorizedWriteSet: readonly string[]): readonly (readonly string[])[];
330
394
  /** Reconstruct the same closed claim used by the direct or continuous planner. */
331
395
  export declare function gitLifecycleStoryWriteSet(storyId: string, story: Record<string, unknown> | undefined, checkpoint: Record<string, unknown> | undefined): readonly string[];
396
+ /** P226.05: the lifecycle store's coverage decision, exported for parity tests. */
397
+ export declare function gitLifecycleWriteSetCovers(scope: string, path: string): boolean;
332
398
  /** Pre-P205 admission for only the exact seven immutable P174 migrations. */
333
399
  export declare function verifyLegacyCheckpointMigrationCandidateSync(projectRoot: string, value: unknown, storyId: string, epicId: string, executionBranch: string, authorizedWriteSet: readonly string[]): boolean;
334
400
  export declare function computeImmutableStoryQaEvidenceDigest(input: {