@ornexus/neocortex 4.61.5 → 4.61.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1193 -1193
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/adapter-registry.js +1 -108
- package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
- package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
- package/packages/client/dist/adapters/codex-adapter.js +2 -80
- package/packages/client/dist/adapters/cursor-adapter.js +4 -115
- package/packages/client/dist/adapters/gemini-adapter.js +2 -71
- package/packages/client/dist/adapters/grok-adapter.js +2 -42
- package/packages/client/dist/adapters/index.js +1 -22
- package/packages/client/dist/adapters/platform-detector.js +1 -220
- package/packages/client/dist/adapters/target-adapter.js +0 -12
- package/packages/client/dist/adapters/vscode-adapter.js +2 -72
- package/packages/client/dist/agent/refresh-stubs.js +2 -443
- package/packages/client/dist/agent/update-agent-yaml.js +1 -102
- package/packages/client/dist/agent/update-description.js +1 -260
- package/packages/client/dist/cache/crypto-utils.js +1 -78
- package/packages/client/dist/cache/encrypted-cache.js +1 -338
- package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
- package/packages/client/dist/cache/index.js +1 -13
- package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
- package/packages/client/dist/checkpoint/index.js +1 -11
- package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
- package/packages/client/dist/cli.js +5 -364
- package/packages/client/dist/commands/activate.js +8 -394
- package/packages/client/dist/commands/architecture-answers.js +7 -274
- package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
- package/packages/client/dist/commands/architecture-root-binding.js +1 -51
- package/packages/client/dist/commands/cache-status.js +2 -112
- package/packages/client/dist/commands/config.js +1 -88
- package/packages/client/dist/commands/doctor.js +2 -635
- package/packages/client/dist/commands/invoke.js +148 -7822
- package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
- package/packages/client/dist/commands/legacy-story-branch.js +1 -96
- package/packages/client/dist/commands/legacy-story-pr.js +1 -276
- package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
- package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
- package/packages/client/dist/commands/mutation-qa-git.js +1 -41
- package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
- package/packages/client/dist/commands/mutation-qa-run.js +3 -219
- package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
- package/packages/client/dist/commands/mutation-qa.js +1 -220
- package/packages/client/dist/commands/native-agent.js +2 -136
- package/packages/client/dist/commands/planning-diagnosis.js +1 -43
- package/packages/client/dist/commands/planning-generation.js +1 -53
- package/packages/client/dist/commands/planning-memory.js +1 -40
- package/packages/client/dist/commands/planning-research.js +1 -42
- package/packages/client/dist/commands/private-session.js +1 -75
- package/packages/client/dist/commands/property-qa.js +1 -139
- package/packages/client/dist/commands/qa-control.js +1 -16
- package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
- package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
- package/packages/client/dist/commands/qa-scan-capture.js +5 -663
- package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
- package/packages/client/dist/commands/qa-scan-review.js +5 -826
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
- package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
- package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
- package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
- package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
- package/packages/client/dist/commands/refactor-characterization.js +21 -671
- package/packages/client/dist/commands/refactor-commit.js +13 -399
- package/packages/client/dist/commands/refactor-control.js +3 -142
- package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
- package/packages/client/dist/commands/refactor-review.js +5 -283
- package/packages/client/dist/commands/refactor-root.js +7 -588
- package/packages/client/dist/commands/refresh-memory.js +3 -174
- package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
- package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
- package/packages/client/dist/commands/story-checkpoint.js +1 -203
- package/packages/client/dist/commands/story-worktree.js +5 -258
- package/packages/client/dist/config/host-auth-broker.js +1 -60
- package/packages/client/dist/config/host-auth-reference.js +1 -93
- package/packages/client/dist/config/profile-directory.js +1 -13
- package/packages/client/dist/config/resolver-selection.js +1 -278
- package/packages/client/dist/config/secure-config.js +12 -281
- package/packages/client/dist/config.js +2 -224
- package/packages/client/dist/constants.js +1 -25
- package/packages/client/dist/context/context-collector.js +2 -222
- package/packages/client/dist/context/context-sanitizer.js +1 -145
- package/packages/client/dist/continuity/autonomous-governance.js +1 -285
- package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
- package/packages/client/dist/continuity/invoke-hooks.js +1 -129
- package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
- package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
- package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
- package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
- package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
- package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
- package/packages/client/dist/continuity/native-agent-store.js +1 -69
- package/packages/client/dist/continuity/native-agent-types.js +1 -105
- package/packages/client/dist/continuity/outbox.js +1 -117
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
- package/packages/client/dist/continuity/sqlite-store.js +81 -2612
- package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
- package/packages/client/dist/errors/error-messages.js +2 -258
- package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
- package/packages/client/dist/evidence/collector.js +1 -347
- package/packages/client/dist/evidence/index.js +1 -1
- package/packages/client/dist/evidence/types.js +0 -2
- package/packages/client/dist/fs/atomic-state-replace.js +1 -152
- package/packages/client/dist/generated/command-registry.generated.js +1 -4076
- package/packages/client/dist/generated/public-projections.generated.js +1 -149
- package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
- package/packages/client/dist/git/epic-operational-state.js +2 -672
- package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
- package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
- package/packages/client/dist/git/git-lifecycle-store.js +8 -2529
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
- package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
- package/packages/client/dist/git/legacy-story-pr.js +70 -3538
- package/packages/client/dist/git/neocortex-trailers.js +2 -53
- package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
- package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
- package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -603
- package/packages/client/dist/git/story-worktree-manager.js +3 -843
- package/packages/client/dist/git/story-worktree-paths.js +1 -150
- package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
- package/packages/client/dist/git/story-write-set-extension.js +1 -0
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
- package/packages/client/dist/i18n/first-run.js +2 -60
- package/packages/client/dist/index.js +1 -50
- package/packages/client/dist/invocation/invoke-input.js +1 -24
- package/packages/client/dist/license/host-auth-recovery.js +1 -401
- package/packages/client/dist/license/index.js +1 -5
- package/packages/client/dist/license/license-client.js +1 -337
- package/packages/client/dist/machine/fingerprint.js +2 -163
- package/packages/client/dist/machine/index.js +1 -5
- package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
- package/packages/client/dist/memory/project-memory-writer.js +41 -1117
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
- package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
- package/packages/client/dist/migrations/project-identity-capability.js +1 -50
- package/packages/client/dist/migrations/project-identity.js +7 -493
- package/packages/client/dist/migrations/state-json.js +4 -393
- package/packages/client/dist/policy/architecture-policy.js +2 -184
- package/packages/client/dist/policy/index.js +1 -7
- package/packages/client/dist/policy/shared-policy-types.js +0 -38
- package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
- package/packages/client/dist/private-execution/clean-baseline.js +2 -279
- package/packages/client/dist/private-execution/codex-executor.js +4 -574
- package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
- package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
- package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
- package/packages/client/dist/private-execution/delivery.js +13 -410
- package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
- package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
- package/packages/client/dist/private-execution/implementation-validation.js +2 -106
- package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
- package/packages/client/dist/private-execution/isolated-session.js +5 -725
- package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
- package/packages/client/dist/private-execution/pact-test-source.js +1 -258
- package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
- package/packages/client/dist/private-execution/pact-write-set.js +1 -172
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
- package/packages/client/dist/private-execution/private-report-store.js +1 -42
- package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
- package/packages/client/dist/private-execution/property-test-choices.js +3 -147
- package/packages/client/dist/private-execution/property-test-plan.js +7 -271
- package/packages/client/dist/private-execution/property-test-review.js +4 -258
- package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
- package/packages/client/dist/private-execution/property-test-source.js +1 -139
- package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
- package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
- package/packages/client/dist/private-execution/root-memory-request.js +1 -29
- package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
- package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
- package/packages/client/dist/private-execution/session-lease.js +1 -63
- package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
- package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
- package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
- package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
- package/packages/client/dist/private-execution/ux-write-set.js +2 -191
- package/packages/client/dist/registry/registry-reconciliation.js +1 -234
- package/packages/client/dist/resilience/circuit-breaker.js +1 -170
- package/packages/client/dist/resilience/degradation-manager.js +1 -164
- package/packages/client/dist/resilience/freshness-indicator.js +1 -100
- package/packages/client/dist/resilience/index.js +1 -8
- package/packages/client/dist/resilience/recovery-detector.js +1 -74
- package/packages/client/dist/resolvers/asset-resolver.js +0 -13
- package/packages/client/dist/resolvers/local-resolver.js +8 -255
- package/packages/client/dist/resolvers/remote-resolver.js +1 -233
- package/packages/client/dist/runner/binary.js +1 -404
- package/packages/client/dist/runner/cli.js +17 -1571
- package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
- package/packages/client/dist/runner/headless/adapters.js +1 -49
- package/packages/client/dist/runner/headless/background-root.js +1 -85
- package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
- package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
- package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
- package/packages/client/dist/runner/headless/managed-profile.js +1 -149
- package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
- package/packages/client/dist/runner/headless/resolver.js +1 -231
- package/packages/client/dist/runner/headless/run-yolo.js +1 -886
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
- package/packages/client/dist/runner/headless/types.js +2 -575
- package/packages/client/dist/runner/host-capacity.js +1 -59
- package/packages/client/dist/runner/local-console.js +13 -396
- package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
- package/packages/client/dist/runner/project-identity.js +1 -106
- package/packages/client/dist/runner/scheduler.js +7 -995
- package/packages/client/dist/runner-cli.js +2 -18
- package/packages/client/dist/state/invocation-shape.js +1 -13
- package/packages/client/dist/state/project-state-snapshot.js +1 -1754
- package/packages/client/dist/state/state-json-repair.js +3 -785
- package/packages/client/dist/state/structural-dag-projection.js +1 -118
- package/packages/client/dist/telemetry/index.js +1 -5
- package/packages/client/dist/telemetry/offline-queue.js +1 -131
- package/packages/client/dist/tier/index.js +1 -5
- package/packages/client/dist/tier/tier-aware-client.js +1 -405
- package/packages/client/dist/types/index.js +1 -38
- package/packages/client/dist/version.js +1 -27
- package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
- package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
- package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
- package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
- package/packages/client/dist/yoloop/discovery-hook.js +2 -300
- package/packages/client/dist/yoloop/index.js +1 -8
- package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
- package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
- package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
- package/packages/client/dist/yoloop/target-normalization.js +1 -180
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,1592 +1,4 @@
|
|
|
1
|
-
/** Root-owned two-phase commit/checkpoint boundary for direct `*yolo` runs. */
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import { readFile, realpath } from 'node:fs/promises';
|
|
6
|
-
import { join, resolve } from 'node:path';
|
|
7
|
-
import { promisify } from 'node:util';
|
|
8
|
-
import { readRootMemoryEffectForCheckpoint } from '../private-execution/root-memory-scope.js';
|
|
9
|
-
import { rootMemoryEffectDigest, verifyRootMemoryPhysicalWriteSet } from '../private-execution/root-memory-git-evidence.js';
|
|
10
|
-
import { acquireGitLifecyclePhysicalIntegrationLock, applyGitLifecycleRuntimeOverlay, computeImmutableStoryQaEvidenceDigest, computeGitLifecyclePhysicalIntegrationLockOwnerDigest, computeP205StoryQaEvidenceDigest, computeLegacyDirectYoloRecoveryReceiptRef, ensureRuntimeEpic, ensureRuntimeStory, ensureGitLifecyclePrivateChildDirectory, executeP205TransientAuthority, projectP205TransientExecutionEvidence, publicStoryReviewArtifactFromGit, LEGACY_DIRECT_YOLO_RECOVERY_COMMITS, mutateGitLifecycleRuntime, P205_COMPLETE_COMMAND, readGitLifecycleRuntime, gitLifecycleRuntimeDirectory, assertGitLifecyclePrivateFile, releaseGitLifecyclePhysicalIntegrationLock, releaseGitLifecyclePhysicalIntegrationLockForCheckpoint, verifyGitLifecyclePhysicalIntegrationLock, verifyAcceptedGitLifecycleStoryCheckpoint, } from './git-lifecycle-store.js';
|
|
11
|
-
import { anchoredAtomicWriteFile, anchoredRemoveFile } from './secure-filesystem-boundary.js';
|
|
12
|
-
import { parseNeocortexTrailers, trailerReasonKey, trailerValue } from './neocortex-trailers.js';
|
|
13
|
-
import { StoryWorktreeManager } from './story-worktree-manager.js';
|
|
14
|
-
import { GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID, GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID, } from './git-lifecycle-step-ids.js';
|
|
15
|
-
const execFileAsync = promisify(execFile);
|
|
16
|
-
// The canonical complete P205 gate can legitimately exceed the former
|
|
17
|
-
// 30-minute C08 window on constrained hosts. Keep one finite lease, aligned
|
|
18
|
-
// with setup authority, rather than retrying or renewing after QA.
|
|
19
|
-
const DIRECT_STORY_CHECKPOINT_LEASE_MS = 60 * 60 * 1000;
|
|
20
|
-
/**
|
|
21
|
-
* Productive P207 setup boundary. It owns only the current checkout and the
|
|
22
|
-
* epic branch; it never creates, removes or repositions a worktree. Existing
|
|
23
|
-
* staged and unstaged bytes must remain identical across the branch switch.
|
|
24
|
-
*/
|
|
25
|
-
export async function prepareDirectYoloSetup(options) {
|
|
26
|
-
let recoveryPhysical;
|
|
27
|
-
let recoveryPhysicalStarted = false;
|
|
28
|
-
try {
|
|
29
|
-
const authority = await resolveLogicalAuthority(options.projectRoot, options.storyId);
|
|
30
|
-
if (await isSecondaryWorktree(authority.projectRoot)) {
|
|
31
|
-
if (options.expiredSetupRecovery)
|
|
32
|
-
return failure('direct-yolo-expired-setup-recovery-invalid');
|
|
33
|
-
const bound = await bindStoryWorktreeSetup(authority);
|
|
34
|
-
return { ok: true, value: storyWorktreeSetupReceipt(authority, bound, false) };
|
|
35
|
-
}
|
|
36
|
-
const nowIso = normalizedTime(options.nowIso);
|
|
37
|
-
const nowMs = Date.parse(nowIso);
|
|
38
|
-
const currentBranch = await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
39
|
-
const currentHead = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
|
|
40
|
-
const runtimeBefore = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
41
|
-
const runtimeEpic = asRecord(runtimeBefore.epics[authority.epicId]);
|
|
42
|
-
const currentLease = asRecord(runtimeEpic?.branch_lease);
|
|
43
|
-
const expiredSetupRecovery = options.expiredSetupRecovery;
|
|
44
|
-
if (expiredSetupRecovery && !validExpiredSetupRecovery(expiredSetupRecovery, runtimeBefore.revision, currentLease, options.storyId, nowMs)) {
|
|
45
|
-
return failure('direct-yolo-expired-setup-recovery-invalid');
|
|
46
|
-
}
|
|
47
|
-
const liveLease = currentLease && Number.isFinite(Date.parse(String(currentLease.expiresAt)))
|
|
48
|
-
&& Date.parse(String(currentLease.expiresAt)) > nowMs;
|
|
49
|
-
if (liveLease && currentLease?.ownerStoryId !== options.storyId) {
|
|
50
|
-
return failure('direct-yolo-writer-active');
|
|
51
|
-
}
|
|
52
|
-
let originBinding = validOriginBinding(runtimeEpic?.origin_binding, authority.executionBranch, authority.originBranch);
|
|
53
|
-
if (currentBranch === authority.executionBranch) {
|
|
54
|
-
if (!originBinding)
|
|
55
|
-
return failure('direct-yolo-origin-binding-invalid');
|
|
56
|
-
}
|
|
57
|
-
else {
|
|
58
|
-
if (currentBranch !== authority.originBranch)
|
|
59
|
-
return failure('direct-yolo-current-branch-mismatch');
|
|
60
|
-
if (originBinding && originBinding.originHeadSha !== currentHead) {
|
|
61
|
-
if (!expiredSetupRecovery)
|
|
62
|
-
return failure('direct-yolo-origin-binding-conflict');
|
|
63
|
-
if (!(await gitExitOk(authority.projectRoot, [
|
|
64
|
-
'merge-base', '--is-ancestor', originBinding.originHeadSha, currentHead,
|
|
65
|
-
])))
|
|
66
|
-
return failure('direct-yolo-origin-binding-conflict');
|
|
67
|
-
const recoveryExecutionRef = `refs/heads/${authority.executionBranch}`;
|
|
68
|
-
if (!(await gitExitOk(authority.projectRoot, [
|
|
69
|
-
'show-ref', '--verify', '--quiet', recoveryExecutionRef,
|
|
70
|
-
])))
|
|
71
|
-
return failure('direct-yolo-execution-branch-missing');
|
|
72
|
-
const recoveryExecutionHead = await git(authority.projectRoot, ['rev-parse', recoveryExecutionRef]);
|
|
73
|
-
if (!(await gitExitOk(authority.projectRoot, [
|
|
74
|
-
'merge-base', '--is-ancestor', recoveryExecutionHead, currentHead,
|
|
75
|
-
])))
|
|
76
|
-
return failure('direct-yolo-execution-branch-diverged');
|
|
77
|
-
}
|
|
78
|
-
originBinding ??= {
|
|
79
|
-
schemaVersion: 1,
|
|
80
|
-
originBranch: authority.originBranch,
|
|
81
|
-
originHeadSha: currentHead,
|
|
82
|
-
executionBranch: authority.executionBranch,
|
|
83
|
-
capturedFromCurrentCheckout: true,
|
|
84
|
-
capturedAt: nowIso,
|
|
85
|
-
};
|
|
86
|
-
const occupiedElsewhere = (await worktreeBranches(authority.projectRoot)).some((item) => item.branch === authority.executionBranch && resolve(item.path) !== authority.projectRoot);
|
|
87
|
-
if (occupiedElsewhere)
|
|
88
|
-
return failure('direct-yolo-execution-branch-checked-out-elsewhere');
|
|
89
|
-
const checkoutBefore = await checkoutPayload(authority.projectRoot);
|
|
90
|
-
const executionRef = `refs/heads/${authority.executionBranch}`;
|
|
91
|
-
if (await gitExitOk(authority.projectRoot, ['show-ref', '--verify', '--quiet', executionRef])) {
|
|
92
|
-
const executionHead = await git(authority.projectRoot, ['rev-parse', executionRef]);
|
|
93
|
-
if (executionHead !== currentHead) {
|
|
94
|
-
if (!(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', executionHead, currentHead]))) {
|
|
95
|
-
return failure('direct-yolo-execution-branch-diverged');
|
|
96
|
-
}
|
|
97
|
-
if (!expiredSetupRecovery) {
|
|
98
|
-
await git(authority.projectRoot, ['update-ref', executionRef, currentHead, executionHead]);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
if (expiredSetupRecovery) {
|
|
102
|
-
recoveryPhysical = {
|
|
103
|
-
checkoutBefore, executionRef, executionBranch: authority.executionBranch,
|
|
104
|
-
executionHead, originBranch: authority.originBranch, originHead: currentHead,
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
else {
|
|
108
|
-
await git(authority.projectRoot, ['switch', authority.executionBranch]);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
else if (expiredSetupRecovery) {
|
|
112
|
-
return failure('direct-yolo-execution-branch-missing');
|
|
113
|
-
}
|
|
114
|
-
else {
|
|
115
|
-
await git(authority.projectRoot, ['switch', '-c', authority.executionBranch]);
|
|
116
|
-
}
|
|
117
|
-
if (!recoveryPhysical && await checkoutPayload(authority.projectRoot) !== checkoutBefore) {
|
|
118
|
-
return failure('direct-yolo-checkout-payload-raced');
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
const headAfter = recoveryPhysical?.originHead ?? await git(authority.projectRoot, ['rev-parse', 'HEAD']);
|
|
122
|
-
if (!recoveryPhysical) {
|
|
123
|
-
const branchAfter = await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
124
|
-
if (branchAfter !== authority.executionBranch)
|
|
125
|
-
return failure('direct-yolo-current-branch-mismatch');
|
|
126
|
-
}
|
|
127
|
-
if (liveLease && currentLease?.ownerStoryId === options.storyId) {
|
|
128
|
-
if (currentLease.setupHeadSha !== headAfter)
|
|
129
|
-
return failure('direct-yolo-setup-lease-head-unbound');
|
|
130
|
-
return { ok: true, value: setupReceipt(authority, originBinding, String(currentLease.expiresAt), true) };
|
|
131
|
-
}
|
|
132
|
-
const acquiredAt = nowIso;
|
|
133
|
-
const expiresAt = new Date(nowMs + 60 * 60 * 1000).toISOString();
|
|
134
|
-
const sessionId = `setup-${randomBytes(32).toString('hex')}`;
|
|
135
|
-
const runtimeAtCas = expiredSetupRecovery
|
|
136
|
-
? runtimeBefore
|
|
137
|
-
: await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
138
|
-
await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
|
|
139
|
-
const epic = ensureRuntimeEpic(document, authority.epicId);
|
|
140
|
-
const lease = asRecord(epic.branch_lease);
|
|
141
|
-
if (expiredSetupRecovery
|
|
142
|
-
&& JSON.stringify(lease) !== JSON.stringify(expiredSetupRecovery.expectedLease)) {
|
|
143
|
-
throw new Error('direct-yolo-expired-setup-recovery-raced');
|
|
144
|
-
}
|
|
145
|
-
if (lease && Date.parse(String(lease.expiresAt)) > nowMs && lease.ownerStoryId !== options.storyId) {
|
|
146
|
-
throw new Error('direct-yolo-writer-active');
|
|
147
|
-
}
|
|
148
|
-
const persistedBinding = validOriginBinding(epic.origin_binding, authority.executionBranch, authority.originBranch);
|
|
149
|
-
if (epic.origin_binding && !persistedBinding)
|
|
150
|
-
throw new Error('direct-yolo-origin-binding-conflict');
|
|
151
|
-
if (persistedBinding && JSON.stringify(persistedBinding) !== JSON.stringify(originBinding)) {
|
|
152
|
-
throw new Error('direct-yolo-origin-binding-conflict');
|
|
153
|
-
}
|
|
154
|
-
epic.branch_mode = 'epic';
|
|
155
|
-
epic.execution_branch = authority.executionBranch;
|
|
156
|
-
epic.origin_branch = authority.originBranch;
|
|
157
|
-
epic.graph_revision = authority.graphRevision;
|
|
158
|
-
epic.origin_binding = originBinding;
|
|
159
|
-
epic.branch_lease = {
|
|
160
|
-
schemaVersion: 1, ownerStoryId: options.storyId, sessionId, idempotencyKey: sessionId,
|
|
161
|
-
acquiredAt, expiresAt, setupHeadSha: headAfter,
|
|
162
|
-
};
|
|
163
|
-
}, {
|
|
164
|
-
expectedRevision: expiredSetupRecovery?.expectedRuntimeRevision ?? runtimeAtCas.revision,
|
|
165
|
-
preCommit: async () => {
|
|
166
|
-
if (recoveryPhysical) {
|
|
167
|
-
const occupiedAtCas = (await worktreeBranches(authority.projectRoot)).some((item) => item.branch === authority.executionBranch && resolve(item.path) !== authority.projectRoot);
|
|
168
|
-
if (occupiedAtCas
|
|
169
|
-
|| await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== authority.originBranch
|
|
170
|
-
|| await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== recoveryPhysical.originHead
|
|
171
|
-
|| await checkoutPayload(authority.projectRoot) !== recoveryPhysical.checkoutBefore
|
|
172
|
-
|| !(await gitExitOk(authority.projectRoot, ['show-ref', '--verify', '--quiet', recoveryPhysical.executionRef]))
|
|
173
|
-
|| await git(authority.projectRoot, ['rev-parse', recoveryPhysical.executionRef]) !== recoveryPhysical.executionHead) {
|
|
174
|
-
throw new Error('direct-yolo-expired-setup-recovery-raced');
|
|
175
|
-
}
|
|
176
|
-
recoveryPhysicalStarted = true;
|
|
177
|
-
if (recoveryPhysical.executionHead !== recoveryPhysical.originHead) {
|
|
178
|
-
await git(authority.projectRoot, [
|
|
179
|
-
'update-ref', recoveryPhysical.executionRef,
|
|
180
|
-
recoveryPhysical.originHead, recoveryPhysical.executionHead,
|
|
181
|
-
]);
|
|
182
|
-
}
|
|
183
|
-
await git(authority.projectRoot, ['switch', authority.executionBranch]);
|
|
184
|
-
if (await checkoutPayload(authority.projectRoot) !== recoveryPhysical.checkoutBefore) {
|
|
185
|
-
throw new Error('direct-yolo-checkout-payload-raced');
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
if (await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== authority.executionBranch
|
|
189
|
-
|| await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== headAfter) {
|
|
190
|
-
throw new Error('direct-yolo-setup-physical-state-raced');
|
|
191
|
-
}
|
|
192
|
-
},
|
|
193
|
-
});
|
|
194
|
-
return { ok: true, value: setupReceipt(authority, originBinding, expiresAt, false) };
|
|
195
|
-
}
|
|
196
|
-
catch (error) {
|
|
197
|
-
if (recoveryPhysicalStarted && recoveryPhysical) {
|
|
198
|
-
await rollbackExpiredSetupRecoveryPhysical(resolve(options.projectRoot), recoveryPhysical).catch(() => undefined);
|
|
199
|
-
}
|
|
200
|
-
return failure(publicReason(error, 'direct-yolo-setup-failed'));
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
/** Accept C01 only from the root after its own physical setup and live lease. */
|
|
204
|
-
export async function acceptDirectYoloSetupCheckpoint(options) {
|
|
205
|
-
let physicalLock;
|
|
206
|
-
try {
|
|
207
|
-
const logical = await resolveLogicalAuthority(options.projectRoot, options.storyId);
|
|
208
|
-
if (await isSecondaryWorktree(logical.projectRoot))
|
|
209
|
-
return await acceptStoryWorktreeSetup(logical);
|
|
210
|
-
const authority = await resolveAuthority(options.projectRoot, options.storyId);
|
|
211
|
-
const nowIso = normalizedTime(options.nowIso);
|
|
212
|
-
const statePath = join(authority.projectRoot, '.neocortex/state.json');
|
|
213
|
-
const trackedBefore = await readFile(statePath, 'utf8');
|
|
214
|
-
const payloadBefore = await checkoutPayload(authority.projectRoot);
|
|
215
|
-
const headSha = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
|
|
216
|
-
const executionRef = `refs/heads/${authority.executionBranch}`;
|
|
217
|
-
const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
218
|
-
const epic = asRecord(runtime.epics[authority.epicId]);
|
|
219
|
-
const binding = validOriginBinding(epic?.origin_binding, authority.executionBranch, authority.originBranch);
|
|
220
|
-
const lease = asRecord(epic?.branch_lease);
|
|
221
|
-
if (!binding)
|
|
222
|
-
return failure('direct-yolo-origin-binding-invalid');
|
|
223
|
-
if (!lease || !isLiveSameStorySetupLease(lease, options.storyId, nowIso)
|
|
224
|
-
|| lease?.sessionId !== lease?.idempotencyKey)
|
|
225
|
-
return failure('direct-yolo-setup-lease-invalid');
|
|
226
|
-
const acquired = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
|
|
227
|
-
kind: 'direct', storyId: options.storyId,
|
|
228
|
-
sessionId: String(lease.sessionId), idempotencyKey: String(lease.idempotencyKey),
|
|
229
|
-
expiresAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(), persistent: false,
|
|
230
|
-
});
|
|
231
|
-
if (!acquired.ok)
|
|
232
|
-
return failure(acquired.reasonCode);
|
|
233
|
-
physicalLock = acquired;
|
|
234
|
-
if (headSha !== lease.setupHeadSha
|
|
235
|
-
|| !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', binding.originHeadSha, headSha]))
|
|
236
|
-
|| await git(authority.projectRoot, ['rev-parse', executionRef]) !== headSha) {
|
|
237
|
-
return failure('direct-yolo-setup-head-mismatch');
|
|
238
|
-
}
|
|
239
|
-
const occupiedElsewhere = (await worktreeBranches(authority.projectRoot)).some((item) => item.branch === authority.executionBranch && resolve(item.path) !== authority.projectRoot);
|
|
240
|
-
if (occupiedElsewhere)
|
|
241
|
-
return failure('direct-yolo-execution-branch-checked-out-elsewhere');
|
|
242
|
-
const tracked = asRecord(JSON.parse(trackedBefore));
|
|
243
|
-
const trackedStory = asRecord(asRecord(tracked?.stories)?.[options.storyId]);
|
|
244
|
-
const runtimeStory = asRecord(runtime.stories[options.storyId]);
|
|
245
|
-
if (!trackedStory || !['backlog', 'ready_to_start'].includes(String(trackedStory.status))
|
|
246
|
-
|| (trackedStory.steps_completed !== undefined
|
|
247
|
-
&& (!Array.isArray(trackedStory.steps_completed) || trackedStory.steps_completed.length > 0))
|
|
248
|
-
|| trackedStory.branch_name || trackedStory.checkpoint) {
|
|
249
|
-
return failure('direct-yolo-setup-story-progress-conflict');
|
|
250
|
-
}
|
|
251
|
-
const accepted = runtimeStory?.status === 'branch-ready'
|
|
252
|
-
&& runtimeStory.last_step === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
|
|
253
|
-
&& Array.isArray(runtimeStory.steps_completed)
|
|
254
|
-
&& runtimeStory.steps_completed.length === 1
|
|
255
|
-
&& runtimeStory.steps_completed[0] === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
|
|
256
|
-
&& Object.keys(runtimeStory).sort().join(',') === 'last_step,status,steps_completed';
|
|
257
|
-
if (runtimeStory && Object.keys(runtimeStory).length > 0 && !accepted) {
|
|
258
|
-
return failure('direct-yolo-setup-story-progress-conflict');
|
|
259
|
-
}
|
|
260
|
-
const physicalGuard = async () => {
|
|
261
|
-
if (Date.parse(String(lease.expiresAt)) <= (options.nowIso ? Date.parse(nowIso) : Date.now())
|
|
262
|
-
|| !physicalLock || !(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))
|
|
263
|
-
|| await readFile(statePath, 'utf8') !== trackedBefore
|
|
264
|
-
|| await checkoutPayload(authority.projectRoot) !== payloadBefore
|
|
265
|
-
|| await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== authority.executionBranch
|
|
266
|
-
|| await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== headSha
|
|
267
|
-
|| !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', binding.originHeadSha, headSha]))
|
|
268
|
-
|| await git(authority.projectRoot, ['rev-parse', executionRef]) !== headSha) {
|
|
269
|
-
throw new Error('direct-yolo-setup-physical-state-raced');
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
if (accepted) {
|
|
273
|
-
await physicalGuard();
|
|
274
|
-
}
|
|
275
|
-
else {
|
|
276
|
-
await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
|
|
277
|
-
const currentEpic = asRecord(document.epics[authority.epicId]);
|
|
278
|
-
const currentStory = ensureRuntimeStory(document, options.storyId);
|
|
279
|
-
if (JSON.stringify(currentEpic?.branch_lease) !== JSON.stringify(lease)
|
|
280
|
-
|| JSON.stringify(currentEpic?.origin_binding) !== JSON.stringify(binding)
|
|
281
|
-
|| currentEpic?.graph_revision !== authority.graphRevision
|
|
282
|
-
|| Object.keys(currentStory).length > 0) {
|
|
283
|
-
throw new Error('direct-yolo-setup-runtime-raced');
|
|
284
|
-
}
|
|
285
|
-
currentStory.status = 'branch-ready';
|
|
286
|
-
currentStory.last_step = GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID;
|
|
287
|
-
currentStory.steps_completed = [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID];
|
|
288
|
-
}, { expectedRevision: runtime.revision, preCommit: physicalGuard });
|
|
289
|
-
}
|
|
290
|
-
return { ok: true, value: Object.freeze({
|
|
291
|
-
...setupReceipt(authority, binding, String(lease.expiresAt), accepted),
|
|
292
|
-
checkpointAccepted: true, graphRevision: authority.graphRevision, headSha,
|
|
293
|
-
}) };
|
|
294
|
-
}
|
|
295
|
-
catch (error) {
|
|
296
|
-
return failure(publicReason(error, 'direct-yolo-setup-acceptance-failed'));
|
|
297
|
-
}
|
|
298
|
-
finally {
|
|
299
|
-
if (physicalLock) {
|
|
300
|
-
await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
/**
|
|
305
|
-
* Productive setup-owner handoff emitter used immediately before C08. The
|
|
306
|
-
* one-time token never crosses stdout; only a public receipt is returned.
|
|
307
|
-
*/
|
|
308
|
-
export async function issueDirectYoloSetupLeaseHandoff(options) {
|
|
309
|
-
try {
|
|
310
|
-
const authority = await resolveAuthority(options.projectRoot, options.storyId);
|
|
311
|
-
const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--cached', '--name-only', '-z']));
|
|
312
|
-
const writeSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
|
|
313
|
-
if (!writeSet.ok)
|
|
314
|
-
return failure(writeSet.reasonCode);
|
|
315
|
-
if (authority.rootMemoryEffect)
|
|
316
|
-
verifyRootMemoryPhysicalWriteSet(authority.projectRoot, authority.rootMemoryEffect, { storyId: options.storyId, executionBranch: authority.executionBranch,
|
|
317
|
-
baseSha: await git(authority.projectRoot, ['rev-parse', 'HEAD']), headRef: ':', childPaths: authority.authorizedWriteSet });
|
|
318
|
-
const stagedReview = publicStoryReviewArtifactFromGit(authority.projectRoot, options.storyId, ':');
|
|
319
|
-
if (stagedReview?.verdict !== 'approved')
|
|
320
|
-
return failure('direct-yolo-review-artifact-not-approved');
|
|
321
|
-
const unstagedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--name-only', '-z']));
|
|
322
|
-
if (unstagedPaths.some((path) => changedPaths.includes(path)))
|
|
323
|
-
return failure('direct-yolo-user-overlap');
|
|
324
|
-
const payload = await gitRaw(authority.projectRoot, ['diff', '--cached', '--binary', '--full-index']);
|
|
325
|
-
if (!payload)
|
|
326
|
-
return failure('direct-yolo-staged-diff-empty');
|
|
327
|
-
const bundleDigest = digest(payload);
|
|
328
|
-
const claimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
|
|
329
|
-
const nowIso = normalizedTime(options.nowIso);
|
|
330
|
-
const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
331
|
-
const setupLease = asRecord(runtime.epics[authority.epicId]?.branch_lease);
|
|
332
|
-
if (!isLiveSameStorySetupLease(setupLease, options.storyId, nowIso)) {
|
|
333
|
-
return failure('direct-yolo-setup-handoff-owner-invalid');
|
|
334
|
-
}
|
|
335
|
-
const sessionId = String(setupLease.sessionId);
|
|
336
|
-
const leaseExpiresAt = String(setupLease.expiresAt);
|
|
337
|
-
const candidateExpiresAt = new Date(Math.min(Date.parse(leaseExpiresAt), Date.parse(nowIso) + 5 * 60 * 1000)).toISOString();
|
|
338
|
-
const prior = await readSetupHandoffTokenRecord(authority.projectRoot, options.storyId);
|
|
339
|
-
const reused = Boolean(prior?.state === 'issued'
|
|
340
|
-
&& prior.fromSessionId === sessionId && prior.bundleDigest === bundleDigest
|
|
341
|
-
&& prior.claimRevision === claimRevision
|
|
342
|
-
&& Date.parse(prior.expiresAt) > Date.parse(nowIso));
|
|
343
|
-
const expiresAt = reused ? prior.expiresAt : candidateExpiresAt;
|
|
344
|
-
const token = reused ? prior.token : randomBytes(32).toString('base64url');
|
|
345
|
-
const tokenDigest = digest(token);
|
|
346
|
-
const grant = Object.freeze({
|
|
347
|
-
schemaVersion: 1,
|
|
348
|
-
kind: 'direct-yolo-setup-handoff',
|
|
349
|
-
storyId: options.storyId,
|
|
350
|
-
fromSessionId: sessionId,
|
|
351
|
-
tokenDigest,
|
|
352
|
-
bundleDigest,
|
|
353
|
-
claimRevision,
|
|
354
|
-
expiresAt,
|
|
355
|
-
});
|
|
356
|
-
const grantDigest = digest(JSON.stringify(grant));
|
|
357
|
-
const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
|
|
358
|
-
kind: 'direct', storyId: options.storyId, sessionId, idempotencyKey: sessionId,
|
|
359
|
-
expiresAt, persistent: false, createdAt: nowIso,
|
|
360
|
-
});
|
|
361
|
-
if (!physicalLock.ok)
|
|
362
|
-
return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
|
|
363
|
-
? 'direct-yolo-integration-backpressure' : 'direct-yolo-integration-lock-failed');
|
|
364
|
-
try {
|
|
365
|
-
await writeSetupHandoffTokenRecord(authority.projectRoot, {
|
|
366
|
-
schemaVersion: 1, kind: 'direct-yolo-setup-handoff-token', state: 'issued',
|
|
367
|
-
storyId: options.storyId, fromSessionId: sessionId, token, tokenDigest,
|
|
368
|
-
bundleDigest, claimRevision, grantDigest, expiresAt,
|
|
369
|
-
});
|
|
370
|
-
await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
|
|
371
|
-
const current = asRecord(ensureRuntimeEpic(document, authority.epicId).branch_lease);
|
|
372
|
-
if (!isLiveSameStorySetupLease(current, options.storyId, nowIso)
|
|
373
|
-
|| current?.sessionId !== sessionId || current.idempotencyKey !== sessionId) {
|
|
374
|
-
throw new Error('direct-yolo-setup-handoff-owner-raced');
|
|
375
|
-
}
|
|
376
|
-
current.handoffGrant = grant;
|
|
377
|
-
}, {
|
|
378
|
-
expectedRevision: runtime.revision,
|
|
379
|
-
preCommit: async () => {
|
|
380
|
-
if (!(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))) {
|
|
381
|
-
throw new Error('direct-yolo-integration-lock-raced');
|
|
382
|
-
}
|
|
383
|
-
const persisted = await readSetupHandoffTokenRecord(authority.projectRoot, options.storyId);
|
|
384
|
-
if (!persisted || persisted.state !== 'issued' || persisted.grantDigest !== grantDigest
|
|
385
|
-
|| persisted.tokenDigest !== tokenDigest)
|
|
386
|
-
throw new Error('direct-yolo-setup-handoff-token-raced');
|
|
387
|
-
},
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
finally {
|
|
391
|
-
await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
|
|
392
|
-
}
|
|
393
|
-
return { ok: true, value: Object.freeze({
|
|
394
|
-
schemaVersion: 1, kind: 'direct-yolo-setup-handoff-receipt', storyId: options.storyId,
|
|
395
|
-
sessionId, bundleDigest, claimRevision, grantDigest, expiresAt, reused, publicSafe: true,
|
|
396
|
-
}) };
|
|
397
|
-
}
|
|
398
|
-
catch (error) {
|
|
399
|
-
return failure(error instanceof Error && /^direct-yolo-/.test(error.message)
|
|
400
|
-
? error.message : 'direct-yolo-setup-handoff-failed');
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
export async function beginDirectYoloStoryCommit(options) {
|
|
404
|
-
try {
|
|
405
|
-
const authority = await resolveAuthority(options.projectRoot, options.storyId);
|
|
406
|
-
const baseSha = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
|
|
407
|
-
const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--cached', '--name-only', '-z']));
|
|
408
|
-
const writeSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
|
|
409
|
-
if (!writeSet.ok)
|
|
410
|
-
return failure(writeSet.reasonCode);
|
|
411
|
-
if (authority.rootMemoryEffect)
|
|
412
|
-
verifyRootMemoryPhysicalWriteSet(authority.projectRoot, authority.rootMemoryEffect, { storyId: options.storyId, executionBranch: authority.executionBranch, baseSha, headRef: ':', childPaths: authority.authorizedWriteSet });
|
|
413
|
-
const stagedReview = publicStoryReviewArtifactFromGit(authority.projectRoot, options.storyId, ':');
|
|
414
|
-
if (stagedReview?.verdict !== 'approved')
|
|
415
|
-
return failure('direct-yolo-review-artifact-not-approved');
|
|
416
|
-
const unstagedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--name-only', '-z']));
|
|
417
|
-
if (unstagedPaths.some((path) => changedPaths.includes(path)))
|
|
418
|
-
return failure('direct-yolo-user-overlap');
|
|
419
|
-
const payload = await gitRaw(authority.projectRoot, ['diff', '--cached', '--binary', '--full-index']);
|
|
420
|
-
if (!payload)
|
|
421
|
-
return failure('direct-yolo-staged-diff-empty');
|
|
422
|
-
const bundleDigest = digest(payload);
|
|
423
|
-
const claimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
|
|
424
|
-
// A begin replay for the exact same staged content keeps the graph epoch it
|
|
425
|
-
// was first issued under; the epic epoch may advance while no lease is held.
|
|
426
|
-
const priorPlan = await readDirectCommitPlan(authority.projectRoot, options.storyId);
|
|
427
|
-
const replayedPlan = priorPlan.state === 'valid'
|
|
428
|
-
&& priorPlan.plan.epicId === authority.epicId
|
|
429
|
-
&& priorPlan.plan.executionBranch === authority.executionBranch
|
|
430
|
-
&& priorPlan.plan.preparedBase === baseSha
|
|
431
|
-
&& priorPlan.plan.bundleDigest === bundleDigest
|
|
432
|
-
&& priorPlan.plan.claimRevision === claimRevision
|
|
433
|
-
? priorPlan.plan : undefined;
|
|
434
|
-
const boundGraphRevision = replayedPlan?.graphRevision ?? authority.graphRevision;
|
|
435
|
-
const idempotencyKey = directCommitIdempotencyKey({
|
|
436
|
-
storyId: options.storyId, epicId: authority.epicId, executionBranch: authority.executionBranch,
|
|
437
|
-
baseSha, bundleDigest, graphRevision: boundGraphRevision, claimRevision,
|
|
438
|
-
});
|
|
439
|
-
const nowIso = normalizedTime(options.nowIso);
|
|
440
|
-
const commitPlan = {
|
|
441
|
-
schemaVersion: 1, kind: 'direct-yolo-commit-plan', storyId: options.storyId,
|
|
442
|
-
epicId: authority.epicId, executionBranch: authority.executionBranch,
|
|
443
|
-
graphRevision: boundGraphRevision, preparedBase: baseSha, bundleDigest, claimRevision,
|
|
444
|
-
idempotencyKey, issuedAt: replayedPlan?.issuedAt ?? nowIso,
|
|
445
|
-
};
|
|
446
|
-
let issuedHandoff = options.setupLeaseHandoff
|
|
447
|
-
?? await resolveIssuedSetupLeaseHandoff(authority.projectRoot, options.storyId, bundleDigest, claimRevision, nowIso);
|
|
448
|
-
const runtimeBeforeLock = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
449
|
-
const priorDirectLease = asRecord(runtimeBeforeLock.epics[authority.epicId]?.branch_lease);
|
|
450
|
-
const reusableDirectLease = priorDirectLease?.ownerStoryId === options.storyId
|
|
451
|
-
&& priorDirectLease.sessionId === idempotencyKey && priorDirectLease.idempotencyKey === idempotencyKey
|
|
452
|
-
&& typeof priorDirectLease.expiresAt === 'string'
|
|
453
|
-
&& Date.parse(priorDirectLease.expiresAt) > Date.parse(nowIso)
|
|
454
|
-
? priorDirectLease : undefined;
|
|
455
|
-
if (reusableDirectLease && options.setupLeaseHandoff) {
|
|
456
|
-
return failure('direct-yolo-setup-handoff-replayed');
|
|
457
|
-
}
|
|
458
|
-
const priorConsumption = asRecord(reusableDirectLease?.handoffConsumption);
|
|
459
|
-
if (priorConsumption) {
|
|
460
|
-
const privateRecord = await readSetupHandoffTokenRecord(authority.projectRoot, options.storyId);
|
|
461
|
-
if (!privateRecord || !['consuming', 'consumed'].includes(privateRecord.state)
|
|
462
|
-
|| privateRecord.fromSessionId !== priorConsumption.fromSessionId
|
|
463
|
-
|| privateRecord.tokenDigest !== priorConsumption.tokenDigest
|
|
464
|
-
|| privateRecord.bundleDigest !== bundleDigest || privateRecord.claimRevision !== claimRevision
|
|
465
|
-
|| priorConsumption.bundleDigest !== bundleDigest || priorConsumption.claimRevision !== claimRevision
|
|
466
|
-
|| privateRecord.consumedBySessionId !== idempotencyKey
|
|
467
|
-
|| priorConsumption.consumedBySessionId !== idempotencyKey) {
|
|
468
|
-
return failure('direct-yolo-setup-handoff-consume-invalid');
|
|
469
|
-
}
|
|
470
|
-
// The runtime CAS already consumed this exact grant. Recovery may finish
|
|
471
|
-
// its private receipt after expiry; it never promotes a second writer.
|
|
472
|
-
if (privateRecord.state === 'consuming') {
|
|
473
|
-
if (!privateRecord.token || digest(privateRecord.token) !== privateRecord.tokenDigest) {
|
|
474
|
-
return failure('direct-yolo-setup-handoff-consume-invalid');
|
|
475
|
-
}
|
|
476
|
-
issuedHandoff = { sessionId: privateRecord.fromSessionId, token: privateRecord.token };
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
const expiresAt = reusableDirectLease
|
|
480
|
-
? String(reusableDirectLease.expiresAt)
|
|
481
|
-
: new Date(Date.parse(nowIso) + DIRECT_STORY_CHECKPOINT_LEASE_MS).toISOString();
|
|
482
|
-
const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
|
|
483
|
-
kind: 'direct', storyId: options.storyId, sessionId: idempotencyKey, idempotencyKey,
|
|
484
|
-
expiresAt, persistent: true,
|
|
485
|
-
createdAt: reusableDirectLease && typeof reusableDirectLease.acquiredAt === 'string'
|
|
486
|
-
? reusableDirectLease.acquiredAt : nowIso,
|
|
487
|
-
});
|
|
488
|
-
if (!physicalLock.ok)
|
|
489
|
-
return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
|
|
490
|
-
? 'direct-yolo-integration-backpressure' : 'direct-yolo-integration-lock-failed');
|
|
491
|
-
try {
|
|
492
|
-
if (issuedHandoff && options.setupLeaseHandoff === undefined) {
|
|
493
|
-
await markSetupHandoffTokenConsuming(authority.projectRoot, options.storyId, issuedHandoff.sessionId, issuedHandoff.token, idempotencyKey, nowIso);
|
|
494
|
-
await options.setupHandoffFault?.('after-consuming-persisted');
|
|
495
|
-
}
|
|
496
|
-
await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
|
|
497
|
-
const epic = ensureRuntimeEpic(document, authority.epicId);
|
|
498
|
-
const current = asRecord(epic.branch_lease);
|
|
499
|
-
const live = current && Date.parse(String(current.expiresAt)) > Date.parse(nowIso);
|
|
500
|
-
const alreadyPromoted = current?.ownerStoryId === options.storyId
|
|
501
|
-
&& current.sessionId === idempotencyKey && current.idempotencyKey === idempotencyKey;
|
|
502
|
-
const sameStorySetup = current?.ownerStoryId === options.storyId
|
|
503
|
-
&& current.sessionId === current.idempotencyKey
|
|
504
|
-
&& typeof current.idempotencyKey === 'string'
|
|
505
|
-
&& /^setup-[a-f0-9]{64}$/.test(current.idempotencyKey);
|
|
506
|
-
const setupHandoffAuthorized = live && sameStorySetup && validSetupLeaseHandoff({
|
|
507
|
-
current,
|
|
508
|
-
handoff: issuedHandoff,
|
|
509
|
-
storyId: options.storyId,
|
|
510
|
-
bundleDigest,
|
|
511
|
-
claimRevision,
|
|
512
|
-
nowIso,
|
|
513
|
-
});
|
|
514
|
-
if (issuedHandoff && live && !alreadyPromoted && !setupHandoffAuthorized) {
|
|
515
|
-
throw new Error('direct-yolo-setup-handoff-invalid');
|
|
516
|
-
}
|
|
517
|
-
if (live && !alreadyPromoted && !setupHandoffAuthorized) {
|
|
518
|
-
throw new Error('direct-yolo-writer-active');
|
|
519
|
-
}
|
|
520
|
-
const setupGrant = setupHandoffAuthorized ? asRecord(current?.handoffGrant) : undefined;
|
|
521
|
-
const handoffConsumption = setupGrant ? {
|
|
522
|
-
schemaVersion: 1,
|
|
523
|
-
kind: 'direct-yolo-setup-handoff-consumption',
|
|
524
|
-
state: 'consumed',
|
|
525
|
-
storyId: options.storyId,
|
|
526
|
-
fromSessionId: String(current?.sessionId),
|
|
527
|
-
tokenDigest: String(setupGrant.tokenDigest),
|
|
528
|
-
bundleDigest,
|
|
529
|
-
claimRevision,
|
|
530
|
-
consumedBySessionId: idempotencyKey,
|
|
531
|
-
consumedAt: nowIso,
|
|
532
|
-
} : undefined;
|
|
533
|
-
epic.branch_mode = 'epic';
|
|
534
|
-
epic.execution_branch = authority.executionBranch;
|
|
535
|
-
epic.origin_branch = authority.originBranch;
|
|
536
|
-
epic.graph_revision = authority.graphRevision;
|
|
537
|
-
epic.branch_lease = live && alreadyPromoted ? current : {
|
|
538
|
-
schemaVersion: 1, ownerStoryId: options.storyId, sessionId: idempotencyKey,
|
|
539
|
-
idempotencyKey, acquiredAt: nowIso, expiresAt,
|
|
540
|
-
...(handoffConsumption ? { handoffConsumption } : {}),
|
|
541
|
-
};
|
|
542
|
-
}, {
|
|
543
|
-
expectedRevision: runtimeBeforeLock.revision,
|
|
544
|
-
preCommit: async () => {
|
|
545
|
-
if (!(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))) {
|
|
546
|
-
throw new Error('direct-yolo-integration-lock-raced');
|
|
547
|
-
}
|
|
548
|
-
// Durable under the runtime lock and independent of the lease: a
|
|
549
|
-
// failed/expired finalize releases the lease, never the plan epoch.
|
|
550
|
-
await writeDirectCommitPlan(authority.projectRoot, commitPlan);
|
|
551
|
-
},
|
|
552
|
-
});
|
|
553
|
-
}
|
|
554
|
-
catch (error) {
|
|
555
|
-
await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
|
|
556
|
-
throw error;
|
|
557
|
-
}
|
|
558
|
-
if (issuedHandoff && options.setupLeaseHandoff === undefined) {
|
|
559
|
-
await options.setupHandoffFault?.('before-consumed-persist');
|
|
560
|
-
await markSetupHandoffTokenConsumed(authority.projectRoot, authority.epicId, options.storyId, issuedHandoff.sessionId, issuedHandoff.token, bundleDigest, claimRevision, idempotencyKey, nowIso);
|
|
561
|
-
}
|
|
562
|
-
const trailers = Object.freeze([
|
|
563
|
-
`Neocortex-Story: ${options.storyId}`,
|
|
564
|
-
`Neocortex-Epic: ${authority.epicId}`,
|
|
565
|
-
`Neocortex-Execution-Branch: ${authority.executionBranch}`,
|
|
566
|
-
`Neocortex-Prepared-Base: ${baseSha}`,
|
|
567
|
-
`Neocortex-Bundle-Digest: ${bundleDigest}`,
|
|
568
|
-
`Neocortex-Review-Artifact-Digest: ${stagedReview.digest}`,
|
|
569
|
-
`Neocortex-Graph-Revision: ${boundGraphRevision}`,
|
|
570
|
-
`Neocortex-Claim-Revision: ${claimRevision}`,
|
|
571
|
-
...(authority.rootMemoryEffect ? [`Neocortex-Root-Memory-Effect: ${rootMemoryEffectDigest(authority.rootMemoryEffect)}`] : []),
|
|
572
|
-
]);
|
|
573
|
-
return { ok: true, value: Object.freeze({
|
|
574
|
-
schemaVersion: 1, storyId: options.storyId, epicId: authority.epicId,
|
|
575
|
-
executionBranch: authority.executionBranch, baseSha, bundleDigest,
|
|
576
|
-
reviewArtifactDigest: stagedReview.digest,
|
|
577
|
-
graphRevision: boundGraphRevision, claimRevision, idempotencyKey,
|
|
578
|
-
changedPaths: Object.freeze(changedPaths), trailers,
|
|
579
|
-
}) };
|
|
580
|
-
}
|
|
581
|
-
catch (error) {
|
|
582
|
-
return failure(publicReason(error, 'direct-yolo-begin-failed'));
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
export async function finalizeDirectYoloStoryCheckpoint(options) {
|
|
586
|
-
let cleanupAuthority;
|
|
587
|
-
let cleanupLease;
|
|
588
|
-
let cleanupPhysical;
|
|
589
|
-
try {
|
|
590
|
-
const authority = await resolveAuthority(options.projectRoot, options.storyId);
|
|
591
|
-
cleanupAuthority = authority;
|
|
592
|
-
const aggregateHeadSha = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
|
|
593
|
-
let runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
594
|
-
const existing = asRecord(runtime.stories[options.storyId]?.checkpoint);
|
|
595
|
-
if (existing) {
|
|
596
|
-
const checkpointHeadSha = typeof existing.headSha === 'string' ? existing.headSha : '';
|
|
597
|
-
const checkpointGraphRevision = typeof existing.graphRevision === 'string' ? existing.graphRevision : '';
|
|
598
|
-
const checkpointPaths = /^[a-f0-9]{40,64}$/.test(checkpointHeadSha)
|
|
599
|
-
? splitNull(await gitRaw(authority.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', checkpointHeadSha]))
|
|
600
|
-
: [];
|
|
601
|
-
const replayWriteSet = validateDirectWriteSet(checkpointPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
|
|
602
|
-
const ancestral = /^[a-f0-9]{40,64}$/.test(checkpointHeadSha)
|
|
603
|
-
&& await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', checkpointHeadSha, aggregateHeadSha]);
|
|
604
|
-
if (!ancestral || !/^[a-f0-9]{64}$/.test(checkpointGraphRevision) || !replayWriteSet.ok) {
|
|
605
|
-
return failure('direct-yolo-replay-invalid');
|
|
606
|
-
}
|
|
607
|
-
const replayQa = await runQa(options, authority.projectRoot, aggregateHeadSha, checkpointGraphRevision);
|
|
608
|
-
if (!(await verifyAcceptedGitLifecycleStoryCheckpoint(authority.projectRoot, existing, options.storyId, authority.epicId, authority.executionBranch, replayQa.transientAuthority, authority.authorizedWriteSet)))
|
|
609
|
-
return failure('direct-yolo-replay-invalid');
|
|
610
|
-
if (!(await physicalCheckoutUnchanged(authority.projectRoot, authority.executionBranch, aggregateHeadSha, checkpointPaths)))
|
|
611
|
-
return failure('direct-yolo-replay-head-raced');
|
|
612
|
-
if (options.push && !(await remoteContainsHead(authority.projectRoot, options.remote ?? 'origin', authority.executionBranch, checkpointHeadSha)))
|
|
613
|
-
return failure('direct-yolo-remote-head-mismatch');
|
|
614
|
-
const physicalOwnerRef = Array.isArray(existing.receiptRefs)
|
|
615
|
-
? existing.receiptRefs.find((item) => typeof item === 'string' && /^physical-lock-owner:[a-f0-9]{64}$/.test(item))
|
|
616
|
-
: undefined;
|
|
617
|
-
if (physicalOwnerRef && typeof existing.idempotencyKey === 'string') {
|
|
618
|
-
await releaseGitLifecyclePhysicalIntegrationLockForCheckpoint(authority.projectRoot, {
|
|
619
|
-
storyId: options.storyId,
|
|
620
|
-
idempotencyKey: existing.idempotencyKey,
|
|
621
|
-
ownerDigest: physicalOwnerRef.slice('physical-lock-owner:'.length),
|
|
622
|
-
});
|
|
623
|
-
}
|
|
624
|
-
await removeDirectCommitPlan(authority.projectRoot, options.storyId).catch(() => undefined);
|
|
625
|
-
return { ok: true, value: existing };
|
|
626
|
-
}
|
|
627
|
-
const headSha = aggregateHeadSha;
|
|
628
|
-
const baseSha = await git(authority.projectRoot, ['rev-parse', `${headSha}^`]);
|
|
629
|
-
const commitBody = await gitRaw(authority.projectRoot, ['show', '--no-patch', '--format=%B', headSha]);
|
|
630
|
-
const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', headSha]));
|
|
631
|
-
const writeSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
|
|
632
|
-
if (!writeSet.ok)
|
|
633
|
-
return failure(writeSet.reasonCode);
|
|
634
|
-
if (authority.rootMemoryEffect)
|
|
635
|
-
verifyRootMemoryPhysicalWriteSet(authority.projectRoot, authority.rootMemoryEffect, { storyId: options.storyId, executionBranch: authority.executionBranch, baseSha, headRef: headSha, childPaths: authority.authorizedWriteSet });
|
|
636
|
-
const expectedClaimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
|
|
637
|
-
// The begin plan binds the graph epoch the trailers were issued under. The
|
|
638
|
-
// epic epoch may legitimately advance after the lease is released (failed
|
|
639
|
-
// finalize, expiry); the checkpoint keeps its own epoch, as in terminal
|
|
640
|
-
// readiness. Content, claim and base bindings remain exact.
|
|
641
|
-
const storedPlan = await readDirectCommitPlan(authority.projectRoot, options.storyId);
|
|
642
|
-
if (storedPlan.state === 'invalid')
|
|
643
|
-
return failure('direct-yolo-commit-plan-invalid');
|
|
644
|
-
const plan = storedPlan.state === 'valid' ? storedPlan.plan : undefined;
|
|
645
|
-
if (plan && (plan.epicId !== authority.epicId || plan.executionBranch !== authority.executionBranch)) {
|
|
646
|
-
return failure('direct-yolo-commit-plan-invalid');
|
|
647
|
-
}
|
|
648
|
-
if (plan && plan.claimRevision !== expectedClaimRevision)
|
|
649
|
-
return failure('direct-yolo-commit-plan-claim-changed');
|
|
650
|
-
if (plan && plan.preparedBase !== baseSha)
|
|
651
|
-
return failure('direct-yolo-commit-plan-base-mismatch');
|
|
652
|
-
const parsedTrailers = parseNeocortexTrailers(commitBody);
|
|
653
|
-
if (!parsedTrailers.ok)
|
|
654
|
-
return failure(`direct-yolo-trailer-duplicate:${parsedTrailers.key}`);
|
|
655
|
-
const trailers = parsedTrailers.values;
|
|
656
|
-
const graphRevision = plan?.graphRevision ?? authority.graphRevision;
|
|
657
|
-
const claimRevision = expectedClaimRevision;
|
|
658
|
-
const required = [
|
|
659
|
-
['Neocortex-Story', options.storyId], ['Neocortex-Epic', authority.epicId],
|
|
660
|
-
['Neocortex-Execution-Branch', authority.executionBranch], ['Neocortex-Prepared-Base', baseSha],
|
|
661
|
-
['Neocortex-Bundle-Digest', plan?.bundleDigest ?? ''],
|
|
662
|
-
['Neocortex-Graph-Revision', graphRevision],
|
|
663
|
-
['Neocortex-Claim-Revision', claimRevision],
|
|
664
|
-
];
|
|
665
|
-
for (const [key, value] of required) {
|
|
666
|
-
const actual = trailerValue(trailers, key);
|
|
667
|
-
if (actual === undefined)
|
|
668
|
-
return failure(`direct-yolo-trailer-missing:${trailerReasonKey(key)}`);
|
|
669
|
-
if (key === 'Neocortex-Bundle-Digest' && !plan) {
|
|
670
|
-
if (!/^[a-f0-9]{64}$/.test(actual))
|
|
671
|
-
return failure(`direct-yolo-trailer-mismatch:${trailerReasonKey(key)}`);
|
|
672
|
-
continue;
|
|
673
|
-
}
|
|
674
|
-
if (actual !== value)
|
|
675
|
-
return failure(`direct-yolo-trailer-mismatch:${trailerReasonKey(key)}`);
|
|
676
|
-
}
|
|
677
|
-
const bundleDigest = trailerValue(trailers, 'Neocortex-Bundle-Digest');
|
|
678
|
-
const publicReview = publicStoryReviewArtifactFromGit(authority.projectRoot, options.storyId, headSha);
|
|
679
|
-
if (publicReview?.verdict !== 'approved')
|
|
680
|
-
return failure('direct-yolo-review-artifact-not-approved');
|
|
681
|
-
const reviewTrailer = trailerValue(trailers, 'Neocortex-Review-Artifact-Digest');
|
|
682
|
-
if (reviewTrailer !== undefined && reviewTrailer !== publicReview.digest) {
|
|
683
|
-
return failure('direct-yolo-review-artifact-digest-mismatch');
|
|
684
|
-
}
|
|
685
|
-
const expectedPayloadDigest = digest(await gitRaw(authority.projectRoot, ['diff', '--binary', '--full-index', `${baseSha}..${headSha}`]));
|
|
686
|
-
if (bundleDigest !== expectedPayloadDigest)
|
|
687
|
-
return failure('direct-yolo-bundle-digest-mismatch');
|
|
688
|
-
const idempotencyKey = directCommitIdempotencyKey({
|
|
689
|
-
storyId: options.storyId, epicId: authority.epicId, executionBranch: authority.executionBranch,
|
|
690
|
-
baseSha, bundleDigest, graphRevision, claimRevision,
|
|
691
|
-
});
|
|
692
|
-
if (plan && plan.idempotencyKey !== idempotencyKey)
|
|
693
|
-
return failure('direct-yolo-commit-plan-invalid');
|
|
694
|
-
const currentLease = asRecord(runtime.epics[authority.epicId]?.branch_lease);
|
|
695
|
-
const nowIso = normalizedTime(options.nowIso);
|
|
696
|
-
const matchingLease = currentLease?.ownerStoryId === options.storyId
|
|
697
|
-
&& currentLease.idempotencyKey === idempotencyKey
|
|
698
|
-
&& currentLease.sessionId === idempotencyKey
|
|
699
|
-
&& Date.parse(String(currentLease.expiresAt)) > Date.now()
|
|
700
|
-
? currentLease : undefined;
|
|
701
|
-
if (currentLease && Date.parse(String(currentLease.expiresAt)) > Date.now() && !matchingLease) {
|
|
702
|
-
return failure('direct-yolo-writer-active');
|
|
703
|
-
}
|
|
704
|
-
const requestedLease = matchingLease ?? {
|
|
705
|
-
schemaVersion: 1, ownerStoryId: options.storyId, sessionId: idempotencyKey,
|
|
706
|
-
idempotencyKey, acquiredAt: nowIso,
|
|
707
|
-
expiresAt: new Date(Date.parse(nowIso) + DIRECT_STORY_CHECKPOINT_LEASE_MS).toISOString(),
|
|
708
|
-
};
|
|
709
|
-
const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
|
|
710
|
-
kind: 'direct', storyId: options.storyId, sessionId: idempotencyKey, idempotencyKey,
|
|
711
|
-
expiresAt: String(requestedLease.expiresAt), persistent: true,
|
|
712
|
-
createdAt: String(requestedLease.acquiredAt),
|
|
713
|
-
});
|
|
714
|
-
if (!physicalLock.ok)
|
|
715
|
-
return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
|
|
716
|
-
? 'direct-yolo-integration-backpressure' : 'direct-yolo-integration-lock-failed');
|
|
717
|
-
cleanupPhysical = physicalLock;
|
|
718
|
-
if (!matchingLease) {
|
|
719
|
-
const leased = await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
|
|
720
|
-
const epic = ensureRuntimeEpic(document, authority.epicId);
|
|
721
|
-
const current = asRecord(epic.branch_lease);
|
|
722
|
-
if (current && Date.parse(String(current.expiresAt)) > Date.parse(nowIso)) {
|
|
723
|
-
throw new Error('direct-yolo-writer-active');
|
|
724
|
-
}
|
|
725
|
-
// Race guard only: the epic epoch must not move while this finalize
|
|
726
|
-
// owns the writer; the checkpoint itself stays bound to the plan epoch.
|
|
727
|
-
if (epic.graph_revision !== authority.graphRevision)
|
|
728
|
-
throw new Error('direct-yolo-graph-revision-raced');
|
|
729
|
-
epic.branch_lease = requestedLease;
|
|
730
|
-
}, { expectedRevision: runtime.revision });
|
|
731
|
-
runtime = leased.document;
|
|
732
|
-
}
|
|
733
|
-
cleanupLease = requestedLease;
|
|
734
|
-
{
|
|
735
|
-
const qaExecution = await runQa(options, authority.projectRoot, headSha, graphRevision);
|
|
736
|
-
if (!(await physicalCheckoutUnchanged(authority.projectRoot, authority.executionBranch, headSha, changedPaths))) {
|
|
737
|
-
return failure('direct-yolo-head-raced');
|
|
738
|
-
}
|
|
739
|
-
if (options.push) {
|
|
740
|
-
const remote = safeRemote(options.remote ?? 'origin');
|
|
741
|
-
await git(authority.projectRoot, ['push', remote, authority.executionBranch]);
|
|
742
|
-
if (!(await remoteHeadIsExact(authority.projectRoot, remote, authority.executionBranch, headSha))) {
|
|
743
|
-
return failure('direct-yolo-remote-head-mismatch');
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
const checkpoint = await buildCheckpoint({
|
|
747
|
-
projectRoot: authority.projectRoot, storyId: options.storyId, epicId: authority.epicId,
|
|
748
|
-
executionBranch: authority.executionBranch, baseSha, headSha, bundleDigest,
|
|
749
|
-
graphRevision, claimRevision, idempotencyKey, qaExecution,
|
|
750
|
-
physicalLockOwnerDigest: computeGitLifecyclePhysicalIntegrationLockOwnerDigest(physicalLock.owner),
|
|
751
|
-
nowIso: normalizedTime(options.nowIso), legacyReceiptRef: undefined, rootMemoryEffect: authority.rootMemoryEffect,
|
|
752
|
-
});
|
|
753
|
-
await options.beforeCheckpointPersist?.();
|
|
754
|
-
const persisted = await persistCheckpoint({
|
|
755
|
-
projectRoot: authority.projectRoot, checkpoint,
|
|
756
|
-
remote: options.push ? options.remote ?? 'origin' : undefined,
|
|
757
|
-
expectedRevision: runtime.revision, expectedLease: requestedLease,
|
|
758
|
-
expectedGraphRevision: authority.graphRevision,
|
|
759
|
-
expectedCheckpointGraphRevision: graphRevision,
|
|
760
|
-
physicalLockPath: physicalLock.path, physicalLockOwner: physicalLock.owner,
|
|
761
|
-
transientAuthority: qaExecution.transientAuthority,
|
|
762
|
-
authorizedWriteSet: authority.authorizedWriteSet,
|
|
763
|
-
});
|
|
764
|
-
if (!persisted)
|
|
765
|
-
return failure('direct-yolo-checkpoint-persist-failed');
|
|
766
|
-
await removeDirectCommitPlan(authority.projectRoot, options.storyId).catch(() => undefined);
|
|
767
|
-
await options.afterCheckpointPersist?.();
|
|
768
|
-
return { ok: true, value: checkpoint };
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
catch (error) {
|
|
772
|
-
return failure(publicReason(error, 'direct-yolo-finalize-failed'));
|
|
773
|
-
}
|
|
774
|
-
finally {
|
|
775
|
-
if (cleanupPhysical) {
|
|
776
|
-
await releaseGitLifecyclePhysicalIntegrationLock(cleanupPhysical.path, cleanupPhysical.owner).catch(() => undefined);
|
|
777
|
-
}
|
|
778
|
-
if (cleanupAuthority && cleanupLease) {
|
|
779
|
-
await releaseOwnedDirectLease(cleanupAuthority.projectRoot, cleanupAuthority.epicId, cleanupLease).catch(() => undefined);
|
|
780
|
-
}
|
|
781
|
-
else if (cleanupAuthority) {
|
|
782
|
-
await cleanupOwnedDirectAuthority(cleanupAuthority, options.storyId).catch(() => undefined);
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
export async function recoverLegacyDirectYoloStoryCheckpoint(options) {
|
|
787
|
-
try {
|
|
788
|
-
const authority = await resolveAuthority(options.projectRoot, options.storyId);
|
|
789
|
-
if (!/^[a-f0-9]{40,64}$/.test(options.commitSha))
|
|
790
|
-
return failure('direct-yolo-recovery-commit-invalid');
|
|
791
|
-
const headSha = await git(authority.projectRoot, ['rev-parse', options.commitSha]);
|
|
792
|
-
if (LEGACY_DIRECT_YOLO_RECOVERY_COMMITS[options.storyId] !== headSha) {
|
|
793
|
-
return failure('direct-yolo-recovery-not-allowlisted');
|
|
794
|
-
}
|
|
795
|
-
if (await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== headSha) {
|
|
796
|
-
return failure('direct-yolo-recovery-head-mismatch');
|
|
797
|
-
}
|
|
798
|
-
await git(authority.projectRoot, ['merge-base', '--is-ancestor', headSha, `refs/heads/${authority.executionBranch}`]);
|
|
799
|
-
const baseSha = await git(authority.projectRoot, ['rev-parse', `${headSha}^`]);
|
|
800
|
-
const payload = await gitRaw(authority.projectRoot, ['diff', '--binary', '--full-index', `${baseSha}..${headSha}`]);
|
|
801
|
-
const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', headSha]));
|
|
802
|
-
const recoveryWriteSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet.length > 0 ? authority.authorizedWriteSet : changedPaths, options.storyId);
|
|
803
|
-
if (!recoveryWriteSet.ok)
|
|
804
|
-
return failure('direct-yolo-recovery-write-set-invalid');
|
|
805
|
-
const bundleDigest = digest(payload);
|
|
806
|
-
const claimRevision = digest([...changedPaths].sort().join('\0'));
|
|
807
|
-
const idempotencyKey = digest(['legacy-direct-yolo-recovery-v1', options.storyId, headSha].join('\0'));
|
|
808
|
-
const nowIso = normalizedTime(options.nowIso);
|
|
809
|
-
const expiresAt = new Date(Date.parse(nowIso) + DIRECT_STORY_CHECKPOINT_LEASE_MS).toISOString();
|
|
810
|
-
const initialRuntime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
811
|
-
const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
|
|
812
|
-
kind: 'direct', storyId: options.storyId, sessionId: idempotencyKey, idempotencyKey,
|
|
813
|
-
expiresAt, persistent: true, createdAt: nowIso,
|
|
814
|
-
});
|
|
815
|
-
if (!physicalLock.ok)
|
|
816
|
-
return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
|
|
817
|
-
? 'direct-yolo-recovery-integration-backpressure' : 'direct-yolo-recovery-integration-lock-failed');
|
|
818
|
-
const requestedLease = {
|
|
819
|
-
schemaVersion: 1, ownerStoryId: options.storyId, sessionId: idempotencyKey,
|
|
820
|
-
idempotencyKey, acquiredAt: nowIso, expiresAt,
|
|
821
|
-
};
|
|
822
|
-
let leaseAcquired = false;
|
|
823
|
-
try {
|
|
824
|
-
const leased = await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
|
|
825
|
-
const epic = ensureRuntimeEpic(document, authority.epicId);
|
|
826
|
-
const current = asRecord(epic.branch_lease);
|
|
827
|
-
if (current && Date.parse(String(current.expiresAt)) > Date.parse(nowIso)
|
|
828
|
-
&& !sameLease(current, requestedLease))
|
|
829
|
-
throw new Error('direct-yolo-recovery-writer-active');
|
|
830
|
-
if (epic.graph_revision !== authority.graphRevision)
|
|
831
|
-
throw new Error('direct-yolo-recovery-graph-raced');
|
|
832
|
-
epic.branch_mode = 'epic';
|
|
833
|
-
epic.execution_branch = authority.executionBranch;
|
|
834
|
-
epic.origin_branch = authority.originBranch;
|
|
835
|
-
epic.branch_lease = requestedLease;
|
|
836
|
-
}, { expectedRevision: initialRuntime.revision });
|
|
837
|
-
leaseAcquired = true;
|
|
838
|
-
const qaExecution = await runQa(options, authority.projectRoot, headSha, authority.graphRevision);
|
|
839
|
-
if (!(await physicalCheckoutUnchanged(authority.projectRoot, authority.executionBranch, headSha, changedPaths))) {
|
|
840
|
-
return failure('direct-yolo-recovery-head-raced');
|
|
841
|
-
}
|
|
842
|
-
if (options.push) {
|
|
843
|
-
const remote = safeRemote(options.remote ?? 'origin');
|
|
844
|
-
const remoteHead = (await git(authority.projectRoot, ['ls-remote', '--heads', remote, `refs/heads/${authority.executionBranch}`])).split(/\s+/)[0];
|
|
845
|
-
if (!remoteHead || !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', headSha, remoteHead]))) {
|
|
846
|
-
return failure('direct-yolo-recovery-remote-proof-missing');
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
const provisional = await buildCheckpoint({
|
|
850
|
-
projectRoot: authority.projectRoot, storyId: options.storyId, epicId: authority.epicId,
|
|
851
|
-
executionBranch: authority.executionBranch, baseSha, headSha, bundleDigest,
|
|
852
|
-
graphRevision: authority.graphRevision, claimRevision, idempotencyKey,
|
|
853
|
-
qaExecution,
|
|
854
|
-
physicalLockOwnerDigest: computeGitLifecyclePhysicalIntegrationLockOwnerDigest(physicalLock.owner),
|
|
855
|
-
nowIso, legacyReceiptRef: undefined,
|
|
856
|
-
});
|
|
857
|
-
const legacyReceiptRef = await computeLegacyDirectYoloRecoveryReceiptRef(authority.projectRoot, {
|
|
858
|
-
storyId: options.storyId,
|
|
859
|
-
epicId: authority.epicId,
|
|
860
|
-
executionBranch: authority.executionBranch,
|
|
861
|
-
baseSha,
|
|
862
|
-
headSha,
|
|
863
|
-
bundleDigest,
|
|
864
|
-
graphRevision: authority.graphRevision,
|
|
865
|
-
});
|
|
866
|
-
if (!legacyReceiptRef)
|
|
867
|
-
return failure('direct-yolo-recovery-evidence-invalid');
|
|
868
|
-
const checkpoint = Object.freeze({
|
|
869
|
-
...provisional,
|
|
870
|
-
receiptRefs: Object.freeze([...provisional.receiptRefs, legacyReceiptRef]),
|
|
871
|
-
});
|
|
872
|
-
const persisted = await persistCheckpoint({
|
|
873
|
-
projectRoot: authority.projectRoot, checkpoint,
|
|
874
|
-
remote: options.push ? options.remote ?? 'origin' : undefined,
|
|
875
|
-
remotePolicy: 'ancestor-recovery',
|
|
876
|
-
expectedRevision: leased.document.revision,
|
|
877
|
-
expectedLease: requestedLease,
|
|
878
|
-
expectedGraphRevision: authority.graphRevision,
|
|
879
|
-
physicalLockPath: physicalLock.path,
|
|
880
|
-
physicalLockOwner: physicalLock.owner,
|
|
881
|
-
transientAuthority: qaExecution.transientAuthority,
|
|
882
|
-
authorizedWriteSet: authority.authorizedWriteSet,
|
|
883
|
-
});
|
|
884
|
-
return persisted ? { ok: true, value: checkpoint } : failure('direct-yolo-recovery-persist-failed');
|
|
885
|
-
}
|
|
886
|
-
finally {
|
|
887
|
-
await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
|
|
888
|
-
if (leaseAcquired)
|
|
889
|
-
await releaseOwnedDirectLease(authority.projectRoot, authority.epicId, requestedLease).catch(() => undefined);
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
catch (error) {
|
|
893
|
-
return failure(publicReason(error, 'direct-yolo-recovery-failed'));
|
|
894
|
-
}
|
|
895
|
-
}
|
|
896
|
-
/** A secondary worktree has a private git dir distinct from the common dir. */
|
|
897
|
-
async function isSecondaryWorktree(projectRoot) {
|
|
898
|
-
const gitDir = await realpath(await git(projectRoot, ['rev-parse', '--absolute-git-dir']));
|
|
899
|
-
const commonDir = await realpath(await git(projectRoot, ['rev-parse', '--path-format=absolute', '--git-common-dir']));
|
|
900
|
-
return gitDir !== commonDir;
|
|
901
|
-
}
|
|
902
|
-
/**
|
|
903
|
-
* P225.07 C01 in a managed story worktree (P225.07-ADR-7): bind to the unique
|
|
904
|
-
* active journal lease of the story and prove the checkout sits, clean, on the
|
|
905
|
-
* temporary branch at the authorized base. No epic lease, no branch switch.
|
|
906
|
-
*/
|
|
907
|
-
async function bindStoryWorktreeSetup(authority) {
|
|
908
|
-
const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
909
|
-
const candidates = Object.values(runtime.storyWorktrees?.entries ?? {})
|
|
910
|
-
.filter((entry) => entry.storyId === authority.storyId && entry.epicId === authority.epicId && entry.state === 'active');
|
|
911
|
-
if (candidates.length === 0)
|
|
912
|
-
throw new Error('direct-yolo-worktree-lease-missing');
|
|
913
|
-
if (candidates.length > 1)
|
|
914
|
-
throw new Error('direct-yolo-worktree-lease-ambiguous');
|
|
915
|
-
const entry = candidates[0];
|
|
916
|
-
if (entry.executionBranch !== authority.executionBranch)
|
|
917
|
-
throw new Error('direct-yolo-worktree-branch-mismatch');
|
|
918
|
-
const toplevel = await realpath(await git(authority.projectRoot, ['rev-parse', '--show-toplevel']));
|
|
919
|
-
if (toplevel !== entry.worktreePath)
|
|
920
|
-
throw new Error('direct-yolo-worktree-path-mismatch');
|
|
921
|
-
const currentBranch = await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => '');
|
|
922
|
-
if (currentBranch !== entry.temporaryBranch)
|
|
923
|
-
throw new Error('direct-yolo-worktree-branch-mismatch');
|
|
924
|
-
const probe = await new StoryWorktreeManager({ projectRoot: authority.projectRoot }).probe(entry.leaseId);
|
|
925
|
-
if (!probe.ok || probe.value.ownership !== 'proven')
|
|
926
|
-
throw new Error('direct-yolo-worktree-ownership-unproven');
|
|
927
|
-
const binding = validOriginBinding(asRecord(runtime.epics[authority.epicId])?.origin_binding, authority.executionBranch, authority.originBranch);
|
|
928
|
-
if (!binding)
|
|
929
|
-
throw new Error('direct-yolo-origin-binding-invalid');
|
|
930
|
-
const authorizedBase = entry.syncedSha ?? entry.baseSha;
|
|
931
|
-
const headSha = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
|
|
932
|
-
const epicRef = `refs/heads/${authority.executionBranch}`;
|
|
933
|
-
if (headSha !== authorizedBase
|
|
934
|
-
|| !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', authorizedBase, epicRef]))
|
|
935
|
-
|| !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', binding.originHeadSha, authorizedBase]))) {
|
|
936
|
-
throw new Error('direct-yolo-worktree-base-divergent');
|
|
937
|
-
}
|
|
938
|
-
if (probe.value.clean !== true
|
|
939
|
-
|| (await gitRaw(authority.projectRoot, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])).length > 0) {
|
|
940
|
-
throw new Error('direct-yolo-worktree-dirty');
|
|
941
|
-
}
|
|
942
|
-
return {
|
|
943
|
-
leaseId: entry.leaseId, temporaryBranch: entry.temporaryBranch, authorizedBase, headSha,
|
|
944
|
-
expiresAt: entry.expiresAt, binding,
|
|
945
|
-
};
|
|
946
|
-
}
|
|
947
|
-
function storyWorktreeSetupReceipt(authority, bound, reused) {
|
|
948
|
-
return Object.freeze({
|
|
949
|
-
...setupReceipt(authority, bound.binding, bound.expiresAt, reused),
|
|
950
|
-
workspace: 'story-worktree', temporaryBranch: bound.temporaryBranch, baseSha: bound.authorizedBase,
|
|
951
|
-
});
|
|
952
|
-
}
|
|
953
|
-
async function acceptStoryWorktreeSetup(authority) {
|
|
954
|
-
const bound = await bindStoryWorktreeSetup(authority);
|
|
955
|
-
const statePath = join(authority.projectRoot, '.neocortex/state.json');
|
|
956
|
-
const trackedBefore = await readFile(statePath, 'utf8');
|
|
957
|
-
const tracked = asRecord(JSON.parse(trackedBefore));
|
|
958
|
-
const trackedStory = asRecord(asRecord(tracked?.stories)?.[authority.storyId]);
|
|
959
|
-
const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
960
|
-
const runtimeStory = asRecord(runtime.stories[authority.storyId]);
|
|
961
|
-
if (!trackedStory || !['backlog', 'ready_to_start'].includes(String(trackedStory.status))
|
|
962
|
-
|| (trackedStory.steps_completed !== undefined
|
|
963
|
-
&& (!Array.isArray(trackedStory.steps_completed) || trackedStory.steps_completed.length > 0))
|
|
964
|
-
|| trackedStory.branch_name || trackedStory.checkpoint) {
|
|
965
|
-
return failure('direct-yolo-setup-story-progress-conflict');
|
|
966
|
-
}
|
|
967
|
-
const accepted = runtimeStory?.status === 'branch-ready'
|
|
968
|
-
&& runtimeStory.last_step === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
|
|
969
|
-
&& Array.isArray(runtimeStory.steps_completed) && runtimeStory.steps_completed.length === 1
|
|
970
|
-
&& runtimeStory.steps_completed[0] === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
|
|
971
|
-
&& Object.keys(runtimeStory).sort().join(',') === 'last_step,status,steps_completed';
|
|
972
|
-
if (runtimeStory && Object.keys(runtimeStory).length > 0 && !accepted) {
|
|
973
|
-
return failure('direct-yolo-setup-story-progress-conflict');
|
|
974
|
-
}
|
|
975
|
-
if (!accepted) {
|
|
976
|
-
await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
|
|
977
|
-
const currentStory = ensureRuntimeStory(document, authority.storyId);
|
|
978
|
-
if (Object.keys(currentStory).length > 0)
|
|
979
|
-
throw new Error('direct-yolo-setup-runtime-raced');
|
|
980
|
-
currentStory.status = 'branch-ready';
|
|
981
|
-
currentStory.last_step = GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID;
|
|
982
|
-
currentStory.steps_completed = [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID];
|
|
983
|
-
}, {
|
|
984
|
-
expectedRevision: runtime.revision,
|
|
985
|
-
preCommit: async () => {
|
|
986
|
-
if (await readFile(statePath, 'utf8') !== trackedBefore
|
|
987
|
-
|| await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== bound.temporaryBranch
|
|
988
|
-
|| await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== bound.headSha
|
|
989
|
-
|| (await gitRaw(authority.projectRoot, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])).length > 0) {
|
|
990
|
-
throw new Error('direct-yolo-setup-physical-state-raced');
|
|
991
|
-
}
|
|
992
|
-
},
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
return { ok: true, value: Object.freeze({
|
|
996
|
-
...storyWorktreeSetupReceipt(authority, bound, accepted),
|
|
997
|
-
checkpointAccepted: true, graphRevision: authority.graphRevision, headSha: bound.headSha,
|
|
998
|
-
}) };
|
|
999
|
-
}
|
|
1000
|
-
/**
|
|
1001
|
-
* P225.07 root integration authority: the same logical authority as direct
|
|
1002
|
-
* C08, required from the root checkout on the execution branch.
|
|
1003
|
-
*/
|
|
1004
|
-
export async function resolveDirectYoloIntegrationAuthority(projectRootInput, storyId) {
|
|
1005
|
-
const authority = await resolveAuthority(projectRootInput, storyId);
|
|
1006
|
-
const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
1007
|
-
const binding = validOriginBinding(asRecord(runtime.epics[authority.epicId])?.origin_binding, authority.executionBranch, authority.originBranch);
|
|
1008
|
-
return { ...authority, originBinding: binding };
|
|
1009
|
-
}
|
|
1010
|
-
/** P225.07: the direct C08 write-set rule, shared with root integration. */
|
|
1011
|
-
export function validateDirectYoloWriteSet(paths, authorizedWriteSet, storyId, rootMemoryEffect) {
|
|
1012
|
-
return validateDirectWriteSet(paths, authorizedWriteSet, storyId, rootMemoryEffect);
|
|
1013
|
-
}
|
|
1014
|
-
/** P225.07: deterministic direct-checkpoint idempotency key (same formula as begin/finalize). */
|
|
1015
|
-
export function directYoloCommitIdempotencyKey(input) {
|
|
1016
|
-
return digest([
|
|
1017
|
-
'direct-yolo-commit-v1', input.storyId, input.epicId, input.executionBranch,
|
|
1018
|
-
input.baseSha, input.bundleDigest, input.graphRevision, input.claimRevision,
|
|
1019
|
-
].join('\0'));
|
|
1020
|
-
}
|
|
1021
|
-
export const DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS = DIRECT_STORY_CHECKPOINT_LEASE_MS;
|
|
1022
|
-
async function resolveLogicalAuthority(projectRootInput, storyId) {
|
|
1023
|
-
if (!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(storyId))
|
|
1024
|
-
throw new Error('direct-yolo-story-id-invalid');
|
|
1025
|
-
const projectRoot = resolve(projectRootInput);
|
|
1026
|
-
const tracked = asRecord(JSON.parse(await readFile(join(projectRoot, '.neocortex/state.json'), 'utf8')));
|
|
1027
|
-
const runtime = await readGitLifecycleRuntime(projectRoot, { required: true });
|
|
1028
|
-
const effective = applyGitLifecycleRuntimeOverlay(tracked, runtime);
|
|
1029
|
-
const stories = asRecord(effective.stories);
|
|
1030
|
-
const epics = asRecord(effective.epics);
|
|
1031
|
-
const story = asRecord(stories?.[storyId]);
|
|
1032
|
-
const epicId = String(story?.epic_id ?? storyId.split('.')[0]);
|
|
1033
|
-
const epic = asRecord(epics?.[epicId]);
|
|
1034
|
-
const executionBranch = String(epic?.execution_branch ?? '');
|
|
1035
|
-
const originBranch = String(epic?.origin_branch ?? '');
|
|
1036
|
-
const graphRevision = String(epic?.graph_revision ?? '');
|
|
1037
|
-
const authorizedWriteSet = Array.isArray(story?.files_to_modify)
|
|
1038
|
-
? [...new Set(story.files_to_modify.filter((item) => typeof item === 'string' && safePath(item)))].sort()
|
|
1039
|
-
: [];
|
|
1040
|
-
if (!story)
|
|
1041
|
-
throw new Error('direct-yolo-story-state-missing');
|
|
1042
|
-
if (epic?.branch_mode !== 'epic')
|
|
1043
|
-
throw new Error('direct-yolo-branch-mode-invalid');
|
|
1044
|
-
if (!safeRef(executionBranch)
|
|
1045
|
-
|| !(await gitExitOk(projectRoot, ['check-ref-format', '--branch', executionBranch]))) {
|
|
1046
|
-
throw new Error('direct-yolo-execution-branch-invalid');
|
|
1047
|
-
}
|
|
1048
|
-
if (!safeRef(originBranch)
|
|
1049
|
-
|| !(await gitExitOk(projectRoot, ['check-ref-format', '--branch', originBranch]))) {
|
|
1050
|
-
throw new Error('direct-yolo-origin-branch-invalid');
|
|
1051
|
-
}
|
|
1052
|
-
if (!/^[a-f0-9]{64}$/.test(graphRevision))
|
|
1053
|
-
throw new Error('direct-yolo-graph-revision-invalid');
|
|
1054
|
-
const rootMemoryEffect = await readRootMemoryEffectForCheckpoint({ projectRoot, storyId, graphRevision,
|
|
1055
|
-
executionBranch, childPaths: authorizedWriteSet });
|
|
1056
|
-
return { projectRoot, storyId, story, epicId, executionBranch, originBranch, graphRevision, authorizedWriteSet, rootMemoryEffect };
|
|
1057
|
-
}
|
|
1058
|
-
async function resolveAuthority(projectRootInput, storyId) {
|
|
1059
|
-
const authority = await resolveLogicalAuthority(projectRootInput, storyId);
|
|
1060
|
-
const currentBranch = await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
1061
|
-
if (currentBranch !== authority.executionBranch)
|
|
1062
|
-
throw new Error('direct-yolo-current-branch-mismatch');
|
|
1063
|
-
return authority;
|
|
1064
|
-
}
|
|
1065
|
-
async function buildCheckpoint(input) {
|
|
1066
|
-
const checkedAt = input.nowIso;
|
|
1067
|
-
const commitBody = await gitRaw(input.projectRoot, ['show', '--no-patch', '--format=%H%n%P%n%B', input.headSha]);
|
|
1068
|
-
const changedPaths = splitNull(await gitRaw(input.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', input.headSha]));
|
|
1069
|
-
const gitEvidenceDigest = computeImmutableStoryQaEvidenceDigest({
|
|
1070
|
-
storyId: input.storyId, baseSha: input.baseSha, headSha: input.headSha,
|
|
1071
|
-
bundleDigest: input.bundleDigest, graphRevision: input.graphRevision,
|
|
1072
|
-
commitBody, changedPaths,
|
|
1073
|
-
});
|
|
1074
|
-
const qaDigest = computeP205StoryQaEvidenceDigest({
|
|
1075
|
-
gitEvidenceDigest, headSha: input.headSha, graphRevision: input.graphRevision,
|
|
1076
|
-
manifestDigest: input.qaExecution.manifestDigest, gateIds: input.qaExecution.gateIds,
|
|
1077
|
-
resultDigest: input.qaExecution.resultDigest,
|
|
1078
|
-
});
|
|
1079
|
-
const qaReceiptRef = `story-qa:${qaDigest}`;
|
|
1080
|
-
const qaReceipt = Object.freeze({
|
|
1081
|
-
schemaVersion: 1, kind: 'story_qa_evidence', producer: 'local-yolo-tdd', evidenceVersion: 'p205-execution-v2',
|
|
1082
|
-
storyId: input.storyId, epicId: input.epicId, baseSha: input.baseSha, headSha: input.headSha,
|
|
1083
|
-
bundleDigest: input.bundleDigest, graphRevision: input.graphRevision,
|
|
1084
|
-
contract: input.qaExecution.contract, command: input.qaExecution.command,
|
|
1085
|
-
manifestDigest: input.qaExecution.manifestDigest, gateIds: input.qaExecution.gateIds,
|
|
1086
|
-
resultDigest: input.qaExecution.resultDigest,
|
|
1087
|
-
sourceEvidenceDigest: qaDigest, verdict: 'passed', checkedAt, receiptRef: qaReceiptRef,
|
|
1088
|
-
});
|
|
1089
|
-
const publicReview = publicStoryReviewArtifactFromGit(input.projectRoot, input.storyId, input.headSha);
|
|
1090
|
-
if (publicReview?.verdict !== 'approved')
|
|
1091
|
-
throw new Error('direct-yolo-review-artifact-not-approved');
|
|
1092
|
-
const reviewDigest = digest([
|
|
1093
|
-
'root-commit-range-review-v2', input.storyId, input.baseSha, input.headSha,
|
|
1094
|
-
input.bundleDigest, input.graphRevision, qaReceiptRef, digest(commitBody), [...changedPaths].sort().join(','),
|
|
1095
|
-
publicReview.digest,
|
|
1096
|
-
].join('\0'));
|
|
1097
|
-
const reviewReceiptRef = `story-review:${reviewDigest}`;
|
|
1098
|
-
const reviewReceipt = Object.freeze({
|
|
1099
|
-
schemaVersion: 1, kind: 'story_review_evidence', producer: 'root-commit-range-review',
|
|
1100
|
-
storyId: input.storyId, epicId: input.epicId, baseSha: input.baseSha, headSha: input.headSha,
|
|
1101
|
-
bundleDigest: input.bundleDigest, graphRevision: input.graphRevision,
|
|
1102
|
-
sourceEvidenceDigest: reviewDigest, reviewArtifactDigest: publicReview.digest,
|
|
1103
|
-
qaReceiptRef, verdict: 'approved', reviewedAt: checkedAt,
|
|
1104
|
-
receiptRef: reviewReceiptRef,
|
|
1105
|
-
});
|
|
1106
|
-
const evidenceRefs = [
|
|
1107
|
-
`.neocortex/stories/${input.storyId}/qa-gate-result.json`,
|
|
1108
|
-
`.neocortex/stories/${input.storyId}/validation-evidence.md`, qaReceiptRef, reviewReceiptRef,
|
|
1109
|
-
...(input.physicalLockOwnerDigest ? [`physical-lock-owner:${input.physicalLockOwnerDigest}`] : []),
|
|
1110
|
-
...(input.legacyReceiptRef ? [input.legacyReceiptRef] : []),
|
|
1111
|
-
];
|
|
1112
|
-
return Object.freeze({
|
|
1113
|
-
schemaVersion: 1, storyId: input.storyId, epicId: input.epicId, branch: input.executionBranch,
|
|
1114
|
-
baseSha: input.baseSha, headSha: input.headSha, commits: Object.freeze([input.headSha]),
|
|
1115
|
-
idempotencyKey: input.idempotencyKey, bundleDigest: input.bundleDigest,
|
|
1116
|
-
graphRevision: input.graphRevision, claimRevision: input.claimRevision,
|
|
1117
|
-
receiptRefs: Object.freeze(evidenceRefs), qaVerdict: 'passed', reviewVerdict: 'approved',
|
|
1118
|
-
qaReceipt, reviewReceipt, recordedAt: checkedAt,
|
|
1119
|
-
...(input.rootMemoryEffect ? { rootMemoryEffect: input.rootMemoryEffect } : {}),
|
|
1120
|
-
});
|
|
1121
|
-
}
|
|
1122
|
-
async function persistCheckpoint(input) {
|
|
1123
|
-
const { projectRoot, checkpoint, remote } = input;
|
|
1124
|
-
let conflict = false;
|
|
1125
|
-
await mutateGitLifecycleRuntime(projectRoot, (document) => {
|
|
1126
|
-
const epic = ensureRuntimeEpic(document, checkpoint.epicId);
|
|
1127
|
-
if (input.expectedLease) {
|
|
1128
|
-
const currentLease = asRecord(epic.branch_lease);
|
|
1129
|
-
if (!sameLease(currentLease, input.expectedLease))
|
|
1130
|
-
throw new Error('direct-yolo-runtime-revision-conflict');
|
|
1131
|
-
if (Date.parse(String(currentLease?.expiresAt)) <= Date.now())
|
|
1132
|
-
throw new Error('direct-yolo-writer-lease-expired');
|
|
1133
|
-
if (epic.graph_revision !== input.expectedGraphRevision
|
|
1134
|
-
|| checkpoint.graphRevision !== (input.expectedCheckpointGraphRevision ?? input.expectedGraphRevision)) {
|
|
1135
|
-
throw new Error('direct-yolo-graph-revision-raced');
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1138
|
-
const story = ensureRuntimeStory(document, checkpoint.storyId);
|
|
1139
|
-
const existing = asRecord(story.checkpoint);
|
|
1140
|
-
if (existing && existing.headSha !== checkpoint.headSha) {
|
|
1141
|
-
conflict = true;
|
|
1142
|
-
return;
|
|
1143
|
-
}
|
|
1144
|
-
story.checkpoint = checkpoint;
|
|
1145
|
-
story.status = 'done';
|
|
1146
|
-
story.last_step = GIT_LIFECYCLE_REVIEW_PR_STEP_ID;
|
|
1147
|
-
const steps = Array.isArray(story.steps_completed) ? story.steps_completed.filter((item) => typeof item === 'string') : [];
|
|
1148
|
-
story.steps_completed = [...new Set([...steps, GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID])];
|
|
1149
|
-
epic.branch_lease = null;
|
|
1150
|
-
}, { expectedRevision: input.expectedRevision, preCommit: async () => {
|
|
1151
|
-
if (conflict)
|
|
1152
|
-
throw new Error('direct-yolo-checkpoint-conflict');
|
|
1153
|
-
const currentBranch = await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
1154
|
-
if (currentBranch !== checkpoint.branch || await git(projectRoot, ['rev-parse', 'HEAD']) !== checkpoint.headSha) {
|
|
1155
|
-
throw new Error('direct-yolo-checkpoint-head-raced');
|
|
1156
|
-
}
|
|
1157
|
-
if (!(await verifyAcceptedGitLifecycleStoryCheckpoint(projectRoot, checkpoint, checkpoint.storyId, checkpoint.epicId, checkpoint.branch, input.transientAuthority, input.authorizedWriteSet)))
|
|
1158
|
-
throw new Error('direct-yolo-checkpoint-physical-invalid');
|
|
1159
|
-
if (input.physicalLockPath && input.physicalLockOwner
|
|
1160
|
-
&& !(await verifyGitLifecyclePhysicalIntegrationLock(input.physicalLockPath, input.physicalLockOwner))) {
|
|
1161
|
-
throw new Error('direct-yolo-integration-lock-raced');
|
|
1162
|
-
}
|
|
1163
|
-
if (remote) {
|
|
1164
|
-
const accepted = input.remotePolicy === 'ancestor-recovery'
|
|
1165
|
-
? await remoteContainsHead(projectRoot, remote, checkpoint.branch, checkpoint.headSha)
|
|
1166
|
-
: await remoteHeadIsExact(projectRoot, remote, checkpoint.branch, checkpoint.headSha);
|
|
1167
|
-
if (!accepted) {
|
|
1168
|
-
throw new Error('direct-yolo-checkpoint-remote-raced');
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
} });
|
|
1172
|
-
return !conflict;
|
|
1173
|
-
}
|
|
1174
|
-
async function remoteContainsHead(projectRoot, remoteInput, branch, headSha) {
|
|
1175
|
-
const remote = safeRemote(remoteInput);
|
|
1176
|
-
const remoteHead = (await git(projectRoot, ['ls-remote', '--heads', remote, `refs/heads/${branch}`])).split(/\s+/)[0];
|
|
1177
|
-
return Boolean(remoteHead && await gitExitOk(projectRoot, ['merge-base', '--is-ancestor', headSha, remoteHead]));
|
|
1178
|
-
}
|
|
1179
|
-
function directCommitIdempotencyKey(input) {
|
|
1180
|
-
return digest([
|
|
1181
|
-
'direct-yolo-commit-v1', input.storyId, input.epicId, input.executionBranch,
|
|
1182
|
-
input.baseSha, input.bundleDigest, input.graphRevision, input.claimRevision,
|
|
1183
|
-
].join('\0'));
|
|
1184
|
-
}
|
|
1185
|
-
const DIRECT_COMMIT_PLAN_KEYS = [
|
|
1186
|
-
'schemaVersion', 'kind', 'storyId', 'epicId', 'executionBranch', 'graphRevision',
|
|
1187
|
-
'preparedBase', 'bundleDigest', 'claimRevision', 'idempotencyKey', 'issuedAt',
|
|
1188
|
-
];
|
|
1189
|
-
async function directCommitPlanLocation(projectRoot, storyId) {
|
|
1190
|
-
const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
|
|
1191
|
-
const parent = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'commit-plans');
|
|
1192
|
-
const name = `direct-${digest(storyId)}.json`;
|
|
1193
|
-
return { parent, name, path: join(parent, name) };
|
|
1194
|
-
}
|
|
1195
|
-
async function writeDirectCommitPlan(projectRoot, plan) {
|
|
1196
|
-
const location = await directCommitPlanLocation(projectRoot, plan.storyId);
|
|
1197
|
-
await anchoredAtomicWriteFile(location.parent, location.name, `${JSON.stringify(plan, null, 2)}\n`);
|
|
1198
|
-
await assertGitLifecyclePrivateFile(location.path, location.parent);
|
|
1199
|
-
}
|
|
1200
|
-
async function readDirectCommitPlan(projectRoot, storyId) {
|
|
1201
|
-
let location;
|
|
1202
|
-
try {
|
|
1203
|
-
location = await directCommitPlanLocation(projectRoot, storyId);
|
|
1204
|
-
}
|
|
1205
|
-
catch {
|
|
1206
|
-
return { state: 'invalid' };
|
|
1207
|
-
}
|
|
1208
|
-
try {
|
|
1209
|
-
if (!existsSync(location.path))
|
|
1210
|
-
return { state: 'absent' };
|
|
1211
|
-
await assertGitLifecyclePrivateFile(location.path, location.parent);
|
|
1212
|
-
const raw = await readFile(location.path, 'utf8');
|
|
1213
|
-
if (raw.length > 16 * 1024)
|
|
1214
|
-
return { state: 'invalid' };
|
|
1215
|
-
const item = asRecord(JSON.parse(raw));
|
|
1216
|
-
if (!item || Object.keys(item).sort().join('\0') !== [...DIRECT_COMMIT_PLAN_KEYS].sort().join('\0')
|
|
1217
|
-
|| item.schemaVersion !== 1 || item.kind !== 'direct-yolo-commit-plan' || item.storyId !== storyId
|
|
1218
|
-
|| typeof item.epicId !== 'string' || typeof item.executionBranch !== 'string' || !safeRef(item.executionBranch)
|
|
1219
|
-
|| typeof item.preparedBase !== 'string' || !/^[a-f0-9]{40,64}$/.test(item.preparedBase)
|
|
1220
|
-
|| ![item.graphRevision, item.bundleDigest, item.claimRevision, item.idempotencyKey].every((value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
|
|
1221
|
-
|| typeof item.issuedAt !== 'string' || !Number.isFinite(Date.parse(item.issuedAt))) {
|
|
1222
|
-
return { state: 'invalid' };
|
|
1223
|
-
}
|
|
1224
|
-
const plan = item;
|
|
1225
|
-
if (plan.idempotencyKey !== directCommitIdempotencyKey({ ...plan, baseSha: plan.preparedBase })) {
|
|
1226
|
-
return { state: 'invalid' };
|
|
1227
|
-
}
|
|
1228
|
-
return { state: 'valid', plan };
|
|
1229
|
-
}
|
|
1230
|
-
catch {
|
|
1231
|
-
return { state: 'invalid' };
|
|
1232
|
-
}
|
|
1233
|
-
}
|
|
1234
|
-
async function removeDirectCommitPlan(projectRoot, storyId) {
|
|
1235
|
-
const location = await directCommitPlanLocation(projectRoot, storyId);
|
|
1236
|
-
if (!existsSync(location.path))
|
|
1237
|
-
return;
|
|
1238
|
-
await anchoredRemoveFile(location.parent, location.name);
|
|
1239
|
-
}
|
|
1240
|
-
function isLiveSameStorySetupLease(lease, storyId, nowIso) {
|
|
1241
|
-
return Boolean(lease?.ownerStoryId === storyId
|
|
1242
|
-
&& lease.sessionId === lease.idempotencyKey
|
|
1243
|
-
&& typeof lease.idempotencyKey === 'string'
|
|
1244
|
-
&& /^setup-[a-f0-9]{64}$/.test(lease.idempotencyKey)
|
|
1245
|
-
&& typeof lease.expiresAt === 'string'
|
|
1246
|
-
&& Date.parse(lease.expiresAt) > Date.parse(nowIso));
|
|
1247
|
-
}
|
|
1248
|
-
async function setupHandoffTokenLocation(projectRoot, storyId) {
|
|
1249
|
-
const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
|
|
1250
|
-
const parent = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'handoffs');
|
|
1251
|
-
const name = `direct-${digest(storyId)}.json`;
|
|
1252
|
-
return { parent, name, path: join(parent, name) };
|
|
1253
|
-
}
|
|
1254
|
-
async function writeSetupHandoffTokenRecord(projectRoot, record) {
|
|
1255
|
-
const location = await setupHandoffTokenLocation(projectRoot, record.storyId);
|
|
1256
|
-
await anchoredAtomicWriteFile(location.parent, location.name, `${JSON.stringify(record, null, 2)}\n`);
|
|
1257
|
-
await assertGitLifecyclePrivateFile(location.path, location.parent);
|
|
1258
|
-
}
|
|
1259
|
-
async function readSetupHandoffTokenRecord(projectRoot, storyId) {
|
|
1260
|
-
try {
|
|
1261
|
-
const location = await setupHandoffTokenLocation(projectRoot, storyId);
|
|
1262
|
-
await assertGitLifecyclePrivateFile(location.path, location.parent);
|
|
1263
|
-
const item = JSON.parse(await readFile(location.path, 'utf8'));
|
|
1264
|
-
const exactKeys = item.state === 'issued'
|
|
1265
|
-
? ['schemaVersion', 'kind', 'state', 'storyId', 'fromSessionId', 'token', 'tokenDigest', 'bundleDigest', 'claimRevision', 'grantDigest', 'expiresAt']
|
|
1266
|
-
: item.state === 'consuming'
|
|
1267
|
-
? ['schemaVersion', 'kind', 'state', 'storyId', 'fromSessionId', 'token', 'tokenDigest', 'bundleDigest', 'claimRevision', 'grantDigest', 'expiresAt', 'consumedBySessionId', 'consumeStartedAt']
|
|
1268
|
-
: ['schemaVersion', 'kind', 'state', 'storyId', 'fromSessionId', 'tokenDigest', 'bundleDigest', 'claimRevision', 'grantDigest', 'expiresAt', 'consumedBySessionId', 'consumedAt'];
|
|
1269
|
-
if (Object.keys(item).sort().join('\0') !== [...exactKeys].sort().join('\0')
|
|
1270
|
-
|| item.schemaVersion !== 1 || item.kind !== 'direct-yolo-setup-handoff-token'
|
|
1271
|
-
|| (item.state !== 'issued' && item.state !== 'consuming' && item.state !== 'consumed') || item.storyId !== storyId
|
|
1272
|
-
|| typeof item.fromSessionId !== 'string' || !/^setup-[a-f0-9]{64}$/.test(item.fromSessionId)
|
|
1273
|
-
|| ![item.tokenDigest, item.bundleDigest, item.claimRevision, item.grantDigest].every((value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
|
|
1274
|
-
|| typeof item.expiresAt !== 'string' || !Number.isFinite(Date.parse(item.expiresAt))
|
|
1275
|
-
|| (item.state === 'issued' || item.state === 'consuming')
|
|
1276
|
-
&& (typeof item.token !== 'string' || !/^[A-Za-z0-9_-]{32,256}$/.test(item.token))
|
|
1277
|
-
|| item.state === 'consuming' && (typeof item.consumedBySessionId !== 'string'
|
|
1278
|
-
|| !/^[a-f0-9]{64}$/.test(item.consumedBySessionId)
|
|
1279
|
-
|| typeof item.consumeStartedAt !== 'string' || !Number.isFinite(Date.parse(item.consumeStartedAt)))
|
|
1280
|
-
|| item.state === 'consumed' && (typeof item.consumedBySessionId !== 'string'
|
|
1281
|
-
|| !/^[a-f0-9]{64}$/.test(item.consumedBySessionId)
|
|
1282
|
-
|| typeof item.consumedAt !== 'string' || !Number.isFinite(Date.parse(item.consumedAt))))
|
|
1283
|
-
return undefined;
|
|
1284
|
-
return item;
|
|
1285
|
-
}
|
|
1286
|
-
catch {
|
|
1287
|
-
return undefined;
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
async function resolveIssuedSetupLeaseHandoff(projectRoot, storyId, bundleDigest, claimRevision, nowIso) {
|
|
1291
|
-
const record = await readSetupHandoffTokenRecord(projectRoot, storyId);
|
|
1292
|
-
if (!record || record.state === 'consumed' || !record.token
|
|
1293
|
-
|| record.bundleDigest !== bundleDigest || record.claimRevision !== claimRevision
|
|
1294
|
-
|| Date.parse(record.expiresAt) <= Date.parse(nowIso)
|
|
1295
|
-
|| digest(record.token) !== record.tokenDigest)
|
|
1296
|
-
return undefined;
|
|
1297
|
-
return { sessionId: record.fromSessionId, token: record.token };
|
|
1298
|
-
}
|
|
1299
|
-
async function markSetupHandoffTokenConsuming(projectRoot, storyId, fromSessionId, token, consumedBySessionId, consumeStartedAt) {
|
|
1300
|
-
const record = await readSetupHandoffTokenRecord(projectRoot, storyId);
|
|
1301
|
-
if (!record || record.state === 'consumed' || record.fromSessionId !== fromSessionId
|
|
1302
|
-
|| record.token !== token || record.tokenDigest !== digest(token)) {
|
|
1303
|
-
throw new Error('direct-yolo-setup-handoff-consume-invalid');
|
|
1304
|
-
}
|
|
1305
|
-
if (record.state === 'consuming') {
|
|
1306
|
-
if (record.consumedBySessionId !== consumedBySessionId) {
|
|
1307
|
-
throw new Error('direct-yolo-setup-handoff-consume-raced');
|
|
1308
|
-
}
|
|
1309
|
-
return;
|
|
1310
|
-
}
|
|
1311
|
-
await writeSetupHandoffTokenRecord(projectRoot, {
|
|
1312
|
-
...record,
|
|
1313
|
-
state: 'consuming',
|
|
1314
|
-
consumedBySessionId,
|
|
1315
|
-
consumeStartedAt,
|
|
1316
|
-
});
|
|
1317
|
-
}
|
|
1318
|
-
async function markSetupHandoffTokenConsumed(projectRoot, epicId, storyId, fromSessionId, token, bundleDigest, claimRevision, consumedBySessionId, consumedAt) {
|
|
1319
|
-
const record = await readSetupHandoffTokenRecord(projectRoot, storyId);
|
|
1320
|
-
if (record?.state === 'consumed' && record.fromSessionId === fromSessionId
|
|
1321
|
-
&& record.consumedBySessionId === consumedBySessionId)
|
|
1322
|
-
return;
|
|
1323
|
-
const runtime = await readGitLifecycleRuntime(projectRoot, { required: true });
|
|
1324
|
-
const lease = asRecord(runtime.epics[epicId]?.branch_lease);
|
|
1325
|
-
const consumption = asRecord(lease?.handoffConsumption);
|
|
1326
|
-
if (!record || record.state !== 'consuming' || record.fromSessionId !== fromSessionId
|
|
1327
|
-
|| record.token !== token || record.tokenDigest !== digest(token)
|
|
1328
|
-
|| record.bundleDigest !== bundleDigest || record.claimRevision !== claimRevision
|
|
1329
|
-
|| record.consumedBySessionId !== consumedBySessionId
|
|
1330
|
-
|| lease?.ownerStoryId !== storyId || lease.sessionId !== consumedBySessionId
|
|
1331
|
-
|| consumption?.kind !== 'direct-yolo-setup-handoff-consumption'
|
|
1332
|
-
|| consumption.state !== 'consumed' || consumption.fromSessionId !== fromSessionId
|
|
1333
|
-
|| consumption.tokenDigest !== record.tokenDigest || consumption.bundleDigest !== bundleDigest
|
|
1334
|
-
|| consumption.claimRevision !== claimRevision || consumption.consumedBySessionId !== consumedBySessionId) {
|
|
1335
|
-
throw new Error('direct-yolo-setup-handoff-consume-invalid');
|
|
1336
|
-
}
|
|
1337
|
-
try {
|
|
1338
|
-
await writeSetupHandoffTokenRecord(projectRoot, {
|
|
1339
|
-
schemaVersion: 1, kind: record.kind, state: 'consumed', storyId,
|
|
1340
|
-
fromSessionId, tokenDigest: record.tokenDigest, bundleDigest: record.bundleDigest,
|
|
1341
|
-
claimRevision: record.claimRevision, grantDigest: record.grantDigest, expiresAt: record.expiresAt,
|
|
1342
|
-
consumedBySessionId, consumedAt,
|
|
1343
|
-
});
|
|
1344
|
-
}
|
|
1345
|
-
catch {
|
|
1346
|
-
throw new Error('direct-yolo-setup-handoff-consume-persist-failed');
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
function validSetupLeaseHandoff(input) {
|
|
1350
|
-
const grant = asRecord(input.current?.handoffGrant);
|
|
1351
|
-
const token = input.handoff?.token;
|
|
1352
|
-
const tokenDigest = typeof token === 'string' && /^[A-Za-z0-9_-]{32,256}$/.test(token)
|
|
1353
|
-
? digest(token)
|
|
1354
|
-
: undefined;
|
|
1355
|
-
return Boolean(grant && tokenDigest && input.handoff
|
|
1356
|
-
&& input.handoff.sessionId === input.current?.sessionId
|
|
1357
|
-
&& grant.schemaVersion === 1
|
|
1358
|
-
&& grant.kind === 'direct-yolo-setup-handoff'
|
|
1359
|
-
&& grant.storyId === input.storyId
|
|
1360
|
-
&& grant.fromSessionId === input.current?.sessionId
|
|
1361
|
-
&& grant.bundleDigest === input.bundleDigest
|
|
1362
|
-
&& grant.claimRevision === input.claimRevision
|
|
1363
|
-
&& typeof grant.expiresAt === 'string'
|
|
1364
|
-
&& Date.parse(grant.expiresAt) > Date.parse(input.nowIso)
|
|
1365
|
-
&& typeof grant.tokenDigest === 'string'
|
|
1366
|
-
&& /^[a-f0-9]{64}$/.test(grant.tokenDigest)
|
|
1367
|
-
&& safeDigestEqual(grant.tokenDigest, tokenDigest));
|
|
1368
|
-
}
|
|
1369
|
-
function safeDigestEqual(left, right) {
|
|
1370
|
-
const leftBytes = Buffer.from(left, 'hex');
|
|
1371
|
-
const rightBytes = Buffer.from(right, 'hex');
|
|
1372
|
-
return leftBytes.length === 32 && rightBytes.length === 32 && timingSafeEqual(leftBytes, rightBytes);
|
|
1373
|
-
}
|
|
1374
|
-
function sameLease(left, right) {
|
|
1375
|
-
return Boolean(left && ['schemaVersion', 'ownerStoryId', 'sessionId', 'idempotencyKey', 'acquiredAt', 'expiresAt']
|
|
1376
|
-
.every((key) => left[key] === right[key]));
|
|
1377
|
-
}
|
|
1378
|
-
async function releaseOwnedDirectLease(projectRoot, epicId, expected) {
|
|
1379
|
-
await mutateGitLifecycleRuntime(projectRoot, (document) => {
|
|
1380
|
-
const epic = ensureRuntimeEpic(document, epicId);
|
|
1381
|
-
const current = asRecord(epic.branch_lease);
|
|
1382
|
-
if (sameLease(current, expected))
|
|
1383
|
-
epic.branch_lease = null;
|
|
1384
|
-
});
|
|
1385
|
-
}
|
|
1386
|
-
async function cleanupOwnedDirectAuthority(authority, storyId) {
|
|
1387
|
-
const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
|
|
1388
|
-
const lease = asRecord(runtime.epics[authority.epicId]?.branch_lease);
|
|
1389
|
-
if (!lease || lease.ownerStoryId !== storyId || !safeTokenValue(lease.sessionId)
|
|
1390
|
-
|| !safeTokenValue(lease.idempotencyKey) || !Number.isFinite(Date.parse(String(lease.acquiredAt)))
|
|
1391
|
-
|| !Number.isFinite(Date.parse(String(lease.expiresAt))))
|
|
1392
|
-
return;
|
|
1393
|
-
const physical = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
|
|
1394
|
-
kind: 'direct', storyId, sessionId: String(lease.sessionId), idempotencyKey: String(lease.idempotencyKey),
|
|
1395
|
-
createdAt: String(lease.acquiredAt), expiresAt: String(lease.expiresAt), persistent: true,
|
|
1396
|
-
});
|
|
1397
|
-
if (!physical.ok)
|
|
1398
|
-
return;
|
|
1399
|
-
const released = await releaseGitLifecyclePhysicalIntegrationLock(physical.path, physical.owner);
|
|
1400
|
-
if (released)
|
|
1401
|
-
await releaseOwnedDirectLease(authority.projectRoot, authority.epicId, lease);
|
|
1402
|
-
}
|
|
1403
|
-
async function runQa(options, projectRoot, headSha, graphRevision) {
|
|
1404
|
-
const transientAuthority = await executeP205TransientAuthority(projectRoot, {
|
|
1405
|
-
headSha,
|
|
1406
|
-
graphRevision,
|
|
1407
|
-
nowIso: options.nowIso,
|
|
1408
|
-
});
|
|
1409
|
-
await options.qaRunner?.({ projectRoot, storyId: options.storyId, headSha });
|
|
1410
|
-
const evidence = projectP205TransientExecutionEvidence(transientAuthority);
|
|
1411
|
-
if (!evidence)
|
|
1412
|
-
throw new Error('p205-transient-authority-invalid');
|
|
1413
|
-
return {
|
|
1414
|
-
contract: 'P205-CI-02', command: P205_COMPLETE_COMMAND,
|
|
1415
|
-
manifestDigest: evidence.manifestDigest, gateIds: evidence.gateIds,
|
|
1416
|
-
resultDigest: evidence.resultDigest, transientAuthority,
|
|
1417
|
-
};
|
|
1418
|
-
}
|
|
1419
|
-
async function physicalCheckoutUnchanged(projectRoot, executionBranch, headSha, committedPaths) {
|
|
1420
|
-
if (await git(projectRoot, ['rev-parse', 'HEAD']) !== headSha
|
|
1421
|
-
|| await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== executionBranch
|
|
1422
|
-
|| !(await gitExitOk(projectRoot, ['diff', '--cached', '--quiet'])))
|
|
1423
|
-
return false;
|
|
1424
|
-
return gitExitOk(projectRoot, ['diff', '--quiet', 'HEAD', '--', ...committedPaths]);
|
|
1425
|
-
}
|
|
1426
|
-
async function remoteHeadIsExact(projectRoot, remoteInput, branch, headSha) {
|
|
1427
|
-
const remote = safeRemote(remoteInput);
|
|
1428
|
-
const remoteHead = (await git(projectRoot, ['ls-remote', '--heads', remote, `refs/heads/${branch}`])).split(/\s+/)[0];
|
|
1429
|
-
return remoteHead === headSha;
|
|
1430
|
-
}
|
|
1431
|
-
function validateDirectWriteSet(paths, authorizedWriteSet, storyId, rootMemoryEffect) {
|
|
1432
|
-
if (paths.length === 0 || paths.some((path) => !safePath(path))) {
|
|
1433
|
-
return { ok: false, reasonCode: 'direct-yolo-write-set-invalid' };
|
|
1434
|
-
}
|
|
1435
|
-
const required = [
|
|
1436
|
-
'.neocortex/state.json', `docs/stories/${storyId}.story.md`,
|
|
1437
|
-
`.neocortex/stories/${storyId}/qa-gate-result.json`,
|
|
1438
|
-
`.neocortex/stories/${storyId}/validation-evidence.md`,
|
|
1439
|
-
`.neocortex/stories/${storyId}/review.md`,
|
|
1440
|
-
];
|
|
1441
|
-
if (!required.every((path) => paths.includes(path)) || !required.every((path) => authorizedWriteSet.includes(path))) {
|
|
1442
|
-
return { ok: false, reasonCode: 'direct-yolo-write-set-invalid' };
|
|
1443
|
-
}
|
|
1444
|
-
if (rootMemoryEffect && (rootMemoryEffect.storyId !== storyId
|
|
1445
|
-
|| rootMemoryEffect.childClaimRevision !== digest([...authorizedWriteSet].sort().join('\0')))) {
|
|
1446
|
-
return { ok: false, reasonCode: 'direct-yolo-root-memory-claim-mismatch' };
|
|
1447
|
-
}
|
|
1448
|
-
if (paths.some((path) => !authorizedWriteSet.includes(path) && !rootMemoryEffect?.files.some(file => file.path === path))) {
|
|
1449
|
-
return { ok: false, reasonCode: 'direct-yolo-write-set-unauthorized' };
|
|
1450
|
-
}
|
|
1451
|
-
return { ok: true };
|
|
1452
|
-
}
|
|
1453
|
-
function safePath(value) {
|
|
1454
|
-
return value.length > 0 && value.length <= 1024 && !value.startsWith('/') && !value.includes('\\')
|
|
1455
|
-
&& !value.split('/').includes('..') && !value.startsWith('.git/') && !value.includes('\0');
|
|
1456
|
-
}
|
|
1457
|
-
function safeTokenValue(value) {
|
|
1458
|
-
return typeof value === 'string' && value.length > 0 && value.length <= 512
|
|
1459
|
-
&& /^[A-Za-z0-9._:@/+\-=]+$/.test(value);
|
|
1460
|
-
}
|
|
1461
|
-
function safeRef(value) {
|
|
1462
|
-
return value.length > 0 && value.length <= 240 && !value.startsWith('-') && !/[\s~^:?*[\\]/.test(value) && !value.includes('..');
|
|
1463
|
-
}
|
|
1464
|
-
function safeRemote(value) {
|
|
1465
|
-
if (!/^[A-Za-z0-9._-]{1,128}$/.test(value))
|
|
1466
|
-
throw new Error('direct-yolo-remote-invalid');
|
|
1467
|
-
return value;
|
|
1468
|
-
}
|
|
1469
|
-
function digest(value) { return createHash('sha256').update(value).digest('hex'); }
|
|
1470
|
-
function splitNull(value) { return value.split('\0').filter(Boolean); }
|
|
1471
|
-
function normalizedTime(value) {
|
|
1472
|
-
return value && Number.isFinite(Date.parse(value)) ? new Date(Date.parse(value)).toISOString() : new Date().toISOString();
|
|
1473
|
-
}
|
|
1474
|
-
function asRecord(value) {
|
|
1475
|
-
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
1476
|
-
}
|
|
1477
|
-
function validExpiredSetupRecovery(value, runtimeRevision, currentLease, storyId, nowMs) {
|
|
1478
|
-
const expectedLease = asRecord(value.expectedLease);
|
|
1479
|
-
const sessionId = expectedLease?.sessionId;
|
|
1480
|
-
const expiry = Date.parse(String(expectedLease?.expiresAt ?? ''));
|
|
1481
|
-
return value.schemaVersion === 1
|
|
1482
|
-
&& Number.isSafeInteger(value.expectedRuntimeRevision)
|
|
1483
|
-
&& value.expectedRuntimeRevision === runtimeRevision
|
|
1484
|
-
&& Boolean(currentLease) && JSON.stringify(currentLease) === JSON.stringify(expectedLease)
|
|
1485
|
-
&& expectedLease?.schemaVersion === 1
|
|
1486
|
-
&& expectedLease.ownerStoryId === storyId
|
|
1487
|
-
&& typeof sessionId === 'string' && /^setup-[a-f0-9]{64}$/.test(sessionId)
|
|
1488
|
-
&& expectedLease.idempotencyKey === sessionId
|
|
1489
|
-
&& Number.isFinite(expiry) && expiry <= nowMs;
|
|
1490
|
-
}
|
|
1491
|
-
async function rollbackExpiredSetupRecoveryPhysical(projectRoot, recovery) {
|
|
1492
|
-
let branch = await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
1493
|
-
if (branch === recovery.executionBranch) {
|
|
1494
|
-
if (await git(projectRoot, ['rev-parse', 'HEAD']) !== recovery.originHead
|
|
1495
|
-
|| await checkoutPayload(projectRoot) !== recovery.checkoutBefore)
|
|
1496
|
-
return;
|
|
1497
|
-
await git(projectRoot, ['switch', recovery.originBranch]);
|
|
1498
|
-
branch = recovery.originBranch;
|
|
1499
|
-
}
|
|
1500
|
-
if (branch !== recovery.originBranch
|
|
1501
|
-
|| await git(projectRoot, ['rev-parse', 'HEAD']) !== recovery.originHead
|
|
1502
|
-
|| await checkoutPayload(projectRoot) !== recovery.checkoutBefore
|
|
1503
|
-
|| recovery.executionHead === recovery.originHead
|
|
1504
|
-
|| !(await gitExitOk(projectRoot, ['show-ref', '--verify', '--quiet', recovery.executionRef])))
|
|
1505
|
-
return;
|
|
1506
|
-
const executionHead = await git(projectRoot, ['rev-parse', recovery.executionRef]);
|
|
1507
|
-
if (executionHead === recovery.originHead) {
|
|
1508
|
-
await git(projectRoot, [
|
|
1509
|
-
'update-ref', recovery.executionRef, recovery.executionHead, recovery.originHead,
|
|
1510
|
-
]);
|
|
1511
|
-
}
|
|
1512
|
-
}
|
|
1513
|
-
function validOriginBinding(value, executionBranch, originBranch) {
|
|
1514
|
-
const item = asRecord(value);
|
|
1515
|
-
if (!item || item.schemaVersion !== 1 || item.originBranch !== originBranch
|
|
1516
|
-
|| item.executionBranch !== executionBranch || item.capturedFromCurrentCheckout !== true
|
|
1517
|
-
|| typeof item.originHeadSha !== 'string' || !/^[a-f0-9]{40,64}$/.test(item.originHeadSha)
|
|
1518
|
-
|| typeof item.capturedAt !== 'string' || !Number.isFinite(Date.parse(item.capturedAt)))
|
|
1519
|
-
return undefined;
|
|
1520
|
-
return item;
|
|
1521
|
-
}
|
|
1522
|
-
function setupReceipt(authority, binding, leaseExpiresAt, reused) {
|
|
1523
|
-
return Object.freeze({
|
|
1524
|
-
schemaVersion: 1, kind: 'direct-yolo-setup-receipt', storyId: authority.storyId,
|
|
1525
|
-
epicId: authority.epicId, executionBranch: authority.executionBranch, originBranch: authority.originBranch,
|
|
1526
|
-
originHeadSha: binding.originHeadSha, leaseExpiresAt, reused, publicSafe: true,
|
|
1527
|
-
});
|
|
1528
|
-
}
|
|
1529
|
-
async function checkoutPayload(projectRoot) {
|
|
1530
|
-
const untrackedPaths = splitNull(await gitRaw(projectRoot, [
|
|
1531
|
-
'ls-files', '--others', '--exclude-standard', '-z',
|
|
1532
|
-
])).sort();
|
|
1533
|
-
const untrackedBlobs = await Promise.all(untrackedPaths.map(async (path) => {
|
|
1534
|
-
if (!safePath(path))
|
|
1535
|
-
throw new Error('direct-yolo-checkout-payload-invalid');
|
|
1536
|
-
return `${path}\0${await git(projectRoot, ['hash-object', '--no-filters', '--', path])}`;
|
|
1537
|
-
}));
|
|
1538
|
-
return digest([
|
|
1539
|
-
await gitRaw(projectRoot, ['diff', '--cached', '--binary', '--full-index']),
|
|
1540
|
-
await gitRaw(projectRoot, ['diff', '--binary', '--full-index']),
|
|
1541
|
-
await gitRaw(projectRoot, ['status', '--porcelain=v1', '-z', '--untracked-files=all']),
|
|
1542
|
-
...untrackedBlobs,
|
|
1543
|
-
].join('\0'));
|
|
1544
|
-
}
|
|
1545
|
-
/** Physical observation for a private YOLO agent step; this is not actor attribution. */
|
|
1546
|
-
export async function captureDirectYoloCheckoutEvidence(projectRootInput) {
|
|
1547
|
-
const projectRoot = resolve(projectRootInput);
|
|
1548
|
-
const headSha = await git(projectRoot, ['rev-parse', 'HEAD']);
|
|
1549
|
-
const branch = await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
1550
|
-
const payloadDigest = await checkoutPayload(projectRoot);
|
|
1551
|
-
if (await git(projectRoot, ['rev-parse', 'HEAD']) !== headSha
|
|
1552
|
-
|| await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== branch) {
|
|
1553
|
-
throw new Error('direct-yolo-checkout-observation-raced');
|
|
1554
|
-
}
|
|
1555
|
-
return Object.freeze({ headSha, branch, payloadDigest });
|
|
1556
|
-
}
|
|
1557
|
-
async function worktreeBranches(projectRoot) {
|
|
1558
|
-
const records = [];
|
|
1559
|
-
let current;
|
|
1560
|
-
for (const line of (await gitRaw(projectRoot, ['worktree', 'list', '--porcelain'])).split('\n')) {
|
|
1561
|
-
if (line.startsWith('worktree ')) {
|
|
1562
|
-
current = { path: line.slice('worktree '.length) };
|
|
1563
|
-
records.push(current);
|
|
1564
|
-
}
|
|
1565
|
-
else if (current && line.startsWith('branch refs/heads/')) {
|
|
1566
|
-
current.branch = line.slice('branch refs/heads/'.length);
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
return records;
|
|
1570
|
-
}
|
|
1571
|
-
function publicReason(error, fallback) {
|
|
1572
|
-
if (error instanceof Error && error.message === 'git-lifecycle-runtime-revision-conflict') {
|
|
1573
|
-
return 'direct-yolo-runtime-revision-conflict';
|
|
1574
|
-
}
|
|
1575
|
-
return error instanceof Error && /^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(error.message) ? error.message : fallback;
|
|
1576
|
-
}
|
|
1577
|
-
function failure(reasonCode) { return { ok: false, reasonCode }; }
|
|
1578
|
-
async function git(cwd, args) {
|
|
1579
|
-
return String((await execFileAsync('git', [...args], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })).stdout).trim();
|
|
1580
|
-
}
|
|
1581
|
-
async function gitRaw(cwd, args) {
|
|
1582
|
-
return String((await execFileAsync('git', [...args], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })).stdout);
|
|
1583
|
-
}
|
|
1584
|
-
async function gitExitOk(cwd, args) {
|
|
1585
|
-
try {
|
|
1586
|
-
await execFileAsync('git', [...args], { cwd, maxBuffer: 8 * 1024 * 1024 });
|
|
1587
|
-
return true;
|
|
1588
|
-
}
|
|
1589
|
-
catch {
|
|
1590
|
-
return false;
|
|
1591
|
-
}
|
|
1592
|
-
}
|
|
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};
|