@yu_robotics/remote-cli 1.6.240 → 1.6.242

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 (61) hide show
  1. package/dist/client/MessageHandler.d.ts +7 -0
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +200 -14
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/delegation/ArtifactCloseoutContinuation.d.ts +14 -0
  6. package/dist/delegation/ArtifactCloseoutContinuation.d.ts.map +1 -0
  7. package/dist/delegation/ArtifactCloseoutContinuation.js +37 -0
  8. package/dist/delegation/ArtifactCloseoutContinuation.js.map +1 -0
  9. package/dist/delegation/DelegationManager.d.ts +0 -1
  10. package/dist/delegation/DelegationManager.d.ts.map +1 -1
  11. package/dist/delegation/DelegationManager.js +1 -1
  12. package/dist/delegation/DelegationManager.js.map +1 -1
  13. package/dist/executor/ClaudePersistentExecutor.d.ts +6 -1
  14. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  15. package/dist/executor/ClaudePersistentExecutor.js +75 -19
  16. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  17. package/dist/executor/IExecutor.d.ts +3 -1
  18. package/dist/executor/IExecutor.d.ts.map +1 -1
  19. package/dist/maintenance/release-notes.json +1 -1
  20. package/dist/managed/tools.d.ts +54 -0
  21. package/dist/managed/tools.d.ts.map +1 -1
  22. package/dist/scheduling/ReviewedNativeCleanup.d.ts +44 -0
  23. package/dist/scheduling/ReviewedNativeCleanup.d.ts.map +1 -0
  24. package/dist/scheduling/ReviewedNativeCleanup.js +165 -0
  25. package/dist/scheduling/ReviewedNativeCleanup.js.map +1 -0
  26. package/dist/scheduling/ScheduleCommand.d.ts +15 -0
  27. package/dist/scheduling/ScheduleCommand.d.ts.map +1 -1
  28. package/dist/scheduling/ScheduleCommand.js +26 -0
  29. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  30. package/dist/scheduling/ScheduleService.d.ts +53 -0
  31. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  32. package/dist/scheduling/ScheduleService.js +282 -20
  33. package/dist/scheduling/ScheduleService.js.map +1 -1
  34. package/dist/scheduling/ScheduleToolScope.d.ts +16 -0
  35. package/dist/scheduling/ScheduleToolScope.d.ts.map +1 -1
  36. package/dist/scheduling/ScheduleToolScope.js +43 -0
  37. package/dist/scheduling/ScheduleToolScope.js.map +1 -1
  38. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +5 -0
  39. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  40. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +22 -0
  41. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  42. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +12 -1
  43. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  44. package/dist/scheduling/claude/ClaudeSessionSchedules.js +74 -7
  45. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  46. package/dist/scheduling/toolContract.d.ts +27 -0
  47. package/dist/scheduling/toolContract.d.ts.map +1 -1
  48. package/dist/scheduling/toolContract.js +4 -1
  49. package/dist/scheduling/toolContract.js.map +1 -1
  50. package/dist/scheduling/types.d.ts +6 -1
  51. package/dist/scheduling/types.d.ts.map +1 -1
  52. package/dist/scheduling/types.js.map +1 -1
  53. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  54. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  55. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  56. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  57. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  58. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  59. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  60. package/native/prebuilds/win32-x64/manifest.json +1 -1
  61. package/package.json +1 -1
@@ -51,6 +51,7 @@ const ERROR_BYTES = 4096;
51
51
  const LIVE = new Set(['creating', 'active', 'running']);
52
52
  const STATES = new Set([...LIVE, 'completed', 'cancelled', 'interrupted', 'failed']);
53
53
  const RESTART_REASON = 'Native schedule interrupted by service restart; not recreated or resumed.';
54
+ const MAX_PURGED_IDS = 10_000;
54
55
  function bounded(value, limit) {
55
56
  if (Buffer.byteLength(value, 'utf8') <= limit)
56
57
  return value;
@@ -109,6 +110,11 @@ class ScheduleService {
109
110
  pending = new Map();
110
111
  runtimes = new Map();
111
112
  retainedCancellations = new Map();
113
+ purged = new Map();
114
+ purges = new Map();
115
+ recordOperations = new Map();
116
+ delivering = new Set();
117
+ refreshes = 0;
112
118
  tail = Promise.resolve();
113
119
  deliveryTail = Promise.resolve();
114
120
  tasks = new Set();
@@ -209,6 +215,8 @@ class ScheduleService {
209
215
  if (this.closing || this.fault)
210
216
  return;
211
217
  const record = this.records.get(id);
218
+ if (!record)
219
+ continue;
212
220
  if (record.cancelRequested || !this.current(record)) {
213
221
  await this.blockRecovery(record, 'Recovery owner retired or cancellation was requested.');
214
222
  continue;
@@ -263,7 +271,8 @@ class ScheduleService {
263
271
  });
264
272
  admitted = true;
265
273
  const admission = Promise.resolve().then(() => provider.reconcile(restoreRecord, { notBefore: this.now(), signal: controller.signal, isCurrent: current,
266
- isOwnerCurrent: () => !record.cancelRequested && !this.fault && this.current(record) }, emit));
274
+ isOwnerCurrent: () => !record.cancelRequested && !this.fault && this.current(record),
275
+ canAdmitOccurrence: () => this.canAdmitOccurrence(id, runtime) }, emit));
267
276
  const adopt = async (handle) => {
268
277
  runtime.handle = handle;
269
278
  runtime.resolveReady(handle);
@@ -380,7 +389,7 @@ class ScheduleService {
380
389
  });
381
390
  }
382
391
  create(owner, input) {
383
- return this.operation(this.createSchedule(owner, input));
392
+ return this.operation(this.recordOperation(input.id, this.createSchedule(owner, input)));
384
393
  }
385
394
  async createSchedule(owner, input) {
386
395
  this.checkReady();
@@ -414,8 +423,8 @@ class ScheduleService {
414
423
  this.checkReady();
415
424
  if (!this.current(originalOwner))
416
425
  throw new Error('Schedule owner is no longer current.');
417
- if (this.records.has(nativeInput.id))
418
- throw new Error('Schedule ID already exists.');
426
+ if (this.records.has(nativeInput.id) || this.purged.has(nativeInput.id))
427
+ throw new Error('Schedule ID already exists or was purged.');
419
428
  if (this.records.size >= this.maxRecords)
420
429
  throw new Error('Schedule catalog is full; history was not pruned.');
421
430
  const liveCount = [...this.records.values()].filter(record => LIVE.has(record.state)
@@ -436,7 +445,7 @@ class ScheduleService {
436
445
  return;
437
446
  const task = this.onEvent(nativeInput.id, structuredClone(event));
438
447
  this.track(task);
439
- });
448
+ }, () => this.canAdmitOccurrence(nativeInput.id, runtime));
440
449
  runtime.handle = handle;
441
450
  runtime.resolveReady(handle);
442
451
  text(handle.nativeId);
@@ -475,6 +484,9 @@ class ScheduleService {
475
484
  record.state = 'failed';
476
485
  record.error = errorText(error);
477
486
  }
487
+ if (error instanceof types_1.NativeScheduleNotAdmittedError && !runtime.handle && !runtime.running.size && !runtime.completed.size) {
488
+ record.creationRefused = true;
489
+ }
478
490
  if (!this.fault)
479
491
  await this.persist();
480
492
  });
@@ -491,6 +503,176 @@ class ScheduleService {
491
503
  validateOwner(owner);
492
504
  return this.serial(async () => [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => structuredClone(record)));
493
505
  }
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)));
510
+ }
511
+ async purgeSelected(owner, selection) {
512
+ this.checkReady();
513
+ validateOwner(owner);
514
+ const selectedIds = await this.serial(async () => {
515
+ if (!this.current(owner))
516
+ 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);
526
+ let changed = false;
527
+ for (const id of ids) {
528
+ const record = this.records.get(id);
529
+ if (!record || !sameOwner(record, owner))
530
+ continue;
531
+ record.cancelRequested = true;
532
+ if (record.recovery)
533
+ record.recovery.status = 'blocked';
534
+ this.runtimes.get(id)?.recoveryAbort?.abort();
535
+ changed = true;
536
+ }
537
+ // Persist admission/recovery denial before any external cleanup attempt.
538
+ if (changed)
539
+ await this.persist();
540
+ return ids;
541
+ });
542
+ const result = { selectedIds, removedIds: [], alreadyRemovedIds: [], pending: [], errors: [] };
543
+ for (const id of selectedIds) {
544
+ const previouslyPurged = this.purged.has(id);
545
+ try {
546
+ const record = this.records.get(id);
547
+ const prior = this.purged.get(id);
548
+ if ((!record || !sameOwner(record, owner)) && (!prior || !sameOwner(prior, owner))) {
549
+ throw new Error('Schedule not found for this owner.');
550
+ }
551
+ let task = this.purges.get(id);
552
+ if (!task) {
553
+ task = this.purgeRecord(owner, id);
554
+ this.purges.set(id, task);
555
+ void task.finally(() => { if (this.purges.get(id) === task)
556
+ this.purges.delete(id); }).catch(() => { });
557
+ }
558
+ const outcome = await task;
559
+ if (outcome.status === 'pending')
560
+ result.pending.push({ id, reason: outcome.reason, detail: outcome.detail });
561
+ else
562
+ (outcome.status === 'removed' ? result.removedIds : result.alreadyRemovedIds).push(id);
563
+ }
564
+ catch (error) {
565
+ if (!previouslyPurged && this.purged.has(id) && sameOwner(this.purged.get(id), owner))
566
+ result.removedIds.push(id);
567
+ result.errors.push({ id, error: errorText(error) });
568
+ }
569
+ }
570
+ return result;
571
+ }
572
+ async purgeRecord(owner, id) {
573
+ const pending = (reason, detail) => ({ status: 'pending', reason, detail });
574
+ this.checkReady();
575
+ if (!this.current(owner))
576
+ throw new Error('Schedule purge owner is no longer current.');
577
+ if (this.purged.has(id))
578
+ return { status: 'alreadyRemoved' };
579
+ const record = this.owned(owner, id);
580
+ const current = () => !this.closing && !this.fault && !this.suspending && this.current(owner)
581
+ && this.records.get(id) === record && record.cancelRequested === true;
582
+ const busy = () => {
583
+ if (this.recordOperations.has(id) || this.recoveryRun || this.refreshes || this.retainedCancellations.has(id)) {
584
+ return pending('operation_pending', 'Creation, recovery, inspection or cleanup is still pending. Retry these same IDs.');
585
+ }
586
+ if (this.delivering.has(id))
587
+ return pending('delivery_pending', 'An external delivery is already in flight; its outcome cannot be revoked.');
588
+ };
589
+ const active = busy();
590
+ if (active)
591
+ return active;
592
+ if (this.purged.size >= MAX_PURGED_IDS)
593
+ return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
594
+ const runtime = this.runtimes.get(id);
595
+ // Do not interpret terminal state, an absent handle or a stopped process as
596
+ // native definition absence. Existing cancelRetained owns its stronger proof.
597
+ let retainedVerified = false;
598
+ const clean = !runtime && record.recovery?.handoff === 'clean' && record.recovery.nativeDefinitionAbsent === true;
599
+ if (runtime?.handle && !runtime.stopped) {
600
+ await this.cancel(owner, id);
601
+ }
602
+ else if (!runtime && !record.creationRefused && !clean && record.recovery && this.supportsRetainedCancellation(record)) {
603
+ try {
604
+ await this.recordOperation(id, this.cancelRetained(record));
605
+ retainedVerified = true;
606
+ }
607
+ catch (error) {
608
+ // A failed receipt (including error-after-commit) is not absence proof.
609
+ // Exact framework verification may still resolve it without recreating.
610
+ if (!this.options.withPurgeVerification)
611
+ throw error;
612
+ }
613
+ }
614
+ if (!current())
615
+ throw new Error('Schedule purge context changed during cleanup.');
616
+ const unfinished = busy();
617
+ if (unfinished)
618
+ return unfinished;
619
+ if (runtime?.running.size)
620
+ return pending('occurrence_running', 'Future cancellation does not revoke an already admitted occurrence.');
621
+ if (runtime && (!runtime.stopped || runtime.releaseAdmission))
622
+ return pending('operation_pending', 'Native runtime retirement is unconfirmed.');
623
+ const handleProof = runtime?.removalConfirmed && runtime.handle?.nativeDefinitionAbsent !== false;
624
+ const erase = (evidence) => this.serial(async () => {
625
+ this.checkReady();
626
+ if (!current() || evidence?.status === 'verified' && !evidence.isCurrent())
627
+ throw new Error('Schedule purge evidence expired before persistence.');
628
+ const changed = busy();
629
+ if (changed)
630
+ return changed;
631
+ if (this.purged.size >= MAX_PURGED_IDS)
632
+ return pending('fence_capacity', 'Durable purge ID capacity reached; no replay fence was discarded.');
633
+ if (this.runtimes.get(id) !== runtime || runtime?.running.size || runtime && !runtime.stopped
634
+ || handleProof && runtime?.handle?.nativeDefinitionAbsent === false) {
635
+ return pending('operation_pending', 'Native ownership changed before history removal.');
636
+ }
637
+ // The ID-only owner fence prevents delayed CREATE retries from resurrecting
638
+ // deleted history. Prompts, results and recovery identities are not retained.
639
+ const outputs = [...this.pending].filter(([, entry]) => entry.scheduleId === id);
640
+ this.purged.set(id, ownerOf(record));
641
+ this.records.delete(id);
642
+ this.dropPending(id);
643
+ try {
644
+ await this.persist();
645
+ }
646
+ catch (error) {
647
+ this.records.set(id, record);
648
+ this.purged.delete(id);
649
+ for (const [key, entry] of outputs)
650
+ this.pending.set(key, entry);
651
+ throw error;
652
+ }
653
+ this.runtimes.delete(id);
654
+ return { status: 'removed' };
655
+ });
656
+ if (record.creationRefused || clean || retainedVerified || handleProof)
657
+ return erase();
658
+ 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.');
660
+ let accepted = false;
661
+ // The framework keeps its native scope/lease open until accept() finishes
662
+ // persisting removal. A receipt returned after closing that lease is unsafe.
663
+ return this.options.withPurgeVerification(structuredClone(record), { isCurrent: current }, async (evidence) => {
664
+ if (accepted)
665
+ throw new Error('Purge verification was already consumed.');
666
+ accepted = true;
667
+ if (!current())
668
+ throw new Error('Schedule purge context changed during verification.');
669
+ if (evidence.status === 'unresolved')
670
+ return pending(evidence.reason, bounded(evidence.detail, ERROR_BYTES));
671
+ if (evidence.status !== 'verified' || typeof evidence.isCurrent !== 'function')
672
+ throw new Error('Invalid native purge verification.');
673
+ return erase(evidence);
674
+ });
675
+ }
494
676
  /** Includes terminal jobs whose native process exit is still unconfirmed. */
495
677
  hasActiveSchedules(threadId) {
496
678
  return [...this.records.values()].some(record => (!threadId || record.threadId === threadId)
@@ -506,6 +688,29 @@ class ScheduleService {
506
688
  return LIVE.has(record.state) || recoveryOwnsWork(record) || record.state === 'interrupted' && !!record.nativeId && this.supportsRetainedCancellation(record)
507
689
  || Boolean(runtime && !runtime.stopped);
508
690
  }
691
+ /** Newly observed local cleanup facts do not supply historical recovery proof. */
692
+ async recordReviewedCleanup(owner, ids, absent) {
693
+ this.checkReady();
694
+ validateOwner(owner);
695
+ ids.forEach(ScheduleCommand_1.validateScheduleId);
696
+ if (!ids.length)
697
+ return;
698
+ await this.serial(async () => {
699
+ if (!this.options.isOwnerCurrent(owner))
700
+ throw new Error('Cleanup catalog owner changed.');
701
+ for (const id of ids) {
702
+ const record = this.owned(owner, id);
703
+ record.cancelRequested = true;
704
+ if (record.recovery)
705
+ record.recovery.status = 'blocked';
706
+ if (record.state !== 'running')
707
+ record.state = 'interrupted';
708
+ record.error = absent ? 'Owner-reviewed native definition absent on current host; predecessor work remains unknown.'
709
+ : 'Owner-reviewed native deletion requested; absence and predecessor work remain unconfirmed.';
710
+ }
711
+ await this.persist();
712
+ });
713
+ }
509
714
  /** Keep admitted native work visible when cleanup cannot safely acquire its host. */
510
715
  async retainCleanupError(owner, id, error) {
511
716
  this.checkReady();
@@ -521,7 +726,8 @@ class ScheduleService {
521
726
  }
522
727
  /** User-requested native reconciliation only; no background polling is installed. */
523
728
  refresh(owner) {
524
- return this.operation(this.refreshNative(owner));
729
+ this.refreshes++;
730
+ return this.operation(this.refreshNative(owner).finally(() => { this.refreshes--; }));
525
731
  }
526
732
  async refreshNative(owner) {
527
733
  this.checkReady();
@@ -564,7 +770,7 @@ class ScheduleService {
564
770
  }
565
771
  }
566
772
  cancel(owner, id) {
567
- return this.operation(this.cancelSchedule(owner, id));
773
+ return this.operation(this.recordOperation(id, this.cancelSchedule(owner, id)));
568
774
  }
569
775
  async cancelSchedule(owner, id) {
570
776
  this.checkReady();
@@ -638,7 +844,7 @@ class ScheduleService {
638
844
  ...record.execution, recovery });
639
845
  if (!recovery || !provider?.cancelRetained || provider.provider !== recovery.provider || provider.strategy !== recovery.strategy
640
846
  || (provider.handoffPolicy ?? 'drain-all') !== (recovery.handoffPolicy ?? 'drain-all')) {
641
- throw new Error('Cancellation intent retained; native cleanup is unconfirmed. Original native ownership metadata or cleanup support is unavailable. Preserve the original session for manual inventory review; do not recreate this job.');
847
+ throw new Error('Cancellation intent retained; native cleanup is unconfirmed. Original native ownership metadata or cleanup support is unavailable. Preserve the original session. For Claude, use /schedule cleanup review in the bound original thread for explicit deletion-only review; do not recreate this job.');
642
848
  }
643
849
  if (!current())
644
850
  throw new Error('Native cancellation owner is no longer current.');
@@ -906,8 +1112,10 @@ class ScheduleService {
906
1112
  try {
907
1113
  const handle = await runtime.ready;
908
1114
  if (handle && !runtime.stopped) {
909
- if (LIVE.has(this.records.get(id).state) || handle.cancellationKeepsRunning)
1115
+ if (LIVE.has(this.records.get(id).state) || handle.cancellationKeepsRunning) {
910
1116
  await handle.cancel();
1117
+ runtime.removalConfirmed = true;
1118
+ }
911
1119
  else
912
1120
  await this.stop(id, runtime);
913
1121
  }
@@ -954,6 +1162,8 @@ class ScheduleService {
954
1162
  let cleanup = false;
955
1163
  const runtime = this.runtimes.get(id);
956
1164
  await this.serial(async () => {
1165
+ if (!runtime || this.runtimes.get(id) !== runtime || !this.records.has(id))
1166
+ return;
957
1167
  if (this.fault)
958
1168
  throw this.fault;
959
1169
  const record = this.records.get(id);
@@ -1087,6 +1297,8 @@ class ScheduleService {
1087
1297
  const pending = this.pending.get(id);
1088
1298
  if (!pending)
1089
1299
  return;
1300
+ if (this.purges.has(pending.scheduleId))
1301
+ return;
1090
1302
  const record = this.records.get(pending.scheduleId);
1091
1303
  if (!this.current(record) || record.state === 'cancelled' && !pending.afterCancellation) {
1092
1304
  this.pending.delete(id);
@@ -1103,7 +1315,8 @@ class ScheduleService {
1103
1315
  success: pending.success, ...(pending.output !== undefined && { output: pending.output }),
1104
1316
  ...(pending.error !== undefined && { error: pending.error }) };
1105
1317
  });
1106
- if (!delivery || this.closing || !this.current(delivery.schedule) || !this.pending.has(id))
1318
+ if (!delivery || this.closing || !this.current(delivery.schedule) || !this.pending.has(id)
1319
+ || this.purges.has(delivery.schedule.id))
1107
1320
  continue;
1108
1321
  const runtime = this.runtimes.get(delivery.schedule.id);
1109
1322
  if (runtime?.cancelling) {
@@ -1111,12 +1324,16 @@ class ScheduleService {
1111
1324
  runtime.heldDeliveries.add(id);
1112
1325
  continue;
1113
1326
  }
1327
+ this.delivering.add(delivery.schedule.id);
1114
1328
  try {
1115
1329
  await this.options.deliver(delivery);
1116
1330
  }
1117
1331
  catch {
1118
1332
  continue;
1119
1333
  } // Keep the persisted outbox; only explicit reconnect retries it.
1334
+ finally {
1335
+ this.delivering.delete(delivery.schedule.id);
1336
+ }
1120
1337
  await this.serial(async () => { this.pending.delete(id); await this.persist(); });
1121
1338
  }
1122
1339
  });
@@ -1124,6 +1341,8 @@ class ScheduleService {
1124
1341
  return run;
1125
1342
  }
1126
1343
  stop(id, runtime) {
1344
+ if (this.runtimes.get(id) !== runtime)
1345
+ return Promise.resolve();
1127
1346
  if (runtime.stopped)
1128
1347
  return Promise.resolve();
1129
1348
  if (runtime.stopPromise)
@@ -1134,8 +1353,12 @@ class ScheduleService {
1134
1353
  throw new Error('Recovery receipt is unresolved; native ownership retained.');
1135
1354
  }
1136
1355
  const handle = await runtime.ready;
1137
- if (handle && !runtime.stopped)
1356
+ if (handle && !runtime.stopped) {
1138
1357
  await handle.stop();
1358
+ // Process/job retirement is not itself proof that persisted timing was deleted.
1359
+ if (handle.nativeDefinitionAbsent === true)
1360
+ runtime.removalConfirmed = true;
1361
+ }
1139
1362
  // A shared session can delete future firings while an occurrence still
1140
1363
  // finishes. Keep ownership until its terminal stopped notification.
1141
1364
  if (!handle?.cancellationKeepsRunning || !runtime.running.size)
@@ -1154,10 +1377,11 @@ class ScheduleService {
1154
1377
  throw error;
1155
1378
  }
1156
1379
  })();
1157
- runtime.stopPromise = operation;
1380
+ const tracked = this.recordOperation(id, operation);
1381
+ runtime.stopPromise = tracked;
1158
1382
  void operation.finally(() => { if (!runtime.stopped)
1159
1383
  runtime.stopPromise = undefined; }).catch(() => { });
1160
- return runtime.recoveryAbort ? this.boundRecovery(operation, 'Native cleanup remains unresolved; ownership retained.') : operation;
1384
+ return runtime.recoveryAbort ? this.boundRecovery(tracked, 'Native cleanup remains unresolved; ownership retained.') : tracked;
1161
1385
  }
1162
1386
  async boundRecovery(operation, message) {
1163
1387
  let timer;
@@ -1171,6 +1395,12 @@ class ScheduleService {
1171
1395
  clearTimeout(timer);
1172
1396
  }
1173
1397
  }
1398
+ canAdmitOccurrence(id, runtime) {
1399
+ const record = this.records.get(id);
1400
+ return !!record && this.runtimes.get(id) === runtime && !this.closing && !this.fault
1401
+ && !runtime.stopped && !runtime.cancelling && !record.cancelRequested
1402
+ && LIVE.has(record.state) && this.current(record);
1403
+ }
1174
1404
  newRuntime() {
1175
1405
  let resolveReady;
1176
1406
  const ready = new Promise(resolve => { resolveReady = resolve; });
@@ -1190,6 +1420,16 @@ class ScheduleService {
1190
1420
  void task.finally(() => this.operations.delete(task)).catch(() => { });
1191
1421
  return task;
1192
1422
  }
1423
+ recordOperation(id, task) {
1424
+ this.recordOperations.set(id, (this.recordOperations.get(id) ?? 0) + 1);
1425
+ return task.finally(() => {
1426
+ const remaining = this.recordOperations.get(id) - 1;
1427
+ if (remaining)
1428
+ this.recordOperations.set(id, remaining);
1429
+ else
1430
+ this.recordOperations.delete(id);
1431
+ });
1432
+ }
1193
1433
  current(owner) {
1194
1434
  try {
1195
1435
  return this.options.isOwnerCurrent(ownerOf(owner)) === true;
@@ -1236,7 +1476,7 @@ class ScheduleService {
1236
1476
  try {
1237
1477
  // JSON can expand one control byte to six bytes (for example, "\\u0001").
1238
1478
  const maxBytes = (this.maxRecords + this.maxPending) * (160 * 1024)
1239
- + this.maxRecords * this.maxOccurrences * 515 + 4096;
1479
+ + this.maxRecords * this.maxOccurrences * 515 + MAX_PURGED_IDS * 2048 + 4096;
1240
1480
  const size = (await handle.stat()).size;
1241
1481
  if (size > maxBytes)
1242
1482
  throw new Error('Schedule catalog exceeds its size limit.');
@@ -1261,14 +1501,14 @@ class ScheduleService {
1261
1501
  }
1262
1502
  }
1263
1503
  load(data) {
1264
- const catalog = object(data, ['version', 'records', 'pending']);
1265
- if (![1, 2].includes(catalog.version) || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
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
1266
1506
  || !Array.isArray(catalog.pending) || catalog.pending.length > this.maxPending)
1267
1507
  throw new Error('Invalid schedule catalog envelope.');
1268
1508
  const records = new Map();
1269
1509
  const pending = new Map();
1270
1510
  for (const value of catalog.records) {
1271
- const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'recovery', 'completedOccurrences', 'skippedOccurrences']);
1511
+ const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation', 'execution', 'cancelRequested', 'creationRefused', 'recovery', 'completedOccurrences', 'skippedOccurrences']);
1272
1512
  (0, ScheduleCommand_1.validateScheduleId)(record.id);
1273
1513
  validateOwner(record);
1274
1514
  (0, ScheduleCommand_1.validateSchedulePrompt)(record.prompt);
@@ -1283,6 +1523,10 @@ class ScheduleService {
1283
1523
  throw new Error('Invalid schedule error.');
1284
1524
  if (record.cancelRequested !== undefined && record.cancelRequested !== true)
1285
1525
  throw new Error('Invalid cancellation intent.');
1526
+ if (record.creationRefused !== undefined && (catalog.version !== 3 || record.creationRefused !== true || record.nativeId !== undefined
1527
+ || !['failed', 'cancelled', 'interrupted'].includes(record.state)
1528
+ || record.completedOccurrences !== undefined))
1529
+ throw new Error('Invalid native admission refusal.');
1286
1530
  if (record.execution !== undefined) {
1287
1531
  const execution = object(record.execution, ['command', 'model', 'effort']);
1288
1532
  for (const value of Object.values(execution))
@@ -1290,8 +1534,8 @@ class ScheduleService {
1290
1534
  text(value, 4096);
1291
1535
  }
1292
1536
  if (record.recovery !== undefined) {
1293
- if (catalog.version !== 2)
1294
- throw new Error('Recovery requires catalog version 2.');
1537
+ if (catalog.version === 1)
1538
+ throw new Error('Recovery requires catalog version 2 or newer.');
1295
1539
  const recovery = object(record.recovery, ['version', 'provider', 'strategy', 'identity', 'status', 'orderlyOnly', 'futureOnly', 'handoff', 'nativeDefinitionAbsent', 'handoffPolicy']);
1296
1540
  this.validateCheckpoint(recovery);
1297
1541
  if (!['eligible', 'pending', 'blocked'].includes(recovery.status))
@@ -1333,8 +1577,24 @@ class ScheduleService {
1333
1577
  throw new Error('Invalid cancellation delivery flag.');
1334
1578
  pending.set(item.id, structuredClone(item));
1335
1579
  }
1580
+ const purged = new Map();
1581
+ if (catalog.version === 3) {
1582
+ if (!Array.isArray(catalog.purged) || catalog.purged.length > MAX_PURGED_IDS)
1583
+ throw new Error('Invalid purge fences.');
1584
+ for (const value of catalog.purged) {
1585
+ const fence = object(value, ['id', 'threadId', 'openId', 'generation']);
1586
+ (0, ScheduleCommand_1.validateScheduleId)(fence.id);
1587
+ validateOwner(fence);
1588
+ if (records.has(fence.id) || purged.has(fence.id))
1589
+ throw new Error('Conflicting purge fence.');
1590
+ purged.set(fence.id, ownerOf(fence));
1591
+ }
1592
+ }
1593
+ else if (catalog.purged !== undefined)
1594
+ throw new Error('Purge fences require catalog version 3.');
1336
1595
  this.records = records;
1337
1596
  this.pending = pending;
1597
+ this.purged = purged;
1338
1598
  }
1339
1599
  async persist() {
1340
1600
  if (!this.catalogGate)
@@ -1355,7 +1615,9 @@ class ScheduleService {
1355
1615
  }
1356
1616
  const handle = await fs.open(temporary, 'wx', 0o600);
1357
1617
  try {
1358
- await handle.writeFile(JSON.stringify({ version: 2, records: [...this.records.values()], pending: [...this.pending.values()] }), 'utf8');
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()],
1620
+ ...(upgraded ? { purged: [...this.purged].map(([id, owner]) => ({ id, ...owner })) } : {}) }), 'utf8');
1359
1621
  await handle.sync();
1360
1622
  }
1361
1623
  finally {