@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,2529 +1,8 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Durable runtime evidence for root-owned Git lifecycle operations.
|
|
3
|
-
*
|
|
4
|
-
|
|
5
|
-
*
|
|
6
|
-
|
|
7
|
-
*
|
|
8
|
-
*/
|
|
9
|
-
import { execFile, execFileSync } from 'node:child_process';
|
|
10
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
11
|
-
import { lstat, open, readFile, realpath, stat } from 'node:fs/promises';
|
|
12
|
-
import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
13
|
-
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
14
|
-
import { promisify } from 'node:util';
|
|
15
|
-
import { publicWriteSet } from '../../../shared/dist/yoloop/public-story-write-set.js';
|
|
16
|
-
import { isRootProjectMemoryEffect } from '../private-execution/shared-root-memory-types.js';
|
|
17
|
-
import { verifyRootMemoryPhysicalWriteSet } from '../private-execution/root-memory-git-evidence.js';
|
|
18
|
-
import { resolveBranchUnit, } from '../../../shared/dist/yoloop/branch-unit.js';
|
|
19
|
-
import { epicHeadReconciliationInputDigest, epicHeadReconciliationPathsDigest, epicHeadReconciliationRangeDigest, validateEpicHeadReconciliationReceipt, } from '../../../shared/dist/yoloop/epic-terminal-git.js';
|
|
20
|
-
import { anchoredAtomicWriteFile, anchoredCreateOwnedDirectory, anchoredEnsureDirectory, anchoredExecuteGit, anchoredExecuteNode, anchoredRemoveDirectory, anchoredRenameDirectory, } from './secure-filesystem-boundary.js';
|
|
21
|
-
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';
|
|
22
|
-
import { parseNeocortexTrailers, trailerValue } from './neocortex-trailers.js';
|
|
23
|
-
const execFileAsync = promisify(execFile);
|
|
24
|
-
export const GIT_LIFECYCLE_RUNTIME_DIRECTORY = 'neocortex-yoloop';
|
|
25
|
-
export const GIT_LIFECYCLE_RUNTIME_FILE = 'runtime.json';
|
|
26
|
-
export const P205_COMPLETE_COMMAND = 'node scripts/test-root.mjs --gate complete';
|
|
27
|
-
export const LEGACY_DIRECT_YOLO_RECOVERY_COMMITS = Object.freeze({
|
|
28
|
-
'P174.03.029264': '339141be7339a0edf55710cbccb6e6558f514792',
|
|
29
|
-
});
|
|
30
|
-
/**
|
|
31
|
-
* Exact immutable bindings for the seven P174 checkpoints predating P205-v2.
|
|
32
|
-
* This table is only an allowlist: every value is recomputed from Git and the
|
|
33
|
-
* independent QA/review receipts before a fresh aggregate P205 may migrate it.
|
|
34
|
-
*/
|
|
35
|
-
export const LEGACY_P174_CHECKPOINT_MIGRATIONS = Object.freeze({
|
|
36
|
-
'P174.03.811759': Object.freeze({ baseSha: '749c8fc732deaf26c81a8e08cc94b83c8cf0f5ba', headSha: '84162456d9cbe5000ffd0ed3eb3d0e88cfeba499', graphRevision: '60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445', effectiveClaimRevision: '11f54704f5007f6139159419cfd7781f908b1502e117365c6d84011384579ed2', commitBodyDigest: 'b4fc759a49765fd8c0b3d0f5d1c333c2a4bf28d324e83eedabb12f9530df3738', changedPathsDigest: '11f54704f5007f6139159419cfd7781f908b1502e117365c6d84011384579ed2', qaDigest: 'f1100775e21f5d0d990f77303a2a06d936908f016983e32a63316d81aee6b9fc', reviewDigest: '50400bbcddb6f02408837cf99077de5d3af8c84822ab23a8b5499c338af7103a' }),
|
|
37
|
-
'P174.03.685003': Object.freeze({ baseSha: '84162456d9cbe5000ffd0ed3eb3d0e88cfeba499', headSha: '272a7fee89e4b9324d35701df1c83b671fa96299', graphRevision: '60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445', effectiveClaimRevision: '6cc3c9033f1c4711dcbe3c676d1d7f9906614c7d6e95228e843d1c63cefbc641', commitBodyDigest: 'e97966e26ce3ba31d5951b9fdac67808c88c1fd8be7ec1e73982f3f1cc7ffd81', changedPathsDigest: '6cc3c9033f1c4711dcbe3c676d1d7f9906614c7d6e95228e843d1c63cefbc641', qaDigest: '7439329a93321f39fb6b0de0a41c22e58373a399f9048e362dff4ffa6f1a7d89', reviewDigest: '1b2d12262e84acf9da7d06149a0effb11274ebdc986affbfd47635b855ec7135' }),
|
|
38
|
-
'P174.03.029264': Object.freeze({ baseSha: '272a7fee89e4b9324d35701df1c83b671fa96299', headSha: '339141be7339a0edf55710cbccb6e6558f514792', graphRevision: '60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445', effectiveClaimRevision: '1053bb2baf487e38fa28d7e8cfb872c5c4da66802534ee226bbc2c7455a6a5ab', commitBodyDigest: '0f269a00dcd168a6f548ff10dfa667b193c948ac9c7211f5cb11a0561757c371', changedPathsDigest: '1053bb2baf487e38fa28d7e8cfb872c5c4da66802534ee226bbc2c7455a6a5ab', qaDigest: 'ef0fd2c6e216557825cd8521ccb2f9960a3af48f18e7a5ada441bee8bfda400b', reviewDigest: '372d0f4a2f32978c8b39f20167637b3917187edb75d49875e93200c4c5a19d0d' }),
|
|
39
|
-
'P174.03.913359': Object.freeze({ baseSha: '339141be7339a0edf55710cbccb6e6558f514792', headSha: '4ccc90b85c49b27f718090bf25bc452f1b84e5e3', graphRevision: '60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445', effectiveClaimRevision: '12b5cfba2667e8064309807776c1b323561dc8d853f9afe5f676007b8494b2b5', commitBodyDigest: '89a6653197509e75246a758d2706876b337770571a1cac47d9d85ec96c196459', changedPathsDigest: '12b5cfba2667e8064309807776c1b323561dc8d853f9afe5f676007b8494b2b5', qaDigest: 'c7d3762ad30e4f9356243df17a1dd7123cbf1b660808d68176f44d1cd5da6449', reviewDigest: 'e4ecf577e174fd66f31aa4a0113ab672ced16b12ee531f6831aa533795145ba1' }),
|
|
40
|
-
'P174.03.724350': Object.freeze({ baseSha: '4ccc90b85c49b27f718090bf25bc452f1b84e5e3', headSha: '568e9464fb086304146b9eb4594281f91302aef1', graphRevision: '60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445', effectiveClaimRevision: 'c8b8b6b96edf9cea78925e2f961bd74069d77af03783a5368b8ac8025bf1fefe', commitBodyDigest: 'b3032338bfcd6c9dc460e9426220a1966dedeff9968c4064fdd36a315560721b', changedPathsDigest: 'c8b8b6b96edf9cea78925e2f961bd74069d77af03783a5368b8ac8025bf1fefe', qaDigest: '91f2f5b00935b1b04bb5d400df500cbc97c412072078b713c6e5ba8fda669bd0', reviewDigest: '9bc92069d3b3a76cc8b02d339d432690258be1376464b69e152ed8fd3d682f05' }),
|
|
41
|
-
'P174.03.011976': Object.freeze({ baseSha: '568e9464fb086304146b9eb4594281f91302aef1', headSha: '195599b1a99a99a8416c4c26c9ab9990847338a4', graphRevision: '60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445', effectiveClaimRevision: '49b7f2a0a967b2ba4249615c6d08834445a60df95045352838808eb4d6743b21', commitBodyDigest: 'b8a28392fac663dd614b695a49c894b7cab116d45722a42850e3b24e2aaf36f4', changedPathsDigest: '49b7f2a0a967b2ba4249615c6d08834445a60df95045352838808eb4d6743b21', qaDigest: '6eb4459a7d80c4a268fc931297e8156ed2a320584f8775f0787d91b42c0929d4', reviewDigest: '98b21de29f7cceeec73da19000c6c144395cce6eb699c6a82dfab505d4ab7b44' }),
|
|
42
|
-
'P174.03.686659': Object.freeze({ baseSha: '195599b1a99a99a8416c4c26c9ab9990847338a4', headSha: '0db3681a5dad4e25ce37d967c636eb9d54915556', graphRevision: '60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445', effectiveClaimRevision: '5c0fdbf820d677c288981b6f73f7d2d9a04ce7f4713687f12a2e984705244b8e', commitBodyDigest: '143257f4018ad773afc0c7280bd8aab8786851a9c20b65f8110881ff54656839', changedPathsDigest: '5c0fdbf820d677c288981b6f73f7d2d9a04ce7f4713687f12a2e984705244b8e', qaDigest: '6303dbf473e2815a3671aeb2c25528d8daba484b92a5a40d1eea5215e1f6763e', reviewDigest: '1bd6695846ed9340c8677cfa9b573880532187aeee487efaaa70577a0c94e7f2' }),
|
|
43
|
-
});
|
|
44
|
-
const LEGACY_STORE_FILE = 'neocortex-yoloop-runtime.json';
|
|
45
|
-
const LOCK_DIRECTORY = 'runtime.lock';
|
|
46
|
-
export const STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS = 64;
|
|
47
|
-
export const STORY_WORKTREE_JOURNAL_MAX_ENTRIES = 256;
|
|
48
|
-
const TRANSIENT_P205_AUTHORITIES = new WeakMap();
|
|
49
|
-
const HEAD_RECONCILIATION_AUTHORITIES = new WeakMap();
|
|
50
|
-
const CONSUMED_TERMINAL_RELEASE_AUTHORITIES = new WeakSet();
|
|
51
|
-
export async function executeP205TransientAuthority(projectRoot, input) {
|
|
52
|
-
const authorities = await executeP205TransientAuthorities(projectRoot, {
|
|
53
|
-
headSha: input.headSha,
|
|
54
|
-
graphRevisions: [input.graphRevision],
|
|
55
|
-
...(input.nowIso !== undefined ? { nowIso: input.nowIso } : {}),
|
|
56
|
-
...(input.anchoredWorkspace !== undefined ? { anchoredWorkspace: input.anchoredWorkspace } : {}),
|
|
57
|
-
});
|
|
58
|
-
return authorities.get(input.graphRevision);
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Execute the physical P205 gate once for one immutable HEAD and mint a
|
|
62
|
-
* separate opaque authority for every historical graph epoch accepted at that
|
|
63
|
-
* HEAD. The graph revision remains part of each evidence digest; only the
|
|
64
|
-
* expensive, graph-independent command execution is shared.
|
|
65
|
-
*/
|
|
66
|
-
export async function executeP205TransientAuthorities(projectRoot, input) {
|
|
67
|
-
const graphRevisions = [...new Set(input.graphRevisions)];
|
|
68
|
-
if (!isSha(input.headSha) || graphRevisions.length === 0 || graphRevisions.some((value) => !isHash(value))) {
|
|
69
|
-
throw new Error('p205-transient-binding-invalid');
|
|
70
|
-
}
|
|
71
|
-
const anchor = input.anchoredWorkspace;
|
|
72
|
-
if (anchor && resolve(projectRoot) !== join(resolve(anchor.parent), anchor.name)) {
|
|
73
|
-
throw new Error('p205-transient-anchor-binding-invalid');
|
|
74
|
-
}
|
|
75
|
-
const runGit = async (args) => anchor
|
|
76
|
-
? (await anchoredExecuteGit(anchor.parent, anchor.name, anchor.identity, args)).toString('utf8')
|
|
77
|
-
: String((await execFileAsync('git', [...args], { cwd: projectRoot, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 })).stdout);
|
|
78
|
-
const readProducer = async () => {
|
|
79
|
-
if (anchor)
|
|
80
|
-
return JSON.parse((await anchoredExecuteNode(anchor.parent, anchor.name, anchor.identity, [
|
|
81
|
-
'-e', "const fs=require('node:fs');process.stdout.write(JSON.stringify({manifest:fs.readFileSync('config/release-gates.v2.json','utf8'),runner:fs.readFileSync('scripts/test-root.mjs','utf8')}));",
|
|
82
|
-
])).toString('utf8'));
|
|
83
|
-
return { manifest: await readFile(join(projectRoot, 'config', 'release-gates.v2.json'), 'utf8'),
|
|
84
|
-
runner: await readFile(join(projectRoot, 'scripts', 'test-root.mjs'), 'utf8') };
|
|
85
|
-
};
|
|
86
|
-
const beforeHead = (await runGit(['rev-parse', 'HEAD'])).trim();
|
|
87
|
-
if (beforeHead !== input.headSha)
|
|
88
|
-
throw new Error('p205-transient-head-mismatch');
|
|
89
|
-
const { manifest: manifestRaw, runner: runnerRaw } = await readProducer();
|
|
90
|
-
const [committedManifest, committedRunner] = await Promise.all([
|
|
91
|
-
runGit(['show', `${input.headSha}:config/release-gates.v2.json`]),
|
|
92
|
-
runGit(['show', `${input.headSha}:scripts/test-root.mjs`]),
|
|
93
|
-
]);
|
|
94
|
-
if (manifestRaw !== committedManifest || runnerRaw !== committedRunner) {
|
|
95
|
-
throw new Error('p205-transient-producer-dirty');
|
|
96
|
-
}
|
|
97
|
-
const manifest = JSON.parse(manifestRaw);
|
|
98
|
-
const gateIds = Array.isArray(manifest.requiredCompleteClasses)
|
|
99
|
-
? manifest.requiredCompleteClasses.filter((item) => typeof item === 'string' && /^[a-z0-9-]+$/.test(item))
|
|
100
|
-
: [];
|
|
101
|
-
if (manifest.contract !== 'P205-CI-02' || gateIds.length === 0)
|
|
102
|
-
throw new Error('p205-transient-manifest-invalid');
|
|
103
|
-
const gateEnv = { ...process.env };
|
|
104
|
-
delete gateEnv.NEOCORTEX_PROFILE_DIR;
|
|
105
|
-
const output = anchor
|
|
106
|
-
? (await anchoredExecuteNode(anchor.parent, anchor.name, anchor.identity, ['scripts/test-root.mjs', '--gate', 'complete'])).toString('utf8')
|
|
107
|
-
: String((await execFileAsync(process.execPath, ['scripts/test-root.mjs', '--gate', 'complete'], {
|
|
108
|
-
cwd: projectRoot, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, env: gateEnv,
|
|
109
|
-
})).stdout);
|
|
110
|
-
const { manifest: afterManifest, runner: afterRunner } = await readProducer();
|
|
111
|
-
if (afterManifest !== manifestRaw || afterRunner !== runnerRaw) {
|
|
112
|
-
throw new Error('p205-transient-producer-raced');
|
|
113
|
-
}
|
|
114
|
-
const afterHead = (await runGit(['rev-parse', 'HEAD'])).trim();
|
|
115
|
-
if (afterHead !== input.headSha)
|
|
116
|
-
throw new Error('p205-transient-head-raced');
|
|
117
|
-
const manifestDigest = createHash('sha256').update(manifestRaw).digest('hex');
|
|
118
|
-
const resultDigest = createHash('sha256').update(output).digest('hex');
|
|
119
|
-
const executedAt = normalizedIso(input.nowIso ?? new Date().toISOString());
|
|
120
|
-
const authorities = new Map();
|
|
121
|
-
const frozenGateIds = Object.freeze(gateIds);
|
|
122
|
-
for (const graphRevision of graphRevisions) {
|
|
123
|
-
const executionEvidenceDigest = createHash('sha256').update([
|
|
124
|
-
'p205-transient-execution-v1', P205_COMPLETE_COMMAND, input.headSha, graphRevision,
|
|
125
|
-
manifestDigest, gateIds.join(','), resultDigest, executedAt,
|
|
126
|
-
].join('\0')).digest('hex');
|
|
127
|
-
const evidence = Object.freeze({
|
|
128
|
-
schemaVersion: 1, kind: 'p205_transient_execution_authority',
|
|
129
|
-
contract: 'P205-CI-02', command: P205_COMPLETE_COMMAND,
|
|
130
|
-
executionHeadSha: input.headSha, graphRevision,
|
|
131
|
-
manifestDigest, gateIds: frozenGateIds, resultDigest, executedAt,
|
|
132
|
-
executionEvidenceDigest,
|
|
133
|
-
});
|
|
134
|
-
const authority = Object.freeze(Object.create(null));
|
|
135
|
-
TRANSIENT_P205_AUTHORITIES.set(authority, evidence);
|
|
136
|
-
authorities.set(graphRevision, authority);
|
|
137
|
-
}
|
|
138
|
-
return authorities;
|
|
139
|
-
}
|
|
140
|
-
export async function readGitLifecycleRuntime(projectRoot, options = {}) {
|
|
141
|
-
const storePath = await runtimeStorePath(projectRoot);
|
|
142
|
-
return readDocument(storePath, options);
|
|
143
|
-
}
|
|
144
|
-
export function readGitLifecycleRuntimeSync(projectRoot, options = {}) {
|
|
145
|
-
let path;
|
|
146
|
-
try {
|
|
147
|
-
const commonDir = execFileSync('git', ['rev-parse', '--git-common-dir'], {
|
|
148
|
-
cwd: projectRoot,
|
|
149
|
-
encoding: 'utf8',
|
|
150
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
151
|
-
}).trim();
|
|
152
|
-
const canonicalRoot = realpathSync(projectRoot);
|
|
153
|
-
const absolute = isAbsolute(commonDir) ? resolve(commonDir) : resolve(canonicalRoot, commonDir);
|
|
154
|
-
const canonicalCommonDir = realpathSync(absolute);
|
|
155
|
-
if (canonicalCommonDir !== absolute)
|
|
156
|
-
throw new Error('git-lifecycle-common-dir-symlink');
|
|
157
|
-
assertCommonDirectoryEntrySync(canonicalCommonDir);
|
|
158
|
-
const runtimeDirectory = join(canonicalCommonDir, GIT_LIFECYCLE_RUNTIME_DIRECTORY);
|
|
159
|
-
const currentPath = join(runtimeDirectory, GIT_LIFECYCLE_RUNTIME_FILE);
|
|
160
|
-
if (existsSync(runtimeDirectory)) {
|
|
161
|
-
assertSafeFilesystemEntrySync(runtimeDirectory, 'directory');
|
|
162
|
-
if (realpathSync(runtimeDirectory) !== runtimeDirectory)
|
|
163
|
-
throw new Error('git-lifecycle-runtime-directory-symlink');
|
|
164
|
-
}
|
|
165
|
-
path = existsSync(currentPath) ? currentPath : join(canonicalCommonDir, LEGACY_STORE_FILE);
|
|
166
|
-
}
|
|
167
|
-
catch {
|
|
168
|
-
if (options.required)
|
|
169
|
-
throw new Error('git-lifecycle-common-dir-invalid');
|
|
170
|
-
return emptyDocument();
|
|
171
|
-
}
|
|
172
|
-
if (!existsSync(path)) {
|
|
173
|
-
if (options.required)
|
|
174
|
-
throw new Error('git-lifecycle-runtime-missing');
|
|
175
|
-
return emptyDocument();
|
|
176
|
-
}
|
|
177
|
-
assertSafeFilesystemEntrySync(path, 'file');
|
|
178
|
-
return validateDocument(JSON.parse(readFileSync(path, 'utf8')));
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Materialize the private lifecycle sidecar for repositories that already
|
|
182
|
-
* declare the epic-branch contract in tracked state but predate the sidecar.
|
|
183
|
-
* Missing state is the only recoverable condition: corrupt, substituted or
|
|
184
|
-
* permission-unsafe paths continue to fail closed.
|
|
185
|
-
*/
|
|
186
|
-
export async function ensureGitLifecycleRuntimeInitialized(projectRoot) {
|
|
187
|
-
try {
|
|
188
|
-
await readGitLifecycleRuntime(projectRoot, { required: true });
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
catch (error) {
|
|
192
|
-
if (!(error instanceof Error) || error.message !== 'git-lifecycle-runtime-missing')
|
|
193
|
-
throw error;
|
|
194
|
-
}
|
|
195
|
-
try {
|
|
196
|
-
await mutateGitLifecycleRuntime(projectRoot, () => undefined, { expectedRevision: 0 });
|
|
197
|
-
}
|
|
198
|
-
catch (error) {
|
|
199
|
-
// Concurrent first-use initialization is idempotent. Accept only a proven
|
|
200
|
-
// winning document; every other filesystem or validation error propagates.
|
|
201
|
-
if (!(error instanceof Error) || error.message !== 'git-lifecycle-runtime-revision-conflict')
|
|
202
|
-
throw error;
|
|
203
|
-
await readGitLifecycleRuntime(projectRoot, { required: true });
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
function isLiveSameStorySetupLease(lease, storyId, nowMs) {
|
|
207
|
-
if (!lease || lease.ownerStoryId !== storyId)
|
|
208
|
-
return false;
|
|
209
|
-
const sessionId = typeof lease.sessionId === 'string' ? lease.sessionId : '';
|
|
210
|
-
const expiresAt = Date.parse(String(lease.expiresAt));
|
|
211
|
-
return /^setup-[a-f0-9]{64}$/.test(sessionId)
|
|
212
|
-
&& lease.idempotencyKey === sessionId
|
|
213
|
-
&& Number.isFinite(expiresAt)
|
|
214
|
-
&& expiresAt > nowMs;
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Close the server-plan -> client -> P207 sidecar handoff. The authority is
|
|
218
|
-
* accepted only for the exact tracked epic/story/branch projection that the
|
|
219
|
-
* server selected. A genuinely new epic may bootstrap its deterministic
|
|
220
|
-
* `epic/<ID>` unit into the private sidecar after the complete tracked topology
|
|
221
|
-
* proves there is no legacy story Git progress. Tracked-state drift, explicit
|
|
222
|
-
* lifecycle conflicts and sidecar revision races fail closed; no tracked,
|
|
223
|
-
* staged or working-tree bytes are modified.
|
|
224
|
-
*/
|
|
225
|
-
export async function persistGitLifecycleGraphAuthority(projectRoot, authority, nowIso = new Date().toISOString()) {
|
|
226
|
-
if (!isGitLifecycleGraphAuthority(authority))
|
|
227
|
-
throw new Error('git-lifecycle-graph-authority-invalid');
|
|
228
|
-
const trackedPath = join(resolve(projectRoot), '.neocortex', 'state.json');
|
|
229
|
-
const trackedRaw = await readFile(trackedPath, 'utf8');
|
|
230
|
-
const tracked = asRecord(JSON.parse(trackedRaw));
|
|
231
|
-
if (!tracked)
|
|
232
|
-
throw new Error('git-lifecycle-tracked-state-invalid');
|
|
233
|
-
// An absent sidecar is the normal first-use state for a new epic. Reading
|
|
234
|
-
// without `required` yields revision zero while corrupt/unsafe stores still
|
|
235
|
-
// fail closed. The authenticated authority mutation below materializes the
|
|
236
|
-
// sidecar only after every tracked-state invariant has passed.
|
|
237
|
-
const runtime = await readGitLifecycleRuntime(projectRoot);
|
|
238
|
-
const effective = applyGitLifecycleRuntimeOverlay(tracked, runtime);
|
|
239
|
-
const epic = asRecord(asRecord(effective.epics)?.[authority.epicId]);
|
|
240
|
-
const story = asRecord(asRecord(effective.stories)?.[authority.storyId]);
|
|
241
|
-
if (!epic)
|
|
242
|
-
throw new Error('git-lifecycle-graph-authority-epic-invalid');
|
|
243
|
-
if (!story || String(story.epic_id ?? authority.storyId.split('.')[0]) !== authority.epicId) {
|
|
244
|
-
throw new Error('git-lifecycle-graph-authority-story-invalid');
|
|
245
|
-
}
|
|
246
|
-
const declaredStoryIds = Array.isArray(epic.stories)
|
|
247
|
-
? epic.stories.filter((value) => typeof value === 'string')
|
|
248
|
-
: Object.keys(asRecord(effective.stories) ?? {}).filter((storyId) => {
|
|
249
|
-
const candidate = asRecord(asRecord(effective.stories)?.[storyId]);
|
|
250
|
-
return String(candidate?.epic_id ?? storyId.split('.')[0]) === authority.epicId;
|
|
251
|
-
});
|
|
252
|
-
if (Array.isArray(epic.stories) && !declaredStoryIds.includes(authority.storyId)) {
|
|
253
|
-
throw new Error('git-lifecycle-graph-authority-story-invalid');
|
|
254
|
-
}
|
|
255
|
-
const branchStories = declaredStoryIds.map((storyId) => {
|
|
256
|
-
const candidate = asRecord(asRecord(effective.stories)?.[storyId]) ?? {};
|
|
257
|
-
return {
|
|
258
|
-
id: storyId,
|
|
259
|
-
branch_name: typeof candidate.branch_name === 'string' || candidate.branch_name === null
|
|
260
|
-
? candidate.branch_name : undefined,
|
|
261
|
-
pr_number: typeof candidate.pr_number === 'number' || candidate.pr_number === null
|
|
262
|
-
? candidate.pr_number : undefined,
|
|
263
|
-
steps_completed: Array.isArray(candidate.steps_completed)
|
|
264
|
-
? candidate.steps_completed.filter((value) => typeof value === 'string') : [],
|
|
265
|
-
checkpoint: asRecord(candidate.checkpoint),
|
|
266
|
-
};
|
|
267
|
-
});
|
|
268
|
-
const branchUnit = resolveBranchUnit({ ...epic, id: authority.epicId }, branchStories);
|
|
269
|
-
if (branchUnit.mode !== 'epic')
|
|
270
|
-
throw new Error('git-lifecycle-graph-authority-epic-invalid');
|
|
271
|
-
if (branchUnit.executionBranch !== authority.executionBranch) {
|
|
272
|
-
throw new Error('git-lifecycle-graph-authority-branch-mismatch');
|
|
273
|
-
}
|
|
274
|
-
if (branchUnit.originBranch !== undefined && branchUnit.originBranch !== authority.originBranch) {
|
|
275
|
-
throw new Error('git-lifecycle-graph-authority-origin-mismatch');
|
|
276
|
-
}
|
|
277
|
-
const runtimeOriginBranch = typeof asRecord(runtime.epics[authority.epicId])?.origin_branch === 'string'
|
|
278
|
-
? String(asRecord(runtime.epics[authority.epicId]).origin_branch)
|
|
279
|
-
: undefined;
|
|
280
|
-
if (runtimeOriginBranch !== undefined && runtimeOriginBranch !== authority.originBranch) {
|
|
281
|
-
throw new Error('git-lifecycle-graph-authority-origin-mismatch');
|
|
282
|
-
}
|
|
283
|
-
// Bootstrap may capture the origin only from the physical checkout selected
|
|
284
|
-
// by the operator. Once recorded, later invocations can legitimately run on
|
|
285
|
-
// the epic execution branch and are bound by the persisted origin instead.
|
|
286
|
-
if (branchUnit.originBranch === undefined && runtimeOriginBranch === undefined) {
|
|
287
|
-
const { stdout } = await execFileAsync('git', ['branch', '--show-current'], {
|
|
288
|
-
cwd: projectRoot, encoding: 'utf8', maxBuffer: 1024 * 1024,
|
|
289
|
-
});
|
|
290
|
-
if (String(stdout).trim() !== authority.originBranch) {
|
|
291
|
-
throw new Error('git-lifecycle-graph-authority-origin-physical-mismatch');
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
const currentGraphRevision = typeof epic.graph_revision === 'string' ? epic.graph_revision : undefined;
|
|
295
|
-
const runtimeGraphRevision = typeof asRecord(runtime.epics[authority.epicId])?.graph_revision === 'string'
|
|
296
|
-
? String(asRecord(runtime.epics[authority.epicId]).graph_revision)
|
|
297
|
-
: undefined;
|
|
298
|
-
if (currentGraphRevision !== undefined && !isHash(currentGraphRevision)) {
|
|
299
|
-
throw new Error('git-lifecycle-graph-revision-invalid');
|
|
300
|
-
}
|
|
301
|
-
if (currentGraphRevision === authority.graphRevision && runtimeGraphRevision === authority.graphRevision
|
|
302
|
-
&& branchUnit.originBranch === authority.originBranch && runtimeOriginBranch === authority.originBranch) {
|
|
303
|
-
return { applied: false, reused: true, revision: runtime.revision, graphRevision: authority.graphRevision };
|
|
304
|
-
}
|
|
305
|
-
const nowMs = Date.parse(nowIso);
|
|
306
|
-
if (!Number.isFinite(nowMs))
|
|
307
|
-
throw new Error('git-lifecycle-graph-authority-time-invalid');
|
|
308
|
-
const lease = asRecord(epic.branch_lease);
|
|
309
|
-
if (lease && Number.isFinite(Date.parse(String(lease.expiresAt)))
|
|
310
|
-
&& Date.parse(String(lease.expiresAt)) > nowMs
|
|
311
|
-
&& !isLiveSameStorySetupLease(lease, authority.storyId, nowMs)) {
|
|
312
|
-
throw new Error('git-lifecycle-graph-authority-writer-active');
|
|
313
|
-
}
|
|
314
|
-
const mutation = await mutateGitLifecycleRuntime(projectRoot, (document) => {
|
|
315
|
-
const runtimeEpic = ensureRuntimeEpic(document, authority.epicId);
|
|
316
|
-
if (runtimeEpic.branch_mode !== undefined && runtimeEpic.branch_mode !== 'epic') {
|
|
317
|
-
throw new Error('git-lifecycle-graph-authority-epic-raced');
|
|
318
|
-
}
|
|
319
|
-
const persistedBranch = runtimeEpic.execution_branch;
|
|
320
|
-
if (persistedBranch !== undefined && persistedBranch !== authority.executionBranch) {
|
|
321
|
-
throw new Error('git-lifecycle-graph-authority-branch-raced');
|
|
322
|
-
}
|
|
323
|
-
const persistedOrigin = runtimeEpic.origin_branch;
|
|
324
|
-
if (persistedOrigin !== undefined && persistedOrigin !== authority.originBranch) {
|
|
325
|
-
throw new Error('git-lifecycle-graph-authority-origin-raced');
|
|
326
|
-
}
|
|
327
|
-
const persistedRevision = runtimeEpic.graph_revision;
|
|
328
|
-
if (persistedRevision !== undefined && persistedRevision !== currentGraphRevision) {
|
|
329
|
-
throw new Error('git-lifecycle-graph-authority-epoch-raced');
|
|
330
|
-
}
|
|
331
|
-
const persistedLease = asRecord(runtimeEpic.branch_lease);
|
|
332
|
-
if (persistedLease && Number.isFinite(Date.parse(String(persistedLease.expiresAt)))
|
|
333
|
-
&& Date.parse(String(persistedLease.expiresAt)) > nowMs
|
|
334
|
-
&& !isLiveSameStorySetupLease(persistedLease, authority.storyId, nowMs)) {
|
|
335
|
-
throw new Error('git-lifecycle-graph-authority-writer-active');
|
|
336
|
-
}
|
|
337
|
-
runtimeEpic.branch_mode = 'epic';
|
|
338
|
-
runtimeEpic.execution_branch = authority.executionBranch;
|
|
339
|
-
runtimeEpic.origin_branch = authority.originBranch;
|
|
340
|
-
runtimeEpic.graph_revision = authority.graphRevision;
|
|
341
|
-
}, {
|
|
342
|
-
expectedRevision: runtime.revision,
|
|
343
|
-
preCommit: async () => {
|
|
344
|
-
if (await readFile(trackedPath, 'utf8') !== trackedRaw) {
|
|
345
|
-
throw new Error('git-lifecycle-graph-authority-tracked-state-raced');
|
|
346
|
-
}
|
|
347
|
-
},
|
|
348
|
-
});
|
|
349
|
-
return {
|
|
350
|
-
applied: true,
|
|
351
|
-
reused: false,
|
|
352
|
-
revision: mutation.document.revision,
|
|
353
|
-
graphRevision: authority.graphRevision,
|
|
354
|
-
};
|
|
355
|
-
}
|
|
356
|
-
export async function mutateGitLifecycleRuntime(projectRoot, mutate, options = {}) {
|
|
357
|
-
const commonDir = await gitCommonDir(projectRoot);
|
|
358
|
-
const runtimeDirectory = await ensureRuntimeDirectory(commonDir);
|
|
359
|
-
const lockPath = join(runtimeDirectory, LOCK_DIRECTORY);
|
|
360
|
-
const lockOwner = await acquireLockWithBackoff(lockPath);
|
|
361
|
-
try {
|
|
362
|
-
const storePath = join(runtimeDirectory, GIT_LIFECYCLE_RUNTIME_FILE);
|
|
363
|
-
const legacyStorePath = join(commonDir, LEGACY_STORE_FILE);
|
|
364
|
-
const current = await readDocument(existsSync(storePath) ? storePath : legacyStorePath);
|
|
365
|
-
if (options.expectedRevision !== undefined && options.expectedRevision !== current.revision) {
|
|
366
|
-
throw new Error('git-lifecycle-runtime-revision-conflict');
|
|
367
|
-
}
|
|
368
|
-
const mutable = structuredClone(current);
|
|
369
|
-
const value = mutate(mutable);
|
|
370
|
-
if (current.schemaVersion === 2 && options.nextSchemaVersion !== undefined
|
|
371
|
-
&& options.nextSchemaVersion !== 2) {
|
|
372
|
-
throw new Error('git-lifecycle-runtime-schema-downgrade');
|
|
373
|
-
}
|
|
374
|
-
const next = validateDocument({
|
|
375
|
-
...mutable,
|
|
376
|
-
schemaVersion: options.nextSchemaVersion ?? current.schemaVersion,
|
|
377
|
-
revision: current.revision + 1,
|
|
378
|
-
});
|
|
379
|
-
await options.preCommit?.(next);
|
|
380
|
-
await assertSafeFilesystemEntry(runtimeDirectory, 'directory');
|
|
381
|
-
await assertStoreDestinationSafe(storePath);
|
|
382
|
-
await anchoredAtomicWriteFile(runtimeDirectory, GIT_LIFECYCLE_RUNTIME_FILE, `${JSON.stringify(next, null, 2)}\n`);
|
|
383
|
-
await assertSafeFilesystemEntry(storePath, 'file');
|
|
384
|
-
await syncDirectory(runtimeDirectory);
|
|
385
|
-
return { document: next, value };
|
|
386
|
-
}
|
|
387
|
-
finally {
|
|
388
|
-
await releaseRuntimeLock(lockPath, lockOwner).catch(() => undefined);
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
async function syncDirectory(path) {
|
|
392
|
-
let handle;
|
|
393
|
-
try {
|
|
394
|
-
handle = await open(path, 'r');
|
|
395
|
-
}
|
|
396
|
-
catch (error) {
|
|
397
|
-
// Node cannot open directories on Windows. The file itself has already
|
|
398
|
-
// been flushed; keep the stronger parent-directory flush everywhere else.
|
|
399
|
-
if (process.platform === 'win32' && (isNodeError(error, 'EPERM') || isNodeError(error, 'EISDIR') || isNodeError(error, 'EINVAL')))
|
|
400
|
-
return;
|
|
401
|
-
throw error;
|
|
402
|
-
}
|
|
403
|
-
try {
|
|
404
|
-
await handle.sync();
|
|
405
|
-
}
|
|
406
|
-
finally {
|
|
407
|
-
await handle.close();
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
/** Merge the runtime overlay over tracked state without mutating either input. */
|
|
411
|
-
export function applyGitLifecycleRuntimeOverlay(tracked, runtime) {
|
|
412
|
-
const merged = structuredClone(tracked);
|
|
413
|
-
const epics = normalizeTrackedCollection(merged, 'epics');
|
|
414
|
-
const stories = normalizeTrackedCollection(merged, 'stories');
|
|
415
|
-
for (const [epicId, overlay] of Object.entries(runtime.epics)) {
|
|
416
|
-
epics[epicId] = { ...(asRecord(epics[epicId]) ?? {}), ...structuredClone(overlay) };
|
|
417
|
-
}
|
|
418
|
-
for (const [storyId, overlay] of Object.entries(runtime.stories)) {
|
|
419
|
-
const trackedStory = asRecord(stories[storyId]) ?? {};
|
|
420
|
-
const trackedSteps = trackedStory.steps_completed;
|
|
421
|
-
const runtimeSteps = overlay.steps_completed;
|
|
422
|
-
const c01OnlyOverlay = overlay.status === 'branch-ready'
|
|
423
|
-
&& overlay.last_step === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
|
|
424
|
-
&& Array.isArray(runtimeSteps) && runtimeSteps.length === 1
|
|
425
|
-
&& runtimeSteps[0] === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
|
|
426
|
-
&& overlay.checkpoint === undefined;
|
|
427
|
-
// Once the tracked story includes C01, later tracked steps must not be
|
|
428
|
-
// masked by the private C01-only bridge used before the first commit.
|
|
429
|
-
if (c01OnlyOverlay && Array.isArray(trackedSteps)
|
|
430
|
-
&& trackedSteps.includes(GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID))
|
|
431
|
-
continue;
|
|
432
|
-
// 4.61.5: C01 instructs the child not to touch tracked state, so later
|
|
433
|
-
// tracked progress (C02..) arrives without C01. Union C01 into it instead
|
|
434
|
-
// of letting the C01-only bridge mask that progress.
|
|
435
|
-
if (c01OnlyOverlay && Array.isArray(trackedSteps) && trackedSteps.length > 0) {
|
|
436
|
-
stories[storyId] = {
|
|
437
|
-
...trackedStory,
|
|
438
|
-
steps_completed: [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID,
|
|
439
|
-
...trackedSteps.filter((step) => step !== GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID)],
|
|
440
|
-
};
|
|
441
|
-
continue;
|
|
442
|
-
}
|
|
443
|
-
stories[storyId] = { ...trackedStory, ...structuredClone(overlay) };
|
|
444
|
-
}
|
|
445
|
-
return merged;
|
|
446
|
-
}
|
|
447
|
-
/**
|
|
448
|
-
* Older project state used arrays while current consumers require records keyed
|
|
449
|
-
* by canonical IDs. Normalize only the in-memory projection and fail closed on
|
|
450
|
-
* ambiguous entries; the tracked document remains byte-for-byte untouched.
|
|
451
|
-
*/
|
|
452
|
-
function normalizeTrackedCollection(parent, key) {
|
|
453
|
-
const current = parent[key];
|
|
454
|
-
if (current === undefined) {
|
|
455
|
-
const created = {};
|
|
456
|
-
parent[key] = created;
|
|
457
|
-
return created;
|
|
458
|
-
}
|
|
459
|
-
const record = asRecord(current);
|
|
460
|
-
if (record)
|
|
461
|
-
return record;
|
|
462
|
-
if (!Array.isArray(current))
|
|
463
|
-
throw new Error(`git-lifecycle-tracked-${key}-invalid`);
|
|
464
|
-
const normalized = {};
|
|
465
|
-
for (const entry of current) {
|
|
466
|
-
const value = asRecord(entry);
|
|
467
|
-
const id = typeof value?.id === 'string' ? value.id.trim() : '';
|
|
468
|
-
if (!id || normalized[id] !== undefined)
|
|
469
|
-
throw new Error(`git-lifecycle-tracked-${key}-ambiguous`);
|
|
470
|
-
normalized[id] = value;
|
|
471
|
-
}
|
|
472
|
-
parent[key] = normalized;
|
|
473
|
-
return normalized;
|
|
474
|
-
}
|
|
475
|
-
/** Return (creating when absent) the mutable P225.05 story-worktree journal. */
|
|
476
|
-
export function ensureStoryWorktreeJournal(document) {
|
|
477
|
-
const mutable = document;
|
|
478
|
-
return mutable.storyWorktrees ?? (mutable.storyWorktrees = { schemaVersion: 1, entries: {}, cleanupReceipts: [] });
|
|
479
|
-
}
|
|
480
|
-
/** Drop an empty journal so documents return to their pre-P225.05 shape. */
|
|
481
|
-
export function compactStoryWorktreeJournal(document) {
|
|
482
|
-
const mutable = document;
|
|
483
|
-
const journal = mutable.storyWorktrees;
|
|
484
|
-
if (journal && Object.keys(journal.entries).length === 0 && journal.cleanupReceipts.length === 0) {
|
|
485
|
-
delete mutable.storyWorktrees;
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
const SWT_LEASE_ID = /^swt-[a-f0-9]{24}$/;
|
|
489
|
-
const SWT_HASH8 = /^[a-f0-9]{8}$/;
|
|
490
|
-
const SWT_SHA256 = /^[a-f0-9]{64}$/;
|
|
491
|
-
const SWT_GIT_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
492
|
-
const SWT_OPAQUE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;
|
|
493
|
-
const SWT_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;
|
|
494
|
-
const SWT_REASON = /^[a-z0-9][a-z0-9._-]{0,79}$/;
|
|
495
|
-
/**
|
|
496
|
-
* Closed P225-CON-RECEIPTS `cleanup-receipt` shape, checked locally so the
|
|
497
|
-
* published client closure needs no extra shared module. Tests prove parity
|
|
498
|
-
* with the shared `validateStoryWorktreeReceipt`.
|
|
499
|
-
*/
|
|
500
|
-
export function isStoryWorktreeCleanupReceiptRecord(value) {
|
|
501
|
-
const receipt = asRecord(value);
|
|
502
|
-
if (!receipt)
|
|
503
|
-
return false;
|
|
504
|
-
const required = [
|
|
505
|
-
'schemaVersion', 'kind', 'receiptId', 'epicId', 'storyId', 'leaseId', 'trigger',
|
|
506
|
-
'worktreeRemoved', 'localBranchRemoved', 'remoteBranchRemoved', 'cleanedAt',
|
|
507
|
-
];
|
|
508
|
-
const allowed = new Set([...required, 'preservedReasonCode']);
|
|
509
|
-
if (Object.keys(receipt).some((key) => !allowed.has(key)) || required.some((key) => receipt[key] === undefined))
|
|
510
|
-
return false;
|
|
511
|
-
return receipt.schemaVersion === 1 && receipt.kind === 'cleanup-receipt'
|
|
512
|
-
&& typeof receipt.receiptId === 'string' && SWT_OPAQUE.test(receipt.receiptId)
|
|
513
|
-
&& isCanonicalLifecycleId(receipt.epicId) && isCanonicalLifecycleId(receipt.storyId)
|
|
514
|
-
&& typeof receipt.leaseId === 'string' && SWT_OPAQUE.test(receipt.leaseId)
|
|
515
|
-
&& ['success', 'failure', 'abandon', 'orphan-recovery'].includes(String(receipt.trigger))
|
|
516
|
-
&& typeof receipt.worktreeRemoved === 'boolean' && typeof receipt.localBranchRemoved === 'boolean'
|
|
517
|
-
&& typeof receipt.remoteBranchRemoved === 'boolean'
|
|
518
|
-
&& typeof receipt.cleanedAt === 'string' && SWT_TIME.test(receipt.cleanedAt)
|
|
519
|
-
&& (receipt.preservedReasonCode === undefined
|
|
520
|
-
|| (typeof receipt.preservedReasonCode === 'string' && SWT_REASON.test(receipt.preservedReasonCode)));
|
|
521
|
-
}
|
|
522
|
-
export const STORY_WORKTREE_EVIDENCE_MAX_RECEIPTS = 512;
|
|
523
|
-
export const STORY_WORKTREE_EVIDENCE_MAX_SPEC_ACCEPTANCES = 256;
|
|
524
|
-
const SWT_RECEIPT_STORY_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
|
|
525
|
-
const SWT_RELATIVE_REF = /^[A-Za-z0-9._@#-][A-Za-z0-9._/@#-]{0,239}$/;
|
|
526
|
-
const SWT_RECEIPT_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
527
|
-
const SWT_URL_LIKE = /[A-Za-z][A-Za-z0-9+.-]*:\/\//;
|
|
528
|
-
const SWT_ABSOLUTE_LIKE = /^(?:\/|~[\\/]|[A-Za-z]:[\\/]|\\\\)/;
|
|
529
|
-
// Server-owned workflow step identifiers never ship in the published client
|
|
530
|
-
// (STEP_ID_IN_DIST boundary); receipts are compared through opaque SHA-256
|
|
531
|
-
// projections: the NUL-joined phase-one step sequence and the C04 barrier step.
|
|
532
|
-
const SWT_PHASE_ONE_STEPS_DIGEST = '18eafb8dbbdcb09db4e3988b2ba2c66f3ee1cf541fedda37077f2a74907232a8';
|
|
533
|
-
const SWT_PHASE_ONE_STEP_COUNT = 6;
|
|
534
|
-
const SWT_SPEC_BARRIER_STEP_DIGEST = '9cd927d02ff5979b5077e75b09cb34be275eca0e1c955403235b9ba0fb7a55eb';
|
|
535
|
-
function swtDigest(value) {
|
|
536
|
-
return createHash('sha256').update(value).digest('hex');
|
|
537
|
-
}
|
|
538
|
-
const SWT_EVIDENCE_RECEIPT_SCHEMAS = Object.freeze({
|
|
539
|
-
'phase-one-receipt': {
|
|
540
|
-
schemaVersion: { oneOf: [1] }, kind: { oneOf: ['phase-one-receipt'] }, receiptId: 'opaque', leaseId: 'opaque',
|
|
541
|
-
epicId: 'story', storyId: 'story', completedStepIds: 'stories', headSha: 'git-sha', specRef: 'ref',
|
|
542
|
-
specDigest: 'sha256', graphRevision: 'sha256', completedAt: 'time',
|
|
543
|
-
},
|
|
544
|
-
'spec-barrier-receipt': {
|
|
545
|
-
schemaVersion: { oneOf: [1] }, kind: { oneOf: ['spec-barrier-receipt'] }, receiptId: 'opaque', epicId: 'story',
|
|
546
|
-
stepId: { sha256Of: SWT_SPEC_BARRIER_STEP_DIGEST }, scope: { oneOf: ['epic'] }, storyIds: 'stories',
|
|
547
|
-
specDigests: 'digest-map', graphRevision: 'sha256', satisfiedAt: 'time',
|
|
548
|
-
},
|
|
549
|
-
'integration-receipt': {
|
|
550
|
-
schemaVersion: { oneOf: [1] }, kind: { oneOf: ['integration-receipt'] }, receiptId: 'opaque', epicId: 'story',
|
|
551
|
-
storyId: 'story', integrationOwner: { oneOf: ['root_agent'] }, integrationIndex: 'positive-int',
|
|
552
|
-
epicHeadBeforeSha: 'git-sha', epicHeadAfterSha: 'git-sha', checkpointDigest: 'sha256',
|
|
553
|
-
outcome: { oneOf: ['integrated', 'conflict-reopened'] }, reasonCode: 'reason', integratedAt: 'time',
|
|
554
|
-
},
|
|
555
|
-
});
|
|
556
|
-
function swtTimestamp(value) {
|
|
557
|
-
if (!SWT_RECEIPT_TIME.test(value) || !Number.isFinite(Date.parse(value)))
|
|
558
|
-
return false;
|
|
559
|
-
const [year, month, day, hour, minute, second] = value.slice(0, 19).split(/[-T:]/).map(Number);
|
|
560
|
-
const probe = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
|
|
561
|
-
return probe.getUTCFullYear() === year && probe.getUTCMonth() === month - 1 && probe.getUTCDate() === day
|
|
562
|
-
&& probe.getUTCHours() === hour && probe.getUTCMinutes() === minute && probe.getUTCSeconds() === second;
|
|
563
|
-
}
|
|
564
|
-
function swtStrings(value, depth = 0) {
|
|
565
|
-
if (depth > 4)
|
|
566
|
-
return false;
|
|
567
|
-
if (typeof value === 'string')
|
|
568
|
-
return !SWT_URL_LIKE.test(value) && !SWT_ABSOLUTE_LIKE.test(value);
|
|
569
|
-
if (Array.isArray(value))
|
|
570
|
-
return value.every((item) => swtStrings(item, depth + 1));
|
|
571
|
-
const record = asRecord(value);
|
|
572
|
-
return record ? Object.entries(record).every(([key, item]) => swtStrings(key, depth + 1) && swtStrings(item, depth + 1)) : true;
|
|
573
|
-
}
|
|
574
|
-
function swtField(rule, value) {
|
|
575
|
-
if (typeof rule === 'object') {
|
|
576
|
-
if ('sha256Of' in rule)
|
|
577
|
-
return typeof value === 'string' && value.length <= 80 && swtDigest(value) === rule.sha256Of;
|
|
578
|
-
return rule.oneOf.includes(value);
|
|
579
|
-
}
|
|
580
|
-
if (rule === 'positive-int')
|
|
581
|
-
return Number.isSafeInteger(value) && value >= 1;
|
|
582
|
-
if (rule === 'stories') {
|
|
583
|
-
return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length
|
|
584
|
-
&& value.every((item) => typeof item === 'string' && SWT_RECEIPT_STORY_ID.test(item) && !item.includes('..'));
|
|
585
|
-
}
|
|
586
|
-
if (rule === 'digest-map') {
|
|
587
|
-
const record = asRecord(value);
|
|
588
|
-
return Boolean(record) && Object.keys(record).length > 0 && Object.entries(record).every(([key, digest]) => SWT_RECEIPT_STORY_ID.test(key) && typeof digest === 'string' && SWT_SHA256.test(digest));
|
|
589
|
-
}
|
|
590
|
-
if (typeof value !== 'string')
|
|
591
|
-
return false;
|
|
592
|
-
switch (rule) {
|
|
593
|
-
case 'opaque': return SWT_OPAQUE.test(value);
|
|
594
|
-
case 'story': return SWT_RECEIPT_STORY_ID.test(value) && !value.includes('..');
|
|
595
|
-
case 'ref': {
|
|
596
|
-
const segments = value.split('/');
|
|
597
|
-
return SWT_RELATIVE_REF.test(value) && !value.endsWith('/') && segments.every((segment) => segment !== ''
|
|
598
|
-
&& segment !== '.' && segment !== '..' && !segment.startsWith('-') && segment.toLowerCase() !== '.git');
|
|
599
|
-
}
|
|
600
|
-
case 'sha256': return SWT_SHA256.test(value);
|
|
601
|
-
case 'git-sha': return SWT_GIT_SHA.test(value);
|
|
602
|
-
case 'time': return swtTimestamp(value);
|
|
603
|
-
case 'reason': return SWT_REASON.test(value);
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
/**
|
|
607
|
-
* Closed local validator for the P225-CON-RECEIPTS kinds the root persists in
|
|
608
|
-
* `story_worktree_evidence` (phase-one, spec-barrier, integration). Kept in the
|
|
609
|
-
* published client closure; tests prove parity with the shared validator.
|
|
610
|
-
*/
|
|
611
|
-
export function isStoryWorktreeEvidenceReceiptRecord(value) {
|
|
612
|
-
const receipt = asRecord(value);
|
|
613
|
-
if (!receipt || typeof receipt.kind !== 'string')
|
|
614
|
-
return false;
|
|
615
|
-
const schema = SWT_EVIDENCE_RECEIPT_SCHEMAS[receipt.kind];
|
|
616
|
-
if (!schema || !swtStrings(receipt))
|
|
617
|
-
return false;
|
|
618
|
-
const keys = Object.keys(receipt);
|
|
619
|
-
if (keys.length !== Object.keys(schema).length || keys.some((key) => !(key in schema)))
|
|
620
|
-
return false;
|
|
621
|
-
if (!Object.entries(schema).every(([field, rule]) => receipt[field] !== undefined && swtField(rule, receipt[field])))
|
|
622
|
-
return false;
|
|
623
|
-
if (receipt.kind === 'phase-one-receipt') {
|
|
624
|
-
const steps = receipt.completedStepIds;
|
|
625
|
-
return steps.length === SWT_PHASE_ONE_STEP_COUNT && swtDigest(steps.join('\0')) === SWT_PHASE_ONE_STEPS_DIGEST;
|
|
626
|
-
}
|
|
627
|
-
if (receipt.kind === 'spec-barrier-receipt') {
|
|
628
|
-
const digestKeys = Object.keys(receipt.specDigests);
|
|
629
|
-
const storyIds = receipt.storyIds;
|
|
630
|
-
return digestKeys.length === storyIds.length && storyIds.every((id) => digestKeys.includes(id));
|
|
631
|
-
}
|
|
632
|
-
return true;
|
|
633
|
-
}
|
|
634
|
-
/** True only for the closed `integration-receipt` shape. */
|
|
635
|
-
export function isStoryWorktreeIntegrationReceiptRecord(value) {
|
|
636
|
-
return asRecord(value)?.kind === 'integration-receipt' && isStoryWorktreeEvidenceReceiptRecord(value);
|
|
637
|
-
}
|
|
638
|
-
/** Closed validator for the `story_worktree_evidence` container (P225.04-ADR-3). */
|
|
639
|
-
export function isStoryWorktreeEvidenceContainer(value) {
|
|
640
|
-
return validateStoryWorktreeEvidenceContainer(value);
|
|
641
|
-
}
|
|
642
|
-
function validateStoryWorktreeEvidenceContainer(value) {
|
|
643
|
-
const container = asRecord(value);
|
|
644
|
-
if (!container)
|
|
645
|
-
return false;
|
|
646
|
-
const keys = Object.keys(container);
|
|
647
|
-
if (keys.some((key) => !['schemaVersion', 'specAcceptances', 'receipts'].includes(key)) || container.schemaVersion !== 1)
|
|
648
|
-
return false;
|
|
649
|
-
const acceptances = container.specAcceptances;
|
|
650
|
-
if (acceptances !== undefined && (!Array.isArray(acceptances) || acceptances.length > STORY_WORKTREE_EVIDENCE_MAX_SPEC_ACCEPTANCES
|
|
651
|
-
|| new Set(acceptances.map((item) => asRecord(item)?.storyId)).size !== acceptances.length
|
|
652
|
-
|| !acceptances.every((item) => {
|
|
653
|
-
const acceptance = asRecord(item);
|
|
654
|
-
return Boolean(acceptance) && Object.keys(acceptance).length === 3
|
|
655
|
-
&& isCanonicalLifecycleId(acceptance.storyId) && String(acceptance.storyId).includes('.')
|
|
656
|
-
&& typeof acceptance.specDigest === 'string' && SWT_SHA256.test(acceptance.specDigest)
|
|
657
|
-
&& typeof acceptance.graphRevision === 'string' && SWT_SHA256.test(acceptance.graphRevision);
|
|
658
|
-
})))
|
|
659
|
-
return false;
|
|
660
|
-
const receipts = container.receipts;
|
|
661
|
-
return receipts === undefined || (Array.isArray(receipts) && receipts.length <= STORY_WORKTREE_EVIDENCE_MAX_RECEIPTS
|
|
662
|
-
&& new Set(receipts.map((item) => asRecord(item)?.receiptId)).size === receipts.length
|
|
663
|
-
&& receipts.every(isStoryWorktreeEvidenceReceiptRecord));
|
|
664
|
-
}
|
|
665
|
-
/** Read (never create) the validated evidence container of one runtime epic overlay. */
|
|
666
|
-
export function readStoryWorktreeEvidence(document, epicId) {
|
|
667
|
-
const container = document.epics[epicId]?.story_worktree_evidence;
|
|
668
|
-
if (container === undefined || container === null)
|
|
669
|
-
return undefined;
|
|
670
|
-
if (!validateStoryWorktreeEvidenceContainer(container))
|
|
671
|
-
throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
|
|
672
|
-
return container;
|
|
673
|
-
}
|
|
674
|
-
/**
|
|
675
|
-
* Append server-returned or root-produced evidence to the mutable runtime
|
|
676
|
-
* document (call inside `mutateGitLifecycleRuntime`). Receipts dedupe by
|
|
677
|
-
* `receiptId` (identical bytes only); spec acceptances dedupe by `storyId`.
|
|
678
|
-
*/
|
|
679
|
-
export function appendStoryWorktreeEvidence(document, epicId, input) {
|
|
680
|
-
const current = readStoryWorktreeEvidence(document, epicId);
|
|
681
|
-
const receipts = [...(current?.receipts ?? [])];
|
|
682
|
-
const acceptances = [...(current?.specAcceptances ?? [])];
|
|
683
|
-
let appendedReceipts = 0;
|
|
684
|
-
let appendedSpecAcceptances = 0;
|
|
685
|
-
for (const receipt of input.receipts ?? []) {
|
|
686
|
-
const record = asRecord(receipt);
|
|
687
|
-
if (!isStoryWorktreeEvidenceReceiptRecord(record) || record.epicId !== epicId) {
|
|
688
|
-
throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
|
|
689
|
-
}
|
|
690
|
-
const existing = receipts.find((item) => item.receiptId === record.receiptId);
|
|
691
|
-
if (existing) {
|
|
692
|
-
if (JSON.stringify(existing) !== JSON.stringify(record))
|
|
693
|
-
throw new Error('git-lifecycle-runtime-story-worktree-evidence-conflict');
|
|
694
|
-
continue;
|
|
695
|
-
}
|
|
696
|
-
receipts.push(structuredClone(record));
|
|
697
|
-
appendedReceipts++;
|
|
698
|
-
}
|
|
699
|
-
for (const acceptance of input.specAcceptances ?? []) {
|
|
700
|
-
const record = asRecord(acceptance);
|
|
701
|
-
const normalized = record ? {
|
|
702
|
-
storyId: record.storyId, specDigest: record.specDigest, graphRevision: record.graphRevision,
|
|
703
|
-
} : undefined;
|
|
704
|
-
if (!normalized || Object.keys(record).length !== 3
|
|
705
|
-
|| !validateStoryWorktreeEvidenceContainer({ schemaVersion: 1, specAcceptances: [normalized] })) {
|
|
706
|
-
throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
|
|
707
|
-
}
|
|
708
|
-
const index = acceptances.findIndex((item) => item.storyId === normalized.storyId);
|
|
709
|
-
if (index >= 0 && JSON.stringify(acceptances[index]) === JSON.stringify(normalized))
|
|
710
|
-
continue;
|
|
711
|
-
if (index >= 0)
|
|
712
|
-
acceptances[index] = normalized;
|
|
713
|
-
else
|
|
714
|
-
acceptances.push(normalized);
|
|
715
|
-
appendedSpecAcceptances++;
|
|
716
|
-
}
|
|
717
|
-
const next = { schemaVersion: 1 };
|
|
718
|
-
if (acceptances.length > 0)
|
|
719
|
-
next.specAcceptances = acceptances;
|
|
720
|
-
if (receipts.length > 0)
|
|
721
|
-
next.receipts = receipts;
|
|
722
|
-
if (!validateStoryWorktreeEvidenceContainer(next))
|
|
723
|
-
throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
|
|
724
|
-
if (appendedReceipts > 0 || appendedSpecAcceptances > 0)
|
|
725
|
-
ensureRuntimeEpic(document, epicId).story_worktree_evidence = next;
|
|
726
|
-
return { appendedReceipts, appendedSpecAcceptances };
|
|
727
|
-
}
|
|
728
|
-
function validateStoryWorktreeJournal(value) {
|
|
729
|
-
const journal = asRecord(value);
|
|
730
|
-
if (!journal)
|
|
731
|
-
return false;
|
|
732
|
-
const keys = Object.keys(journal);
|
|
733
|
-
if (keys.length !== 3 || !keys.every((key) => ['schemaVersion', 'entries', 'cleanupReceipts'].includes(key)))
|
|
734
|
-
return false;
|
|
735
|
-
const entries = asRecord(journal.entries);
|
|
736
|
-
if (journal.schemaVersion !== 1 || !entries || !Array.isArray(journal.cleanupReceipts)
|
|
737
|
-
|| journal.cleanupReceipts.length > STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS
|
|
738
|
-
|| Object.keys(entries).length > STORY_WORKTREE_JOURNAL_MAX_ENTRIES
|
|
739
|
-
|| journal.cleanupReceipts.some((receipt) => !isStoryWorktreeCleanupReceiptRecord(receipt)))
|
|
740
|
-
return false;
|
|
741
|
-
return Object.entries(entries).every(([leaseId, entry]) => validateStoryWorktreeJournalEntry(leaseId, entry));
|
|
742
|
-
}
|
|
743
|
-
function validateStoryWorktreeJournalEntry(leaseId, value) {
|
|
744
|
-
const entry = asRecord(value);
|
|
745
|
-
if (!entry)
|
|
746
|
-
return false;
|
|
747
|
-
const required = [
|
|
748
|
-
'schemaVersion', 'leaseId', 'epicId', 'storyId', 'dispatchDigest', 'hash8', 'executionBranch',
|
|
749
|
-
'temporaryBranch', 'worktreeRef', 'worktreePath', 'workspaceMechanism', 'ownerId', 'nonceDigest',
|
|
750
|
-
'baseSha', 'graphRevision', 'state', 'acquiredAt', 'expiresAt',
|
|
751
|
-
];
|
|
752
|
-
const allowed = new Set([...required, 'syncedSha']);
|
|
753
|
-
if (Object.keys(entry).some((key) => !allowed.has(key)) || required.some((key) => entry[key] === undefined))
|
|
754
|
-
return false;
|
|
755
|
-
const epicId = entry.epicId;
|
|
756
|
-
const hash8 = entry.hash8;
|
|
757
|
-
return entry.schemaVersion === 1
|
|
758
|
-
&& entry.leaseId === leaseId && SWT_LEASE_ID.test(leaseId)
|
|
759
|
-
&& isCanonicalLifecycleId(epicId) && !String(epicId).includes('.')
|
|
760
|
-
&& isCanonicalLifecycleId(entry.storyId) && String(entry.storyId).startsWith(`${String(epicId)}.`)
|
|
761
|
-
&& typeof entry.dispatchDigest === 'string' && SWT_SHA256.test(entry.dispatchDigest)
|
|
762
|
-
&& typeof hash8 === 'string' && SWT_HASH8.test(hash8)
|
|
763
|
-
&& entry.executionBranch === `epic/${String(epicId)}`
|
|
764
|
-
&& typeof entry.temporaryBranch === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(entry.temporaryBranch)
|
|
765
|
-
&& !entry.temporaryBranch.includes('..') && entry.temporaryBranch !== entry.executionBranch
|
|
766
|
-
&& entry.worktreeRef === `wt/${hash8}`
|
|
767
|
-
&& typeof entry.worktreePath === 'string' && entry.worktreePath.length <= 4096
|
|
768
|
-
&& (isAbsolute(entry.worktreePath) || /^[A-Za-z]:[\\/]/.test(entry.worktreePath))
|
|
769
|
-
&& (entry.workspaceMechanism === 'client_managed_worktree' || entry.workspaceMechanism === 'native_subagent_worktree')
|
|
770
|
-
&& typeof entry.ownerId === 'string' && SWT_OPAQUE.test(entry.ownerId)
|
|
771
|
-
&& typeof entry.nonceDigest === 'string' && SWT_SHA256.test(entry.nonceDigest)
|
|
772
|
-
&& typeof entry.baseSha === 'string' && SWT_GIT_SHA.test(entry.baseSha)
|
|
773
|
-
&& typeof entry.graphRevision === 'string' && SWT_SHA256.test(entry.graphRevision)
|
|
774
|
-
&& (entry.state === 'creating' || entry.state === 'active')
|
|
775
|
-
&& typeof entry.acquiredAt === 'string' && SWT_TIME.test(entry.acquiredAt)
|
|
776
|
-
&& typeof entry.expiresAt === 'string' && SWT_TIME.test(entry.expiresAt)
|
|
777
|
-
&& (entry.syncedSha === undefined || (typeof entry.syncedSha === 'string' && SWT_GIT_SHA.test(entry.syncedSha)));
|
|
778
|
-
}
|
|
779
|
-
export function ensureRuntimeEpic(document, epicId) {
|
|
780
|
-
return document.epics[epicId] ?? (document.epics[epicId] = {});
|
|
781
|
-
}
|
|
782
|
-
export function ensureRuntimeStory(document, storyId) {
|
|
783
|
-
return document.stories[storyId] ?? (document.stories[storyId] = {});
|
|
784
|
-
}
|
|
785
|
-
/** Runtime-safe accepted-checkpoint predicate kept in the published client closure. */
|
|
786
|
-
export function isAcceptedGitLifecycleStoryCheckpoint(value, storyId, epicId, executionBranch) {
|
|
787
|
-
const item = asRecord(value);
|
|
788
|
-
return Boolean(item && item.epicId === epicId && item.branch === executionBranch
|
|
789
|
-
&& item.qaVerdict === 'passed' && item.reviewVerdict === 'approved'
|
|
790
|
-
&& validateCheckpoint(item, storyId));
|
|
791
|
-
}
|
|
792
|
-
/**
|
|
793
|
-
* Structural JSON is untrusted under a same-UID threat model. Recompute the
|
|
794
|
-
* commit-range/review authority from Git before a checkpoint can authorize
|
|
795
|
-
* aggregate QA or terminal integration.
|
|
796
|
-
*/
|
|
797
|
-
export async function verifyAcceptedGitLifecycleStoryCheckpoint(projectRoot, value, storyId, epicId, executionBranch, transientAuthority, authorizedWriteSet = []) {
|
|
798
|
-
return verifyAcceptedGitLifecycleStoryCheckpointSync(projectRoot, value, storyId, epicId, executionBranch, transientAuthority, authorizedWriteSet).verdict === 'verified';
|
|
799
|
-
}
|
|
800
|
-
/**
|
|
801
|
-
* Synchronous variant used at the state-snapshot boundary, before any runtime
|
|
802
|
-
* overlay is sent to the server. It returns a fresh, public, Git-derived receipt.
|
|
803
|
-
*/
|
|
804
|
-
export function verifyAcceptedGitLifecycleStoryCheckpointSync(projectRoot, value, storyId, epicId, executionBranch, transientAuthority, authorizedWriteSet = [], nowIso = new Date().toISOString(), mode = transientAuthority === undefined ? 'scheduling' : 'integration') {
|
|
805
|
-
const rejected = () => checkpointVerification({
|
|
806
|
-
storyId, epicId, executionBranch, value, verifiedAt: nowIso,
|
|
807
|
-
verdict: 'rejected', reasonCode: 'checkpoint-git-physical-invalid',
|
|
808
|
-
});
|
|
809
|
-
try {
|
|
810
|
-
if (!isAcceptedGitLifecycleStoryCheckpoint(value, storyId, epicId, executionBranch))
|
|
811
|
-
return rejected();
|
|
812
|
-
const checkpoint = asRecord(value);
|
|
813
|
-
const qa = asRecord(checkpoint.qaReceipt);
|
|
814
|
-
const review = asRecord(checkpoint.reviewReceipt);
|
|
815
|
-
const headSha = String(checkpoint.headSha);
|
|
816
|
-
const baseSha = String(checkpoint.baseSha);
|
|
817
|
-
const publicReview = publicStoryReviewArtifactFromGit(projectRoot, storyId, headSha, review.reviewArtifactDigest === undefined);
|
|
818
|
-
const legacyWithoutPublicArtifact = review.reviewArtifactDigest === undefined
|
|
819
|
-
&& !publicStoryReviewBlobExistsInGit(projectRoot, storyId, headSha);
|
|
820
|
-
if (review.reviewArtifactDigest !== undefined && review.reviewArtifactDigest !== publicReview?.digest)
|
|
821
|
-
return rejected();
|
|
822
|
-
const branchHead = gitSync(projectRoot, ['rev-parse', `refs/heads/${executionBranch}`]).trim();
|
|
823
|
-
execFileSync('git', ['merge-base', '--is-ancestor', headSha, branchHead], { cwd: projectRoot, stdio: 'ignore' });
|
|
824
|
-
const historicalReviewPending = !legacyWithoutPublicArtifact && publicReview?.verdict !== 'approved';
|
|
825
|
-
if (historicalReviewPending) {
|
|
826
|
-
if (review.reviewArtifactDigest !== undefined || !verifyHistoricalReviewReconciliation(projectRoot, checkpoint, review, qa, storyId, epicId, branchHead))
|
|
827
|
-
return rejected();
|
|
828
|
-
}
|
|
829
|
-
else if (checkpoint.reviewReconciliation !== undefined) {
|
|
830
|
-
// A supplemental receipt cannot replace or shadow an already approved blob.
|
|
831
|
-
return rejected();
|
|
832
|
-
}
|
|
833
|
-
const commitBody = gitSync(projectRoot, ['show', '--no-patch', '--format=%H%n%P%n%B', headSha]);
|
|
834
|
-
const parentSha = gitSync(projectRoot, ['rev-parse', `${headSha}^`]).trim();
|
|
835
|
-
const commitCount = gitSync(projectRoot, ['rev-list', '--count', `${baseSha}..${headSha}`]).trim();
|
|
836
|
-
if (parentSha !== baseSha || commitCount !== '1')
|
|
837
|
-
return rejected();
|
|
838
|
-
// Same single-valued parser as the direct C08 finalizer: identical repeated
|
|
839
|
-
// lines collapse, a checkpoint key with two different values is ambiguous.
|
|
840
|
-
const parsedTrailers = parseNeocortexTrailers(commitBody);
|
|
841
|
-
if (!parsedTrailers.ok)
|
|
842
|
-
return rejected();
|
|
843
|
-
const trailers = parsedTrailers.values;
|
|
844
|
-
const reviewTrailer = trailerValue(trailers, 'Neocortex-Review-Artifact-Digest');
|
|
845
|
-
if (reviewTrailer !== undefined && (reviewTrailer !== publicReview?.digest
|
|
846
|
-
|| review.reviewArtifactDigest !== publicReview?.digest))
|
|
847
|
-
return rejected();
|
|
848
|
-
const requiredTrailers = [
|
|
849
|
-
['Neocortex-Story', storyId],
|
|
850
|
-
['Neocortex-Epic', epicId],
|
|
851
|
-
['Neocortex-Execution-Branch', executionBranch],
|
|
852
|
-
['Neocortex-Bundle-Digest', String(checkpoint.bundleDigest)],
|
|
853
|
-
['Neocortex-Graph-Revision', String(checkpoint.graphRevision)],
|
|
854
|
-
...(checkpoint.dispatchId ? [['Neocortex-Dispatch', String(checkpoint.dispatchId)]] : []),
|
|
855
|
-
...(checkpoint.bundleId ? [['Neocortex-Bundle', String(checkpoint.bundleId)]] : []),
|
|
856
|
-
...(checkpoint.claimRevision ? [['Neocortex-Claim-Revision', String(checkpoint.claimRevision)]] : []),
|
|
857
|
-
];
|
|
858
|
-
const hasCanonicalTrailers = requiredTrailers.every(([key, value]) => trailerValue(trailers, key) === value);
|
|
859
|
-
if (hasCanonicalTrailers) {
|
|
860
|
-
const preparedBase = trailerValue(trailers, 'Neocortex-Prepared-Base') ?? '';
|
|
861
|
-
if (!/^[a-f0-9]{40,64}$/i.test(preparedBase))
|
|
862
|
-
return rejected();
|
|
863
|
-
execFileSync('git', ['merge-base', '--is-ancestor', preparedBase, headSha], { cwd: projectRoot, stdio: 'ignore' });
|
|
864
|
-
}
|
|
865
|
-
const changedRaw = gitSync(projectRoot, [
|
|
866
|
-
'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', headSha,
|
|
867
|
-
]);
|
|
868
|
-
const changedPaths = changedRaw.split('\0').filter(Boolean);
|
|
869
|
-
if (changedPaths.length === 0 || changedPaths.some((path) => !safeRepositoryPath(path)))
|
|
870
|
-
return rejected();
|
|
871
|
-
const commitBodyDigest = createHash('sha256').update(commitBody).digest('hex');
|
|
872
|
-
const changedPathsDigest = createHash('sha256').update([...changedPaths].sort().join('\0')).digest('hex');
|
|
873
|
-
const claimProof = checkpointClaimProof({
|
|
874
|
-
projectRoot, checkpoint, storyId, epicId, executionBranch, baseSha, headSha,
|
|
875
|
-
commitBodyDigest, changedPathsDigest, changedPaths,
|
|
876
|
-
authorizedWriteSet: authorizedWriteSet.length > 0
|
|
877
|
-
? authorizedWriteSet : trackedStoryWriteSet(projectRoot, storyId),
|
|
878
|
-
});
|
|
879
|
-
if (!claimProof)
|
|
880
|
-
return rejected();
|
|
881
|
-
if (qa.receiptRef !== `story-qa:${String(qa.sourceEvidenceDigest)}`)
|
|
882
|
-
return rejected();
|
|
883
|
-
const expectedQaDigest = computeImmutableStoryQaEvidenceDigest({
|
|
884
|
-
storyId, baseSha, headSha,
|
|
885
|
-
bundleDigest: String(checkpoint.bundleDigest), graphRevision: String(checkpoint.graphRevision),
|
|
886
|
-
commitBody, changedPaths,
|
|
887
|
-
});
|
|
888
|
-
const executionQa = qa.evidenceVersion === 'p205-execution-v2'
|
|
889
|
-
&& qa.contract === 'P205-CI-02'
|
|
890
|
-
&& qa.command === P205_COMPLETE_COMMAND
|
|
891
|
-
&& isHash(qa.manifestDigest)
|
|
892
|
-
&& safeStringArray(qa.gateIds, 32, true)
|
|
893
|
-
&& isHash(qa.resultDigest)
|
|
894
|
-
&& qa.sourceEvidenceDigest === computeP205StoryQaEvidenceDigest({
|
|
895
|
-
gitEvidenceDigest: expectedQaDigest,
|
|
896
|
-
headSha,
|
|
897
|
-
graphRevision: String(checkpoint.graphRevision),
|
|
898
|
-
manifestDigest: String(qa.manifestDigest),
|
|
899
|
-
gateIds: qa.gateIds,
|
|
900
|
-
resultDigest: String(qa.resultDigest),
|
|
901
|
-
});
|
|
902
|
-
const immutableQa = qa.evidenceVersion === 'git-immutable-v1'
|
|
903
|
-
&& qa.sourceEvidenceDigest === expectedQaDigest;
|
|
904
|
-
const boundedLegacyQa = qa.evidenceVersion === undefined
|
|
905
|
-
&& claimProof.mode === 'legacy-migration'
|
|
906
|
-
&& claimProof.binding?.qaDigest === qa.sourceEvidenceDigest;
|
|
907
|
-
const aggregateP205 = transientP205AuthorityMatches(transientAuthority, branchHead, String(checkpoint.graphRevision));
|
|
908
|
-
const transientQa = aggregateP205 && (executionQa
|
|
909
|
-
|| claimProof.mode === 'legacy-migration' && (immutableQa || boundedLegacyQa));
|
|
910
|
-
const schedulingQa = mode === 'scheduling' && transientAuthority === undefined && executionQa;
|
|
911
|
-
if (!transientQa && !schedulingQa)
|
|
912
|
-
return rejected();
|
|
913
|
-
const artifactBound = review.reviewArtifactDigest !== undefined;
|
|
914
|
-
const expectedReviewDigest = createHash('sha256').update([
|
|
915
|
-
artifactBound ? 'root-commit-range-review-v2' : 'root-commit-range-review-v1', storyId, baseSha, headSha,
|
|
916
|
-
String(checkpoint.bundleDigest), String(checkpoint.graphRevision), String(qa.receiptRef),
|
|
917
|
-
createHash('sha256').update(commitBody).digest('hex'), [...changedPaths].sort().join(','),
|
|
918
|
-
...(artifactBound ? [publicReview.digest] : []),
|
|
919
|
-
].join('\0')).digest('hex');
|
|
920
|
-
if (review.sourceEvidenceDigest !== expectedReviewDigest
|
|
921
|
-
|| review.receiptRef !== `story-review:${expectedReviewDigest}`)
|
|
922
|
-
return rejected();
|
|
923
|
-
if (claimProof.mode === 'legacy-migration'
|
|
924
|
-
&& claimProof.binding?.reviewDigest !== undefined
|
|
925
|
-
&& claimProof.binding.reviewDigest !== review.sourceEvidenceDigest)
|
|
926
|
-
return rejected();
|
|
927
|
-
if (!hasCanonicalTrailers) {
|
|
928
|
-
if (LEGACY_DIRECT_YOLO_RECOVERY_COMMITS[storyId] !== headSha
|
|
929
|
-
|| !Array.isArray(checkpoint.receiptRefs)
|
|
930
|
-
|| !checkpoint.receiptRefs.some((item) => typeof item === 'string' && item.startsWith('legacy-direct-yolo:'))) {
|
|
931
|
-
return rejected();
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
const sourceEvidenceDigest = createHash('sha256').update([
|
|
935
|
-
'checkpoint-p205-transient-v1', storyId, epicId, executionBranch, baseSha, headSha,
|
|
936
|
-
String(checkpoint.bundleDigest), commitBodyDigest, changedPathsDigest,
|
|
937
|
-
claimProof.mode, claimProof.effectiveClaimRevision,
|
|
938
|
-
String(qa.sourceEvidenceDigest), String(review.sourceEvidenceDigest),
|
|
939
|
-
...(checkpoint.reviewReconciliation
|
|
940
|
-
? [String(asRecord(checkpoint.reviewReconciliation)?.sourceEvidenceDigest)] : []),
|
|
941
|
-
transientAuthorityEvidence(transientAuthority)?.executionEvidenceDigest
|
|
942
|
-
?? (schedulingQa ? 'scheduling-git-verification' : 'legacy-bounded-authority'),
|
|
943
|
-
].join('\0')).digest('hex');
|
|
944
|
-
const effectiveAuthority = transientQa ? transientAuthorityEvidence(transientAuthority) : undefined;
|
|
945
|
-
return Object.freeze({
|
|
946
|
-
schemaVersion: 1, kind: 'story_checkpoint_physical_verification', producer: 'client-p205-transient-v1',
|
|
947
|
-
storyId, epicId, branch: executionBranch, baseSha, headSha,
|
|
948
|
-
aggregateHeadSha: effectiveAuthority?.executionHeadSha ?? headSha,
|
|
949
|
-
commitBodyDigest, changedPathsDigest,
|
|
950
|
-
claimVerification: claimProof.mode,
|
|
951
|
-
effectiveClaimRevision: claimProof.effectiveClaimRevision,
|
|
952
|
-
sourceEvidenceDigest,
|
|
953
|
-
command: P205_COMPLETE_COMMAND,
|
|
954
|
-
manifestDigest: effectiveAuthority?.manifestDigest ?? '0'.repeat(64),
|
|
955
|
-
gateIds: effectiveAuthority?.gateIds ?? Object.freeze(['legacy-bounded']),
|
|
956
|
-
resultDigest: effectiveAuthority?.resultDigest ?? '0'.repeat(64),
|
|
957
|
-
graphRevision: String(checkpoint.graphRevision),
|
|
958
|
-
executionEvidenceDigest: effectiveAuthority?.executionEvidenceDigest ?? '0'.repeat(64),
|
|
959
|
-
verifiedAt: effectiveAuthority?.executedAt ?? normalizedIso(nowIso), verdict: 'verified',
|
|
960
|
-
reasonCodes: Object.freeze([
|
|
961
|
-
transientQa ? 'checkpoint-p205-transient-verified'
|
|
962
|
-
: schedulingQa ? 'checkpoint-git-scheduling-verified'
|
|
963
|
-
: 'checkpoint-legacy-bounded-verified',
|
|
964
|
-
...(claimProof.mode === 'legacy-migration' ? ['checkpoint-legacy-migration-verified'] : []),
|
|
965
|
-
]), publicSafe: true,
|
|
966
|
-
});
|
|
967
|
-
}
|
|
968
|
-
catch {
|
|
969
|
-
return rejected();
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
/**
|
|
973
|
-
* Classify a checkpoint for one story without allowing physical scheduling
|
|
974
|
-
* evidence to impersonate transient P205 integration authority.
|
|
975
|
-
*/
|
|
976
|
-
export function classifyGitLifecycleStoryCheckpointProjectionSync(projectRoot, value, storyId, epicId, executionBranch, transientAuthority, authorizedWriteSet = [], nowIso = new Date().toISOString()) {
|
|
977
|
-
const mode = transientAuthority ? 'integration' : 'scheduling';
|
|
978
|
-
const verification = verifyAcceptedGitLifecycleStoryCheckpointSync(projectRoot, value, storyId, epicId, executionBranch, transientAuthority, authorizedWriteSet, nowIso, mode);
|
|
979
|
-
if (verification.verdict !== 'verified')
|
|
980
|
-
return { kind: 'rejected', verification };
|
|
981
|
-
if (mode === 'integration')
|
|
982
|
-
return { kind: 'integration-authorized', verification };
|
|
983
|
-
if (!verification.reasonCodes.includes('checkpoint-git-scheduling-verified')) {
|
|
984
|
-
return { kind: 'rejected', verification: checkpointVerification({
|
|
985
|
-
storyId, epicId, executionBranch, value, verifiedAt: nowIso,
|
|
986
|
-
verdict: 'rejected', reasonCode: 'checkpoint-git-physical-invalid',
|
|
987
|
-
}) };
|
|
988
|
-
}
|
|
989
|
-
return {
|
|
990
|
-
kind: 'scheduling-only',
|
|
991
|
-
evidence: Object.freeze({
|
|
992
|
-
schemaVersion: 1,
|
|
993
|
-
kind: 'story_scheduling_checkpoint_evidence',
|
|
994
|
-
producer: 'client-git-physical-v1',
|
|
995
|
-
storyId,
|
|
996
|
-
epicId,
|
|
997
|
-
branch: executionBranch,
|
|
998
|
-
baseSha: verification.baseSha,
|
|
999
|
-
headSha: verification.headSha,
|
|
1000
|
-
graphRevision: verification.graphRevision,
|
|
1001
|
-
effectiveClaimRevision: verification.effectiveClaimRevision,
|
|
1002
|
-
sourceEvidenceDigest: verification.sourceEvidenceDigest,
|
|
1003
|
-
verifiedAt: verification.verifiedAt,
|
|
1004
|
-
reasonCodes: Object.freeze(['checkpoint-git-scheduling-verified']),
|
|
1005
|
-
integrationAuthorized: false,
|
|
1006
|
-
publicSafe: true,
|
|
1007
|
-
}),
|
|
1008
|
-
};
|
|
1009
|
-
}
|
|
1010
|
-
function transientP205AuthorityMatches(authority, aggregateHeadSha, graphRevision) {
|
|
1011
|
-
const evidence = transientAuthorityEvidence(authority);
|
|
1012
|
-
return Boolean(evidence
|
|
1013
|
-
&& evidence.schemaVersion === 1 && evidence.kind === 'p205_transient_execution_authority'
|
|
1014
|
-
&& evidence.contract === 'P205-CI-02' && evidence.command === P205_COMPLETE_COMMAND
|
|
1015
|
-
&& evidence.graphRevision === graphRevision
|
|
1016
|
-
&& isHash(evidence.resultDigest) && isHash(evidence.executionEvidenceDigest)
|
|
1017
|
-
&& evidence.executionHeadSha === aggregateHeadSha && isSha(aggregateHeadSha));
|
|
1018
|
-
}
|
|
1019
|
-
function transientAuthorityEvidence(authority) {
|
|
1020
|
-
return authority && typeof authority === 'object' ? TRANSIENT_P205_AUTHORITIES.get(authority) : undefined;
|
|
1021
|
-
}
|
|
1022
|
-
/** Read-only projection for persistence/audit; it never recreates authority. */
|
|
1023
|
-
export function projectP205TransientExecutionEvidence(authority) {
|
|
1024
|
-
const evidence = transientAuthorityEvidence(authority);
|
|
1025
|
-
return evidence ? Object.freeze({
|
|
1026
|
-
executionHeadSha: evidence.executionHeadSha,
|
|
1027
|
-
graphRevision: evidence.graphRevision,
|
|
1028
|
-
manifestDigest: evidence.manifestDigest,
|
|
1029
|
-
gateIds: Object.freeze([...evidence.gateIds]),
|
|
1030
|
-
resultDigest: evidence.resultDigest,
|
|
1031
|
-
executedAt: evidence.executedAt,
|
|
1032
|
-
executionEvidenceDigest: evidence.executionEvidenceDigest,
|
|
1033
|
-
}) : undefined;
|
|
1034
|
-
}
|
|
1035
|
-
export function p205TransientAuthorityMatchesAggregate(authority, headSha, graphRevision) {
|
|
1036
|
-
const evidence = transientAuthorityEvidence(authority);
|
|
1037
|
-
return Boolean(evidence && evidence.executionHeadSha === headSha
|
|
1038
|
-
&& evidence.graphRevision === graphRevision && evidence.command === P205_COMPLETE_COMMAND);
|
|
1039
|
-
}
|
|
1040
|
-
/**
|
|
1041
|
-
* Reopen a persisted reconciliation receipt from physical Git and mint a
|
|
1042
|
-
* process-local, one-shot terminal capability. This path never runs P205 and
|
|
1043
|
-
* never creates an aggregate PASS; it only renews admissibility for identical
|
|
1044
|
-
* immutable inputs.
|
|
1045
|
-
*/
|
|
1046
|
-
export async function revalidateEpicHeadReconciliationAuthority(projectRoot, receipt, aggregateQaReceipt, nowIso = new Date().toISOString()) {
|
|
1047
|
-
const tracked = JSON.parse(readFileSync(join(projectRoot, '.neocortex', 'state.json'), 'utf8'));
|
|
1048
|
-
const runtime = readGitLifecycleRuntimeSync(projectRoot, { required: true });
|
|
1049
|
-
const effective = applyGitLifecycleRuntimeOverlay(tracked, runtime);
|
|
1050
|
-
const epics = asRecord(effective.epics);
|
|
1051
|
-
const stories = asRecord(effective.stories);
|
|
1052
|
-
const epic = asRecord(epics?.[receipt.epicId]);
|
|
1053
|
-
const originBinding = asRecord(epic?.origin_binding);
|
|
1054
|
-
const persistedAggregate = asRecord(epic?.aggregate_qa_receipt);
|
|
1055
|
-
if (!epic || !stories || epic.branch_mode !== 'epic'
|
|
1056
|
-
|| epic.execution_branch !== receipt.executionBranch || epic.origin_branch !== receipt.originBranch
|
|
1057
|
-
|| epic.graph_revision !== receipt.graphRevision
|
|
1058
|
-
|| !originBinding || originBinding.originHeadSha !== receipt.originHeadSha
|
|
1059
|
-
|| originBinding.originBranch !== receipt.originBranch || originBinding.executionBranch !== receipt.executionBranch
|
|
1060
|
-
|| !persistedAggregate || persistedAggregate.receiptRef !== aggregateQaReceipt.receiptRef
|
|
1061
|
-
|| persistedAggregate.executionHeadSha !== aggregateQaReceipt.executionHeadSha
|
|
1062
|
-
|| persistedAggregate.graphRevision !== aggregateQaReceipt.graphRevision
|
|
1063
|
-
|| persistedAggregate.manifestDigest !== aggregateQaReceipt.manifestDigest
|
|
1064
|
-
|| persistedAggregate.resultDigest !== aggregateQaReceipt.resultDigest) {
|
|
1065
|
-
throw new Error('epic-head-reconciliation-state-drift');
|
|
1066
|
-
}
|
|
1067
|
-
const branch = gitSync(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']).trim();
|
|
1068
|
-
const head = gitSync(projectRoot, ['rev-parse', 'HEAD']).trim();
|
|
1069
|
-
if (branch !== receipt.executionBranch || head !== receipt.executionHeadSha) {
|
|
1070
|
-
throw new Error('epic-head-reconciliation-head-raced');
|
|
1071
|
-
}
|
|
1072
|
-
execFileSync('git', ['cat-file', '-e', `${receipt.originHeadSha}^{commit}`], { cwd: projectRoot, stdio: 'ignore' });
|
|
1073
|
-
execFileSync('git', ['merge-base', '--is-ancestor', receipt.originHeadSha, head], { cwd: projectRoot, stdio: 'ignore' });
|
|
1074
|
-
const acceptedIds = Array.isArray(epic.stories)
|
|
1075
|
-
? epic.stories.filter((item) => typeof item === 'string')
|
|
1076
|
-
: Object.keys(stories).filter((storyId) => storyId.startsWith(`${receipt.epicId}.`));
|
|
1077
|
-
const acceptedHeads = [];
|
|
1078
|
-
const allowedWriteSet = new Set();
|
|
1079
|
-
for (const storyId of acceptedIds) {
|
|
1080
|
-
const story = asRecord(stories[storyId]);
|
|
1081
|
-
const checkpoint = asRecord(story?.checkpoint);
|
|
1082
|
-
if (!story || !checkpoint)
|
|
1083
|
-
throw new Error('epic-head-reconciliation-checkpoint-drift');
|
|
1084
|
-
const decision = classifyGitLifecycleStoryCheckpointProjectionSync(projectRoot, checkpoint, storyId, receipt.epicId, receipt.executionBranch, undefined, gitLifecycleStoryWriteSet(storyId, story, checkpoint), nowIso);
|
|
1085
|
-
if (decision.kind !== 'scheduling-only')
|
|
1086
|
-
throw new Error('epic-head-reconciliation-checkpoint-drift');
|
|
1087
|
-
acceptedHeads.push(String(checkpoint.headSha));
|
|
1088
|
-
for (const scope of gitLifecycleStoryWriteSet(storyId, story, checkpoint))
|
|
1089
|
-
allowedWriteSet.add(scope);
|
|
1090
|
-
}
|
|
1091
|
-
const lastCheckpointHead = acceptedHeads.at(-1);
|
|
1092
|
-
if (!lastCheckpointHead || lastCheckpointHead !== receipt.lastAcceptedCheckpointHeadSha) {
|
|
1093
|
-
throw new Error('epic-head-reconciliation-checkpoint-drift');
|
|
1094
|
-
}
|
|
1095
|
-
execFileSync('git', ['merge-base', '--is-ancestor', lastCheckpointHead, head], { cwd: projectRoot, stdio: 'ignore' });
|
|
1096
|
-
const commits = gitSync(projectRoot, ['rev-list', '--first-parent', '--reverse', `${lastCheckpointHead}..${head}`])
|
|
1097
|
-
.trim().split('\n').filter(Boolean);
|
|
1098
|
-
const changedPaths = gitSync(projectRoot, ['diff', '--name-only', '-z', `${lastCheckpointHead}..${head}`])
|
|
1099
|
-
.split('\0').filter(Boolean).sort();
|
|
1100
|
-
const sortedWriteSet = [...allowedWriteSet].sort();
|
|
1101
|
-
const core = Object.freeze({
|
|
1102
|
-
...receipt,
|
|
1103
|
-
revalidatedAt: normalizedIso(nowIso),
|
|
1104
|
-
inputDigest: undefined,
|
|
1105
|
-
});
|
|
1106
|
-
const { inputDigest: _ignored, ...receiptCore } = core;
|
|
1107
|
-
const renewed = Object.freeze({
|
|
1108
|
-
...receiptCore,
|
|
1109
|
-
inputDigest: epicHeadReconciliationInputDigest(receiptCore),
|
|
1110
|
-
});
|
|
1111
|
-
if (!sameOrdered(acceptedIds, renewed.acceptedCheckpointIds)
|
|
1112
|
-
|| !sameOrdered(acceptedHeads, renewed.acceptedCheckpointHeads)
|
|
1113
|
-
|| !sameOrdered(commits, renewed.reconciliationCommitShas)
|
|
1114
|
-
|| !sameOrdered(changedPaths, renewed.changedPaths)
|
|
1115
|
-
|| !sameOrdered(sortedWriteSet, renewed.allowedWriteSet)
|
|
1116
|
-
|| !validateEpicHeadReconciliationReceipt(renewed, {
|
|
1117
|
-
epicId: receipt.epicId,
|
|
1118
|
-
executionBranch: receipt.executionBranch,
|
|
1119
|
-
originBranch: receipt.originBranch,
|
|
1120
|
-
graphRevision: receipt.graphRevision,
|
|
1121
|
-
originHeadSha: receipt.originHeadSha,
|
|
1122
|
-
executionHeadSha: head,
|
|
1123
|
-
acceptedCheckpointIds: acceptedIds,
|
|
1124
|
-
acceptedCheckpointHeads: acceptedHeads,
|
|
1125
|
-
aggregateQaReceipt,
|
|
1126
|
-
nowIso,
|
|
1127
|
-
}))
|
|
1128
|
-
throw new Error('epic-head-reconciliation-physical-invalid');
|
|
1129
|
-
await mutateGitLifecycleRuntime(projectRoot, (document) => {
|
|
1130
|
-
const runtimeEpic = ensureRuntimeEpic(document, receipt.epicId);
|
|
1131
|
-
const current = runtimeEpic.head_reconciliation_receipt;
|
|
1132
|
-
if (!current || current.inputDigest !== receipt.inputDigest) {
|
|
1133
|
-
throw new Error('epic-head-reconciliation-cas-conflict');
|
|
1134
|
-
}
|
|
1135
|
-
runtimeEpic.head_reconciliation_receipt = renewed;
|
|
1136
|
-
}, {
|
|
1137
|
-
expectedRevision: runtime.revision,
|
|
1138
|
-
preCommit: async () => {
|
|
1139
|
-
if (gitSync(projectRoot, ['rev-parse', 'HEAD']).trim() !== head
|
|
1140
|
-
|| gitSync(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']).trim() !== branch) {
|
|
1141
|
-
throw new Error('epic-head-reconciliation-head-raced');
|
|
1142
|
-
}
|
|
1143
|
-
},
|
|
1144
|
-
});
|
|
1145
|
-
const authority = Object.freeze(Object.create(null));
|
|
1146
|
-
HEAD_RECONCILIATION_AUTHORITIES.set(authority, Object.freeze({
|
|
1147
|
-
executionHeadSha: head,
|
|
1148
|
-
graphRevision: receipt.graphRevision,
|
|
1149
|
-
aggregateReceiptRef: aggregateQaReceipt.receiptRef,
|
|
1150
|
-
reconciliationInputDigest: renewed.inputDigest,
|
|
1151
|
-
}));
|
|
1152
|
-
return Object.freeze({ authority, receipt: renewed });
|
|
1153
|
-
}
|
|
1154
|
-
/** Consume one exact terminal authority. Serialized objects and replays fail. */
|
|
1155
|
-
export function consumeEpicTerminalReleaseAuthority(authority, input) {
|
|
1156
|
-
if (!authority || typeof authority !== 'object')
|
|
1157
|
-
return false;
|
|
1158
|
-
if (CONSUMED_TERMINAL_RELEASE_AUTHORITIES.has(authority))
|
|
1159
|
-
return false;
|
|
1160
|
-
const p205 = TRANSIENT_P205_AUTHORITIES.get(authority);
|
|
1161
|
-
const reconciliation = HEAD_RECONCILIATION_AUTHORITIES.get(authority);
|
|
1162
|
-
const p205Valid = Boolean(p205 && p205.executionHeadSha === input.executionHeadSha && p205.graphRevision === input.graphRevision
|
|
1163
|
-
&& p205.manifestDigest === input.aggregateQaReceipt.manifestDigest
|
|
1164
|
-
&& p205.resultDigest === input.aggregateQaReceipt.resultDigest
|
|
1165
|
-
&& p205.executedAt === input.aggregateQaReceipt.checkedAt);
|
|
1166
|
-
if (p205Valid) {
|
|
1167
|
-
CONSUMED_TERMINAL_RELEASE_AUTHORITIES.add(authority);
|
|
1168
|
-
return true;
|
|
1169
|
-
}
|
|
1170
|
-
const valid = Boolean(reconciliation && input.headReconciliationReceipt
|
|
1171
|
-
&& reconciliation.executionHeadSha === input.executionHeadSha
|
|
1172
|
-
&& reconciliation.graphRevision === input.graphRevision
|
|
1173
|
-
&& reconciliation.aggregateReceiptRef === input.aggregateQaReceipt.receiptRef
|
|
1174
|
-
&& reconciliation.reconciliationInputDigest === input.headReconciliationReceipt.inputDigest);
|
|
1175
|
-
if (!valid)
|
|
1176
|
-
return false;
|
|
1177
|
-
CONSUMED_TERMINAL_RELEASE_AUTHORITIES.add(authority);
|
|
1178
|
-
return true;
|
|
1179
|
-
}
|
|
1180
|
-
function checkpointClaimProof(input) {
|
|
1181
|
-
const legacy = LEGACY_P174_CHECKPOINT_MIGRATIONS[input.storyId];
|
|
1182
|
-
const persistedClaim = typeof input.checkpoint.claimRevision === 'string' ? input.checkpoint.claimRevision : undefined;
|
|
1183
|
-
const claimlessLegacy = input.storyId === 'P174.03.811759' || input.storyId === 'P174.03.685003';
|
|
1184
|
-
const normalized = normalizeAuthorizedWriteSet(input.authorizedWriteSet);
|
|
1185
|
-
let rootMemoryPaths = [];
|
|
1186
|
-
if (input.checkpoint.rootMemoryEffect !== undefined) {
|
|
1187
|
-
if (legacy)
|
|
1188
|
-
return undefined;
|
|
1189
|
-
try {
|
|
1190
|
-
rootMemoryPaths = verifyRootMemoryPhysicalWriteSet(input.projectRoot, input.checkpoint.rootMemoryEffect, {
|
|
1191
|
-
storyId: input.storyId, executionBranch: input.executionBranch, baseSha: input.baseSha,
|
|
1192
|
-
headRef: input.headSha, childPaths: normalized,
|
|
1193
|
-
}).files.map(file => file.path);
|
|
1194
|
-
}
|
|
1195
|
-
catch {
|
|
1196
|
-
return undefined;
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
const declaredWriteSetValid = normalized.length > 0 && normalized.length === input.authorizedWriteSet.length
|
|
1200
|
-
&& input.changedPaths.every((path) => normalized.some((scope) => writeSetCovers(scope, path)) || rootMemoryPaths.includes(path));
|
|
1201
|
-
if (legacy
|
|
1202
|
-
&& input.epicId === 'P174' && input.executionBranch === 'epic/P174'
|
|
1203
|
-
&& input.baseSha === legacy.baseSha && input.headSha === legacy.headSha
|
|
1204
|
-
&& input.checkpoint.graphRevision === legacy.graphRevision
|
|
1205
|
-
&& input.commitBodyDigest === legacy.commitBodyDigest
|
|
1206
|
-
&& input.changedPathsDigest === legacy.changedPathsDigest
|
|
1207
|
-
&& (claimlessLegacy ? persistedClaim === undefined : persistedClaim === legacy.effectiveClaimRevision)) {
|
|
1208
|
-
if (input.authorizedWriteSet.length > 0
|
|
1209
|
-
&& (!declaredWriteSetValid || !claimMatchesWriteSet(legacy.effectiveClaimRevision, normalized)))
|
|
1210
|
-
return undefined;
|
|
1211
|
-
return Object.freeze({ mode: 'legacy-migration', effectiveClaimRevision: legacy.effectiveClaimRevision, binding: legacy });
|
|
1212
|
-
}
|
|
1213
|
-
// Claimless compatibility is closed over the seven immutable P174 ranges
|
|
1214
|
-
// above. Format, age, story name and otherwise-valid JSON evidence never
|
|
1215
|
-
// authorize a generic migration.
|
|
1216
|
-
if (persistedClaim === undefined)
|
|
1217
|
-
return undefined;
|
|
1218
|
-
if (!persistedClaim || !isHash(persistedClaim))
|
|
1219
|
-
return undefined;
|
|
1220
|
-
if (!declaredWriteSetValid || !claimMatchesWriteSet(persistedClaim, normalized))
|
|
1221
|
-
return undefined;
|
|
1222
|
-
return Object.freeze({ mode: 'canonical', effectiveClaimRevision: persistedClaim });
|
|
1223
|
-
}
|
|
1224
|
-
function normalizeAuthorizedWriteSet(values) {
|
|
1225
|
-
const normalized = values.map((value) => value.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/{2,}/g, '/'));
|
|
1226
|
-
// Directory scopes (`dir/`) are valid write-set entries: writeSetCovers and the
|
|
1227
|
-
// direct checkpoint already admit them, so the checkpoint claim proof must too.
|
|
1228
|
-
if (normalized.some((value) => !safeWriteScope(value)))
|
|
1229
|
-
return Object.freeze([]);
|
|
1230
|
-
return Object.freeze([...new Set(normalized)].sort());
|
|
1231
|
-
}
|
|
1232
|
-
function trackedStoryWriteSet(projectRoot, storyId) {
|
|
1233
|
-
try {
|
|
1234
|
-
const state = JSON.parse(readFileSync(join(projectRoot, '.neocortex', 'state.json'), 'utf8'));
|
|
1235
|
-
const stories = asRecord(state.stories);
|
|
1236
|
-
const story = asRecord(stories?.[storyId]);
|
|
1237
|
-
const runtime = readGitLifecycleRuntimeSync(projectRoot);
|
|
1238
|
-
const checkpoint = asRecord(runtime.stories[storyId]?.checkpoint) ?? asRecord(story?.checkpoint);
|
|
1239
|
-
return gitLifecycleStoryWriteSet(storyId, story, checkpoint);
|
|
1240
|
-
}
|
|
1241
|
-
catch {
|
|
1242
|
-
return [];
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
/** Reconstruct the same closed claim used by the direct or continuous planner. */
|
|
1246
|
-
export function gitLifecycleStoryWriteSet(storyId, story, checkpoint) {
|
|
1247
|
-
const authored = Array.isArray(story?.files_to_modify)
|
|
1248
|
-
? story.files_to_modify.filter((value) => typeof value === 'string') : [];
|
|
1249
|
-
if (!checkpoint?.dispatchId || !checkpoint.bundleId)
|
|
1250
|
-
return authored;
|
|
1251
|
-
try {
|
|
1252
|
-
return publicWriteSet({ ...story, id: storyId, files_to_modify: authored });
|
|
1253
|
-
}
|
|
1254
|
-
catch {
|
|
1255
|
-
return [];
|
|
1256
|
-
}
|
|
1257
|
-
}
|
|
1258
|
-
function claimMatchesWriteSet(claimRevision, writeSet) {
|
|
1259
|
-
return claimRevision === createHash('sha256').update(writeSet.join('\0')).digest('hex')
|
|
1260
|
-
|| claimRevision === createHash('sha256').update(JSON.stringify(writeSet)).digest('hex');
|
|
1261
|
-
}
|
|
1262
|
-
function writeSetCovers(scope, path) {
|
|
1263
|
-
return scope === path || scope.endsWith('/') && path.startsWith(scope);
|
|
1264
|
-
}
|
|
1265
|
-
/** Pre-P205 admission for only the exact seven immutable P174 migrations. */
|
|
1266
|
-
export function verifyLegacyCheckpointMigrationCandidateSync(projectRoot, value, storyId, epicId, executionBranch, authorizedWriteSet) {
|
|
1267
|
-
try {
|
|
1268
|
-
if (!isAcceptedGitLifecycleStoryCheckpoint(value, storyId, epicId, executionBranch))
|
|
1269
|
-
return false;
|
|
1270
|
-
const checkpoint = asRecord(value);
|
|
1271
|
-
const qa = asRecord(checkpoint.qaReceipt);
|
|
1272
|
-
const review = asRecord(checkpoint.reviewReceipt);
|
|
1273
|
-
const headSha = String(checkpoint.headSha);
|
|
1274
|
-
const baseSha = String(checkpoint.baseSha);
|
|
1275
|
-
const branchHead = gitSync(projectRoot, ['rev-parse', `refs/heads/${executionBranch}`]).trim();
|
|
1276
|
-
execFileSync('git', ['merge-base', '--is-ancestor', headSha, branchHead], { cwd: projectRoot, stdio: 'ignore' });
|
|
1277
|
-
if (gitSync(projectRoot, ['rev-parse', `${headSha}^`]).trim() !== baseSha
|
|
1278
|
-
|| gitSync(projectRoot, ['rev-list', '--count', `${baseSha}..${headSha}`]).trim() !== '1')
|
|
1279
|
-
return false;
|
|
1280
|
-
const commitBody = gitSync(projectRoot, ['show', '--no-patch', '--format=%H%n%P%n%B', headSha]);
|
|
1281
|
-
const changedPaths = gitSync(projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', headSha])
|
|
1282
|
-
.split('\0').filter(Boolean);
|
|
1283
|
-
if (changedPaths.length === 0 || changedPaths.some((path) => !safeRepositoryPath(path)))
|
|
1284
|
-
return false;
|
|
1285
|
-
const proof = checkpointClaimProof({
|
|
1286
|
-
projectRoot, checkpoint, storyId, epicId, executionBranch, baseSha, headSha, changedPaths, authorizedWriteSet,
|
|
1287
|
-
commitBodyDigest: createHash('sha256').update(commitBody).digest('hex'),
|
|
1288
|
-
changedPathsDigest: createHash('sha256').update([...changedPaths].sort().join('\0')).digest('hex'),
|
|
1289
|
-
});
|
|
1290
|
-
if (proof?.mode !== 'legacy-migration' || !proof.binding
|
|
1291
|
-
|| qa.sourceEvidenceDigest !== proof.binding.qaDigest
|
|
1292
|
-
|| qa.receiptRef !== `story-qa:${proof.binding.qaDigest}`
|
|
1293
|
-
|| review.sourceEvidenceDigest !== proof.binding.reviewDigest
|
|
1294
|
-
|| review.receiptRef !== `story-review:${proof.binding.reviewDigest}`
|
|
1295
|
-
|| review.qaReceiptRef !== qa.receiptRef)
|
|
1296
|
-
return false;
|
|
1297
|
-
return true;
|
|
1298
|
-
}
|
|
1299
|
-
catch {
|
|
1300
|
-
return false;
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1303
|
-
export function computeImmutableStoryQaEvidenceDigest(input) {
|
|
1304
|
-
return createHash('sha256').update([
|
|
1305
|
-
'local-yolo-tdd-git-immutable-v1', input.storyId, input.baseSha, input.headSha,
|
|
1306
|
-
input.bundleDigest, input.graphRevision,
|
|
1307
|
-
createHash('sha256').update(input.commitBody).digest('hex'),
|
|
1308
|
-
createHash('sha256').update([...input.changedPaths].sort().join('\0')).digest('hex'),
|
|
1309
|
-
].join('\0')).digest('hex');
|
|
1310
|
-
}
|
|
1311
|
-
/** Bind an actual successful P205 execution to immutable Git authority. */
|
|
1312
|
-
export function computeP205StoryQaEvidenceDigest(input) {
|
|
1313
|
-
return createHash('sha256').update([
|
|
1314
|
-
'local-yolo-tdd-p205-execution-v2', P205_COMPLETE_COMMAND,
|
|
1315
|
-
input.gitEvidenceDigest, input.headSha, input.graphRevision,
|
|
1316
|
-
input.manifestDigest, input.gateIds.join(','), input.resultDigest,
|
|
1317
|
-
].join('\0')).digest('hex');
|
|
1318
|
-
}
|
|
1319
|
-
function checkpointVerification(input) {
|
|
1320
|
-
const checkpoint = asRecord(input.value);
|
|
1321
|
-
return Object.freeze({
|
|
1322
|
-
schemaVersion: 1, kind: 'story_checkpoint_physical_verification', producer: 'client-p205-transient-v1',
|
|
1323
|
-
storyId: input.storyId, epicId: input.epicId, branch: input.executionBranch,
|
|
1324
|
-
baseSha: isSha(checkpoint?.baseSha) ? String(checkpoint?.baseSha) : '0'.repeat(40),
|
|
1325
|
-
headSha: isSha(checkpoint?.headSha) ? String(checkpoint?.headSha) : '0'.repeat(40),
|
|
1326
|
-
aggregateHeadSha: '0'.repeat(40),
|
|
1327
|
-
commitBodyDigest: '0'.repeat(64), changedPathsDigest: '0'.repeat(64),
|
|
1328
|
-
claimVerification: 'canonical', effectiveClaimRevision: '0'.repeat(64),
|
|
1329
|
-
command: P205_COMPLETE_COMMAND, manifestDigest: '0'.repeat(64), gateIds: Object.freeze([]),
|
|
1330
|
-
resultDigest: '0'.repeat(64), graphRevision: '0'.repeat(64), executionEvidenceDigest: '0'.repeat(64),
|
|
1331
|
-
sourceEvidenceDigest: '0'.repeat(64), verifiedAt: normalizedIso(input.verifiedAt),
|
|
1332
|
-
verdict: input.verdict, reasonCodes: Object.freeze([input.reasonCode]), publicSafe: true,
|
|
1333
|
-
});
|
|
1334
|
-
}
|
|
1335
|
-
function gitSync(cwd, args) {
|
|
1336
|
-
return execFileSync('git', [...args], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
|
|
1337
|
-
}
|
|
1338
|
-
/** Read public review evidence from Git, never from the mutable worktree. */
|
|
1339
|
-
export function publicStoryReviewArtifactFromGit(projectRoot, storyId, revision, allowLegacyDecision = false) {
|
|
1340
|
-
if (!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(storyId))
|
|
1341
|
-
return undefined;
|
|
1342
|
-
if (revision !== ':' && !/^[a-f0-9]{40,64}$/i.test(revision))
|
|
1343
|
-
return undefined;
|
|
1344
|
-
const path = `.neocortex/stories/${storyId}/review.md`;
|
|
1345
|
-
let bytes;
|
|
1346
|
-
try {
|
|
1347
|
-
bytes = execFileSync('git', ['show', `${revision === ':' ? ':' : `${revision}:`}${path}`], {
|
|
1348
|
-
cwd: projectRoot, maxBuffer: 128 * 1024, stdio: ['ignore', 'pipe', 'ignore'],
|
|
1349
|
-
});
|
|
1350
|
-
}
|
|
1351
|
-
catch {
|
|
1352
|
-
return undefined;
|
|
1353
|
-
}
|
|
1354
|
-
if (bytes.length === 0 || bytes.length > 64 * 1024 || bytes.includes(0))
|
|
1355
|
-
return undefined;
|
|
1356
|
-
let content;
|
|
1357
|
-
try {
|
|
1358
|
-
content = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
1359
|
-
}
|
|
1360
|
-
catch {
|
|
1361
|
-
return undefined;
|
|
1362
|
-
}
|
|
1363
|
-
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
1364
|
-
const storyHeading = new RegExp(`^#\\s+${storyId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=\\s|$|[:—-])`);
|
|
1365
|
-
if (!lines.some((line) => storyHeading.test(line)))
|
|
1366
|
-
return undefined;
|
|
1367
|
-
const verdictLines = lines.filter((line) => /^Verdict\s*:/i.test(line));
|
|
1368
|
-
if (lines.some((line) => /^Status\s*:\s*(pending|changes-requested|rejected)\b/i.test(line))) {
|
|
1369
|
-
return undefined;
|
|
1370
|
-
}
|
|
1371
|
-
const legacyDecisionLines = lines.filter((line) => /^Decision\s*:/i.test(line));
|
|
1372
|
-
if (verdictLines.length === 0 && allowLegacyDecision
|
|
1373
|
-
&& legacyDecisionLines.length === 1
|
|
1374
|
-
&& /^Decision\s*:\s*APPROVED\b/i.test(legacyDecisionLines[0])) {
|
|
1375
|
-
return Object.freeze({ verdict: 'approved', digest: createHash('sha256').update(bytes).digest('hex') });
|
|
1376
|
-
}
|
|
1377
|
-
if (verdictLines.length !== 1)
|
|
1378
|
-
return undefined;
|
|
1379
|
-
const verdict = /^Verdict\s*:\s*(approved|pending|changes-requested)(?=\s|$|[;,.])/i.exec(verdictLines[0])?.[1]?.toLowerCase();
|
|
1380
|
-
if (verdict !== 'approved' && verdict !== 'pending' && verdict !== 'changes-requested')
|
|
1381
|
-
return undefined;
|
|
1382
|
-
return Object.freeze({ verdict, digest: createHash('sha256').update(bytes).digest('hex') });
|
|
1383
|
-
}
|
|
1384
|
-
/** Binds a later root approval to the exact immutable range of a legacy checkpoint. */
|
|
1385
|
-
export function computeHistoricalReviewReconciliationDigest(input) {
|
|
1386
|
-
return createHash('sha256').update([
|
|
1387
|
-
'root-historical-review-reconciliation-v1', input.storyId, input.epicId,
|
|
1388
|
-
input.checkpointHeadSha, input.approvalCommitSha, input.approvalArtifactDigest,
|
|
1389
|
-
input.qaReceiptRef, input.reviewReceiptRef,
|
|
1390
|
-
createHash('sha256').update(input.approvalCommitBody).digest('hex'),
|
|
1391
|
-
].join('\0')).digest('hex');
|
|
1392
|
-
}
|
|
1393
|
-
function verifyHistoricalReviewReconciliation(projectRoot, checkpoint, review, qa, storyId, epicId, branchHead) {
|
|
1394
|
-
const receipt = asRecord(checkpoint.reviewReconciliation);
|
|
1395
|
-
if (!receipt || !validateHistoricalReviewReconciliation(receipt, checkpoint))
|
|
1396
|
-
return false;
|
|
1397
|
-
const approvalSha = String(receipt.approvalCommitSha);
|
|
1398
|
-
const checkpointHead = String(checkpoint.headSha);
|
|
1399
|
-
if (approvalSha === checkpointHead)
|
|
1400
|
-
return false;
|
|
1401
|
-
try {
|
|
1402
|
-
execFileSync('git', ['merge-base', '--is-ancestor', checkpointHead, approvalSha], { cwd: projectRoot, stdio: 'ignore' });
|
|
1403
|
-
execFileSync('git', ['merge-base', '--is-ancestor', approvalSha, branchHead], { cwd: projectRoot, stdio: 'ignore' });
|
|
1404
|
-
if (!gitSync(projectRoot, ['rev-list', '--first-parent', branchHead]).split('\n').includes(approvalSha))
|
|
1405
|
-
return false;
|
|
1406
|
-
const parents = gitSync(projectRoot, ['show', '--no-patch', '--format=%P', approvalSha]).trim().split(/\s+/);
|
|
1407
|
-
if (parents.length !== 1 || !isSha(parents[0]))
|
|
1408
|
-
return false;
|
|
1409
|
-
const approvalCommitBody = gitSync(projectRoot, ['show', '--no-patch', '--format=%H%n%P%n%B', approvalSha]);
|
|
1410
|
-
const trailers = new Set(approvalCommitBody.split('\n').map((line) => line.trim()));
|
|
1411
|
-
if (!trailers.has(`Neocortex-Review-Reconciliation: ${storyId}`)
|
|
1412
|
-
|| !trailers.has(`Neocortex-Original-Checkpoint: ${checkpointHead}`)
|
|
1413
|
-
|| !trailers.has(`Neocortex-Original-Review-Receipt: ${String(review.receiptRef)}`))
|
|
1414
|
-
return false;
|
|
1415
|
-
const reviewPath = `.neocortex/stories/${storyId}/review.md`;
|
|
1416
|
-
const changedPaths = gitSync(projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', approvalSha])
|
|
1417
|
-
.split('\0').filter(Boolean);
|
|
1418
|
-
if (!changedPaths.includes(reviewPath) || changedPaths.some((path) => !safeRepositoryPath(path)))
|
|
1419
|
-
return false;
|
|
1420
|
-
const approved = publicStoryReviewArtifactFromGit(projectRoot, storyId, approvalSha);
|
|
1421
|
-
if (approved?.verdict !== 'approved' || approved.digest !== receipt.approvalArtifactDigest)
|
|
1422
|
-
return false;
|
|
1423
|
-
const current = publicStoryReviewArtifactFromGit(projectRoot, storyId, branchHead);
|
|
1424
|
-
if (current?.verdict !== 'approved' || current.digest !== approved.digest)
|
|
1425
|
-
return false;
|
|
1426
|
-
const digest = computeHistoricalReviewReconciliationDigest({
|
|
1427
|
-
storyId, epicId, checkpointHeadSha: checkpointHead, approvalCommitSha: approvalSha,
|
|
1428
|
-
approvalArtifactDigest: approved.digest, qaReceiptRef: String(qa.receiptRef),
|
|
1429
|
-
reviewReceiptRef: String(review.receiptRef), approvalCommitBody,
|
|
1430
|
-
});
|
|
1431
|
-
return receipt.sourceEvidenceDigest === digest
|
|
1432
|
-
&& receipt.receiptRef === `story-review-reconciliation:${digest}`;
|
|
1433
|
-
}
|
|
1434
|
-
catch {
|
|
1435
|
-
return false;
|
|
1436
|
-
}
|
|
1437
|
-
}
|
|
1438
|
-
function publicStoryReviewBlobExistsInGit(projectRoot, storyId, headSha) {
|
|
1439
|
-
if (!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(storyId)
|
|
1440
|
-
|| !/^[a-f0-9]{40,64}$/i.test(headSha))
|
|
1441
|
-
return false;
|
|
1442
|
-
try {
|
|
1443
|
-
execFileSync('git', ['cat-file', '-e', `${headSha}:.neocortex/stories/${storyId}/review.md`], {
|
|
1444
|
-
cwd: projectRoot, stdio: 'ignore', maxBuffer: 1024,
|
|
1445
|
-
});
|
|
1446
|
-
return true;
|
|
1447
|
-
}
|
|
1448
|
-
catch {
|
|
1449
|
-
return false;
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
function normalizedIso(value) {
|
|
1453
|
-
return Number.isFinite(Date.parse(value)) ? new Date(Date.parse(value)).toISOString() : new Date().toISOString();
|
|
1454
|
-
}
|
|
1455
|
-
/**
|
|
1456
|
-
* Bounded migration evidence for direct-*yolo commits created before canonical
|
|
1457
|
-
* trailers were mandatory. The receipt is derived only from immutable commit
|
|
1458
|
-
* data and story-owned evidence blobs; JSON sidecar shape alone is never enough.
|
|
1459
|
-
*/
|
|
1460
|
-
export async function computeLegacyDirectYoloRecoveryReceiptRef(projectRoot, input) {
|
|
1461
|
-
if (LEGACY_DIRECT_YOLO_RECOVERY_COMMITS[input.storyId] !== input.headSha)
|
|
1462
|
-
return undefined;
|
|
1463
|
-
const evidencePaths = [
|
|
1464
|
-
'.neocortex/state.json',
|
|
1465
|
-
`.neocortex/stories/${input.storyId}/qa-gate-result.json`,
|
|
1466
|
-
`.neocortex/stories/${input.storyId}/validation-evidence.md`,
|
|
1467
|
-
`.neocortex/stories/${input.storyId}/review.md`,
|
|
1468
|
-
`docs/stories/${input.storyId}.story.md`,
|
|
1469
|
-
];
|
|
1470
|
-
try {
|
|
1471
|
-
const branchHead = (await execFileAsync('git', ['rev-parse', `refs/heads/${input.executionBranch}`], {
|
|
1472
|
-
cwd: projectRoot, encoding: 'utf8', maxBuffer: 1024 * 1024,
|
|
1473
|
-
})).stdout.trim();
|
|
1474
|
-
await execFileAsync('git', ['merge-base', '--is-ancestor', input.headSha, branchHead], { cwd: projectRoot });
|
|
1475
|
-
const parentSha = (await execFileAsync('git', ['rev-parse', `${input.headSha}^`], {
|
|
1476
|
-
cwd: projectRoot, encoding: 'utf8', maxBuffer: 1024 * 1024,
|
|
1477
|
-
})).stdout.trim();
|
|
1478
|
-
if (parentSha !== input.baseSha)
|
|
1479
|
-
return undefined;
|
|
1480
|
-
const immutablePayload = String((await execFileAsync('git', [
|
|
1481
|
-
'diff', '--binary', '--full-index', `${input.baseSha}..${input.headSha}`,
|
|
1482
|
-
], { cwd: projectRoot, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })).stdout);
|
|
1483
|
-
if (createHash('sha256').update(immutablePayload).digest('hex') !== input.bundleDigest)
|
|
1484
|
-
return undefined;
|
|
1485
|
-
const commitBody = String((await execFileAsync('git', ['show', '--no-patch', '--format=%H%n%P%n%B', input.headSha], {
|
|
1486
|
-
cwd: projectRoot, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024,
|
|
1487
|
-
})).stdout);
|
|
1488
|
-
const subject = String((await execFileAsync('git', ['show', '--no-patch', '--format=%s', input.headSha], {
|
|
1489
|
-
cwd: projectRoot, encoding: 'utf8', maxBuffer: 1024 * 1024,
|
|
1490
|
-
})).stdout).trim();
|
|
1491
|
-
if (!subject.includes(input.storyId))
|
|
1492
|
-
return undefined;
|
|
1493
|
-
const changedRaw = String((await execFileAsync('git', [
|
|
1494
|
-
'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', input.headSha,
|
|
1495
|
-
], { cwd: projectRoot, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 })).stdout);
|
|
1496
|
-
const changedPaths = changedRaw.split('\0').filter(Boolean);
|
|
1497
|
-
if (!evidencePaths.every((path) => changedPaths.includes(path))
|
|
1498
|
-
|| changedPaths.some((path) => !safeRepositoryPath(path)))
|
|
1499
|
-
return undefined;
|
|
1500
|
-
const blobs = await Promise.all(evidencePaths.map(async (path) => String((await execFileAsync('git', [
|
|
1501
|
-
'show', `${input.headSha}:${path}`,
|
|
1502
|
-
], { cwd: projectRoot, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })).stdout)));
|
|
1503
|
-
const state = JSON.parse(blobs[0]);
|
|
1504
|
-
const stories = asRecord(state.stories);
|
|
1505
|
-
const epics = asRecord(state.epics);
|
|
1506
|
-
const story = asRecord(stories?.[input.storyId]);
|
|
1507
|
-
const epic = asRecord(epics?.[input.epicId]);
|
|
1508
|
-
const steps = Array.isArray(story?.steps_completed) ? story.steps_completed : [];
|
|
1509
|
-
const qa = JSON.parse(blobs[1]);
|
|
1510
|
-
if (story?.status !== 'done' || !steps.includes(GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID) || !steps.includes(GIT_LIFECYCLE_REVIEW_PR_STEP_ID)
|
|
1511
|
-
|| epic?.branch_mode !== 'epic' || epic.execution_branch !== input.executionBranch
|
|
1512
|
-
|| qa.storyId !== input.storyId || qa.status !== 'qa-passed' || qa.safeToContinueYoloop !== true
|
|
1513
|
-
|| !Array.isArray(qa.blockingChecks) || qa.blockingChecks.length !== 0
|
|
1514
|
-
|| !blobs[2].includes(input.storyId) || !/P205[\s\S]{0,80}(pass|aprov)/i.test(blobs[2])
|
|
1515
|
-
|| !blobs[3].includes(input.storyId) || !/approved|aprovado/i.test(blobs[3])
|
|
1516
|
-
|| !blobs[4].includes(input.storyId))
|
|
1517
|
-
return undefined;
|
|
1518
|
-
const digest = createHash('sha256').update([
|
|
1519
|
-
'legacy-direct-yolo-recovery-v1', input.storyId, input.epicId, input.executionBranch,
|
|
1520
|
-
input.baseSha, input.headSha, input.bundleDigest, input.graphRevision,
|
|
1521
|
-
createHash('sha256').update(commitBody).digest('hex'),
|
|
1522
|
-
createHash('sha256').update([...changedPaths].sort().join('\0')).digest('hex'),
|
|
1523
|
-
...blobs.map((blob) => createHash('sha256').update(blob).digest('hex')),
|
|
1524
|
-
].join('\0')).digest('hex');
|
|
1525
|
-
return `legacy-direct-yolo:${digest}`;
|
|
1526
|
-
}
|
|
1527
|
-
catch {
|
|
1528
|
-
return undefined;
|
|
1529
|
-
}
|
|
1530
|
-
}
|
|
1531
|
-
async function runtimeStorePath(projectRoot) {
|
|
1532
|
-
const commonDir = await gitCommonDir(projectRoot);
|
|
1533
|
-
const runtimeDirectory = join(commonDir, GIT_LIFECYCLE_RUNTIME_DIRECTORY);
|
|
1534
|
-
const currentPath = join(runtimeDirectory, GIT_LIFECYCLE_RUNTIME_FILE);
|
|
1535
|
-
if (existsSync(runtimeDirectory)) {
|
|
1536
|
-
await assertSafeFilesystemEntry(runtimeDirectory, 'directory');
|
|
1537
|
-
if (await realpath(runtimeDirectory) !== runtimeDirectory)
|
|
1538
|
-
throw new Error('git-lifecycle-runtime-directory-symlink');
|
|
1539
|
-
}
|
|
1540
|
-
return existsSync(currentPath) ? currentPath : join(commonDir, LEGACY_STORE_FILE);
|
|
1541
|
-
}
|
|
1542
|
-
/** Resolve/create the private root used by lifecycle state, locks and sandboxes. */
|
|
1543
|
-
export async function gitLifecycleRuntimeDirectory(projectRoot) {
|
|
1544
|
-
return ensureRuntimeDirectory(await gitCommonDir(projectRoot));
|
|
1545
|
-
}
|
|
1546
|
-
/** Create or validate one private direct child without following substitutions. */
|
|
1547
|
-
export async function ensureGitLifecyclePrivateChildDirectory(parent, childName) {
|
|
1548
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(childName) || childName.includes('..')) {
|
|
1549
|
-
throw new Error('git-lifecycle-private-child-invalid');
|
|
1550
|
-
}
|
|
1551
|
-
const canonicalParent = resolve(parent);
|
|
1552
|
-
await assertPrivateDirectory(canonicalParent);
|
|
1553
|
-
const child = resolve(canonicalParent, childName);
|
|
1554
|
-
assertDirectChild(canonicalParent, child);
|
|
1555
|
-
if (!existsSync(child))
|
|
1556
|
-
await anchoredEnsureDirectory(canonicalParent, childName);
|
|
1557
|
-
await assertPrivateDirectory(child, canonicalParent);
|
|
1558
|
-
await assertPrivateDirectory(canonicalParent);
|
|
1559
|
-
return child;
|
|
1560
|
-
}
|
|
1561
|
-
/** Validate a private directory and every direct parent binding before use. */
|
|
1562
|
-
export async function assertGitLifecyclePrivateDirectory(path, parent) {
|
|
1563
|
-
const canonicalParent = resolve(parent);
|
|
1564
|
-
const child = resolve(path);
|
|
1565
|
-
assertDirectChild(canonicalParent, child);
|
|
1566
|
-
await assertPrivateDirectory(canonicalParent);
|
|
1567
|
-
await assertPrivateDirectory(child, canonicalParent);
|
|
1568
|
-
}
|
|
1569
|
-
export async function assertGitLifecyclePrivateFile(path, parent) {
|
|
1570
|
-
await assertSafePrivateFile(path, parent);
|
|
1571
|
-
}
|
|
1572
|
-
/** Remove only the validated directory object renamed inside its validated parent. */
|
|
1573
|
-
export async function removeGitLifecyclePrivateDirectory(path, parent, verifyRenamed) {
|
|
1574
|
-
const canonicalParent = resolve(parent);
|
|
1575
|
-
const child = resolve(path);
|
|
1576
|
-
assertDirectChild(canonicalParent, child);
|
|
1577
|
-
try {
|
|
1578
|
-
await assertGitLifecyclePrivateDirectory(child, canonicalParent);
|
|
1579
|
-
}
|
|
1580
|
-
catch (error) {
|
|
1581
|
-
if (isNodeError(error, 'ENOENT'))
|
|
1582
|
-
return false;
|
|
1583
|
-
throw error;
|
|
1584
|
-
}
|
|
1585
|
-
const quarantine = resolve(canonicalParent, `${child.slice(canonicalParent.length + 1)}.remove.${process.pid}.${Date.now()}.${randomBytes(4).toString('hex')}`);
|
|
1586
|
-
assertDirectChild(canonicalParent, quarantine);
|
|
1587
|
-
await anchoredRenameDirectory(canonicalParent, basename(child), basename(quarantine));
|
|
1588
|
-
await assertGitLifecyclePrivateDirectory(quarantine, canonicalParent);
|
|
1589
|
-
if (verifyRenamed && !(await verifyRenamed(quarantine))) {
|
|
1590
|
-
await restoreQuarantinedPrivateDirectory(quarantine, child, canonicalParent).catch(() => undefined);
|
|
1591
|
-
return false;
|
|
1592
|
-
}
|
|
1593
|
-
await anchoredRemoveDirectory(canonicalParent, basename(quarantine));
|
|
1594
|
-
return true;
|
|
1595
|
-
}
|
|
1596
|
-
async function restoreQuarantinedPrivateDirectory(quarantine, original, parent) {
|
|
1597
|
-
await assertGitLifecyclePrivateDirectory(quarantine, parent);
|
|
1598
|
-
try {
|
|
1599
|
-
await lstat(original);
|
|
1600
|
-
return;
|
|
1601
|
-
}
|
|
1602
|
-
catch (error) {
|
|
1603
|
-
if (!isNodeError(error, 'ENOENT'))
|
|
1604
|
-
throw error;
|
|
1605
|
-
}
|
|
1606
|
-
await anchoredRenameDirectory(parent, basename(quarantine), basename(original));
|
|
1607
|
-
await assertGitLifecyclePrivateDirectory(original, parent);
|
|
1608
|
-
}
|
|
1609
|
-
async function privateOwnerFingerprint(path) {
|
|
1610
|
-
try {
|
|
1611
|
-
await assertGitLifecyclePrivateDirectory(path, dirname(path));
|
|
1612
|
-
const ownerPath = join(path, 'owner.json');
|
|
1613
|
-
await assertSafePrivateFile(ownerPath, path);
|
|
1614
|
-
const owner = await readFile(ownerPath);
|
|
1615
|
-
await assertSafePrivateFile(ownerPath, path);
|
|
1616
|
-
return createHash('sha256').update(owner).digest('hex');
|
|
1617
|
-
}
|
|
1618
|
-
catch {
|
|
1619
|
-
return undefined;
|
|
1620
|
-
}
|
|
1621
|
-
}
|
|
1622
|
-
/** One physical writer lock shared by direct `*yolo` and continuous DAG integration. */
|
|
1623
|
-
export async function acquireGitLifecyclePhysicalIntegrationLock(projectRoot, requested) {
|
|
1624
|
-
const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
|
|
1625
|
-
const leasesRoot = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'leases');
|
|
1626
|
-
const lockPath = join(leasesRoot, 'integration');
|
|
1627
|
-
const legacyRecoveryPath = `${lockPath}.recovery`;
|
|
1628
|
-
if (existsSync(legacyRecoveryPath)) {
|
|
1629
|
-
await assertGitLifecyclePrivateDirectory(legacyRecoveryPath, leasesRoot);
|
|
1630
|
-
const recoveryPid = await readLegacyPhysicalIntegrationOwnerPid(legacyRecoveryPath);
|
|
1631
|
-
const recoveryFingerprint = await privateOwnerFingerprint(legacyRecoveryPath);
|
|
1632
|
-
if (recoveryPid === undefined || processExists(recoveryPid)) {
|
|
1633
|
-
return { ok: false, reasonCode: 'git-lifecycle-integration-backpressure' };
|
|
1634
|
-
}
|
|
1635
|
-
if (!recoveryFingerprint || !(await removeGitLifecyclePrivateDirectory(legacyRecoveryPath, leasesRoot, async (renamed) => await privateOwnerFingerprint(renamed) === recoveryFingerprint)))
|
|
1636
|
-
return { ok: false, reasonCode: 'git-lifecycle-integration-backpressure' };
|
|
1637
|
-
}
|
|
1638
|
-
const nowIso = normalizedIso(requested.createdAt ?? new Date().toISOString());
|
|
1639
|
-
const owner = Object.freeze({
|
|
1640
|
-
schemaVersion: 1, kind: requested.kind, storyId: requested.storyId,
|
|
1641
|
-
sessionId: requested.sessionId, idempotencyKey: requested.idempotencyKey,
|
|
1642
|
-
pid: process.pid, createdAt: nowIso, expiresAt: normalizedIso(requested.expiresAt),
|
|
1643
|
-
persistent: requested.persistent,
|
|
1644
|
-
ownerNonce: requested.ownerNonce ?? randomBytes(16).toString('hex'),
|
|
1645
|
-
});
|
|
1646
|
-
if (Date.parse(owner.expiresAt) <= Date.parse(owner.createdAt)) {
|
|
1647
|
-
return { ok: false, reasonCode: 'git-lifecycle-integration-lock-failed' };
|
|
1648
|
-
}
|
|
1649
|
-
const create = async () => {
|
|
1650
|
-
await assertPrivateDirectory(leasesRoot, runtimeDirectory);
|
|
1651
|
-
try {
|
|
1652
|
-
await anchoredCreateOwnedDirectory(leasesRoot, basename(lockPath), `${JSON.stringify(owner)}\n`);
|
|
1653
|
-
await assertGitLifecyclePrivateDirectory(lockPath, leasesRoot);
|
|
1654
|
-
await assertSafePrivateFile(join(lockPath, 'owner.json'), lockPath);
|
|
1655
|
-
return true;
|
|
1656
|
-
}
|
|
1657
|
-
catch (error) {
|
|
1658
|
-
if (!isNodeError(error, 'EEXIST')) {
|
|
1659
|
-
await removeGitLifecyclePrivateDirectory(lockPath, leasesRoot).catch(() => undefined);
|
|
1660
|
-
}
|
|
1661
|
-
throw error;
|
|
1662
|
-
}
|
|
1663
|
-
};
|
|
1664
|
-
try {
|
|
1665
|
-
await create();
|
|
1666
|
-
return { ok: true, owner, path: lockPath };
|
|
1667
|
-
}
|
|
1668
|
-
catch (error) {
|
|
1669
|
-
if (!isNodeError(error, 'EEXIST'))
|
|
1670
|
-
return { ok: false, reasonCode: 'git-lifecycle-integration-lock-failed' };
|
|
1671
|
-
}
|
|
1672
|
-
try {
|
|
1673
|
-
const current = await readPhysicalIntegrationOwner(lockPath);
|
|
1674
|
-
const legacyPid = current ? undefined : await readLegacyPhysicalIntegrationOwnerPid(lockPath);
|
|
1675
|
-
if (current && samePhysicalIntegrationOwner(current, owner))
|
|
1676
|
-
return { ok: true, owner: current, path: lockPath };
|
|
1677
|
-
const currentActive = current && Date.parse(current.expiresAt) > Date.now()
|
|
1678
|
-
&& (current.persistent || processExists(current.pid));
|
|
1679
|
-
if (currentActive || legacyPid !== undefined && processExists(legacyPid)
|
|
1680
|
-
|| (!current && legacyPid === undefined && await recentlyCreated(lockPath))) {
|
|
1681
|
-
return { ok: false, reasonCode: 'git-lifecycle-integration-backpressure' };
|
|
1682
|
-
}
|
|
1683
|
-
const ownerFingerprint = await privateOwnerFingerprint(lockPath);
|
|
1684
|
-
if (!ownerFingerprint)
|
|
1685
|
-
return { ok: false, reasonCode: 'git-lifecycle-integration-lock-failed' };
|
|
1686
|
-
const quarantine = `${lockPath}.stale.${process.pid}.${Date.now()}`;
|
|
1687
|
-
await anchoredRenameDirectory(leasesRoot, basename(lockPath), basename(quarantine));
|
|
1688
|
-
try {
|
|
1689
|
-
await assertGitLifecyclePrivateDirectory(quarantine, leasesRoot);
|
|
1690
|
-
if (await privateOwnerFingerprint(quarantine) !== ownerFingerprint) {
|
|
1691
|
-
await restoreQuarantinedPrivateDirectory(quarantine, lockPath, leasesRoot).catch(() => undefined);
|
|
1692
|
-
return { ok: false, reasonCode: 'git-lifecycle-integration-backpressure' };
|
|
1693
|
-
}
|
|
1694
|
-
await create();
|
|
1695
|
-
}
|
|
1696
|
-
finally {
|
|
1697
|
-
await removeGitLifecyclePrivateDirectory(quarantine, leasesRoot, async (renamed) => await privateOwnerFingerprint(renamed) === ownerFingerprint).catch(() => undefined);
|
|
1698
|
-
}
|
|
1699
|
-
return { ok: true, owner, path: lockPath };
|
|
1700
|
-
}
|
|
1701
|
-
catch (error) {
|
|
1702
|
-
return {
|
|
1703
|
-
ok: false,
|
|
1704
|
-
reasonCode: isNodeError(error, 'EEXIST') || isNodeError(error, 'ENOENT')
|
|
1705
|
-
? 'git-lifecycle-integration-backpressure'
|
|
1706
|
-
: 'git-lifecycle-integration-lock-failed',
|
|
1707
|
-
};
|
|
1708
|
-
}
|
|
1709
|
-
}
|
|
1710
|
-
export async function verifyGitLifecyclePhysicalIntegrationLock(path, expected) {
|
|
1711
|
-
const current = await readPhysicalIntegrationOwner(path);
|
|
1712
|
-
return Boolean(current && samePhysicalIntegrationOwnerExact(current, expected)
|
|
1713
|
-
&& Date.parse(current.expiresAt) > Date.now());
|
|
1714
|
-
}
|
|
1715
|
-
export async function releaseGitLifecyclePhysicalIntegrationLock(path, expected) {
|
|
1716
|
-
try {
|
|
1717
|
-
const parent = dirname(path);
|
|
1718
|
-
await assertGitLifecyclePrivateDirectory(path, parent);
|
|
1719
|
-
const current = await readPhysicalIntegrationOwner(path);
|
|
1720
|
-
if (!current || !samePhysicalIntegrationOwnerExact(current, expected))
|
|
1721
|
-
return false;
|
|
1722
|
-
const ownerFingerprint = await privateOwnerFingerprint(path);
|
|
1723
|
-
if (!ownerFingerprint)
|
|
1724
|
-
return false;
|
|
1725
|
-
const quarantine = `${path}.release.${process.pid}.${Date.now()}`;
|
|
1726
|
-
await anchoredRenameDirectory(parent, basename(path), basename(quarantine));
|
|
1727
|
-
await assertGitLifecyclePrivateDirectory(quarantine, parent);
|
|
1728
|
-
const renamedOwner = await readPhysicalIntegrationOwner(quarantine);
|
|
1729
|
-
if (!renamedOwner || !samePhysicalIntegrationOwnerExact(renamedOwner, expected)
|
|
1730
|
-
|| await privateOwnerFingerprint(quarantine) !== ownerFingerprint) {
|
|
1731
|
-
await restoreQuarantinedPrivateDirectory(quarantine, path, parent).catch(() => undefined);
|
|
1732
|
-
return false;
|
|
1733
|
-
}
|
|
1734
|
-
return removeGitLifecyclePrivateDirectory(quarantine, parent, async (renamed) => await privateOwnerFingerprint(renamed) === ownerFingerprint);
|
|
1735
|
-
}
|
|
1736
|
-
catch (error) {
|
|
1737
|
-
if (isNodeError(error, 'ENOENT'))
|
|
1738
|
-
return false;
|
|
1739
|
-
throw error;
|
|
1740
|
-
}
|
|
1741
|
-
}
|
|
1742
|
-
export function computeGitLifecyclePhysicalIntegrationLockOwnerDigest(owner) {
|
|
1743
|
-
return createHash('sha256').update([
|
|
1744
|
-
'git-lifecycle-physical-owner-v1', owner.kind, owner.storyId, owner.sessionId,
|
|
1745
|
-
owner.idempotencyKey, String(owner.pid), owner.createdAt, owner.expiresAt,
|
|
1746
|
-
owner.persistent ? 'persistent' : 'ephemeral', owner.ownerNonce,
|
|
1747
|
-
].join('\0')).digest('hex');
|
|
1748
|
-
}
|
|
1749
|
-
/** Recover only the exact persistent lock whose digest was bound to a checkpoint. */
|
|
1750
|
-
export async function releaseGitLifecyclePhysicalIntegrationLockForCheckpoint(projectRoot, input) {
|
|
1751
|
-
if (!isCanonicalLifecycleId(input.storyId) || !safeToken(input.idempotencyKey) || !isHash(input.ownerDigest)) {
|
|
1752
|
-
return 'foreign';
|
|
1753
|
-
}
|
|
1754
|
-
const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
|
|
1755
|
-
const leasesRoot = join(runtimeDirectory, 'leases');
|
|
1756
|
-
const lockPath = join(leasesRoot, 'integration');
|
|
1757
|
-
if (!existsSync(lockPath))
|
|
1758
|
-
return 'absent';
|
|
1759
|
-
try {
|
|
1760
|
-
await assertGitLifecyclePrivateDirectory(leasesRoot, runtimeDirectory);
|
|
1761
|
-
await assertGitLifecyclePrivateDirectory(lockPath, leasesRoot);
|
|
1762
|
-
const current = await readPhysicalIntegrationOwner(lockPath);
|
|
1763
|
-
if (!current || current.kind !== 'direct' || current.storyId !== input.storyId
|
|
1764
|
-
|| current.sessionId !== input.idempotencyKey || current.idempotencyKey !== input.idempotencyKey
|
|
1765
|
-
|| current.persistent !== true
|
|
1766
|
-
|| computeGitLifecyclePhysicalIntegrationLockOwnerDigest(current) !== input.ownerDigest)
|
|
1767
|
-
return 'foreign';
|
|
1768
|
-
return await releaseGitLifecyclePhysicalIntegrationLock(lockPath, current) ? 'released' : 'foreign';
|
|
1769
|
-
}
|
|
1770
|
-
catch {
|
|
1771
|
-
return 'foreign';
|
|
1772
|
-
}
|
|
1773
|
-
}
|
|
1774
|
-
async function readPhysicalIntegrationOwner(path) {
|
|
1775
|
-
try {
|
|
1776
|
-
await assertGitLifecyclePrivateDirectory(path, dirname(path));
|
|
1777
|
-
const ownerPath = join(path, 'owner.json');
|
|
1778
|
-
await assertSafePrivateFile(ownerPath, path);
|
|
1779
|
-
const item = JSON.parse(await readFile(ownerPath, 'utf8'));
|
|
1780
|
-
if (item.schemaVersion !== 1 || (item.kind !== 'direct' && item.kind !== 'continuous')
|
|
1781
|
-
|| !isCanonicalLifecycleId(item.storyId) || !safeToken(item.sessionId) || !safeToken(item.idempotencyKey)
|
|
1782
|
-
|| !Number.isSafeInteger(item.pid) || Number(item.pid) <= 0 || !isIso(item.createdAt) || !isIso(item.expiresAt)
|
|
1783
|
-
|| typeof item.persistent !== 'boolean' || typeof item.ownerNonce !== 'string'
|
|
1784
|
-
|| !/^[a-f0-9]{32}$/.test(item.ownerNonce))
|
|
1785
|
-
return undefined;
|
|
1786
|
-
return item;
|
|
1787
|
-
}
|
|
1788
|
-
catch {
|
|
1789
|
-
return undefined;
|
|
1790
|
-
}
|
|
1791
|
-
}
|
|
1792
|
-
async function readLegacyPhysicalIntegrationOwnerPid(path) {
|
|
1793
|
-
try {
|
|
1794
|
-
await assertGitLifecyclePrivateDirectory(path, dirname(path));
|
|
1795
|
-
const ownerPath = join(path, 'owner.json');
|
|
1796
|
-
await assertSafePrivateFile(ownerPath, path);
|
|
1797
|
-
const item = JSON.parse(await readFile(ownerPath, 'utf8'));
|
|
1798
|
-
return Number.isSafeInteger(item.pid) && Number(item.pid) > 0 ? Number(item.pid) : undefined;
|
|
1799
|
-
}
|
|
1800
|
-
catch {
|
|
1801
|
-
return undefined;
|
|
1802
|
-
}
|
|
1803
|
-
}
|
|
1804
|
-
function samePhysicalIntegrationOwner(left, right) {
|
|
1805
|
-
return left.kind === right.kind && left.storyId === right.storyId
|
|
1806
|
-
&& left.sessionId === right.sessionId && left.idempotencyKey === right.idempotencyKey
|
|
1807
|
-
&& left.expiresAt === right.expiresAt && left.persistent === right.persistent;
|
|
1808
|
-
}
|
|
1809
|
-
function samePhysicalIntegrationOwnerExact(left, right) {
|
|
1810
|
-
return samePhysicalIntegrationOwner(left, right)
|
|
1811
|
-
&& left.schemaVersion === right.schemaVersion && left.pid === right.pid && left.createdAt === right.createdAt
|
|
1812
|
-
&& left.ownerNonce === right.ownerNonce;
|
|
1813
|
-
}
|
|
1814
|
-
async function gitCommonDir(projectRoot) {
|
|
1815
|
-
const canonicalRoot = await realpath(projectRoot);
|
|
1816
|
-
const result = await execFileAsync('git', ['rev-parse', '--git-common-dir'], {
|
|
1817
|
-
cwd: canonicalRoot,
|
|
1818
|
-
encoding: 'utf8',
|
|
1819
|
-
maxBuffer: 1024 * 1024,
|
|
1820
|
-
});
|
|
1821
|
-
const commonDir = result.stdout.trim();
|
|
1822
|
-
const resolvedCommonDir = isAbsolute(commonDir) ? resolve(commonDir) : resolve(canonicalRoot, commonDir);
|
|
1823
|
-
const canonicalCommonDir = await realpath(resolvedCommonDir);
|
|
1824
|
-
if (canonicalCommonDir !== resolvedCommonDir)
|
|
1825
|
-
throw new Error('git-lifecycle-common-dir-symlink');
|
|
1826
|
-
await assertCommonDirectoryEntry(canonicalCommonDir);
|
|
1827
|
-
const revalidated = await execFileAsync('git', ['rev-parse', '--git-common-dir'], {
|
|
1828
|
-
cwd: canonicalRoot,
|
|
1829
|
-
encoding: 'utf8',
|
|
1830
|
-
maxBuffer: 1024 * 1024,
|
|
1831
|
-
});
|
|
1832
|
-
const secondRaw = revalidated.stdout.trim();
|
|
1833
|
-
const second = isAbsolute(secondRaw) ? resolve(secondRaw) : resolve(canonicalRoot, secondRaw);
|
|
1834
|
-
if (second !== resolvedCommonDir)
|
|
1835
|
-
throw new Error('git-lifecycle-common-dir-raced');
|
|
1836
|
-
return canonicalCommonDir;
|
|
1837
|
-
}
|
|
1838
|
-
async function ensureRuntimeDirectory(commonDir) {
|
|
1839
|
-
const runtimeDirectory = join(commonDir, GIT_LIFECYCLE_RUNTIME_DIRECTORY);
|
|
1840
|
-
if (!existsSync(runtimeDirectory)) {
|
|
1841
|
-
await anchoredEnsureDirectory(commonDir, GIT_LIFECYCLE_RUNTIME_DIRECTORY);
|
|
1842
|
-
}
|
|
1843
|
-
await assertSafeFilesystemEntry(runtimeDirectory, 'directory');
|
|
1844
|
-
if (await realpath(runtimeDirectory) !== runtimeDirectory)
|
|
1845
|
-
throw new Error('git-lifecycle-runtime-directory-symlink');
|
|
1846
|
-
return runtimeDirectory;
|
|
1847
|
-
}
|
|
1848
|
-
async function readDocument(path, options = {}) {
|
|
1849
|
-
try {
|
|
1850
|
-
await assertSafeFilesystemEntry(path, 'file');
|
|
1851
|
-
return validateDocument(JSON.parse(await readFile(path, 'utf8')));
|
|
1852
|
-
}
|
|
1853
|
-
catch (error) {
|
|
1854
|
-
if (isNodeError(error, 'ENOENT')) {
|
|
1855
|
-
if (options.required)
|
|
1856
|
-
throw new Error('git-lifecycle-runtime-missing');
|
|
1857
|
-
return emptyDocument();
|
|
1858
|
-
}
|
|
1859
|
-
throw error;
|
|
1860
|
-
}
|
|
1861
|
-
}
|
|
1862
|
-
async function assertStoreDestinationSafe(path) {
|
|
1863
|
-
try {
|
|
1864
|
-
await assertSafeFilesystemEntry(path, 'file');
|
|
1865
|
-
}
|
|
1866
|
-
catch (error) {
|
|
1867
|
-
if (isNodeError(error, 'ENOENT'))
|
|
1868
|
-
return;
|
|
1869
|
-
throw error;
|
|
1870
|
-
}
|
|
1871
|
-
}
|
|
1872
|
-
async function assertSafeFilesystemEntry(path, kind) {
|
|
1873
|
-
const info = await lstat(path);
|
|
1874
|
-
if (info.isSymbolicLink())
|
|
1875
|
-
throw new Error(`git-lifecycle-${kind}-symlink`);
|
|
1876
|
-
if (kind === 'file' ? !info.isFile() : !info.isDirectory())
|
|
1877
|
-
throw new Error(`git-lifecycle-${kind}-invalid`);
|
|
1878
|
-
if (posixSecurityAvailable() && info.uid !== process.getuid())
|
|
1879
|
-
throw new Error(`git-lifecycle-${kind}-ownership-mismatch`);
|
|
1880
|
-
if (posixSecurityAvailable() && (info.mode & 0o077) !== 0)
|
|
1881
|
-
throw new Error(`git-lifecycle-${kind}-permissions-unsafe`);
|
|
1882
|
-
}
|
|
1883
|
-
function assertDirectChild(parent, child) {
|
|
1884
|
-
const normalizedParent = resolve(parent);
|
|
1885
|
-
const normalizedChild = resolve(child);
|
|
1886
|
-
const childRelative = relative(normalizedParent, normalizedChild);
|
|
1887
|
-
if (!childRelative || childRelative.startsWith('..') || isAbsolute(childRelative)
|
|
1888
|
-
|| dirname(normalizedChild) !== normalizedParent) {
|
|
1889
|
-
throw new Error('git-lifecycle-private-path-escape');
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
1892
|
-
async function assertPrivateDirectory(path, expectedParent) {
|
|
1893
|
-
const normalized = resolve(path);
|
|
1894
|
-
if (expectedParent)
|
|
1895
|
-
assertDirectChild(resolve(expectedParent), normalized);
|
|
1896
|
-
await assertSafeFilesystemEntry(normalized, 'directory');
|
|
1897
|
-
if (resolve(await realpath(normalized)) !== normalized)
|
|
1898
|
-
throw new Error('git-lifecycle-directory-substituted');
|
|
1899
|
-
if (expectedParent) {
|
|
1900
|
-
const parent = resolve(expectedParent);
|
|
1901
|
-
await assertSafeFilesystemEntry(parent, 'directory');
|
|
1902
|
-
if (resolve(await realpath(parent)) !== parent)
|
|
1903
|
-
throw new Error('git-lifecycle-directory-parent-substituted');
|
|
1904
|
-
}
|
|
1905
|
-
}
|
|
1906
|
-
async function assertSafePrivateFile(path, expectedParent) {
|
|
1907
|
-
const normalized = resolve(path);
|
|
1908
|
-
assertDirectChild(resolve(expectedParent), normalized);
|
|
1909
|
-
await assertPrivateDirectory(resolve(expectedParent));
|
|
1910
|
-
await assertSafeFilesystemEntry(normalized, 'file');
|
|
1911
|
-
if (resolve(await realpath(normalized)) !== normalized)
|
|
1912
|
-
throw new Error('git-lifecycle-file-substituted');
|
|
1913
|
-
}
|
|
1914
|
-
function assertSafeFilesystemEntrySync(path, kind) {
|
|
1915
|
-
const info = lstatSync(path);
|
|
1916
|
-
if (info.isSymbolicLink())
|
|
1917
|
-
throw new Error(`git-lifecycle-${kind}-symlink`);
|
|
1918
|
-
if (kind === 'file' ? !info.isFile() : !info.isDirectory())
|
|
1919
|
-
throw new Error(`git-lifecycle-${kind}-invalid`);
|
|
1920
|
-
if (posixSecurityAvailable() && info.uid !== process.getuid())
|
|
1921
|
-
throw new Error(`git-lifecycle-${kind}-ownership-mismatch`);
|
|
1922
|
-
if (posixSecurityAvailable() && (info.mode & 0o077) !== 0)
|
|
1923
|
-
throw new Error(`git-lifecycle-${kind}-permissions-unsafe`);
|
|
1924
|
-
}
|
|
1925
|
-
async function assertCommonDirectoryEntry(path) {
|
|
1926
|
-
const info = await lstat(path);
|
|
1927
|
-
if (info.isSymbolicLink())
|
|
1928
|
-
throw new Error('git-lifecycle-common-dir-symlink');
|
|
1929
|
-
if (!info.isDirectory())
|
|
1930
|
-
throw new Error('git-lifecycle-common-dir-invalid');
|
|
1931
|
-
}
|
|
1932
|
-
function assertCommonDirectoryEntrySync(path) {
|
|
1933
|
-
const info = lstatSync(path);
|
|
1934
|
-
if (info.isSymbolicLink())
|
|
1935
|
-
throw new Error('git-lifecycle-common-dir-symlink');
|
|
1936
|
-
if (!info.isDirectory())
|
|
1937
|
-
throw new Error('git-lifecycle-common-dir-invalid');
|
|
1938
|
-
}
|
|
1939
|
-
export function posixSecurityAvailable(platform = process.platform) {
|
|
1940
|
-
return platform !== 'win32' && typeof process.getuid === 'function';
|
|
1941
|
-
}
|
|
1942
|
-
function validateDocument(value) {
|
|
1943
|
-
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
1944
|
-
throw new Error('git-lifecycle-runtime-invalid');
|
|
1945
|
-
const record = value;
|
|
1946
|
-
const schemaVersion = record.schemaVersion;
|
|
1947
|
-
assertExactKeys(record, schemaVersion === 2
|
|
1948
|
-
? ['schemaVersion', 'revision', 'epics', 'stories', 'operational', 'storyWorktrees']
|
|
1949
|
-
: ['schemaVersion', 'revision', 'epics', 'stories', 'storyWorktrees'], 'git-lifecycle-runtime-unknown-field');
|
|
1950
|
-
if (record.storyWorktrees !== undefined && !validateStoryWorktreeJournal(record.storyWorktrees)) {
|
|
1951
|
-
throw new Error('git-lifecycle-runtime-story-worktrees-invalid');
|
|
1952
|
-
}
|
|
1953
|
-
const epics = asRecord(record.epics);
|
|
1954
|
-
const stories = asRecord(record.stories);
|
|
1955
|
-
if ((schemaVersion !== 1 && schemaVersion !== 2)
|
|
1956
|
-
|| !Number.isSafeInteger(record.revision) || Number(record.revision) < 0
|
|
1957
|
-
|| !epics || !stories
|
|
1958
|
-
|| Object.values(epics).some((entry) => !asRecord(entry))
|
|
1959
|
-
|| Object.values(stories).some((entry) => !asRecord(entry))
|
|
1960
|
-
|| (schemaVersion === 2 && !validateOperationalEnvelope(record.operational))) {
|
|
1961
|
-
throw new Error('git-lifecycle-runtime-invalid');
|
|
1962
|
-
}
|
|
1963
|
-
for (const [epicId, overlay] of Object.entries(epics)) {
|
|
1964
|
-
if (!isCanonicalLifecycleId(epicId) || !validateEpicOverlay(overlay)) {
|
|
1965
|
-
throw new Error('git-lifecycle-runtime-epic-invalid');
|
|
1966
|
-
}
|
|
1967
|
-
}
|
|
1968
|
-
for (const [storyId, overlay] of Object.entries(stories)) {
|
|
1969
|
-
if (!isCanonicalLifecycleId(storyId) || !storyId.includes('.') || !validateStoryOverlay(overlay, storyId)) {
|
|
1970
|
-
throw new Error('git-lifecycle-runtime-story-invalid');
|
|
1971
|
-
}
|
|
1972
|
-
}
|
|
1973
|
-
return record;
|
|
1974
|
-
}
|
|
1975
|
-
/**
|
|
1976
|
-
* Keep the physical store closed even before a domain consumer reads v2. The
|
|
1977
|
-
* domain module validates every nested field; this boundary additionally
|
|
1978
|
-
* rejects future/private top-level fields and unbounded collections so a
|
|
1979
|
-
* malformed document can never be treated as a legacy v1 fallback.
|
|
1980
|
-
*/
|
|
1981
|
-
function validateOperationalEnvelope(value) {
|
|
1982
|
-
const item = asRecord(value);
|
|
1983
|
-
if (!item)
|
|
1984
|
-
return false;
|
|
1985
|
-
assertExactKeys(item, [
|
|
1986
|
-
'schemaVersion', 'repositoryFingerprint', 'writerEpoch', 'capabilities',
|
|
1987
|
-
'identities', 'yoloop', 'projectionBindings', 'activeJournal',
|
|
1988
|
-
'backfillReceipts', 'reconciliationReceipts', 'rollbackReceipts',
|
|
1989
|
-
], 'git-lifecycle-runtime-operational-unknown-field');
|
|
1990
|
-
const identities = asRecord(item.identities);
|
|
1991
|
-
const yoloop = asRecord(item.yoloop);
|
|
1992
|
-
const bindings = asRecord(item.projectionBindings);
|
|
1993
|
-
return item.schemaVersion === 'EpicOperationalState/1.0'
|
|
1994
|
-
&& isHash(item.repositoryFingerprint)
|
|
1995
|
-
&& Number.isSafeInteger(item.writerEpoch) && Number(item.writerEpoch) >= 1
|
|
1996
|
-
&& Array.isArray(item.capabilities) && item.capabilities.length <= 16
|
|
1997
|
-
&& item.capabilities.every((capability) => safeToken(capability))
|
|
1998
|
-
&& Boolean(identities) && Object.keys(identities).length <= 2_048
|
|
1999
|
-
&& Boolean(yoloop) && yoloop.schemaVersion === 'CommonYoloopAuthority/1.0'
|
|
2000
|
-
&& Boolean(bindings)
|
|
2001
|
-
&& (item.activeJournal === null || Boolean(asRecord(item.activeJournal)))
|
|
2002
|
-
&& validateBoundedRecordArray(item.backfillReceipts, 64)
|
|
2003
|
-
&& validateBoundedRecordArray(item.reconciliationReceipts, 64)
|
|
2004
|
-
&& validateBoundedRecordArray(item.rollbackReceipts, 64);
|
|
2005
|
-
}
|
|
2006
|
-
function validateBoundedRecordArray(value, max) {
|
|
2007
|
-
return Array.isArray(value) && value.length <= max && value.every((entry) => Boolean(asRecord(entry)));
|
|
2008
|
-
}
|
|
2009
|
-
const EPIC_OVERLAY_KEYS = [
|
|
2010
|
-
'branch_mode', 'execution_branch', 'origin_branch', 'branch_lease', 'origin_binding',
|
|
2011
|
-
'graph_revision', 'aggregate_qa_receipt', 'head_reconciliation_receipt', 'terminal_git_receipt', 'physicalMergeStatus',
|
|
2012
|
-
'pr_number', 'git_reconciliation_receipts', 'git_reconciliation_debt', 'story_worktree_evidence',
|
|
2013
|
-
];
|
|
2014
|
-
const STORY_OVERLAY_KEYS = ['checkpoint', 'status', 'last_step', 'steps_completed'];
|
|
2015
|
-
function validateEpicOverlay(value) {
|
|
2016
|
-
assertExactKeys(value, EPIC_OVERLAY_KEYS, 'git-lifecycle-runtime-epic-unknown-field');
|
|
2017
|
-
return (value.branch_mode === undefined || value.branch_mode === 'epic')
|
|
2018
|
-
&& (value.execution_branch === undefined || safeGitRef(value.execution_branch))
|
|
2019
|
-
&& (value.origin_branch === undefined || safeGitRef(value.origin_branch))
|
|
2020
|
-
&& (value.branch_lease === undefined || value.branch_lease === null || validateLease(value.branch_lease))
|
|
2021
|
-
&& (value.origin_binding === undefined || value.origin_binding === null || validateOriginBinding(value.origin_binding))
|
|
2022
|
-
&& (value.graph_revision === undefined || isHash(value.graph_revision))
|
|
2023
|
-
&& (value.aggregate_qa_receipt === undefined || value.aggregate_qa_receipt === null || validateAggregateQa(value.aggregate_qa_receipt))
|
|
2024
|
-
&& (value.head_reconciliation_receipt === undefined || value.head_reconciliation_receipt === null
|
|
2025
|
-
|| validateHeadReconciliationReceipt(value.head_reconciliation_receipt))
|
|
2026
|
-
&& (value.terminal_git_receipt === undefined || value.terminal_git_receipt === null || validateTerminalReceipt(value.terminal_git_receipt))
|
|
2027
|
-
&& (value.physicalMergeStatus === undefined || ['merged', 'pushed', 'denied_external_gate', 'blocked_local_or_repo', 'not_attempted'].includes(String(value.physicalMergeStatus)))
|
|
2028
|
-
&& (value.pr_number === undefined || value.pr_number === null || Number.isSafeInteger(value.pr_number) && Number(value.pr_number) > 0)
|
|
2029
|
-
&& (value.git_reconciliation_receipts === undefined || validateReconciliationReceipts(value.git_reconciliation_receipts))
|
|
2030
|
-
&& (value.git_reconciliation_debt === undefined || validateReconciliationDebt(value.git_reconciliation_debt))
|
|
2031
|
-
&& (value.story_worktree_evidence === undefined || validateStoryWorktreeEvidenceContainer(value.story_worktree_evidence));
|
|
2032
|
-
}
|
|
2033
|
-
function validateStoryOverlay(value, storyId) {
|
|
2034
|
-
assertExactKeys(value, STORY_OVERLAY_KEYS, 'git-lifecycle-runtime-story-unknown-field');
|
|
2035
|
-
return (value.checkpoint === undefined || value.checkpoint === null || validateCheckpoint(value.checkpoint, storyId))
|
|
2036
|
-
&& (value.status === undefined || safeToken(value.status))
|
|
2037
|
-
&& (value.last_step === undefined || value.last_step === null || safeToken(value.last_step))
|
|
2038
|
-
&& (value.steps_completed === undefined || safeStringArray(value.steps_completed, 128));
|
|
2039
|
-
}
|
|
2040
|
-
function validateLease(value) {
|
|
2041
|
-
const item = asRecord(value);
|
|
2042
|
-
if (!item)
|
|
2043
|
-
return false;
|
|
2044
|
-
assertExactKeys(item, [
|
|
2045
|
-
'schemaVersion', 'ownerStoryId', 'sessionId', 'idempotencyKey', 'acquiredAt', 'expiresAt',
|
|
2046
|
-
'handoffGrant', 'handoffConsumption', 'setupHeadSha',
|
|
2047
|
-
], 'git-lifecycle-runtime-lease-unknown-field');
|
|
2048
|
-
return item.schemaVersion === 1 && isCanonicalLifecycleId(item.ownerStoryId)
|
|
2049
|
-
&& safeToken(item.sessionId) && safeToken(item.idempotencyKey)
|
|
2050
|
-
&& isIso(item.acquiredAt) && isIso(item.expiresAt)
|
|
2051
|
-
&& Date.parse(String(item.expiresAt)) > Date.parse(String(item.acquiredAt))
|
|
2052
|
-
&& (item.setupHeadSha === undefined || isSha(item.setupHeadSha))
|
|
2053
|
-
&& (item.handoffGrant === undefined || validateDirectYoloSetupHandoffGrant(item.handoffGrant, item))
|
|
2054
|
-
&& (item.handoffConsumption === undefined || validateDirectYoloSetupHandoffConsumption(item.handoffConsumption, item));
|
|
2055
|
-
}
|
|
2056
|
-
function validateDirectYoloSetupHandoffGrant(value, lease) {
|
|
2057
|
-
const item = asRecord(value);
|
|
2058
|
-
if (!item)
|
|
2059
|
-
return false;
|
|
2060
|
-
assertExactKeys(item, [
|
|
2061
|
-
'schemaVersion', 'kind', 'storyId', 'fromSessionId', 'tokenDigest',
|
|
2062
|
-
'bundleDigest', 'claimRevision', 'expiresAt',
|
|
2063
|
-
], 'git-lifecycle-runtime-handoff-grant-unknown-field');
|
|
2064
|
-
return item.schemaVersion === 1 && item.kind === 'direct-yolo-setup-handoff'
|
|
2065
|
-
&& item.storyId === lease.ownerStoryId && item.fromSessionId === lease.sessionId
|
|
2066
|
-
&& isHash(item.tokenDigest) && isHash(item.bundleDigest) && isHash(item.claimRevision)
|
|
2067
|
-
&& isIso(item.expiresAt)
|
|
2068
|
-
&& Date.parse(String(item.expiresAt)) <= Date.parse(String(lease.expiresAt));
|
|
2069
|
-
}
|
|
2070
|
-
function validateDirectYoloSetupHandoffConsumption(value, lease) {
|
|
2071
|
-
const item = asRecord(value);
|
|
2072
|
-
if (!item)
|
|
2073
|
-
return false;
|
|
2074
|
-
assertExactKeys(item, [
|
|
2075
|
-
'schemaVersion', 'kind', 'state', 'storyId', 'fromSessionId', 'tokenDigest',
|
|
2076
|
-
'bundleDigest', 'claimRevision', 'consumedBySessionId', 'consumedAt',
|
|
2077
|
-
], 'git-lifecycle-runtime-handoff-consumption-unknown-field');
|
|
2078
|
-
return item.schemaVersion === 1 && item.kind === 'direct-yolo-setup-handoff-consumption'
|
|
2079
|
-
&& item.state === 'consumed' && item.storyId === lease.ownerStoryId
|
|
2080
|
-
&& safeToken(item.fromSessionId) && isHash(item.tokenDigest)
|
|
2081
|
-
&& isHash(item.bundleDigest) && isHash(item.claimRevision)
|
|
2082
|
-
&& item.consumedBySessionId === lease.sessionId && isIso(item.consumedAt);
|
|
2083
|
-
}
|
|
2084
|
-
function validateOriginBinding(value) {
|
|
2085
|
-
const item = asRecord(value);
|
|
2086
|
-
if (!item)
|
|
2087
|
-
return false;
|
|
2088
|
-
assertExactKeys(item, ['schemaVersion', 'originBranch', 'originHeadSha', 'executionBranch', 'capturedFromCurrentCheckout', 'capturedAt'], 'git-lifecycle-runtime-origin-unknown-field');
|
|
2089
|
-
return item.schemaVersion === 1 && safeGitRef(item.originBranch) && safeGitRef(item.executionBranch)
|
|
2090
|
-
&& item.originBranch !== item.executionBranch && isSha(item.originHeadSha)
|
|
2091
|
-
&& item.capturedFromCurrentCheckout === true && isIso(item.capturedAt);
|
|
2092
|
-
}
|
|
2093
|
-
function validateAggregateQa(value) {
|
|
2094
|
-
const item = asRecord(value);
|
|
2095
|
-
if (!item)
|
|
2096
|
-
return false;
|
|
2097
|
-
assertExactKeys(item, [
|
|
2098
|
-
'schemaVersion', 'evidenceVersion', 'producer', 'contract', 'command', 'verdict',
|
|
2099
|
-
'executionHeadSha', 'graphRevision', 'manifestDigest', 'resultDigest', 'checkedAt', 'receiptRef', 'gateIds',
|
|
2100
|
-
], 'git-lifecycle-runtime-aggregate-qa-unknown-field');
|
|
2101
|
-
const executionV2 = item.evidenceVersion === 'p205-execution-v2'
|
|
2102
|
-
&& item.producer === 'local-yolo-tdd' && item.contract === 'P205-CI-02'
|
|
2103
|
-
&& item.command === P205_COMPLETE_COMMAND && isHash(item.manifestDigest) && isHash(item.resultDigest);
|
|
2104
|
-
const legacy = item.evidenceVersion === undefined && item.producer === undefined && item.contract === undefined
|
|
2105
|
-
&& item.command === undefined && item.manifestDigest === undefined && item.resultDigest === undefined;
|
|
2106
|
-
return item.schemaVersion === 1 && (executionV2 || legacy) && item.verdict === 'passed' && isSha(item.executionHeadSha)
|
|
2107
|
-
&& isHash(item.graphRevision) && isIso(item.checkedAt) && safeReceiptRef(item.receiptRef)
|
|
2108
|
-
&& safeStringArray(item.gateIds, 128, true);
|
|
2109
|
-
}
|
|
2110
|
-
function validateHeadReconciliationReceipt(value) {
|
|
2111
|
-
const item = asRecord(value);
|
|
2112
|
-
if (!item)
|
|
2113
|
-
return false;
|
|
2114
|
-
assertExactKeys(item, [
|
|
2115
|
-
'schemaVersion', 'kind', 'producer', 'epicId', 'executionBranch', 'originBranch', 'graphRevision',
|
|
2116
|
-
'originHeadSha', 'lastAcceptedCheckpointHeadSha', 'executionHeadSha', 'acceptedCheckpointIds',
|
|
2117
|
-
'acceptedCheckpointHeads', 'reconciliationCommitShas', 'commitRangeDigest', 'changedPaths',
|
|
2118
|
-
'changedPathsDigest', 'allowedWriteSet', 'allowedWriteSetDigest', 'aggregateReceiptRef',
|
|
2119
|
-
'aggregateManifestDigest', 'aggregateResultDigest', 'producedAt', 'revalidatedAt', 'inputDigest', 'publicSafe',
|
|
2120
|
-
], 'git-lifecycle-runtime-head-reconciliation-unknown-field');
|
|
2121
|
-
const acceptedIds = safeStringArray(item.acceptedCheckpointIds, 2_048, true)
|
|
2122
|
-
? item.acceptedCheckpointIds : [];
|
|
2123
|
-
const acceptedHeads = safeStringArray(item.acceptedCheckpointHeads, 2_048, true)
|
|
2124
|
-
? item.acceptedCheckpointHeads : [];
|
|
2125
|
-
const commits = safeStringArray(item.reconciliationCommitShas, 2_048)
|
|
2126
|
-
? item.reconciliationCommitShas : [];
|
|
2127
|
-
const changedPaths = boundedStringArray(item.changedPaths, 2_048) ? item.changedPaths : [];
|
|
2128
|
-
const allowedWriteSet = boundedStringArray(item.allowedWriteSet, 2_048, true) ? item.allowedWriteSet : [];
|
|
2129
|
-
if (item.schemaVersion !== 1 || item.kind !== 'epic_head_reconciliation'
|
|
2130
|
-
|| item.producer !== 'client-p205-head-reconciliation-v1' || item.publicSafe !== true
|
|
2131
|
-
|| !isCanonicalLifecycleId(item.epicId) || !safeGitRef(item.executionBranch) || !safeGitRef(item.originBranch)
|
|
2132
|
-
|| item.executionBranch === item.originBranch || !isHash(item.graphRevision)
|
|
2133
|
-
|| !isSha(item.originHeadSha) || !isSha(item.lastAcceptedCheckpointHeadSha) || !isSha(item.executionHeadSha)
|
|
2134
|
-
|| acceptedIds.length === 0 || acceptedIds.length !== acceptedHeads.length
|
|
2135
|
-
|| acceptedIds.some((id) => !isCanonicalLifecycleId(id) || !id.startsWith(`${String(item.epicId)}.`))
|
|
2136
|
-
|| acceptedHeads.some((sha) => !isSha(sha)) || commits.some((sha) => !isSha(sha))
|
|
2137
|
-
|| allowedWriteSet.length === 0
|
|
2138
|
-
|| (item.lastAcceptedCheckpointHeadSha !== item.executionHeadSha
|
|
2139
|
-
&& (commits.length === 0 || changedPaths.length === 0))
|
|
2140
|
-
|| (item.lastAcceptedCheckpointHeadSha === item.executionHeadSha
|
|
2141
|
-
&& (commits.length !== 0 || changedPaths.length !== 0))
|
|
2142
|
-
|| !sameOrdered(changedPaths, [...new Set(changedPaths)].sort())
|
|
2143
|
-
|| !sameOrdered(allowedWriteSet, [...new Set(allowedWriteSet)].sort())
|
|
2144
|
-
|| changedPaths.some((path) => !safeRepositoryPath(path))
|
|
2145
|
-
|| allowedWriteSet.some((path) => !safeWriteScope(path))
|
|
2146
|
-
|| changedPaths.some((path) => !allowedWriteSet.some((scope) => writeSetCovers(scope, path)))
|
|
2147
|
-
|| !isHash(item.commitRangeDigest) || !isHash(item.changedPathsDigest) || !isHash(item.allowedWriteSetDigest)
|
|
2148
|
-
|| !safeReceiptRef(item.aggregateReceiptRef) || !isHash(item.aggregateManifestDigest)
|
|
2149
|
-
|| !isHash(item.aggregateResultDigest) || !isIso(item.producedAt) || !isIso(item.revalidatedAt)
|
|
2150
|
-
|| Date.parse(String(item.revalidatedAt)) < Date.parse(String(item.producedAt)) || !isHash(item.inputDigest))
|
|
2151
|
-
return false;
|
|
2152
|
-
const typed = item;
|
|
2153
|
-
return typed.commitRangeDigest === epicHeadReconciliationRangeDigest(typed.lastAcceptedCheckpointHeadSha, typed.executionHeadSha, typed.reconciliationCommitShas) && typed.changedPathsDigest === epicHeadReconciliationPathsDigest(typed.changedPaths)
|
|
2154
|
-
&& typed.allowedWriteSetDigest === epicHeadReconciliationPathsDigest(typed.allowedWriteSet)
|
|
2155
|
-
&& typed.inputDigest === epicHeadReconciliationInputDigest(typed);
|
|
2156
|
-
}
|
|
2157
|
-
function validateTerminalReceipt(value) {
|
|
2158
|
-
const item = asRecord(value);
|
|
2159
|
-
if (!item)
|
|
2160
|
-
return false;
|
|
2161
|
-
assertExactKeys(item, [
|
|
2162
|
-
'schemaVersion', 'epicId', 'executionBranch', 'originBranch', 'baseSha', 'executionHeadSha',
|
|
2163
|
-
'mergeSha', 'pushedSha', 'strategy', 'prNumber', 'physicalStatus', 'localGateReceiptRefs',
|
|
2164
|
-
'idempotencyKey', 'attemptStartedAt', 'completedAt', 'retryEligible', 'reasonCodes', 'publicSafe', 'candidateQa',
|
|
2165
|
-
'providerGuard',
|
|
2166
|
-
], 'git-lifecycle-runtime-terminal-receipt-unknown-field');
|
|
2167
|
-
return item.schemaVersion === 1 && isCanonicalLifecycleId(item.epicId)
|
|
2168
|
-
&& safeGitRef(item.executionBranch) && safeGitRef(item.originBranch) && isSha(item.baseSha) && isSha(item.executionHeadSha)
|
|
2169
|
-
&& (item.mergeSha === undefined || isSha(item.mergeSha)) && (item.pushedSha === undefined || isSha(item.pushedSha))
|
|
2170
|
-
&& (item.strategy === 'direct' || item.strategy === 'single_pr')
|
|
2171
|
-
&& (item.candidateQa === undefined || validateMergeCandidateQaReceipt(item.candidateQa, item))
|
|
2172
|
-
&& (item.providerGuard === undefined || validateProviderGuardReceipt(item.providerGuard, item))
|
|
2173
|
-
&& (item.prNumber === undefined || Number.isSafeInteger(item.prNumber) && Number(item.prNumber) > 0)
|
|
2174
|
-
&& ['prepared', 'merged', 'pushed', 'denied_external_gate', 'blocked_local_or_repo'].includes(String(item.physicalStatus))
|
|
2175
|
-
&& safeStringArray(item.localGateReceiptRefs, 128, true) && safeToken(item.idempotencyKey)
|
|
2176
|
-
&& isIso(item.attemptStartedAt) && (item.completedAt === undefined || isIso(item.completedAt))
|
|
2177
|
-
&& typeof item.retryEligible === 'boolean' && safeStringArray(item.reasonCodes, 128)
|
|
2178
|
-
&& item.publicSafe === true;
|
|
2179
|
-
}
|
|
2180
|
-
function validateProviderGuardReceipt(value, terminal) {
|
|
2181
|
-
const item = asRecord(value);
|
|
2182
|
-
if (!item)
|
|
2183
|
-
return false;
|
|
2184
|
-
assertExactKeys(item, [
|
|
2185
|
-
'schemaVersion', 'provider', 'mode', 'source', 'prHeadSha', 'originHeadSha', 'checkedAt', 'publicSafe',
|
|
2186
|
-
], 'git-lifecycle-runtime-provider-guard-unknown-field');
|
|
2187
|
-
const modeSourceValid = item.mode === 'recovered_exact_tree'
|
|
2188
|
-
? item.source === 'physical_recovery'
|
|
2189
|
-
: item.mode === 'strict_up_to_date_expected_head'
|
|
2190
|
-
&& ['branch_protection', 'ruleset', 'branch_protection_and_ruleset'].includes(String(item.source));
|
|
2191
|
-
return item.schemaVersion === 1 && item.provider === 'github' && modeSourceValid
|
|
2192
|
-
&& terminal.strategy === 'single_pr' && terminal.physicalStatus === 'pushed'
|
|
2193
|
-
&& Number.isSafeInteger(terminal.prNumber) && Number(terminal.prNumber) > 0
|
|
2194
|
-
&& isSha(item.prHeadSha) && item.prHeadSha === terminal.mergeSha
|
|
2195
|
-
&& isSha(item.originHeadSha) && item.originHeadSha === terminal.baseSha
|
|
2196
|
-
&& isIso(item.checkedAt) && item.publicSafe === true;
|
|
2197
|
-
}
|
|
2198
|
-
function validateMergeCandidateQaReceipt(value, terminal) {
|
|
2199
|
-
const item = asRecord(value);
|
|
2200
|
-
if (!item)
|
|
2201
|
-
return false;
|
|
2202
|
-
assertExactKeys(item, ['schemaVersion', 'kind', 'contract', 'command', 'originHeadSha', 'executionHeadSha',
|
|
2203
|
-
'mergeSha', 'treeSha', 'graphRevision', 'manifestDigest', 'resultDigest', 'gateIds', 'checkedAt', 'receiptRef'], 'git-lifecycle-runtime-merge-candidate-unknown-field');
|
|
2204
|
-
return item.schemaVersion === 1 && item.kind === 'epic_merge_candidate_qa'
|
|
2205
|
-
&& item.contract === 'P205-CI-02' && item.command === P205_COMPLETE_COMMAND
|
|
2206
|
-
&& isSha(item.originHeadSha) && item.originHeadSha === terminal.baseSha
|
|
2207
|
-
&& isSha(item.executionHeadSha) && item.executionHeadSha === terminal.executionHeadSha
|
|
2208
|
-
&& isSha(item.mergeSha) && item.mergeSha === terminal.mergeSha
|
|
2209
|
-
&& isSha(item.treeSha) && isHash(item.graphRevision) && isHash(item.manifestDigest) && isHash(item.resultDigest)
|
|
2210
|
-
&& safeStringArray(item.gateIds, 128, true) && isIso(item.checkedAt) && safeReceiptRef(item.receiptRef);
|
|
2211
|
-
}
|
|
2212
|
-
function validateCheckpoint(value, storyId) {
|
|
2213
|
-
const item = asRecord(value);
|
|
2214
|
-
if (!item)
|
|
2215
|
-
return false;
|
|
2216
|
-
assertExactKeys(item, [
|
|
2217
|
-
'schemaVersion', 'storyId', 'epicId', 'branch', 'baseSha', 'headSha', 'commits', 'idempotencyKey',
|
|
2218
|
-
'dispatchId', 'bundleId', 'bundleDigest', 'graphRevision', 'claimRevision', 'receiptRefs',
|
|
2219
|
-
'qaVerdict', 'reviewVerdict', 'qaReceipt', 'reviewReceipt', 'reviewReconciliation', 'recordedAt', 'rootMemoryEffect',
|
|
2220
|
-
], 'git-lifecycle-runtime-checkpoint-unknown-field');
|
|
2221
|
-
const epicId = String(storyId).split('.')[0];
|
|
2222
|
-
return item.schemaVersion === 1 && item.storyId === storyId && item.epicId === epicId
|
|
2223
|
-
&& safeGitRef(item.branch) && isSha(item.baseSha) && isSha(item.headSha) && item.baseSha !== item.headSha
|
|
2224
|
-
&& safeShaArray(item.commits) && item.commits.length === 1 && item.commits[0] === item.headSha
|
|
2225
|
-
&& safeToken(item.idempotencyKey) && (item.dispatchId === undefined || isHash(item.dispatchId))
|
|
2226
|
-
&& (item.bundleId === undefined || isHash(item.bundleId)) && isHash(item.bundleDigest)
|
|
2227
|
-
&& isHash(item.graphRevision) && (item.claimRevision === undefined || isHash(item.claimRevision))
|
|
2228
|
-
&& (item.rootMemoryEffect === undefined || isRootProjectMemoryEffect(item.rootMemoryEffect)
|
|
2229
|
-
&& item.rootMemoryEffect.storyId === storyId && item.rootMemoryEffect.executionBranch === item.branch
|
|
2230
|
-
&& item.rootMemoryEffect.sourceHeadSha === item.baseSha && item.rootMemoryEffect.childClaimRevision === item.claimRevision)
|
|
2231
|
-
&& safeStringArray(item.receiptRefs, 256, true)
|
|
2232
|
-
&& (item.qaVerdict === 'passed' || item.qaVerdict === 'blocked')
|
|
2233
|
-
&& ['approved', 'changes-requested', 'pending'].includes(String(item.reviewVerdict))
|
|
2234
|
-
&& validateStoryQaReceipt(item.qaReceipt, item)
|
|
2235
|
-
&& (item.reviewVerdict === 'pending' ? item.reviewReceipt === undefined : validateStoryReviewReceipt(item.reviewReceipt, item))
|
|
2236
|
-
&& (item.reviewReconciliation === undefined || validateHistoricalReviewReconciliation(item.reviewReconciliation, item))
|
|
2237
|
-
&& isIso(item.recordedAt);
|
|
2238
|
-
}
|
|
2239
|
-
function validateHistoricalReviewReconciliation(value, checkpoint) {
|
|
2240
|
-
const item = asRecord(value);
|
|
2241
|
-
const qa = asRecord(checkpoint.qaReceipt);
|
|
2242
|
-
const review = asRecord(checkpoint.reviewReceipt);
|
|
2243
|
-
if (!item || !qa || !review)
|
|
2244
|
-
return false;
|
|
2245
|
-
assertExactKeys(item, [
|
|
2246
|
-
'schemaVersion', 'kind', 'storyId', 'epicId', 'checkpointHeadSha', 'approvalCommitSha',
|
|
2247
|
-
'approvalArtifactDigest', 'qaReceiptRef', 'reviewReceiptRef', 'sourceEvidenceDigest', 'reviewedAt', 'receiptRef',
|
|
2248
|
-
], 'git-lifecycle-runtime-review-reconciliation-unknown-field');
|
|
2249
|
-
return item.schemaVersion === 1 && item.kind === 'historical_review_reconciliation'
|
|
2250
|
-
&& item.storyId === checkpoint.storyId && item.epicId === checkpoint.epicId
|
|
2251
|
-
&& item.checkpointHeadSha === checkpoint.headSha && isSha(item.approvalCommitSha)
|
|
2252
|
-
&& isHash(item.approvalArtifactDigest) && item.qaReceiptRef === qa.receiptRef
|
|
2253
|
-
&& item.reviewReceiptRef === review.receiptRef && isHash(item.sourceEvidenceDigest)
|
|
2254
|
-
&& isIso(item.reviewedAt) && Date.parse(String(item.reviewedAt)) >= Date.parse(String(qa.checkedAt))
|
|
2255
|
-
&& safeReceiptRef(item.receiptRef)
|
|
2256
|
-
&& Array.isArray(checkpoint.receiptRefs) && checkpoint.receiptRefs.includes(item.receiptRef);
|
|
2257
|
-
}
|
|
2258
|
-
function validateStoryQaReceipt(value, checkpoint) {
|
|
2259
|
-
const item = asRecord(value);
|
|
2260
|
-
if (!item)
|
|
2261
|
-
return false;
|
|
2262
|
-
assertExactKeys(item, [
|
|
2263
|
-
'schemaVersion', 'kind', 'producer', 'evidenceVersion', 'storyId', 'epicId', 'baseSha', 'headSha', 'bundleDigest',
|
|
2264
|
-
'graphRevision', 'contract', 'command', 'manifestDigest', 'gateIds', 'resultDigest',
|
|
2265
|
-
'sourceEvidenceDigest', 'verdict', 'checkedAt', 'receiptRef',
|
|
2266
|
-
], 'git-lifecycle-runtime-story-qa-unknown-field');
|
|
2267
|
-
return item.schemaVersion === 1 && item.kind === 'story_qa_evidence' && item.producer === 'local-yolo-tdd'
|
|
2268
|
-
&& (item.evidenceVersion === undefined || item.evidenceVersion === 'git-immutable-v1'
|
|
2269
|
-
|| item.evidenceVersion === 'p205-execution-v2' && item.contract === 'P205-CI-02'
|
|
2270
|
-
&& item.command === P205_COMPLETE_COMMAND && isHash(item.manifestDigest)
|
|
2271
|
-
&& safeStringArray(item.gateIds, 32, true) && isHash(item.resultDigest))
|
|
2272
|
-
&& evidenceBindingMatches(item, checkpoint) && isHash(item.sourceEvidenceDigest)
|
|
2273
|
-
&& item.verdict === checkpoint.qaVerdict && (item.verdict === 'passed' || item.verdict === 'blocked')
|
|
2274
|
-
&& isIso(item.checkedAt) && safeReceiptRef(item.receiptRef)
|
|
2275
|
-
&& checkpoint.receiptRefs.includes(item.receiptRef);
|
|
2276
|
-
}
|
|
2277
|
-
function validateStoryReviewReceipt(value, checkpoint) {
|
|
2278
|
-
const item = asRecord(value);
|
|
2279
|
-
const qa = asRecord(checkpoint.qaReceipt);
|
|
2280
|
-
if (!item || !qa)
|
|
2281
|
-
return false;
|
|
2282
|
-
assertExactKeys(item, [
|
|
2283
|
-
'schemaVersion', 'kind', 'producer', 'storyId', 'epicId', 'baseSha', 'headSha', 'bundleDigest',
|
|
2284
|
-
'graphRevision', 'sourceEvidenceDigest', 'reviewArtifactDigest', 'qaReceiptRef', 'verdict', 'reviewedAt', 'receiptRef',
|
|
2285
|
-
], 'git-lifecycle-runtime-story-review-unknown-field');
|
|
2286
|
-
return item.schemaVersion === 1 && item.kind === 'story_review_evidence' && item.producer === 'root-commit-range-review'
|
|
2287
|
-
&& evidenceBindingMatches(item, checkpoint) && isHash(item.sourceEvidenceDigest)
|
|
2288
|
-
&& (item.reviewArtifactDigest === undefined || isHash(item.reviewArtifactDigest))
|
|
2289
|
-
&& item.qaReceiptRef === qa.receiptRef && item.receiptRef !== qa.receiptRef
|
|
2290
|
-
&& (item.verdict === 'approved' || item.verdict === 'changes-requested')
|
|
2291
|
-
&& (item.verdict === 'approved' ? checkpoint.reviewVerdict === 'approved' : checkpoint.reviewVerdict === 'changes-requested')
|
|
2292
|
-
&& isIso(item.reviewedAt) && Date.parse(String(item.reviewedAt)) >= Date.parse(String(qa.checkedAt))
|
|
2293
|
-
&& safeReceiptRef(item.receiptRef) && checkpoint.receiptRefs.includes(item.receiptRef);
|
|
2294
|
-
}
|
|
2295
|
-
function evidenceBindingMatches(item, checkpoint) {
|
|
2296
|
-
return ['storyId', 'epicId', 'baseSha', 'headSha', 'bundleDigest', 'graphRevision']
|
|
2297
|
-
.every((key) => item[key] === checkpoint[key]);
|
|
2298
|
-
}
|
|
2299
|
-
function validateReconciliationReceipts(value) {
|
|
2300
|
-
if (!Array.isArray(value) || value.length > 1024)
|
|
2301
|
-
return false;
|
|
2302
|
-
return value.every((entry) => {
|
|
2303
|
-
const item = asRecord(entry);
|
|
2304
|
-
if (!item)
|
|
2305
|
-
return false;
|
|
2306
|
-
assertExactKeys(item, ['schemaVersion', 'resourceId', 'action', 'outcome', 'idempotencyKey', 'reasonCodes', 'recordedAt', 'publicSafe'], 'git-lifecycle-runtime-reconciliation-receipt-unknown-field');
|
|
2307
|
-
return item.schemaVersion === 1 && safeToken(item.resourceId)
|
|
2308
|
-
&& ['no_op', 'delete_local_branch', 'delete_remote_branch', 'close_pull_request'].includes(String(item.action))
|
|
2309
|
-
&& ['applied', 'already_absent', 'dry_run', 'failed'].includes(String(item.outcome))
|
|
2310
|
-
&& safeToken(item.idempotencyKey) && safeStringArray(item.reasonCodes, 128) && isIso(item.recordedAt) && item.publicSafe === true;
|
|
2311
|
-
});
|
|
2312
|
-
}
|
|
2313
|
-
function validateReconciliationDebt(value) {
|
|
2314
|
-
if (!Array.isArray(value) || value.length > 1024)
|
|
2315
|
-
return false;
|
|
2316
|
-
return value.every((entry) => {
|
|
2317
|
-
const item = asRecord(entry);
|
|
2318
|
-
if (!item)
|
|
2319
|
-
return false;
|
|
2320
|
-
assertExactKeys(item, ['schemaVersion', 'resourceId', 'action', 'managed', 'reasonCodes', 'evidence', 'publicSafe'], 'git-lifecycle-runtime-reconciliation-debt-unknown-field');
|
|
2321
|
-
return item.schemaVersion === 1 && safeToken(item.resourceId) && item.action === 'preserve'
|
|
2322
|
-
&& typeof item.managed === 'boolean' && safeStringArray(item.reasonCodes, 128)
|
|
2323
|
-
&& safeStringArray(item.evidence, 16) && item.publicSafe === true;
|
|
2324
|
-
});
|
|
2325
|
-
}
|
|
2326
|
-
function assertExactKeys(record, allowed, reasonCode) {
|
|
2327
|
-
const allow = new Set(allowed);
|
|
2328
|
-
if (Object.keys(record).some((key) => !allow.has(key)))
|
|
2329
|
-
throw new Error(reasonCode);
|
|
2330
|
-
}
|
|
2331
|
-
function isCanonicalLifecycleId(value) {
|
|
2332
|
-
return typeof value === 'string' && /^P[1-9][0-9]*(?:\.[0-9]+)*$/.test(value);
|
|
2333
|
-
}
|
|
2334
|
-
function isGitLifecycleGraphAuthority(value) {
|
|
2335
|
-
const item = asRecord(value);
|
|
2336
|
-
if (!item)
|
|
2337
|
-
return false;
|
|
2338
|
-
return Object.keys(item).length === 10
|
|
2339
|
-
&& item.schemaVersion === 1
|
|
2340
|
-
&& item.kind === 'git_lifecycle_graph_authority'
|
|
2341
|
-
&& item.producer === 'server-continuous-yoloop-v1'
|
|
2342
|
-
&& (item.source === 'yolo' || item.source === 'yoloop')
|
|
2343
|
-
&& isCanonicalLifecycleId(item.epicId)
|
|
2344
|
-
&& isCanonicalLifecycleId(item.storyId)
|
|
2345
|
-
&& String(item.storyId).startsWith(`${String(item.epicId)}.`)
|
|
2346
|
-
&& safeGitRef(item.executionBranch)
|
|
2347
|
-
&& safeGitRef(item.originBranch)
|
|
2348
|
-
&& item.originBranch !== item.executionBranch
|
|
2349
|
-
&& typeof item.graphRevision === 'string'
|
|
2350
|
-
&& /^[a-f0-9]{64}$/.test(item.graphRevision)
|
|
2351
|
-
&& item.publicSafe === true;
|
|
2352
|
-
}
|
|
2353
|
-
function safeGitRef(value) {
|
|
2354
|
-
return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/.test(value)
|
|
2355
|
-
&& !value.includes('..') && !value.includes('//') && !value.includes('@{')
|
|
2356
|
-
&& !value.endsWith('/') && !value.endsWith('.') && !value.split('/').some((part) => !part || part.startsWith('.') || part.endsWith('.lock'));
|
|
2357
|
-
}
|
|
2358
|
-
function safeRepositoryPath(value) {
|
|
2359
|
-
return safeWriteScope(value) && !value.endsWith('/');
|
|
2360
|
-
}
|
|
2361
|
-
function safeWriteScope(value) {
|
|
2362
|
-
return value.length > 0 && value.length <= 1024 && !isAbsolute(value)
|
|
2363
|
-
&& !/^[A-Za-z]:[\\/]/.test(value) && !value.includes('\0') && !value.includes('\\')
|
|
2364
|
-
&& !value.includes('//') && !value.replace(/\/$/, '').split('/').some((part) => !part || part === '.' || part === '..')
|
|
2365
|
-
&& value.replace(/\/$/, '').split('/')[0] !== '.git';
|
|
2366
|
-
}
|
|
2367
|
-
function safeToken(value) {
|
|
2368
|
-
return typeof value === 'string' && value.length > 0 && value.length <= 240 && /^[A-Za-z0-9._:/#\-[\]]+$/.test(value) && !value.includes('..');
|
|
2369
|
-
}
|
|
2370
|
-
function safeReceiptRef(value) {
|
|
2371
|
-
return safeToken(value);
|
|
2372
|
-
}
|
|
2373
|
-
function isSha(value) {
|
|
2374
|
-
return typeof value === 'string' && /^[a-f0-9]{40,64}$/i.test(value);
|
|
2375
|
-
}
|
|
2376
|
-
function isHash(value) {
|
|
2377
|
-
return typeof value === 'string' && /^[a-f0-9]{64}$/i.test(value);
|
|
2378
|
-
}
|
|
2379
|
-
function isIso(value) {
|
|
2380
|
-
return typeof value === 'string' && value.length <= 64 && Number.isFinite(Date.parse(value));
|
|
2381
|
-
}
|
|
2382
|
-
function safeStringArray(value, max, nonEmpty = false) {
|
|
2383
|
-
return Array.isArray(value) && value.length <= max && (!nonEmpty || value.length > 0) && value.every(safeToken);
|
|
2384
|
-
}
|
|
2385
|
-
function boundedStringArray(value, max, nonEmpty = false) {
|
|
2386
|
-
return Array.isArray(value) && value.length <= max && (!nonEmpty || value.length > 0)
|
|
2387
|
-
&& value.every((item) => typeof item === 'string' && item.length > 0 && item.length <= 1024);
|
|
2388
|
-
}
|
|
2389
|
-
function sameOrdered(left, right) {
|
|
2390
|
-
return left.length === right.length && left.every((item, index) => item === right[index]);
|
|
2391
|
-
}
|
|
2392
|
-
function safeShaArray(value) {
|
|
2393
|
-
return Array.isArray(value) && value.length > 0 && value.length <= 256 && value.every(isSha);
|
|
2394
|
-
}
|
|
2395
|
-
function emptyDocument() {
|
|
2396
|
-
return { schemaVersion: 1, revision: 0, epics: {}, stories: {} };
|
|
2397
|
-
}
|
|
2398
|
-
/**
|
|
2399
|
-
* 4.61.5: parallel story-worktree children share this runtime; a live
|
|
2400
|
-
* holder is normally a sub-second write, so retry only `lock-active` with a
|
|
2401
|
-
* bounded backoff (about 4 s in total). Every other lock error fails at once.
|
|
2402
|
-
*/
|
|
2403
|
-
async function acquireLockWithBackoff(lockPath) {
|
|
2404
|
-
const delays = [50, 100, 200, 400, 600, 800, 1000, 1000];
|
|
2405
|
-
for (let attempt = 0;; attempt += 1) {
|
|
2406
|
-
try {
|
|
2407
|
-
return await acquireLock(lockPath);
|
|
2408
|
-
}
|
|
2409
|
-
catch (error) {
|
|
2410
|
-
if (!(error instanceof Error) || error.message !== 'git-lifecycle-runtime-lock-active' || attempt >= delays.length)
|
|
2411
|
-
throw error;
|
|
2412
|
-
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
|
2413
|
-
}
|
|
2414
|
-
}
|
|
2415
|
-
}
|
|
2416
|
-
async function acquireLock(lockPath) {
|
|
2417
|
-
const parent = dirname(lockPath);
|
|
2418
|
-
const requested = { pid: process.pid, nonce: randomBytes(16).toString('hex') };
|
|
2419
|
-
const create = async () => {
|
|
2420
|
-
await assertPrivateDirectory(parent);
|
|
2421
|
-
await anchoredCreateOwnedDirectory(parent, basename(lockPath), JSON.stringify(requested));
|
|
2422
|
-
try {
|
|
2423
|
-
await assertGitLifecyclePrivateDirectory(lockPath, parent);
|
|
2424
|
-
await assertSafePrivateFile(join(lockPath, 'owner.json'), lockPath);
|
|
2425
|
-
}
|
|
2426
|
-
catch (error) {
|
|
2427
|
-
await removeGitLifecyclePrivateDirectory(lockPath, parent).catch(() => undefined);
|
|
2428
|
-
throw error;
|
|
2429
|
-
}
|
|
2430
|
-
};
|
|
2431
|
-
try {
|
|
2432
|
-
await create();
|
|
2433
|
-
}
|
|
2434
|
-
catch (error) {
|
|
2435
|
-
if (!isNodeError(error, 'EEXIST'))
|
|
2436
|
-
throw error;
|
|
2437
|
-
await assertSafeFilesystemEntry(lockPath, 'directory');
|
|
2438
|
-
const owner = await readOwner(lockPath);
|
|
2439
|
-
if (owner !== undefined && processExists(owner.pid))
|
|
2440
|
-
throw new Error('git-lifecycle-runtime-lock-active');
|
|
2441
|
-
if (owner === undefined && await recentlyCreated(lockPath))
|
|
2442
|
-
throw new Error('git-lifecycle-runtime-lock-active');
|
|
2443
|
-
const ownerFingerprint = await privateOwnerFingerprint(lockPath);
|
|
2444
|
-
if (!ownerFingerprint)
|
|
2445
|
-
throw new Error('git-lifecycle-runtime-lock-owner-invalid');
|
|
2446
|
-
const quarantine = `${lockPath}.stale.${process.pid}.${Date.now()}`;
|
|
2447
|
-
await anchoredRenameDirectory(parent, basename(lockPath), basename(quarantine));
|
|
2448
|
-
try {
|
|
2449
|
-
await assertGitLifecyclePrivateDirectory(quarantine, parent);
|
|
2450
|
-
if (await privateOwnerFingerprint(quarantine) !== ownerFingerprint) {
|
|
2451
|
-
await restoreQuarantinedPrivateDirectory(quarantine, lockPath, parent).catch(() => undefined);
|
|
2452
|
-
throw new Error('git-lifecycle-runtime-lock-owner-replaced');
|
|
2453
|
-
}
|
|
2454
|
-
await create();
|
|
2455
|
-
}
|
|
2456
|
-
finally {
|
|
2457
|
-
await removeGitLifecyclePrivateDirectory(quarantine, parent, async (renamed) => await privateOwnerFingerprint(renamed) === ownerFingerprint).catch(() => undefined);
|
|
2458
|
-
}
|
|
2459
|
-
}
|
|
2460
|
-
return requested;
|
|
2461
|
-
}
|
|
2462
|
-
async function releaseRuntimeLock(lockPath, expected) {
|
|
2463
|
-
const parent = dirname(lockPath);
|
|
2464
|
-
try {
|
|
2465
|
-
await assertGitLifecyclePrivateDirectory(lockPath, parent);
|
|
2466
|
-
const current = await readOwner(lockPath);
|
|
2467
|
-
if (!current || !sameRuntimeLockOwner(current, expected))
|
|
2468
|
-
return false;
|
|
2469
|
-
const ownerFingerprint = await privateOwnerFingerprint(lockPath);
|
|
2470
|
-
if (!ownerFingerprint)
|
|
2471
|
-
return false;
|
|
2472
|
-
const quarantine = `${lockPath}.release.${process.pid}.${Date.now()}`;
|
|
2473
|
-
await anchoredRenameDirectory(parent, basename(lockPath), basename(quarantine));
|
|
2474
|
-
await assertGitLifecyclePrivateDirectory(quarantine, parent);
|
|
2475
|
-
const renamed = await readOwner(quarantine);
|
|
2476
|
-
if (!renamed || !sameRuntimeLockOwner(renamed, expected)
|
|
2477
|
-
|| await privateOwnerFingerprint(quarantine) !== ownerFingerprint) {
|
|
2478
|
-
await restoreQuarantinedPrivateDirectory(quarantine, lockPath, parent).catch(() => undefined);
|
|
2479
|
-
return false;
|
|
2480
|
-
}
|
|
2481
|
-
return removeGitLifecyclePrivateDirectory(quarantine, parent, async (renamedPath) => await privateOwnerFingerprint(renamedPath) === ownerFingerprint);
|
|
2482
|
-
}
|
|
2483
|
-
catch (error) {
|
|
2484
|
-
if (isNodeError(error, 'ENOENT'))
|
|
2485
|
-
return false;
|
|
2486
|
-
throw error;
|
|
2487
|
-
}
|
|
2488
|
-
}
|
|
2489
|
-
async function recentlyCreated(path) {
|
|
2490
|
-
try {
|
|
2491
|
-
return Date.now() - (await stat(path)).mtimeMs < 30_000;
|
|
2492
|
-
}
|
|
2493
|
-
catch {
|
|
2494
|
-
return true;
|
|
2495
|
-
}
|
|
2496
|
-
}
|
|
2497
|
-
async function readOwner(lockPath) {
|
|
2498
|
-
try {
|
|
2499
|
-
await assertGitLifecyclePrivateDirectory(lockPath, dirname(lockPath));
|
|
2500
|
-
const ownerPath = join(lockPath, 'owner.json');
|
|
2501
|
-
await assertSafePrivateFile(ownerPath, lockPath);
|
|
2502
|
-
const value = JSON.parse(await readFile(ownerPath, 'utf8'));
|
|
2503
|
-
return Number.isSafeInteger(value.pid) && Number(value.pid) > 0
|
|
2504
|
-
&& (value.nonce === undefined || typeof value.nonce === 'string' && /^[a-f0-9]{32}$/.test(value.nonce))
|
|
2505
|
-
? { pid: Number(value.pid), ...(typeof value.nonce === 'string' ? { nonce: value.nonce } : {}) }
|
|
2506
|
-
: undefined;
|
|
2507
|
-
}
|
|
2508
|
-
catch {
|
|
2509
|
-
return undefined;
|
|
2510
|
-
}
|
|
2511
|
-
}
|
|
2512
|
-
function sameRuntimeLockOwner(left, right) {
|
|
2513
|
-
return left.pid === right.pid && left.nonce !== undefined && left.nonce === right.nonce;
|
|
2514
|
-
}
|
|
2515
|
-
function processExists(pid) {
|
|
2516
|
-
try {
|
|
2517
|
-
process.kill(pid, 0);
|
|
2518
|
-
return true;
|
|
2519
|
-
}
|
|
2520
|
-
catch (error) {
|
|
2521
|
-
return isNodeError(error, 'EPERM');
|
|
2522
|
-
}
|
|
2523
|
-
}
|
|
2524
|
-
function asRecord(value) {
|
|
2525
|
-
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
2526
|
-
}
|
|
2527
|
-
function isNodeError(error, code) {
|
|
2528
|
-
return error instanceof Error && 'code' in error && error.code === code;
|
|
2529
|
-
}
|
|
1
|
+
import{execFile as zt,execFileSync as q}from"node:child_process";import{createHash as b,randomBytes as ke}from"node:crypto";import{lstat as Ce,open as Lt,readFile as Z,realpath as re,stat as qt}from"node:fs/promises";import{existsSync as K,lstatSync as rt,readFileSync as Oe,realpathSync as Be}from"node:fs";import{basename as H,dirname as X,isAbsolute as oe,join as _,relative as jt,resolve as S}from"node:path";import{promisify as Mt}from"node:util";import{publicWriteSet as Gt}from"../../../shared/dist/yoloop/public-story-write-set.js";import{isRootProjectMemoryEffect as Ft}from"../private-execution/shared-root-memory-types.js";import{verifyRootMemoryPhysicalWriteSet as Kt}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as Jt}from"../../../shared/dist/yoloop/branch-unit.js";import{epicHeadReconciliationInputDigest as nt,epicHeadReconciliationPathsDigest as ct,epicHeadReconciliationRangeDigest as Yt,validateEpicHeadReconciliationReceipt as Zt}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{anchoredAtomicWriteFile as Ut,anchoredCreateOwnedDirectory as at,anchoredEnsureDirectory as ot,anchoredExecuteGit as Qt,anchoredExecuteNode as st,anchoredRemoveDirectory as Xt,anchoredRenameDirectory as se}from"./secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as ei,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ti,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as pe}from"./git-lifecycle-step-ids.js";import{parseNeocortexTrailers as ii,trailerValue as Pe}from"./neocortex-trailers.js";const z=Mt(zt),ve="neocortex-yoloop",_e="runtime.json",G="node scripts/test-root.mjs --gate complete",dt=Object.freeze({"P174.03.029264":"339141be7339a0edf55710cbccb6e6558f514792"}),ri=Object.freeze({"P174.03.811759":Object.freeze({baseSha:"749c8fc732deaf26c81a8e08cc94b83c8cf0f5ba",headSha:"84162456d9cbe5000ffd0ed3eb3d0e88cfeba499",graphRevision:"60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445",effectiveClaimRevision:"11f54704f5007f6139159419cfd7781f908b1502e117365c6d84011384579ed2",commitBodyDigest:"b4fc759a49765fd8c0b3d0f5d1c333c2a4bf28d324e83eedabb12f9530df3738",changedPathsDigest:"11f54704f5007f6139159419cfd7781f908b1502e117365c6d84011384579ed2",qaDigest:"f1100775e21f5d0d990f77303a2a06d936908f016983e32a63316d81aee6b9fc",reviewDigest:"50400bbcddb6f02408837cf99077de5d3af8c84822ab23a8b5499c338af7103a"}),"P174.03.685003":Object.freeze({baseSha:"84162456d9cbe5000ffd0ed3eb3d0e88cfeba499",headSha:"272a7fee89e4b9324d35701df1c83b671fa96299",graphRevision:"60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445",effectiveClaimRevision:"6cc3c9033f1c4711dcbe3c676d1d7f9906614c7d6e95228e843d1c63cefbc641",commitBodyDigest:"e97966e26ce3ba31d5951b9fdac67808c88c1fd8be7ec1e73982f3f1cc7ffd81",changedPathsDigest:"6cc3c9033f1c4711dcbe3c676d1d7f9906614c7d6e95228e843d1c63cefbc641",qaDigest:"7439329a93321f39fb6b0de0a41c22e58373a399f9048e362dff4ffa6f1a7d89",reviewDigest:"1b2d12262e84acf9da7d06149a0effb11274ebdc986affbfd47635b855ec7135"}),"P174.03.029264":Object.freeze({baseSha:"272a7fee89e4b9324d35701df1c83b671fa96299",headSha:"339141be7339a0edf55710cbccb6e6558f514792",graphRevision:"60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445",effectiveClaimRevision:"1053bb2baf487e38fa28d7e8cfb872c5c4da66802534ee226bbc2c7455a6a5ab",commitBodyDigest:"0f269a00dcd168a6f548ff10dfa667b193c948ac9c7211f5cb11a0561757c371",changedPathsDigest:"1053bb2baf487e38fa28d7e8cfb872c5c4da66802534ee226bbc2c7455a6a5ab",qaDigest:"ef0fd2c6e216557825cd8521ccb2f9960a3af48f18e7a5ada441bee8bfda400b",reviewDigest:"372d0f4a2f32978c8b39f20167637b3917187edb75d49875e93200c4c5a19d0d"}),"P174.03.913359":Object.freeze({baseSha:"339141be7339a0edf55710cbccb6e6558f514792",headSha:"4ccc90b85c49b27f718090bf25bc452f1b84e5e3",graphRevision:"60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445",effectiveClaimRevision:"12b5cfba2667e8064309807776c1b323561dc8d853f9afe5f676007b8494b2b5",commitBodyDigest:"89a6653197509e75246a758d2706876b337770571a1cac47d9d85ec96c196459",changedPathsDigest:"12b5cfba2667e8064309807776c1b323561dc8d853f9afe5f676007b8494b2b5",qaDigest:"c7d3762ad30e4f9356243df17a1dd7123cbf1b660808d68176f44d1cd5da6449",reviewDigest:"e4ecf577e174fd66f31aa4a0113ab672ced16b12ee531f6831aa533795145ba1"}),"P174.03.724350":Object.freeze({baseSha:"4ccc90b85c49b27f718090bf25bc452f1b84e5e3",headSha:"568e9464fb086304146b9eb4594281f91302aef1",graphRevision:"60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445",effectiveClaimRevision:"c8b8b6b96edf9cea78925e2f961bd74069d77af03783a5368b8ac8025bf1fefe",commitBodyDigest:"b3032338bfcd6c9dc460e9426220a1966dedeff9968c4064fdd36a315560721b",changedPathsDigest:"c8b8b6b96edf9cea78925e2f961bd74069d77af03783a5368b8ac8025bf1fefe",qaDigest:"91f2f5b00935b1b04bb5d400df500cbc97c412072078b713c6e5ba8fda669bd0",reviewDigest:"9bc92069d3b3a76cc8b02d339d432690258be1376464b69e152ed8fd3d682f05"}),"P174.03.011976":Object.freeze({baseSha:"568e9464fb086304146b9eb4594281f91302aef1",headSha:"195599b1a99a99a8416c4c26c9ab9990847338a4",graphRevision:"60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445",effectiveClaimRevision:"49b7f2a0a967b2ba4249615c6d08834445a60df95045352838808eb4d6743b21",commitBodyDigest:"b8a28392fac663dd614b695a49c894b7cab116d45722a42850e3b24e2aaf36f4",changedPathsDigest:"49b7f2a0a967b2ba4249615c6d08834445a60df95045352838808eb4d6743b21",qaDigest:"6eb4459a7d80c4a268fc931297e8156ed2a320584f8775f0787d91b42c0929d4",reviewDigest:"98b21de29f7cceeec73da19000c6c144395cce6eb699c6a82dfab505d4ab7b44"}),"P174.03.686659":Object.freeze({baseSha:"195599b1a99a99a8416c4c26c9ab9990847338a4",headSha:"0db3681a5dad4e25ce37d967c636eb9d54915556",graphRevision:"60b343b4b810e6d5abc3159275012b9ab9ab517f9d780e7550fa5b49be740445",effectiveClaimRevision:"5c0fdbf820d677c288981b6f73f7d2d9a04ce7f4713687f12a2e984705244b8e",commitBodyDigest:"143257f4018ad773afc0c7280bd8aab8786851a9c20b65f8110881ff54656839",changedPathsDigest:"5c0fdbf820d677c288981b6f73f7d2d9a04ce7f4713687f12a2e984705244b8e",qaDigest:"6303dbf473e2815a3671aeb2c25528d8daba484b92a5a40d1eea5215e1f6763e",reviewDigest:"1bd6695846ed9340c8677cfa9b573880532187aeee487efaaa70577a0c94e7f2"})}),Te="neocortex-yoloop-runtime.json",ni="runtime.lock",ci=64,ai=256,He=new WeakMap,ft=new WeakMap,Ne=new WeakSet;async function Br(t,e){return(await oi(t,{headSha:e.headSha,graphRevisions:[e.graphRevision],...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.anchoredWorkspace!==void 0?{anchoredWorkspace:e.anchoredWorkspace}:{}})).get(e.graphRevision)}async function oi(t,e){const i=[...new Set(e.graphRevisions)];if(!v(e.headSha)||i.length===0||i.some(E=>!p(E)))throw new Error("p205-transient-binding-invalid");const r=e.anchoredWorkspace;if(r&&S(t)!==_(S(r.parent),r.name))throw new Error("p205-transient-anchor-binding-invalid");const n=async E=>r?(await Qt(r.parent,r.name,r.identity,E)).toString("utf8"):String((await z("git",[...E],{cwd:t,encoding:"utf8",maxBuffer:8*1024*1024})).stdout),c=async()=>r?JSON.parse((await st(r.parent,r.name,r.identity,["-e","const fs=require('node:fs');process.stdout.write(JSON.stringify({manifest:fs.readFileSync('config/release-gates.v2.json','utf8'),runner:fs.readFileSync('scripts/test-root.mjs','utf8')}));"])).toString("utf8")):{manifest:await Z(_(t,"config","release-gates.v2.json"),"utf8"),runner:await Z(_(t,"scripts","test-root.mjs"),"utf8")};if((await n(["rev-parse","HEAD"])).trim()!==e.headSha)throw new Error("p205-transient-head-mismatch");const{manifest:a,runner:g}=await c(),[s,f]=await Promise.all([n(["show",`${e.headSha}:config/release-gates.v2.json`]),n(["show",`${e.headSha}:scripts/test-root.mjs`])]);if(a!==s||g!==f)throw new Error("p205-transient-producer-dirty");const h=JSON.parse(a),u=Array.isArray(h.requiredCompleteClasses)?h.requiredCompleteClasses.filter(E=>typeof E=="string"&&/^[a-z0-9-]+$/.test(E)):[];if(h.contract!=="P205-CI-02"||u.length===0)throw new Error("p205-transient-manifest-invalid");const l={...process.env};delete l.NEOCORTEX_PROFILE_DIR;const m=r?(await st(r.parent,r.name,r.identity,["scripts/test-root.mjs","--gate","complete"])).toString("utf8"):String((await z(process.execPath,["scripts/test-root.mjs","--gate","complete"],{cwd:t,encoding:"utf8",maxBuffer:64*1024*1024,env:l})).stdout),{manifest:R,runner:O}=await c();if(R!==a||O!==g)throw new Error("p205-transient-producer-raced");if((await n(["rev-parse","HEAD"])).trim()!==e.headSha)throw new Error("p205-transient-head-raced");const j=b("sha256").update(a).digest("hex"),y=b("sha256").update(m).digest("hex"),w=de(e.nowIso??new Date().toISOString()),M=new Map,U=Object.freeze(u);for(const E of i){const k=b("sha256").update(["p205-transient-execution-v1",G,e.headSha,E,j,u.join(","),y,w].join("\0")).digest("hex"),ue=Object.freeze({schemaVersion:1,kind:"p205_transient_execution_authority",contract:"P205-CI-02",command:G,executionHeadSha:e.headSha,graphRevision:E,manifestDigest:j,gateIds:U,resultDigest:y,executedAt:w,executionEvidenceDigest:k}),B=Object.freeze(Object.create(null));He.set(B,ue),M.set(E,B)}return M}async function Ve(t,e={}){const i=await Li(t);return It(i,e)}function gt(t,e={}){let i;try{const r=q("git",["rev-parse","--git-common-dir"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),n=Be(t),c=oe(r)?S(r):S(n,r),o=Be(c);if(o!==c)throw new Error("git-lifecycle-common-dir-symlink");Ki(o);const a=_(o,ve),g=_(a,_e);if(K(a)&&(kt(a,"directory"),Be(a)!==a))throw new Error("git-lifecycle-runtime-directory-symlink");i=K(g)?g:_(o,Te)}catch{if(e.required)throw new Error("git-lifecycle-common-dir-invalid");return Ue()}if(!K(i)){if(e.required)throw new Error("git-lifecycle-runtime-missing");return Ue()}return kt(i,"file"),Je(JSON.parse(Oe(i,"utf8")))}async function Pr(t){try{await Ve(t,{required:!0});return}catch(e){if(!(e instanceof Error)||e.message!=="git-lifecycle-runtime-missing")throw e}try{await $e(t,()=>{},{expectedRevision:0})}catch(e){if(!(e instanceof Error)||e.message!=="git-lifecycle-runtime-revision-conflict")throw e;await Ve(t,{required:!0})}}function ht(t,e,i){if(!t||t.ownerStoryId!==e)return!1;const r=typeof t.sessionId=="string"?t.sessionId:"",n=Date.parse(String(t.expiresAt));return/^setup-[a-f0-9]{64}$/.test(r)&&t.idempotencyKey===r&&Number.isFinite(n)&&n>i}async function Tr(t,e,i=new Date().toISOString()){if(!hr(e))throw new Error("git-lifecycle-graph-authority-invalid");const r=_(S(t),".neocortex","state.json"),n=await Z(r,"utf8"),c=d(JSON.parse(n));if(!c)throw new Error("git-lifecycle-tracked-state-invalid");const o=await Ve(t),a=lt(c,o),g=d(d(a.epics)?.[e.epicId]),s=d(d(a.stories)?.[e.storyId]);if(!g)throw new Error("git-lifecycle-graph-authority-epic-invalid");if(!s||String(s.epic_id??e.storyId.split(".")[0])!==e.epicId)throw new Error("git-lifecycle-graph-authority-story-invalid");const f=Array.isArray(g.stories)?g.stories.filter(y=>typeof y=="string"):Object.keys(d(a.stories)??{}).filter(y=>{const w=d(d(a.stories)?.[y]);return String(w?.epic_id??y.split(".")[0])===e.epicId});if(Array.isArray(g.stories)&&!f.includes(e.storyId))throw new Error("git-lifecycle-graph-authority-story-invalid");const h=f.map(y=>{const w=d(d(a.stories)?.[y])??{};return{id:y,branch_name:typeof w.branch_name=="string"||w.branch_name===null?w.branch_name:void 0,pr_number:typeof w.pr_number=="number"||w.pr_number===null?w.pr_number:void 0,steps_completed:Array.isArray(w.steps_completed)?w.steps_completed.filter(M=>typeof M=="string"):[],checkpoint:d(w.checkpoint)}}),u=Jt({...g,id:e.epicId},h);if(u.mode!=="epic")throw new Error("git-lifecycle-graph-authority-epic-invalid");if(u.executionBranch!==e.executionBranch)throw new Error("git-lifecycle-graph-authority-branch-mismatch");if(u.originBranch!==void 0&&u.originBranch!==e.originBranch)throw new Error("git-lifecycle-graph-authority-origin-mismatch");const l=typeof d(o.epics[e.epicId])?.origin_branch=="string"?String(d(o.epics[e.epicId]).origin_branch):void 0;if(l!==void 0&&l!==e.originBranch)throw new Error("git-lifecycle-graph-authority-origin-mismatch");if(u.originBranch===void 0&&l===void 0){const{stdout:y}=await z("git",["branch","--show-current"],{cwd:t,encoding:"utf8",maxBuffer:1048576});if(String(y).trim()!==e.originBranch)throw new Error("git-lifecycle-graph-authority-origin-physical-mismatch")}const m=typeof g.graph_revision=="string"?g.graph_revision:void 0,R=typeof d(o.epics[e.epicId])?.graph_revision=="string"?String(d(o.epics[e.epicId]).graph_revision):void 0;if(m!==void 0&&!p(m))throw new Error("git-lifecycle-graph-revision-invalid");if(m===e.graphRevision&&R===e.graphRevision&&u.originBranch===e.originBranch&&l===e.originBranch)return{applied:!1,reused:!0,revision:o.revision,graphRevision:e.graphRevision};const O=Date.parse(i);if(!Number.isFinite(O))throw new Error("git-lifecycle-graph-authority-time-invalid");const D=d(g.branch_lease);if(D&&Number.isFinite(Date.parse(String(D.expiresAt)))&&Date.parse(String(D.expiresAt))>O&&!ht(D,e.storyId,O))throw new Error("git-lifecycle-graph-authority-writer-active");return{applied:!0,reused:!1,revision:(await $e(t,y=>{const w=je(y,e.epicId);if(w.branch_mode!==void 0&&w.branch_mode!=="epic")throw new Error("git-lifecycle-graph-authority-epic-raced");const M=w.execution_branch;if(M!==void 0&&M!==e.executionBranch)throw new Error("git-lifecycle-graph-authority-branch-raced");const U=w.origin_branch;if(U!==void 0&&U!==e.originBranch)throw new Error("git-lifecycle-graph-authority-origin-raced");const E=w.graph_revision;if(E!==void 0&&E!==m)throw new Error("git-lifecycle-graph-authority-epoch-raced");const k=d(w.branch_lease);if(k&&Number.isFinite(Date.parse(String(k.expiresAt)))&&Date.parse(String(k.expiresAt))>O&&!ht(k,e.storyId,O))throw new Error("git-lifecycle-graph-authority-writer-active");w.branch_mode="epic",w.execution_branch=e.executionBranch,w.origin_branch=e.originBranch,w.graph_revision=e.graphRevision},{expectedRevision:o.revision,preCommit:async()=>{if(await Z(r,"utf8")!==n)throw new Error("git-lifecycle-graph-authority-tracked-state-raced")}})).document.revision,graphRevision:e.graphRevision}}async function $e(t,e,i={}){const r=await Ke(t),n=await At(r),c=_(n,ni),o=await lr(c);try{const a=_(n,_e),g=_(r,Te),s=await It(K(a)?a:g);if(i.expectedRevision!==void 0&&i.expectedRevision!==s.revision)throw new Error("git-lifecycle-runtime-revision-conflict");const f=structuredClone(s),h=e(f);if(s.schemaVersion===2&&i.nextSchemaVersion!==void 0&&i.nextSchemaVersion!==2)throw new Error("git-lifecycle-runtime-schema-downgrade");const u=Je({...f,schemaVersion:i.nextSchemaVersion??s.schemaVersion,revision:s.revision+1});return await i.preCommit?.(u),await J(n,"directory"),await Gi(a),await Ut(n,_e,`${JSON.stringify(u,null,2)}
|
|
2
|
+
`),await J(a,"file"),await si(n),{document:u,value:h}}finally{await mr(c,o).catch(()=>{})}}async function si(t){let e;try{e=await Lt(t,"r")}catch(i){if(process.platform==="win32"&&(V(i,"EPERM")||V(i,"EISDIR")||V(i,"EINVAL")))return;throw i}try{await e.sync()}finally{await e.close()}}const di=256;function fi(t){return typeof t=="string"&&ge(t)&&t.length<=512&&!/^(?:\.neocortex|\.git|\.claude)(?:\/|$)/.test(t)&&!t.startsWith("docs/stories/")&&!/[\u0000-\u001f\u007f]/.test(t)}function gi(t){return b("sha256").update(["root-write-set-extension-v1",...t].join("\0")).digest("hex")}function ut(t){const e=d(t);if(!e)return!1;A(e,["schemaVersion","kind","paths","digest","approvedAt","approvedBy"],"git-lifecycle-runtime-write-set-extension-unknown-field");const i=e.paths;return e.schemaVersion===1&&e.kind==="root-write-set-extension"&&Array.isArray(i)&&i.length>0&&i.length<=di&&i.every(fi)&&ie(i,[...new Set(i)].sort())&&e.digest===gi(i)&&I(e.approvedAt)&&e.approvedBy==="root_agent"}function hi(t){try{const e=t?.write_set_extension;return e!==void 0&&ut(e)?e.paths:[]}catch{return[]}}function lt(t,e){const i=structuredClone(t),r=pt(i,"epics"),n=pt(i,"stories");for(const[c,o]of Object.entries(e.epics))r[c]={...d(r[c])??{},...structuredClone(o)};for(const[c,o]of Object.entries(e.stories)){const{write_set_extension:a,...g}=o,s=d(n[c])??{};ui(n,c,s,g),a!==void 0&&(n[c]={...d(n[c])??s,write_set_extension:structuredClone(a)})}return i}function ui(t,e,i,r){const n=i.steps_completed,c=r.steps_completed,o=r.status==="branch-ready"&&r.last_step===pe&&Array.isArray(c)&&c.length===1&&c[0]===pe&&r.checkpoint===void 0;if(!(o&&Array.isArray(n)&&n.includes(pe))){if(o&&Array.isArray(n)&&n.length>0){t[e]={...i,steps_completed:[pe,...n.filter(a=>a!==pe)]};return}t[e]={...i,...structuredClone(r)}}}function pt(t,e){const i=t[e];if(i===void 0){const c={};return t[e]=c,c}const r=d(i);if(r)return r;if(!Array.isArray(i))throw new Error(`git-lifecycle-tracked-${e}-invalid`);const n={};for(const c of i){const o=d(c),a=typeof o?.id=="string"?o.id.trim():"";if(!a||n[a]!==void 0)throw new Error(`git-lifecycle-tracked-${e}-ambiguous`);n[a]=o}return t[e]=n,n}function Hr(t){const e=t;return e.storyWorktrees??(e.storyWorktrees={schemaVersion:1,entries:{},cleanupReceipts:[]})}function Nr(t){const e=t,i=e.storyWorktrees;i&&Object.keys(i.entries).length===0&&i.cleanupReceipts.length===0&&delete e.storyWorktrees}const li=/^swt-[a-f0-9]{24}$/,pi=/^[a-f0-9]{8}$/,ne=/^[a-f0-9]{64}$/,We=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Re=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,ze=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,mt=/^[a-z0-9][a-z0-9._-]{0,79}$/;function mi(t){const e=d(t);if(!e)return!1;const i=["schemaVersion","kind","receiptId","epicId","storyId","leaseId","trigger","worktreeRemoved","localBranchRemoved","remoteBranchRemoved","cleanedAt"],r=new Set([...i,"preservedReasonCode"]);return Object.keys(e).some(n=>!r.has(n))||i.some(n=>e[n]===void 0)?!1:e.schemaVersion===1&&e.kind==="cleanup-receipt"&&typeof e.receiptId=="string"&&Re.test(e.receiptId)&&N(e.epicId)&&N(e.storyId)&&typeof e.leaseId=="string"&&Re.test(e.leaseId)&&["success","failure","abandon","orphan-recovery"].includes(String(e.trigger))&&typeof e.worktreeRemoved=="boolean"&&typeof e.localBranchRemoved=="boolean"&&typeof e.remoteBranchRemoved=="boolean"&&typeof e.cleanedAt=="string"&&ze.test(e.cleanedAt)&&(e.preservedReasonCode===void 0||typeof e.preservedReasonCode=="string"&&mt.test(e.preservedReasonCode))}const yi=512,wi=256,Le=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,bi=/^[A-Za-z0-9._@#-][A-Za-z0-9._/@#-]{0,239}$/,Si=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,vi=/[A-Za-z][A-Za-z0-9+.-]*:\/\//,_i=/^(?:\/|~[\\/]|[A-Za-z]:[\\/]|\\\\)/,Ri="18eafb8dbbdcb09db4e3988b2ba2c66f3ee1cf541fedda37077f2a74907232a8",Di=6,Ei="9cd927d02ff5979b5077e75b09cb34be275eca0e1c955403235b9ba0fb7a55eb";function yt(t){return b("sha256").update(t).digest("hex")}const xi=Object.freeze({"phase-one-receipt":{schemaVersion:{oneOf:[1]},kind:{oneOf:["phase-one-receipt"]},receiptId:"opaque",leaseId:"opaque",epicId:"story",storyId:"story",completedStepIds:"stories",headSha:"git-sha",specRef:"ref",specDigest:"sha256",graphRevision:"sha256",completedAt:"time"},"spec-barrier-receipt":{schemaVersion:{oneOf:[1]},kind:{oneOf:["spec-barrier-receipt"]},receiptId:"opaque",epicId:"story",stepId:{sha256Of:Ei},scope:{oneOf:["epic"]},storyIds:"stories",specDigests:"digest-map",graphRevision:"sha256",satisfiedAt:"time"},"integration-receipt":{schemaVersion:{oneOf:[1]},kind:{oneOf:["integration-receipt"]},receiptId:"opaque",epicId:"story",storyId:"story",integrationOwner:{oneOf:["root_agent"]},integrationIndex:"positive-int",epicHeadBeforeSha:"git-sha",epicHeadAfterSha:"git-sha",checkpointDigest:"sha256",outcome:{oneOf:["integrated","conflict-reopened"]},reasonCode:"reason",integratedAt:"time"}});function Ai(t){if(!Si.test(t)||!Number.isFinite(Date.parse(t)))return!1;const[e,i,r,n,c,o]=t.slice(0,19).split(/[-T:]/).map(Number),a=new Date(Date.UTC(e,i-1,r,n,c,o));return a.getUTCFullYear()===e&&a.getUTCMonth()===i-1&&a.getUTCDate()===r&&a.getUTCHours()===n&&a.getUTCMinutes()===c&&a.getUTCSeconds()===o}function De(t,e=0){if(e>4)return!1;if(typeof t=="string")return!vi.test(t)&&!_i.test(t);if(Array.isArray(t))return t.every(r=>De(r,e+1));const i=d(t);return i?Object.entries(i).every(([r,n])=>De(r,e+1)&&De(n,e+1)):!0}function Ii(t,e){if(typeof t=="object")return"sha256Of"in t?typeof e=="string"&&e.length<=80&&yt(e)===t.sha256Of:t.oneOf.includes(e);if(t==="positive-int")return Number.isSafeInteger(e)&&e>=1;if(t==="stories")return Array.isArray(e)&&e.length>0&&new Set(e).size===e.length&&e.every(i=>typeof i=="string"&&Le.test(i)&&!i.includes(".."));if(t==="digest-map"){const i=d(e);return!!i&&Object.keys(i).length>0&&Object.entries(i).every(([r,n])=>Le.test(r)&&typeof n=="string"&&ne.test(n))}if(typeof e!="string")return!1;switch(t){case"opaque":return Re.test(e);case"story":return Le.test(e)&&!e.includes("..");case"ref":{const i=e.split("/");return bi.test(e)&&!e.endsWith("/")&&i.every(r=>r!==""&&r!=="."&&r!==".."&&!r.startsWith("-")&&r.toLowerCase()!==".git")}case"sha256":return ne.test(e);case"git-sha":return We.test(e);case"time":return Ai(e);case"reason":return mt.test(e)}}function qe(t){const e=d(t);if(!e||typeof e.kind!="string")return!1;const i=xi[e.kind];if(!i||!De(e))return!1;const r=Object.keys(e);if(r.length!==Object.keys(i).length||r.some(n=>!(n in i))||!Object.entries(i).every(([n,c])=>e[n]!==void 0&&Ii(c,e[n])))return!1;if(e.kind==="phase-one-receipt"){const n=e.completedStepIds;return n.length===Di&&yt(n.join("\0"))===Ri}if(e.kind==="spec-barrier-receipt"){const n=Object.keys(e.specDigests),c=e.storyIds;return n.length===c.length&&c.every(o=>n.includes(o))}return!0}function Vr(t){return d(t)?.kind==="integration-receipt"&&qe(t)}function $r(t){return me(t)}function me(t){const e=d(t);if(!e||Object.keys(e).some(c=>!["schemaVersion","specAcceptances","receipts"].includes(c))||e.schemaVersion!==1)return!1;const r=e.specAcceptances;if(r!==void 0&&(!Array.isArray(r)||r.length>wi||new Set(r.map(c=>d(c)?.storyId)).size!==r.length||!r.every(c=>{const o=d(c);return!!o&&Object.keys(o).length===3&&N(o.storyId)&&String(o.storyId).includes(".")&&typeof o.specDigest=="string"&&ne.test(o.specDigest)&&typeof o.graphRevision=="string"&&ne.test(o.graphRevision)})))return!1;const n=e.receipts;return n===void 0||Array.isArray(n)&&n.length<=yi&&new Set(n.map(c=>d(c)?.receiptId)).size===n.length&&n.every(qe)}function ki(t,e){const i=t.epics[e]?.story_worktree_evidence;if(i!=null){if(!me(i))throw new Error("git-lifecycle-runtime-story-worktree-evidence-invalid");return i}}function Wr(t,e,i){const r=ki(t,e),n=[...r?.receipts??[]],c=[...r?.specAcceptances??[]];let o=0,a=0;for(const s of i.receipts??[]){const f=d(s);if(!qe(f)||f.epicId!==e)throw new Error("git-lifecycle-runtime-story-worktree-evidence-invalid");const h=n.find(u=>u.receiptId===f.receiptId);if(h){if(JSON.stringify(h)!==JSON.stringify(f))throw new Error("git-lifecycle-runtime-story-worktree-evidence-conflict");continue}n.push(structuredClone(f)),o++}for(const s of i.specAcceptances??[]){const f=d(s),h=f?{storyId:f.storyId,specDigest:f.specDigest,graphRevision:f.graphRevision}:void 0;if(!h||Object.keys(f).length!==3||!me({schemaVersion:1,specAcceptances:[h]}))throw new Error("git-lifecycle-runtime-story-worktree-evidence-invalid");const u=c.findIndex(l=>l.storyId===h.storyId);u>=0&&JSON.stringify(c[u])===JSON.stringify(h)||(u>=0?c[u]=h:c.push(h),a++)}const g={schemaVersion:1};if(c.length>0&&(g.specAcceptances=c),n.length>0&&(g.receipts=n),!me(g))throw new Error("git-lifecycle-runtime-story-worktree-evidence-invalid");return(o>0||a>0)&&(je(t,e).story_worktree_evidence=g),{appendedReceipts:o,appendedSpecAcceptances:a}}function Ci(t){const e=d(t);if(!e)return!1;const i=Object.keys(e);if(i.length!==3||!i.every(n=>["schemaVersion","entries","cleanupReceipts"].includes(n)))return!1;const r=d(e.entries);return e.schemaVersion!==1||!r||!Array.isArray(e.cleanupReceipts)||e.cleanupReceipts.length>ci||Object.keys(r).length>ai||e.cleanupReceipts.some(n=>!mi(n))?!1:Object.entries(r).every(([n,c])=>Oi(n,c))}function Oi(t,e){const i=d(e);if(!i)return!1;const r=["schemaVersion","leaseId","epicId","storyId","dispatchDigest","hash8","executionBranch","temporaryBranch","worktreeRef","worktreePath","workspaceMechanism","ownerId","nonceDigest","baseSha","graphRevision","state","acquiredAt","expiresAt"],n=new Set([...r,"syncedSha"]);if(Object.keys(i).some(a=>!n.has(a))||r.some(a=>i[a]===void 0))return!1;const c=i.epicId,o=i.hash8;return i.schemaVersion===1&&i.leaseId===t&&li.test(t)&&N(c)&&!String(c).includes(".")&&N(i.storyId)&&String(i.storyId).startsWith(`${String(c)}.`)&&typeof i.dispatchDigest=="string"&&ne.test(i.dispatchDigest)&&typeof o=="string"&&pi.test(o)&&i.executionBranch===`epic/${String(c)}`&&typeof i.temporaryBranch=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.temporaryBranch)&&!i.temporaryBranch.includes("..")&&i.temporaryBranch!==i.executionBranch&&i.worktreeRef===`wt/${o}`&&typeof i.worktreePath=="string"&&i.worktreePath.length<=4096&&(oe(i.worktreePath)||/^[A-Za-z]:[\\/]/.test(i.worktreePath))&&(i.workspaceMechanism==="client_managed_worktree"||i.workspaceMechanism==="native_subagent_worktree")&&typeof i.ownerId=="string"&&Re.test(i.ownerId)&&typeof i.nonceDigest=="string"&&ne.test(i.nonceDigest)&&typeof i.baseSha=="string"&&We.test(i.baseSha)&&typeof i.graphRevision=="string"&&ne.test(i.graphRevision)&&(i.state==="creating"||i.state==="active")&&typeof i.acquiredAt=="string"&&ze.test(i.acquiredAt)&&typeof i.expiresAt=="string"&&ze.test(i.expiresAt)&&(i.syncedSha===void 0||typeof i.syncedSha=="string"&&We.test(i.syncedSha))}function je(t,e){return t.epics[e]??(t.epics[e]={})}function zr(t,e){return t.stories[e]??(t.stories[e]={})}function wt(t,e,i,r){const n=d(t);return!!(n&&n.epicId===i&&n.branch===r&&n.qaVerdict==="passed"&&n.reviewVerdict==="approved"&&Ct(n,e))}async function Lr(t,e,i,r,n,c,o=[]){return bt(t,e,i,r,n,c,o).verdict==="verified"}function bt(t,e,i,r,n,c,o=[],a=new Date().toISOString(),g=c===void 0?"scheduling":"integration"){const s=()=>Rt({storyId:i,epicId:r,executionBranch:n,value:e,verifiedAt:a,verdict:"rejected",reasonCode:"checkpoint-git-physical-invalid"});try{if(!wt(e,i,r,n))return s();const f=d(e),h=d(f.qaReceipt),u=d(f.reviewReceipt),l=String(f.headSha),m=String(f.baseSha),R=Ge(t,i,l,u.reviewArtifactDigest===void 0),O=u.reviewArtifactDigest===void 0&&!zi(t,i,l);if(u.reviewArtifactDigest!==void 0&&u.reviewArtifactDigest!==R?.digest)return s();const D=x(t,["rev-parse",`refs/heads/${n}`]).trim();if(q("git",["merge-base","--is-ancestor",l,D],{cwd:t,stdio:"ignore"}),!O&&R?.verdict!=="approved"){if(u.reviewArtifactDigest!==void 0||!Wi(t,f,u,h,i,r,D))return s()}else if(f.reviewReconciliation!==void 0)return s();const y=x(t,["show","--no-patch","--format=%H%n%P%n%B",l]),w=x(t,["rev-parse",`${l}^`]).trim(),M=x(t,["rev-list","--count",`${m}..${l}`]).trim();if(w!==m||M!=="1")return s();const U=ii(y);if(!U.ok)return s();const E=U.values,k=Pe(E,"Neocortex-Review-Artifact-Digest");if(k!==void 0&&(k!==R?.digest||u.reviewArtifactDigest!==R?.digest))return s();const B=[["Neocortex-Story",i],["Neocortex-Epic",r],["Neocortex-Execution-Branch",n],["Neocortex-Bundle-Digest",String(f.bundleDigest)],["Neocortex-Graph-Revision",String(f.graphRevision)],...f.dispatchId?[["Neocortex-Dispatch",String(f.dispatchId)]]:[],...f.bundleId?[["Neocortex-Bundle",String(f.bundleId)]]:[],...f.claimRevision?[["Neocortex-Claim-Revision",String(f.claimRevision)]]:[]].every(([Y,Wt])=>Pe(E,Y)===Wt);if(B){const Y=Pe(E,"Neocortex-Prepared-Base")??"";if(!/^[a-f0-9]{40,64}$/i.test(Y))return s();q("git",["merge-base","--is-ancestor",Y,l],{cwd:t,stdio:"ignore"})}const T=x(t,["diff-tree","--no-commit-id","--name-only","-r","-z",l]).split("\0").filter(Boolean);if(T.length===0||T.some(Y=>!ge(Y)))return s();const Se=b("sha256").update(y).digest("hex"),le=b("sha256").update([...T].sort().join("\0")).digest("hex"),L=St({projectRoot:t,checkpoint:f,storyId:i,epicId:r,executionBranch:n,baseSha:m,headSha:l,commitBodyDigest:Se,changedPathsDigest:le,changedPaths:T,authorizedWriteSet:o.length>0?o:Hi(t,i)});if(!L||h.receiptRef!==`story-qa:${String(h.sourceEvidenceDigest)}`)return s();const Xe=Ni({storyId:i,baseSha:m,headSha:l,bundleDigest:String(f.bundleDigest),graphRevision:String(f.graphRevision),commitBody:y,changedPaths:T}),et=h.evidenceVersion==="p205-execution-v2"&&h.contract==="P205-CI-02"&&h.command===G&&p(h.manifestDigest)&&W(h.gateIds,32,!0)&&p(h.resultDigest)&&h.sourceEvidenceDigest===Vi({gitEvidenceDigest:Xe,headSha:l,graphRevision:String(f.graphRevision),manifestDigest:String(h.manifestDigest),gateIds:h.gateIds,resultDigest:String(h.resultDigest)}),Nt=h.evidenceVersion==="git-immutable-v1"&&h.sourceEvidenceDigest===Xe,Vt=h.evidenceVersion===void 0&&L.mode==="legacy-migration"&&L.binding?.qaDigest===h.sourceEvidenceDigest,Ae=Pi(c,D,String(f.graphRevision))&&(et||L.mode==="legacy-migration"&&(Nt||Vt)),Ie=g==="scheduling"&&c===void 0&&et;if(!Ae&&!Ie)return s();const tt=u.reviewArtifactDigest!==void 0,it=b("sha256").update([tt?"root-commit-range-review-v2":"root-commit-range-review-v1",i,m,l,String(f.bundleDigest),String(f.graphRevision),String(h.receiptRef),b("sha256").update(y).digest("hex"),[...T].sort().join(","),...tt?[R.digest]:[]].join("\0")).digest("hex");if(u.sourceEvidenceDigest!==it||u.receiptRef!==`story-review:${it}`||L.mode==="legacy-migration"&&L.binding?.reviewDigest!==void 0&&L.binding.reviewDigest!==u.sourceEvidenceDigest||!B&&(dt[i]!==l||!Array.isArray(f.receiptRefs)||!f.receiptRefs.some(Y=>typeof Y=="string"&&Y.startsWith("legacy-direct-yolo:"))))return s();const $t=b("sha256").update(["checkpoint-p205-transient-v1",i,r,n,m,l,String(f.bundleDigest),Se,le,L.mode,L.effectiveClaimRevision,String(h.sourceEvidenceDigest),String(u.sourceEvidenceDigest),...f.reviewReconciliation?[String(d(f.reviewReconciliation)?.sourceEvidenceDigest)]:[],ye(c)?.executionEvidenceDigest??(Ie?"scheduling-git-verification":"legacy-bounded-authority")].join("\0")).digest("hex"),ae=Ae?ye(c):void 0;return Object.freeze({schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:i,epicId:r,branch:n,baseSha:m,headSha:l,aggregateHeadSha:ae?.executionHeadSha??l,commitBodyDigest:Se,changedPathsDigest:le,claimVerification:L.mode,effectiveClaimRevision:L.effectiveClaimRevision,sourceEvidenceDigest:$t,command:G,manifestDigest:ae?.manifestDigest??"0".repeat(64),gateIds:ae?.gateIds??Object.freeze(["legacy-bounded"]),resultDigest:ae?.resultDigest??"0".repeat(64),graphRevision:String(f.graphRevision),executionEvidenceDigest:ae?.executionEvidenceDigest??"0".repeat(64),verifiedAt:ae?.executedAt??de(a),verdict:"verified",reasonCodes:Object.freeze([Ae?"checkpoint-p205-transient-verified":Ie?"checkpoint-git-scheduling-verified":"checkpoint-legacy-bounded-verified",...L.mode==="legacy-migration"?["checkpoint-legacy-migration-verified"]:[]]),publicSafe:!0})}catch{return s()}}function Bi(t,e,i,r,n,c,o=[],a=new Date().toISOString()){const g=c?"integration":"scheduling",s=bt(t,e,i,r,n,c,o,a,g);return s.verdict!=="verified"?{kind:"rejected",verification:s}:g==="integration"?{kind:"integration-authorized",verification:s}:s.reasonCodes.includes("checkpoint-git-scheduling-verified")?{kind:"scheduling-only",evidence:Object.freeze({schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:r,branch:n,baseSha:s.baseSha,headSha:s.headSha,graphRevision:s.graphRevision,effectiveClaimRevision:s.effectiveClaimRevision,sourceEvidenceDigest:s.sourceEvidenceDigest,verifiedAt:s.verifiedAt,reasonCodes:Object.freeze(["checkpoint-git-scheduling-verified"]),integrationAuthorized:!1,publicSafe:!0})}:{kind:"rejected",verification:Rt({storyId:i,epicId:r,executionBranch:n,value:e,verifiedAt:a,verdict:"rejected",reasonCode:"checkpoint-git-physical-invalid"})}}function Pi(t,e,i){const r=ye(t);return!!(r&&r.schemaVersion===1&&r.kind==="p205_transient_execution_authority"&&r.contract==="P205-CI-02"&&r.command===G&&r.graphRevision===i&&p(r.resultDigest)&&p(r.executionEvidenceDigest)&&r.executionHeadSha===e&&v(e))}function ye(t){return t&&typeof t=="object"?He.get(t):void 0}function qr(t){const e=ye(t);return e?Object.freeze({executionHeadSha:e.executionHeadSha,graphRevision:e.graphRevision,manifestDigest:e.manifestDigest,gateIds:Object.freeze([...e.gateIds]),resultDigest:e.resultDigest,executedAt:e.executedAt,executionEvidenceDigest:e.executionEvidenceDigest}):void 0}function jr(t,e,i){const r=ye(t);return!!(r&&r.executionHeadSha===e&&r.graphRevision===i&&r.command===G)}async function Mr(t,e,i,r=new Date().toISOString()){const n=JSON.parse(Oe(_(t,".neocortex","state.json"),"utf8")),c=gt(t,{required:!0}),o=lt(n,c),a=d(o.epics),g=d(o.stories),s=d(a?.[e.epicId]),f=d(s?.origin_binding),h=d(s?.aggregate_qa_receipt);if(!s||!g||s.branch_mode!=="epic"||s.execution_branch!==e.executionBranch||s.origin_branch!==e.originBranch||s.graph_revision!==e.graphRevision||!f||f.originHeadSha!==e.originHeadSha||f.originBranch!==e.originBranch||f.executionBranch!==e.executionBranch||!h||h.receiptRef!==i.receiptRef||h.executionHeadSha!==i.executionHeadSha||h.graphRevision!==i.graphRevision||h.manifestDigest!==i.manifestDigest||h.resultDigest!==i.resultDigest)throw new Error("epic-head-reconciliation-state-drift");const u=x(t,["symbolic-ref","--quiet","--short","HEAD"]).trim(),l=x(t,["rev-parse","HEAD"]).trim();if(u!==e.executionBranch||l!==e.executionHeadSha)throw new Error("epic-head-reconciliation-head-raced");q("git",["cat-file","-e",`${e.originHeadSha}^{commit}`],{cwd:t,stdio:"ignore"}),q("git",["merge-base","--is-ancestor",e.originHeadSha,l],{cwd:t,stdio:"ignore"});const m=Array.isArray(s.stories)?s.stories.filter(B=>typeof B=="string"):Object.keys(g).filter(B=>B.startsWith(`${e.epicId}.`)),R=[],O=new Set;for(const B of m){const Q=d(g[B]),T=d(Q?.checkpoint);if(!Q||!T)throw new Error("epic-head-reconciliation-checkpoint-drift");if(Bi(t,T,B,e.epicId,e.executionBranch,void 0,Me(B,Q,T),r).kind!=="scheduling-only")throw new Error("epic-head-reconciliation-checkpoint-drift");R.push(String(T.headSha));for(const le of Me(B,Q,T))O.add(le)}const D=R.at(-1);if(!D||D!==e.lastAcceptedCheckpointHeadSha)throw new Error("epic-head-reconciliation-checkpoint-drift");q("git",["merge-base","--is-ancestor",D,l],{cwd:t,stdio:"ignore"});const j=x(t,["rev-list","--first-parent","--reverse",`${D}..${l}`]).trim().split(`
|
|
3
|
+
`).filter(Boolean),y=x(t,["diff","--name-only","-z",`${D}..${l}`]).split("\0").filter(Boolean).sort(),w=[...O].sort(),M=Object.freeze({...e,revalidatedAt:de(r),inputDigest:void 0}),{inputDigest:U,...E}=M,k=Object.freeze({...E,inputDigest:nt(E)});if(!ie(m,k.acceptedCheckpointIds)||!ie(R,k.acceptedCheckpointHeads)||!ie(j,k.reconciliationCommitShas)||!ie(y,k.changedPaths)||!ie(w,k.allowedWriteSet)||!Zt(k,{epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,graphRevision:e.graphRevision,originHeadSha:e.originHeadSha,executionHeadSha:l,acceptedCheckpointIds:m,acceptedCheckpointHeads:R,aggregateQaReceipt:i,nowIso:r}))throw new Error("epic-head-reconciliation-physical-invalid");await $e(t,B=>{const Q=je(B,e.epicId),T=Q.head_reconciliation_receipt;if(!T||T.inputDigest!==e.inputDigest)throw new Error("epic-head-reconciliation-cas-conflict");Q.head_reconciliation_receipt=k},{expectedRevision:c.revision,preCommit:async()=>{if(x(t,["rev-parse","HEAD"]).trim()!==l||x(t,["symbolic-ref","--quiet","--short","HEAD"]).trim()!==u)throw new Error("epic-head-reconciliation-head-raced")}});const ue=Object.freeze(Object.create(null));return ft.set(ue,Object.freeze({executionHeadSha:l,graphRevision:e.graphRevision,aggregateReceiptRef:i.receiptRef,reconciliationInputDigest:k.inputDigest})),Object.freeze({authority:ue,receipt:k})}function Gr(t,e){if(!t||typeof t!="object"||Ne.has(t))return!1;const i=He.get(t),r=ft.get(t);return i&&i.executionHeadSha===e.executionHeadSha&&i.graphRevision===e.graphRevision&&i.manifestDigest===e.aggregateQaReceipt.manifestDigest&&i.resultDigest===e.aggregateQaReceipt.resultDigest&&i.executedAt===e.aggregateQaReceipt.checkedAt?(Ne.add(t),!0):!(r&&e.headReconciliationReceipt&&r.executionHeadSha===e.executionHeadSha&&r.graphRevision===e.graphRevision&&r.aggregateReceiptRef===e.aggregateQaReceipt.receiptRef&&r.reconciliationInputDigest===e.headReconciliationReceipt.inputDigest)?!1:(Ne.add(t),!0)}function St(t){const e=ri[t.storyId],i=typeof t.checkpoint.claimRevision=="string"?t.checkpoint.claimRevision:void 0,r=t.storyId==="P174.03.811759"||t.storyId==="P174.03.685003",n=Ti(t.authorizedWriteSet);let c=[];if(t.checkpoint.rootMemoryEffect!==void 0){if(e)return;try{c=Kt(t.projectRoot,t.checkpoint.rootMemoryEffect,{storyId:t.storyId,executionBranch:t.executionBranch,baseSha:t.baseSha,headRef:t.headSha,childPaths:n}).files.map(a=>a.path)}catch{return}}const o=n.length>0&&n.length===t.authorizedWriteSet.length&&t.changedPaths.every(a=>n.some(g=>_t(g,a))||c.includes(a));if(e&&t.epicId==="P174"&&t.executionBranch==="epic/P174"&&t.baseSha===e.baseSha&&t.headSha===e.headSha&&t.checkpoint.graphRevision===e.graphRevision&&t.commitBodyDigest===e.commitBodyDigest&&t.changedPathsDigest===e.changedPathsDigest&&(r?i===void 0:i===e.effectiveClaimRevision))return t.authorizedWriteSet.length>0&&(!o||!vt(e.effectiveClaimRevision,n))?void 0:Object.freeze({mode:"legacy-migration",effectiveClaimRevision:e.effectiveClaimRevision,binding:e});if(i!==void 0&&!(!i||!p(i))&&!(!o||!vt(i,n)))return Object.freeze({mode:"canonical",effectiveClaimRevision:i})}function Ti(t){const e=t.map(i=>i.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/{2,}/g,"/"));return e.some(i=>!Ze(i))?Object.freeze([]):Object.freeze([...new Set(e)].sort())}function Hi(t,e){try{const i=JSON.parse(Oe(_(t,".neocortex","state.json"),"utf8")),r=d(i.stories),n=d(r?.[e]),c=gt(t),o=d(c.stories[e]?.checkpoint)??d(n?.checkpoint),a=c.stories[e]?.write_set_extension;return Me(e,a!==void 0?{...n??{},write_set_extension:a}:n,o)}catch{return[]}}function Me(t,e,i){const r=Array.isArray(e?.files_to_modify)?e.files_to_modify.filter(o=>typeof o=="string"):[],n=hi(e).filter(o=>!r.includes(o)),c=n.length>0?[...r,...n]:r;if(!i?.dispatchId||!i.bundleId)return c;try{return Gt({...e,id:t,files_to_modify:c})}catch{return[]}}function vt(t,e){return t===b("sha256").update(e.join("\0")).digest("hex")||t===b("sha256").update(JSON.stringify(e)).digest("hex")}function _t(t,e){return t===e||t.endsWith("/")&&e.startsWith(t)}function Fr(t,e,i,r,n,c){try{if(!wt(e,i,r,n))return!1;const o=d(e),a=d(o.qaReceipt),g=d(o.reviewReceipt),s=String(o.headSha),f=String(o.baseSha),h=x(t,["rev-parse",`refs/heads/${n}`]).trim();if(q("git",["merge-base","--is-ancestor",s,h],{cwd:t,stdio:"ignore"}),x(t,["rev-parse",`${s}^`]).trim()!==f||x(t,["rev-list","--count",`${f}..${s}`]).trim()!=="1")return!1;const u=x(t,["show","--no-patch","--format=%H%n%P%n%B",s]),l=x(t,["diff-tree","--no-commit-id","--name-only","-r","-z",s]).split("\0").filter(Boolean);if(l.length===0||l.some(R=>!ge(R)))return!1;const m=St({projectRoot:t,checkpoint:o,storyId:i,epicId:r,executionBranch:n,baseSha:f,headSha:s,changedPaths:l,authorizedWriteSet:c,commitBodyDigest:b("sha256").update(u).digest("hex"),changedPathsDigest:b("sha256").update([...l].sort().join("\0")).digest("hex")});return!(m?.mode!=="legacy-migration"||!m.binding||a.sourceEvidenceDigest!==m.binding.qaDigest||a.receiptRef!==`story-qa:${m.binding.qaDigest}`||g.sourceEvidenceDigest!==m.binding.reviewDigest||g.receiptRef!==`story-review:${m.binding.reviewDigest}`||g.qaReceiptRef!==a.receiptRef)}catch{return!1}}function Ni(t){return b("sha256").update(["local-yolo-tdd-git-immutable-v1",t.storyId,t.baseSha,t.headSha,t.bundleDigest,t.graphRevision,b("sha256").update(t.commitBody).digest("hex"),b("sha256").update([...t.changedPaths].sort().join("\0")).digest("hex")].join("\0")).digest("hex")}function Vi(t){return b("sha256").update(["local-yolo-tdd-p205-execution-v2",G,t.gitEvidenceDigest,t.headSha,t.graphRevision,t.manifestDigest,t.gateIds.join(","),t.resultDigest].join("\0")).digest("hex")}function Rt(t){const e=d(t.value);return Object.freeze({schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t.storyId,epicId:t.epicId,branch:t.executionBranch,baseSha:v(e?.baseSha)?String(e?.baseSha):"0".repeat(40),headSha:v(e?.headSha)?String(e?.headSha):"0".repeat(40),aggregateHeadSha:"0".repeat(40),commitBodyDigest:"0".repeat(64),changedPathsDigest:"0".repeat(64),claimVerification:"canonical",effectiveClaimRevision:"0".repeat(64),command:G,manifestDigest:"0".repeat(64),gateIds:Object.freeze([]),resultDigest:"0".repeat(64),graphRevision:"0".repeat(64),executionEvidenceDigest:"0".repeat(64),sourceEvidenceDigest:"0".repeat(64),verifiedAt:de(t.verifiedAt),verdict:t.verdict,reasonCodes:Object.freeze([t.reasonCode]),publicSafe:!0})}function x(t,e){return q("git",[...e],{cwd:t,encoding:"utf8",maxBuffer:32*1024*1024})}function Ge(t,e,i,r=!1){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(e)||i!==":"&&!/^[a-f0-9]{40,64}$/i.test(i))return;const n=`.neocortex/stories/${e}/review.md`;let c;try{c=q("git",["show",`${i===":"?":":`${i}:`}${n}`],{cwd:t,maxBuffer:128*1024,stdio:["ignore","pipe","ignore"]})}catch{return}if(c.length===0||c.length>64*1024||c.includes(0))return;let o;try{o=new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch{return}const a=o.replace(/\r\n/g,`
|
|
4
|
+
`).split(`
|
|
5
|
+
`),g=new RegExp(`^#\\s+${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?=\\s|$|[:\u2014-])`);if(!a.some(u=>g.test(u)))return;const s=a.filter(u=>/^Verdict\s*:/i.test(u));if(a.some(u=>/^Status\s*:\s*(pending|changes-requested|rejected)\b/i.test(u)))return;const f=a.filter(u=>/^Decision\s*:/i.test(u));if(s.length===0&&r&&f.length===1&&/^Decision\s*:\s*APPROVED\b/i.test(f[0]))return Object.freeze({verdict:"approved",digest:b("sha256").update(c).digest("hex")});if(s.length!==1)return;const h=/^Verdict\s*:\s*(approved|pending|changes-requested)(?=\s|$|[;,.])/i.exec(s[0])?.[1]?.toLowerCase();if(!(h!=="approved"&&h!=="pending"&&h!=="changes-requested"))return Object.freeze({verdict:h,digest:b("sha256").update(c).digest("hex")})}function $i(t){return b("sha256").update(["root-historical-review-reconciliation-v1",t.storyId,t.epicId,t.checkpointHeadSha,t.approvalCommitSha,t.approvalArtifactDigest,t.qaReceiptRef,t.reviewReceiptRef,b("sha256").update(t.approvalCommitBody).digest("hex")].join("\0")).digest("hex")}function Wi(t,e,i,r,n,c,o){const a=d(e.reviewReconciliation);if(!a||!Ot(a,e))return!1;const g=String(a.approvalCommitSha),s=String(e.headSha);if(g===s)return!1;try{if(q("git",["merge-base","--is-ancestor",s,g],{cwd:t,stdio:"ignore"}),q("git",["merge-base","--is-ancestor",g,o],{cwd:t,stdio:"ignore"}),!x(t,["rev-list","--first-parent",o]).split(`
|
|
6
|
+
`).includes(g))return!1;const f=x(t,["show","--no-patch","--format=%P",g]).trim().split(/\s+/);if(f.length!==1||!v(f[0]))return!1;const h=x(t,["show","--no-patch","--format=%H%n%P%n%B",g]),u=new Set(h.split(`
|
|
7
|
+
`).map(j=>j.trim()));if(!u.has(`Neocortex-Review-Reconciliation: ${n}`)||!u.has(`Neocortex-Original-Checkpoint: ${s}`)||!u.has(`Neocortex-Original-Review-Receipt: ${String(i.receiptRef)}`))return!1;const l=`.neocortex/stories/${n}/review.md`,m=x(t,["diff-tree","--no-commit-id","--name-only","-r","-z",g]).split("\0").filter(Boolean);if(!m.includes(l)||m.some(j=>!ge(j)))return!1;const R=Ge(t,n,g);if(R?.verdict!=="approved"||R.digest!==a.approvalArtifactDigest)return!1;const O=Ge(t,n,o);if(O?.verdict!=="approved"||O.digest!==R.digest)return!1;const D=$i({storyId:n,epicId:c,checkpointHeadSha:s,approvalCommitSha:g,approvalArtifactDigest:R.digest,qaReceiptRef:String(r.receiptRef),reviewReceiptRef:String(i.receiptRef),approvalCommitBody:h});return a.sourceEvidenceDigest===D&&a.receiptRef===`story-review-reconciliation:${D}`}catch{return!1}}function zi(t,e,i){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(e)||!/^[a-f0-9]{40,64}$/i.test(i))return!1;try{return q("git",["cat-file","-e",`${i}:.neocortex/stories/${e}/review.md`],{cwd:t,stdio:"ignore",maxBuffer:1024}),!0}catch{return!1}}function de(t){return Number.isFinite(Date.parse(t))?new Date(Date.parse(t)).toISOString():new Date().toISOString()}async function Kr(t,e){if(dt[e.storyId]!==e.headSha)return;const i=[".neocortex/state.json",`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,`.neocortex/stories/${e.storyId}/review.md`,`docs/stories/${e.storyId}.story.md`];try{const r=(await z("git",["rev-parse",`refs/heads/${e.executionBranch}`],{cwd:t,encoding:"utf8",maxBuffer:1048576})).stdout.trim();if(await z("git",["merge-base","--is-ancestor",e.headSha,r],{cwd:t}),(await z("git",["rev-parse",`${e.headSha}^`],{cwd:t,encoding:"utf8",maxBuffer:1024*1024})).stdout.trim()!==e.baseSha)return;const c=String((await z("git",["diff","--binary","--full-index",`${e.baseSha}..${e.headSha}`],{cwd:t,encoding:"utf8",maxBuffer:32*1024*1024})).stdout);if(b("sha256").update(c).digest("hex")!==e.bundleDigest)return;const o=String((await z("git",["show","--no-patch","--format=%H%n%P%n%B",e.headSha],{cwd:t,encoding:"utf8",maxBuffer:4*1024*1024})).stdout);if(!String((await z("git",["show","--no-patch","--format=%s",e.headSha],{cwd:t,encoding:"utf8",maxBuffer:1024*1024})).stdout).trim().includes(e.storyId))return;const s=String((await z("git",["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha],{cwd:t,encoding:"utf8",maxBuffer:8*1024*1024})).stdout).split("\0").filter(Boolean);if(!i.every(y=>s.includes(y))||s.some(y=>!ge(y)))return;const f=await Promise.all(i.map(async y=>String((await z("git",["show",`${e.headSha}:${y}`],{cwd:t,encoding:"utf8",maxBuffer:16*1024*1024})).stdout))),h=JSON.parse(f[0]),u=d(h.stories),l=d(h.epics),m=d(u?.[e.storyId]),R=d(l?.[e.epicId]),O=Array.isArray(m?.steps_completed)?m.steps_completed:[],D=JSON.parse(f[1]);return m?.status!=="done"||!O.includes(ei)||!O.includes(ti)||R?.branch_mode!=="epic"||R.execution_branch!==e.executionBranch||D.storyId!==e.storyId||D.status!=="qa-passed"||D.safeToContinueYoloop!==!0||!Array.isArray(D.blockingChecks)||D.blockingChecks.length!==0||!f[2].includes(e.storyId)||!/P205[\s\S]{0,80}(pass|aprov)/i.test(f[2])||!f[3].includes(e.storyId)||!/approved|aprovado/i.test(f[3])||!f[4].includes(e.storyId)?void 0:`legacy-direct-yolo:${b("sha256").update(["legacy-direct-yolo-recovery-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,b("sha256").update(o).digest("hex"),b("sha256").update([...s].sort().join("\0")).digest("hex"),...f.map(y=>b("sha256").update(y).digest("hex"))].join("\0")).digest("hex")}`}catch{return}}async function Li(t){const e=await Ke(t),i=_(e,ve),r=_(i,_e);if(K(i)&&(await J(i,"directory"),await re(i)!==i))throw new Error("git-lifecycle-runtime-directory-symlink");return K(r)?r:_(e,Te)}async function Dt(t){return At(await Ke(t))}async function qi(t,e){if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)||e.includes(".."))throw new Error("git-lifecycle-private-child-invalid");const i=S(t);await ee(i);const r=S(i,e);return fe(i,r),K(r)||await ot(i,e),await ee(r,i),await ee(i),r}async function C(t,e){const i=S(e),r=S(t);fe(i,r),await ee(i),await ee(r,i)}async function Jr(t,e){await te(t,e)}async function ce(t,e,i){const r=S(e),n=S(t);fe(r,n);try{await C(n,r)}catch(o){if(V(o,"ENOENT"))return!1;throw o}const c=S(r,`${n.slice(r.length+1)}.remove.${process.pid}.${Date.now()}.${ke(4).toString("hex")}`);return fe(r,c),await se(r,H(n),H(c)),await C(c,r),i&&!await i(c)?(await we(c,n,r).catch(()=>{}),!1):(await Xt(r,H(c)),!0)}async function we(t,e,i){await C(t,i);try{await Ce(e);return}catch(r){if(!V(r,"ENOENT"))throw r}await se(i,H(t),H(e)),await C(e,i)}async function $(t){try{await C(t,X(t));const e=_(t,"owner.json");await te(e,t);const i=await Z(e);return await te(e,t),b("sha256").update(i).digest("hex")}catch{return}}async function Yr(t,e){const i=await Dt(t),r=await qi(i,"leases"),n=_(r,"integration"),c=`${n}.recovery`;if(K(c)){await C(c,r);const s=await Et(c),f=await $(c);if(s===void 0||xe(s))return{ok:!1,reasonCode:"git-lifecycle-integration-backpressure"};if(!f||!await ce(c,r,async h=>await $(h)===f))return{ok:!1,reasonCode:"git-lifecycle-integration-backpressure"}}const o=de(e.createdAt??new Date().toISOString()),a=Object.freeze({schemaVersion:1,kind:e.kind,storyId:e.storyId,sessionId:e.sessionId,idempotencyKey:e.idempotencyKey,pid:process.pid,createdAt:o,expiresAt:de(e.expiresAt),persistent:e.persistent,ownerNonce:e.ownerNonce??ke(16).toString("hex")});if(Date.parse(a.expiresAt)<=Date.parse(a.createdAt))return{ok:!1,reasonCode:"git-lifecycle-integration-lock-failed"};const g=async()=>{await ee(r,i);try{return await at(r,H(n),`${JSON.stringify(a)}
|
|
8
|
+
`),await C(n,r),await te(_(n,"owner.json"),n),!0}catch(s){throw V(s,"EEXIST")||await ce(n,r).catch(()=>{}),s}};try{return await g(),{ok:!0,owner:a,path:n}}catch(s){if(!V(s,"EEXIST"))return{ok:!1,reasonCode:"git-lifecycle-integration-lock-failed"}}try{const s=await be(n),f=s?void 0:await Et(n);if(s&&xt(s,a))return{ok:!0,owner:s,path:n};if(s&&Date.parse(s.expiresAt)>Date.now()&&(s.persistent||xe(s.pid))||f!==void 0&&xe(f)||!s&&f===void 0&&await Tt(n))return{ok:!1,reasonCode:"git-lifecycle-integration-backpressure"};const u=await $(n);if(!u)return{ok:!1,reasonCode:"git-lifecycle-integration-lock-failed"};const l=`${n}.stale.${process.pid}.${Date.now()}`;await se(r,H(n),H(l));try{if(await C(l,r),await $(l)!==u)return await we(l,n,r).catch(()=>{}),{ok:!1,reasonCode:"git-lifecycle-integration-backpressure"};await g()}finally{await ce(l,r,async m=>await $(m)===u).catch(()=>{})}return{ok:!0,owner:a,path:n}}catch(s){return{ok:!1,reasonCode:V(s,"EEXIST")||V(s,"ENOENT")?"git-lifecycle-integration-backpressure":"git-lifecycle-integration-lock-failed"}}}async function Zr(t,e){const i=await be(t);return!!(i&&Fe(i,e)&&Date.parse(i.expiresAt)>Date.now())}async function ji(t,e){try{const i=X(t);await C(t,i);const r=await be(t);if(!r||!Fe(r,e))return!1;const n=await $(t);if(!n)return!1;const c=`${t}.release.${process.pid}.${Date.now()}`;await se(i,H(t),H(c)),await C(c,i);const o=await be(c);return!o||!Fe(o,e)||await $(c)!==n?(await we(c,t,i).catch(()=>{}),!1):ce(c,i,async a=>await $(a)===n)}catch(i){if(V(i,"ENOENT"))return!1;throw i}}function Mi(t){return b("sha256").update(["git-lifecycle-physical-owner-v1",t.kind,t.storyId,t.sessionId,t.idempotencyKey,String(t.pid),t.createdAt,t.expiresAt,t.persistent?"persistent":"ephemeral",t.ownerNonce].join("\0")).digest("hex")}async function Ur(t,e){if(!N(e.storyId)||!P(e.idempotencyKey)||!p(e.ownerDigest))return"foreign";const i=await Dt(t),r=_(i,"leases"),n=_(r,"integration");if(!K(n))return"absent";try{await C(r,i),await C(n,r);const c=await be(n);return!c||c.kind!=="direct"||c.storyId!==e.storyId||c.sessionId!==e.idempotencyKey||c.idempotencyKey!==e.idempotencyKey||c.persistent!==!0||Mi(c)!==e.ownerDigest?"foreign":await ji(n,c)?"released":"foreign"}catch{return"foreign"}}async function be(t){try{await C(t,X(t));const e=_(t,"owner.json");await te(e,t);const i=JSON.parse(await Z(e,"utf8"));return i.schemaVersion!==1||i.kind!=="direct"&&i.kind!=="continuous"||!N(i.storyId)||!P(i.sessionId)||!P(i.idempotencyKey)||!Number.isSafeInteger(i.pid)||Number(i.pid)<=0||!I(i.createdAt)||!I(i.expiresAt)||typeof i.persistent!="boolean"||typeof i.ownerNonce!="string"||!/^[a-f0-9]{32}$/.test(i.ownerNonce)?void 0:i}catch{return}}async function Et(t){try{await C(t,X(t));const e=_(t,"owner.json");await te(e,t);const i=JSON.parse(await Z(e,"utf8"));return Number.isSafeInteger(i.pid)&&Number(i.pid)>0?Number(i.pid):void 0}catch{return}}function xt(t,e){return t.kind===e.kind&&t.storyId===e.storyId&&t.sessionId===e.sessionId&&t.idempotencyKey===e.idempotencyKey&&t.expiresAt===e.expiresAt&&t.persistent===e.persistent}function Fe(t,e){return xt(t,e)&&t.schemaVersion===e.schemaVersion&&t.pid===e.pid&&t.createdAt===e.createdAt&&t.ownerNonce===e.ownerNonce}async function Ke(t){const e=await re(t),r=(await z("git",["rev-parse","--git-common-dir"],{cwd:e,encoding:"utf8",maxBuffer:1024*1024})).stdout.trim(),n=oe(r)?S(r):S(e,r),c=await re(n);if(c!==n)throw new Error("git-lifecycle-common-dir-symlink");await Fi(c);const a=(await z("git",["rev-parse","--git-common-dir"],{cwd:e,encoding:"utf8",maxBuffer:1024*1024})).stdout.trim();if((oe(a)?S(a):S(e,a))!==n)throw new Error("git-lifecycle-common-dir-raced");return c}async function At(t){const e=_(t,ve);if(K(e)||await ot(t,ve),await J(e,"directory"),await re(e)!==e)throw new Error("git-lifecycle-runtime-directory-symlink");return e}async function It(t,e={}){try{return await J(t,"file"),Je(JSON.parse(await Z(t,"utf8")))}catch(i){if(V(i,"ENOENT")){if(e.required)throw new Error("git-lifecycle-runtime-missing");return Ue()}throw i}}async function Gi(t){try{await J(t,"file")}catch(e){if(V(e,"ENOENT"))return;throw e}}async function J(t,e){const i=await Ce(t);if(i.isSymbolicLink())throw new Error(`git-lifecycle-${e}-symlink`);if(e==="file"?!i.isFile():!i.isDirectory())throw new Error(`git-lifecycle-${e}-invalid`);if(Ee()&&i.uid!==process.getuid())throw new Error(`git-lifecycle-${e}-ownership-mismatch`);if(Ee()&&(i.mode&63)!==0)throw new Error(`git-lifecycle-${e}-permissions-unsafe`)}function fe(t,e){const i=S(t),r=S(e),n=jt(i,r);if(!n||n.startsWith("..")||oe(n)||X(r)!==i)throw new Error("git-lifecycle-private-path-escape")}async function ee(t,e){const i=S(t);if(e&&fe(S(e),i),await J(i,"directory"),S(await re(i))!==i)throw new Error("git-lifecycle-directory-substituted");if(e){const r=S(e);if(await J(r,"directory"),S(await re(r))!==r)throw new Error("git-lifecycle-directory-parent-substituted")}}async function te(t,e){const i=S(t);if(fe(S(e),i),await ee(S(e)),await J(i,"file"),S(await re(i))!==i)throw new Error("git-lifecycle-file-substituted")}function kt(t,e){const i=rt(t);if(i.isSymbolicLink())throw new Error(`git-lifecycle-${e}-symlink`);if(e==="file"?!i.isFile():!i.isDirectory())throw new Error(`git-lifecycle-${e}-invalid`);if(Ee()&&i.uid!==process.getuid())throw new Error(`git-lifecycle-${e}-ownership-mismatch`);if(Ee()&&(i.mode&63)!==0)throw new Error(`git-lifecycle-${e}-permissions-unsafe`)}async function Fi(t){const e=await Ce(t);if(e.isSymbolicLink())throw new Error("git-lifecycle-common-dir-symlink");if(!e.isDirectory())throw new Error("git-lifecycle-common-dir-invalid")}function Ki(t){const e=rt(t);if(e.isSymbolicLink())throw new Error("git-lifecycle-common-dir-symlink");if(!e.isDirectory())throw new Error("git-lifecycle-common-dir-invalid")}function Ee(t=process.platform){return t!=="win32"&&typeof process.getuid=="function"}function Je(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("git-lifecycle-runtime-invalid");const e=t,i=e.schemaVersion;if(A(e,i===2?["schemaVersion","revision","epics","stories","operational","storyWorktrees"]:["schemaVersion","revision","epics","stories","storyWorktrees"],"git-lifecycle-runtime-unknown-field"),e.storyWorktrees!==void 0&&!Ci(e.storyWorktrees))throw new Error("git-lifecycle-runtime-story-worktrees-invalid");const r=d(e.epics),n=d(e.stories);if(i!==1&&i!==2||!Number.isSafeInteger(e.revision)||Number(e.revision)<0||!r||!n||Object.values(r).some(c=>!d(c))||Object.values(n).some(c=>!d(c))||i===2&&!Ji(e.operational))throw new Error("git-lifecycle-runtime-invalid");for(const[c,o]of Object.entries(r))if(!N(c)||!Ui(o))throw new Error("git-lifecycle-runtime-epic-invalid");for(const[c,o]of Object.entries(n))if(!N(c)||!c.includes(".")||!Qi(o,c))throw new Error("git-lifecycle-runtime-story-invalid");return e}function Ji(t){const e=d(t);if(!e)return!1;A(e,["schemaVersion","repositoryFingerprint","writerEpoch","capabilities","identities","yoloop","projectionBindings","activeJournal","backfillReceipts","reconciliationReceipts","rollbackReceipts"],"git-lifecycle-runtime-operational-unknown-field");const i=d(e.identities),r=d(e.yoloop),n=d(e.projectionBindings);return e.schemaVersion==="EpicOperationalState/1.0"&&p(e.repositoryFingerprint)&&Number.isSafeInteger(e.writerEpoch)&&Number(e.writerEpoch)>=1&&Array.isArray(e.capabilities)&&e.capabilities.length<=16&&e.capabilities.every(c=>P(c))&&!!i&&Object.keys(i).length<=2048&&!!r&&r.schemaVersion==="CommonYoloopAuthority/1.0"&&!!n&&(e.activeJournal===null||!!d(e.activeJournal))&&Ye(e.backfillReceipts,64)&&Ye(e.reconciliationReceipts,64)&&Ye(e.rollbackReceipts,64)}function Ye(t,e){return Array.isArray(t)&&t.length<=e&&t.every(i=>!!d(i))}const Yi=["branch_mode","execution_branch","origin_branch","branch_lease","origin_binding","graph_revision","aggregate_qa_receipt","head_reconciliation_receipt","terminal_git_receipt","physicalMergeStatus","pr_number","git_reconciliation_receipts","git_reconciliation_debt","story_worktree_evidence"],Zi=["checkpoint","status","last_step","steps_completed","write_set_extension"];function Ui(t){return A(t,Yi,"git-lifecycle-runtime-epic-unknown-field"),(t.branch_mode===void 0||t.branch_mode==="epic")&&(t.execution_branch===void 0||F(t.execution_branch))&&(t.origin_branch===void 0||F(t.origin_branch))&&(t.branch_lease===void 0||t.branch_lease===null||Xi(t.branch_lease))&&(t.origin_binding===void 0||t.origin_binding===null||ir(t.origin_binding))&&(t.graph_revision===void 0||p(t.graph_revision))&&(t.aggregate_qa_receipt===void 0||t.aggregate_qa_receipt===null||rr(t.aggregate_qa_receipt))&&(t.head_reconciliation_receipt===void 0||t.head_reconciliation_receipt===null||nr(t.head_reconciliation_receipt))&&(t.terminal_git_receipt===void 0||t.terminal_git_receipt===null||cr(t.terminal_git_receipt))&&(t.physicalMergeStatus===void 0||["merged","pushed","denied_external_gate","blocked_local_or_repo","not_attempted"].includes(String(t.physicalMergeStatus)))&&(t.pr_number===void 0||t.pr_number===null||Number.isSafeInteger(t.pr_number)&&Number(t.pr_number)>0)&&(t.git_reconciliation_receipts===void 0||fr(t.git_reconciliation_receipts))&&(t.git_reconciliation_debt===void 0||gr(t.git_reconciliation_debt))&&(t.story_worktree_evidence===void 0||me(t.story_worktree_evidence))}function Qi(t,e){return A(t,Zi,"git-lifecycle-runtime-story-unknown-field"),(t.checkpoint===void 0||t.checkpoint===null||Ct(t.checkpoint,e))&&(t.status===void 0||P(t.status))&&(t.last_step===void 0||t.last_step===null||P(t.last_step))&&(t.steps_completed===void 0||W(t.steps_completed,128))&&(t.write_set_extension===void 0||ut(t.write_set_extension))}function Xi(t){const e=d(t);return e?(A(e,["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt","handoffGrant","handoffConsumption","setupHeadSha"],"git-lifecycle-runtime-lease-unknown-field"),e.schemaVersion===1&&N(e.ownerStoryId)&&P(e.sessionId)&&P(e.idempotencyKey)&&I(e.acquiredAt)&&I(e.expiresAt)&&Date.parse(String(e.expiresAt))>Date.parse(String(e.acquiredAt))&&(e.setupHeadSha===void 0||v(e.setupHeadSha))&&(e.handoffGrant===void 0||er(e.handoffGrant,e))&&(e.handoffConsumption===void 0||tr(e.handoffConsumption,e))):!1}function er(t,e){const i=d(t);return i?(A(i,["schemaVersion","kind","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","expiresAt"],"git-lifecycle-runtime-handoff-grant-unknown-field"),i.schemaVersion===1&&i.kind==="direct-yolo-setup-handoff"&&i.storyId===e.ownerStoryId&&i.fromSessionId===e.sessionId&&p(i.tokenDigest)&&p(i.bundleDigest)&&p(i.claimRevision)&&I(i.expiresAt)&&Date.parse(String(i.expiresAt))<=Date.parse(String(e.expiresAt))):!1}function tr(t,e){const i=d(t);return i?(A(i,["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","consumedBySessionId","consumedAt"],"git-lifecycle-runtime-handoff-consumption-unknown-field"),i.schemaVersion===1&&i.kind==="direct-yolo-setup-handoff-consumption"&&i.state==="consumed"&&i.storyId===e.ownerStoryId&&P(i.fromSessionId)&&p(i.tokenDigest)&&p(i.bundleDigest)&&p(i.claimRevision)&&i.consumedBySessionId===e.sessionId&&I(i.consumedAt)):!1}function ir(t){const e=d(t);return e?(A(e,["schemaVersion","originBranch","originHeadSha","executionBranch","capturedFromCurrentCheckout","capturedAt"],"git-lifecycle-runtime-origin-unknown-field"),e.schemaVersion===1&&F(e.originBranch)&&F(e.executionBranch)&&e.originBranch!==e.executionBranch&&v(e.originHeadSha)&&e.capturedFromCurrentCheckout===!0&&I(e.capturedAt)):!1}function rr(t){const e=d(t);if(!e)return!1;A(e,["schemaVersion","evidenceVersion","producer","contract","command","verdict","executionHeadSha","graphRevision","manifestDigest","resultDigest","checkedAt","receiptRef","gateIds"],"git-lifecycle-runtime-aggregate-qa-unknown-field");const i=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command===G&&p(e.manifestDigest)&&p(e.resultDigest),r=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0;return e.schemaVersion===1&&(i||r)&&e.verdict==="passed"&&v(e.executionHeadSha)&&p(e.graphRevision)&&I(e.checkedAt)&&he(e.receiptRef)&&W(e.gateIds,128,!0)}function nr(t){const e=d(t);if(!e)return!1;A(e,["schemaVersion","kind","producer","epicId","executionBranch","originBranch","graphRevision","originHeadSha","lastAcceptedCheckpointHeadSha","executionHeadSha","acceptedCheckpointIds","acceptedCheckpointHeads","reconciliationCommitShas","commitRangeDigest","changedPaths","changedPathsDigest","allowedWriteSet","allowedWriteSetDigest","aggregateReceiptRef","aggregateManifestDigest","aggregateResultDigest","producedAt","revalidatedAt","inputDigest","publicSafe"],"git-lifecycle-runtime-head-reconciliation-unknown-field");const i=W(e.acceptedCheckpointIds,2048,!0)?e.acceptedCheckpointIds:[],r=W(e.acceptedCheckpointHeads,2048,!0)?e.acceptedCheckpointHeads:[],n=W(e.reconciliationCommitShas,2048)?e.reconciliationCommitShas:[],c=Pt(e.changedPaths,2048)?e.changedPaths:[],o=Pt(e.allowedWriteSet,2048,!0)?e.allowedWriteSet:[];if(e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0||!N(e.epicId)||!F(e.executionBranch)||!F(e.originBranch)||e.executionBranch===e.originBranch||!p(e.graphRevision)||!v(e.originHeadSha)||!v(e.lastAcceptedCheckpointHeadSha)||!v(e.executionHeadSha)||i.length===0||i.length!==r.length||i.some(g=>!N(g)||!g.startsWith(`${String(e.epicId)}.`))||r.some(g=>!v(g))||n.some(g=>!v(g))||o.length===0||e.lastAcceptedCheckpointHeadSha!==e.executionHeadSha&&(n.length===0||c.length===0)||e.lastAcceptedCheckpointHeadSha===e.executionHeadSha&&(n.length!==0||c.length!==0)||!ie(c,[...new Set(c)].sort())||!ie(o,[...new Set(o)].sort())||c.some(g=>!ge(g))||o.some(g=>!Ze(g))||c.some(g=>!o.some(s=>_t(s,g)))||!p(e.commitRangeDigest)||!p(e.changedPathsDigest)||!p(e.allowedWriteSetDigest)||!he(e.aggregateReceiptRef)||!p(e.aggregateManifestDigest)||!p(e.aggregateResultDigest)||!I(e.producedAt)||!I(e.revalidatedAt)||Date.parse(String(e.revalidatedAt))<Date.parse(String(e.producedAt))||!p(e.inputDigest))return!1;const a=e;return a.commitRangeDigest===Yt(a.lastAcceptedCheckpointHeadSha,a.executionHeadSha,a.reconciliationCommitShas)&&a.changedPathsDigest===ct(a.changedPaths)&&a.allowedWriteSetDigest===ct(a.allowedWriteSet)&&a.inputDigest===nt(a)}function cr(t){const e=d(t);return e?(A(e,["schemaVersion","epicId","executionBranch","originBranch","baseSha","executionHeadSha","mergeSha","pushedSha","strategy","prNumber","physicalStatus","localGateReceiptRefs","idempotencyKey","attemptStartedAt","completedAt","retryEligible","reasonCodes","publicSafe","candidateQa","providerGuard"],"git-lifecycle-runtime-terminal-receipt-unknown-field"),e.schemaVersion===1&&N(e.epicId)&&F(e.executionBranch)&&F(e.originBranch)&&v(e.baseSha)&&v(e.executionHeadSha)&&(e.mergeSha===void 0||v(e.mergeSha))&&(e.pushedSha===void 0||v(e.pushedSha))&&(e.strategy==="direct"||e.strategy==="single_pr")&&(e.candidateQa===void 0||or(e.candidateQa,e))&&(e.providerGuard===void 0||ar(e.providerGuard,e))&&(e.prNumber===void 0||Number.isSafeInteger(e.prNumber)&&Number(e.prNumber)>0)&&["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))&&W(e.localGateReceiptRefs,128,!0)&&P(e.idempotencyKey)&&I(e.attemptStartedAt)&&(e.completedAt===void 0||I(e.completedAt))&&typeof e.retryEligible=="boolean"&&W(e.reasonCodes,128)&&e.publicSafe===!0):!1}function ar(t,e){const i=d(t);if(!i)return!1;A(i,["schemaVersion","provider","mode","source","prHeadSha","originHeadSha","checkedAt","publicSafe"],"git-lifecycle-runtime-provider-guard-unknown-field");const r=i.mode==="recovered_exact_tree"?i.source==="physical_recovery":i.mode==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(String(i.source));return i.schemaVersion===1&&i.provider==="github"&&r&&e.strategy==="single_pr"&&e.physicalStatus==="pushed"&&Number.isSafeInteger(e.prNumber)&&Number(e.prNumber)>0&&v(i.prHeadSha)&&i.prHeadSha===e.mergeSha&&v(i.originHeadSha)&&i.originHeadSha===e.baseSha&&I(i.checkedAt)&&i.publicSafe===!0}function or(t,e){const i=d(t);return i?(A(i,["schemaVersion","kind","contract","command","originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest","gateIds","checkedAt","receiptRef"],"git-lifecycle-runtime-merge-candidate-unknown-field"),i.schemaVersion===1&&i.kind==="epic_merge_candidate_qa"&&i.contract==="P205-CI-02"&&i.command===G&&v(i.originHeadSha)&&i.originHeadSha===e.baseSha&&v(i.executionHeadSha)&&i.executionHeadSha===e.executionHeadSha&&v(i.mergeSha)&&i.mergeSha===e.mergeSha&&v(i.treeSha)&&p(i.graphRevision)&&p(i.manifestDigest)&&p(i.resultDigest)&&W(i.gateIds,128,!0)&&I(i.checkedAt)&&he(i.receiptRef)):!1}function Ct(t,e){const i=d(t);if(!i)return!1;A(i,["schemaVersion","storyId","epicId","branch","baseSha","headSha","commits","idempotencyKey","dispatchId","bundleId","bundleDigest","graphRevision","claimRevision","receiptRefs","qaVerdict","reviewVerdict","qaReceipt","reviewReceipt","reviewReconciliation","recordedAt","rootMemoryEffect"],"git-lifecycle-runtime-checkpoint-unknown-field");const r=String(e).split(".")[0];return i.schemaVersion===1&&i.storyId===e&&i.epicId===r&&F(i.branch)&&v(i.baseSha)&&v(i.headSha)&&i.baseSha!==i.headSha&&ur(i.commits)&&i.commits.length===1&&i.commits[0]===i.headSha&&P(i.idempotencyKey)&&(i.dispatchId===void 0||p(i.dispatchId))&&(i.bundleId===void 0||p(i.bundleId))&&p(i.bundleDigest)&&p(i.graphRevision)&&(i.claimRevision===void 0||p(i.claimRevision))&&(i.rootMemoryEffect===void 0||Ft(i.rootMemoryEffect)&&i.rootMemoryEffect.storyId===e&&i.rootMemoryEffect.executionBranch===i.branch&&i.rootMemoryEffect.sourceHeadSha===i.baseSha&&i.rootMemoryEffect.childClaimRevision===i.claimRevision)&&W(i.receiptRefs,256,!0)&&(i.qaVerdict==="passed"||i.qaVerdict==="blocked")&&["approved","changes-requested","pending"].includes(String(i.reviewVerdict))&&sr(i.qaReceipt,i)&&(i.reviewVerdict==="pending"?i.reviewReceipt===void 0:dr(i.reviewReceipt,i))&&(i.reviewReconciliation===void 0||Ot(i.reviewReconciliation,i))&&I(i.recordedAt)}function Ot(t,e){const i=d(t),r=d(e.qaReceipt),n=d(e.reviewReceipt);return!i||!r||!n?!1:(A(i,["schemaVersion","kind","storyId","epicId","checkpointHeadSha","approvalCommitSha","approvalArtifactDigest","qaReceiptRef","reviewReceiptRef","sourceEvidenceDigest","reviewedAt","receiptRef"],"git-lifecycle-runtime-review-reconciliation-unknown-field"),i.schemaVersion===1&&i.kind==="historical_review_reconciliation"&&i.storyId===e.storyId&&i.epicId===e.epicId&&i.checkpointHeadSha===e.headSha&&v(i.approvalCommitSha)&&p(i.approvalArtifactDigest)&&i.qaReceiptRef===r.receiptRef&&i.reviewReceiptRef===n.receiptRef&&p(i.sourceEvidenceDigest)&&I(i.reviewedAt)&&Date.parse(String(i.reviewedAt))>=Date.parse(String(r.checkedAt))&&he(i.receiptRef)&&Array.isArray(e.receiptRefs)&&e.receiptRefs.includes(i.receiptRef))}function sr(t,e){const i=d(t);return i?(A(i,["schemaVersion","kind","producer","evidenceVersion","storyId","epicId","baseSha","headSha","bundleDigest","graphRevision","contract","command","manifestDigest","gateIds","resultDigest","sourceEvidenceDigest","verdict","checkedAt","receiptRef"],"git-lifecycle-runtime-story-qa-unknown-field"),i.schemaVersion===1&&i.kind==="story_qa_evidence"&&i.producer==="local-yolo-tdd"&&(i.evidenceVersion===void 0||i.evidenceVersion==="git-immutable-v1"||i.evidenceVersion==="p205-execution-v2"&&i.contract==="P205-CI-02"&&i.command===G&&p(i.manifestDigest)&&W(i.gateIds,32,!0)&&p(i.resultDigest))&&Bt(i,e)&&p(i.sourceEvidenceDigest)&&i.verdict===e.qaVerdict&&(i.verdict==="passed"||i.verdict==="blocked")&&I(i.checkedAt)&&he(i.receiptRef)&&e.receiptRefs.includes(i.receiptRef)):!1}function dr(t,e){const i=d(t),r=d(e.qaReceipt);return!i||!r?!1:(A(i,["schemaVersion","kind","producer","storyId","epicId","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","reviewArtifactDigest","qaReceiptRef","verdict","reviewedAt","receiptRef"],"git-lifecycle-runtime-story-review-unknown-field"),i.schemaVersion===1&&i.kind==="story_review_evidence"&&i.producer==="root-commit-range-review"&&Bt(i,e)&&p(i.sourceEvidenceDigest)&&(i.reviewArtifactDigest===void 0||p(i.reviewArtifactDigest))&&i.qaReceiptRef===r.receiptRef&&i.receiptRef!==r.receiptRef&&(i.verdict==="approved"||i.verdict==="changes-requested")&&(i.verdict==="approved"?e.reviewVerdict==="approved":e.reviewVerdict==="changes-requested")&&I(i.reviewedAt)&&Date.parse(String(i.reviewedAt))>=Date.parse(String(r.checkedAt))&&he(i.receiptRef)&&e.receiptRefs.includes(i.receiptRef))}function Bt(t,e){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>t[i]===e[i])}function fr(t){return!Array.isArray(t)||t.length>1024?!1:t.every(e=>{const i=d(e);return i?(A(i,["schemaVersion","resourceId","action","outcome","idempotencyKey","reasonCodes","recordedAt","publicSafe"],"git-lifecycle-runtime-reconciliation-receipt-unknown-field"),i.schemaVersion===1&&P(i.resourceId)&&["no_op","delete_local_branch","delete_remote_branch","close_pull_request"].includes(String(i.action))&&["applied","already_absent","dry_run","failed"].includes(String(i.outcome))&&P(i.idempotencyKey)&&W(i.reasonCodes,128)&&I(i.recordedAt)&&i.publicSafe===!0):!1})}function gr(t){return!Array.isArray(t)||t.length>1024?!1:t.every(e=>{const i=d(e);return i?(A(i,["schemaVersion","resourceId","action","managed","reasonCodes","evidence","publicSafe"],"git-lifecycle-runtime-reconciliation-debt-unknown-field"),i.schemaVersion===1&&P(i.resourceId)&&i.action==="preserve"&&typeof i.managed=="boolean"&&W(i.reasonCodes,128)&&W(i.evidence,16)&&i.publicSafe===!0):!1})}function A(t,e,i){const r=new Set(e);if(Object.keys(t).some(n=>!r.has(n)))throw new Error(i)}function N(t){return typeof t=="string"&&/^P[1-9][0-9]*(?:\.[0-9]+)*$/.test(t)}function hr(t){const e=d(t);return e?Object.keys(e).length===10&&e.schemaVersion===1&&e.kind==="git_lifecycle_graph_authority"&&e.producer==="server-continuous-yoloop-v1"&&(e.source==="yolo"||e.source==="yoloop")&&N(e.epicId)&&N(e.storyId)&&String(e.storyId).startsWith(`${String(e.epicId)}.`)&&F(e.executionBranch)&&F(e.originBranch)&&e.originBranch!==e.executionBranch&&typeof e.graphRevision=="string"&&/^[a-f0-9]{64}$/.test(e.graphRevision)&&e.publicSafe===!0:!1}function F(t){return typeof t=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/.test(t)&&!t.includes("..")&&!t.includes("//")&&!t.includes("@{")&&!t.endsWith("/")&&!t.endsWith(".")&&!t.split("/").some(e=>!e||e.startsWith(".")||e.endsWith(".lock"))}function ge(t){return Ze(t)&&!t.endsWith("/")}function Ze(t){return t.length>0&&t.length<=1024&&!oe(t)&&!/^[A-Za-z]:[\\/]/.test(t)&&!t.includes("\0")&&!t.includes("\\")&&!t.includes("//")&&!t.replace(/\/$/,"").split("/").some(e=>!e||e==="."||e==="..")&&t.replace(/\/$/,"").split("/")[0]!==".git"}function P(t){return typeof t=="string"&&t.length>0&&t.length<=240&&/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)&&!t.includes("..")}function he(t){return P(t)}function v(t){return typeof t=="string"&&/^[a-f0-9]{40,64}$/i.test(t)}function p(t){return typeof t=="string"&&/^[a-f0-9]{64}$/i.test(t)}function I(t){return typeof t=="string"&&t.length<=64&&Number.isFinite(Date.parse(t))}function W(t,e,i=!1){return Array.isArray(t)&&t.length<=e&&(!i||t.length>0)&&t.every(P)}function Pt(t,e,i=!1){return Array.isArray(t)&&t.length<=e&&(!i||t.length>0)&&t.every(r=>typeof r=="string"&&r.length>0&&r.length<=1024)}function ie(t,e){return t.length===e.length&&t.every((i,r)=>i===e[r])}function ur(t){return Array.isArray(t)&&t.length>0&&t.length<=256&&t.every(v)}function Ue(){return{schemaVersion:1,revision:0,epics:{},stories:{}}}async function lr(t){const e=[50,100,200,400,600,800,1e3,1e3];for(let i=0;;i+=1)try{return await pr(t)}catch(r){if(!(r instanceof Error)||r.message!=="git-lifecycle-runtime-lock-active"||i>=e.length)throw r;await new Promise(n=>setTimeout(n,e[i]))}}async function pr(t){const e=X(t),i={pid:process.pid,nonce:ke(16).toString("hex")},r=async()=>{await ee(e),await at(e,H(t),JSON.stringify(i));try{await C(t,e),await te(_(t,"owner.json"),t)}catch(n){throw await ce(t,e).catch(()=>{}),n}};try{await r()}catch(n){if(!V(n,"EEXIST"))throw n;await J(t,"directory");const c=await Qe(t);if(c!==void 0&&xe(c.pid))throw new Error("git-lifecycle-runtime-lock-active");if(c===void 0&&await Tt(t))throw new Error("git-lifecycle-runtime-lock-active");const o=await $(t);if(!o)throw new Error("git-lifecycle-runtime-lock-owner-invalid");const a=`${t}.stale.${process.pid}.${Date.now()}`;await se(e,H(t),H(a));try{if(await C(a,e),await $(a)!==o)throw await we(a,t,e).catch(()=>{}),new Error("git-lifecycle-runtime-lock-owner-replaced");await r()}finally{await ce(a,e,async g=>await $(g)===o).catch(()=>{})}}return i}async function mr(t,e){const i=X(t);try{await C(t,i);const r=await Qe(t);if(!r||!Ht(r,e))return!1;const n=await $(t);if(!n)return!1;const c=`${t}.release.${process.pid}.${Date.now()}`;await se(i,H(t),H(c)),await C(c,i);const o=await Qe(c);return!o||!Ht(o,e)||await $(c)!==n?(await we(c,t,i).catch(()=>{}),!1):ce(c,i,async a=>await $(a)===n)}catch(r){if(V(r,"ENOENT"))return!1;throw r}}async function Tt(t){try{return Date.now()-(await qt(t)).mtimeMs<3e4}catch{return!0}}async function Qe(t){try{await C(t,X(t));const e=_(t,"owner.json");await te(e,t);const i=JSON.parse(await Z(e,"utf8"));return Number.isSafeInteger(i.pid)&&Number(i.pid)>0&&(i.nonce===void 0||typeof i.nonce=="string"&&/^[a-f0-9]{32}$/.test(i.nonce))?{pid:Number(i.pid),...typeof i.nonce=="string"?{nonce:i.nonce}:{}}:void 0}catch{return}}function Ht(t,e){return t.pid===e.pid&&t.nonce!==void 0&&t.nonce===e.nonce}function xe(t){try{return process.kill(t,0),!0}catch(e){return V(e,"EPERM")}}function d(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function V(t,e){return t instanceof Error&&"code"in t&&t.code===e}export{ve as GIT_LIFECYCLE_RUNTIME_DIRECTORY,_e as GIT_LIFECYCLE_RUNTIME_FILE,dt as LEGACY_DIRECT_YOLO_RECOVERY_COMMITS,ri as LEGACY_P174_CHECKPOINT_MIGRATIONS,G as P205_COMPLETE_COMMAND,yi as STORY_WORKTREE_EVIDENCE_MAX_RECEIPTS,wi as STORY_WORKTREE_EVIDENCE_MAX_SPEC_ACCEPTANCES,ci as STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS,ai as STORY_WORKTREE_JOURNAL_MAX_ENTRIES,di as STORY_WRITE_SET_MAX_ENTRIES,Yr as acquireGitLifecyclePhysicalIntegrationLock,Wr as appendStoryWorktreeEvidence,lt as applyGitLifecycleRuntimeOverlay,C as assertGitLifecyclePrivateDirectory,Jr as assertGitLifecyclePrivateFile,Bi as classifyGitLifecycleStoryCheckpointProjectionSync,Nr as compactStoryWorktreeJournal,Mi as computeGitLifecyclePhysicalIntegrationLockOwnerDigest,$i as computeHistoricalReviewReconciliationDigest,Ni as computeImmutableStoryQaEvidenceDigest,Kr as computeLegacyDirectYoloRecoveryReceiptRef,Vi as computeP205StoryQaEvidenceDigest,Gr as consumeEpicTerminalReleaseAuthority,qi as ensureGitLifecyclePrivateChildDirectory,Pr as ensureGitLifecycleRuntimeInitialized,je as ensureRuntimeEpic,zr as ensureRuntimeStory,Hr as ensureStoryWorktreeJournal,oi as executeP205TransientAuthorities,Br as executeP205TransientAuthority,Dt as gitLifecycleRuntimeDirectory,Me as gitLifecycleStoryWriteSet,wt as isAcceptedGitLifecycleStoryCheckpoint,mi as isStoryWorktreeCleanupReceiptRecord,$r as isStoryWorktreeEvidenceContainer,qe as isStoryWorktreeEvidenceReceiptRecord,Vr as isStoryWorktreeIntegrationReceiptRecord,ut as isStoryWriteSetExtension,fi as isStoryWriteSetExtensionPath,$e as mutateGitLifecycleRuntime,jr as p205TransientAuthorityMatchesAggregate,Tr as persistGitLifecycleGraphAuthority,Ee as posixSecurityAvailable,qr as projectP205TransientExecutionEvidence,Ge as publicStoryReviewArtifactFromGit,Ve as readGitLifecycleRuntime,gt as readGitLifecycleRuntimeSync,ki as readStoryWorktreeEvidence,ji as releaseGitLifecyclePhysicalIntegrationLock,Ur as releaseGitLifecyclePhysicalIntegrationLockForCheckpoint,ce as removeGitLifecyclePrivateDirectory,Mr as revalidateEpicHeadReconciliationAuthority,gi as storyWriteSetExtensionDigest,hi as storyWriteSetExtensionPaths,Lr as verifyAcceptedGitLifecycleStoryCheckpoint,bt as verifyAcceptedGitLifecycleStoryCheckpointSync,Zr as verifyGitLifecyclePhysicalIntegrationLock,Fr as verifyLegacyCheckpointMigrationCandidateSync};
|