@fro.bot/systematic 3.22.2 → 3.22.4

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-0sc6c1vd.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
+ }
1226
+ return { status: "error", reasonCode: "file-read-failed" };
1227
+ }
1228
+ }
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;
1257
+ try {
1258
+ return readOpenedRegularFile(opened.fd, expected, maxBytes);
1259
+ } catch {
1073
1260
  return { status: "error", reasonCode: "file-read-failed" };
1261
+ } finally {
1262
+ try {
1263
+ fs6.closeSync(opened.fd);
1264
+ } catch {}
1074
1265
  }
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
1266
  }
1082
- function appendSymlinkFact(hash, symlinkReader, absolutePath, relativePath, limits, totalBytes) {
1083
- let target;
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;
1084
1278
  try {
1085
- target = symlinkReader(absolutePath);
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
+ }
1332
+ }
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" };
1113
1377
  }
1114
- if (totalBytes + content.byteLength > limits.maxTotalFileBytes) {
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" };
1124
1422
  }
1125
- function appendFileFactV2(hash, runner, fileReader, symlinkReader, statReader, context, entry, limits, totalBytes) {
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" };
1437
+ }
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" };
1190
- }
1191
- if (diff.status !== 0 && diff.status !== 1) {
1192
- return { status: "error", reasonCode: "command-failed" };
1758
+ observations.push(result.observation);
1193
1759
  }
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
  },
@@ -3652,11 +4257,11 @@ function createReceiptLedger(options = {}) {
3652
4257
  unit: null
3653
4258
  };
3654
4259
  function digestIdentity(domain, identity) {
3655
- const normalized = normalizedIdentity(identity);
3656
- if (!normalized || !DIGEST_DOMAIN_SET.has(domain)) {
4260
+ const trimmed = typeof identity === "string" ? identity.trim() : "";
4261
+ if (!trimmed || !DIGEST_DOMAIN_SET.has(domain)) {
3657
4262
  return digestReceiptIdentity(domain, "invalid", sessionSaltBytes);
3658
4263
  }
3659
- return digestReceiptIdentity(domain, normalized, sessionSaltBytes);
4264
+ return digestReceiptIdentity(domain, trimmed, sessionSaltBytes);
3660
4265
  }
3661
4266
  function digestContext(context, operation) {
3662
4267
  return {
@@ -8704,7 +9309,7 @@ function createWorkflowGuard(options) {
8704
9309
  return operation === "push" || operation === "pr-creation" || operation === "check-readback" || operation === "review-readback";
8705
9310
  }
8706
9311
  function stateFingerprint(operation, state) {
8707
- const value = [
9312
+ const value = JSON.stringify([
8708
9313
  operation,
8709
9314
  state.workspaceIdentity,
8710
9315
  state.repositoryIdentity ?? "-",
@@ -8715,7 +9320,7 @@ function createWorkflowGuard(options) {
8715
9320
  state.pullRequest?.state ?? "-",
8716
9321
  state.checkState ?? "-",
8717
9322
  state.reviewDecision ?? "-"
8718
- ].join("|");
9323
+ ]);
8719
9324
  return options.ledger.digestIdentity("resource", value);
8720
9325
  }
8721
9326
  function operationBeforeReason(input, unit) {
@@ -10535,6 +11140,9 @@ function normalizeTarget(args2) {
10535
11140
  function digestCall(ledger, callID) {
10536
11141
  return ledger.digestIdentity("call", callID);
10537
11142
  }
11143
+ function isLocalOperationAfter(host) {
11144
+ return isLocalOperationTool(host.tool);
11145
+ }
10538
11146
  function isLocalOperationTool(tool) {
10539
11147
  return tool === "write" || tool === "edit" || tool === "apply_patch" || tool === "bash";
10540
11148
  }
@@ -10749,49 +11357,52 @@ function deriveOpencodeOperationTarget(tool, args2, options) {
10749
11357
  }
10750
11358
  return tool === "bash" ? deriveBashTarget(args2, sessionLocation, parentTargetRoot, options, realPath) : unavailableOperationTarget();
10751
11359
  }
10752
- function serializeStableArray(value, depth, budget) {
11360
+ function serializeStableArray(value, depth) {
11361
+ if (Object.getOwnPropertySymbols(value).length > 0)
11362
+ return;
10753
11363
  const entries = [];
10754
- let remaining = budget;
10755
11364
  for (const entry of value) {
10756
- const serialized = stableSerialize(entry, depth + 1, remaining);
11365
+ const serialized = stableSerialize(entry, depth + 1);
10757
11366
  if (serialized === undefined)
10758
11367
  return;
10759
11368
  entries.push(serialized);
10760
- remaining -= serialized.length;
10761
11369
  }
10762
11370
  return `[${entries.join(",")}]`;
10763
11371
  }
10764
- function serializeStableRecord(value, depth, budget) {
11372
+ function serializeStableRecord(value, depth) {
10765
11373
  const entries = [];
10766
- let remaining = budget;
10767
11374
  for (const key of Object.keys(value).sort()) {
10768
- const serialized = stableSerialize(value[key], depth + 1, remaining);
11375
+ const serialized = stableSerialize(value[key], depth + 1);
10769
11376
  if (serialized === undefined)
10770
11377
  return;
10771
- const entry = `${JSON.stringify(key)}:${serialized}`;
10772
- entries.push(entry);
10773
- remaining -= entry.length;
11378
+ entries.push(`${JSON.stringify(key)}:${serialized}`);
10774
11379
  }
10775
11380
  return `{${entries.join(",")}}`;
10776
11381
  }
10777
- function stableSerialize(value, depth = 0, budget = 8192) {
10778
- if (budget <= 0 || depth > 8)
11382
+ function isPlainObject(value) {
11383
+ const prototype = Object.getPrototypeOf(value);
11384
+ if (prototype === null)
11385
+ return true;
11386
+ const parent = Object.getPrototypeOf(prototype);
11387
+ return parent === null;
11388
+ }
11389
+ function stableSerialize(value, depth = 0) {
11390
+ if (depth > 8)
10779
11391
  return;
10780
11392
  if (value === null)
10781
11393
  return "null";
10782
- if (typeof value === "string") {
10783
- if (value.length > budget)
10784
- return;
11394
+ if (typeof value === "string")
10785
11395
  return JSON.stringify(value);
10786
- }
10787
11396
  if (typeof value === "number" || typeof value === "boolean") {
10788
11397
  return JSON.stringify(value);
10789
11398
  }
10790
11399
  if (Array.isArray(value))
10791
- return serializeStableArray(value, depth, budget);
10792
- if (!isRecord7(value))
11400
+ return serializeStableArray(value, depth);
11401
+ if (!isRecord7(value) || !isPlainObject(value))
10793
11402
  return;
10794
- return serializeStableRecord(value, depth, budget);
11403
+ if (Object.getOwnPropertySymbols(value).length > 0)
11404
+ return;
11405
+ return serializeStableRecord(value, depth);
10795
11406
  }
10796
11407
  function canonicalPatchText(patchText, sessionLocation) {
10797
11408
  if (patchTextFileTargets(patchText) === undefined)
@@ -10835,8 +11446,9 @@ function canonicalHunks(value, sessionLocation) {
10835
11446
  return hunks;
10836
11447
  }
10837
11448
  function canonicalOperationArgs(tool, args2, sessionLocation) {
10838
- if (tool !== "apply_patch" || !isRecord7(args2))
11449
+ if (tool !== "apply_patch" || !isRecord7(args2) || !isPlainObject(args2)) {
10839
11450
  return args2;
11451
+ }
10840
11452
  const patchPaths = patchFileTargets(args2);
10841
11453
  if (patchPaths === undefined)
10842
11454
  return args2;
@@ -10854,6 +11466,8 @@ function canonicalOperationArgs(tool, args2, sessionLocation) {
10854
11466
  return hunks === undefined ? args2 : { ...args2, hunks };
10855
11467
  }
10856
11468
  function argsFingerprint(ledger, tool, args2, sessionLocation) {
11469
+ if (stableSerialize(args2) === undefined)
11470
+ return;
10857
11471
  const serialized = stableSerialize(canonicalOperationArgs(tool, args2, sessionLocation));
10858
11472
  return serialized === undefined ? undefined : ledger.digestIdentity("call", serialized);
10859
11473
  }
@@ -11103,6 +11717,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11103
11717
  const callBindings = new Map;
11104
11718
  const pendingOperations = new Map;
11105
11719
  const sealedOperations = new Map;
11720
+ const skippedOperations = new Set;
11106
11721
  const abandonedOperations = new Map;
11107
11722
  const rolledUpChildren = new Set;
11108
11723
  const questionAttestation = createQuestionAttestation();
@@ -11888,6 +12503,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11888
12503
  });
11889
12504
  pendingOperations.delete(callDigest);
11890
12505
  }
12506
+ for (const callDigest of skippedOperations) {
12507
+ abandonedOperations.set(callDigest, { skipped: true });
12508
+ }
12509
+ skippedOperations.clear();
11891
12510
  }
11892
12511
  function readStatus() {
11893
12512
  return guard ? guard.status() : unavailableWorkflowStatus();
@@ -11931,6 +12550,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11931
12550
  })
11932
12551
  };
11933
12552
  }
12553
+ function operationObservationApplies() {
12554
+ const current = readStatus();
12555
+ if (current.state === "disabled" || current.state === "unavailable") {
12556
+ return false;
12557
+ }
12558
+ return current.epoch?.status === "active" || pendingSkills.size > 0;
12559
+ }
11934
12560
  function observerReadbackApplies() {
11935
12561
  return options.observer !== undefined && requireGuard().status().epoch !== null;
11936
12562
  }
@@ -12281,6 +12907,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12281
12907
  async function prepareOperation(host, args2) {
12282
12908
  if (!options.observer || !isLocalOperationTool(host.tool))
12283
12909
  return;
12910
+ if (!operationObservationApplies()) {
12911
+ skippedOperations.add(digestCall(ledger, host.callID));
12912
+ return;
12913
+ }
12284
12914
  const initiator = currentInitiator();
12285
12915
  const { parentTargetRoot, sessionLocation } = effectiveTargetContext();
12286
12916
  const fingerprint = argsFingerprint(ledger, host.tool, args2, sessionLocation);
@@ -12997,6 +13627,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12997
13627
  const sealed = sealedOperations.get(callDigest);
12998
13628
  const abandoned = abandonedOperations.get(callDigest);
12999
13629
  const prior = sealed ?? abandoned;
13630
+ if (prior !== undefined && "skipped" in prior)
13631
+ return true;
13000
13632
  return prior !== undefined && fingerprint !== undefined && prior.tool === host.tool && prior.argsFingerprint === fingerprint;
13001
13633
  }
13002
13634
  function takePendingOperation(callDigest, host, fingerprint) {
@@ -13245,15 +13877,20 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13245
13877
  [SYSTEMATIC_WORKFLOW_RECEIPT_METADATA_KEY]: existing ? Array.isArray(existing) ? [...existing, marker] : [existing, marker] : marker
13246
13878
  };
13247
13879
  }
13248
- async function finishOperation(host, output) {
13249
- if (!options.observer || !isLocalOperationTool(host.tool))
13880
+ function takeOperationToFinish(callDigest, host) {
13881
+ if (skippedOperations.has(callDigest))
13250
13882
  return;
13251
- const callDigest = digestCall(ledger, host.callID);
13252
13883
  const { sessionLocation } = effectiveTargetContext();
13253
13884
  const fingerprint = argsFingerprint(ledger, host.tool, host.args, sessionLocation);
13254
13885
  if (isSealedOperationReplay(callDigest, host, fingerprint))
13255
13886
  return;
13256
- const pending = takePendingOperation(callDigest, host, fingerprint);
13887
+ return takePendingOperation(callDigest, host, fingerprint);
13888
+ }
13889
+ async function finishOperation(host, output) {
13890
+ if (!options.observer || !isLocalOperationAfter(host))
13891
+ return;
13892
+ const callDigest = digestCall(ledger, host.callID);
13893
+ const pending = takeOperationToFinish(callDigest, host);
13257
13894
  if (!pending)
13258
13895
  return;
13259
13896
  const result = await completeOperationObservation(callDigest, host, pending, output);