@fro.bot/systematic 3.22.3 → 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-99dtcz5j.js";
22
+ } from "./index-aaygsm67.js";
23
23
 
24
24
  // src/index.ts
25
25
  import { createHash as createHash4 } from "crypto";
@@ -752,16 +752,27 @@ function normalizePath(path) {
752
752
  import { spawnSync } from "child_process";
753
753
  import { createHash } from "crypto";
754
754
  import fs6 from "fs";
755
+ import os3 from "os";
755
756
  import path5 from "path";
756
757
  var DEFAULT_LIMITS = {
757
758
  maxCommandOutputBytes: 8388608,
758
759
  maxCommandTimeoutMs: 5000,
759
760
  maxFiles: 20000,
761
+ maxGitlinks: 32,
760
762
  maxRemoteCommandOutputBytes: 1048576,
761
763
  maxRemoteItems: 4096,
762
764
  maxTotalFileBytes: 134217728,
763
765
  maxPathBytes: 4096
764
766
  };
767
+ var GIT_OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
768
+ var STAGE_LIST_ARGS = [
769
+ "ls-files",
770
+ "--stage",
771
+ "--full-name",
772
+ "-z",
773
+ "--",
774
+ ":/"
775
+ ];
765
776
  var UNTRACKED_FILES_ARGS = [
766
777
  "ls-files",
767
778
  "--others",
@@ -771,6 +782,30 @@ var UNTRACKED_FILES_ARGS = [
771
782
  "--",
772
783
  ":/"
773
784
  ];
785
+ var FORCED_GIT_PREFIX = [
786
+ "--no-replace-objects",
787
+ "-c",
788
+ "core.ignorecase=false",
789
+ "-c",
790
+ "core.fsmonitor=false"
791
+ ];
792
+ var STRICT_UTF8_DECODER = new TextDecoder("utf-8", {
793
+ fatal: true,
794
+ ignoreBOM: true
795
+ });
796
+ var WORKTREE_DIGEST_DOMAIN = "systematic:opencode-observer:worktree:v3\x00";
797
+ var IGNORED_GITIGNORE_ARGS = [
798
+ "ls-files",
799
+ "-o",
800
+ "-i",
801
+ "--exclude-standard",
802
+ "--directory",
803
+ "--full-name",
804
+ "-z",
805
+ "--",
806
+ ":(top,glob)**/.gitignore"
807
+ ];
808
+ var MAX_IGNORE_SOURCE_BYTES = 1048576;
774
809
  function unavailable(result) {
775
810
  return { status: "unavailable", reasonCode: result.reasonCode };
776
811
  }
@@ -795,25 +830,42 @@ function sanitizedEnvironment() {
795
830
  }
796
831
  return env;
797
832
  }
833
+ function decodeCommandStdout(raw) {
834
+ if (typeof raw === "string")
835
+ return { text: raw, invalid: false };
836
+ if (raw instanceof Uint8Array) {
837
+ try {
838
+ return { text: STRICT_UTF8_DECODER.decode(raw), invalid: false };
839
+ } catch {
840
+ return { text: "", invalid: true };
841
+ }
842
+ }
843
+ return { text: "", invalid: raw !== null && raw !== undefined };
844
+ }
798
845
  function defaultCommandRunner(args2, cwd, maxOutputBytes, timeoutMs) {
799
846
  try {
800
847
  const result = spawnSync("git", [...args2], {
801
848
  cwd,
802
849
  env: sanitizedEnvironment(),
803
- encoding: "utf8",
850
+ encoding: "buffer",
804
851
  maxBuffer: maxOutputBytes,
805
852
  timeout: timeoutMs
806
853
  });
854
+ const stdout = decodeCommandStdout(result.stdout);
807
855
  return {
808
856
  status: result.status ?? -1,
809
- stdout: typeof result.stdout === "string" ? result.stdout : "",
810
- stderr: typeof result.stderr === "string" ? result.stderr : "",
811
- timedOut: isCommandTimeout(result.error)
857
+ stdout: stdout.text,
858
+ stderr: Buffer.isBuffer(result.stderr) ? result.stderr.toString("utf8") : "",
859
+ timedOut: isCommandTimeout(result.error),
860
+ ...stdout.invalid ? { invalidOutput: true } : {}
812
861
  };
813
862
  } catch {
814
863
  return { status: -1, stdout: "", stderr: "" };
815
864
  }
816
865
  }
866
+ function withForcedGitPrefix(runner) {
867
+ return (args2, cwd, maxOutputBytes, timeoutMs) => runner([...FORCED_GIT_PREFIX, ...args2], cwd, maxOutputBytes, timeoutMs);
868
+ }
817
869
  function defaultRemoteCommandRunner(executable, args2, cwd, maxOutputBytes, timeoutMs) {
818
870
  try {
819
871
  const result = spawnSync(executable, [...args2], {
@@ -838,6 +890,7 @@ function mergeLimits(input) {
838
890
  maxCommandOutputBytes: input?.maxCommandOutputBytes ?? DEFAULT_LIMITS.maxCommandOutputBytes,
839
891
  maxCommandTimeoutMs: input?.maxCommandTimeoutMs ?? DEFAULT_LIMITS.maxCommandTimeoutMs,
840
892
  maxFiles: input?.maxFiles ?? DEFAULT_LIMITS.maxFiles,
893
+ maxGitlinks: input?.maxGitlinks ?? DEFAULT_LIMITS.maxGitlinks,
841
894
  maxRemoteCommandOutputBytes: input?.maxRemoteCommandOutputBytes ?? DEFAULT_LIMITS.maxRemoteCommandOutputBytes,
842
895
  maxRemoteItems: input?.maxRemoteItems ?? DEFAULT_LIMITS.maxRemoteItems,
843
896
  maxTotalFileBytes: input?.maxTotalFileBytes ?? DEFAULT_LIMITS.maxTotalFileBytes,
@@ -860,10 +913,10 @@ function parseStageEntries(output, maxPathBytes) {
860
913
  const relativePath = record.slice(separator + 1);
861
914
  if (outputBytes(relativePath) > maxPathBytes)
862
915
  return;
863
- const [mode] = header.split(" ");
864
- if (!mode)
916
+ const [mode, id] = header.split(" ");
917
+ if (!mode || !id || !GIT_OBJECT_ID.test(id))
865
918
  return;
866
- entries.push({ record, mode, relativePath });
919
+ entries.push({ mode, id: id.toLowerCase(), relativePath });
867
920
  }
868
921
  return entries.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
869
922
  }
@@ -877,23 +930,37 @@ function safePath(root, relativePath) {
877
930
  }
878
931
  return absolutePath;
879
932
  }
880
- function runCommand(runner, args2, cwd, limits) {
933
+ function commandResultError(result, limits) {
934
+ if (result.timedOut)
935
+ return "command-timeout";
936
+ if (result.invalidOutput)
937
+ return "file-read-failed";
938
+ if (outputBytes(result.stdout) > limits.maxCommandOutputBytes || outputBytes(result.stderr) > limits.maxCommandOutputBytes) {
939
+ return "command-output-limit";
940
+ }
941
+ return;
942
+ }
943
+ function runCommandAllowingExit(runner, args2, cwd, limits, acceptedExits) {
881
944
  let result;
882
945
  try {
883
946
  result = runner(args2, cwd, limits.maxCommandOutputBytes, limits.maxCommandTimeoutMs);
884
947
  } catch {
885
948
  return { status: "error", reasonCode: "command-failed" };
886
949
  }
887
- if (result.timedOut) {
888
- return { status: "error", reasonCode: "command-timeout" };
889
- }
890
- if (outputBytes(result.stdout) > limits.maxCommandOutputBytes || outputBytes(result.stderr) > limits.maxCommandOutputBytes) {
891
- return { status: "error", reasonCode: "command-output-limit" };
892
- }
893
- if (result.status !== 0) {
950
+ const resultError = commandResultError(result, limits);
951
+ if (resultError)
952
+ return { status: "error", reasonCode: resultError };
953
+ if (!acceptedExits.includes(result.status)) {
894
954
  return { status: "error", reasonCode: "command-failed" };
895
955
  }
896
- return { status: "ok", output: { stdout: result.stdout } };
956
+ return {
957
+ status: "ok",
958
+ output: { stdout: result.stdout },
959
+ exitCode: result.status
960
+ };
961
+ }
962
+ function runCommand(runner, args2, cwd, limits) {
963
+ return runCommandAllowingExit(runner, args2, cwd, limits, [0]);
897
964
  }
898
965
  function canonicalPath(filePath, realPath = fs6.realpathSync) {
899
966
  try {
@@ -913,7 +980,7 @@ function requiredGitPath(runner, args2, cwd, limits, realPath = fs6.realpathSync
913
980
  const value = canonicalPath(rawValue, realPath);
914
981
  return value === undefined ? { status: "error", reasonCode: "target-unavailable" } : { status: "ok", value };
915
982
  }
916
- function captureParentIdentity(targetDirectory, runner, limits, realPath = fs6.realpathSync) {
983
+ function captureRootPin(targetDirectory, runner, limits, realPath) {
917
984
  const targetRoot = requiredGitPath(runner, ["rev-parse", "--show-toplevel"], targetDirectory, limits, realPath);
918
985
  if (targetRoot.status === "error")
919
986
  return targetRoot;
@@ -921,6 +988,19 @@ function captureParentIdentity(targetDirectory, runner, limits, realPath = fs6.r
921
988
  if (gitDir.status === "error")
922
989
  return gitDir;
923
990
  const commonDir = requiredGitPath(runner, ["rev-parse", "--path-format=absolute", "--git-common-dir"], targetDirectory, limits, realPath);
991
+ if (commonDir.status === "error")
992
+ return commonDir;
993
+ return {
994
+ status: "ok",
995
+ pin: {
996
+ targetRoot: targetRoot.value,
997
+ gitDir: gitDir.value,
998
+ commonDir: commonDir.value
999
+ }
1000
+ };
1001
+ }
1002
+ function captureParentIdentity(targetDirectory, pin, runner, limits, realPath = fs6.realpathSync) {
1003
+ const commonDir = requiredGitPath(runner, ["rev-parse", "--path-format=absolute", "--git-common-dir"], targetDirectory, limits, realPath);
924
1004
  if (commonDir.status === "error")
925
1005
  return commonDir;
926
1006
  const worktreeList = runCommand(runner, ["worktree", "list", "--porcelain", "-z"], targetDirectory, limits);
@@ -934,8 +1014,8 @@ function captureParentIdentity(targetDirectory, runner, limits, realPath = fs6.r
934
1014
  return roots.length > 0 ? {
935
1015
  status: "ok",
936
1016
  identity: {
937
- targetRoot: targetRoot.value,
938
- gitDir: gitDir.value,
1017
+ targetRoot: pin.targetRoot,
1018
+ gitDir: pin.gitDir,
939
1019
  commonDir: commonDir.value,
940
1020
  registeredWorktreeRoots: roots
941
1021
  }
@@ -995,7 +1075,7 @@ function validateDotGitLinkage(targetRoot, gitDir, commonDir, realPath) {
995
1075
  return backlinkStat.isFile() && !backlinkStat.isSymbolicLink() && readGitdirBacklink(backlinkPath, realPath) === canonicalPath(dotGit, realPath);
996
1076
  }
997
1077
  function validateRegisteredWorktree(candidateDirectory, parentIdentity, options = {}) {
998
- const runner = options.commandRunner ?? defaultCommandRunner;
1078
+ const runner = options.commandRunner ?? withForcedGitPrefix(defaultCommandRunner);
999
1079
  const limits = mergeLimits(options.limits);
1000
1080
  const realPath = options.realPath ?? fs6.realpathSync;
1001
1081
  const candidateRoot = canonicalPath(candidateDirectory, realPath);
@@ -1030,175 +1110,688 @@ function validateRegisteredWorktree(candidateDirectory, parentIdentity, options
1030
1110
  commonDir: commonDir.value
1031
1111
  };
1032
1112
  }
1033
- function readRevision(runner, context, limits) {
1113
+ function readRevision(runner, context, head, insideWorkTree, limits) {
1034
1114
  const branch = runCommand(runner, ["symbolic-ref", "--short", "HEAD"], context.commandDirectory, limits);
1035
1115
  if (branch.status === "error" && branch.reasonCode !== "command-failed") {
1036
1116
  return branch;
1037
1117
  }
1038
1118
  const branchValue = branch.status === "ok" ? branch.output.stdout.trim() : "detached";
1039
- let head;
1040
- try {
1041
- head = runner(["rev-parse", "--verify", "HEAD"], context.commandDirectory, limits.maxCommandOutputBytes, limits.maxCommandTimeoutMs);
1042
- } catch {
1043
- return { status: "error", reasonCode: "command-failed" };
1044
- }
1045
- if (head.timedOut) {
1046
- return { status: "error", reasonCode: "command-timeout" };
1047
- }
1048
- if (outputBytes(head.stdout) > limits.maxCommandOutputBytes || outputBytes(head.stderr) > limits.maxCommandOutputBytes) {
1049
- return { status: "error", reasonCode: "command-output-limit" };
1050
- }
1051
- const headValue = head.status === 0 ? head.stdout.trim() : "unborn";
1052
- const inside = runCommand(runner, ["rev-parse", "--is-inside-work-tree"], context.commandDirectory, limits);
1053
- if (inside.status === "error")
1054
- return inside;
1055
1119
  return {
1056
1120
  status: "ok",
1057
1121
  digest: digest("repository-revision", [
1058
- headValue,
1122
+ head ?? "unborn",
1059
1123
  branchValue,
1060
- inside.output.stdout.trim()
1124
+ String(insideWorkTree)
1061
1125
  ])
1062
1126
  };
1063
1127
  }
1128
+ function readRepositoryAnchor(runner, cwd, limits, realPath) {
1129
+ const result = runCommandAllowingExit(runner, [
1130
+ "rev-parse",
1131
+ "--show-toplevel",
1132
+ "--absolute-git-dir",
1133
+ "--git-path",
1134
+ "info/exclude",
1135
+ "--is-inside-work-tree",
1136
+ "--path-format=absolute",
1137
+ "--git-common-dir",
1138
+ "--verify",
1139
+ "-q",
1140
+ "HEAD"
1141
+ ], cwd, limits, [0, 1]);
1142
+ if (result.status === "error")
1143
+ return result;
1144
+ const lines = result.output.stdout.split(`
1145
+ `);
1146
+ if (lines.at(-1) === "")
1147
+ lines.pop();
1148
+ const unborn = result.exitCode === 1 && lines.length === 5;
1149
+ if (result.exitCode !== 0 && !unborn) {
1150
+ return { status: "error", reasonCode: "command-failed" };
1151
+ }
1152
+ const [
1153
+ toplevelLine,
1154
+ gitDirLine,
1155
+ excludeLine,
1156
+ insideLine,
1157
+ commonDirLine,
1158
+ headLine
1159
+ ] = lines;
1160
+ const malformed = lines.length !== (unborn ? 5 : 6) || commonDirLine === undefined || insideLine !== "true" && insideLine !== "false" || toplevelLine === undefined || gitDirLine === undefined || excludeLine === undefined || excludeLine.length === 0 || outputBytes(toplevelLine) > limits.maxPathBytes || headLine !== undefined && !GIT_OBJECT_ID.test(headLine);
1161
+ if (malformed)
1162
+ return { status: "error", reasonCode: "target-unavailable" };
1163
+ const toplevel = absoluteCanonicalPath(toplevelLine, realPath);
1164
+ const gitDir = absoluteCanonicalPath(gitDirLine, realPath);
1165
+ const commonDir = absoluteCanonicalPath(commonDirLine, realPath);
1166
+ if (toplevel === undefined || gitDir === undefined || commonDir === undefined) {
1167
+ return { status: "error", reasonCode: "target-unavailable" };
1168
+ }
1169
+ return {
1170
+ status: "ok",
1171
+ toplevel,
1172
+ gitDir,
1173
+ commonDir,
1174
+ head: headLine?.toLowerCase(),
1175
+ infoExcludePath: path5.resolve(cwd, excludeLine),
1176
+ insideWorkTree: insideLine === "true"
1177
+ };
1178
+ }
1179
+ function absoluteCanonicalPath(value, realPath) {
1180
+ return path5.isAbsolute(value) ? canonicalPath(value, realPath) : undefined;
1181
+ }
1064
1182
  function isEnoent(error) {
1065
1183
  return error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
1066
1184
  }
1067
- function appendSubmoduleFact(hash, runner, submodulePath, relativePath, limits, totalBytes) {
1068
- const submodule = runCommand(runner, ["rev-parse", "--verify", "HEAD"], submodulePath, limits);
1069
- if (submodule.status === "error")
1070
- return submodule;
1071
- const revision = submodule.output.stdout.trim();
1072
- if (!/^[0-9a-f]{40}$/i.test(revision)) {
1185
+ function observed(absolutePath, record, stat, displacedByDirectory = false) {
1186
+ return {
1187
+ status: "ok",
1188
+ observation: {
1189
+ absolutePath,
1190
+ record,
1191
+ stat,
1192
+ ...displacedByDirectory ? { displacedByDirectory: true } : {}
1193
+ }
1194
+ };
1195
+ }
1196
+ function hashField(hash, field) {
1197
+ const bytes = typeof field === "string" ? Buffer.from(field) : field;
1198
+ hash.update(`${bytes.byteLength}:`);
1199
+ hash.update(bytes);
1200
+ }
1201
+ function gitBlobId(content, format) {
1202
+ return createHash(format).update(`blob ${content.byteLength}\x00`).update(content).digest("hex");
1203
+ }
1204
+ function missingObservation(absolutePath, relativePath, displacedByDirectory = false) {
1205
+ return observed(absolutePath, { path: relativePath, kind: "missing", mode: "", id: undefined }, undefined, displacedByDirectory);
1206
+ }
1207
+ function vanishedPath(tracked, absolutePath, relativePath) {
1208
+ return tracked ? missingObservation(absolutePath, relativePath) : { status: "error", reasonCode: "worktree-unstable" };
1209
+ }
1210
+ function sameStat(left, right) {
1211
+ return left.isFile === right.isFile && left.isSymbolicLink === right.isSymbolicLink && left.mode === right.mode && left.size === right.size && left.dev === right.dev && left.ino === right.ino && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
1212
+ }
1213
+ function hasErrorCode(error, ...codes) {
1214
+ return error !== null && typeof error === "object" && "code" in error && typeof error.code === "string" && codes.includes(error.code);
1215
+ }
1216
+ function openWithoutFollowing(absolutePath) {
1217
+ const flags2 = fs6.constants.O_RDONLY | (fs6.constants.O_NOFOLLOW ?? 0) | (fs6.constants.O_NONBLOCK ?? 0);
1218
+ try {
1219
+ return { status: "ok", fd: fs6.openSync(absolutePath, flags2) };
1220
+ } catch (error) {
1221
+ if (isEnoent(error))
1222
+ return { status: "missing" };
1223
+ if (hasErrorCode(error, "ELOOP", "EMLINK")) {
1224
+ return { status: "error", reasonCode: "worktree-unstable" };
1225
+ }
1073
1226
  return { status: "error", reasonCode: "file-read-failed" };
1074
1227
  }
1075
- hash.update("gitlink\x00");
1076
- hash.update(relativePath);
1077
- hash.update("\x00");
1078
- hash.update(revision.toLowerCase());
1079
- hash.update("\x00");
1080
- return { status: "ok", totalBytes };
1081
1228
  }
1082
- function appendSymlinkFact(hash, symlinkReader, absolutePath, relativePath, limits, totalBytes) {
1083
- let target;
1229
+ function readOpenedRegularFile(fd, expected, maxBytes) {
1230
+ const opened = fs6.fstatSync(fd, { bigint: true });
1231
+ const identityKnown = expected.dev !== undefined && expected.ino !== undefined;
1232
+ if (!opened.isFile() || identityKnown && (opened.dev !== BigInt(expected.dev ?? 0) || opened.ino !== BigInt(expected.ino ?? 0))) {
1233
+ return { status: "error", reasonCode: "worktree-unstable" };
1234
+ }
1235
+ let buffer = Buffer.allocUnsafe(Math.min(Math.max(expected.size, 0), maxBytes) + 1);
1236
+ let total = 0;
1237
+ for (;; ) {
1238
+ if (total === buffer.length) {
1239
+ const grown = Buffer.allocUnsafe(Math.min(buffer.length * 2, maxBytes + 1));
1240
+ buffer.copy(grown, 0, 0, total);
1241
+ buffer = grown;
1242
+ }
1243
+ const count = fs6.readSync(fd, buffer, total, buffer.length - total, null);
1244
+ if (count === 0)
1245
+ break;
1246
+ total += count;
1247
+ if (total > maxBytes) {
1248
+ return { status: "error", reasonCode: "file-output-limit" };
1249
+ }
1250
+ }
1251
+ return { status: "ok", content: buffer.subarray(0, total) };
1252
+ }
1253
+ function readRegularFileHardened(absolutePath, expected, maxBytes) {
1254
+ const opened = openWithoutFollowing(absolutePath);
1255
+ if (opened.status !== "ok")
1256
+ return opened;
1084
1257
  try {
1085
- target = symlinkReader(absolutePath);
1258
+ return readOpenedRegularFile(opened.fd, expected, maxBytes);
1259
+ } catch {
1260
+ return { status: "error", reasonCode: "file-read-failed" };
1261
+ } finally {
1262
+ try {
1263
+ fs6.closeSync(opened.fd);
1264
+ } catch {}
1265
+ }
1266
+ }
1267
+ function adaptInjectedFileReader(fileReader) {
1268
+ return (absolutePath) => {
1269
+ try {
1270
+ return { status: "ok", content: fileReader(absolutePath) };
1271
+ } catch (error) {
1272
+ return isEnoent(error) ? { status: "missing" } : { status: "error", reasonCode: "file-read-failed" };
1273
+ }
1274
+ };
1275
+ }
1276
+ function directoryEmptiness(absolutePath) {
1277
+ let directory;
1278
+ try {
1279
+ directory = fs6.opendirSync(absolutePath);
1086
1280
  } catch (error) {
1087
- return isEnoent(error) ? { status: "ok", totalBytes } : { status: "error", reasonCode: "file-read-failed" };
1281
+ return hasErrorCode(error, "ENOENT", "ENOTDIR") ? "empty" : "unreadable";
1088
1282
  }
1089
- const targetBytes = Buffer.from(target, "utf8");
1090
- const nextTotalBytes = totalBytes + targetBytes.byteLength;
1091
- if (targetBytes.byteLength > limits.maxPathBytes || nextTotalBytes > limits.maxTotalFileBytes) {
1092
- return { status: "error", reasonCode: "file-output-limit" };
1283
+ try {
1284
+ return directory.readSync() === null ? "empty" : "non-empty";
1285
+ } catch {
1286
+ return "unreadable";
1287
+ } finally {
1288
+ try {
1289
+ directory.closeSync();
1290
+ } catch {}
1093
1291
  }
1094
- hash.update("symlink\x00");
1095
- hash.update(relativePath);
1096
- hash.update("\x00");
1097
- hash.update(targetBytes);
1098
- hash.update("\x00");
1099
- return { status: "ok", totalBytes: nextTotalBytes };
1100
1292
  }
1101
- function appendRegularFact(hash, fileReader, absolutePath, relativePath, stat, limits, totalBytes) {
1102
- if (!stat.isFile || !Number.isSafeInteger(stat.size) || stat.size < 0) {
1293
+ function readInitializedGitlink(readers, absolutePath, limits) {
1294
+ const result = runCommand(readers.runner, ["rev-parse", "--show-toplevel", "--verify", "-q", "HEAD"], absolutePath, limits);
1295
+ if (result.status === "error")
1296
+ return result;
1297
+ const lines = result.output.stdout.split(`
1298
+ `);
1299
+ if (lines.at(-1) === "")
1300
+ lines.pop();
1301
+ const [toplevel, id] = lines;
1302
+ if (lines.length !== 2 || toplevel === undefined || id === undefined || !GIT_OBJECT_ID.test(id) || !path5.isAbsolute(toplevel)) {
1103
1303
  return { status: "error", reasonCode: "file-read-failed" };
1104
1304
  }
1105
- if (totalBytes + stat.size > limits.maxTotalFileBytes) {
1106
- return { status: "error", reasonCode: "file-output-limit" };
1305
+ const submodule = canonicalPath(absolutePath, readers.realPath);
1306
+ const reported = canonicalPath(toplevel, readers.realPath);
1307
+ return submodule !== undefined && submodule === reported ? { status: "initialized", id: id.toLowerCase() } : { status: "error", reasonCode: "file-read-failed" };
1308
+ }
1309
+ function inspectGitlink(readers, absolutePath, limits) {
1310
+ let directory;
1311
+ try {
1312
+ directory = readers.statReader(absolutePath);
1313
+ } catch (error) {
1314
+ return hasErrorCode(error, "ENOENT", "ENOTDIR") ? { status: "absent" } : { status: "error", reasonCode: "file-read-failed" };
1315
+ }
1316
+ if (!directory.isDirectory) {
1317
+ return { status: "error", reasonCode: "file-read-failed" };
1107
1318
  }
1108
- let content;
1109
1319
  try {
1110
- content = fileReader(absolutePath);
1320
+ readers.statReader(path5.join(absolutePath, ".git"));
1111
1321
  } catch (error) {
1112
- return isEnoent(error) ? { status: "ok", totalBytes } : { status: "error", reasonCode: "file-read-failed" };
1322
+ if (!isEnoent(error)) {
1323
+ return { status: "error", reasonCode: "file-read-failed" };
1324
+ }
1325
+ switch (directoryEmptiness(absolutePath)) {
1326
+ case "empty":
1327
+ return { status: "uninitialized" };
1328
+ case "non-empty":
1329
+ case "unreadable":
1330
+ return { status: "error", reasonCode: "file-read-failed" };
1331
+ }
1113
1332
  }
1114
- if (totalBytes + content.byteLength > limits.maxTotalFileBytes) {
1333
+ return readInitializedGitlink(readers, absolutePath, limits);
1334
+ }
1335
+ function appendSubmoduleFact(hash, readers, absolutePath, relativePath, limits) {
1336
+ const inspected = inspectGitlink(readers, absolutePath, limits);
1337
+ if (inspected.status === "error")
1338
+ return inspected;
1339
+ if (inspected.status === "absent") {
1340
+ return missingObservation(absolutePath, relativePath);
1341
+ }
1342
+ const id = inspected.status === "initialized" ? inspected.id : undefined;
1343
+ hash.update("gitlink");
1344
+ hashField(hash, relativePath);
1345
+ hashField(hash, id ?? "uninitialized");
1346
+ return observed(absolutePath, { path: relativePath, kind: "gitlink", mode: "160000", id }, undefined);
1347
+ }
1348
+ function appendSymlinkFact(hash, readers, absolutePath, relativePath, stat, limits, budget, format, tracked) {
1349
+ let target;
1350
+ try {
1351
+ target = readers.symlinkReader(absolutePath);
1352
+ } catch (error) {
1353
+ return isEnoent(error) ? vanishedPath(tracked, absolutePath, relativePath) : { status: "error", reasonCode: "file-read-failed" };
1354
+ }
1355
+ const nextBytes = budget.bytes + target.byteLength;
1356
+ if (target.byteLength > limits.maxPathBytes || nextBytes > limits.maxTotalFileBytes) {
1357
+ return { status: "error", reasonCode: "file-output-limit" };
1358
+ }
1359
+ hash.update("symlink");
1360
+ hashField(hash, relativePath);
1361
+ hashField(hash, target);
1362
+ budget.bytes = nextBytes;
1363
+ return observed(absolutePath, {
1364
+ path: relativePath,
1365
+ kind: "symlink",
1366
+ mode: "120000",
1367
+ id: gitBlobId(target, format)
1368
+ }, stat);
1369
+ }
1370
+ function appendRegularFact(hash, readers, absolutePath, relativePath, stat, limits, budget, format, tracked) {
1371
+ if (!stat.isFile || !Number.isSafeInteger(stat.size) || stat.size < 0) {
1372
+ return { status: "error", reasonCode: "file-read-failed" };
1373
+ }
1374
+ const remaining = limits.maxTotalFileBytes - budget.bytes;
1375
+ if (stat.size > remaining) {
1376
+ return { status: "error", reasonCode: "file-output-limit" };
1377
+ }
1378
+ const read = readers.readRegular(absolutePath, stat, remaining);
1379
+ if (read.status === "missing")
1380
+ return vanishedPath(tracked, absolutePath, relativePath);
1381
+ if (read.status === "error")
1382
+ return read;
1383
+ const { content } = read;
1384
+ if (content.byteLength > remaining) {
1115
1385
  return { status: "error", reasonCode: "file-output-limit" };
1116
1386
  }
1117
- hash.update("regular\x00");
1118
- hash.update(relativePath);
1119
- hash.update("\x00");
1120
- hash.update((stat.mode & 73) !== 0 ? "executable\x00" : "non-executable\x00");
1121
- hash.update(content);
1122
- hash.update("\x00");
1123
- return { status: "ok", totalBytes: totalBytes + content.byteLength };
1387
+ hash.update("regular");
1388
+ hashField(hash, relativePath);
1389
+ hashField(hash, (stat.mode & 73) !== 0 ? "executable" : "non-executable");
1390
+ hashField(hash, content);
1391
+ budget.bytes += content.byteLength;
1392
+ return observed(absolutePath, {
1393
+ path: relativePath,
1394
+ kind: "regular",
1395
+ mode: (stat.mode & 64) !== 0 ? "100755" : "100644",
1396
+ id: gitBlobId(content, format)
1397
+ }, stat);
1398
+ }
1399
+ function checkAncestorDirectories(worktreeRoot, relativePath, verified) {
1400
+ const parts2 = relativePath.split("/").slice(0, -1);
1401
+ let current = worktreeRoot;
1402
+ for (const part of parts2) {
1403
+ current = path5.join(current, part);
1404
+ if (verified.has(current))
1405
+ continue;
1406
+ let stat;
1407
+ try {
1408
+ stat = fs6.lstatSync(current);
1409
+ } catch (error) {
1410
+ if (hasErrorCode(error, "ENOENT", "ENOTDIR"))
1411
+ return { status: "ok" };
1412
+ return { status: "error", reasonCode: "file-read-failed" };
1413
+ }
1414
+ if (stat.isSymbolicLink()) {
1415
+ return { status: "error", reasonCode: "file-read-failed" };
1416
+ }
1417
+ if (!stat.isDirectory())
1418
+ return { status: "ok" };
1419
+ verified.add(current);
1420
+ }
1421
+ return { status: "ok" };
1422
+ }
1423
+ function verifyAncestorsUnchanged(verified) {
1424
+ for (const directory of verified) {
1425
+ try {
1426
+ const stat = fs6.lstatSync(directory);
1427
+ if (stat.isSymbolicLink() || !stat.isDirectory())
1428
+ return UNSTABLE;
1429
+ } catch (error) {
1430
+ if (!hasErrorCode(error, "ENOENT", "ENOTDIR")) {
1431
+ return { status: "error", reasonCode: "file-read-failed" };
1432
+ }
1433
+ return UNSTABLE;
1434
+ }
1435
+ }
1436
+ return { status: "ok" };
1124
1437
  }
1125
- function appendFileFactV2(hash, runner, fileReader, symlinkReader, statReader, context, entry, limits, totalBytes) {
1438
+ function appendPathFact(hash, readers, context, entry, limits, budget, format, verifiedDirectories) {
1126
1439
  const { mode, relativePath } = entry;
1127
1440
  const absolutePath = safePath(context.worktreeRoot, relativePath);
1128
1441
  if (!absolutePath || outputBytes(relativePath) > limits.maxPathBytes) {
1129
1442
  return { status: "error", reasonCode: "file-read-failed" };
1130
1443
  }
1444
+ const ancestors = checkAncestorDirectories(context.worktreeRoot, relativePath, verifiedDirectories);
1445
+ if (ancestors.status === "error")
1446
+ return ancestors;
1447
+ const tracked = mode !== "";
1448
+ if (entry.displacedGitlink) {
1449
+ return missingObservation(absolutePath, relativePath, true);
1450
+ }
1451
+ if (mode === "160000") {
1452
+ return appendSubmoduleFact(hash, readers, absolutePath, relativePath, limits);
1453
+ }
1131
1454
  let stat;
1132
1455
  try {
1133
- stat = statReader(absolutePath);
1456
+ stat = readers.statReader(absolutePath);
1134
1457
  } catch (error) {
1135
- return isEnoent(error) ? { status: "ok", totalBytes } : { status: "error", reasonCode: "file-read-failed" };
1458
+ return hasErrorCode(error, "ENOENT", "ENOTDIR") ? vanishedPath(tracked, absolutePath, relativePath) : { status: "error", reasonCode: "file-read-failed" };
1136
1459
  }
1137
- if (mode === "160000")
1138
- return appendSubmoduleFact(hash, runner, absolutePath, relativePath, limits, totalBytes);
1139
- if (stat.isSymbolicLink) {
1140
- return appendSymlinkFact(hash, symlinkReader, absolutePath, relativePath, limits, totalBytes);
1460
+ if (tracked && stat.isDirectory && !stat.isSymbolicLink) {
1461
+ return missingObservation(absolutePath, relativePath, true);
1141
1462
  }
1142
- return appendRegularFact(hash, fileReader, absolutePath, relativePath, stat, limits, totalBytes);
1463
+ return stat.isSymbolicLink ? appendSymlinkFact(hash, readers, absolutePath, relativePath, stat, limits, budget, format, tracked) : appendRegularFact(hash, readers, absolutePath, relativePath, stat, limits, budget, format, tracked);
1143
1464
  }
1144
- function readWorktreeRevisionV2(runner, fileReader, symlinkReader, statReader, context, limits) {
1145
- const tracked = runCommand(runner, ["ls-files", "--full-name", "-z", "--", ":/"], context.commandDirectory, limits);
1146
- if (tracked.status === "error")
1147
- return tracked;
1148
- const staged = runCommand(runner, ["ls-files", "--stage", "--full-name", "-z", "--", ":/"], context.commandDirectory, limits);
1465
+ function listWorktreePaths(runner, context, limits) {
1466
+ const staged = runCommand(runner, STAGE_LIST_ARGS, context.commandDirectory, limits);
1149
1467
  if (staged.status === "error")
1150
1468
  return staged;
1151
1469
  const untracked = runCommand(runner, UNTRACKED_FILES_ARGS, context.commandDirectory, limits);
1152
1470
  if (untracked.status === "error")
1153
1471
  return untracked;
1154
- const stageEntries = parseStageEntries(staged.output.stdout, limits.maxPathBytes);
1472
+ const ignoredGitignores = runCommand(runner, IGNORED_GITIGNORE_ARGS, context.commandDirectory, limits);
1473
+ if (ignoredGitignores.status === "error")
1474
+ return ignoredGitignores;
1475
+ return {
1476
+ status: "ok",
1477
+ staged: staged.output.stdout,
1478
+ untracked: untracked.output.stdout,
1479
+ ignoredGitignores: ignoredGitignores.output.stdout
1480
+ };
1481
+ }
1482
+ var UNSTABLE = {
1483
+ status: "error",
1484
+ reasonCode: "worktree-unstable"
1485
+ };
1486
+ function verifyGitlinkUnchanged(readers, limits, { absolutePath, record }) {
1487
+ const fresh = inspectGitlink(readers, absolutePath, limits);
1488
+ if (fresh.status === "error") {
1489
+ return fresh.reasonCode === "file-read-failed" ? UNSTABLE : fresh;
1490
+ }
1491
+ if (fresh.status === "absent")
1492
+ return UNSTABLE;
1493
+ const id = fresh.status === "initialized" ? fresh.id : undefined;
1494
+ return id === record.id ? { status: "ok" } : UNSTABLE;
1495
+ }
1496
+ function verifyObservationUnchanged(readers, limits, observation) {
1497
+ const { absolutePath, record, stat } = observation;
1498
+ if (record.kind === "gitlink") {
1499
+ return verifyGitlinkUnchanged(readers, limits, observation);
1500
+ }
1501
+ let fresh;
1502
+ try {
1503
+ fresh = readers.statReader(absolutePath);
1504
+ } catch (error) {
1505
+ if (!hasErrorCode(error, "ENOENT", "ENOTDIR")) {
1506
+ return { status: "error", reasonCode: "file-read-failed" };
1507
+ }
1508
+ return record.kind === "missing" ? { status: "ok" } : UNSTABLE;
1509
+ }
1510
+ if (record.kind === "missing") {
1511
+ const stillDisplaced = observation.displacedByDirectory === true && fresh.isDirectory && !fresh.isSymbolicLink;
1512
+ return stillDisplaced ? { status: "ok" } : UNSTABLE;
1513
+ }
1514
+ if (stat === undefined)
1515
+ return UNSTABLE;
1516
+ return sameStat(stat, fresh) ? { status: "ok" } : UNSTABLE;
1517
+ }
1518
+ function verifyObservationsUnchanged(readers, limits, observations) {
1519
+ for (const observation of observations) {
1520
+ const result = verifyObservationUnchanged(readers, limits, observation);
1521
+ if (result.status === "error")
1522
+ return result;
1523
+ }
1524
+ return { status: "ok" };
1525
+ }
1526
+ function verifyListingsUnchanged(runner, context, limits, first) {
1527
+ const fresh = listWorktreePaths(runner, context, limits);
1528
+ if (fresh.status === "error")
1529
+ return fresh;
1530
+ return fresh.staged === first.staged && fresh.untracked === first.untracked && fresh.ignoredGitignores === first.ignoredGitignores ? { status: "ok" } : UNSTABLE;
1531
+ }
1532
+ function verifyIgnoreSourcesUnchanged(runner, context, limits, first) {
1533
+ const fresh = readIgnoreSources(runner, context, limits);
1534
+ if (fresh.status === "error")
1535
+ return fresh;
1536
+ return sameIgnoreSources(first.ignoreSources, fresh.facts) ? { status: "ok" } : UNSTABLE;
1537
+ }
1538
+ function verifyAnchorUnchanged(readers, context, limits, head) {
1539
+ const anchor = readRepositoryAnchor(readers.runner, context.commandDirectory, limits, readers.realPath);
1540
+ if (anchor.status === "error")
1541
+ return anchor;
1542
+ const { pin } = context;
1543
+ if (anchor.toplevel !== pin.targetRoot || anchor.gitDir !== pin.gitDir || anchor.commonDir !== pin.commonDir) {
1544
+ return { status: "error", reasonCode: "target-unavailable" };
1545
+ }
1546
+ return anchor.head === head ? { status: "ok" } : UNSTABLE;
1547
+ }
1548
+ function runFinalPass(readers, context, limits, head, first, observations, verifiedDirectories) {
1549
+ const sources = verifyIgnoreSourcesUnchanged(readers.runner, context, limits, first);
1550
+ if (sources.status === "error")
1551
+ return sources;
1552
+ const ancestors = verifyAncestorsUnchanged(verifiedDirectories);
1553
+ if (ancestors.status === "error")
1554
+ return ancestors;
1555
+ const unchanged = verifyObservationsUnchanged(readers, limits, observations);
1556
+ if (unchanged.status === "error")
1557
+ return unchanged;
1558
+ const listings = verifyListingsUnchanged(readers.runner, context, limits, first);
1559
+ if (listings.status === "error")
1560
+ return listings;
1561
+ return verifyAnchorUnchanged(readers, context, limits, head);
1562
+ }
1563
+ function readIgnoreSourceFile(label, filePath) {
1564
+ const absent = {
1565
+ status: "ok",
1566
+ fact: { label, content: undefined }
1567
+ };
1568
+ let resolved;
1569
+ let stat;
1570
+ try {
1571
+ resolved = fs6.realpathSync(filePath);
1572
+ stat = fs6.statSync(resolved, { bigint: true });
1573
+ } catch (error) {
1574
+ return hasErrorCode(error, "ENOENT", "ENOTDIR") ? absent : { status: "error", reasonCode: "file-read-failed" };
1575
+ }
1576
+ if (!stat.isFile() || stat.size > BigInt(MAX_IGNORE_SOURCE_BYTES)) {
1577
+ return { status: "error", reasonCode: "file-read-failed" };
1578
+ }
1579
+ const read = readRegularFileHardened(resolved, {
1580
+ isFile: true,
1581
+ isSymbolicLink: false,
1582
+ isDirectory: false,
1583
+ mode: Number(stat.mode),
1584
+ size: Number(stat.size),
1585
+ dev: stat.dev,
1586
+ ino: stat.ino
1587
+ }, MAX_IGNORE_SOURCE_BYTES);
1588
+ if (read.status === "missing") {
1589
+ return { status: "error", reasonCode: "worktree-unstable" };
1590
+ }
1591
+ if (read.status === "error") {
1592
+ return {
1593
+ status: "error",
1594
+ reasonCode: read.reasonCode === "file-output-limit" ? "file-read-failed" : read.reasonCode
1595
+ };
1596
+ }
1597
+ return { status: "ok", fact: { label, content: read.content } };
1598
+ }
1599
+ function defaultExcludesFilePath() {
1600
+ const xdg = process.env.XDG_CONFIG_HOME;
1601
+ if (xdg)
1602
+ return path5.join(xdg, "git", "ignore");
1603
+ return path5.join(process.env.HOME || os3.homedir(), ".config", "git", "ignore");
1604
+ }
1605
+ function resolveExcludesFilePath(runner, context, limits) {
1606
+ const result = runCommandAllowingExit(runner, ["config", "--type=path", "--get", "core.excludesFile"], context.commandDirectory, limits, [0, 1]);
1607
+ if (result.status === "error")
1608
+ return result;
1609
+ if (result.exitCode === 1) {
1610
+ return { status: "ok", filePath: defaultExcludesFilePath() };
1611
+ }
1612
+ const configured = result.output.stdout.replace(/\n$/, "");
1613
+ return {
1614
+ status: "ok",
1615
+ filePath: configured.length === 0 ? undefined : path5.resolve(context.worktreeRoot, configured)
1616
+ };
1617
+ }
1618
+ function readIgnoreSources(runner, context, limits) {
1619
+ const infoExclude = readIgnoreSourceFile("info-exclude", context.infoExcludePath);
1620
+ if (infoExclude.status === "error")
1621
+ return infoExclude;
1622
+ const configured = resolveExcludesFilePath(runner, context, limits);
1623
+ if (configured.status === "error")
1624
+ return configured;
1625
+ const global = configured.filePath === undefined ? {
1626
+ status: "ok",
1627
+ fact: { label: "core-excludes-file", content: undefined }
1628
+ } : readIgnoreSourceFile("core-excludes-file", configured.filePath);
1629
+ if (global.status === "error")
1630
+ return global;
1631
+ return { status: "ok", facts: [infoExclude.fact, global.fact] };
1632
+ }
1633
+ function hashIgnoreSource(hash, fact) {
1634
+ hash.update("ignore-source");
1635
+ hashField(hash, fact.label);
1636
+ hashField(hash, fact.content === undefined ? "absent" : "present");
1637
+ hashField(hash, fact.content ?? "");
1638
+ }
1639
+ function sameIgnoreSources(left, right) {
1640
+ return left.length === right.length && left.every((fact, index) => {
1641
+ const other = right[index];
1642
+ if (other === undefined || fact.label !== other.label)
1643
+ return false;
1644
+ if (fact.content === undefined || other.content === undefined) {
1645
+ return fact.content === other.content;
1646
+ }
1647
+ return Buffer.compare(fact.content, other.content) === 0;
1648
+ });
1649
+ }
1650
+ function readHeadTree(runner, context, head, limits) {
1651
+ const entries = new Map;
1652
+ if (head === undefined)
1653
+ return { status: "ok", entries, ids: [] };
1654
+ const listing = runCommand(runner, ["ls-tree", "-r", "-z", "--full-tree", head], context.commandDirectory, limits);
1655
+ if (listing.status === "error")
1656
+ return listing;
1657
+ for (const record of splitRecords(listing.output.stdout)) {
1658
+ const separator = record.indexOf("\t");
1659
+ const [mode, , id] = record.slice(0, separator).split(" ");
1660
+ const entryPath = record.slice(separator + 1);
1661
+ if (separator <= 0 || !mode || !id || !/^[0-7]{6}$/.test(mode) || !GIT_OBJECT_ID.test(id) || outputBytes(entryPath) > limits.maxPathBytes) {
1662
+ return { status: "error", reasonCode: "file-read-failed" };
1663
+ }
1664
+ entries.set(entryPath, { mode, id: id.toLowerCase() });
1665
+ }
1666
+ return {
1667
+ status: "ok",
1668
+ entries,
1669
+ ids: [...entries.values()].map((entry) => entry.id)
1670
+ };
1671
+ }
1672
+ function inferObjectFormat(ids) {
1673
+ const lengths = new Set(ids.map((id) => id.length));
1674
+ if (lengths.size === 0)
1675
+ return "sha1";
1676
+ if (lengths.size > 1)
1677
+ return;
1678
+ return lengths.has(64) ? "sha256" : "sha1";
1679
+ }
1680
+ function readWorktreeListings(runner, context, headTree, limits) {
1681
+ const first = listWorktreePaths(runner, context, limits);
1682
+ if (first.status === "error")
1683
+ return first;
1684
+ const stageEntries = parseStageEntries(first.staged, limits.maxPathBytes);
1155
1685
  if (!stageEntries)
1156
1686
  return { status: "error", reasonCode: "file-read-failed" };
1157
- const modes = new Map(stageEntries.map((entry) => [entry.relativePath, entry.mode]));
1158
- const paths = [
1159
- ...new Set([
1160
- ...splitRecords(tracked.output.stdout),
1161
- ...splitRecords(untracked.output.stdout)
1162
- ])
1163
- ].sort((left, right) => Buffer.from(left).compare(Buffer.from(right)));
1687
+ const selfIgnored = splitRecords(first.ignoredGitignores).filter((entry) => !entry.endsWith("/"));
1688
+ const unique = new Set([
1689
+ ...stageEntries.map((entry) => entry.relativePath),
1690
+ ...headTree.keys(),
1691
+ ...splitRecords(first.untracked),
1692
+ ...selfIgnored
1693
+ ]);
1694
+ const paths = [...unique].map((entry) => ({ entry, key: Buffer.from(entry) })).sort((left, right) => left.key.compare(right.key)).map(({ entry }) => entry);
1695
+ return { status: "ok", first, stageEntries, paths };
1696
+ }
1697
+ function hasPathBeneath(sortedPaths, directory) {
1698
+ const prefix = `${directory}/`;
1699
+ const key = Buffer.from(prefix);
1700
+ let low = 0;
1701
+ let high = sortedPaths.length;
1702
+ while (low < high) {
1703
+ const middle = low + high >>> 1;
1704
+ const candidate = sortedPaths[middle];
1705
+ if (candidate !== undefined && Buffer.from(candidate).compare(key) < 0) {
1706
+ low = middle + 1;
1707
+ } else {
1708
+ high = middle;
1709
+ }
1710
+ }
1711
+ return low < sortedPaths.length && (sortedPaths[low]?.startsWith(prefix) ?? false);
1712
+ }
1713
+ function findDisplacedGitlinks(sortedPaths, indexModes, headTree) {
1714
+ const candidates = sortedPaths.filter((entry) => !indexModes.has(entry) && headTree.get(entry)?.mode === "160000");
1715
+ return new Set(candidates.filter((entry) => hasPathBeneath(sortedPaths, entry)));
1716
+ }
1717
+ function readWorktreeSnapshot(readers, context, head, limits) {
1718
+ const { runner } = readers;
1719
+ const sources = readIgnoreSources(runner, context, limits);
1720
+ if (sources.status === "error")
1721
+ return sources;
1722
+ const tree = readHeadTree(runner, context, head, limits);
1723
+ if (tree.status === "error")
1724
+ return tree;
1725
+ const listings = readWorktreeListings(runner, context, tree.entries, limits);
1726
+ if (listings.status === "error")
1727
+ return listings;
1728
+ const format = inferObjectFormat([
1729
+ ...tree.ids,
1730
+ ...listings.stageEntries.map((entry) => entry.id)
1731
+ ]);
1732
+ if (format === undefined) {
1733
+ return { status: "error", reasonCode: "file-read-failed" };
1734
+ }
1735
+ const { paths } = listings;
1164
1736
  if (paths.length > limits.maxFiles) {
1165
1737
  return { status: "error", reasonCode: "file-limit" };
1166
1738
  }
1739
+ const modes = new Map(listings.stageEntries.map((entry) => [entry.relativePath, entry.mode]));
1740
+ const modeOf = (relativePath) => modes.get(relativePath) ?? tree.entries.get(relativePath)?.mode ?? "";
1741
+ const displacedGitlinks = findDisplacedGitlinks(paths, modes, tree.entries);
1742
+ if (paths.filter((entry) => modeOf(entry) === "160000" && !displacedGitlinks.has(entry)).length > limits.maxGitlinks) {
1743
+ return { status: "error", reasonCode: "file-limit" };
1744
+ }
1167
1745
  const hash = createHash("sha256");
1168
- hash.update("systematic:opencode-observer:worktree:v2\x00");
1169
- let totalBytes = 0;
1746
+ hash.update(WORKTREE_DIGEST_DOMAIN);
1747
+ const budget = { bytes: 0 };
1748
+ const observations = [];
1749
+ const verifiedDirectories = new Set;
1170
1750
  for (const relativePath of paths) {
1171
- const result = appendFileFactV2(hash, runner, fileReader, symlinkReader, statReader, context, { relativePath, mode: modes.get(relativePath) ?? "" }, limits, totalBytes);
1751
+ const result = appendPathFact(hash, readers, context, {
1752
+ relativePath,
1753
+ mode: modeOf(relativePath),
1754
+ ...displacedGitlinks.has(relativePath) ? { displacedGitlink: true } : {}
1755
+ }, limits, budget, format, verifiedDirectories);
1172
1756
  if (result.status === "error")
1173
1757
  return result;
1174
- totalBytes = result.totalBytes;
1175
- }
1176
- return { status: "ok", digest: hash.digest("hex") };
1177
- }
1178
- function readCommitClosure(runner, context, limits) {
1179
- let diff;
1180
- try {
1181
- diff = runner(["diff", "--quiet", "HEAD", "--", ":/"], context.commandDirectory, limits.maxCommandOutputBytes, limits.maxCommandTimeoutMs);
1182
- } catch {
1183
- return { status: "error", reasonCode: "command-failed" };
1184
- }
1185
- if (diff.timedOut) {
1186
- return { status: "error", reasonCode: "command-timeout" };
1187
- }
1188
- if (outputBytes(diff.stdout) > limits.maxCommandOutputBytes || outputBytes(diff.stderr) > limits.maxCommandOutputBytes) {
1189
- return { status: "error", reasonCode: "command-output-limit" };
1758
+ observations.push(result.observation);
1190
1759
  }
1191
- if (diff.status !== 0 && diff.status !== 1) {
1192
- return { status: "error", reasonCode: "command-failed" };
1193
- }
1194
- const untracked = runCommand(runner, UNTRACKED_FILES_ARGS, context.commandDirectory, limits);
1195
- if (untracked.status === "error")
1196
- return untracked;
1760
+ for (const fact of sources.facts)
1761
+ hashIgnoreSource(hash, fact);
1762
+ const stable = runFinalPass(readers, context, limits, head, { ...listings.first, ignoreSources: sources.facts }, observations, verifiedDirectories);
1763
+ if (stable.status === "error")
1764
+ return stable;
1197
1765
  return {
1198
1766
  status: "ok",
1199
- closed: diff.status === 0 && untracked.output.stdout.length === 0
1767
+ digest: hash.digest("hex"),
1768
+ records: observations.map((observation) => observation.record),
1769
+ headTree: tree.entries
1200
1770
  };
1201
1771
  }
1772
+ function recordKindForTreeMode(mode) {
1773
+ if (mode === "120000")
1774
+ return "symlink";
1775
+ if (mode === "160000")
1776
+ return "gitlink";
1777
+ return "regular";
1778
+ }
1779
+ function recordMatchesTreeEntry(record, entry) {
1780
+ return record.id !== undefined && record.id === entry.id && record.mode === entry.mode && record.kind === recordKindForTreeMode(entry.mode);
1781
+ }
1782
+ function deriveCommitClosure(records, headTree, head) {
1783
+ if (head === undefined)
1784
+ return false;
1785
+ let matched = 0;
1786
+ for (const record of records) {
1787
+ const entry = headTree.get(record.path);
1788
+ if (entry === undefined || !recordMatchesTreeEntry(record, entry)) {
1789
+ return false;
1790
+ }
1791
+ matched += 1;
1792
+ }
1793
+ return matched === headTree.size;
1794
+ }
1202
1795
  function runRemoteCommand(runner, executable, args2, root, limits) {
1203
1796
  let result;
1204
1797
  try {
@@ -1378,6 +1971,28 @@ function readCheckReadback(runner, root, limits, pullRequest) {
1378
1971
  function readRemoteSnapshot(runner, operation, phase, commandDirectory, limits) {
1379
1972
  return operation === "push" ? readPushRemoteSnapshot(runner, phase, commandDirectory, limits) : readRemotePullRequest(runner, operation, commandDirectory, limits);
1380
1973
  }
1974
+ function resolveWorktreeReaders(runner, options) {
1975
+ return {
1976
+ runner,
1977
+ realPath: options.realPath ?? fs6.realpathSync,
1978
+ readRegular: options.fileReader ? adaptInjectedFileReader(options.fileReader) : readRegularFileHardened,
1979
+ symlinkReader: options.symlinkReader ?? ((filePath) => fs6.readlinkSync(filePath, { encoding: "buffer" })),
1980
+ statReader: options.statReader ?? ((filePath) => {
1981
+ const stat = fs6.lstatSync(filePath, { bigint: true });
1982
+ return {
1983
+ isFile: stat.isFile(),
1984
+ isSymbolicLink: stat.isSymbolicLink(),
1985
+ isDirectory: stat.isDirectory(),
1986
+ mode: Number(stat.mode),
1987
+ size: Number(stat.size),
1988
+ dev: stat.dev,
1989
+ ino: stat.ino,
1990
+ mtimeNs: stat.mtimeNs,
1991
+ ctimeNs: stat.ctimeNs
1992
+ };
1993
+ })
1994
+ };
1995
+ }
1381
1996
  function createOpencodeOperationObserver(options) {
1382
1997
  const limits = mergeLimits(options.limits);
1383
1998
  let targetDirectory;
@@ -1386,23 +2001,13 @@ function createOpencodeOperationObserver(options) {
1386
2001
  } catch {
1387
2002
  targetDirectory = path5.resolve(options.targetDirectory);
1388
2003
  }
1389
- const runner = options.commandRunner ?? defaultCommandRunner;
2004
+ const runner = withForcedGitPrefix(options.commandRunner ?? defaultCommandRunner);
1390
2005
  const remoteRunner = options.remoteCommandRunner ?? defaultRemoteCommandRunner;
1391
2006
  const realPath = options.realPath ?? fs6.realpathSync;
1392
- const parentIdentityResult = captureParentIdentity(targetDirectory, runner, limits, realPath);
2007
+ const rootPinResult = captureRootPin(targetDirectory, runner, limits, realPath);
2008
+ const parentIdentityResult = rootPinResult.status === "error" ? rootPinResult : captureParentIdentity(targetDirectory, rootPinResult.pin, runner, limits, realPath);
1393
2009
  const targetDigest = digest("target", [targetDirectory]);
1394
- const fileReader = options.fileReader ?? fs6.readFileSync;
1395
- const symlinkReader = options.symlinkReader ?? fs6.readlinkSync;
1396
- const statReader = options.statReader ?? ((filePath) => {
1397
- const stat = fs6.lstatSync(filePath);
1398
- return {
1399
- isFile: stat.isFile(),
1400
- isSymbolicLink: stat.isSymbolicLink(),
1401
- isDirectory: stat.isDirectory(),
1402
- mode: stat.mode,
1403
- size: stat.size
1404
- };
1405
- });
2010
+ const readers = resolveWorktreeReaders(runner, options);
1406
2011
  return {
1407
2012
  targetDigest,
1408
2013
  validateRegisteredWorktree(candidateDirectory) {
@@ -1411,33 +2016,33 @@ function createOpencodeOperationObserver(options) {
1411
2016
  return validateRegisteredWorktree(candidateDirectory, parentIdentityResult.identity, { commandRunner: runner, limits, realPath });
1412
2017
  },
1413
2018
  async snapshot() {
1414
- const rootResult = runCommand(runner, ["rev-parse", "--show-toplevel"], targetDirectory, limits);
1415
- if (rootResult.status === "error")
1416
- return unavailable(rootResult);
1417
- const root = rootResult.output.stdout.trim();
1418
- if (root.length === 0 || outputBytes(root) > limits.maxPathBytes) {
2019
+ const anchor = readRepositoryAnchor(runner, targetDirectory, limits, realPath);
2020
+ if (anchor.status === "error")
2021
+ return unavailable(anchor);
2022
+ if (rootPinResult.status === "error")
2023
+ return unavailable(rootPinResult);
2024
+ if (anchor.toplevel !== rootPinResult.pin.targetRoot || anchor.gitDir !== rootPinResult.pin.gitDir || anchor.commonDir !== rootPinResult.pin.commonDir) {
1419
2025
  return { status: "unavailable", reasonCode: "target-unavailable" };
1420
2026
  }
1421
2027
  const context = {
1422
2028
  commandDirectory: targetDirectory,
1423
- worktreeRoot: root
2029
+ worktreeRoot: anchor.toplevel,
2030
+ infoExcludePath: anchor.infoExcludePath,
2031
+ pin: rootPinResult.pin
1424
2032
  };
1425
- const repository = readRevision(runner, context, limits);
2033
+ const repository = readRevision(runner, context, anchor.head, anchor.insideWorkTree, limits);
1426
2034
  if (repository.status === "error")
1427
2035
  return unavailable(repository);
1428
- const worktree = readWorktreeRevisionV2(runner, fileReader, symlinkReader, statReader, context, limits);
2036
+ const worktree = readWorktreeSnapshot(readers, context, anchor.head, limits);
1429
2037
  if (worktree.status === "error")
1430
2038
  return unavailable(worktree);
1431
- const closure = readCommitClosure(runner, context, limits);
1432
- if (closure.status === "error")
1433
- return unavailable(closure);
1434
2039
  return {
1435
2040
  status: "available",
1436
2041
  snapshot: {
1437
2042
  targetDigest,
1438
2043
  repositoryRevisionDigest: repository.digest,
1439
2044
  worktreeRevisionDigest: worktree.digest,
1440
- commitClosure: closure.closed
2045
+ commitClosure: deriveCommitClosure(worktree.records, worktree.headTree, anchor.head)
1441
2046
  }
1442
2047
  };
1443
2048
  },
@@ -10331,6 +10936,7 @@ var REASON_CODES = new Set([
10331
10936
  "rejected-operation",
10332
10937
  "resource-mismatch",
10333
10938
  "running-operation",
10939
+ "snapshot-blocked",
10334
10940
  "stale-receipt",
10335
10941
  "transition-finalized",
10336
10942
  "transition-terminal",
@@ -10367,9 +10973,26 @@ function isWorkflowGuardBlockedError(value) {
10367
10973
  function defaultTargetObserver(targetDirectory) {
10368
10974
  return createOpencodeOperationObserver({ targetDirectory });
10369
10975
  }
10976
+ var TIMED_OUT_READ = { status: "timeout" };
10370
10977
  function unconfirmedReadback(probe) {
10371
10978
  return { probe, reasonCode: "command-timeout" };
10372
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
+ };
10373
10996
  function initializationCause(kind) {
10374
10997
  return { site: "initialize-session", kind, timedOut: false };
10375
10998
  }
@@ -10395,6 +11018,17 @@ function beforeCause(kind, reasonCode) {
10395
11018
  function afterCause(kind, reasonCode) {
10396
11019
  return hookCause("tool-after", kind, reasonCode);
10397
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
+ }
10398
11032
  function afterFailure(kind, reasonCode) {
10399
11033
  return { status: "unavailable", cause: afterCause(kind, reasonCode) };
10400
11034
  }
@@ -10413,7 +11047,7 @@ async function readSnapshot(observer, expectedTargetIdentity) {
10413
11047
  return { status: "fatal" };
10414
11048
  }
10415
11049
  if (isProbeTimeout(result))
10416
- return { status: "timeout" };
11050
+ return TIMED_OUT_READ;
10417
11051
  if (result.status === "unavailable") {
10418
11052
  return { status: "fatal", reasonCode: result.reasonCode };
10419
11053
  }
@@ -10422,6 +11056,9 @@ async function readSnapshot(observer, expectedTargetIdentity) {
10422
11056
  }
10423
11057
  return { status: "ok", value: result.snapshot };
10424
11058
  }
11059
+ function probeFailureReason(failure) {
11060
+ return failure.status === "timeout" ? "command-timeout" : failure.reasonCode;
11061
+ }
10425
11062
  function isProbeTimeout(result) {
10426
11063
  if (result === undefined)
10427
11064
  return false;
@@ -10544,6 +11181,9 @@ function isLocalOperationTool(tool) {
10544
11181
  function unavailableOperationTarget() {
10545
11182
  return { status: "unavailable", reasonCode: "target-unavailable" };
10546
11183
  }
11184
+ function timedOutOperationTarget() {
11185
+ return { status: "unavailable", reasonCode: "command-timeout" };
11186
+ }
10547
11187
  function canonicalExistingPath(filePath, realPath) {
10548
11188
  try {
10549
11189
  return realPath(filePath);
@@ -10571,8 +11211,9 @@ function targetIsGitAdminStorage(targetPath, validation) {
10571
11211
  return pathWithinOrEqual(path6.join(validation.targetRoot, ".git"), targetPath) || pathWithinOrEqual(validation.gitDir, targetPath) || pathWithinOrEqual(validation.commonDir, targetPath);
10572
11212
  }
10573
11213
  function targetResultFromValidation(candidatePath, validation) {
10574
- if (validation.status === "error")
10575
- return unavailableOperationTarget();
11214
+ if (validation.status === "error") {
11215
+ return isProbeTimeout(validation) ? timedOutOperationTarget() : unavailableOperationTarget();
11216
+ }
10576
11217
  if (!pathWithinOrEqual(validation.targetRoot, candidatePath)) {
10577
11218
  return unavailableOperationTarget();
10578
11219
  }
@@ -10608,21 +11249,31 @@ function deriveFileTarget(rawPath, baseDirectory, parentTargetRoot, options, rea
10608
11249
  }
10609
11250
  function sharedTargetRoot(targets, extraRoots = []) {
10610
11251
  const roots = [...extraRoots];
11252
+ let definiteFailure = false;
11253
+ let timedOut = false;
10611
11254
  for (const target of targets) {
10612
- if (target.status === "unavailable")
10613
- return;
10614
- 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;
10615
11261
  }
10616
11262
  const targetRoot = roots[0];
10617
- 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();
10618
11269
  }
10619
11270
  function deriveDirectoryTarget(rawPath, baseDirectory, parentTargetRoot, options, realPath) {
10620
11271
  const resolvedPath = canonicalExistingPath(path6.resolve(baseDirectory, rawPath), realPath);
10621
11272
  if (!resolvedPath)
10622
- return { status: "unavailable" };
11273
+ return unavailableOperationTarget();
10623
11274
  const parentResult = path6.isAbsolute(rawPath) ? undefined : trustedParentTarget(parentTargetRoot, resolvedPath);
10624
11275
  if (parentResult?.status === "unavailable") {
10625
- return { status: "unavailable" };
11276
+ return unavailableOperationTarget();
10626
11277
  }
10627
11278
  if (parentResult) {
10628
11279
  return {
@@ -10631,10 +11282,13 @@ function deriveDirectoryTarget(rawPath, baseDirectory, parentTargetRoot, options
10631
11282
  };
10632
11283
  }
10633
11284
  const validated = validationForCandidate(resolvedPath, options);
10634
- return validated.status === "available" ? {
10635
- status: "available",
10636
- target: { targetRoot: validated.targetRoot, resolvedPath }
10637
- } : { 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;
10638
11292
  }
10639
11293
  var PATCH_FILE_PREFIXES = [
10640
11294
  "*** Add File:",
@@ -10697,8 +11351,7 @@ function deriveFileOperationTarget(args2, sessionLocation, parentTargetRoot, opt
10697
11351
  if (!paths)
10698
11352
  return unavailableOperationTarget();
10699
11353
  const targets = paths.map((rawPath) => deriveFileTarget(rawPath, sessionLocation, parentTargetRoot, options, realPath));
10700
- const targetRoot = sharedTargetRoot(targets);
10701
- return targetRoot ? { status: "available", targetRoot } : unavailableOperationTarget();
11354
+ return sharedTargetRoot(targets);
10702
11355
  }
10703
11356
  function deriveApplyPatchTarget(args2, sessionLocation, parentTargetRoot, options, realPath) {
10704
11357
  if (args2.workdir !== undefined && (typeof args2.workdir !== "string" || args2.workdir.length === 0)) {
@@ -10715,11 +11368,13 @@ function deriveApplyPatchTarget(args2, sessionLocation, parentTargetRoot, option
10715
11368
  }
10716
11369
  } : deriveDirectoryTarget(args2.workdir, sessionLocation, parentTargetRoot, options, realPath);
10717
11370
  if (workdir.status === "unavailable")
10718
- return unavailableOperationTarget();
10719
- 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());
10720
11376
  const seedWorkdirRoot = args2.workdir !== undefined || targets.length === 0;
10721
- const targetRoot = sharedTargetRoot(targets, seedWorkdirRoot ? [workdir.target.targetRoot] : []);
10722
- return targetRoot ? { status: "available", targetRoot } : unavailableOperationTarget();
11377
+ return sharedTargetRoot(targets, seedWorkdirRoot && workdir.status === "available" ? [workdir.target.targetRoot] : []);
10723
11378
  }
10724
11379
  function deriveBashTarget(args2, sessionLocation, parentTargetRoot, options, realPath) {
10725
11380
  if (args2.workdir === undefined) {
@@ -10924,7 +11579,7 @@ function isSuccessfulAfter(output) {
10924
11579
  function isSuccessfulSkillAfter(output) {
10925
11580
  return parseHostOutput(output, { maxOutputLength: Number.POSITIVE_INFINITY }) !== undefined;
10926
11581
  }
10927
- function statusForTool(status, unavailableCause, seedDeferrals = [], unconfirmedReadbacks = []) {
11582
+ function statusForTool(status, unavailableCause, seedDeferrals = [], unconfirmedReadbacks = [], snapshotBlock) {
10928
11583
  return JSON.stringify({
10929
11584
  state: status.state,
10930
11585
  reasonCode: status.reasonCode,
@@ -10933,6 +11588,7 @@ function statusForTool(status, unavailableCause, seedDeferrals = [], unconfirmed
10933
11588
  missingOperations: status.missingOperations,
10934
11589
  ...unavailableCause && status.state === "unavailable" ? { firstUnavailableCause: unavailableCause } : {},
10935
11590
  ...seedDeferrals.length > 0 ? { seedDeferrals } : {},
11591
+ ...snapshotBlock ? { snapshotBlock } : {},
10936
11592
  ...unconfirmedReadbacks.length > 0 ? { unconfirmedReadbacks } : {}
10937
11593
  });
10938
11594
  }
@@ -11113,6 +11769,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11113
11769
  const pendingOperations = new Map;
11114
11770
  const sealedOperations = new Map;
11115
11771
  const skippedOperations = new Set;
11772
+ let localCallSequence = 0;
11773
+ const inFlightLocalCalls = new Map;
11116
11774
  const abandonedOperations = new Map;
11117
11775
  const rolledUpChildren = new Set;
11118
11776
  const questionAttestation = createQuestionAttestation();
@@ -11122,13 +11780,20 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11122
11780
  let firstUnavailableCause;
11123
11781
  let pendingUnavailableCause;
11124
11782
  let seedDeferralRecord;
11783
+ let snapshotBlockRecord;
11784
+ let snapshotBlockVersion = 0;
11125
11785
  let unitStartGeneration = 0;
11126
11786
  function startFreshUnit(input, policy) {
11787
+ const previousUnitId = requireGuard().status().unit?.unitId;
11127
11788
  const result = requireGuard().startUnit(input, policy);
11128
11789
  if (result.status === "started") {
11129
11790
  unitStartGeneration += 1;
11791
+ snapshotBlockVersion += 1;
11130
11792
  firstUnavailableCause = undefined;
11131
- seedDeferralRecord = undefined;
11793
+ if (result.unit.unitId !== previousUnitId) {
11794
+ seedDeferralRecord = undefined;
11795
+ snapshotBlockRecord = undefined;
11796
+ }
11132
11797
  }
11133
11798
  return result;
11134
11799
  }
@@ -11153,19 +11818,21 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11153
11818
  }
11154
11819
  function parentObserverRegistration() {
11155
11820
  if (!options.observer)
11156
- return;
11821
+ return { status: "fatal" };
11157
11822
  const targetRoot = canonicalExistingPath(options.targetDirectory ?? process.cwd(), fs8.realpathSync);
11158
11823
  if (!targetRoot)
11159
- return;
11824
+ return { status: "fatal" };
11160
11825
  let validation;
11161
11826
  try {
11162
11827
  validation = options.observer.validateRegisteredWorktree(targetRoot);
11163
11828
  } catch {
11164
- return;
11829
+ return { status: "fatal" };
11165
11830
  }
11831
+ if (isProbeTimeout(validation))
11832
+ return TIMED_OUT_READ;
11166
11833
  const registeredIdentity = registeredWorktreeIdentity(validation);
11167
11834
  if (validation.status !== "ok" || registeredIdentity === undefined || validation.targetRoot !== targetRoot) {
11168
- return;
11835
+ return { status: "fatal" };
11169
11836
  }
11170
11837
  const registration = {
11171
11838
  targetRoot,
@@ -11173,14 +11840,15 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11173
11840
  observer: options.observer
11174
11841
  };
11175
11842
  rememberOperationObserver(registration);
11176
- return registration;
11843
+ return { status: "ok", value: registration };
11177
11844
  }
11178
11845
  function operationObserverRegistration(targetIdentity) {
11179
11846
  const existing = operationObservers.get(targetIdentity);
11180
11847
  if (existing)
11181
- return existing;
11182
- if (options.observer?.targetDigest !== targetIdentity)
11183
- return;
11848
+ return { status: "ok", value: existing };
11849
+ if (options.observer?.targetDigest !== targetIdentity) {
11850
+ return { status: "fatal" };
11851
+ }
11184
11852
  return parentObserverRegistration();
11185
11853
  }
11186
11854
  function resolveEffectiveObserver() {
@@ -11199,9 +11867,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11199
11867
  };
11200
11868
  }
11201
11869
  const registration = operationObserverRegistration(pinnedTargetIdentity);
11202
- if (!registration)
11203
- return { status: "fatal" };
11204
- return resolvePinnedObserver(parentObserver, registration, pinnedTargetIdentity);
11870
+ if (registration.status !== "ok")
11871
+ return registration;
11872
+ return resolvePinnedObserver(parentObserver, registration.value, pinnedTargetIdentity);
11205
11873
  }
11206
11874
  function resolvePinnedObserver(parentObserver, registration, pinnedTargetIdentity) {
11207
11875
  let validation;
@@ -11211,7 +11879,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11211
11879
  return { status: "fatal" };
11212
11880
  }
11213
11881
  if (isProbeTimeout(validation))
11214
- return { status: "timeout" };
11882
+ return TIMED_OUT_READ;
11215
11883
  if (validation.status !== "ok") {
11216
11884
  return { status: "fatal", reasonCode: validation.reasonCode };
11217
11885
  }
@@ -11681,6 +12349,34 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11681
12349
  initializationPromise = next;
11682
12350
  await next;
11683
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
+ }
11684
12380
  async function rollupForegroundTask(host, output) {
11685
12381
  if (!options.hostReadback || !isRecord7(output))
11686
12382
  return;
@@ -11693,6 +12389,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11693
12389
  if (rolledUpChildren.has(rollupKey))
11694
12390
  return;
11695
12391
  const parentBefore = requireGuard().currentOperationContext();
12392
+ const rollupGeneration = unitStartGeneration;
11696
12393
  const children = await options.hostReadback.listChildren(host.sessionID);
11697
12394
  if (!children.some((child) => child.sessionId === childSessionID && child.parentID === host.sessionID)) {
11698
12395
  markUnavailable(afterCause("call-lifecycle-mismatch"));
@@ -11740,6 +12437,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11740
12437
  return;
11741
12438
  const expectedWorkspace = childLedger.digestIdentity("workspace", parentBefore.workspaceIdentity);
11742
12439
  let batchTargetIdentity = currentStatus.unit.pinnedOperationTargetIdentity;
12440
+ let blockClear;
11743
12441
  const candidates = [];
11744
12442
  for (const childReceipt of recovered.receipts) {
11745
12443
  const operation = childReceipt.canonical.operation;
@@ -11759,11 +12457,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11759
12457
  return;
11760
12458
  }
11761
12459
  batchTargetIdentity = targetIdentity;
11762
- const registration = operationObserverRegistration(targetIdentity);
11763
- if (!registration || !options.observer) {
12460
+ const registered = operationObserverRegistration(targetIdentity);
12461
+ if (registered.status === "timeout")
12462
+ return;
12463
+ if (registered.status !== "ok" || !options.observer) {
11764
12464
  markUnavailable(afterCause("operation-input-invalid"));
11765
12465
  return;
11766
12466
  }
12467
+ const registration = registered.value;
11767
12468
  let validation;
11768
12469
  try {
11769
12470
  validation = options.observer.validateRegisteredWorktree(registration.targetRoot);
@@ -11771,38 +12472,35 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11771
12472
  markUnavailable(afterCause("operation-input-invalid"));
11772
12473
  return;
11773
12474
  }
12475
+ if (isProbeTimeout(validation))
12476
+ return;
11774
12477
  if (validation.status === "error" || validation.targetRoot !== registration.targetRoot || registeredWorktreeIdentity(validation) !== registration.registeredWorktreeIdentity || registration.observer.targetDigest !== targetIdentity) {
11775
12478
  markUnavailable(afterCause("operation-input-invalid", validation.status === "error" ? validation.reasonCode : undefined));
11776
12479
  return;
11777
12480
  }
11778
- let targetResult;
11779
- try {
11780
- targetResult = await registration.observer.snapshot();
11781
- } catch {
11782
- markUnavailable(afterCause("local-snapshot-error"));
11783
- return;
11784
- }
11785
- if (targetResult.status === "unavailable") {
11786
- markUnavailable(afterCause("local-snapshot-unavailable", targetResult.reasonCode));
11787
- return;
11788
- }
11789
- if (targetResult.snapshot.targetDigest !== targetIdentity) {
11790
- markUnavailable(afterCause("operation-target-mismatch"));
12481
+ const targetRead = await readChildSnapshot(registration.observer, targetIdentity, rollupGeneration);
12482
+ if (targetRead.kind === "halt")
11791
12483
  return;
12484
+ if (targetRead.blockCapture) {
12485
+ blockClear = {
12486
+ capture: targetRead.blockCapture,
12487
+ targetIdentity,
12488
+ snapshot: targetRead.snapshot
12489
+ };
11792
12490
  }
11793
12491
  const recoveredContext = recoveredOperationContexts.get(childReceipt.canonical.receiptId);
11794
12492
  if (recoveredContext && recoveredContext.targetIdentity !== targetIdentity || targetIdentity !== options.observer.targetDigest && !recoveredContext) {
11795
12493
  markUnavailable(afterCause("operation-target-mismatch"));
11796
12494
  return;
11797
12495
  }
11798
- const expectedRepository = childLedger.digestIdentity("repository", targetResult.snapshot.repositoryRevisionDigest);
11799
- 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);
11800
12498
  if (childReceipt.canonical.repositoryDigest !== expectedRepository || childReceipt.canonical.worktreeDigest !== expectedWorktree) {
11801
12499
  continue;
11802
12500
  }
11803
12501
  candidates.push({
11804
12502
  receipt: childReceipt,
11805
- snapshot: targetResult.snapshot,
12503
+ snapshot: targetRead.snapshot,
11806
12504
  before: recoveredContext?.before
11807
12505
  });
11808
12506
  }
@@ -11848,6 +12546,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11848
12546
  }
11849
12547
  if (minted)
11850
12548
  rolledUpChildren.add(rollupKey);
12549
+ if (blockClear) {
12550
+ commitSnapshotBlockClear(blockClear.capture, readbackTarget(blockClear.targetIdentity), blockClear.snapshot, snapshotFailureCause(afterCause));
12551
+ }
11851
12552
  }
11852
12553
  let runtimePolicy = trustedSkillPolicy("unknown", options.runtimeRequiredOperations ?? []);
11853
12554
  function markUnavailable(cause) {
@@ -11902,6 +12603,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11902
12603
  abandonedOperations.set(callDigest, { skipped: true });
11903
12604
  }
11904
12605
  skippedOperations.clear();
12606
+ inFlightLocalCalls.clear();
11905
12607
  }
11906
12608
  function readStatus() {
11907
12609
  return guard ? guard.status() : unavailableWorkflowStatus();
@@ -11972,24 +12674,45 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11972
12674
  return [];
11973
12675
  }
11974
12676
  const effective = lookup.value;
12677
+ const blockCapture = captureSnapshotBlock();
12678
+ const blockVersion = snapshotBlockVersion;
12679
+ const generation = unitStartGeneration;
11975
12680
  const read = await readSnapshot(effective.observer, effective.targetIdentity);
11976
12681
  if (read.status === "timeout") {
11977
12682
  return skippedWithRemoteTail(effective.pinned ? "pinned" : "local");
11978
12683
  }
11979
12684
  if (read.status === "fatal") {
11980
- 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));
11981
12692
  return [];
11982
12693
  }
11983
- return applyReadbackAndProbeRemote(effective, read.value);
12694
+ setSnapshotBlock(reasonCode, effective.targetIdentity, { generation });
12695
+ return [];
11984
12696
  }
11985
- async function applyReadbackAndProbeRemote(effective, snapshot) {
11986
- 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({
11987
12710
  workspaceIdentity: options.workspaceIdentity,
11988
12711
  repositoryIdentity: snapshot.repositoryRevisionDigest,
11989
12712
  worktreeIdentity: snapshot.worktreeRevisionDigest,
11990
12713
  ...effective.pinned ? { operationTargetIdentity: effective.targetIdentity } : {}
11991
12714
  });
11992
- if (observed.status === "rejected" && observed.reasonCode === "workspace-mismatch") {
12715
+ if (observed?.status === "rejected" && observed.reasonCode === "workspace-mismatch") {
11993
12716
  markUnavailable(observerReadbackFailedCause());
11994
12717
  return [];
11995
12718
  }
@@ -12151,7 +12874,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12151
12874
  output.title = title;
12152
12875
  output.output = JSON.stringify({
12153
12876
  status: result.status,
12154
- reasonCode: result.reasonCode
12877
+ reasonCode: result.reasonCode,
12878
+ ...result.blockReason ? { blockReason: result.blockReason } : {},
12879
+ ...result.blockTarget ? { blockTarget: result.blockTarget } : {}
12155
12880
  });
12156
12881
  output.metadata = {
12157
12882
  ...withoutStaleConditionalMetadata(existingMetadata),
@@ -12299,9 +13024,96 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12299
13024
  return { operation: classification.category };
12300
13025
  }
12301
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
+ }
12302
13113
  async function prepareOperation(host, args2) {
12303
13114
  if (!options.observer || !isLocalOperationTool(host.tool))
12304
13115
  return;
13116
+ const localCall = beginLocalCall(digestCall(ledger, host.callID));
12305
13117
  if (!operationObservationApplies()) {
12306
13118
  skippedOperations.add(digestCall(ledger, host.callID));
12307
13119
  return;
@@ -12323,6 +13135,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12323
13135
  validateRegisteredWorktree: options.observer.validateRegisteredWorktree
12324
13136
  });
12325
13137
  if (target.status === "unavailable") {
13138
+ if (target.reasonCode === "command-timeout") {
13139
+ skippedOperations.add(callDigest);
13140
+ return;
13141
+ }
12326
13142
  markUnavailable(beforeCause("operation-input-invalid", target.reasonCode));
12327
13143
  return;
12328
13144
  }
@@ -12333,6 +13149,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12333
13149
  markUnavailable(beforeCause("operation-input-invalid"));
12334
13150
  return;
12335
13151
  }
13152
+ if (isProbeTimeout(registeredTarget)) {
13153
+ skippedOperations.add(callDigest);
13154
+ return;
13155
+ }
12336
13156
  const registeredIdentity = registeredWorktreeIdentity(registeredTarget);
12337
13157
  if (registeredTarget.status !== "ok" || registeredIdentity === undefined || registeredTarget.targetRoot !== target.targetRoot) {
12338
13158
  markUnavailable(beforeCause("operation-input-invalid", registeredTarget.status === "error" ? registeredTarget.reasonCode : undefined));
@@ -12344,21 +13164,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12344
13164
  return;
12345
13165
  }
12346
13166
  const operationObserver = target.targetRoot === canonicalParentTargetRoot ? options.observer : [...operationObservers.values()].find((registration) => registration.targetRoot === target.targetRoot)?.observer ?? (options.createTargetObserver ?? defaultTargetObserver)(target.targetRoot);
12347
- let result;
12348
- try {
12349
- result = await operationObserver.snapshot();
12350
- } catch {
12351
- markUnavailable(beforeCause("local-snapshot-error"));
12352
- return;
12353
- }
12354
- if (result.status === "unavailable") {
12355
- markUnavailable(beforeCause("local-snapshot-unavailable", result.reasonCode));
13167
+ const taken = await takeBeforeSnapshot(operationObserver, initiator);
13168
+ if (taken.kind === "skip") {
13169
+ skippedOperations.add(callDigest);
12356
13170
  return;
12357
13171
  }
12358
- if (result.snapshot.targetDigest !== operationObserver.targetDigest) {
12359
- markUnavailable(beforeCause("operation-target-mismatch"));
13172
+ if (taken.kind === "stop")
12360
13173
  return;
12361
- }
12362
13174
  rememberOperationObserver({
12363
13175
  targetRoot: target.targetRoot,
12364
13176
  registeredWorktreeIdentity: registeredIdentity,
@@ -12376,7 +13188,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12376
13188
  targetIdentity: operationObserver.targetDigest,
12377
13189
  registeredWorktreeIdentity: registeredIdentity,
12378
13190
  observer: operationObserver,
12379
- before: result.snapshot,
13191
+ before: taken.snapshot,
13192
+ localCall,
12380
13193
  ...initiator ? { initiator } : {},
12381
13194
  ...remote ? { remoteOperation: remote.operation, remoteBefore: remote.before } : {}
12382
13195
  });
@@ -12492,31 +13305,52 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12492
13305
  timedOut: false
12493
13306
  };
12494
13307
  }
12495
- let local;
12496
- try {
12497
- local = await options.observer.snapshot();
12498
- } catch {
12499
- return {
12500
- site: "seed-remote-scopes",
12501
- kind: "local-snapshot-error",
12502
- timedOut: false
12503
- };
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;
12504
13318
  }
12505
- if (local.status === "unavailable") {
12506
- return {
12507
- site: "seed-remote-scopes",
12508
- kind: "local-snapshot-unavailable",
12509
- reasonCode: local.reasonCode,
12510
- timedOut: local.reasonCode === "command-timeout"
12511
- };
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 };
12512
13331
  }
12513
- return seedEachRemoteScope(remoteOperations, remoteSnapshot, local.snapshot);
13332
+ return {
13333
+ kind: "fatal",
13334
+ cause: snapshotFailureCause(seedCause)(reasonCode)
13335
+ };
12514
13336
  }
12515
- async function seedEachRemoteScope(operations, reader, local) {
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");
13343
+ }
13344
+ setSnapshotBlock(reasonCode, targetIdentity, { generation });
13345
+ }
13346
+ async function seedEachRemoteScope(operations, reader, local, generation) {
12516
13347
  for (const operation of operations) {
12517
- const outcome = await seedRemoteScope(reader, operation, local);
13348
+ const outcome = await seedRemoteScope(reader, operation, local, generation);
13349
+ if (outcome.kind === "superseded")
13350
+ return;
12518
13351
  if (outcome.kind === "fatal")
12519
13352
  return outcome.cause;
13353
+ clearSeedDeferral(operation);
12520
13354
  if (outcome.kind === "deferred") {
12521
13355
  recordSeedDeferral(operation, outcome.reasonCode);
12522
13356
  }
@@ -12607,6 +13441,118 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12607
13441
  ...operation === "pr-creation" ? { propagate: false } : {}
12608
13442
  };
12609
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
+ };
12610
13556
  function currentSeedDeferrals() {
12611
13557
  return seedDeferralEntries().map(({ operation, reasonCode }) => ({
12612
13558
  operation,
@@ -12616,8 +13562,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12616
13562
  function fatalSeed(cause) {
12617
13563
  return { kind: "fatal", cause };
12618
13564
  }
12619
- async function seedRemoteScope(reader, operation, local) {
12620
- const result = await readRemoteScope(reader, operation, "before");
13565
+ function classifyRemoteSeedRead(operation, result) {
12621
13566
  if (!result) {
12622
13567
  return fatalSeed({
12623
13568
  site: "seed-remote-scope",
@@ -12627,24 +13572,30 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12627
13572
  });
12628
13573
  }
12629
13574
  if (result.status === "missing-resource") {
12630
- if (operation === "push") {
12631
- return { kind: "deferred", reasonCode: "missing-resource" };
12632
- }
12633
- return { kind: "tolerated" };
13575
+ return operation === "push" ? { kind: "deferred", reasonCode: "missing-resource" } : { kind: "tolerated" };
12634
13576
  }
12635
- if (result.status !== "available") {
12636
- if (result.reasonCode === "command-timeout") {
12637
- return { kind: "deferred", reasonCode: "command-timeout" };
12638
- }
12639
- return fatalSeed({
12640
- site: "seed-remote-scope",
12641
- kind: "remote-scope-unavailable",
12642
- operation,
12643
- reasonCode: result.reasonCode,
12644
- timedOut: false
12645
- });
13577
+ if (result.status === "available") {
13578
+ return { kind: "read", snapshot: result.snapshot };
12646
13579
  }
12647
- 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"));
12648
13599
  if (observed.status === "rejected") {
12649
13600
  return fatalSeed({
12650
13601
  site: "seed-remote-scope",
@@ -12799,6 +13750,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12799
13750
  return;
12800
13751
  }
12801
13752
  const reasonCode = "reasonCode" in result ? result.reasonCode : "guard-unavailable";
13753
+ if (reasonCode === "stale-receipt") {
13754
+ finishStaleFinalize(callDigest, pending, output);
13755
+ return;
13756
+ }
12802
13757
  markUnavailable(afterCause("transition-finalize-rejected", reasonCode));
12803
13758
  const terminal = {
12804
13759
  target: pending.target,
@@ -12809,6 +13764,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12809
13764
  terminalCompletes.set(callDigest, terminal);
12810
13765
  writeTerminalCompletionResult(output, terminal, pending.target);
12811
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
+ }
12812
13775
  function writeTerminalReplay(output, terminal, target) {
12813
13776
  if (terminal.metadataOnly) {
12814
13777
  writeAbandonedCompletionMetadata(output, target, terminal.reasonCode);
@@ -12856,13 +13819,18 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12856
13819
  if (remember)
12857
13820
  abandonedCompletes.set(callDigest, pending.target);
12858
13821
  }
13822
+ function blockedOrFailure(failure, targetIdentity) {
13823
+ return failure.status === "fatal" && isSnapshotBlockingReason(failure.reasonCode) ? { status: "blocked", reasonCode: failure.reasonCode, targetIdentity } : failure;
13824
+ }
12859
13825
  async function completionReadbacks() {
12860
13826
  const observer = options.observer;
12861
13827
  if (!observer)
12862
13828
  return { status: "none" };
13829
+ const blockCapture = captureSnapshotBlock();
12863
13830
  const parent = await readSnapshot(observer, options.workspaceIdentity);
12864
- if (parent.status !== "ok")
12865
- return parent;
13831
+ if (parent.status !== "ok") {
13832
+ return blockedOrFailure(parent, options.workspaceIdentity);
13833
+ }
12866
13834
  const lookup = resolveEffectiveObserver();
12867
13835
  if (lookup.status !== "ok")
12868
13836
  return lookup;
@@ -12870,18 +13838,27 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12870
13838
  let initialEffective = parent.value;
12871
13839
  if (effective.pinned) {
12872
13840
  const pinned = await readSnapshot(effective.observer, effective.targetIdentity);
12873
- if (pinned.status !== "ok")
12874
- return pinned;
13841
+ if (pinned.status !== "ok") {
13842
+ return blockedOrFailure(pinned, effective.targetIdentity);
13843
+ }
12875
13844
  initialEffective = pinned.value;
12876
13845
  }
12877
13846
  const remote = await completionRemoteReadbacks(effective.observer);
12878
13847
  if (remote.status !== "ready")
12879
13848
  return remote;
12880
13849
  const finalParent = await readSnapshot(observer);
12881
- if (finalParent.status !== "ok")
12882
- return finalParent;
12883
- 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")
12884
13855
  return { status: "fatal" };
13856
+ if (drift === "revision") {
13857
+ return {
13858
+ status: "blocked",
13859
+ reasonCode: "worktree-unstable",
13860
+ targetIdentity: options.workspaceIdentity
13861
+ };
12885
13862
  }
12886
13863
  const final = effective.pinned ? await revalidatePinnedCompletion(effective, initialEffective) : { status: "ready", effective, snapshot: finalParent.value };
12887
13864
  if (final.status !== "ready")
@@ -12896,11 +13873,20 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12896
13873
  operationTargetIdentity: final.effective.targetIdentity
12897
13874
  },
12898
13875
  ...remote.readbacks.map(({ operation, snapshot }) => remoteReadbackInput(operation, final.snapshot, options.workspaceIdentity, snapshot))
12899
- ]
13876
+ ],
13877
+ ...blockCapture ? {
13878
+ blockClear: {
13879
+ capture: blockCapture,
13880
+ target: final.effective,
13881
+ snapshot: final.snapshot
13882
+ }
13883
+ } : {}
12900
13884
  };
12901
13885
  }
12902
- function completionParentDrifted(initial, final) {
12903
- 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";
12904
13890
  }
12905
13891
  async function revalidatePinnedCompletion(effective, initial) {
12906
13892
  const lookup = resolveEffectiveObserver();
@@ -12911,10 +13897,15 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12911
13897
  return { status: "fatal" };
12912
13898
  }
12913
13899
  const pinned = await readSnapshot(revalidated.observer, revalidated.targetIdentity);
12914
- if (pinned.status !== "ok")
12915
- return pinned;
13900
+ if (pinned.status !== "ok") {
13901
+ return blockedOrFailure(pinned, revalidated.targetIdentity);
13902
+ }
12916
13903
  if (pinned.value.repositoryRevisionDigest !== initial.repositoryRevisionDigest || pinned.value.worktreeRevisionDigest !== initial.worktreeRevisionDigest) {
12917
- return { status: "fatal" };
13904
+ return {
13905
+ status: "blocked",
13906
+ reasonCode: "worktree-unstable",
13907
+ targetIdentity: revalidated.targetIdentity
13908
+ };
12918
13909
  }
12919
13910
  return {
12920
13911
  status: "ready",
@@ -12933,7 +13924,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12933
13924
  for (const operation of remoteOperations) {
12934
13925
  const result = await readRemoteScope(remoteSnapshot, operation);
12935
13926
  if (isProbeTimeout(result))
12936
- return { status: "timeout" };
13927
+ return TIMED_OUT_READ;
12937
13928
  if (result?.status !== "available") {
12938
13929
  return { status: "fatal", reasonCode: remoteFailureReason(result) };
12939
13930
  }
@@ -12955,6 +13946,12 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12955
13946
  markUnavailable(afterCause("call-lifecycle-mismatch"));
12956
13947
  writeAbandonedCompletionResult(output, finalTarget, "guard-unavailable");
12957
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
+ }
12958
13955
  function finishUnavailableReadback(callDigest, pending, output, reasonCode) {
12959
13956
  abandonComplete(callDigest, pending, true);
12960
13957
  terminalCompletes.set(callDigest, {
@@ -12973,16 +13970,38 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12973
13970
  }
12974
13971
  }
12975
13972
  function finishRetryableReadback(callDigest, pending, output) {
12976
- abandonComplete(callDigest, pending, true);
12977
- const terminal = {
13973
+ rejectCompletion(callDigest, pending, output, {
12978
13974
  target: pending.target,
12979
13975
  status: "rejected",
12980
13976
  reasonCode: "readback-timeout",
12981
13977
  title: "Workflow readback timed out"
12982
- };
12983
- terminalCompletes.set(callDigest, terminal);
12984
- writeTerminalCompletionResult(output, terminal, pending.target, terminal.title);
13978
+ }, { abandon: true });
12985
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;
14003
+ }
14004
+ const completionFailureCause = (reasonCode) => observerReadbackFailedCause(reasonCode, "complete-readback");
12986
14005
  async function finishComplete(host, output) {
12987
14006
  const callDigest = digestCall(ledger, host.callID);
12988
14007
  const pending = pendingCompletes.get(callDigest);
@@ -12997,7 +14016,23 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12997
14016
  finishUnreplayableComplete(finalTarget, output);
12998
14017
  return;
12999
14018
  }
14019
+ const generation = unitStartGeneration;
13000
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
+ }
13001
14036
  if (readbacks.status === "fatal") {
13002
14037
  finishUnavailableReadback(callDigest, pending, output, readbacks.reasonCode);
13003
14038
  return;
@@ -13006,6 +14041,15 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13006
14041
  finishReadbackTimeout(callDigest, pending, output);
13007
14042
  return;
13008
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
+ }
13009
14053
  finalizeComplete(callDigest, pending, output, readbacks.status === "ready" ? readbacks.readbacks : undefined);
13010
14054
  }
13011
14055
  function sealOperation(callDigest, operation, abandoned = false) {
@@ -13047,6 +14091,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13047
14091
  } catch {
13048
14092
  return afterFailure("operation-input-invalid");
13049
14093
  }
14094
+ if (isProbeTimeout(validation))
14095
+ return TIMED_OUT_READ;
13050
14096
  if (validation.status === "error" || validation.targetRoot !== pending.targetRoot || registeredWorktreeIdentity(validation) !== pending.registeredWorktreeIdentity) {
13051
14097
  return afterFailure("operation-input-invalid", validation.status === "error" ? validation.reasonCode : undefined);
13052
14098
  }
@@ -13058,16 +14104,34 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13058
14104
  const targetFailure = afterTargetFailure(options.observer, pending);
13059
14105
  if (targetFailure)
13060
14106
  return targetFailure;
13061
- let result;
13062
- try {
13063
- result = await pending.observer.snapshot();
13064
- } catch {
13065
- 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);
13066
14111
  }
13067
- if (result.status === "unavailable") {
13068
- 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 };
13069
14117
  }
13070
- return result.snapshot.targetDigest === pending.targetIdentity ? { status: "available", snapshot: result.snapshot } : afterFailure("operation-target-mismatch");
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");
14123
+ }
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
+ });
13071
14135
  }
13072
14136
  async function captureRemoteAfter(operation, observer) {
13073
14137
  const remoteSnapshot = observer.remoteSnapshot;
@@ -13079,7 +14143,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13079
14143
  } catch {
13080
14144
  return afterFailure("operation-observation-rejected");
13081
14145
  }
13082
- 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);
13083
14153
  }
13084
14154
  async function readRemoteScope(reader, operation, phase = "after") {
13085
14155
  try {
@@ -13164,13 +14234,22 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13164
14234
  function ownsOperation(pending) {
13165
14235
  return !pending.initiator || isCurrentInitiator(pending.initiator);
13166
14236
  }
13167
- function sealLostOperation(callDigest, pending) {
14237
+ function sealAndIgnore(callDigest, pending) {
13168
14238
  sealOperation(callDigest, pending, true);
13169
14239
  return { status: "ignored" };
13170
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
+ }
13171
14250
  async function completeOperationObservation(callDigest, host, pending, output) {
13172
14251
  if (!ownsOperation(pending))
13173
- return sealLostOperation(callDigest, pending);
14252
+ return sealAndIgnore(callDigest, pending);
13174
14253
  const parsedOutput = parseHostOutput(output);
13175
14254
  if (!parsedOutput) {
13176
14255
  sealOperation(callDigest, pending, true);
@@ -13178,20 +14257,25 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13178
14257
  }
13179
14258
  const capture = await captureAfterOperation(pending);
13180
14259
  if (!ownsOperation(pending))
13181
- 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);
13182
14268
  if (capture.status === "unavailable") {
13183
14269
  sealOperation(callDigest, pending, true);
13184
14270
  return capture;
13185
14271
  }
13186
14272
  const afterSnapshot = capture.snapshot;
13187
14273
  const observation = buildOperationObservation(host, pending, afterSnapshot, requireGuard().status(), parsedOutput);
13188
- if (!observation) {
13189
- sealOperation(callDigest, pending, true);
13190
- return { status: "ignored" };
13191
- }
14274
+ if (!observation)
14275
+ return sealAndIgnore(callDigest, pending);
13192
14276
  const classification = await classifyLocalObservation(observation);
13193
14277
  if (!ownsOperation(pending))
13194
- return sealLostOperation(callDigest, pending);
14278
+ return sealAndIgnore(callDigest, pending);
13195
14279
  if (classification.status !== "ready") {
13196
14280
  sealOperation(callDigest, pending, true);
13197
14281
  return classification;
@@ -13200,7 +14284,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13200
14284
  if (remoteOperation(finalObservation.operation)) {
13201
14285
  const remoteCapture = await captureRemoteAfter(finalObservation.operation, pending.observer);
13202
14286
  if (!ownsOperation(pending)) {
13203
- 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);
13204
14294
  }
13205
14295
  if (remoteCapture.status === "unavailable") {
13206
14296
  sealOperation(callDigest, pending, true);
@@ -13229,7 +14319,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13229
14319
  }
13230
14320
  }
13231
14321
  if (!ownsOperation(pending))
13232
- return sealLostOperation(callDigest, pending);
14322
+ return sealAndIgnore(callDigest, pending);
14323
+ if (finalObservation.operation === "verification" && overlappedAnotherLocalCall(pending)) {
14324
+ return sealAndIgnore(callDigest, pending);
14325
+ }
13233
14326
  const observed = await observeClassifiedOperation(finalObservation);
13234
14327
  if (!observed) {
13235
14328
  sealOperation(callDigest, pending, true);
@@ -13285,6 +14378,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13285
14378
  if (!options.observer || !isLocalOperationAfter(host))
13286
14379
  return;
13287
14380
  const callDigest = digestCall(ledger, host.callID);
14381
+ endLocalCall(callDigest);
13288
14382
  const pending = takeOperationToFinish(callDigest, host);
13289
14383
  if (!pending)
13290
14384
  return;
@@ -13382,6 +14476,8 @@ ${marker}` : marker;
13382
14476
  readStatus,
13383
14477
  unavailableCause: () => firstUnavailableCause ?? pendingUnavailableCause,
13384
14478
  seedDeferrals: currentSeedDeferrals,
14479
+ snapshotBlock: snapshotBlockControls,
14480
+ noteUnparsedLocalCall: beginUnparsedLocalCall,
13385
14481
  refreshReadback,
13386
14482
  observeReceipt: (input) => {
13387
14483
  ensureSynchronousRuntime();
@@ -13501,7 +14597,7 @@ function createOpencodeWorkflowGuard(options) {
13501
14597
  const unconfirmed = await runtime.refreshReadback();
13502
14598
  return {
13503
14599
  title: "Workflow guard status",
13504
- 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()
13505
14601
  };
13506
14602
  }),
13507
14603
  systematic_workflow_complete: makeWorkflowTool("Request completion of a guarded workflow unit or epoch.", completeToolShape, sessionRuntimeFor, (_runtime, input) => completeToolSchema.safeParse(input).success ? {
@@ -13519,10 +14615,18 @@ function createOpencodeWorkflowGuard(options) {
13519
14615
  output: unavailableToolResult()
13520
14616
  })
13521
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
+ }
13522
14624
  async function before(input, output) {
13523
14625
  const host = parseHostBefore(input);
13524
- if (!host)
14626
+ if (!host) {
14627
+ countUnparsedLocalCall(input);
13525
14628
  return;
14629
+ }
13526
14630
  await sessionRuntimeFor(host.sessionID).hooks["tool.execute.before"](input, output);
13527
14631
  }
13528
14632
  async function after(input, output) {
@@ -13597,6 +14701,9 @@ function createOpencodeWorkflowGuard(options) {
13597
14701
  return { status: "rejected", reasonCode: "guard-unavailable" };
13598
14702
  }
13599
14703
  return sessionRuntimeFor(sessionID).startUnit(input, policy);
14704
+ },
14705
+ snapshotBlock(sessionID) {
14706
+ return boundedString(sessionID, 256) ? sessionRuntimeFor(sessionID).snapshotBlock : INERT_SNAPSHOT_BLOCK;
13600
14707
  }
13601
14708
  };
13602
14709
  }