@fro.bot/systematic 3.22.4 → 3.22.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  extractCommandFrontmatter,
20
20
  findSkillsInDir,
21
21
  discoverSkills
22
- } from "./index-0sc6c1vd.js";
22
+ } from "./index-aaygsm67.js";
23
23
 
24
24
  // src/index.ts
25
25
  import { createHash as createHash4 } from "crypto";
@@ -10936,6 +10936,7 @@ var REASON_CODES = new Set([
10936
10936
  "rejected-operation",
10937
10937
  "resource-mismatch",
10938
10938
  "running-operation",
10939
+ "snapshot-blocked",
10939
10940
  "stale-receipt",
10940
10941
  "transition-finalized",
10941
10942
  "transition-terminal",
@@ -10972,9 +10973,26 @@ function isWorkflowGuardBlockedError(value) {
10972
10973
  function defaultTargetObserver(targetDirectory) {
10973
10974
  return createOpencodeOperationObserver({ targetDirectory });
10974
10975
  }
10976
+ var TIMED_OUT_READ = { status: "timeout" };
10975
10977
  function unconfirmedReadback(probe) {
10976
10978
  return { probe, reasonCode: "command-timeout" };
10977
10979
  }
10980
+ var SNAPSHOT_BLOCKING_REASONS = [
10981
+ "file-limit",
10982
+ "file-output-limit",
10983
+ "command-output-limit",
10984
+ "worktree-unstable"
10985
+ ];
10986
+ function isSnapshotBlockingReason(reasonCode) {
10987
+ return typeof reasonCode === "string" && SNAPSHOT_BLOCKING_REASONS.includes(reasonCode);
10988
+ }
10989
+ var INERT_SNAPSHOT_BLOCK = {
10990
+ set: () => false,
10991
+ current: () => {
10992
+ return;
10993
+ },
10994
+ clear: async () => ({ status: "not-blocked" })
10995
+ };
10978
10996
  function initializationCause(kind) {
10979
10997
  return { site: "initialize-session", kind, timedOut: false };
10980
10998
  }
@@ -11000,6 +11018,17 @@ function beforeCause(kind, reasonCode) {
11000
11018
  function afterCause(kind, reasonCode) {
11001
11019
  return hookCause("tool-after", kind, reasonCode);
11002
11020
  }
11021
+ function snapshotFailureCause(build) {
11022
+ return (reasonCode) => reasonCode === undefined ? build("local-snapshot-error") : build("local-snapshot-unavailable", reasonCode);
11023
+ }
11024
+ function seedCause(kind, reasonCode) {
11025
+ return {
11026
+ site: "seed-remote-scopes",
11027
+ kind,
11028
+ ...reasonCode !== undefined ? { reasonCode } : {},
11029
+ timedOut: reasonCode === "command-timeout"
11030
+ };
11031
+ }
11003
11032
  function afterFailure(kind, reasonCode) {
11004
11033
  return { status: "unavailable", cause: afterCause(kind, reasonCode) };
11005
11034
  }
@@ -11018,7 +11047,7 @@ async function readSnapshot(observer, expectedTargetIdentity) {
11018
11047
  return { status: "fatal" };
11019
11048
  }
11020
11049
  if (isProbeTimeout(result))
11021
- return { status: "timeout" };
11050
+ return TIMED_OUT_READ;
11022
11051
  if (result.status === "unavailable") {
11023
11052
  return { status: "fatal", reasonCode: result.reasonCode };
11024
11053
  }
@@ -11027,6 +11056,9 @@ async function readSnapshot(observer, expectedTargetIdentity) {
11027
11056
  }
11028
11057
  return { status: "ok", value: result.snapshot };
11029
11058
  }
11059
+ function probeFailureReason(failure) {
11060
+ return failure.status === "timeout" ? "command-timeout" : failure.reasonCode;
11061
+ }
11030
11062
  function isProbeTimeout(result) {
11031
11063
  if (result === undefined)
11032
11064
  return false;
@@ -11149,6 +11181,9 @@ function isLocalOperationTool(tool) {
11149
11181
  function unavailableOperationTarget() {
11150
11182
  return { status: "unavailable", reasonCode: "target-unavailable" };
11151
11183
  }
11184
+ function timedOutOperationTarget() {
11185
+ return { status: "unavailable", reasonCode: "command-timeout" };
11186
+ }
11152
11187
  function canonicalExistingPath(filePath, realPath) {
11153
11188
  try {
11154
11189
  return realPath(filePath);
@@ -11176,8 +11211,9 @@ function targetIsGitAdminStorage(targetPath, validation) {
11176
11211
  return pathWithinOrEqual(path6.join(validation.targetRoot, ".git"), targetPath) || pathWithinOrEqual(validation.gitDir, targetPath) || pathWithinOrEqual(validation.commonDir, targetPath);
11177
11212
  }
11178
11213
  function targetResultFromValidation(candidatePath, validation) {
11179
- if (validation.status === "error")
11180
- return unavailableOperationTarget();
11214
+ if (validation.status === "error") {
11215
+ return isProbeTimeout(validation) ? timedOutOperationTarget() : unavailableOperationTarget();
11216
+ }
11181
11217
  if (!pathWithinOrEqual(validation.targetRoot, candidatePath)) {
11182
11218
  return unavailableOperationTarget();
11183
11219
  }
@@ -11213,21 +11249,31 @@ function deriveFileTarget(rawPath, baseDirectory, parentTargetRoot, options, rea
11213
11249
  }
11214
11250
  function sharedTargetRoot(targets, extraRoots = []) {
11215
11251
  const roots = [...extraRoots];
11252
+ let definiteFailure = false;
11253
+ let timedOut = false;
11216
11254
  for (const target of targets) {
11217
- if (target.status === "unavailable")
11218
- return;
11219
- roots.push(target.targetRoot);
11255
+ if (target.status === "available")
11256
+ roots.push(target.targetRoot);
11257
+ else if (target.reasonCode === "command-timeout")
11258
+ timedOut = true;
11259
+ else
11260
+ definiteFailure = true;
11220
11261
  }
11221
11262
  const targetRoot = roots[0];
11222
- return targetRoot && roots.every((root) => root === targetRoot) ? targetRoot : undefined;
11263
+ const spans = targetRoot !== undefined && roots.some((r) => r !== targetRoot);
11264
+ if (definiteFailure || spans)
11265
+ return unavailableOperationTarget();
11266
+ if (timedOut)
11267
+ return timedOutOperationTarget();
11268
+ return targetRoot ? { status: "available", targetRoot } : unavailableOperationTarget();
11223
11269
  }
11224
11270
  function deriveDirectoryTarget(rawPath, baseDirectory, parentTargetRoot, options, realPath) {
11225
11271
  const resolvedPath = canonicalExistingPath(path6.resolve(baseDirectory, rawPath), realPath);
11226
11272
  if (!resolvedPath)
11227
- return { status: "unavailable" };
11273
+ return unavailableOperationTarget();
11228
11274
  const parentResult = path6.isAbsolute(rawPath) ? undefined : trustedParentTarget(parentTargetRoot, resolvedPath);
11229
11275
  if (parentResult?.status === "unavailable") {
11230
- return { status: "unavailable" };
11276
+ return unavailableOperationTarget();
11231
11277
  }
11232
11278
  if (parentResult) {
11233
11279
  return {
@@ -11236,10 +11282,13 @@ function deriveDirectoryTarget(rawPath, baseDirectory, parentTargetRoot, options
11236
11282
  };
11237
11283
  }
11238
11284
  const validated = validationForCandidate(resolvedPath, options);
11239
- return validated.status === "available" ? {
11240
- status: "available",
11241
- target: { targetRoot: validated.targetRoot, resolvedPath }
11242
- } : { status: "unavailable" };
11285
+ if (validated.status === "available") {
11286
+ return {
11287
+ status: "available",
11288
+ target: { targetRoot: validated.targetRoot, resolvedPath }
11289
+ };
11290
+ }
11291
+ return validated.reasonCode === "command-timeout" ? { status: "timeout", resolvedPath } : validated;
11243
11292
  }
11244
11293
  var PATCH_FILE_PREFIXES = [
11245
11294
  "*** Add File:",
@@ -11302,8 +11351,7 @@ function deriveFileOperationTarget(args2, sessionLocation, parentTargetRoot, opt
11302
11351
  if (!paths)
11303
11352
  return unavailableOperationTarget();
11304
11353
  const targets = paths.map((rawPath) => deriveFileTarget(rawPath, sessionLocation, parentTargetRoot, options, realPath));
11305
- const targetRoot = sharedTargetRoot(targets);
11306
- return targetRoot ? { status: "available", targetRoot } : unavailableOperationTarget();
11354
+ return sharedTargetRoot(targets);
11307
11355
  }
11308
11356
  function deriveApplyPatchTarget(args2, sessionLocation, parentTargetRoot, options, realPath) {
11309
11357
  if (args2.workdir !== undefined && (typeof args2.workdir !== "string" || args2.workdir.length === 0)) {
@@ -11320,11 +11368,13 @@ function deriveApplyPatchTarget(args2, sessionLocation, parentTargetRoot, option
11320
11368
  }
11321
11369
  } : deriveDirectoryTarget(args2.workdir, sessionLocation, parentTargetRoot, options, realPath);
11322
11370
  if (workdir.status === "unavailable")
11323
- return unavailableOperationTarget();
11324
- const targets = patchPaths.map((rawPath) => deriveFileTarget(rawPath, workdir.target.resolvedPath, parentTargetRoot, options, realPath, args2.workdir === undefined));
11371
+ return workdir;
11372
+ const resolvedWorkdir = workdir.status === "available" ? workdir.target.resolvedPath : workdir.resolvedPath;
11373
+ const targets = patchPaths.map((rawPath) => deriveFileTarget(rawPath, resolvedWorkdir, parentTargetRoot, options, realPath, args2.workdir === undefined));
11374
+ if (workdir.status === "timeout")
11375
+ targets.push(timedOutOperationTarget());
11325
11376
  const seedWorkdirRoot = args2.workdir !== undefined || targets.length === 0;
11326
- const targetRoot = sharedTargetRoot(targets, seedWorkdirRoot ? [workdir.target.targetRoot] : []);
11327
- return targetRoot ? { status: "available", targetRoot } : unavailableOperationTarget();
11377
+ return sharedTargetRoot(targets, seedWorkdirRoot && workdir.status === "available" ? [workdir.target.targetRoot] : []);
11328
11378
  }
11329
11379
  function deriveBashTarget(args2, sessionLocation, parentTargetRoot, options, realPath) {
11330
11380
  if (args2.workdir === undefined) {
@@ -11529,7 +11579,7 @@ function isSuccessfulAfter(output) {
11529
11579
  function isSuccessfulSkillAfter(output) {
11530
11580
  return parseHostOutput(output, { maxOutputLength: Number.POSITIVE_INFINITY }) !== undefined;
11531
11581
  }
11532
- function statusForTool(status, unavailableCause, seedDeferrals = [], unconfirmedReadbacks = []) {
11582
+ function statusForTool(status, unavailableCause, seedDeferrals = [], unconfirmedReadbacks = [], snapshotBlock) {
11533
11583
  return JSON.stringify({
11534
11584
  state: status.state,
11535
11585
  reasonCode: status.reasonCode,
@@ -11538,6 +11588,7 @@ function statusForTool(status, unavailableCause, seedDeferrals = [], unconfirmed
11538
11588
  missingOperations: status.missingOperations,
11539
11589
  ...unavailableCause && status.state === "unavailable" ? { firstUnavailableCause: unavailableCause } : {},
11540
11590
  ...seedDeferrals.length > 0 ? { seedDeferrals } : {},
11591
+ ...snapshotBlock ? { snapshotBlock } : {},
11541
11592
  ...unconfirmedReadbacks.length > 0 ? { unconfirmedReadbacks } : {}
11542
11593
  });
11543
11594
  }
@@ -11718,6 +11769,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11718
11769
  const pendingOperations = new Map;
11719
11770
  const sealedOperations = new Map;
11720
11771
  const skippedOperations = new Set;
11772
+ let localCallSequence = 0;
11773
+ const inFlightLocalCalls = new Map;
11721
11774
  const abandonedOperations = new Map;
11722
11775
  const rolledUpChildren = new Set;
11723
11776
  const questionAttestation = createQuestionAttestation();
@@ -11727,13 +11780,20 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11727
11780
  let firstUnavailableCause;
11728
11781
  let pendingUnavailableCause;
11729
11782
  let seedDeferralRecord;
11783
+ let snapshotBlockRecord;
11784
+ let snapshotBlockVersion = 0;
11730
11785
  let unitStartGeneration = 0;
11731
11786
  function startFreshUnit(input, policy) {
11787
+ const previousUnitId = requireGuard().status().unit?.unitId;
11732
11788
  const result = requireGuard().startUnit(input, policy);
11733
11789
  if (result.status === "started") {
11734
11790
  unitStartGeneration += 1;
11791
+ snapshotBlockVersion += 1;
11735
11792
  firstUnavailableCause = undefined;
11736
- seedDeferralRecord = undefined;
11793
+ if (result.unit.unitId !== previousUnitId) {
11794
+ seedDeferralRecord = undefined;
11795
+ snapshotBlockRecord = undefined;
11796
+ }
11737
11797
  }
11738
11798
  return result;
11739
11799
  }
@@ -11758,19 +11818,21 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11758
11818
  }
11759
11819
  function parentObserverRegistration() {
11760
11820
  if (!options.observer)
11761
- return;
11821
+ return { status: "fatal" };
11762
11822
  const targetRoot = canonicalExistingPath(options.targetDirectory ?? process.cwd(), fs8.realpathSync);
11763
11823
  if (!targetRoot)
11764
- return;
11824
+ return { status: "fatal" };
11765
11825
  let validation;
11766
11826
  try {
11767
11827
  validation = options.observer.validateRegisteredWorktree(targetRoot);
11768
11828
  } catch {
11769
- return;
11829
+ return { status: "fatal" };
11770
11830
  }
11831
+ if (isProbeTimeout(validation))
11832
+ return TIMED_OUT_READ;
11771
11833
  const registeredIdentity = registeredWorktreeIdentity(validation);
11772
11834
  if (validation.status !== "ok" || registeredIdentity === undefined || validation.targetRoot !== targetRoot) {
11773
- return;
11835
+ return { status: "fatal" };
11774
11836
  }
11775
11837
  const registration = {
11776
11838
  targetRoot,
@@ -11778,14 +11840,15 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11778
11840
  observer: options.observer
11779
11841
  };
11780
11842
  rememberOperationObserver(registration);
11781
- return registration;
11843
+ return { status: "ok", value: registration };
11782
11844
  }
11783
11845
  function operationObserverRegistration(targetIdentity) {
11784
11846
  const existing = operationObservers.get(targetIdentity);
11785
11847
  if (existing)
11786
- return existing;
11787
- if (options.observer?.targetDigest !== targetIdentity)
11788
- return;
11848
+ return { status: "ok", value: existing };
11849
+ if (options.observer?.targetDigest !== targetIdentity) {
11850
+ return { status: "fatal" };
11851
+ }
11789
11852
  return parentObserverRegistration();
11790
11853
  }
11791
11854
  function resolveEffectiveObserver() {
@@ -11804,9 +11867,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11804
11867
  };
11805
11868
  }
11806
11869
  const registration = operationObserverRegistration(pinnedTargetIdentity);
11807
- if (!registration)
11808
- return { status: "fatal" };
11809
- return resolvePinnedObserver(parentObserver, registration, pinnedTargetIdentity);
11870
+ if (registration.status !== "ok")
11871
+ return registration;
11872
+ return resolvePinnedObserver(parentObserver, registration.value, pinnedTargetIdentity);
11810
11873
  }
11811
11874
  function resolvePinnedObserver(parentObserver, registration, pinnedTargetIdentity) {
11812
11875
  let validation;
@@ -11816,7 +11879,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11816
11879
  return { status: "fatal" };
11817
11880
  }
11818
11881
  if (isProbeTimeout(validation))
11819
- return { status: "timeout" };
11882
+ return TIMED_OUT_READ;
11820
11883
  if (validation.status !== "ok") {
11821
11884
  return { status: "fatal", reasonCode: validation.reasonCode };
11822
11885
  }
@@ -12286,6 +12349,34 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12286
12349
  initializationPromise = next;
12287
12350
  await next;
12288
12351
  }
12352
+ function blockOrFailChildSnapshot(reasonCode, targetIdentity, rollupGeneration) {
12353
+ if (!isSnapshotBlockingReason(reasonCode)) {
12354
+ markUnavailable(snapshotFailureCause(afterCause)(reasonCode));
12355
+ return;
12356
+ }
12357
+ setSnapshotBlock(reasonCode, targetIdentity, {
12358
+ generation: rollupGeneration
12359
+ });
12360
+ }
12361
+ async function readChildSnapshot(observer, targetIdentity, rollupGeneration) {
12362
+ const capture = captureSnapshotBlock();
12363
+ const read = await readSnapshot(observer);
12364
+ if (read.status === "timeout")
12365
+ return { kind: "halt" };
12366
+ if (read.status !== "ok") {
12367
+ blockOrFailChildSnapshot(probeFailureReason(read), targetIdentity, rollupGeneration);
12368
+ return { kind: "halt" };
12369
+ }
12370
+ if (read.value.targetDigest !== targetIdentity) {
12371
+ markUnavailable(afterCause("operation-target-mismatch"));
12372
+ return { kind: "halt" };
12373
+ }
12374
+ return {
12375
+ kind: "snapshot",
12376
+ snapshot: read.value,
12377
+ ...capture ? { blockCapture: capture } : {}
12378
+ };
12379
+ }
12289
12380
  async function rollupForegroundTask(host, output) {
12290
12381
  if (!options.hostReadback || !isRecord7(output))
12291
12382
  return;
@@ -12298,6 +12389,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12298
12389
  if (rolledUpChildren.has(rollupKey))
12299
12390
  return;
12300
12391
  const parentBefore = requireGuard().currentOperationContext();
12392
+ const rollupGeneration = unitStartGeneration;
12301
12393
  const children = await options.hostReadback.listChildren(host.sessionID);
12302
12394
  if (!children.some((child) => child.sessionId === childSessionID && child.parentID === host.sessionID)) {
12303
12395
  markUnavailable(afterCause("call-lifecycle-mismatch"));
@@ -12345,6 +12437,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12345
12437
  return;
12346
12438
  const expectedWorkspace = childLedger.digestIdentity("workspace", parentBefore.workspaceIdentity);
12347
12439
  let batchTargetIdentity = currentStatus.unit.pinnedOperationTargetIdentity;
12440
+ let blockClear;
12348
12441
  const candidates = [];
12349
12442
  for (const childReceipt of recovered.receipts) {
12350
12443
  const operation = childReceipt.canonical.operation;
@@ -12364,11 +12457,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12364
12457
  return;
12365
12458
  }
12366
12459
  batchTargetIdentity = targetIdentity;
12367
- const registration = operationObserverRegistration(targetIdentity);
12368
- if (!registration || !options.observer) {
12460
+ const registered = operationObserverRegistration(targetIdentity);
12461
+ if (registered.status === "timeout")
12462
+ return;
12463
+ if (registered.status !== "ok" || !options.observer) {
12369
12464
  markUnavailable(afterCause("operation-input-invalid"));
12370
12465
  return;
12371
12466
  }
12467
+ const registration = registered.value;
12372
12468
  let validation;
12373
12469
  try {
12374
12470
  validation = options.observer.validateRegisteredWorktree(registration.targetRoot);
@@ -12376,38 +12472,35 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12376
12472
  markUnavailable(afterCause("operation-input-invalid"));
12377
12473
  return;
12378
12474
  }
12475
+ if (isProbeTimeout(validation))
12476
+ return;
12379
12477
  if (validation.status === "error" || validation.targetRoot !== registration.targetRoot || registeredWorktreeIdentity(validation) !== registration.registeredWorktreeIdentity || registration.observer.targetDigest !== targetIdentity) {
12380
12478
  markUnavailable(afterCause("operation-input-invalid", validation.status === "error" ? validation.reasonCode : undefined));
12381
12479
  return;
12382
12480
  }
12383
- let targetResult;
12384
- try {
12385
- targetResult = await registration.observer.snapshot();
12386
- } catch {
12387
- markUnavailable(afterCause("local-snapshot-error"));
12388
- return;
12389
- }
12390
- if (targetResult.status === "unavailable") {
12391
- markUnavailable(afterCause("local-snapshot-unavailable", targetResult.reasonCode));
12392
- return;
12393
- }
12394
- if (targetResult.snapshot.targetDigest !== targetIdentity) {
12395
- markUnavailable(afterCause("operation-target-mismatch"));
12481
+ const targetRead = await readChildSnapshot(registration.observer, targetIdentity, rollupGeneration);
12482
+ if (targetRead.kind === "halt")
12396
12483
  return;
12484
+ if (targetRead.blockCapture) {
12485
+ blockClear = {
12486
+ capture: targetRead.blockCapture,
12487
+ targetIdentity,
12488
+ snapshot: targetRead.snapshot
12489
+ };
12397
12490
  }
12398
12491
  const recoveredContext = recoveredOperationContexts.get(childReceipt.canonical.receiptId);
12399
12492
  if (recoveredContext && recoveredContext.targetIdentity !== targetIdentity || targetIdentity !== options.observer.targetDigest && !recoveredContext) {
12400
12493
  markUnavailable(afterCause("operation-target-mismatch"));
12401
12494
  return;
12402
12495
  }
12403
- const expectedRepository = childLedger.digestIdentity("repository", targetResult.snapshot.repositoryRevisionDigest);
12404
- const expectedWorktree = childLedger.digestIdentity("worktree", targetResult.snapshot.worktreeRevisionDigest);
12496
+ const expectedRepository = childLedger.digestIdentity("repository", targetRead.snapshot.repositoryRevisionDigest);
12497
+ const expectedWorktree = childLedger.digestIdentity("worktree", targetRead.snapshot.worktreeRevisionDigest);
12405
12498
  if (childReceipt.canonical.repositoryDigest !== expectedRepository || childReceipt.canonical.worktreeDigest !== expectedWorktree) {
12406
12499
  continue;
12407
12500
  }
12408
12501
  candidates.push({
12409
12502
  receipt: childReceipt,
12410
- snapshot: targetResult.snapshot,
12503
+ snapshot: targetRead.snapshot,
12411
12504
  before: recoveredContext?.before
12412
12505
  });
12413
12506
  }
@@ -12453,6 +12546,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12453
12546
  }
12454
12547
  if (minted)
12455
12548
  rolledUpChildren.add(rollupKey);
12549
+ if (blockClear) {
12550
+ commitSnapshotBlockClear(blockClear.capture, readbackTarget(blockClear.targetIdentity), blockClear.snapshot, snapshotFailureCause(afterCause));
12551
+ }
12456
12552
  }
12457
12553
  let runtimePolicy = trustedSkillPolicy("unknown", options.runtimeRequiredOperations ?? []);
12458
12554
  function markUnavailable(cause) {
@@ -12507,6 +12603,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12507
12603
  abandonedOperations.set(callDigest, { skipped: true });
12508
12604
  }
12509
12605
  skippedOperations.clear();
12606
+ inFlightLocalCalls.clear();
12510
12607
  }
12511
12608
  function readStatus() {
12512
12609
  return guard ? guard.status() : unavailableWorkflowStatus();
@@ -12577,24 +12674,45 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12577
12674
  return [];
12578
12675
  }
12579
12676
  const effective = lookup.value;
12677
+ const blockCapture = captureSnapshotBlock();
12678
+ const blockVersion = snapshotBlockVersion;
12679
+ const generation = unitStartGeneration;
12580
12680
  const read = await readSnapshot(effective.observer, effective.targetIdentity);
12581
12681
  if (read.status === "timeout") {
12582
12682
  return skippedWithRemoteTail(effective.pinned ? "pinned" : "local");
12583
12683
  }
12584
12684
  if (read.status === "fatal") {
12585
- markUnavailable(observerReadbackFailedCause(read.reasonCode));
12685
+ return blockOrFailRefresh(read.reasonCode, effective, generation);
12686
+ }
12687
+ return applyRefreshSnapshot(effective, read.value, blockCapture, blockVersion);
12688
+ }
12689
+ function blockOrFailRefresh(reasonCode, effective, generation) {
12690
+ if (!isSnapshotBlockingReason(reasonCode)) {
12691
+ markUnavailable(observerReadbackFailedCause(reasonCode));
12586
12692
  return [];
12587
12693
  }
12588
- return applyReadbackAndProbeRemote(effective, read.value);
12694
+ setSnapshotBlock(reasonCode, effective.targetIdentity, { generation });
12695
+ return [];
12589
12696
  }
12590
- async function applyReadbackAndProbeRemote(effective, snapshot) {
12591
- const observed = requireGuard().observeReadback({
12697
+ async function applyRefreshSnapshot(effective, snapshot, blockCapture, blockVersion) {
12698
+ const skipped = () => skippedWithRemoteTail(effective.pinned ? "pinned" : "local");
12699
+ if (snapshotBlockVersion !== blockVersion)
12700
+ return skipped();
12701
+ const cleared = blockCapture ? commitSnapshotBlockClear(blockCapture, effective, snapshot, observerReadbackFailedCause) : undefined;
12702
+ if (cleared?.status === "fatal")
12703
+ return [];
12704
+ if (cleared?.status === "stale")
12705
+ return skipped();
12706
+ return applyReadbackAndProbeRemote(effective, snapshot, cleared?.status === "cleared");
12707
+ }
12708
+ async function applyReadbackAndProbeRemote(effective, snapshot, localApplied = false) {
12709
+ const observed = localApplied ? undefined : requireGuard().observeReadback({
12592
12710
  workspaceIdentity: options.workspaceIdentity,
12593
12711
  repositoryIdentity: snapshot.repositoryRevisionDigest,
12594
12712
  worktreeIdentity: snapshot.worktreeRevisionDigest,
12595
12713
  ...effective.pinned ? { operationTargetIdentity: effective.targetIdentity } : {}
12596
12714
  });
12597
- if (observed.status === "rejected" && observed.reasonCode === "workspace-mismatch") {
12715
+ if (observed?.status === "rejected" && observed.reasonCode === "workspace-mismatch") {
12598
12716
  markUnavailable(observerReadbackFailedCause());
12599
12717
  return [];
12600
12718
  }
@@ -12756,7 +12874,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12756
12874
  output.title = title;
12757
12875
  output.output = JSON.stringify({
12758
12876
  status: result.status,
12759
- reasonCode: result.reasonCode
12877
+ reasonCode: result.reasonCode,
12878
+ ...result.blockReason ? { blockReason: result.blockReason } : {},
12879
+ ...result.blockTarget ? { blockTarget: result.blockTarget } : {}
12760
12880
  });
12761
12881
  output.metadata = {
12762
12882
  ...withoutStaleConditionalMetadata(existingMetadata),
@@ -12904,9 +13024,96 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12904
13024
  return { operation: classification.category };
12905
13025
  }
12906
13026
  }
13027
+ function isEffectiveTarget(observer) {
13028
+ return observer.targetDigest === currentEffectiveTargetIdentity();
13029
+ }
13030
+ async function takeBeforeSnapshot(observer, initiator) {
13031
+ const gated = await clearBlockForOtherTarget(observer, initiator);
13032
+ if (gated)
13033
+ return gated;
13034
+ const capture = captureSnapshotBlock();
13035
+ if (capture && !isEffectiveTarget(observer))
13036
+ return { kind: "skip" };
13037
+ const read = await readBeforeSnapshot(observer, initiator);
13038
+ if (read.kind !== "snapshot" || !capture)
13039
+ return read;
13040
+ return clearBlockFromBeforeSnapshot(capture, observer, read.snapshot);
13041
+ }
13042
+ async function readBeforeSnapshot(observer, initiator) {
13043
+ const read = await readSnapshot(observer);
13044
+ if (read.status === "timeout")
13045
+ return { kind: "skip" };
13046
+ if (read.status !== "ok") {
13047
+ return blockOrFailBeforeSnapshot(probeFailureReason(read), observer, initiator);
13048
+ }
13049
+ if (read.value.targetDigest !== observer.targetDigest) {
13050
+ markUnavailable(beforeCause("operation-target-mismatch"));
13051
+ return { kind: "stop" };
13052
+ }
13053
+ return { kind: "snapshot", snapshot: read.value };
13054
+ }
13055
+ function clearBlockFromBeforeSnapshot(capture, observer, snapshot) {
13056
+ const cleared = commitSnapshotBlockClear(capture, readbackTarget(observer.targetDigest), snapshot, snapshotFailureCause(beforeCause));
13057
+ if (cleared.status === "fatal")
13058
+ return { kind: "stop" };
13059
+ return cleared.status === "cleared" ? { kind: "snapshot", snapshot } : { kind: "skip" };
13060
+ }
13061
+ function blockOrFailBeforeSnapshot(reasonCode, observer, initiator) {
13062
+ if (!isSnapshotBlockingReason(reasonCode)) {
13063
+ markUnavailable(snapshotFailureCause(beforeCause)(reasonCode));
13064
+ return { kind: "stop" };
13065
+ }
13066
+ setSnapshotBlock(reasonCode, observer.targetDigest, { initiator });
13067
+ return { kind: "skip" };
13068
+ }
13069
+ async function clearBlockForOtherTarget(observer, initiator) {
13070
+ if (!captureSnapshotBlock() || isEffectiveTarget(observer))
13071
+ return;
13072
+ const lookup = resolveEffectiveObserver();
13073
+ if (lookup.status === "timeout")
13074
+ return { kind: "skip" };
13075
+ if (lookup.status !== "ok") {
13076
+ markUnavailable(beforeCause("operation-input-invalid", probeFailureReason(lookup)));
13077
+ return { kind: "stop" };
13078
+ }
13079
+ const result = await clearSnapshotBlock(lookup.value, snapshotFailureCause(beforeCause));
13080
+ if (result.status === "timeout")
13081
+ return { kind: "skip" };
13082
+ if (result.status === "fatal")
13083
+ return { kind: "stop" };
13084
+ if (result.status === "still-blocked") {
13085
+ setSnapshotBlock(result.reasonCode, lookup.value.targetIdentity, {
13086
+ initiator
13087
+ });
13088
+ return { kind: "skip" };
13089
+ }
13090
+ return result.status === "stale" ? { kind: "skip" } : undefined;
13091
+ }
13092
+ function beginLocalCall(callDigest) {
13093
+ localCallSequence += 1;
13094
+ const start2 = {
13095
+ sequenceAtStart: localCallSequence,
13096
+ otherInFlightAtStart: [...inFlightLocalCalls].some(([key, state]) => key !== callDigest && state !== "returned")
13097
+ };
13098
+ inFlightLocalCalls.set(callDigest, inFlightLocalCalls.has(callDigest) ? "ambiguous" : "running");
13099
+ return start2;
13100
+ }
13101
+ function endLocalCall(callDigest) {
13102
+ if (inFlightLocalCalls.get(callDigest) === "running") {
13103
+ inFlightLocalCalls.set(callDigest, "returned");
13104
+ }
13105
+ }
13106
+ function beginUnparsedLocalCall() {
13107
+ localCallSequence += 1;
13108
+ inFlightLocalCalls.set(`unparsed:${localCallSequence}`, "ambiguous");
13109
+ }
13110
+ function overlappedAnotherLocalCall(pending) {
13111
+ return pending.localCall.otherInFlightAtStart || localCallSequence !== pending.localCall.sequenceAtStart;
13112
+ }
12907
13113
  async function prepareOperation(host, args2) {
12908
13114
  if (!options.observer || !isLocalOperationTool(host.tool))
12909
13115
  return;
13116
+ const localCall = beginLocalCall(digestCall(ledger, host.callID));
12910
13117
  if (!operationObservationApplies()) {
12911
13118
  skippedOperations.add(digestCall(ledger, host.callID));
12912
13119
  return;
@@ -12928,6 +13135,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12928
13135
  validateRegisteredWorktree: options.observer.validateRegisteredWorktree
12929
13136
  });
12930
13137
  if (target.status === "unavailable") {
13138
+ if (target.reasonCode === "command-timeout") {
13139
+ skippedOperations.add(callDigest);
13140
+ return;
13141
+ }
12931
13142
  markUnavailable(beforeCause("operation-input-invalid", target.reasonCode));
12932
13143
  return;
12933
13144
  }
@@ -12938,6 +13149,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12938
13149
  markUnavailable(beforeCause("operation-input-invalid"));
12939
13150
  return;
12940
13151
  }
13152
+ if (isProbeTimeout(registeredTarget)) {
13153
+ skippedOperations.add(callDigest);
13154
+ return;
13155
+ }
12941
13156
  const registeredIdentity = registeredWorktreeIdentity(registeredTarget);
12942
13157
  if (registeredTarget.status !== "ok" || registeredIdentity === undefined || registeredTarget.targetRoot !== target.targetRoot) {
12943
13158
  markUnavailable(beforeCause("operation-input-invalid", registeredTarget.status === "error" ? registeredTarget.reasonCode : undefined));
@@ -12949,21 +13164,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12949
13164
  return;
12950
13165
  }
12951
13166
  const operationObserver = target.targetRoot === canonicalParentTargetRoot ? options.observer : [...operationObservers.values()].find((registration) => registration.targetRoot === target.targetRoot)?.observer ?? (options.createTargetObserver ?? defaultTargetObserver)(target.targetRoot);
12952
- let result;
12953
- try {
12954
- result = await operationObserver.snapshot();
12955
- } catch {
12956
- markUnavailable(beforeCause("local-snapshot-error"));
12957
- return;
12958
- }
12959
- if (result.status === "unavailable") {
12960
- markUnavailable(beforeCause("local-snapshot-unavailable", result.reasonCode));
13167
+ const taken = await takeBeforeSnapshot(operationObserver, initiator);
13168
+ if (taken.kind === "skip") {
13169
+ skippedOperations.add(callDigest);
12961
13170
  return;
12962
13171
  }
12963
- if (result.snapshot.targetDigest !== operationObserver.targetDigest) {
12964
- markUnavailable(beforeCause("operation-target-mismatch"));
13172
+ if (taken.kind === "stop")
12965
13173
  return;
12966
- }
12967
13174
  rememberOperationObserver({
12968
13175
  targetRoot: target.targetRoot,
12969
13176
  registeredWorktreeIdentity: registeredIdentity,
@@ -12981,7 +13188,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12981
13188
  targetIdentity: operationObserver.targetDigest,
12982
13189
  registeredWorktreeIdentity: registeredIdentity,
12983
13190
  observer: operationObserver,
12984
- before: result.snapshot,
13191
+ before: taken.snapshot,
13192
+ localCall,
12985
13193
  ...initiator ? { initiator } : {},
12986
13194
  ...remote ? { remoteOperation: remote.operation, remoteBefore: remote.before } : {}
12987
13195
  });
@@ -13097,31 +13305,52 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13097
13305
  timedOut: false
13098
13306
  };
13099
13307
  }
13100
- let local;
13101
- try {
13102
- local = await options.observer.snapshot();
13103
- } catch {
13104
- return {
13105
- site: "seed-remote-scopes",
13106
- kind: "local-snapshot-error",
13107
- timedOut: false
13108
- };
13308
+ const lookup = resolveEffectiveObserver();
13309
+ if (lookup.status !== "ok")
13310
+ return seedLookupCause(lookup);
13311
+ const generation = unitStartGeneration;
13312
+ const local = await readSeedSnapshot(lookup.value.observer);
13313
+ if (local.kind === "fatal")
13314
+ return local.cause;
13315
+ if (local.kind === "blocked") {
13316
+ blockSeededScopes(remoteOperations, local.reasonCode, lookup.value.targetIdentity, generation);
13317
+ return;
13109
13318
  }
13110
- if (local.status === "unavailable") {
13111
- return {
13112
- site: "seed-remote-scopes",
13113
- kind: "local-snapshot-unavailable",
13114
- reasonCode: local.reasonCode,
13115
- timedOut: local.reasonCode === "command-timeout"
13116
- };
13319
+ return seedEachRemoteScope(remoteOperations, remoteSnapshot, local.snapshot, generation);
13320
+ }
13321
+ function seedLookupCause(failure) {
13322
+ return snapshotFailureCause(seedCause)(probeFailureReason(failure));
13323
+ }
13324
+ async function readSeedSnapshot(observer) {
13325
+ const read = await readSnapshot(observer);
13326
+ if (read.status === "ok")
13327
+ return { kind: "snapshot", snapshot: read.value };
13328
+ const reasonCode = probeFailureReason(read);
13329
+ if (isSnapshotBlockingReason(reasonCode)) {
13330
+ return { kind: "blocked", reasonCode };
13331
+ }
13332
+ return {
13333
+ kind: "fatal",
13334
+ cause: snapshotFailureCause(seedCause)(reasonCode)
13335
+ };
13336
+ }
13337
+ function blockSeededScopes(operations, reasonCode, targetIdentity, generation) {
13338
+ if (generation !== unitStartGeneration)
13339
+ return;
13340
+ for (const operation of operations) {
13341
+ clearSeedDeferral(operation);
13342
+ recordSeedDeferral(operation, "snapshot-blocked");
13117
13343
  }
13118
- return seedEachRemoteScope(remoteOperations, remoteSnapshot, local.snapshot);
13344
+ setSnapshotBlock(reasonCode, targetIdentity, { generation });
13119
13345
  }
13120
- async function seedEachRemoteScope(operations, reader, local) {
13346
+ async function seedEachRemoteScope(operations, reader, local, generation) {
13121
13347
  for (const operation of operations) {
13122
- const outcome = await seedRemoteScope(reader, operation, local);
13348
+ const outcome = await seedRemoteScope(reader, operation, local, generation);
13349
+ if (outcome.kind === "superseded")
13350
+ return;
13123
13351
  if (outcome.kind === "fatal")
13124
13352
  return outcome.cause;
13353
+ clearSeedDeferral(operation);
13125
13354
  if (outcome.kind === "deferred") {
13126
13355
  recordSeedDeferral(operation, outcome.reasonCode);
13127
13356
  }
@@ -13212,6 +13441,118 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13212
13441
  ...operation === "pr-creation" ? { propagate: false } : {}
13213
13442
  };
13214
13443
  }
13444
+ function currentEffectiveTargetIdentity() {
13445
+ return requireGuard().status().unit?.pinnedOperationTargetIdentity ?? options.workspaceIdentity;
13446
+ }
13447
+ function readbackTarget(targetIdentity) {
13448
+ return {
13449
+ targetIdentity,
13450
+ pinned: targetIdentity !== options.workspaceIdentity
13451
+ };
13452
+ }
13453
+ function writeSnapshotBlock(record2) {
13454
+ snapshotBlockRecord = record2;
13455
+ snapshotBlockVersion += 1;
13456
+ }
13457
+ function currentSnapshotBlock() {
13458
+ const record2 = snapshotBlockRecord;
13459
+ if (!record2)
13460
+ return;
13461
+ const status = requireGuard().status();
13462
+ if (record2.unitId !== status.unit?.unitId)
13463
+ return;
13464
+ if (record2.targetIdentity !== currentEffectiveTargetIdentity()) {
13465
+ writeSnapshotBlock(undefined);
13466
+ return;
13467
+ }
13468
+ return record2;
13469
+ }
13470
+ function blockSetIsCurrent(captured) {
13471
+ if ("generation" in captured) {
13472
+ return captured.generation === unitStartGeneration;
13473
+ }
13474
+ return captured.initiator !== undefined && isCurrentInitiator(captured.initiator);
13475
+ }
13476
+ function setSnapshotBlock(reasonCode, targetIdentity, captured) {
13477
+ const unitId = requireGuard().status().unit?.unitId;
13478
+ if (!unitId || !blockSetIsCurrent(captured) || targetIdentity !== currentEffectiveTargetIdentity()) {
13479
+ return false;
13480
+ }
13481
+ writeSnapshotBlock({
13482
+ unitId,
13483
+ unitGeneration: unitStartGeneration,
13484
+ targetIdentity,
13485
+ reasonCode
13486
+ });
13487
+ return true;
13488
+ }
13489
+ function captureSnapshotBlock() {
13490
+ const record2 = currentSnapshotBlock();
13491
+ return record2 ? { record: record2, generation: unitStartGeneration } : undefined;
13492
+ }
13493
+ function snapshotBlockStillCurrent(capture, snapshotTargetIdentity) {
13494
+ return snapshotBlockRecord === capture.record && unitStartGeneration === capture.generation && capture.record.targetIdentity === snapshotTargetIdentity && currentEffectiveTargetIdentity() === snapshotTargetIdentity;
13495
+ }
13496
+ async function clearSnapshotBlock(effective, failureCause) {
13497
+ const capture = captureSnapshotBlock();
13498
+ if (!capture)
13499
+ return { status: "not-blocked" };
13500
+ const read = await readSnapshot(effective.observer, effective.targetIdentity);
13501
+ if (read.status === "timeout")
13502
+ return TIMED_OUT_READ;
13503
+ if (read.status === "fatal") {
13504
+ return settleFailedBlockSnapshot(read.reasonCode, capture, effective.targetIdentity, failureCause);
13505
+ }
13506
+ return commitSnapshotBlockClear(capture, effective, read.value, failureCause);
13507
+ }
13508
+ function settleFailedBlockSnapshot(reasonCode, capture, targetIdentity, failureCause) {
13509
+ if (isSnapshotBlockingReason(reasonCode)) {
13510
+ return snapshotBlockStillCurrent(capture, targetIdentity) ? { status: "still-blocked", reasonCode } : { status: "stale" };
13511
+ }
13512
+ markUnavailable(failureCause(reasonCode));
13513
+ return { status: "fatal" };
13514
+ }
13515
+ function commitSnapshotBlockClear(capture, target, snapshot, failureCause) {
13516
+ if (!snapshotBlockStillCurrent(capture, target.targetIdentity)) {
13517
+ return { status: "stale" };
13518
+ }
13519
+ const observed = requireGuard().observeReadback({
13520
+ workspaceIdentity: options.workspaceIdentity,
13521
+ repositoryIdentity: snapshot.repositoryRevisionDigest,
13522
+ worktreeIdentity: snapshot.worktreeRevisionDigest,
13523
+ ...target.pinned ? { operationTargetIdentity: target.targetIdentity } : {}
13524
+ });
13525
+ if (observed.status === "rejected" && observed.reasonCode === "workspace-mismatch") {
13526
+ markUnavailable(failureCause());
13527
+ return { status: "fatal" };
13528
+ }
13529
+ writeSnapshotBlock(undefined);
13530
+ return { status: "cleared" };
13531
+ }
13532
+ const snapshotBlockControls = {
13533
+ set: (reasonCode) => {
13534
+ ensureSynchronousRuntime();
13535
+ return setSnapshotBlock(reasonCode, currentEffectiveTargetIdentity(), {
13536
+ generation: unitStartGeneration
13537
+ });
13538
+ },
13539
+ current: () => {
13540
+ ensureSynchronousRuntime();
13541
+ const record2 = currentSnapshotBlock();
13542
+ return record2 ? { reasonCode: record2.reasonCode } : undefined;
13543
+ },
13544
+ clear: async () => {
13545
+ ensureSynchronousRuntime();
13546
+ const lookup = resolveEffectiveObserver();
13547
+ if (lookup.status === "timeout")
13548
+ return TIMED_OUT_READ;
13549
+ if (lookup.status === "fatal") {
13550
+ markUnavailable(observerReadbackFailedCause(lookup.reasonCode));
13551
+ return { status: "fatal" };
13552
+ }
13553
+ return clearSnapshotBlock(lookup.value, observerReadbackFailedCause);
13554
+ }
13555
+ };
13215
13556
  function currentSeedDeferrals() {
13216
13557
  return seedDeferralEntries().map(({ operation, reasonCode }) => ({
13217
13558
  operation,
@@ -13221,8 +13562,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13221
13562
  function fatalSeed(cause) {
13222
13563
  return { kind: "fatal", cause };
13223
13564
  }
13224
- async function seedRemoteScope(reader, operation, local) {
13225
- const result = await readRemoteScope(reader, operation, "before");
13565
+ function classifyRemoteSeedRead(operation, result) {
13226
13566
  if (!result) {
13227
13567
  return fatalSeed({
13228
13568
  site: "seed-remote-scope",
@@ -13232,24 +13572,30 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13232
13572
  });
13233
13573
  }
13234
13574
  if (result.status === "missing-resource") {
13235
- if (operation === "push") {
13236
- return { kind: "deferred", reasonCode: "missing-resource" };
13237
- }
13238
- return { kind: "tolerated" };
13575
+ return operation === "push" ? { kind: "deferred", reasonCode: "missing-resource" } : { kind: "tolerated" };
13239
13576
  }
13240
- if (result.status !== "available") {
13241
- if (result.reasonCode === "command-timeout") {
13242
- return { kind: "deferred", reasonCode: "command-timeout" };
13243
- }
13244
- return fatalSeed({
13245
- site: "seed-remote-scope",
13246
- kind: "remote-scope-unavailable",
13247
- operation,
13248
- reasonCode: result.reasonCode,
13249
- timedOut: false
13250
- });
13577
+ if (result.status === "available") {
13578
+ return { kind: "read", snapshot: result.snapshot };
13251
13579
  }
13252
- const observed = requireGuard().observeReadback(remoteReadbackInput(operation, local, options.workspaceIdentity, result.snapshot, operation !== "pr-creation"));
13580
+ if (result.reasonCode === "command-timeout") {
13581
+ return { kind: "deferred", reasonCode: "command-timeout" };
13582
+ }
13583
+ return fatalSeed({
13584
+ site: "seed-remote-scope",
13585
+ kind: "remote-scope-unavailable",
13586
+ operation,
13587
+ reasonCode: result.reasonCode,
13588
+ timedOut: false
13589
+ });
13590
+ }
13591
+ async function seedRemoteScope(reader, operation, local, generation) {
13592
+ const result = await readRemoteScope(reader, operation, "before");
13593
+ if (generation !== unitStartGeneration)
13594
+ return { kind: "superseded" };
13595
+ const read = classifyRemoteSeedRead(operation, result);
13596
+ if (read.kind !== "read")
13597
+ return read;
13598
+ const observed = requireGuard().observeReadback(remoteReadbackInput(operation, local, options.workspaceIdentity, read.snapshot, operation !== "pr-creation"));
13253
13599
  if (observed.status === "rejected") {
13254
13600
  return fatalSeed({
13255
13601
  site: "seed-remote-scope",
@@ -13404,6 +13750,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13404
13750
  return;
13405
13751
  }
13406
13752
  const reasonCode = "reasonCode" in result ? result.reasonCode : "guard-unavailable";
13753
+ if (reasonCode === "stale-receipt") {
13754
+ finishStaleFinalize(callDigest, pending, output);
13755
+ return;
13756
+ }
13407
13757
  markUnavailable(afterCause("transition-finalize-rejected", reasonCode));
13408
13758
  const terminal = {
13409
13759
  target: pending.target,
@@ -13414,6 +13764,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13414
13764
  terminalCompletes.set(callDigest, terminal);
13415
13765
  writeTerminalCompletionResult(output, terminal, pending.target);
13416
13766
  }
13767
+ function finishStaleFinalize(callDigest, pending, output) {
13768
+ rejectCompletion(callDigest, pending, output, {
13769
+ target: pending.target,
13770
+ status: "rejected",
13771
+ reasonCode: "stale-receipt",
13772
+ title: "Workflow receipt stale"
13773
+ }, { abandon: false });
13774
+ }
13417
13775
  function writeTerminalReplay(output, terminal, target) {
13418
13776
  if (terminal.metadataOnly) {
13419
13777
  writeAbandonedCompletionMetadata(output, target, terminal.reasonCode);
@@ -13461,13 +13819,18 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13461
13819
  if (remember)
13462
13820
  abandonedCompletes.set(callDigest, pending.target);
13463
13821
  }
13822
+ function blockedOrFailure(failure, targetIdentity) {
13823
+ return failure.status === "fatal" && isSnapshotBlockingReason(failure.reasonCode) ? { status: "blocked", reasonCode: failure.reasonCode, targetIdentity } : failure;
13824
+ }
13464
13825
  async function completionReadbacks() {
13465
13826
  const observer = options.observer;
13466
13827
  if (!observer)
13467
13828
  return { status: "none" };
13829
+ const blockCapture = captureSnapshotBlock();
13468
13830
  const parent = await readSnapshot(observer, options.workspaceIdentity);
13469
- if (parent.status !== "ok")
13470
- return parent;
13831
+ if (parent.status !== "ok") {
13832
+ return blockedOrFailure(parent, options.workspaceIdentity);
13833
+ }
13471
13834
  const lookup = resolveEffectiveObserver();
13472
13835
  if (lookup.status !== "ok")
13473
13836
  return lookup;
@@ -13475,18 +13838,27 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13475
13838
  let initialEffective = parent.value;
13476
13839
  if (effective.pinned) {
13477
13840
  const pinned = await readSnapshot(effective.observer, effective.targetIdentity);
13478
- if (pinned.status !== "ok")
13479
- return pinned;
13841
+ if (pinned.status !== "ok") {
13842
+ return blockedOrFailure(pinned, effective.targetIdentity);
13843
+ }
13480
13844
  initialEffective = pinned.value;
13481
13845
  }
13482
13846
  const remote = await completionRemoteReadbacks(effective.observer);
13483
13847
  if (remote.status !== "ready")
13484
13848
  return remote;
13485
13849
  const finalParent = await readSnapshot(observer);
13486
- if (finalParent.status !== "ok")
13487
- return finalParent;
13488
- if (completionParentDrifted(parent.value, finalParent.value)) {
13850
+ if (finalParent.status !== "ok") {
13851
+ return blockedOrFailure(finalParent, options.workspaceIdentity);
13852
+ }
13853
+ const drift = completionParentDrift(parent.value, finalParent.value);
13854
+ if (drift === "target")
13489
13855
  return { status: "fatal" };
13856
+ if (drift === "revision") {
13857
+ return {
13858
+ status: "blocked",
13859
+ reasonCode: "worktree-unstable",
13860
+ targetIdentity: options.workspaceIdentity
13861
+ };
13490
13862
  }
13491
13863
  const final = effective.pinned ? await revalidatePinnedCompletion(effective, initialEffective) : { status: "ready", effective, snapshot: finalParent.value };
13492
13864
  if (final.status !== "ready")
@@ -13501,11 +13873,20 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13501
13873
  operationTargetIdentity: final.effective.targetIdentity
13502
13874
  },
13503
13875
  ...remote.readbacks.map(({ operation, snapshot }) => remoteReadbackInput(operation, final.snapshot, options.workspaceIdentity, snapshot))
13504
- ]
13876
+ ],
13877
+ ...blockCapture ? {
13878
+ blockClear: {
13879
+ capture: blockCapture,
13880
+ target: final.effective,
13881
+ snapshot: final.snapshot
13882
+ }
13883
+ } : {}
13505
13884
  };
13506
13885
  }
13507
- function completionParentDrifted(initial, final) {
13508
- return final.targetDigest !== initial.targetDigest || final.repositoryRevisionDigest !== initial.repositoryRevisionDigest || final.worktreeRevisionDigest !== initial.worktreeRevisionDigest;
13886
+ function completionParentDrift(initial, final) {
13887
+ if (final.targetDigest !== initial.targetDigest)
13888
+ return "target";
13889
+ return final.repositoryRevisionDigest !== initial.repositoryRevisionDigest || final.worktreeRevisionDigest !== initial.worktreeRevisionDigest ? "revision" : "none";
13509
13890
  }
13510
13891
  async function revalidatePinnedCompletion(effective, initial) {
13511
13892
  const lookup = resolveEffectiveObserver();
@@ -13516,10 +13897,15 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13516
13897
  return { status: "fatal" };
13517
13898
  }
13518
13899
  const pinned = await readSnapshot(revalidated.observer, revalidated.targetIdentity);
13519
- if (pinned.status !== "ok")
13520
- return pinned;
13900
+ if (pinned.status !== "ok") {
13901
+ return blockedOrFailure(pinned, revalidated.targetIdentity);
13902
+ }
13521
13903
  if (pinned.value.repositoryRevisionDigest !== initial.repositoryRevisionDigest || pinned.value.worktreeRevisionDigest !== initial.worktreeRevisionDigest) {
13522
- return { status: "fatal" };
13904
+ return {
13905
+ status: "blocked",
13906
+ reasonCode: "worktree-unstable",
13907
+ targetIdentity: revalidated.targetIdentity
13908
+ };
13523
13909
  }
13524
13910
  return {
13525
13911
  status: "ready",
@@ -13538,7 +13924,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13538
13924
  for (const operation of remoteOperations) {
13539
13925
  const result = await readRemoteScope(remoteSnapshot, operation);
13540
13926
  if (isProbeTimeout(result))
13541
- return { status: "timeout" };
13927
+ return TIMED_OUT_READ;
13542
13928
  if (result?.status !== "available") {
13543
13929
  return { status: "fatal", reasonCode: remoteFailureReason(result) };
13544
13930
  }
@@ -13560,6 +13946,12 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13560
13946
  markUnavailable(afterCause("call-lifecycle-mismatch"));
13561
13947
  writeAbandonedCompletionResult(output, finalTarget, "guard-unavailable");
13562
13948
  }
13949
+ function rejectCompletion(callDigest, pending, output, terminal, { abandon }) {
13950
+ if (abandon)
13951
+ abandonComplete(callDigest, pending, true);
13952
+ terminalCompletes.set(callDigest, terminal);
13953
+ writeTerminalCompletionResult(output, terminal, pending.target, terminal.title);
13954
+ }
13563
13955
  function finishUnavailableReadback(callDigest, pending, output, reasonCode) {
13564
13956
  abandonComplete(callDigest, pending, true);
13565
13957
  terminalCompletes.set(callDigest, {
@@ -13578,16 +13970,38 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13578
13970
  }
13579
13971
  }
13580
13972
  function finishRetryableReadback(callDigest, pending, output) {
13581
- abandonComplete(callDigest, pending, true);
13582
- const terminal = {
13973
+ rejectCompletion(callDigest, pending, output, {
13583
13974
  target: pending.target,
13584
13975
  status: "rejected",
13585
13976
  reasonCode: "readback-timeout",
13586
13977
  title: "Workflow readback timed out"
13587
- };
13588
- terminalCompletes.set(callDigest, terminal);
13589
- writeTerminalCompletionResult(output, terminal, pending.target, terminal.title);
13978
+ }, { abandon: true });
13979
+ }
13980
+ function finishBlockedComplete(callDigest, pending, output, reasonCode, blockTarget) {
13981
+ if (requireGuard().status().state === "unavailable") {
13982
+ finishUnavailableReadback(callDigest, pending, output, reasonCode);
13983
+ return;
13984
+ }
13985
+ rejectCompletion(callDigest, pending, output, {
13986
+ target: pending.target,
13987
+ status: "rejected",
13988
+ reasonCode: "snapshot-blocked",
13989
+ blockReason: reasonCode,
13990
+ ...blockTarget ? { blockTarget } : {},
13991
+ title: "Workflow snapshot blocked"
13992
+ }, { abandon: true });
13993
+ }
13994
+ function commitCompletionBlockClear(readbacks) {
13995
+ if (readbacks.status !== "ready" || !readbacks.blockClear) {
13996
+ return { status: "none" };
13997
+ }
13998
+ const { capture, target, snapshot } = readbacks.blockClear;
13999
+ return commitSnapshotBlockClear(capture, target, snapshot, completionFailureCause);
14000
+ }
14001
+ function currentBlockReason() {
14002
+ return currentSnapshotBlock()?.reasonCode;
13590
14003
  }
14004
+ const completionFailureCause = (reasonCode) => observerReadbackFailedCause(reasonCode, "complete-readback");
13591
14005
  async function finishComplete(host, output) {
13592
14006
  const callDigest = digestCall(ledger, host.callID);
13593
14007
  const pending = pendingCompletes.get(callDigest);
@@ -13602,7 +14016,23 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13602
14016
  finishUnreplayableComplete(finalTarget, output);
13603
14017
  return;
13604
14018
  }
14019
+ const generation = unitStartGeneration;
13605
14020
  const readbacks = await completionReadbacks();
14021
+ settleCompletionReadbacks(callDigest, pending, output, readbacks, generation);
14022
+ }
14023
+ function blockForCompletion(blocked, generation) {
14024
+ if (requireGuard().status().state !== "unavailable") {
14025
+ setSnapshotBlock(blocked.reasonCode, blocked.targetIdentity, {
14026
+ generation
14027
+ });
14028
+ }
14029
+ }
14030
+ function settleCompletionReadbacks(callDigest, pending, output, readbacks, generation) {
14031
+ if (readbacks.status === "blocked") {
14032
+ blockForCompletion(readbacks, generation);
14033
+ finishBlockedComplete(callDigest, pending, output, readbacks.reasonCode, readbacks.targetIdentity === currentEffectiveTargetIdentity() ? undefined : "parent-checkout");
14034
+ return;
14035
+ }
13606
14036
  if (readbacks.status === "fatal") {
13607
14037
  finishUnavailableReadback(callDigest, pending, output, readbacks.reasonCode);
13608
14038
  return;
@@ -13611,6 +14041,15 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13611
14041
  finishReadbackTimeout(callDigest, pending, output);
13612
14042
  return;
13613
14043
  }
14044
+ if (commitCompletionBlockClear(readbacks).status === "fatal") {
14045
+ finishUnavailableReadback(callDigest, pending, output);
14046
+ return;
14047
+ }
14048
+ const block = currentBlockReason();
14049
+ if (block) {
14050
+ finishBlockedComplete(callDigest, pending, output, block);
14051
+ return;
14052
+ }
13614
14053
  finalizeComplete(callDigest, pending, output, readbacks.status === "ready" ? readbacks.readbacks : undefined);
13615
14054
  }
13616
14055
  function sealOperation(callDigest, operation, abandoned = false) {
@@ -13652,6 +14091,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13652
14091
  } catch {
13653
14092
  return afterFailure("operation-input-invalid");
13654
14093
  }
14094
+ if (isProbeTimeout(validation))
14095
+ return TIMED_OUT_READ;
13655
14096
  if (validation.status === "error" || validation.targetRoot !== pending.targetRoot || registeredWorktreeIdentity(validation) !== pending.registeredWorktreeIdentity) {
13656
14097
  return afterFailure("operation-input-invalid", validation.status === "error" ? validation.reasonCode : undefined);
13657
14098
  }
@@ -13663,16 +14104,34 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13663
14104
  const targetFailure = afterTargetFailure(options.observer, pending);
13664
14105
  if (targetFailure)
13665
14106
  return targetFailure;
13666
- let result;
13667
- try {
13668
- result = await pending.observer.snapshot();
13669
- } catch {
13670
- return afterFailure("local-snapshot-error");
14107
+ const blockCapture = captureSnapshotBlock();
14108
+ const read = await readSnapshot(pending.observer);
14109
+ if (read.status === "ok") {
14110
+ return settleCleanAfterSnapshot(blockCapture, pending, read.value);
13671
14111
  }
13672
- if (result.status === "unavailable") {
13673
- return afterFailure("local-snapshot-unavailable", result.reasonCode);
14112
+ if (read.status === "timeout")
14113
+ return TIMED_OUT_READ;
14114
+ const reasonCode = probeFailureReason(read);
14115
+ if (isSnapshotBlockingReason(reasonCode)) {
14116
+ return { status: "blocked", reasonCode };
14117
+ }
14118
+ return reasonCode === undefined ? afterFailure("local-snapshot-error") : afterFailure("local-snapshot-unavailable", reasonCode);
14119
+ }
14120
+ function settleCleanAfterSnapshot(blockCapture, pending, snapshot) {
14121
+ if (snapshot.targetDigest !== pending.targetIdentity) {
14122
+ return afterFailure("operation-target-mismatch");
13674
14123
  }
13675
- return result.snapshot.targetDigest === pending.targetIdentity ? { status: "available", snapshot: result.snapshot } : afterFailure("operation-target-mismatch");
14124
+ const failure = blockCapture ? clearBlockAfterOperation(blockCapture, pending, snapshot) : undefined;
14125
+ return failure ?? { status: "available", snapshot };
14126
+ }
14127
+ function clearBlockAfterOperation(capture, pending, snapshot) {
14128
+ const cleared = commitSnapshotBlockClear(capture, readbackTarget(pending.targetIdentity), snapshot, snapshotFailureCause(afterCause));
14129
+ return cleared.status === "fatal" ? afterFailure("local-snapshot-error") : undefined;
14130
+ }
14131
+ function setBlockFromAfterSnapshot(pending, reasonCode) {
14132
+ setSnapshotBlock(reasonCode, pending.targetIdentity, {
14133
+ initiator: pending.initiator
14134
+ });
13676
14135
  }
13677
14136
  async function captureRemoteAfter(operation, observer) {
13678
14137
  const remoteSnapshot = observer.remoteSnapshot;
@@ -13684,7 +14143,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13684
14143
  } catch {
13685
14144
  return afterFailure("operation-observation-rejected");
13686
14145
  }
13687
- return result.status === "available" ? { status: "available", snapshot: result.snapshot } : afterFailure("operation-observation-rejected", remoteFailureReason(result));
14146
+ if (isProbeTimeout(result))
14147
+ return TIMED_OUT_READ;
14148
+ const reasonCode = remoteFailureReason(result);
14149
+ if (reasonCode === "missing-resource" || reasonCode === "remote-not-advanced") {
14150
+ return { status: "unadvanced", reasonCode };
14151
+ }
14152
+ return result.status === "available" ? { status: "available", snapshot: result.snapshot } : afterFailure("operation-observation-rejected", reasonCode);
13688
14153
  }
13689
14154
  async function readRemoteScope(reader, operation, phase = "after") {
13690
14155
  try {
@@ -13769,13 +14234,22 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13769
14234
  function ownsOperation(pending) {
13770
14235
  return !pending.initiator || isCurrentInitiator(pending.initiator);
13771
14236
  }
13772
- function sealLostOperation(callDigest, pending) {
14237
+ function sealAndIgnore(callDigest, pending) {
13773
14238
  sealOperation(callDigest, pending, true);
13774
14239
  return { status: "ignored" };
13775
14240
  }
14241
+ function settleUnadvancedRemote(callDigest, pending, finalOperation, unadvanced) {
14242
+ const bothPush = pending.remoteOperation === "push" && finalOperation === "push";
14243
+ const before = pending.remoteBefore;
14244
+ const sealed = bothPush && (unadvanced.reasonCode === "remote-not-advanced" || before?.status === "missing-resource" || isProbeTimeout(before));
14245
+ if (sealed)
14246
+ return sealAndIgnore(callDigest, pending);
14247
+ sealOperation(callDigest, pending, true);
14248
+ return afterFailure("operation-observation-rejected", unadvanced.reasonCode);
14249
+ }
13776
14250
  async function completeOperationObservation(callDigest, host, pending, output) {
13777
14251
  if (!ownsOperation(pending))
13778
- return sealLostOperation(callDigest, pending);
14252
+ return sealAndIgnore(callDigest, pending);
13779
14253
  const parsedOutput = parseHostOutput(output);
13780
14254
  if (!parsedOutput) {
13781
14255
  sealOperation(callDigest, pending, true);
@@ -13783,20 +14257,25 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13783
14257
  }
13784
14258
  const capture = await captureAfterOperation(pending);
13785
14259
  if (!ownsOperation(pending))
13786
- return sealLostOperation(callDigest, pending);
14260
+ return sealAndIgnore(callDigest, pending);
14261
+ if (capture.status === "blocked") {
14262
+ sealOperation(callDigest, pending, true);
14263
+ setBlockFromAfterSnapshot(pending, capture.reasonCode);
14264
+ return { status: "ignored" };
14265
+ }
14266
+ if (capture.status === "timeout")
14267
+ return sealAndIgnore(callDigest, pending);
13787
14268
  if (capture.status === "unavailable") {
13788
14269
  sealOperation(callDigest, pending, true);
13789
14270
  return capture;
13790
14271
  }
13791
14272
  const afterSnapshot = capture.snapshot;
13792
14273
  const observation = buildOperationObservation(host, pending, afterSnapshot, requireGuard().status(), parsedOutput);
13793
- if (!observation) {
13794
- sealOperation(callDigest, pending, true);
13795
- return { status: "ignored" };
13796
- }
14274
+ if (!observation)
14275
+ return sealAndIgnore(callDigest, pending);
13797
14276
  const classification = await classifyLocalObservation(observation);
13798
14277
  if (!ownsOperation(pending))
13799
- return sealLostOperation(callDigest, pending);
14278
+ return sealAndIgnore(callDigest, pending);
13800
14279
  if (classification.status !== "ready") {
13801
14280
  sealOperation(callDigest, pending, true);
13802
14281
  return classification;
@@ -13805,7 +14284,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13805
14284
  if (remoteOperation(finalObservation.operation)) {
13806
14285
  const remoteCapture = await captureRemoteAfter(finalObservation.operation, pending.observer);
13807
14286
  if (!ownsOperation(pending)) {
13808
- return sealLostOperation(callDigest, pending);
14287
+ return sealAndIgnore(callDigest, pending);
14288
+ }
14289
+ if (remoteCapture.status === "timeout") {
14290
+ return sealAndIgnore(callDigest, pending);
14291
+ }
14292
+ if (remoteCapture.status === "unadvanced") {
14293
+ return settleUnadvancedRemote(callDigest, pending, finalObservation.operation, remoteCapture);
13809
14294
  }
13810
14295
  if (remoteCapture.status === "unavailable") {
13811
14296
  sealOperation(callDigest, pending, true);
@@ -13834,7 +14319,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13834
14319
  }
13835
14320
  }
13836
14321
  if (!ownsOperation(pending))
13837
- return sealLostOperation(callDigest, pending);
14322
+ return sealAndIgnore(callDigest, pending);
14323
+ if (finalObservation.operation === "verification" && overlappedAnotherLocalCall(pending)) {
14324
+ return sealAndIgnore(callDigest, pending);
14325
+ }
13838
14326
  const observed = await observeClassifiedOperation(finalObservation);
13839
14327
  if (!observed) {
13840
14328
  sealOperation(callDigest, pending, true);
@@ -13890,6 +14378,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13890
14378
  if (!options.observer || !isLocalOperationAfter(host))
13891
14379
  return;
13892
14380
  const callDigest = digestCall(ledger, host.callID);
14381
+ endLocalCall(callDigest);
13893
14382
  const pending = takeOperationToFinish(callDigest, host);
13894
14383
  if (!pending)
13895
14384
  return;
@@ -13987,6 +14476,8 @@ ${marker}` : marker;
13987
14476
  readStatus,
13988
14477
  unavailableCause: () => firstUnavailableCause ?? pendingUnavailableCause,
13989
14478
  seedDeferrals: currentSeedDeferrals,
14479
+ snapshotBlock: snapshotBlockControls,
14480
+ noteUnparsedLocalCall: beginUnparsedLocalCall,
13990
14481
  refreshReadback,
13991
14482
  observeReceipt: (input) => {
13992
14483
  ensureSynchronousRuntime();
@@ -14106,7 +14597,7 @@ function createOpencodeWorkflowGuard(options) {
14106
14597
  const unconfirmed = await runtime.refreshReadback();
14107
14598
  return {
14108
14599
  title: "Workflow guard status",
14109
- output: statusToolSchema.safeParse(input).success ? statusForTool(runtime.readStatus(), runtime.unavailableCause(), runtime.seedDeferrals(), unconfirmed) : unavailableToolResult()
14600
+ output: statusToolSchema.safeParse(input).success ? statusForTool(runtime.readStatus(), runtime.unavailableCause(), runtime.seedDeferrals(), unconfirmed, runtime.snapshotBlock.current()) : unavailableToolResult()
14110
14601
  };
14111
14602
  }),
14112
14603
  systematic_workflow_complete: makeWorkflowTool("Request completion of a guarded workflow unit or epoch.", completeToolShape, sessionRuntimeFor, (_runtime, input) => completeToolSchema.safeParse(input).success ? {
@@ -14124,10 +14615,18 @@ function createOpencodeWorkflowGuard(options) {
14124
14615
  output: unavailableToolResult()
14125
14616
  })
14126
14617
  };
14618
+ function countUnparsedLocalCall(input) {
14619
+ if (!isRecord7(input) || !boundedString(input.sessionID, 256) || !boundedString(input.tool, 128) || !isLocalOperationTool(input.tool)) {
14620
+ return;
14621
+ }
14622
+ sessionRuntimeFor(input.sessionID).noteUnparsedLocalCall();
14623
+ }
14127
14624
  async function before(input, output) {
14128
14625
  const host = parseHostBefore(input);
14129
- if (!host)
14626
+ if (!host) {
14627
+ countUnparsedLocalCall(input);
14130
14628
  return;
14629
+ }
14131
14630
  await sessionRuntimeFor(host.sessionID).hooks["tool.execute.before"](input, output);
14132
14631
  }
14133
14632
  async function after(input, output) {
@@ -14202,6 +14701,9 @@ function createOpencodeWorkflowGuard(options) {
14202
14701
  return { status: "rejected", reasonCode: "guard-unavailable" };
14203
14702
  }
14204
14703
  return sessionRuntimeFor(sessionID).startUnit(input, policy);
14704
+ },
14705
+ snapshotBlock(sessionID) {
14706
+ return boundedString(sessionID, 256) ? sessionRuntimeFor(sessionID).snapshotBlock : INERT_SNAPSHOT_BLOCK;
14205
14707
  }
14206
14708
  };
14207
14709
  }