@ornexus/neocortex 4.60.81 → 4.61.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/release-source.json +1 -1
  2. package/install.ps1 +33 -1
  3. package/install.sh +35 -1
  4. package/package.json +2 -2
  5. package/packages/client/dist/adapters/platform-detector.d.ts +1 -1
  6. package/packages/client/dist/adapters/platform-detector.js +6 -0
  7. package/packages/client/dist/cli.js +7 -0
  8. package/packages/client/dist/commands/invoke.d.ts +15 -8
  9. package/packages/client/dist/commands/invoke.js +75 -1
  10. package/packages/client/dist/commands/story-checkpoint.d.ts +2 -1
  11. package/packages/client/dist/commands/story-checkpoint.js +34 -2
  12. package/packages/client/dist/commands/story-worktree.d.ts +46 -0
  13. package/packages/client/dist/commands/story-worktree.js +258 -0
  14. package/packages/client/dist/config.js +1 -0
  15. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +46 -0
  16. package/packages/client/dist/git/direct-yolo-checkpoint.js +137 -1
  17. package/packages/client/dist/git/git-lifecycle-store.d.ts +84 -0
  18. package/packages/client/dist/git/git-lifecycle-store.js +314 -4
  19. package/packages/client/dist/git/story-worktree-cleanup.d.ts +226 -0
  20. package/packages/client/dist/git/story-worktree-cleanup.js +1058 -0
  21. package/packages/client/dist/git/story-worktree-integration.d.ts +91 -0
  22. package/packages/client/dist/git/story-worktree-integration.js +603 -0
  23. package/packages/client/dist/git/story-worktree-manager.d.ts +205 -0
  24. package/packages/client/dist/git/story-worktree-manager.js +843 -0
  25. package/packages/client/dist/git/story-worktree-paths.d.ts +65 -0
  26. package/packages/client/dist/git/story-worktree-paths.js +150 -0
  27. package/packages/client/dist/policy/subagent-approval-policy.js +3 -1
  28. package/packages/client/dist/runner/headless/continuous-story-workspace.d.ts +49 -1
  29. package/packages/client/dist/runner/headless/continuous-story-workspace.js +175 -27
  30. package/packages/client/dist/runner/headless/run-yoloop.d.ts +39 -0
  31. package/packages/client/dist/runner/headless/run-yoloop.js +71 -0
  32. package/packages/client/dist/runner-cli.js +0 -0
  33. package/packages/client/dist/state/project-state-snapshot.js +3 -0
  34. package/packages/shared/dist/yoloop/epic-terminal-git.js +27 -3
  35. package/targets-stubs/antigravity/gemini.md +1 -1
  36. package/targets-stubs/antigravity/neocortex.md +21 -0
  37. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  38. package/targets-stubs/claude-code/README.md +17 -0
  39. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  40. package/targets-stubs/claude-code/neocortex-root.md +57 -49
  41. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  42. package/targets-stubs/claude-code/neocortex.md +28 -25
  43. package/targets-stubs/codex/AGENTS.md +31 -30
  44. package/targets-stubs/codex/neocortex.toml +10 -0
  45. package/targets-stubs/cursor/agent.md +13 -2
  46. package/targets-stubs/deepseek-harness/SKILL.md +13 -0
  47. package/targets-stubs/gemini-cli/agent.md +23 -2
  48. package/targets-stubs/grok/SKILL.md +21 -0
  49. package/targets-stubs/kimi/neocortex.md +21 -0
  50. package/targets-stubs/openclaw/SKILL.md +21 -0
  51. package/targets-stubs/opencode/neocortex-root.md +19 -15
  52. package/targets-stubs/opencode/neocortex.md +10 -0
  53. package/targets-stubs/vscode/neocortex.agent.md +13 -2
@@ -43,6 +43,8 @@ export const LEGACY_P174_CHECKPOINT_MIGRATIONS = Object.freeze({
43
43
  });
44
44
  const LEGACY_STORE_FILE = 'neocortex-yoloop-runtime.json';
45
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;
46
48
  const TRANSIENT_P205_AUTHORITIES = new WeakMap();
47
49
  const HEAD_RECONCILIATION_AUTHORITIES = new WeakMap();
48
50
  const CONSUMED_TERMINAL_RELEASE_AUTHORITIES = new WeakSet();
@@ -459,6 +461,310 @@ function normalizeTrackedCollection(parent, key) {
459
461
  parent[key] = normalized;
460
462
  return normalized;
461
463
  }
464
+ /** Return (creating when absent) the mutable P225.05 story-worktree journal. */
465
+ export function ensureStoryWorktreeJournal(document) {
466
+ const mutable = document;
467
+ return mutable.storyWorktrees ?? (mutable.storyWorktrees = { schemaVersion: 1, entries: {}, cleanupReceipts: [] });
468
+ }
469
+ /** Drop an empty journal so documents return to their pre-P225.05 shape. */
470
+ export function compactStoryWorktreeJournal(document) {
471
+ const mutable = document;
472
+ const journal = mutable.storyWorktrees;
473
+ if (journal && Object.keys(journal.entries).length === 0 && journal.cleanupReceipts.length === 0) {
474
+ delete mutable.storyWorktrees;
475
+ }
476
+ }
477
+ const SWT_LEASE_ID = /^swt-[a-f0-9]{24}$/;
478
+ const SWT_HASH8 = /^[a-f0-9]{8}$/;
479
+ const SWT_SHA256 = /^[a-f0-9]{64}$/;
480
+ const SWT_GIT_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
481
+ const SWT_OPAQUE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;
482
+ const SWT_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;
483
+ const SWT_REASON = /^[a-z0-9][a-z0-9._-]{0,79}$/;
484
+ /**
485
+ * Closed P225-CON-RECEIPTS `cleanup-receipt` shape, checked locally so the
486
+ * published client closure needs no extra shared module. Tests prove parity
487
+ * with the shared `validateStoryWorktreeReceipt`.
488
+ */
489
+ export function isStoryWorktreeCleanupReceiptRecord(value) {
490
+ const receipt = asRecord(value);
491
+ if (!receipt)
492
+ return false;
493
+ const required = [
494
+ 'schemaVersion', 'kind', 'receiptId', 'epicId', 'storyId', 'leaseId', 'trigger',
495
+ 'worktreeRemoved', 'localBranchRemoved', 'remoteBranchRemoved', 'cleanedAt',
496
+ ];
497
+ const allowed = new Set([...required, 'preservedReasonCode']);
498
+ if (Object.keys(receipt).some((key) => !allowed.has(key)) || required.some((key) => receipt[key] === undefined))
499
+ return false;
500
+ return receipt.schemaVersion === 1 && receipt.kind === 'cleanup-receipt'
501
+ && typeof receipt.receiptId === 'string' && SWT_OPAQUE.test(receipt.receiptId)
502
+ && isCanonicalLifecycleId(receipt.epicId) && isCanonicalLifecycleId(receipt.storyId)
503
+ && typeof receipt.leaseId === 'string' && SWT_OPAQUE.test(receipt.leaseId)
504
+ && ['success', 'failure', 'abandon', 'orphan-recovery'].includes(String(receipt.trigger))
505
+ && typeof receipt.worktreeRemoved === 'boolean' && typeof receipt.localBranchRemoved === 'boolean'
506
+ && typeof receipt.remoteBranchRemoved === 'boolean'
507
+ && typeof receipt.cleanedAt === 'string' && SWT_TIME.test(receipt.cleanedAt)
508
+ && (receipt.preservedReasonCode === undefined
509
+ || (typeof receipt.preservedReasonCode === 'string' && SWT_REASON.test(receipt.preservedReasonCode)));
510
+ }
511
+ export const STORY_WORKTREE_EVIDENCE_MAX_RECEIPTS = 512;
512
+ export const STORY_WORKTREE_EVIDENCE_MAX_SPEC_ACCEPTANCES = 256;
513
+ const SWT_RECEIPT_STORY_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
514
+ const SWT_RELATIVE_REF = /^[A-Za-z0-9._@#-][A-Za-z0-9._/@#-]{0,239}$/;
515
+ 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})$/;
516
+ const SWT_URL_LIKE = /[A-Za-z][A-Za-z0-9+.-]*:\/\//;
517
+ const SWT_ABSOLUTE_LIKE = /^(?:\/|~[\\/]|[A-Za-z]:[\\/]|\\\\)/;
518
+ // Server-owned workflow step identifiers never ship in the published client
519
+ // (STEP_ID_IN_DIST boundary); receipts are compared through opaque SHA-256
520
+ // projections: the NUL-joined phase-one step sequence and the C04 barrier step.
521
+ const SWT_PHASE_ONE_STEPS_DIGEST = '18eafb8dbbdcb09db4e3988b2ba2c66f3ee1cf541fedda37077f2a74907232a8';
522
+ const SWT_PHASE_ONE_STEP_COUNT = 6;
523
+ const SWT_SPEC_BARRIER_STEP_DIGEST = '9cd927d02ff5979b5077e75b09cb34be275eca0e1c955403235b9ba0fb7a55eb';
524
+ function swtDigest(value) {
525
+ return createHash('sha256').update(value).digest('hex');
526
+ }
527
+ const SWT_EVIDENCE_RECEIPT_SCHEMAS = Object.freeze({
528
+ 'phase-one-receipt': {
529
+ schemaVersion: { oneOf: [1] }, kind: { oneOf: ['phase-one-receipt'] }, receiptId: 'opaque', leaseId: 'opaque',
530
+ epicId: 'story', storyId: 'story', completedStepIds: 'stories', headSha: 'git-sha', specRef: 'ref',
531
+ specDigest: 'sha256', graphRevision: 'sha256', completedAt: 'time',
532
+ },
533
+ 'spec-barrier-receipt': {
534
+ schemaVersion: { oneOf: [1] }, kind: { oneOf: ['spec-barrier-receipt'] }, receiptId: 'opaque', epicId: 'story',
535
+ stepId: { sha256Of: SWT_SPEC_BARRIER_STEP_DIGEST }, scope: { oneOf: ['epic'] }, storyIds: 'stories',
536
+ specDigests: 'digest-map', graphRevision: 'sha256', satisfiedAt: 'time',
537
+ },
538
+ 'integration-receipt': {
539
+ schemaVersion: { oneOf: [1] }, kind: { oneOf: ['integration-receipt'] }, receiptId: 'opaque', epicId: 'story',
540
+ storyId: 'story', integrationOwner: { oneOf: ['root_agent'] }, integrationIndex: 'positive-int',
541
+ epicHeadBeforeSha: 'git-sha', epicHeadAfterSha: 'git-sha', checkpointDigest: 'sha256',
542
+ outcome: { oneOf: ['integrated', 'conflict-reopened'] }, reasonCode: 'reason', integratedAt: 'time',
543
+ },
544
+ });
545
+ function swtTimestamp(value) {
546
+ if (!SWT_RECEIPT_TIME.test(value) || !Number.isFinite(Date.parse(value)))
547
+ return false;
548
+ const [year, month, day, hour, minute, second] = value.slice(0, 19).split(/[-T:]/).map(Number);
549
+ const probe = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
550
+ return probe.getUTCFullYear() === year && probe.getUTCMonth() === month - 1 && probe.getUTCDate() === day
551
+ && probe.getUTCHours() === hour && probe.getUTCMinutes() === minute && probe.getUTCSeconds() === second;
552
+ }
553
+ function swtStrings(value, depth = 0) {
554
+ if (depth > 4)
555
+ return false;
556
+ if (typeof value === 'string')
557
+ return !SWT_URL_LIKE.test(value) && !SWT_ABSOLUTE_LIKE.test(value);
558
+ if (Array.isArray(value))
559
+ return value.every((item) => swtStrings(item, depth + 1));
560
+ const record = asRecord(value);
561
+ return record ? Object.entries(record).every(([key, item]) => swtStrings(key, depth + 1) && swtStrings(item, depth + 1)) : true;
562
+ }
563
+ function swtField(rule, value) {
564
+ if (typeof rule === 'object') {
565
+ if ('sha256Of' in rule)
566
+ return typeof value === 'string' && value.length <= 80 && swtDigest(value) === rule.sha256Of;
567
+ return rule.oneOf.includes(value);
568
+ }
569
+ if (rule === 'positive-int')
570
+ return Number.isSafeInteger(value) && value >= 1;
571
+ if (rule === 'stories') {
572
+ return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length
573
+ && value.every((item) => typeof item === 'string' && SWT_RECEIPT_STORY_ID.test(item) && !item.includes('..'));
574
+ }
575
+ if (rule === 'digest-map') {
576
+ const record = asRecord(value);
577
+ 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));
578
+ }
579
+ if (typeof value !== 'string')
580
+ return false;
581
+ switch (rule) {
582
+ case 'opaque': return SWT_OPAQUE.test(value);
583
+ case 'story': return SWT_RECEIPT_STORY_ID.test(value) && !value.includes('..');
584
+ case 'ref': {
585
+ const segments = value.split('/');
586
+ return SWT_RELATIVE_REF.test(value) && !value.endsWith('/') && segments.every((segment) => segment !== ''
587
+ && segment !== '.' && segment !== '..' && !segment.startsWith('-') && segment.toLowerCase() !== '.git');
588
+ }
589
+ case 'sha256': return SWT_SHA256.test(value);
590
+ case 'git-sha': return SWT_GIT_SHA.test(value);
591
+ case 'time': return swtTimestamp(value);
592
+ case 'reason': return SWT_REASON.test(value);
593
+ }
594
+ }
595
+ /**
596
+ * Closed local validator for the P225-CON-RECEIPTS kinds the root persists in
597
+ * `story_worktree_evidence` (phase-one, spec-barrier, integration). Kept in the
598
+ * published client closure; tests prove parity with the shared validator.
599
+ */
600
+ export function isStoryWorktreeEvidenceReceiptRecord(value) {
601
+ const receipt = asRecord(value);
602
+ if (!receipt || typeof receipt.kind !== 'string')
603
+ return false;
604
+ const schema = SWT_EVIDENCE_RECEIPT_SCHEMAS[receipt.kind];
605
+ if (!schema || !swtStrings(receipt))
606
+ return false;
607
+ const keys = Object.keys(receipt);
608
+ if (keys.length !== Object.keys(schema).length || keys.some((key) => !(key in schema)))
609
+ return false;
610
+ if (!Object.entries(schema).every(([field, rule]) => receipt[field] !== undefined && swtField(rule, receipt[field])))
611
+ return false;
612
+ if (receipt.kind === 'phase-one-receipt') {
613
+ const steps = receipt.completedStepIds;
614
+ return steps.length === SWT_PHASE_ONE_STEP_COUNT && swtDigest(steps.join('\0')) === SWT_PHASE_ONE_STEPS_DIGEST;
615
+ }
616
+ if (receipt.kind === 'spec-barrier-receipt') {
617
+ const digestKeys = Object.keys(receipt.specDigests);
618
+ const storyIds = receipt.storyIds;
619
+ return digestKeys.length === storyIds.length && storyIds.every((id) => digestKeys.includes(id));
620
+ }
621
+ return true;
622
+ }
623
+ /** True only for the closed `integration-receipt` shape. */
624
+ export function isStoryWorktreeIntegrationReceiptRecord(value) {
625
+ return asRecord(value)?.kind === 'integration-receipt' && isStoryWorktreeEvidenceReceiptRecord(value);
626
+ }
627
+ /** Closed validator for the `story_worktree_evidence` container (P225.04-ADR-3). */
628
+ export function isStoryWorktreeEvidenceContainer(value) {
629
+ return validateStoryWorktreeEvidenceContainer(value);
630
+ }
631
+ function validateStoryWorktreeEvidenceContainer(value) {
632
+ const container = asRecord(value);
633
+ if (!container)
634
+ return false;
635
+ const keys = Object.keys(container);
636
+ if (keys.some((key) => !['schemaVersion', 'specAcceptances', 'receipts'].includes(key)) || container.schemaVersion !== 1)
637
+ return false;
638
+ const acceptances = container.specAcceptances;
639
+ if (acceptances !== undefined && (!Array.isArray(acceptances) || acceptances.length > STORY_WORKTREE_EVIDENCE_MAX_SPEC_ACCEPTANCES
640
+ || new Set(acceptances.map((item) => asRecord(item)?.storyId)).size !== acceptances.length
641
+ || !acceptances.every((item) => {
642
+ const acceptance = asRecord(item);
643
+ return Boolean(acceptance) && Object.keys(acceptance).length === 3
644
+ && isCanonicalLifecycleId(acceptance.storyId) && String(acceptance.storyId).includes('.')
645
+ && typeof acceptance.specDigest === 'string' && SWT_SHA256.test(acceptance.specDigest)
646
+ && typeof acceptance.graphRevision === 'string' && SWT_SHA256.test(acceptance.graphRevision);
647
+ })))
648
+ return false;
649
+ const receipts = container.receipts;
650
+ return receipts === undefined || (Array.isArray(receipts) && receipts.length <= STORY_WORKTREE_EVIDENCE_MAX_RECEIPTS
651
+ && new Set(receipts.map((item) => asRecord(item)?.receiptId)).size === receipts.length
652
+ && receipts.every(isStoryWorktreeEvidenceReceiptRecord));
653
+ }
654
+ /** Read (never create) the validated evidence container of one runtime epic overlay. */
655
+ export function readStoryWorktreeEvidence(document, epicId) {
656
+ const container = document.epics[epicId]?.story_worktree_evidence;
657
+ if (container === undefined || container === null)
658
+ return undefined;
659
+ if (!validateStoryWorktreeEvidenceContainer(container))
660
+ throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
661
+ return container;
662
+ }
663
+ /**
664
+ * Append server-returned or root-produced evidence to the mutable runtime
665
+ * document (call inside `mutateGitLifecycleRuntime`). Receipts dedupe by
666
+ * `receiptId` (identical bytes only); spec acceptances dedupe by `storyId`.
667
+ */
668
+ export function appendStoryWorktreeEvidence(document, epicId, input) {
669
+ const current = readStoryWorktreeEvidence(document, epicId);
670
+ const receipts = [...(current?.receipts ?? [])];
671
+ const acceptances = [...(current?.specAcceptances ?? [])];
672
+ let appendedReceipts = 0;
673
+ let appendedSpecAcceptances = 0;
674
+ for (const receipt of input.receipts ?? []) {
675
+ const record = asRecord(receipt);
676
+ if (!isStoryWorktreeEvidenceReceiptRecord(record) || record.epicId !== epicId) {
677
+ throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
678
+ }
679
+ const existing = receipts.find((item) => item.receiptId === record.receiptId);
680
+ if (existing) {
681
+ if (JSON.stringify(existing) !== JSON.stringify(record))
682
+ throw new Error('git-lifecycle-runtime-story-worktree-evidence-conflict');
683
+ continue;
684
+ }
685
+ receipts.push(structuredClone(record));
686
+ appendedReceipts++;
687
+ }
688
+ for (const acceptance of input.specAcceptances ?? []) {
689
+ const record = asRecord(acceptance);
690
+ const normalized = record ? {
691
+ storyId: record.storyId, specDigest: record.specDigest, graphRevision: record.graphRevision,
692
+ } : undefined;
693
+ if (!normalized || Object.keys(record).length !== 3
694
+ || !validateStoryWorktreeEvidenceContainer({ schemaVersion: 1, specAcceptances: [normalized] })) {
695
+ throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
696
+ }
697
+ const index = acceptances.findIndex((item) => item.storyId === normalized.storyId);
698
+ if (index >= 0 && JSON.stringify(acceptances[index]) === JSON.stringify(normalized))
699
+ continue;
700
+ if (index >= 0)
701
+ acceptances[index] = normalized;
702
+ else
703
+ acceptances.push(normalized);
704
+ appendedSpecAcceptances++;
705
+ }
706
+ const next = { schemaVersion: 1 };
707
+ if (acceptances.length > 0)
708
+ next.specAcceptances = acceptances;
709
+ if (receipts.length > 0)
710
+ next.receipts = receipts;
711
+ if (!validateStoryWorktreeEvidenceContainer(next))
712
+ throw new Error('git-lifecycle-runtime-story-worktree-evidence-invalid');
713
+ if (appendedReceipts > 0 || appendedSpecAcceptances > 0)
714
+ ensureRuntimeEpic(document, epicId).story_worktree_evidence = next;
715
+ return { appendedReceipts, appendedSpecAcceptances };
716
+ }
717
+ function validateStoryWorktreeJournal(value) {
718
+ const journal = asRecord(value);
719
+ if (!journal)
720
+ return false;
721
+ const keys = Object.keys(journal);
722
+ if (keys.length !== 3 || !keys.every((key) => ['schemaVersion', 'entries', 'cleanupReceipts'].includes(key)))
723
+ return false;
724
+ const entries = asRecord(journal.entries);
725
+ if (journal.schemaVersion !== 1 || !entries || !Array.isArray(journal.cleanupReceipts)
726
+ || journal.cleanupReceipts.length > STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS
727
+ || Object.keys(entries).length > STORY_WORKTREE_JOURNAL_MAX_ENTRIES
728
+ || journal.cleanupReceipts.some((receipt) => !isStoryWorktreeCleanupReceiptRecord(receipt)))
729
+ return false;
730
+ return Object.entries(entries).every(([leaseId, entry]) => validateStoryWorktreeJournalEntry(leaseId, entry));
731
+ }
732
+ function validateStoryWorktreeJournalEntry(leaseId, value) {
733
+ const entry = asRecord(value);
734
+ if (!entry)
735
+ return false;
736
+ const required = [
737
+ 'schemaVersion', 'leaseId', 'epicId', 'storyId', 'dispatchDigest', 'hash8', 'executionBranch',
738
+ 'temporaryBranch', 'worktreeRef', 'worktreePath', 'workspaceMechanism', 'ownerId', 'nonceDigest',
739
+ 'baseSha', 'graphRevision', 'state', 'acquiredAt', 'expiresAt',
740
+ ];
741
+ const allowed = new Set([...required, 'syncedSha']);
742
+ if (Object.keys(entry).some((key) => !allowed.has(key)) || required.some((key) => entry[key] === undefined))
743
+ return false;
744
+ const epicId = entry.epicId;
745
+ const hash8 = entry.hash8;
746
+ return entry.schemaVersion === 1
747
+ && entry.leaseId === leaseId && SWT_LEASE_ID.test(leaseId)
748
+ && isCanonicalLifecycleId(epicId) && !String(epicId).includes('.')
749
+ && isCanonicalLifecycleId(entry.storyId) && String(entry.storyId).startsWith(`${String(epicId)}.`)
750
+ && typeof entry.dispatchDigest === 'string' && SWT_SHA256.test(entry.dispatchDigest)
751
+ && typeof hash8 === 'string' && SWT_HASH8.test(hash8)
752
+ && entry.executionBranch === `epic/${String(epicId)}`
753
+ && typeof entry.temporaryBranch === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(entry.temporaryBranch)
754
+ && !entry.temporaryBranch.includes('..') && entry.temporaryBranch !== entry.executionBranch
755
+ && entry.worktreeRef === `wt/${hash8}`
756
+ && typeof entry.worktreePath === 'string' && entry.worktreePath.length <= 4096
757
+ && (isAbsolute(entry.worktreePath) || /^[A-Za-z]:[\\/]/.test(entry.worktreePath))
758
+ && (entry.workspaceMechanism === 'client_managed_worktree' || entry.workspaceMechanism === 'native_subagent_worktree')
759
+ && typeof entry.ownerId === 'string' && SWT_OPAQUE.test(entry.ownerId)
760
+ && typeof entry.nonceDigest === 'string' && SWT_SHA256.test(entry.nonceDigest)
761
+ && typeof entry.baseSha === 'string' && SWT_GIT_SHA.test(entry.baseSha)
762
+ && typeof entry.graphRevision === 'string' && SWT_SHA256.test(entry.graphRevision)
763
+ && (entry.state === 'creating' || entry.state === 'active')
764
+ && typeof entry.acquiredAt === 'string' && SWT_TIME.test(entry.acquiredAt)
765
+ && typeof entry.expiresAt === 'string' && SWT_TIME.test(entry.expiresAt)
766
+ && (entry.syncedSha === undefined || (typeof entry.syncedSha === 'string' && SWT_GIT_SHA.test(entry.syncedSha)));
767
+ }
462
768
  export function ensureRuntimeEpic(document, epicId) {
463
769
  return document.epics[epicId] ?? (document.epics[epicId] = {});
464
770
  }
@@ -1628,8 +1934,11 @@ function validateDocument(value) {
1628
1934
  const record = value;
1629
1935
  const schemaVersion = record.schemaVersion;
1630
1936
  assertExactKeys(record, schemaVersion === 2
1631
- ? ['schemaVersion', 'revision', 'epics', 'stories', 'operational']
1632
- : ['schemaVersion', 'revision', 'epics', 'stories'], 'git-lifecycle-runtime-unknown-field');
1937
+ ? ['schemaVersion', 'revision', 'epics', 'stories', 'operational', 'storyWorktrees']
1938
+ : ['schemaVersion', 'revision', 'epics', 'stories', 'storyWorktrees'], 'git-lifecycle-runtime-unknown-field');
1939
+ if (record.storyWorktrees !== undefined && !validateStoryWorktreeJournal(record.storyWorktrees)) {
1940
+ throw new Error('git-lifecycle-runtime-story-worktrees-invalid');
1941
+ }
1633
1942
  const epics = asRecord(record.epics);
1634
1943
  const stories = asRecord(record.stories);
1635
1944
  if ((schemaVersion !== 1 && schemaVersion !== 2)
@@ -1689,7 +1998,7 @@ function validateBoundedRecordArray(value, max) {
1689
1998
  const EPIC_OVERLAY_KEYS = [
1690
1999
  'branch_mode', 'execution_branch', 'origin_branch', 'branch_lease', 'origin_binding',
1691
2000
  'graph_revision', 'aggregate_qa_receipt', 'head_reconciliation_receipt', 'terminal_git_receipt', 'physicalMergeStatus',
1692
- 'pr_number', 'git_reconciliation_receipts', 'git_reconciliation_debt',
2001
+ 'pr_number', 'git_reconciliation_receipts', 'git_reconciliation_debt', 'story_worktree_evidence',
1693
2002
  ];
1694
2003
  const STORY_OVERLAY_KEYS = ['checkpoint', 'status', 'last_step', 'steps_completed'];
1695
2004
  function validateEpicOverlay(value) {
@@ -1707,7 +2016,8 @@ function validateEpicOverlay(value) {
1707
2016
  && (value.physicalMergeStatus === undefined || ['merged', 'pushed', 'denied_external_gate', 'blocked_local_or_repo', 'not_attempted'].includes(String(value.physicalMergeStatus)))
1708
2017
  && (value.pr_number === undefined || value.pr_number === null || Number.isSafeInteger(value.pr_number) && Number(value.pr_number) > 0)
1709
2018
  && (value.git_reconciliation_receipts === undefined || validateReconciliationReceipts(value.git_reconciliation_receipts))
1710
- && (value.git_reconciliation_debt === undefined || validateReconciliationDebt(value.git_reconciliation_debt));
2019
+ && (value.git_reconciliation_debt === undefined || validateReconciliationDebt(value.git_reconciliation_debt))
2020
+ && (value.story_worktree_evidence === undefined || validateStoryWorktreeEvidenceContainer(value.story_worktree_evidence));
1711
2021
  }
1712
2022
  function validateStoryOverlay(value, storyId) {
1713
2023
  assertExactKeys(value, STORY_OVERLAY_KEYS, 'git-lifecycle-runtime-story-unknown-field');
@@ -0,0 +1,226 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * This file is part of Neocortex CLI, licensed under the
6
+ * Functional Source License, Version 1.1 (FSL-1.1).
7
+ *
8
+ * Change Date: February 20, 2029
9
+ * Change License: MIT
10
+ *
11
+ * See the LICENSE file in the project root for full license text.
12
+ */
13
+ import type { CleanupReceipt } from '../../../shared/dist/yoloop/story-worktree-receipts.js';
14
+ import { StoryWorktreeManager, type RepositoryFacts, type StoryWorktreeResult } from './story-worktree-manager.js';
15
+ export declare const STORY_WORKTREE_CLEANUP_FILE = "story-worktree-cleanup.json";
16
+ export declare const STORY_WORKTREE_BUNDLE_DIRECTORY = "story-worktree-bundles";
17
+ export declare const STORY_WORKTREE_CLEANUP_MAX_RECORDS = 256;
18
+ export declare const STORY_WORKTREE_CLEANUP_TRIGGERS: readonly ["success", "failure", "abandon", "orphan-recovery"];
19
+ export type StoryWorktreeCleanupTrigger = (typeof STORY_WORKTREE_CLEANUP_TRIGGERS)[number];
20
+ export declare const STORY_WORKTREE_CLEANUP_STATES: readonly ["active", "integrated", "failed", "abandoned", "bundled", "remove-pending", "removed"];
21
+ export type StoryWorktreeCleanupState = (typeof STORY_WORKTREE_CLEANUP_STATES)[number];
22
+ export declare const STORY_WORKTREE_CLEANUP_REASON_CODES: Readonly<{
23
+ readonly MANUAL_PRESERVED: "manual-worktree-preserved";
24
+ readonly REMOVE_PENDING: "story-worktree-remove-pending";
25
+ readonly ORPHAN_RECOVERED: "story-worktree-orphan-recovered";
26
+ readonly ORPHAN_UNPROVEN: "story-worktree-orphan-unproven";
27
+ readonly OWNER_ALIVE: "story-worktree-owner-alive";
28
+ readonly LEASE_LIVE: "story-worktree-lease-live";
29
+ readonly CLAIMED: "story-worktree-cleanup-claimed";
30
+ readonly IN_PROGRESS: "story-worktree-cleanup-in-progress";
31
+ readonly DIRTY_PRESERVED: "story-worktree-dirty-preserved";
32
+ readonly BUNDLE_QUOTA: "story-worktree-bundle-quota-exceeded";
33
+ readonly BUNDLE_FAILED: "story-worktree-bundle-failed";
34
+ readonly BUNDLE_UNVERIFIED: "story-worktree-bundle-unverified";
35
+ readonly REMOTE_DIVERGED: "story-worktree-remote-sha-diverged";
36
+ readonly REMOTE_UNVERIFIED: "story-worktree-remote-unverified";
37
+ readonly REMOTE_ABSENT: "story-worktree-remote-absent";
38
+ readonly REMOTE_UNPRESERVED: "story-worktree-remote-unpreserved";
39
+ readonly REMOTE_UNKNOWN: "story-worktree-remote-unknown";
40
+ readonly BRANCH_MOVED: "story-worktree-branch-moved";
41
+ readonly BRANCH_CHECKED_OUT: "story-worktree-branch-checked-out";
42
+ readonly ADOPTED_BRANCH: "story-worktree-adopted-branch-preserved";
43
+ readonly ENTRY_CONFLICT: "story-worktree-entry-conflict";
44
+ readonly STATE_INVALID: "story-worktree-cleanup-state-invalid";
45
+ readonly SWEEP_FAILED: "story-worktree-sweep-failed";
46
+ }>;
47
+ export interface StoryWorktreeRemotePush {
48
+ readonly remote: string;
49
+ readonly branch: string;
50
+ readonly sha: string;
51
+ }
52
+ export interface StoryWorktreeCleanupRecord {
53
+ readonly schemaVersion: 1;
54
+ readonly leaseId: string;
55
+ readonly epicId: string;
56
+ readonly storyId: string;
57
+ readonly state: StoryWorktreeCleanupState;
58
+ readonly removeAttempts: number;
59
+ readonly updatedAt: string;
60
+ readonly trigger?: StoryWorktreeCleanupTrigger;
61
+ readonly headSha?: string;
62
+ readonly bundleDigest?: string;
63
+ readonly bundleBytes?: number;
64
+ readonly bundleExpiresAt?: string;
65
+ readonly remotePush?: StoryWorktreeRemotePush;
66
+ readonly remoteBranchRemoved?: boolean;
67
+ readonly ownerPid?: number;
68
+ readonly ownerHostDigest?: string;
69
+ readonly claimToken?: string;
70
+ readonly claimExpiresAt?: string;
71
+ }
72
+ export interface StoryWorktreeCleanupDocument {
73
+ readonly schemaVersion: 1;
74
+ readonly records: Record<string, StoryWorktreeCleanupRecord>;
75
+ }
76
+ export interface StoryWorktreeCleanupOptions {
77
+ readonly projectRoot: string;
78
+ readonly manager?: StoryWorktreeManager;
79
+ readonly worktreeRoot?: string;
80
+ readonly now?: () => Date;
81
+ readonly bundleTtlMs?: number;
82
+ readonly claimTtlMs?: number;
83
+ readonly maxBundles?: number;
84
+ readonly maxBundleBytes?: number;
85
+ readonly removeAttempts?: number;
86
+ readonly removeDelayMs?: number;
87
+ /** Fault-injection seam (simulated Windows file locks). Never forces. */
88
+ readonly removeWorktree?: (mainRoot: string, worktreePath: string) => Promise<boolean>;
89
+ readonly isProcessAlive?: (pid: number) => boolean;
90
+ readonly lockRetry?: {
91
+ readonly attempts: number;
92
+ readonly delayMs: number;
93
+ };
94
+ }
95
+ export type StoryWorktreeCleanupOutcome = 'removed' | 'remove-pending' | 'reclaimed' | 'dry-run';
96
+ export interface StoryWorktreeCleanupValue {
97
+ readonly leaseId: string;
98
+ readonly outcome: StoryWorktreeCleanupOutcome;
99
+ readonly trigger: StoryWorktreeCleanupTrigger;
100
+ readonly state: StoryWorktreeCleanupState;
101
+ readonly plannedActions?: readonly string[];
102
+ readonly receipt?: CleanupReceipt;
103
+ readonly receiptDigest?: string;
104
+ readonly bundleDigest?: string;
105
+ readonly preservedReasonCodes: readonly string[];
106
+ }
107
+ export interface StoryWorktreeSweepItem {
108
+ readonly leaseId: string;
109
+ readonly action: 'skipped' | 'recovered' | 'remove-pending' | 'preserved' | 'planned' | 'record-closed';
110
+ readonly reasonCode?: string;
111
+ readonly bundleDigest?: string;
112
+ readonly plannedActions?: readonly string[];
113
+ }
114
+ export interface StoryWorktreeSweepValue {
115
+ readonly dryRun: boolean;
116
+ readonly entriesScanned: number;
117
+ readonly recovered: number;
118
+ readonly removePending: number;
119
+ readonly preserved: number;
120
+ readonly skipped: number;
121
+ readonly manualWorktreesPreserved: number;
122
+ readonly bundlesExpired: number;
123
+ readonly items: readonly StoryWorktreeSweepItem[];
124
+ readonly reasonCodes: readonly string[];
125
+ }
126
+ /** Private bundle file name: one immutable file per (lease, verified tip). */
127
+ export declare function storyWorktreeBundleFileName(leaseId: string, headSha: string): string;
128
+ export declare function storyWorktreeOwnerHostDigest(host?: string): string;
129
+ /** Closed-schema validation of one sidecar record. */
130
+ export declare function isStoryWorktreeCleanupRecord(leaseId: string, value: unknown): value is StoryWorktreeCleanupRecord;
131
+ export declare function parseStoryWorktreeCleanupDocument(raw: string): StoryWorktreeCleanupDocument;
132
+ /**
133
+ * True when a cleanup for this lease is in progress (or the sidecar cannot be
134
+ * trusted): P225.05 `create`/`adopt` must not hand the worktree to a new child.
135
+ */
136
+ export declare function storyWorktreeCleanupInProgress(commonDir: string, leaseId: string, nowMs?: number): Promise<boolean>;
137
+ export declare class StoryWorktreeCleanup {
138
+ private readonly options;
139
+ private readonly manager;
140
+ private readonly now;
141
+ private readonly isProcessAlive;
142
+ constructor(options: StoryWorktreeCleanupOptions);
143
+ /** Read the sidecar without creating anything (absent = empty). */
144
+ readState(facts?: RepositoryFacts): Promise<StoryWorktreeCleanupDocument>;
145
+ /** Record a pushed temporary branch; only a recorded push is ever deleted. */
146
+ recordPush(input: {
147
+ readonly leaseId: string;
148
+ readonly remote: string;
149
+ }): Promise<StoryWorktreeResult<StoryWorktreeRemotePush & {
150
+ readonly leaseId: string;
151
+ }>>;
152
+ /** Optional liveness evidence: a live owner on this host is never swept. */
153
+ registerOwnerProcess(input: {
154
+ readonly leaseId: string;
155
+ readonly pid: number;
156
+ }): Promise<StoryWorktreeResult<{
157
+ readonly leaseId: string;
158
+ }>>;
159
+ cleanup(input: {
160
+ readonly leaseId: string;
161
+ readonly trigger: StoryWorktreeCleanupTrigger;
162
+ readonly dryRun?: boolean;
163
+ }): Promise<StoryWorktreeResult<StoryWorktreeCleanupValue>>;
164
+ sweep(input?: {
165
+ readonly epicId?: string;
166
+ readonly dryRun?: boolean;
167
+ }): Promise<StoryWorktreeResult<StoryWorktreeSweepValue>>;
168
+ private cleanupUnguarded;
169
+ /**
170
+ * Expired `creating` reservation (crash between reserve and activate). Only
171
+ * a provably empty worktree at `baseSha` on its own branch is removed.
172
+ */
173
+ private recoverCreating;
174
+ private closeDetachedRecord;
175
+ private deleteRemote;
176
+ private deleteRecordedRemote;
177
+ /** `undefined` = branch absent, `null` = remote unverifiable. */
178
+ private lsRemote;
179
+ private createBundle;
180
+ /** Read-only digest check (never creates directories; safe in dry-run). */
181
+ private bundleMatches;
182
+ /**
183
+ * TTL: expired bundles of finished records, plus unreferenced bundle files
184
+ * (crash between `bundle create` and its record) older than the TTL.
185
+ */
186
+ private expireBundles;
187
+ private definitelyMissing;
188
+ private removeWithRetry;
189
+ private probe;
190
+ private facts;
191
+ private gitOk;
192
+ /** Per-lease cleanup claim (compare-and-set under the runtime lock). */
193
+ private claim;
194
+ /** Drop our claim; a record that carries nothing else returns to absence. */
195
+ private releaseClaim;
196
+ private emptyRecord;
197
+ /**
198
+ * Create-or-update one sidecar record bound to a live journal entry (same
199
+ * nonce). A foreign live claim refuses; `token` identifies our own claim.
200
+ */
201
+ private update;
202
+ /**
203
+ * One serialized write: journal mutation (optional) and sidecar mutation run
204
+ * under the lifecycle runtime's exclusive lock; the sidecar is validated and
205
+ * written atomically in `preCommit`, before the runtime document itself.
206
+ */
207
+ private mutate;
208
+ private guard;
209
+ }
210
+ /**
211
+ * Best-effort sweep used by `run-yoloop` and signal handlers. A repository
212
+ * without journaled story worktrees or cleanup records is never written.
213
+ * Only actionable reason codes are returned.
214
+ */
215
+ export declare function sweepStoryWorktreeOrphans(projectRoot: string, options?: Omit<StoryWorktreeCleanupOptions, 'projectRoot'> & {
216
+ readonly epicId?: string;
217
+ readonly dryRun?: boolean;
218
+ }): Promise<{
219
+ readonly reasonCodes: readonly string[];
220
+ readonly value?: StoryWorktreeSweepValue;
221
+ }>;
222
+ /**
223
+ * Opt-in signal sweep: on SIGINT/SIGTERM run one bounded sweep, remove the
224
+ * listeners and re-raise the signal so default termination still applies.
225
+ */
226
+ export declare function installStoryWorktreeSignalSweep(projectRoot: string, sweep?: (root: string) => Promise<unknown>, raise?: (signal: NodeJS.Signals) => void): () => void;