@fro.bot/systematic 3.21.5 → 3.21.7

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-c17zm38x.js";
22
+ } from "./index-99dtcz5j.js";
23
23
 
24
24
  // src/index.ts
25
25
  import { createHash as createHash4 } from "crypto";
@@ -8381,8 +8381,9 @@ function parseReadback(input) {
8381
8381
  "resourceRevisionIdentity",
8382
8382
  "pullRequest",
8383
8383
  "checkState",
8384
- "reviewDecision"
8385
- ])) || !isBoundedString(input.workspaceIdentity) || input.operation !== undefined && !isOperation4(input.operation)) {
8384
+ "reviewDecision",
8385
+ "propagate"
8386
+ ])) || !isBoundedString(input.workspaceIdentity) || input.operation !== undefined && !isOperation4(input.operation) || input.propagate !== undefined && typeof input.propagate !== "boolean") {
8386
8387
  return;
8387
8388
  }
8388
8389
  const after = parseLegacyReadbackAfter({
@@ -8408,7 +8409,8 @@ function parseReadback(input) {
8408
8409
  resourceRevisionIdentity: after.resourceRevisionIdentity,
8409
8410
  pullRequest: after.pullRequest,
8410
8411
  checkState: after.checkState,
8411
- reviewDecision: after.reviewDecision
8412
+ reviewDecision: after.reviewDecision,
8413
+ ...input.propagate === undefined ? {} : { propagate: input.propagate }
8412
8414
  };
8413
8415
  }
8414
8416
  function parseLegacyReadbackAfter(input) {
@@ -8845,7 +8847,7 @@ function createWorkflowGuard(options) {
8845
8847
  const expected = unit ? currentResource(unit, readback.operation) : currentResourceIdentities.get(readback.operation);
8846
8848
  const changed = readback.resourceIdentity !== expected;
8847
8849
  currentResourceIdentities.set(readback.operation, readback.resourceIdentity);
8848
- if (readback.operation === "pr-creation" && unit) {
8850
+ if (readback.operation === "pr-creation" && unit && readback.propagate !== false) {
8849
8851
  propagatePullRequestScope(unit, readback.resourceIdentity);
8850
8852
  }
8851
8853
  return changed;
@@ -9212,7 +9214,7 @@ function createWorkflowGuard(options) {
9212
9214
  if (globalIssue)
9213
9215
  return projectGlobalIssue(globalIssue, lists);
9214
9216
  if (!epoch)
9215
- return makeStatus("unavailable", "no-active-epoch");
9217
+ return makeStatus("inactive", "no-active-epoch");
9216
9218
  if (epoch.status === "completed") {
9217
9219
  return makeStatus("protected", "epoch-completed", undefined, lists.satisfied, lists.missing);
9218
9220
  }
@@ -9253,7 +9255,7 @@ function createWorkflowGuard(options) {
9253
9255
  if (!epoch) {
9254
9256
  return {
9255
9257
  ready: false,
9256
- status: "unavailable",
9258
+ status: "rejected",
9257
9259
  reasonCode: "no-active-epoch"
9258
9260
  };
9259
9261
  }
@@ -10192,6 +10194,9 @@ function createWorkflowGuard(options) {
10192
10194
  currentOperationContext() {
10193
10195
  return currentOperationContext();
10194
10196
  },
10197
+ hasResourceBaseline(operation) {
10198
+ return epoch?.unit ? currentResource(epoch.unit, operation) !== undefined : false;
10199
+ },
10195
10200
  status() {
10196
10201
  return projection();
10197
10202
  },
@@ -10354,6 +10359,14 @@ function isWorkflowGuardBlockedError(value) {
10354
10359
  return false;
10355
10360
  return typeof candidate.reasonCode === "string" && REASON_CODES.has(candidate.reasonCode);
10356
10361
  }
10362
+ function initializationCause(kind) {
10363
+ return { site: "initialize-session", kind, timedOut: false };
10364
+ }
10365
+ var OBSERVER_READBACK_FAILED_CAUSE = Object.freeze({
10366
+ site: "refresh-readback",
10367
+ kind: "observer-readback-failed",
10368
+ timedOut: false
10369
+ });
10357
10370
  var startToolShape = {
10358
10371
  expected_operations: array(_enum(OPERATIONS)).optional(),
10359
10372
  resource_scopes: record(string(), string()).optional()
@@ -10838,27 +10851,30 @@ function isSuccessfulAfter(output) {
10838
10851
  function isSuccessfulSkillAfter(output) {
10839
10852
  return parseHostOutput(output, { maxOutputLength: Number.POSITIVE_INFINITY }) !== undefined;
10840
10853
  }
10841
- function statusForTool(status, unavailableCause) {
10854
+ function statusForTool(status, unavailableCause, seedDeferrals = []) {
10842
10855
  return JSON.stringify({
10843
10856
  state: status.state,
10844
10857
  reasonCode: status.reasonCode,
10845
10858
  ...status.repair ? { repair: status.repair } : {},
10846
10859
  satisfiedOperations: status.satisfiedOperations,
10847
10860
  missingOperations: status.missingOperations,
10848
- ...unavailableCause && status.state === "unavailable" ? { firstUnavailableCause: unavailableCause } : {}
10861
+ ...unavailableCause && status.state === "unavailable" ? { firstUnavailableCause: unavailableCause } : {},
10862
+ ...seedDeferrals.length > 0 ? { seedDeferrals } : {}
10849
10863
  });
10850
10864
  }
10851
10865
  function markerStatusRank(state) {
10852
- return {
10866
+ const ranks = {
10853
10867
  disabled: 0,
10854
- protected: 1,
10855
- waiting: 2,
10856
- rejected: 3,
10857
- unavailable: 4
10858
- }[state];
10868
+ inactive: 1,
10869
+ protected: 2,
10870
+ waiting: 3,
10871
+ rejected: 4,
10872
+ unavailable: 5
10873
+ };
10874
+ return ranks[state];
10859
10875
  }
10860
10876
  function isWorkflowState(value) {
10861
- return value === "protected" || value === "waiting" || value === "rejected" || value === "disabled" || value === "unavailable";
10877
+ return value === "protected" || value === "waiting" || value === "rejected" || value === "disabled" || value === "unavailable" || value === "inactive";
10862
10878
  }
10863
10879
  function parseMarkerDebug(value) {
10864
10880
  if (value === undefined)
@@ -11005,7 +11021,7 @@ function buildMarker(sources, malformed, current) {
11005
11021
  };
11006
11022
  return `${MARKER_OPEN}${JSON.stringify(document)}${MARKER_CLOSE}`;
11007
11023
  }
11008
- function createSessionRuntime(options, operationObservers, recoveredOperationContexts) {
11024
+ function createSessionRuntime(options, operationObservers, recoveredOperationContexts, runtimeStartedAt) {
11009
11025
  let ledger;
11010
11026
  let guard;
11011
11027
  let initialized = false;
@@ -11029,12 +11045,23 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11029
11045
  const blockedQuestionCalls = new Map;
11030
11046
  const consumedQuestionTargets = new Set;
11031
11047
  let firstUnavailableCause;
11048
+ let seedDeferralRecord;
11049
+ let unitStartGeneration = 0;
11032
11050
  function startFreshUnit(input, policy) {
11033
11051
  const result = guard.startUnit(input, policy);
11034
- if (result.status === "started")
11052
+ if (result.status === "started") {
11053
+ unitStartGeneration += 1;
11035
11054
  firstUnavailableCause = undefined;
11055
+ seedDeferralRecord = undefined;
11056
+ }
11036
11057
  return result;
11037
11058
  }
11059
+ function recordUnavailable(target, cause) {
11060
+ const result = target.setMode({ mode: "unavailable" });
11061
+ if (cause && result.status === "changed" && !firstUnavailableCause) {
11062
+ firstUnavailableCause = cause;
11063
+ }
11064
+ }
11038
11065
  function effectiveTargetContext() {
11039
11066
  const parentTargetRoot = options.targetDirectory ?? process.cwd();
11040
11067
  return {
@@ -11253,13 +11280,75 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11253
11280
  collectReceiptMarkers(part, markers);
11254
11281
  }
11255
11282
  }
11256
- function containsGuardHistory(value) {
11283
+ function hasNoEpochRejection(part) {
11284
+ const carriers = [
11285
+ part.metadata,
11286
+ isRecord7(part.state) && part.state.metadata
11287
+ ];
11288
+ return carriers.some((carrier) => isRecord7(carrier) && isRecord7(carrier.workflowGuard) && carrier.workflowGuard.status === "rejected" && carrier.workflowGuard.reasonCode === "no-active-epoch");
11289
+ }
11290
+ function newestMessage(history) {
11291
+ let newest;
11292
+ let newestCreated = Number.NEGATIVE_INFINITY;
11293
+ let tied = false;
11294
+ for (const entry of history) {
11295
+ const created = messageCreated(entry);
11296
+ if (!isRecord7(entry) || created === undefined)
11297
+ return;
11298
+ if (created > newestCreated) {
11299
+ newest = entry;
11300
+ newestCreated = created;
11301
+ tied = false;
11302
+ } else if (created === newestCreated) {
11303
+ tied = true;
11304
+ }
11305
+ }
11306
+ return tied ? undefined : newest;
11307
+ }
11308
+ function messageInfo(entry) {
11309
+ return isRecord7(entry) && isRecord7(entry.info) ? entry.info : undefined;
11310
+ }
11311
+ function messageCreated(entry) {
11312
+ const info2 = messageInfo(entry);
11313
+ const time = info2 && isRecord7(info2.time) ? info2.time : undefined;
11314
+ return typeof time?.created === "number" && Number.isFinite(time.created) ? time.created : undefined;
11315
+ }
11316
+ function isCurrentTurn(message) {
11317
+ const info2 = messageInfo(message);
11318
+ const time = info2 && isRecord7(info2.time) ? info2.time : undefined;
11319
+ const created = messageCreated(message);
11320
+ return info2?.role === "assistant" && (time?.completed === undefined || time.completed === null) && created !== undefined && created >= runtimeStartedAt;
11321
+ }
11322
+ function currentTurnExemptParts(history) {
11323
+ const exempt = new Set;
11324
+ const newest = newestMessage(history);
11325
+ if (!newest || !isCurrentTurn(newest) || !Array.isArray(newest.parts)) {
11326
+ return exempt;
11327
+ }
11328
+ for (const part of newest.parts) {
11329
+ if (isRecord7(part) && (part.tool === "systematic_workflow_start" || part.tool === "systematic_workflow_complete" || part.tool === "systematic_workflow_control") && isRecord7(part.state) && (part.state.status === "pending" || part.state.status === "running")) {
11330
+ exempt.add(part);
11331
+ }
11332
+ }
11333
+ return exempt;
11334
+ }
11335
+ function isExemptGuardPart(part, currentTurn) {
11336
+ if (part.tool === "systematic_workflow_status")
11337
+ return true;
11338
+ if (currentTurn.has(part))
11339
+ return true;
11340
+ if (part.tool !== "systematic_workflow_start" && part.tool !== "systematic_workflow_complete") {
11341
+ return false;
11342
+ }
11343
+ return isRecord7(part.state) && part.state.status === "completed" && hasNoEpochRejection(part);
11344
+ }
11345
+ function containsGuardHistory(value, currentTurn) {
11257
11346
  if (!isRecord7(value))
11258
11347
  return false;
11259
11348
  if (value.tool === "systematic_workflow_start" || value.tool === "systematic_workflow_status" || value.tool === "systematic_workflow_complete" || value.tool === "systematic_workflow_control") {
11260
- return true;
11349
+ return !isExemptGuardPart(value, currentTurn);
11261
11350
  }
11262
- return Array.isArray(value.parts) && value.parts.some((part) => containsGuardHistory(part));
11351
+ return Array.isArray(value.parts) && value.parts.some((part) => containsGuardHistory(part, currentTurn));
11263
11352
  }
11264
11353
  function createGuard(nextLedger) {
11265
11354
  return createWorkflowGuard({
@@ -11298,16 +11387,18 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11298
11387
  emptyHistoryLedger ??= mintLedger();
11299
11388
  return emptyHistoryLedger;
11300
11389
  }
11301
- function publishUnavailable(reusableLedger) {
11390
+ function publishUnavailable(cause, reusableLedger) {
11302
11391
  ledger = reusableLedger ?? mintLedger();
11303
11392
  guard = createGuard(ledger);
11304
- if (options.config.mode !== "disabled")
11305
- guard.setMode({ mode: "unavailable" });
11393
+ if (options.config.mode !== "disabled") {
11394
+ recordUnavailable(guard, cause);
11395
+ }
11306
11396
  initialized = true;
11307
11397
  }
11308
11398
  function publishFresh(reusableLedger) {
11309
11399
  ledger = reusableLedger ?? mintLedger();
11310
11400
  guard = createGuard(ledger);
11401
+ firstUnavailableCause = undefined;
11311
11402
  initialized = true;
11312
11403
  }
11313
11404
  function ensureSynchronousRuntime() {
@@ -11359,8 +11450,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11359
11450
  }
11360
11451
  function recoverPersistedMarkers(markers) {
11361
11452
  const seed = extractReceiptReadbackSeed(markers);
11362
- if (seed.status !== "ready")
11363
- return false;
11453
+ if (seed.status !== "ready") {
11454
+ return initializationCause("markers-malformed-or-incompatible");
11455
+ }
11364
11456
  let recoveredLedger;
11365
11457
  try {
11366
11458
  recoveredLedger = createReceiptLedger({
@@ -11369,14 +11461,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11369
11461
  sessionSalt: seed.sessionSalt
11370
11462
  });
11371
11463
  } catch {
11372
- return false;
11464
+ return initializationCause("markers-malformed-or-incompatible");
11373
11465
  }
11374
11466
  if (!seedAgrees(recoveredLedger, seed)) {
11375
- return false;
11467
+ return initializationCause("markers-malformed-or-incompatible");
11376
11468
  }
11377
11469
  const recovered = recoveredLedger.recoverReadback(markers);
11378
11470
  if (recovered.status === "rejected") {
11379
- return false;
11471
+ return initializationCause("recovery-rejected");
11380
11472
  }
11381
11473
  const recoveredGuard = createGuard(recoveredLedger);
11382
11474
  const restored = recoveredGuard.restore({
@@ -11388,12 +11480,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11388
11480
  }
11389
11481
  });
11390
11482
  if (restored.status === "rejected") {
11391
- return false;
11483
+ return initializationCause("recovery-rejected");
11392
11484
  }
11393
11485
  ledger = recoveredLedger;
11394
11486
  guard = recoveredGuard;
11487
+ firstUnavailableCause = undefined;
11395
11488
  initialized = true;
11396
- return true;
11489
+ return;
11397
11490
  }
11398
11491
  function classifyMarkersFromParts(parts2) {
11399
11492
  const allMarkers = [];
@@ -11422,15 +11515,20 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11422
11515
  }
11423
11516
  function publishEmptyMarkers(parts2, allowFresh) {
11424
11517
  const reusableLedger = emptyHistoryLedgerForRetry();
11425
- if (allowFresh && !parts2.some((part) => containsGuardHistory(part))) {
11518
+ const currentTurn = currentTurnExemptParts(parts2);
11519
+ if (parts2.some((part) => containsGuardHistory(part, currentTurn))) {
11520
+ publishUnavailable(initializationCause("markerless-guard-history"), reusableLedger);
11521
+ return;
11522
+ }
11523
+ if (allowFresh) {
11426
11524
  publishFresh(reusableLedger);
11427
- } else {
11428
- retryableEmptyHistory = true;
11429
- publishUnavailable(reusableLedger);
11525
+ return;
11430
11526
  }
11527
+ retryableEmptyHistory = true;
11528
+ publishFresh(reusableLedger);
11431
11529
  }
11432
11530
  async function initializeSession(sessionID, allowFresh) {
11433
- const reader = options.hostReadback?.readSessionParts;
11531
+ const reader = options.hostReadback?.readSessionPartsStrict ?? options.hostReadback?.readSessionParts;
11434
11532
  if (!reader) {
11435
11533
  publishFresh();
11436
11534
  return;
@@ -11439,32 +11537,40 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11439
11537
  try {
11440
11538
  parts2 = await reader(sessionID);
11441
11539
  } catch {
11442
- publishUnavailable();
11540
+ publishUnavailable(initializationCause("history-read-failed"));
11443
11541
  return;
11444
11542
  }
11445
11543
  const classification = classifyMarkersFromParts(parts2);
11446
11544
  if (classification.kind === "ambiguous") {
11447
- publishUnavailable();
11545
+ publishUnavailable(initializationCause("markers-ambiguous"));
11448
11546
  return;
11449
11547
  }
11450
11548
  if (classification.kind === "foreign-empty") {
11451
11549
  publishEmptyMarkers(parts2, allowFresh);
11452
11550
  return;
11453
11551
  }
11454
- if (!recoverPersistedMarkers(classification.markers))
11455
- publishUnavailable();
11552
+ const failure = recoverPersistedMarkers(classification.markers);
11553
+ if (failure)
11554
+ publishUnavailable(failure);
11456
11555
  }
11457
11556
  async function recoverFromHost(sessionID, allowFresh = true) {
11458
- if (initializationPromise) {
11459
- await initializationPromise;
11557
+ let reinitialize = false;
11558
+ while (initializationPromise) {
11559
+ const seen = initializationPromise;
11560
+ await seen;
11561
+ if (initializationPromise !== seen)
11562
+ continue;
11460
11563
  if (!retryableEmptyHistory || !allowFresh)
11461
11564
  return;
11462
- initializationPromise = undefined;
11463
- initialized = false;
11565
+ reinitialize = true;
11566
+ break;
11464
11567
  }
11568
+ if (reinitialize)
11569
+ initialized = false;
11465
11570
  retryableEmptyHistory = false;
11466
- initializationPromise = initializeSession(sessionID, allowFresh);
11467
- await initializationPromise;
11571
+ const next = initializeSession(sessionID, allowFresh);
11572
+ initializationPromise = next;
11573
+ await next;
11468
11574
  }
11469
11575
  async function rollupForegroundTask(host, output) {
11470
11576
  if (!options.hostReadback || !isRecord7(output))
@@ -11634,10 +11740,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11634
11740
  function markUnavailable(cause) {
11635
11741
  if (options.config.mode === "disabled")
11636
11742
  return;
11637
- const result = guard.setMode({ mode: "unavailable" });
11638
- if (cause && result.status === "changed" && !firstUnavailableCause) {
11639
- firstUnavailableCause = cause;
11640
- }
11743
+ recordUnavailable(guard, cause);
11641
11744
  }
11642
11745
  function bindCall(callDigest, kind, fingerprint) {
11643
11746
  const existing = callBindings.get(callDigest);
@@ -11671,7 +11774,6 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11671
11774
  }
11672
11775
  }
11673
11776
  function readStatus() {
11674
- abandonPending();
11675
11777
  return guard.status();
11676
11778
  }
11677
11779
  function control(sessionID, input) {
@@ -11713,24 +11815,26 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11713
11815
  })
11714
11816
  };
11715
11817
  }
11818
+ function observerReadbackApplies() {
11819
+ return options.observer !== undefined && guard.status().epoch !== null;
11820
+ }
11716
11821
  async function refreshReadback() {
11717
- abandonPending();
11718
- if (!options.observer)
11822
+ if (!observerReadbackApplies())
11719
11823
  return;
11720
11824
  const effective = effectiveOperationObserver();
11721
11825
  if (!effective) {
11722
- markUnavailable();
11826
+ markUnavailable(OBSERVER_READBACK_FAILED_CAUSE);
11723
11827
  return;
11724
11828
  }
11725
11829
  let result;
11726
11830
  try {
11727
11831
  result = await effective.observer.snapshot();
11728
11832
  } catch {
11729
- markUnavailable();
11833
+ markUnavailable(OBSERVER_READBACK_FAILED_CAUSE);
11730
11834
  return;
11731
11835
  }
11732
11836
  if (result.status === "unavailable" || result.snapshot.targetDigest !== effective.targetIdentity) {
11733
- markUnavailable();
11837
+ markUnavailable(OBSERVER_READBACK_FAILED_CAUSE);
11734
11838
  return;
11735
11839
  }
11736
11840
  const observed = guard.observeReadback({
@@ -11740,7 +11844,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11740
11844
  ...effective.pinned ? { operationTargetIdentity: effective.targetIdentity } : {}
11741
11845
  });
11742
11846
  if (observed.status === "rejected" && observed.reasonCode === "workspace-mismatch" || !await refreshRemoteReadbacks(effective.observer, result.snapshot)) {
11743
- markUnavailable();
11847
+ markUnavailable(OBSERVER_READBACK_FAILED_CAUSE);
11744
11848
  }
11745
11849
  }
11746
11850
  async function refreshRemoteReadbacks(observer, local) {
@@ -11878,11 +11982,11 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11878
11982
  workflowGuard: { status: "completed", target }
11879
11983
  };
11880
11984
  }
11881
- function writeTerminalCompletionResult(output, result, target) {
11985
+ function writeTerminalCompletionResult(output, result, target, title = "Workflow transition unavailable") {
11882
11986
  if (!isRecord7(output))
11883
11987
  return;
11884
11988
  const existingMetadata = isRecord7(output.metadata) ? output.metadata : {};
11885
- output.title = "Workflow transition unavailable";
11989
+ output.title = title;
11886
11990
  output.output = JSON.stringify({
11887
11991
  status: result.status,
11888
11992
  reasonCode: result.reasonCode
@@ -11897,6 +12001,27 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11897
12001
  }
11898
12002
  };
11899
12003
  }
12004
+ function writeNoEpochBlockedResult(callDigest, output, target) {
12005
+ const current = guard.status();
12006
+ const terminal = !current.epoch ? {
12007
+ target,
12008
+ status: "rejected",
12009
+ reasonCode: "no-active-epoch",
12010
+ title: "Workflow transition rejected"
12011
+ } : current.state === "unavailable" ? { target, status: "unavailable", reasonCode: current.reasonCode } : {
12012
+ target,
12013
+ status: "rejected",
12014
+ reasonCode: current.reasonCode,
12015
+ title: "Workflow transition rejected"
12016
+ };
12017
+ terminalCompletes.set(callDigest, terminal);
12018
+ writeTerminalCompletionResult(output, terminal, target, terminal.title);
12019
+ }
12020
+ function writeBlockedCompleteResult(callDigest, output, blocked) {
12021
+ if (blocked?.reasonCode === "no-active-epoch") {
12022
+ writeNoEpochBlockedResult(callDigest, output, blocked.target);
12023
+ }
12024
+ }
11900
12025
  function writeAbandonedCompletionResult(output, target, reasonCode) {
11901
12026
  writeTerminalCompletionResult(output, { target, status: "unavailable", reasonCode }, target);
11902
12027
  }
@@ -11949,7 +12074,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11949
12074
  if (options.config.mode === "protected") {
11950
12075
  throw createWorkflowGuardBlockedError("guard-unavailable");
11951
12076
  }
11952
- blockedCompletes.set(callDigest, target);
12077
+ blockedCompletes.set(callDigest, {
12078
+ target,
12079
+ reasonCode: status.reasonCode
12080
+ });
11953
12081
  blockedQuestionCalls.set(callDigest, challenge.challenge.challengeId);
11954
12082
  return true;
11955
12083
  }
@@ -11976,10 +12104,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11976
12104
  });
11977
12105
  return;
11978
12106
  }
11979
- if (options.config.mode === "protected") {
12107
+ if (options.config.mode === "protected" && prepared.reasonCode !== "no-active-epoch") {
11980
12108
  throw createWorkflowGuardBlockedError(prepared.reasonCode);
11981
12109
  }
11982
- blockedCompletes.set(callDigest, target);
12110
+ blockedCompletes.set(callDigest, {
12111
+ target,
12112
+ reasonCode: prepared.reasonCode
12113
+ });
11983
12114
  }
11984
12115
  async function remoteIntentForOperation(host, args2, observer) {
11985
12116
  if (host.tool !== "bash" || !isRecord7(args2))
@@ -11994,10 +12125,11 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11994
12125
  if (!remoteSnapshot)
11995
12126
  return { operation: classification.category };
11996
12127
  try {
11997
- return {
11998
- operation: classification.category,
11999
- before: await remoteSnapshot(classification.category, "before")
12000
- };
12128
+ let before = await remoteSnapshot(classification.category, "before");
12129
+ if (before.status === "unavailable" && before.reasonCode === "command-timeout" && deferredSeedFor(classification.category)) {
12130
+ before = await remoteSnapshot(classification.category, "before");
12131
+ }
12132
+ return { operation: classification.category, before };
12001
12133
  } catch {
12002
12134
  return { operation: classification.category };
12003
12135
  }
@@ -12005,6 +12137,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12005
12137
  async function prepareOperation(host, args2) {
12006
12138
  if (!options.observer || !isLocalOperationTool(host.tool))
12007
12139
  return;
12140
+ const initiator = currentInitiator();
12008
12141
  const { parentTargetRoot, sessionLocation } = effectiveTargetContext();
12009
12142
  const fingerprint = argsFingerprint(ledger, host.tool, args2, sessionLocation);
12010
12143
  if (!fingerprint) {
@@ -12065,6 +12198,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12065
12198
  observer: operationObserver
12066
12199
  });
12067
12200
  const remote = await remoteIntentForOperation(host, args2, operationObserver);
12201
+ if (remote) {
12202
+ bindDeferredBaseline(remote.operation, remote.before, operationObserver, initiator);
12203
+ }
12068
12204
  pendingOperations.set(callDigest, {
12069
12205
  callID: host.callID,
12070
12206
  tool: host.tool,
@@ -12074,6 +12210,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12074
12210
  registeredWorktreeIdentity: registeredIdentity,
12075
12211
  observer: operationObserver,
12076
12212
  before: result.snapshot,
12213
+ ...initiator ? { initiator } : {},
12077
12214
  ...remote ? { remoteOperation: remote.operation, remoteBefore: remote.before } : {}
12078
12215
  });
12079
12216
  }
@@ -12203,52 +12340,151 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12203
12340
  timedOut: local.reasonCode === "command-timeout"
12204
12341
  };
12205
12342
  }
12206
- for (const operation of remoteOperations) {
12207
- const cause = await seedRemoteScope(remoteSnapshot, operation, local.snapshot);
12208
- if (cause)
12209
- return cause;
12343
+ return seedEachRemoteScope(remoteOperations, remoteSnapshot, local.snapshot);
12344
+ }
12345
+ async function seedEachRemoteScope(operations, reader, local) {
12346
+ for (const operation of operations) {
12347
+ const outcome = await seedRemoteScope(reader, operation, local);
12348
+ if (outcome.kind === "fatal")
12349
+ return outcome.cause;
12350
+ if (outcome.kind === "deferred") {
12351
+ recordSeedDeferral(operation, outcome.reasonCode);
12352
+ }
12210
12353
  }
12211
12354
  return;
12212
12355
  }
12356
+ function recordSeedDeferral(operation, reasonCode) {
12357
+ if (guard.hasResourceBaseline(operation))
12358
+ return;
12359
+ const observer = options.observer;
12360
+ if (!observer)
12361
+ return;
12362
+ seedDeferralEntries(true).push({
12363
+ operation,
12364
+ reasonCode,
12365
+ observer,
12366
+ targetIdentity: observer.targetDigest
12367
+ });
12368
+ }
12369
+ function seedDeferralEntries(reset = false) {
12370
+ const unitId = guard.status().unit?.unitId;
12371
+ if (!unitId)
12372
+ return [];
12373
+ if (seedDeferralRecord?.unitId === unitId)
12374
+ return seedDeferralRecord.entries;
12375
+ if (!reset)
12376
+ return [];
12377
+ seedDeferralRecord = { unitId, entries: [] };
12378
+ return seedDeferralRecord.entries;
12379
+ }
12380
+ function deferredSeedFor(operation) {
12381
+ return seedDeferralEntries().find((entry) => entry.operation === operation);
12382
+ }
12383
+ function clearSeedDeferral(operation) {
12384
+ if (!seedDeferralRecord)
12385
+ return;
12386
+ const index = seedDeferralRecord.entries.findIndex((entry) => entry.operation === operation);
12387
+ if (index !== -1)
12388
+ seedDeferralRecord.entries.splice(index, 1);
12389
+ }
12390
+ function bindDeferredBaseline(operation, before, observer, initiator) {
12391
+ if (!initiator || !isCurrentInitiator(initiator))
12392
+ return;
12393
+ const deferred = deferredSeedFor(operation);
12394
+ if (!deferred)
12395
+ return;
12396
+ if (guard.hasResourceBaseline(operation)) {
12397
+ clearSeedDeferral(operation);
12398
+ return;
12399
+ }
12400
+ if (!before || !sameSeedObserver(deferred, observer))
12401
+ return;
12402
+ bindFromBeforeRead(operation, before);
12403
+ }
12404
+ function bindFromBeforeRead(operation, before) {
12405
+ if (before.status === "missing-resource") {
12406
+ if (operation === "pr-creation")
12407
+ clearSeedDeferral(operation);
12408
+ return;
12409
+ }
12410
+ if (before.status !== "available")
12411
+ return;
12412
+ const observed = guard.observeReadback(deferredBaselineReadback(operation, before.snapshot));
12413
+ if (observed.status !== "rejected")
12414
+ clearSeedDeferral(operation);
12415
+ }
12416
+ function currentInitiator() {
12417
+ const current = guard.status();
12418
+ return current.epoch && current.unit ? {
12419
+ epochId: current.epoch.epochId,
12420
+ unitId: current.unit.unitId,
12421
+ generation: unitStartGeneration
12422
+ } : undefined;
12423
+ }
12424
+ function isCurrentInitiator(initiator) {
12425
+ const current = currentInitiator();
12426
+ return current !== undefined && current.epochId === initiator.epochId && current.unitId === initiator.unitId && current.generation === initiator.generation;
12427
+ }
12428
+ function sameSeedObserver(deferred, observer) {
12429
+ return observer === deferred.observer && observer.targetDigest === deferred.targetIdentity;
12430
+ }
12431
+ function deferredBaselineReadback(operation, snapshot) {
12432
+ return {
12433
+ operation,
12434
+ workspaceIdentity: options.workspaceIdentity,
12435
+ resourceIdentity: snapshot.resourceIdentity,
12436
+ ...operation === "push" ? { resourceRevisionIdentity: snapshot.resourceRevisionIdentity } : {},
12437
+ ...operation === "pr-creation" ? { propagate: false } : {}
12438
+ };
12439
+ }
12440
+ function currentSeedDeferrals() {
12441
+ return seedDeferralEntries().map(({ operation, reasonCode }) => ({
12442
+ operation,
12443
+ reasonCode
12444
+ }));
12445
+ }
12446
+ function fatalSeed(cause) {
12447
+ return { kind: "fatal", cause };
12448
+ }
12213
12449
  async function seedRemoteScope(reader, operation, local) {
12214
12450
  const result = await readRemoteScope(reader, operation, "before");
12215
12451
  if (!result) {
12216
- return {
12452
+ return fatalSeed({
12217
12453
  site: "seed-remote-scope",
12218
12454
  kind: "remote-scope-unreadable",
12219
12455
  operation,
12220
12456
  timedOut: false
12221
- };
12457
+ });
12222
12458
  }
12223
12459
  if (result.status === "missing-resource") {
12224
- const allowed = operation === "pr-creation" || operation === "check-readback" || operation === "review-readback";
12225
- return allowed ? undefined : {
12226
- site: "seed-remote-scope",
12227
- kind: "remote-scope-missing-resource",
12228
- operation,
12229
- timedOut: false
12230
- };
12460
+ if (operation === "push") {
12461
+ return { kind: "deferred", reasonCode: "missing-resource" };
12462
+ }
12463
+ return { kind: "tolerated" };
12231
12464
  }
12232
12465
  if (result.status !== "available") {
12233
- return {
12466
+ if (result.reasonCode === "command-timeout") {
12467
+ return { kind: "deferred", reasonCode: "command-timeout" };
12468
+ }
12469
+ return fatalSeed({
12234
12470
  site: "seed-remote-scope",
12235
12471
  kind: "remote-scope-unavailable",
12236
12472
  operation,
12237
12473
  reasonCode: result.reasonCode,
12238
- timedOut: result.reasonCode === "command-timeout"
12239
- };
12474
+ timedOut: false
12475
+ });
12240
12476
  }
12241
12477
  const observed = guard.observeReadback(remoteReadbackInput(operation, local, options.workspaceIdentity, result.snapshot, operation !== "pr-creation"));
12242
12478
  if (observed.status === "rejected") {
12243
- return {
12479
+ return fatalSeed({
12244
12480
  site: "seed-remote-scope",
12245
12481
  kind: "remote-readback-rejected",
12246
12482
  operation,
12247
12483
  reasonCode: observed.reasonCode,
12248
12484
  timedOut: false
12249
- };
12485
+ });
12250
12486
  }
12251
- return;
12487
+ return { kind: "seeded" };
12252
12488
  }
12253
12489
  async function finishSkill(host, output) {
12254
12490
  const callDigest = digestCall(ledger, host.callID);
@@ -12407,7 +12643,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12407
12643
  writeAbandonedCompletionMetadata(output, target, terminal.reasonCode);
12408
12644
  return;
12409
12645
  }
12410
- writeTerminalCompletionResult(output, terminal, target);
12646
+ writeTerminalCompletionResult(output, terminal, target, terminal.title);
12411
12647
  }
12412
12648
  function replayTerminalComplete(callDigest, finalTarget, output) {
12413
12649
  const questionChallengeID = blockedQuestionCalls.get(callDigest);
@@ -12426,8 +12662,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12426
12662
  }
12427
12663
  const replay = finalizedCompletes.get(callDigest);
12428
12664
  const abandonedTarget = abandonedCompletes.get(callDigest);
12429
- const blockedTarget = blockedCompletes.get(callDigest);
12430
- const expectedTarget = replay?.target ?? abandonedTarget ?? blockedTarget;
12665
+ const blocked = blockedCompletes.get(callDigest);
12666
+ const expectedTarget = replay?.target ?? abandonedTarget ?? blocked?.target;
12431
12667
  if (!expectedTarget)
12432
12668
  return false;
12433
12669
  if (finalTarget !== expectedTarget) {
@@ -12437,6 +12673,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12437
12673
  if (replay)
12438
12674
  replayComplete(callDigest);
12439
12675
  blockedCompletes.delete(callDigest);
12676
+ writeBlockedCompleteResult(callDigest, output, blocked);
12440
12677
  return true;
12441
12678
  }
12442
12679
  function abandonComplete(callDigest, pending, remember) {
@@ -12667,8 +12904,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12667
12904
  tool: host.tool,
12668
12905
  ...command ? { command } : {},
12669
12906
  context: {
12670
- epochId: current.epoch.epochId,
12671
- unitId: current.unit.unitId,
12907
+ epochId: pending.initiator?.epochId ?? current.epoch.epochId,
12908
+ unitId: pending.initiator?.unitId ?? current.unit.unitId,
12672
12909
  workspaceIdentity: options.workspaceIdentity,
12673
12910
  repositoryIdentity: pending.before.repositoryRevisionDigest,
12674
12911
  worktreeIdentity: pending.before.worktreeRevisionDigest,
@@ -12676,7 +12913,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12676
12913
  ...pending.remoteBefore?.status === "available" ? {
12677
12914
  resourceIdentity: pending.remoteBefore.snapshot.resourceIdentity,
12678
12915
  resourceRevisionIdentity: pending.remoteBefore.snapshot.resourceRevisionIdentity
12679
- } : operation === "pr-creation" && remoteAfter ? { resourceIdentity: remoteAfter.resourceIdentity } : {}
12916
+ } : operation === "pr-creation" && remoteAfter && pending.remoteBefore?.status === "missing-resource" ? { resourceIdentity: remoteAfter.resourceIdentity } : {}
12680
12917
  },
12681
12918
  after: {
12682
12919
  workspaceIdentity: options.workspaceIdentity,
@@ -12729,13 +12966,24 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12729
12966
  return;
12730
12967
  }
12731
12968
  }
12969
+ function ownsOperation(pending) {
12970
+ return !pending.initiator || isCurrentInitiator(pending.initiator);
12971
+ }
12972
+ function sealLostOperation(callDigest, pending) {
12973
+ sealOperation(callDigest, pending, true);
12974
+ return { status: "ignored" };
12975
+ }
12732
12976
  async function completeOperationObservation(callDigest, host, pending, output) {
12977
+ if (!ownsOperation(pending))
12978
+ return sealLostOperation(callDigest, pending);
12733
12979
  const parsedOutput = parseHostOutput(output);
12734
12980
  if (!parsedOutput) {
12735
12981
  sealOperation(callDigest, pending, true);
12736
12982
  return { status: "unavailable" };
12737
12983
  }
12738
12984
  const afterSnapshot = await captureAfterOperation(pending);
12985
+ if (!ownsOperation(pending))
12986
+ return sealLostOperation(callDigest, pending);
12739
12987
  if (!afterSnapshot) {
12740
12988
  sealOperation(callDigest, pending, true);
12741
12989
  return { status: "unavailable" };
@@ -12746,6 +12994,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12746
12994
  return { status: "ignored" };
12747
12995
  }
12748
12996
  const classification = await classifyLocalObservation(observation);
12997
+ if (!ownsOperation(pending))
12998
+ return sealLostOperation(callDigest, pending);
12749
12999
  if (classification.status !== "ready") {
12750
13000
  sealOperation(callDigest, pending, true);
12751
13001
  return { status: classification.status };
@@ -12753,6 +13003,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12753
13003
  let finalObservation = classification.observation;
12754
13004
  if (remoteOperation(finalObservation.operation)) {
12755
13005
  const remoteAfter = await captureRemoteAfter(finalObservation.operation, pending.observer);
13006
+ if (!ownsOperation(pending)) {
13007
+ return sealLostOperation(callDigest, pending);
13008
+ }
12756
13009
  if (!remoteAfter) {
12757
13010
  sealOperation(callDigest, pending, true);
12758
13011
  return { status: "unavailable" };
@@ -12763,7 +13016,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12763
13016
  return { status: "ignored" };
12764
13017
  }
12765
13018
  finalObservation = rebuilt;
12766
- if (finalObservation.operation === "pr-creation" && pending.remoteBefore?.status !== "available") {
13019
+ if (finalObservation.operation === "pr-creation" && pending.remoteBefore?.status === "missing-resource") {
12767
13020
  const seeded = guard.observeReadback({
12768
13021
  operation: "pr-creation",
12769
13022
  workspaceIdentity: options.workspaceIdentity,
@@ -12778,6 +13031,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12778
13031
  }
12779
13032
  }
12780
13033
  }
13034
+ if (!ownsOperation(pending))
13035
+ return sealLostOperation(callDigest, pending);
12781
13036
  const observed = await observeClassifiedOperation(finalObservation);
12782
13037
  if (!observed) {
12783
13038
  sealOperation(callDigest, pending, true);
@@ -12924,6 +13179,7 @@ ${marker}` : marker;
12924
13179
  },
12925
13180
  readStatus,
12926
13181
  unavailableCause: () => firstUnavailableCause,
13182
+ seedDeferrals: currentSeedDeferrals,
12927
13183
  refreshReadback,
12928
13184
  observeReceipt: (input) => {
12929
13185
  ensureSynchronousRuntime();
@@ -13018,6 +13274,7 @@ function createOpencodeWorkflowGuard(options) {
13018
13274
  const sessions = new Map;
13019
13275
  const operationObservers = new Map;
13020
13276
  const recoveredOperationContexts = new Map;
13277
+ const runtimeStartedAt = (options.now ?? Date.now)();
13021
13278
  function sessionRuntimeFor(sessionID) {
13022
13279
  const existing = sessions.get(sessionID);
13023
13280
  if (existing)
@@ -13026,7 +13283,7 @@ function createOpencodeWorkflowGuard(options) {
13026
13283
  ...options,
13027
13284
  registrationIdentity: options.registrationIdentity,
13028
13285
  sessionSalt: options.sessionSalt
13029
- }, operationObservers, recoveredOperationContexts);
13286
+ }, operationObservers, recoveredOperationContexts, runtimeStartedAt);
13030
13287
  sessions.set(sessionID, runtime);
13031
13288
  return runtime;
13032
13289
  }
@@ -13042,7 +13299,7 @@ function createOpencodeWorkflowGuard(options) {
13042
13299
  await runtime.refreshReadback();
13043
13300
  return {
13044
13301
  title: "Workflow guard status",
13045
- output: statusToolSchema.safeParse(input).success ? statusForTool(runtime.readStatus(), runtime.unavailableCause()) : unavailableToolResult()
13302
+ output: statusToolSchema.safeParse(input).success ? statusForTool(runtime.readStatus(), runtime.unavailableCause(), runtime.seedDeferrals()) : unavailableToolResult()
13046
13303
  };
13047
13304
  }),
13048
13305
  systematic_workflow_complete: makeWorkflowTool("Request completion of a guarded workflow unit or epoch.", completeToolShape, sessionRuntimeFor, (_runtime, input) => completeToolSchema.safeParse(input).success ? {
@@ -13486,15 +13743,25 @@ var initializePlugin = async ({
13486
13743
  observer,
13487
13744
  classifier: createReceiptClassifier(),
13488
13745
  hostReadback: (() => {
13746
+ const readMessages = async (sessionID) => {
13747
+ const messages = client.session.messages.bind(client.session);
13748
+ return messages({ path: { id: sessionID }, query: { directory } });
13749
+ };
13489
13750
  return {
13490
13751
  readSessionParts: async (sessionID) => {
13491
- const messages = client.session.messages.bind(client.session);
13492
- const response = await messages({
13493
- path: { id: sessionID },
13494
- query: { directory }
13495
- });
13752
+ const response = await readMessages(sessionID);
13496
13753
  return Array.isArray(response.data) ? response.data : [];
13497
13754
  },
13755
+ readSessionPartsStrict: async (sessionID) => {
13756
+ const response = await readMessages(sessionID);
13757
+ if (response.error !== undefined && response.error !== null) {
13758
+ throw new Error("session history read failed");
13759
+ }
13760
+ if (!Array.isArray(response.data)) {
13761
+ throw new Error("session history read returned malformed data");
13762
+ }
13763
+ return response.data;
13764
+ },
13498
13765
  listChildren: async (sessionID) => {
13499
13766
  const children = client.session.children.bind(client.session);
13500
13767
  const response = await children({