@yu_robotics/remote-cli 1.6.242 → 1.6.244

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 (60) hide show
  1. package/dist/client/MessageHandler.d.ts +2 -0
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +59 -8
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/executor/ClaudePersistentExecutor.d.ts +1 -0
  6. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  7. package/dist/executor/ClaudePersistentExecutor.js +4 -1
  8. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  9. package/dist/executor/DshExecutor.d.ts +1 -1
  10. package/dist/executor/DshExecutor.d.ts.map +1 -1
  11. package/dist/executor/DshExecutor.js +1 -0
  12. package/dist/executor/DshExecutor.js.map +1 -1
  13. package/dist/executor/IExecutor.d.ts +2 -0
  14. package/dist/executor/IExecutor.d.ts.map +1 -1
  15. package/dist/maintenance/release-notes.json +1 -1
  16. package/dist/managed/tools.d.ts +4 -4
  17. package/dist/scheduling/ReviewedNativeCleanup.d.ts +5 -0
  18. package/dist/scheduling/ReviewedNativeCleanup.d.ts.map +1 -1
  19. package/dist/scheduling/ReviewedNativeCleanup.js.map +1 -1
  20. package/dist/scheduling/ScheduleCleanup.d.ts +31 -0
  21. package/dist/scheduling/ScheduleCleanup.d.ts.map +1 -0
  22. package/dist/scheduling/ScheduleCleanup.js +42 -0
  23. package/dist/scheduling/ScheduleCleanup.js.map +1 -0
  24. package/dist/scheduling/SchedulePurgeVerification.d.ts +8 -0
  25. package/dist/scheduling/SchedulePurgeVerification.d.ts.map +1 -0
  26. package/dist/scheduling/SchedulePurgeVerification.js +96 -0
  27. package/dist/scheduling/SchedulePurgeVerification.js.map +1 -0
  28. package/dist/scheduling/ScheduleService.d.ts +26 -6
  29. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  30. package/dist/scheduling/ScheduleService.js +248 -45
  31. package/dist/scheduling/ScheduleService.js.map +1 -1
  32. package/dist/scheduling/ScheduleToolScope.d.ts +12 -0
  33. package/dist/scheduling/ScheduleToolScope.d.ts.map +1 -1
  34. package/dist/scheduling/ScheduleToolScope.js +2 -0
  35. package/dist/scheduling/ScheduleToolScope.js.map +1 -1
  36. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +1 -0
  37. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  38. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +6 -1
  39. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  40. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +4 -0
  41. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  42. package/dist/scheduling/claude/ClaudeSessionSchedules.js +10 -0
  43. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  44. package/dist/scheduling/dsh/SessionScheduleClient.d.ts.map +1 -1
  45. package/dist/scheduling/dsh/SessionScheduleClient.js +2 -0
  46. package/dist/scheduling/dsh/SessionScheduleClient.js.map +1 -1
  47. package/dist/scheduling/toolContract.d.ts +2 -2
  48. package/dist/scheduling/toolContract.js +2 -2
  49. package/dist/scheduling/toolContract.js.map +1 -1
  50. package/dist/scheduling/types.d.ts +3 -0
  51. package/dist/scheduling/types.d.ts.map +1 -1
  52. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  53. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  54. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  55. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  56. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  57. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  58. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  59. package/native/prebuilds/win32-x64/manifest.json +1 -1
  60. package/package.json +1 -1
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.ScheduleService = exports.SCHEDULE_CATALOG_FILE = void 0;
40
+ const ScheduleCleanup_1 = require("./ScheduleCleanup");
40
41
  const OwnershipRuntime_1 = require("../delegation/OwnershipRuntime");
41
42
  const node_fs_1 = require("node:fs");
42
43
  const fs = __importStar(require("node:fs/promises"));
@@ -52,6 +53,9 @@ const LIVE = new Set(['creating', 'active', 'running']);
52
53
  const STATES = new Set([...LIVE, 'completed', 'cancelled', 'interrupted', 'failed']);
53
54
  const RESTART_REASON = 'Native schedule interrupted by service restart; not recreated or resumed.';
54
55
  const MAX_PURGED_IDS = 10_000;
56
+ const MAX_CLEANUP_RECORDS = 1000;
57
+ const MAX_PURGE_REQUESTS = 1000;
58
+ const MAX_PURGE_SELECTION_IDS = 20_000;
55
59
  function bounded(value, limit) {
56
60
  if (Buffer.byteLength(value, 'utf8') <= limit)
57
61
  return value;
@@ -85,6 +89,12 @@ function validateOwner(owner) {
85
89
  function sameOwner(left, right) {
86
90
  return left.threadId === right.threadId && left.openId === right.openId && left.generation === right.generation;
87
91
  }
92
+ /** Deletion-only obligations and receipts remain manageable by the same user in
93
+ * the same thread after reset. Original provenance stays immutable; live records
94
+ * and all execution admission continue to require exact generation ownership. */
95
+ function sameCleanupOwner(left, right) {
96
+ return left.threadId === right.threadId && left.openId === right.openId;
97
+ }
88
98
  /** Terminal intent prevents recreation, but uncertain native cleanup still owns admission. */
89
99
  function recoveryOwnsWork(record) {
90
100
  return !!record.recovery && (!['completed', 'cancelled'].includes(record.state)
@@ -111,6 +121,8 @@ class ScheduleService {
111
121
  runtimes = new Map();
112
122
  retainedCancellations = new Map();
113
123
  purged = new Map();
124
+ cleanup = new Map();
125
+ purgeRequests = new Map();
114
126
  purges = new Map();
115
127
  recordOperations = new Map();
116
128
  delivering = new Set();
@@ -503,26 +515,75 @@ class ScheduleService {
503
515
  validateOwner(owner);
504
516
  return this.serial(async () => [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => structuredClone(record)));
505
517
  }
506
- /** Cancel first, then erase only verified retired history. No native sweep or
507
- * recovery admission is implied. Missing/foreign IDs never count as removed. */
508
- purge(owner, selection) {
509
- return this.operation(this.purgeSelected(structuredClone(owner), structuredClone(selection)));
518
+ /** Operational deletion ledger, separate from user history and never recoverable. */
519
+ async listCleanup(owner) {
520
+ this.checkReady();
521
+ validateOwner(owner);
522
+ return this.serial(async () => [...this.cleanup.values()].filter(record => sameCleanupOwner(record, owner)).map(record => structuredClone(record)));
523
+ }
524
+ /** Preserve the last known original-session route while deletion is unresolved. */
525
+ hasCleanupContext(threadId) {
526
+ return [...this.cleanup.values()].some(item => item.threadId === threadId && item.backend === 'claude' && !!item.attribution);
510
527
  }
511
- async purgeSelected(owner, selection) {
528
+ /** Freeze production request selection durably before acquiring a native lease.
529
+ * Keys bind authenticated ownership and the framework operation ID, not model proof. */
530
+ freezePurgeSelection(owner, selection, requestId, isCurrent) {
531
+ this.checkReady();
532
+ validateOwner(owner);
533
+ (0, ScheduleCommand_1.validateScheduleId)(requestId);
534
+ owner = structuredClone(owner);
535
+ selection = structuredClone(selection);
536
+ return this.operation(this.serial(async () => {
537
+ if (!this.current(owner) || !isCurrent())
538
+ throw new Error('Schedule purge request context changed.');
539
+ const ids = this.purgeIds(owner, selection);
540
+ const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(value)).digest('hex');
541
+ const key = hash([ownerOf(owner), requestId]);
542
+ const digest = hash('all' in selection ? { all: true } : { ids: [...selection.ids].sort() });
543
+ const previous = this.purgeRequests.get(key);
544
+ if (previous) {
545
+ if (previous.digest !== digest)
546
+ throw new Error('Purge requestId was reused with a different selection.');
547
+ return [...previous.ids];
548
+ }
549
+ const references = [...this.purgeRequests.values()].reduce((count, receipt) => count + receipt.ids.length, 0);
550
+ if (this.purgeRequests.size >= MAX_PURGE_REQUESTS || references + ids.length > MAX_PURGE_SELECTION_IDS)
551
+ throw new Error('Durable purge request capacity reached (1000 requests / 20000 selected IDs); no retry selection was discarded.');
552
+ this.purgeRequests.set(key, { digest, ids });
553
+ try {
554
+ await this.persist();
555
+ }
556
+ catch (error) {
557
+ this.purgeRequests.delete(key);
558
+ throw error;
559
+ }
560
+ return [...ids];
561
+ }));
562
+ }
563
+ purgeIds(owner, selection) {
564
+ const value = object(selection, ['ids', 'all']);
565
+ if (value.all !== undefined ? value.all !== true || value.ids !== undefined : !Array.isArray(value.ids))
566
+ throw new Error('Select exact schedule IDs or all current-owner schedules.');
567
+ const ids = value.all === true ? [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => record.id)
568
+ .concat([...this.cleanup.values()].filter(record => sameCleanupOwner(record, owner)).map(record => record.id))
569
+ : [...value.ids];
570
+ if (ids.length > this.maxRecords + MAX_CLEANUP_RECORDS || new Set(ids).size !== ids.length)
571
+ throw new Error('Invalid schedule purge selection.');
572
+ ids.forEach(ScheduleCommand_1.validateScheduleId);
573
+ return ids;
574
+ }
575
+ /** Cancel first. Remove eligible history independently of unresolved native
576
+ * absence, preserving a minimal deletion ledger and permanent replay fence. */
577
+ purge(owner, selection, isCurrent = () => true) {
578
+ return this.operation(this.purgeSelected(structuredClone(owner), structuredClone(selection), isCurrent));
579
+ }
580
+ async purgeSelected(owner, selection, isCurrent) {
512
581
  this.checkReady();
513
582
  validateOwner(owner);
514
583
  const selectedIds = await this.serial(async () => {
515
- if (!this.current(owner))
584
+ if (!this.current(owner) || !isCurrent())
516
585
  throw new Error('Schedule purge owner is no longer current.');
517
- const value = object(selection, ['ids', 'all']);
518
- if (value.all !== undefined ? value.all !== true || value.ids !== undefined : !Array.isArray(value.ids)) {
519
- throw new Error('Select exact schedule IDs or all current-owner schedules.');
520
- }
521
- const ids = value.all === true ? [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => record.id)
522
- : [...value.ids];
523
- if (ids.length > this.maxRecords || new Set(ids).size !== ids.length)
524
- throw new Error('Invalid schedule purge selection.');
525
- ids.forEach(ScheduleCommand_1.validateScheduleId);
586
+ const ids = this.purgeIds(owner, selection);
526
587
  let changed = false;
527
588
  for (const id of ids) {
528
589
  const record = this.records.get(id);
@@ -539,18 +600,18 @@ class ScheduleService {
539
600
  await this.persist();
540
601
  return ids;
541
602
  });
542
- const result = { selectedIds, removedIds: [], alreadyRemovedIds: [], pending: [], errors: [] };
603
+ const result = { selectedIds, status: 'complete', removedIds: [], historyRemovedIds: [], nativeCleanupUnresolved: [], alreadyRemovedIds: [], pending: [], errors: [] };
543
604
  for (const id of selectedIds) {
544
605
  const previouslyPurged = this.purged.has(id);
545
606
  try {
546
607
  const record = this.records.get(id);
547
608
  const prior = this.purged.get(id);
548
- if ((!record || !sameOwner(record, owner)) && (!prior || !sameOwner(prior, owner))) {
609
+ if ((!record || !sameOwner(record, owner)) && (!prior || !sameCleanupOwner(prior, owner))) {
549
610
  throw new Error('Schedule not found for this owner.');
550
611
  }
551
612
  let task = this.purges.get(id);
552
613
  if (!task) {
553
- task = this.purgeRecord(owner, id);
614
+ task = this.purgeRecord(owner, id, isCurrent);
554
615
  this.purges.set(id, task);
555
616
  void task.finally(() => { if (this.purges.get(id) === task)
556
617
  this.purges.delete(id); }).catch(() => { });
@@ -562,25 +623,78 @@ class ScheduleService {
562
623
  (outcome.status === 'removed' ? result.removedIds : result.alreadyRemovedIds).push(id);
563
624
  }
564
625
  catch (error) {
565
- if (!previouslyPurged && this.purged.has(id) && sameOwner(this.purged.get(id), owner))
566
- result.removedIds.push(id);
626
+ if (this.purged.has(id) && sameCleanupOwner(this.purged.get(id), owner))
627
+ (previouslyPurged ? result.alreadyRemovedIds : result.removedIds).push(id);
567
628
  result.errors.push({ id, error: errorText(error) });
568
629
  }
569
630
  }
631
+ result.historyRemovedIds = [...result.removedIds];
632
+ result.nativeCleanupUnresolved = selectedIds.flatMap(id => {
633
+ const item = this.cleanup.get(id);
634
+ return item && sameCleanupOwner(item, owner) ? [(0, ScheduleCleanup_1.cleanupSummary)(item)] : [];
635
+ });
636
+ if (result.pending.length || result.errors.length || result.nativeCleanupUnresolved.length)
637
+ result.status = 'partial';
570
638
  return result;
571
639
  }
572
- async purgeRecord(owner, id) {
640
+ async retryCleanup(owner, id, isCurrent) {
641
+ const item = this.cleanup.get(id);
642
+ if (this.options.isNativeMutationPending?.(owner))
643
+ return { status: 'pending', reason: 'operation_pending', detail: 'A native mutation receipt is unsettled; retry after reconciliation.' };
644
+ if (!item || !this.options.withPurgeVerification)
645
+ return { status: 'alreadyRemoved' };
646
+ const current = () => !this.closing && !this.fault && !this.suspending && isCurrent() && this.current(owner) && this.cleanup.get(id) === item;
647
+ let accepted = false;
648
+ return this.options.withPurgeVerification(structuredClone(item), { isCurrent: current }, async (evidence) => {
649
+ if (accepted)
650
+ throw new Error('Purge verification was already consumed.');
651
+ accepted = true;
652
+ return this.serial(async () => {
653
+ this.checkReady();
654
+ if (!current())
655
+ throw new Error('Schedule cleanup context changed.');
656
+ if (evidence.status === 'unresolved') {
657
+ if (!['unattributed', 'native_absence_unknown', 'predecessor_unknown'].includes(evidence.reason))
658
+ return { status: 'pending', reason: evidence.reason, detail: bounded(evidence.detail, ERROR_BYTES) };
659
+ if (['unattributed', 'native_absence_unknown', 'predecessor_unknown'].includes(evidence.reason) && item.reason !== evidence.reason) {
660
+ const previous = item.reason;
661
+ item.reason = evidence.reason;
662
+ try {
663
+ await this.persist();
664
+ }
665
+ catch (error) {
666
+ item.reason = previous;
667
+ throw error;
668
+ }
669
+ }
670
+ return { status: 'alreadyRemoved' };
671
+ }
672
+ if (evidence.status !== 'verified' || !evidence.isCurrent())
673
+ throw new Error('Schedule cleanup evidence expired.');
674
+ this.cleanup.delete(id);
675
+ try {
676
+ await this.persist();
677
+ }
678
+ catch (error) {
679
+ this.cleanup.set(id, item);
680
+ throw error;
681
+ }
682
+ return { status: 'alreadyRemoved' };
683
+ });
684
+ });
685
+ }
686
+ async purgeRecord(owner, id, isCurrent) {
573
687
  const pending = (reason, detail) => ({ status: 'pending', reason, detail });
574
688
  this.checkReady();
575
- if (!this.current(owner))
689
+ if (!this.current(owner) || !isCurrent())
576
690
  throw new Error('Schedule purge owner is no longer current.');
577
691
  if (this.purged.has(id))
578
- return { status: 'alreadyRemoved' };
692
+ return this.retryCleanup(owner, id, isCurrent);
579
693
  const record = this.owned(owner, id);
580
- const current = () => !this.closing && !this.fault && !this.suspending && this.current(owner)
694
+ const current = () => !this.closing && !this.fault && !this.suspending && isCurrent() && this.current(owner)
581
695
  && this.records.get(id) === record && record.cancelRequested === true;
582
696
  const busy = () => {
583
- if (this.recordOperations.has(id) || this.recoveryRun || this.refreshes || this.retainedCancellations.has(id)) {
697
+ if (this.options.isNativeMutationPending?.(owner) || this.recordOperations.has(id) || this.recoveryRun || this.refreshes || this.retainedCancellations.has(id)) {
584
698
  return pending('operation_pending', 'Creation, recovery, inspection or cleanup is still pending. Retry these same IDs.');
585
699
  }
586
700
  if (this.delivering.has(id))
@@ -595,7 +709,7 @@ class ScheduleService {
595
709
  // Do not interpret terminal state, an absent handle or a stopped process as
596
710
  // native definition absence. Existing cancelRetained owns its stronger proof.
597
711
  let retainedVerified = false;
598
- const clean = !runtime && record.recovery?.handoff === 'clean' && record.recovery.nativeDefinitionAbsent === true;
712
+ const clean = !runtime && (record.cleanupConfirmed === true || record.recovery?.handoff === 'clean' && record.recovery.nativeDefinitionAbsent === true);
599
713
  if (runtime?.handle && !runtime.stopped) {
600
714
  await this.cancel(owner, id);
601
715
  }
@@ -607,8 +721,8 @@ class ScheduleService {
607
721
  catch (error) {
608
722
  // A failed receipt (including error-after-commit) is not absence proof.
609
723
  // Exact framework verification may still resolve it without recreating.
610
- if (!this.options.withPurgeVerification)
611
- throw error;
724
+ // The settled failed mutation remains an unresolved cleanup obligation.
725
+ // It cannot veto deletion of text after all local work has retired.
612
726
  }
613
727
  }
614
728
  if (!current())
@@ -621,7 +735,7 @@ class ScheduleService {
621
735
  if (runtime && (!runtime.stopped || runtime.releaseAdmission))
622
736
  return pending('operation_pending', 'Native runtime retirement is unconfirmed.');
623
737
  const handleProof = runtime?.removalConfirmed && runtime.handle?.nativeDefinitionAbsent !== false;
624
- const erase = (evidence) => this.serial(async () => {
738
+ const erase = (evidence, unresolved) => this.serial(async () => {
625
739
  this.checkReady();
626
740
  if (!current() || evidence?.status === 'verified' && !evidence.isCurrent())
627
741
  throw new Error('Schedule purge evidence expired before persistence.');
@@ -634,10 +748,14 @@ class ScheduleService {
634
748
  || handleProof && runtime?.handle?.nativeDefinitionAbsent === false) {
635
749
  return pending('operation_pending', 'Native ownership changed before history removal.');
636
750
  }
637
- // The ID-only owner fence prevents delayed CREATE retries from resurrecting
638
- // deleted history. Prompts, results and recovery identities are not retained.
751
+ if (unresolved && this.cleanup.size >= MAX_CLEANUP_RECORDS)
752
+ return pending('fence_capacity', 'Native cleanup ledger capacity reached (1000); resolve existing cleanup before removing more history.');
753
+ // Commit history/output deletion, minimal operational selector and replay
754
+ // denial in the same atomic catalog replacement. Never retain user text.
639
755
  const outputs = [...this.pending].filter(([, entry]) => entry.scheduleId === id);
640
756
  this.purged.set(id, ownerOf(record));
757
+ if (unresolved)
758
+ this.cleanup.set(id, (0, ScheduleCleanup_1.cleanupRecord)(record, unresolved));
641
759
  this.records.delete(id);
642
760
  this.dropPending(id);
643
761
  try {
@@ -646,6 +764,7 @@ class ScheduleService {
646
764
  catch (error) {
647
765
  this.records.set(id, record);
648
766
  this.purged.delete(id);
767
+ this.cleanup.delete(id);
649
768
  for (const [key, entry] of outputs)
650
769
  this.pending.set(key, entry);
651
770
  throw error;
@@ -656,7 +775,7 @@ class ScheduleService {
656
775
  if (record.creationRefused || clean || retainedVerified || handleProof)
657
776
  return erase();
658
777
  if (!this.options.withPurgeVerification)
659
- return pending('native_absence_unknown', 'Native absence and execution retirement require exact provider verification; terminal state and current-session absence alone are insufficient.');
778
+ return erase(undefined, 'native_absence_unknown');
660
779
  let accepted = false;
661
780
  // The framework keeps its native scope/lease open until accept() finishes
662
781
  // persisting removal. A receipt returned after closing that lease is unsafe.
@@ -667,7 +786,8 @@ class ScheduleService {
667
786
  if (!current())
668
787
  throw new Error('Schedule purge context changed during verification.');
669
788
  if (evidence.status === 'unresolved')
670
- return pending(evidence.reason, bounded(evidence.detail, ERROR_BYTES));
789
+ return ['unattributed', 'native_absence_unknown', 'predecessor_unknown'].includes(evidence.reason)
790
+ ? erase(undefined, evidence.reason) : pending(evidence.reason, bounded(evidence.detail, ERROR_BYTES));
671
791
  if (evidence.status !== 'verified' || typeof evidence.isCurrent !== 'function')
672
792
  throw new Error('Invalid native purge verification.');
673
793
  return erase(evidence);
@@ -688,8 +808,9 @@ class ScheduleService {
688
808
  return LIVE.has(record.state) || recoveryOwnsWork(record) || record.state === 'interrupted' && !!record.nativeId && this.supportsRetainedCancellation(record)
689
809
  || Boolean(runtime && !runtime.stopped);
690
810
  }
691
- /** Newly observed local cleanup facts do not supply historical recovery proof. */
692
- async recordReviewedCleanup(owner, ids, absent) {
811
+ /** Newly observed cleanup facts never supply historical recovery proof. The optional
812
+ * retirement callback is framework-owned and checked under the native cleanup lease. */
813
+ async recordReviewedCleanup(owner, ids, absent, retirementConfirmed) {
693
814
  this.checkReady();
694
815
  validateOwner(owner);
695
816
  ids.forEach(ScheduleCommand_1.validateScheduleId);
@@ -700,6 +821,7 @@ class ScheduleService {
700
821
  throw new Error('Cleanup catalog owner changed.');
701
822
  for (const id of ids) {
702
823
  const record = this.owned(owner, id);
824
+ delete record.cleanupConfirmed;
703
825
  record.cancelRequested = true;
704
826
  if (record.recovery)
705
827
  record.recovery.status = 'blocked';
@@ -707,6 +829,18 @@ class ScheduleService {
707
829
  record.state = 'interrupted';
708
830
  record.error = absent ? 'Owner-reviewed native definition absent on current host; predecessor work remains unknown.'
709
831
  : 'Owner-reviewed native deletion requested; absence and predecessor work remain unconfirmed.';
832
+ const runtime = this.runtimes.get(id);
833
+ if (absent && retirementConfirmed?.() === true && (!runtime || runtime.stopped && !runtime.running.size)
834
+ && !this.recordOperations.has(id) && !this.recoveryRun && !this.refreshes && !this.retainedCancellations.has(id)) {
835
+ record.state = 'cancelled';
836
+ record.cleanupConfirmed = true;
837
+ delete record.error;
838
+ // Native-only cleanup must not discard already-admitted output. History
839
+ // purge owns output removal after checking in-flight delivery fences.
840
+ for (const pending of this.pending.values())
841
+ if (pending.scheduleId === id)
842
+ pending.afterCancellation = true;
843
+ }
710
844
  }
711
845
  await this.persist();
712
846
  });
@@ -853,6 +987,7 @@ class ScheduleService {
853
987
  if (!current())
854
988
  throw new Error('Native cancellation owner changed before its receipt was saved.');
855
989
  record.state = 'cancelled';
990
+ record.cleanupConfirmed = true;
856
991
  delete record.error;
857
992
  for (const [key, pending] of this.pending)
858
993
  if (pending.scheduleId === record.id && !pending.afterCancellation)
@@ -1344,7 +1479,7 @@ class ScheduleService {
1344
1479
  if (this.runtimes.get(id) !== runtime)
1345
1480
  return Promise.resolve();
1346
1481
  if (runtime.stopped)
1347
- return Promise.resolve();
1482
+ return this.rememberCleanup(id, runtime);
1348
1483
  if (runtime.stopPromise)
1349
1484
  return runtime.recoveryAbort ? this.boundRecovery(runtime.stopPromise, 'Native cleanup remains unresolved; ownership retained.') : runtime.stopPromise;
1350
1485
  const operation = (async () => {
@@ -1366,6 +1501,7 @@ class ScheduleService {
1366
1501
  if (runtime.stopped) {
1367
1502
  runtime.releaseAdmission?.();
1368
1503
  runtime.releaseAdmission = undefined;
1504
+ await this.rememberCleanup(id, runtime);
1369
1505
  }
1370
1506
  }
1371
1507
  catch (error) {
@@ -1383,6 +1519,17 @@ class ScheduleService {
1383
1519
  runtime.stopPromise = undefined; }).catch(() => { });
1384
1520
  return runtime.recoveryAbort ? this.boundRecovery(tracked, 'Native cleanup remains unresolved; ownership retained.') : tracked;
1385
1521
  }
1522
+ rememberCleanup(id, runtime) {
1523
+ return this.serial(async () => {
1524
+ const record = this.records.get(id);
1525
+ if (this.runtimes.get(id) === runtime && runtime.stopped && !runtime.running.size
1526
+ && runtime.removalConfirmed && runtime.handle?.nativeDefinitionAbsent === true
1527
+ && record?.cancelRequested && record.state === 'cancelled' && !record.cleanupConfirmed) {
1528
+ record.cleanupConfirmed = true;
1529
+ await this.persist();
1530
+ }
1531
+ });
1532
+ }
1386
1533
  async boundRecovery(operation, message) {
1387
1534
  let timer;
1388
1535
  try {
@@ -1476,7 +1623,8 @@ class ScheduleService {
1476
1623
  try {
1477
1624
  // JSON can expand one control byte to six bytes (for example, "\\u0001").
1478
1625
  const maxBytes = (this.maxRecords + this.maxPending) * (160 * 1024)
1479
- + this.maxRecords * this.maxOccurrences * 515 + MAX_PURGED_IDS * 2048 + 4096;
1626
+ + this.maxRecords * this.maxOccurrences * 515 + MAX_PURGED_IDS * 2048
1627
+ + MAX_CLEANUP_RECORDS * 8192 + MAX_PURGE_SELECTION_IDS * 1024 + 4096;
1480
1628
  const size = (await handle.stat()).size;
1481
1629
  if (size > maxBytes)
1482
1630
  throw new Error('Schedule catalog exceeds its size limit.');
@@ -1501,14 +1649,14 @@ class ScheduleService {
1501
1649
  }
1502
1650
  }
1503
1651
  load(data) {
1504
- const catalog = object(data, ['version', 'records', 'pending', 'purged']);
1505
- if (![1, 2, 3].includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
1652
+ const catalog = object(data, ['version', 'records', 'pending', 'purged', 'cleanup', 'purgeRequests']);
1653
+ if (![1, 2, 3, 4, 5].includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
1506
1654
  || !Array.isArray(catalog.pending) || catalog.pending.length > this.maxPending)
1507
1655
  throw new Error('Invalid schedule catalog envelope.');
1508
1656
  const records = new Map();
1509
1657
  const pending = new Map();
1510
1658
  for (const value of catalog.records) {
1511
- const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'creationRefused', 'recovery', 'completedOccurrences', 'skippedOccurrences']);
1659
+ const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'creationRefused', 'cleanupConfirmed', 'recovery', 'completedOccurrences', 'skippedOccurrences']);
1512
1660
  (0, ScheduleCommand_1.validateScheduleId)(record.id);
1513
1661
  validateOwner(record);
1514
1662
  (0, ScheduleCommand_1.validateSchedulePrompt)(record.prompt);
@@ -1523,10 +1671,13 @@ class ScheduleService {
1523
1671
  throw new Error('Invalid schedule error.');
1524
1672
  if (record.cancelRequested !== undefined && record.cancelRequested !== true)
1525
1673
  throw new Error('Invalid cancellation intent.');
1526
- if (record.creationRefused !== undefined && (catalog.version !== 3 || record.creationRefused !== true || record.nativeId !== undefined
1674
+ if (record.creationRefused !== undefined && (Number(catalog.version) < 3 || record.creationRefused !== true || record.nativeId !== undefined
1527
1675
  || !['failed', 'cancelled', 'interrupted'].includes(record.state)
1528
1676
  || record.completedOccurrences !== undefined))
1529
1677
  throw new Error('Invalid native admission refusal.');
1678
+ if (record.cleanupConfirmed !== undefined && (Number(catalog.version) < 4 || record.cleanupConfirmed !== true
1679
+ || record.cancelRequested !== true || record.state !== 'cancelled'))
1680
+ throw new Error('Invalid confirmed cleanup receipt.');
1530
1681
  if (record.execution !== undefined) {
1531
1682
  const execution = object(record.execution, ['command', 'model', 'effort']);
1532
1683
  for (const value of Object.values(execution))
@@ -1578,7 +1729,7 @@ class ScheduleService {
1578
1729
  pending.set(item.id, structuredClone(item));
1579
1730
  }
1580
1731
  const purged = new Map();
1581
- if (catalog.version === 3) {
1732
+ if (Number(catalog.version) >= 3) {
1582
1733
  if (!Array.isArray(catalog.purged) || catalog.purged.length > MAX_PURGED_IDS)
1583
1734
  throw new Error('Invalid purge fences.');
1584
1735
  for (const value of catalog.purged) {
@@ -1591,10 +1742,59 @@ class ScheduleService {
1591
1742
  }
1592
1743
  }
1593
1744
  else if (catalog.purged !== undefined)
1594
- throw new Error('Purge fences require catalog version 3.');
1745
+ throw new Error('Purge fences require catalog version 3 or newer.');
1746
+ const cleanup = new Map();
1747
+ const purgeRequests = new Map();
1748
+ if (catalog.version === 5) {
1749
+ if (!Array.isArray(catalog.cleanup) || catalog.cleanup.length > MAX_CLEANUP_RECORDS)
1750
+ throw new Error('Invalid cleanup ledger.');
1751
+ for (const value of catalog.cleanup) {
1752
+ const entry = object(value, ['id', 'threadId', 'openId', 'generation', 'backend', 'cwd', 'nativeId', 'historyRemoved', 'reason', 'attribution']);
1753
+ (0, ScheduleCommand_1.validateScheduleId)(entry.id);
1754
+ validateOwner(entry);
1755
+ text(entry.cwd, 4096);
1756
+ const fence = purged.get(entry.id);
1757
+ if (!fence || !sameOwner(fence, entry) || cleanup.has(entry.id)
1758
+ || !node_path_1.default.isAbsolute(entry.cwd) || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(entry.backend) || entry.historyRemoved !== true
1759
+ || !['unattributed', 'native_absence_unknown', 'predecessor_unknown'].includes(entry.reason))
1760
+ throw new Error('Invalid cleanup selector.');
1761
+ if (entry.nativeId !== undefined)
1762
+ text(entry.nativeId);
1763
+ if (entry.attribution !== undefined) {
1764
+ const a = object(entry.attribution, ['sessionId', 'marker', 'promptHash', 'rule']);
1765
+ text(a.sessionId);
1766
+ if (typeof a.promptHash !== 'string' || !/^[a-f0-9]{64}$/.test(a.promptHash)
1767
+ || (entry.backend === 'claude' ? typeof a.marker !== 'string' || !/^[a-f0-9-]{36}$/.test(a.marker) : a.marker !== undefined))
1768
+ throw new Error('Invalid cleanup attribution.');
1769
+ const rule = object(a.rule, ['kind', 'at', 'expression', 'timezone']);
1770
+ object(rule, rule.kind === 'once' ? ['kind', 'at'] : ['kind', 'expression', 'timezone']);
1771
+ (0, ScheduleCommand_1.validateScheduleRule)(rule);
1772
+ }
1773
+ cleanup.set(entry.id, structuredClone(entry));
1774
+ }
1775
+ if (catalog.purgeRequests !== undefined) {
1776
+ if (!Array.isArray(catalog.purgeRequests) || catalog.purgeRequests.length > MAX_PURGE_REQUESTS)
1777
+ throw new Error('Invalid purge requests.');
1778
+ let references = 0;
1779
+ for (const value of catalog.purgeRequests) {
1780
+ const receipt = object(value, ['key', 'digest', 'ids']);
1781
+ if (typeof receipt.key !== 'string' || !/^[a-f0-9]{64}$/.test(receipt.key) || purgeRequests.has(receipt.key)
1782
+ || typeof receipt.digest !== 'string' || !/^[a-f0-9]{64}$/.test(receipt.digest)
1783
+ || !Array.isArray(receipt.ids) || new Set(receipt.ids).size !== receipt.ids.length
1784
+ || (references += receipt.ids.length) > MAX_PURGE_SELECTION_IDS)
1785
+ throw new Error('Invalid purge request receipt.');
1786
+ receipt.ids.forEach(ScheduleCommand_1.validateScheduleId);
1787
+ purgeRequests.set(receipt.key, { digest: receipt.digest, ids: [...receipt.ids] });
1788
+ }
1789
+ }
1790
+ }
1791
+ else if (catalog.cleanup !== undefined || catalog.purgeRequests !== undefined)
1792
+ throw new Error('Cleanup ledger requires catalog version 5.');
1595
1793
  this.records = records;
1596
1794
  this.pending = pending;
1597
1795
  this.purged = purged;
1796
+ this.cleanup = cleanup;
1797
+ this.purgeRequests = purgeRequests;
1598
1798
  }
1599
1799
  async persist() {
1600
1800
  if (!this.catalogGate)
@@ -1615,8 +1815,11 @@ class ScheduleService {
1615
1815
  }
1616
1816
  const handle = await fs.open(temporary, 'wx', 0o600);
1617
1817
  try {
1618
- const upgraded = this.purged.size > 0 || [...this.records.values()].some(record => record.creationRefused);
1619
- await handle.writeFile(JSON.stringify({ version: upgraded ? 3 : 2, records: [...this.records.values()], pending: [...this.pending.values()],
1818
+ const confirmedCleanup = [...this.records.values()].some(record => record.cleanupConfirmed);
1819
+ const upgraded = this.purgeRequests.size > 0 || confirmedCleanup || this.purged.size > 0 || [...this.records.values()].some(record => record.creationRefused);
1820
+ await handle.writeFile(JSON.stringify({ version: this.cleanup.size || this.purgeRequests.size ? 5 : confirmedCleanup ? 4 : upgraded ? 3 : 2, records: [...this.records.values()], pending: [...this.pending.values()],
1821
+ ...(this.cleanup.size || this.purgeRequests.size ? { cleanup: [...this.cleanup.values()],
1822
+ purgeRequests: [...this.purgeRequests].map(([key, receipt]) => ({ key, ...receipt })) } : {}),
1620
1823
  ...(upgraded ? { purged: [...this.purged].map(([id, owner]) => ({ id, ...owner })) } : {}) }), 'utf8');
1621
1824
  await handle.sync();
1622
1825
  }