larness 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +6 -5
  2. package/app.js +22 -105
  3. package/apps/server/dist/{address-BDs0FfMq.js → address-D0ZG5qR4.js} +5 -2
  4. package/apps/server/dist/args-CrKTPT06.js +92 -0
  5. package/apps/server/dist/cli.js +340 -0
  6. package/apps/server/dist/{client-D88ULjn9.js → client-D_Ni3Zpx.js} +21 -1
  7. package/apps/server/dist/code-B2JBoV4x.js +24 -0
  8. package/apps/server/dist/{doctor-dwTQiTef.js → doctor-CE6cONuz.js} +3 -2
  9. package/apps/server/dist/doctor-sPRlI92N.js +1 -0
  10. package/apps/server/dist/doctor.js +1 -1
  11. package/apps/server/dist/index.js +724 -126
  12. package/apps/server/dist/{paths-DUfwiH2X.js → inspect-XgAc84F9.js} +106 -87
  13. package/apps/server/dist/lifecycle-C3KV3-Ax.js +263 -0
  14. package/apps/server/dist/log-files-CFOaEy6O.js +26 -0
  15. package/apps/server/dist/{managed-Br7VqQiP.js → managed-Cw3MVilO.js} +221 -71
  16. package/apps/server/dist/paths-BhVn34MT.js +77 -0
  17. package/apps/server/dist/{status-D2oSIMoj.js → status-CV_zWfs6.js} +16 -3
  18. package/apps/server/dist/status.js +37 -9
  19. package/apps/server/dist/supervisor-IYDKL4iU.js +297 -0
  20. package/apps/server/dist/tui.js +167 -333
  21. package/apps/server/dist/version-ui_X8H2k.js +13 -0
  22. package/apps/server/drizzle/0001_auth.sql +109 -109
  23. package/apps/server/drizzle/0002_projects.sql +12 -12
  24. package/apps/server/drizzle/0003_workspace.sql +80 -80
  25. package/apps/server/drizzle/0004_models.sql +30 -30
  26. package/apps/server/drizzle/0005_resources.sql +54 -54
  27. package/apps/server/drizzle/0006_commands.sql +23 -23
  28. package/apps/server/drizzle/0007_terminals.sql +41 -41
  29. package/apps/server/drizzle/0008_resource_actions.sql +23 -23
  30. package/apps/server/drizzle/0010_services.sql +31 -31
  31. package/apps/web/dist/assets/{FileEditor-JaazRNUl.js → FileEditor-DnQa6Owc.js} +1 -1
  32. package/apps/web/dist/assets/{FileViewer-DzJpg82J.js → FileViewer-DKlF-CWF.js} +1 -1
  33. package/apps/web/dist/assets/{cssMode-B8mOf4OC.js → cssMode-C9KmpsHc.js} +1 -1
  34. package/apps/web/dist/assets/{editor.api-BQ-DCb9F.js → editor.api-BwfHyHQ6.js} +1 -1
  35. package/apps/web/dist/assets/{freemarker2-C1ckA1My.js → freemarker2-D41RlIQ5.js} +1 -1
  36. package/apps/web/dist/assets/{handlebars-suElsFdc.js → handlebars-D-7R6ic0.js} +1 -1
  37. package/apps/web/dist/assets/{html-CvWl95vU.js → html-CUME4rt-.js} +1 -1
  38. package/apps/web/dist/assets/{htmlMode-CrdRQhj8.js → htmlMode-8w7WLhnL.js} +1 -1
  39. package/apps/web/dist/assets/{index-C6uOTgh6.js → index-BOS3UrP1.js} +2 -2
  40. package/apps/web/dist/assets/{javascript-DmE3KPeg.js → javascript-_3pdDG34.js} +1 -1
  41. package/apps/web/dist/assets/{jsonMode-TuNjADgG.js → jsonMode-DiqocFCf.js} +1 -1
  42. package/apps/web/dist/assets/{liquid-C_Ceyr5s.js → liquid-j0FoiTXN.js} +1 -1
  43. package/apps/web/dist/assets/{lspLanguageFeatures-DZfo74cL.js → lspLanguageFeatures-Zj7K2sG4.js} +1 -1
  44. package/apps/web/dist/assets/main-DZIruO5x.js +157 -0
  45. package/apps/web/dist/assets/main-gq3n_vn8.css +1 -0
  46. package/apps/web/dist/assets/{mdx-D8eqTMYQ.js → mdx-CGQ8Cw6J.js} +1 -1
  47. package/apps/web/dist/assets/{monaco-BGhTlUO7.js → monaco-CyMA3azg.js} +3 -3
  48. package/apps/web/dist/assets/{python-Cx6dqJ-u.js → python-BtY34Z9A.js} +1 -1
  49. package/apps/web/dist/assets/{razor-u7rb64U6.js → razor-CzYHpLv5.js} +1 -1
  50. package/apps/web/dist/assets/{tsMode-Cu3GDz4d.js → tsMode-GZx3VEv9.js} +1 -1
  51. package/apps/web/dist/assets/{typescript-H0OSh9BN.js → typescript-CAfvuTDQ.js} +1 -1
  52. package/apps/web/dist/assets/{workers-DJ7JInlW.js → workers-C5BOxOmH.js} +1 -1
  53. package/apps/web/dist/assets/{xml-C_rrJhqX.js → xml-BGX4mtH7.js} +1 -1
  54. package/apps/web/dist/assets/{yaml-Cub5doLg.js → yaml-B2AgBtJB.js} +1 -1
  55. package/apps/web/dist/favicon.svg +4 -4
  56. package/apps/web/dist/index.html +1 -1
  57. package/docs/README.md +8 -1
  58. package/docs/guides/install.md +23 -7
  59. package/package.json +3 -1
  60. package/apps/server/dist/lock-DyEoZgG_.js +0 -101
  61. package/apps/web/dist/assets/main-C3xYrJa1.js +0 -157
  62. package/apps/web/dist/assets/main-ptChOROf.css +0 -1
@@ -1,5 +1,5 @@
1
- import { Yn as FilePathSchema, jn as OriginUrlSchema, nr as MAX_EDITABLE_FILE_BYTES } from "./paths-DUfwiH2X.js";
2
- import { createHash, randomInt, randomUUID } from "node:crypto";
1
+ import { An as OriginUrlSchema, Jn as FilePathSchema, tr as MAX_EDITABLE_FILE_BYTES } from "./inspect-XgAc84F9.js";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { constants, existsSync, readFileSync, realpathSync, statSync, watch } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
@@ -8,7 +8,7 @@ import { StringDecoder } from "node:string_decoder";
8
8
  import { promisify } from "node:util";
9
9
  import { access, lstat, mkdir, open, opendir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
10
10
  import { applyPatch, diffLines, parsePatch } from "diff";
11
- import { tmpdir } from "node:os";
11
+ import os, { tmpdir } from "node:os";
12
12
  // ../../packages/resources/src/commands/redactor.ts
13
13
  const PREFIX = /(authorization|api[_-]?key|token|password|cookie|secret)["']?\s{0,16}[:=]\s{0,16}(["']?)/i;
14
14
  const DELIMITER = /[\s"'&;,}]/;
@@ -786,13 +786,21 @@ async function canonicalDirectory(input) {
786
786
  async function resolveInsideRoot(rootReal, input) {
787
787
  validateInput(input);
788
788
  if (!path.isAbsolute(rootReal)) throw new PathGuardError("INVALID_PATH", "project root must be absolute");
789
- const absolute = path.isAbsolute(input) ? path.normalize(input) : path.resolve(rootReal, input);
789
+ return assertInsideRoot(rootReal, await resolveCanonicalPath(path.isAbsolute(input) ? path.normalize(input) : path.resolve(rootReal, input)));
790
+ }
791
+ /**
792
+ * Resolve a path to its canonical form even when it lives outside the primary
793
+ * root: realpath the nearest existing ancestor and re-append the missing tail.
794
+ */
795
+ async function resolveCanonicalPath(input) {
796
+ validateInput(input);
797
+ const absolute = path.isAbsolute(input) ? path.normalize(input) : path.resolve(input);
790
798
  const missing = [];
791
799
  let current = absolute;
792
800
  for (;;) {
793
801
  try {
794
802
  const existing = await realpath(current);
795
- return assertInsideRoot(rootReal, path.join(existing, ...missing));
803
+ return path.join(existing, ...missing);
796
804
  } catch (error) {
797
805
  if (!(error instanceof PathGuardError)) {
798
806
  const code = error.code;
@@ -805,15 +813,73 @@ async function resolveInsideRoot(rootReal, input) {
805
813
  current = parent;
806
814
  }
807
815
  }
816
+ /** POSIX pseudo filesystems whose entries can block or grow without bound. */
817
+ const PSEUDO_FILESYSTEM_ROOTS = [
818
+ "/proc",
819
+ "/sys",
820
+ "/dev"
821
+ ];
822
+ async function homeRealPath() {
823
+ const home = os.homedir();
824
+ try {
825
+ return await realpath(home);
826
+ } catch {
827
+ return path.resolve(home);
828
+ }
829
+ }
830
+ /**
831
+ * Read-side resolver. Relative inputs keep the old "inside the root" rule;
832
+ * absolute inputs may escape the root only when `allowExternal` is true, and
833
+ * always fail closed on `<dataDir>`, pseudo filesystems and root-level targets.
834
+ */
835
+ async function resolveReadPath(policy, input) {
836
+ validateInput(input);
837
+ if (!path.isAbsolute(policy.root)) throw new PathGuardError("INVALID_PATH", "project root must be absolute");
838
+ if (!path.isAbsolute(input)) return {
839
+ absolutePath: await resolveInsideRoot(policy.root, input),
840
+ rootScope: "primary"
841
+ };
842
+ if (policy.allowExternal !== true) return {
843
+ absolutePath: await resolveInsideRoot(policy.root, input),
844
+ rootScope: "primary"
845
+ };
846
+ const normalized = path.normalize(input);
847
+ if (path.parse(normalized).root === normalized) throw new PathGuardError("INVALID_PATH", "specify a directory below the filesystem root instead of the root itself");
848
+ const absolutePath = await resolveCanonicalPath(normalized);
849
+ if (absolutePath === await homeRealPath()) throw new PathGuardError("INVALID_PATH", "specify a directory below the home directory instead of the home directory itself");
850
+ if (process.platform !== "win32") {
851
+ for (const pseudoRoot of PSEUDO_FILESYSTEM_ROOTS) if (isInsideRoot(pseudoRoot, absolutePath)) throw new PathGuardError("FORBIDDEN", `pseudo filesystem is not readable: ${pseudoRoot}`);
852
+ }
853
+ for (const protectedRoot of policy.protectedRoots ?? []) if (isInsideRoot(protectedRoot, absolutePath)) throw new PathGuardError("FORBIDDEN", "path is inside a protected Larness directory");
854
+ return {
855
+ absolutePath,
856
+ rootScope: isInsideRoot(policy.root, absolutePath) ? "primary" : "external"
857
+ };
858
+ }
808
859
  // ../../packages/resources/src/files/fileService.ts
809
860
  const MAX_TOOL_OUTPUT_BYTES = 1048576;
810
861
  const MAX_TOOL_OUTPUT_LINES = 2e3;
811
862
  const MAX_READ_BYTES = 1048576;
812
863
  const MAX_WRITE_BYTES = 1048576;
864
+ /**
865
+ * Names skipped while walking a project by default. These are package stores
866
+ * and build outputs, not source. The ignore applies to entries discovered
867
+ * during a walk; an explicit `path` start is not filtered, so a caller can
868
+ * still inspect one deliberately. Full `.gitignore` semantics are not parsed
869
+ * here (see specs/092-search-ignore).
870
+ */
813
871
  const DEFAULT_IGNORED = /* @__PURE__ */ new Set([
814
872
  ".git",
815
873
  "node_modules",
816
- ".larness"
874
+ ".larness",
875
+ ".pnpm-store",
876
+ "dist",
877
+ "build",
878
+ "coverage",
879
+ "test-results",
880
+ "tmp",
881
+ ".turbo",
882
+ ".vite"
817
883
  ]);
818
884
  var FileError = class extends Error {
819
885
  code;
@@ -847,6 +913,7 @@ function mapPathError(error) {
847
913
  if (error instanceof PathGuardError) {
848
914
  if (error.code === "NOT_FOUND") throw new FileError("NOT_FOUND", error.message);
849
915
  if (error.code === "PATH_OUTSIDE_PROJECT") throw new FileError("PATH_OUTSIDE_PROJECT", error.message);
916
+ if (error.code === "FORBIDDEN") throw new FileError("FORBIDDEN", error.message);
850
917
  throw new FileError("VALIDATION_ERROR", error.message);
851
918
  }
852
919
  throw error;
@@ -892,8 +959,24 @@ async function resolveInput(rootReal, input) {
892
959
  mapPathError(error);
893
960
  }
894
961
  }
962
+ async function resolveReadInput(rootReal, input, access) {
963
+ try {
964
+ return await resolveReadPath({
965
+ root: rootReal,
966
+ ...access?.allowExternal === void 0 ? {} : { allowExternal: access.allowExternal },
967
+ ...access?.protectedRoots === void 0 ? {} : { protectedRoots: access.protectedRoots }
968
+ }, fromPosix(input));
969
+ } catch (error) {
970
+ mapPathError(error);
971
+ }
972
+ }
973
+ /** Display the target relative to the primary root, or absolute when external. */
974
+ function displayPath(rootReal, target, rootScope) {
975
+ return rootScope === "external" ? toPosix(target) : toPosix(path.relative(rootReal, target));
976
+ }
895
977
  async function listFiles(rootReal, options = {}) {
896
- const base = await resolveInput(rootReal, options.path ?? ".");
978
+ const resolved = await resolveReadInput(rootReal, options.path ?? ".", options.access);
979
+ const base = resolved.absolutePath;
897
980
  if (!(await statOrThrow(base)).isDirectory()) throw new FileError("VALIDATION_ERROR", "path is not a directory");
898
981
  const depth = Math.min(Math.max(Math.trunc(options.depth ?? 3), 1), 10);
899
982
  const limit = Math.min(Math.max(Math.trunc(options.limit ?? 500), 1), 2e3);
@@ -907,7 +990,7 @@ async function listFiles(rootReal, options = {}) {
907
990
  for (const entry of entries) {
908
991
  if (truncated) return;
909
992
  const absolute = path.join(dir, entry.name);
910
- const relativePath = toPosix(path.relative(rootReal, absolute));
993
+ const relativePath = displayPath(rootReal, absolute, resolved.rootScope);
911
994
  if (isIgnoredFile(relativePath, entry.name, ignore) || entry.isSymbolicLink()) continue;
912
995
  if (entry.isDirectory()) {
913
996
  files.push({
@@ -942,14 +1025,16 @@ async function listFiles(rootReal, options = {}) {
942
1025
  }
943
1026
  return {
944
1027
  files,
945
- truncated
1028
+ truncated,
1029
+ rootScope: resolved.rootScope
946
1030
  };
947
1031
  }
948
1032
  function hashContent(buffer) {
949
1033
  return createHash("sha256").update(buffer).digest("hex");
950
1034
  }
951
1035
  async function readTextFile(rootReal, options) {
952
- const target = await resolveInput(rootReal, options.path);
1036
+ const resolved = await resolveReadInput(rootReal, options.path, options.access);
1037
+ const target = resolved.absolutePath;
953
1038
  const info = await statOrThrow(target);
954
1039
  if (!info.isFile()) throw new FileError("VALIDATION_ERROR", "path is not a file");
955
1040
  if (info.size > 1048576) throw new FileError("TOO_LARGE", `file exceeds ${MAX_READ_BYTES} bytes`, { size: info.size });
@@ -969,12 +1054,13 @@ async function readTextFile(rootReal, options) {
969
1054
  const byteLength = Buffer.byteLength(content, "utf8");
970
1055
  const truncated = fitted.clipped || offset - 1 + kept.length < lines.length || byteLength > 1048576;
971
1056
  return {
972
- path: toPosix(path.relative(rootReal, target)),
1057
+ path: displayPath(rootReal, target, resolved.rootScope),
973
1058
  version,
974
1059
  content: byteLength > 1048576 ? Buffer.from(content, "utf8").subarray(0, MAX_TOOL_OUTPUT_BYTES).toString("utf8") : content,
975
1060
  truncated,
976
1061
  totalLines: lines.length,
977
1062
  offset,
1063
+ rootScope: resolved.rootScope,
978
1064
  nextOffset: Math.min(lines.length + 1, offset + kept.length)
979
1065
  };
980
1066
  }
@@ -1007,7 +1093,21 @@ function fitLines(lines, maxChars) {
1007
1093
  clipped
1008
1094
  };
1009
1095
  }
1096
+ function searchDirectory(relativePath) {
1097
+ const segments = relativePath.split("/");
1098
+ if (segments.length <= 1) return "(root)";
1099
+ const top = segments[0] ?? "";
1100
+ if ((top === "apps" || top === "packages") && segments.length > 2) return `${top}/${segments[1]}`;
1101
+ return top;
1102
+ }
1103
+ function sortedDirectories(counts) {
1104
+ return [...counts.entries()].map(([directory, matches]) => ({
1105
+ path: directory,
1106
+ matches
1107
+ })).sort((left, right) => right.matches - left.matches || left.path.localeCompare(right.path));
1108
+ }
1010
1109
  function globToRegExp(glob) {
1110
+ const recursive = !glob.includes("/");
1011
1111
  let pattern = "";
1012
1112
  for (let index = 0; index < glob.length; index += 1) {
1013
1113
  const char = glob[index] ?? "";
@@ -1022,12 +1122,13 @@ function globToRegExp(glob) {
1022
1122
  } else if (char === "?") pattern += "[^/]";
1023
1123
  else pattern += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
1024
1124
  }
1025
- return new RegExp(`^${pattern}$`);
1125
+ return new RegExp(`^${recursive ? "(?:.*/)?" : ""}${pattern}$`);
1026
1126
  }
1027
1127
  async function searchCode(rootReal, options) {
1028
1128
  const query = options.query.trim();
1029
1129
  if (query.length === 0 || query.length > 500) throw new FileError("VALIDATION_ERROR", "query must be 1-500 characters");
1030
- const base = await resolveInput(rootReal, options.path ?? ".");
1130
+ const resolved = await resolveReadInput(rootReal, options.path ?? ".", options.access);
1131
+ const base = resolved.absolutePath;
1031
1132
  const limit = Math.min(Math.max(Math.trunc(options.limit ?? 100), 1), 500);
1032
1133
  const ignore = options.ignore ?? [];
1033
1134
  const needle = options.caseSensitive === true ? query : query.toLowerCase();
@@ -1035,71 +1136,76 @@ async function searchCode(rootReal, options) {
1035
1136
  const maxFiles = Math.min(Math.max(Math.trunc(options.maxFiles ?? 2e3), 1), 2e4);
1036
1137
  const globPattern = options.glob === void 0 ? void 0 : globToRegExp(options.glob);
1037
1138
  const matches = [];
1139
+ const directoryCounts = /* @__PURE__ */ new Map();
1038
1140
  let scannedFiles = 0;
1039
1141
  let truncated = false;
1040
1142
  let scanBudgetExhausted = false;
1041
1143
  const searchFile = async (file) => {
1042
- if (truncated || scanBudgetExhausted) return;
1144
+ if (scanBudgetExhausted) return;
1043
1145
  const info = await statOrThrow(file);
1044
1146
  if (!info.isFile() || info.size > 262144) return;
1045
1147
  const buffer = await readFileOrThrow(file);
1046
1148
  if (buffer.includes(0)) return;
1047
- const relativePath = toPosix(path.relative(rootReal, file));
1048
- if (globPattern !== void 0 && !globPattern.test(relativePath)) return;
1149
+ const displayPathForFile = displayPath(rootReal, file, resolved.rootScope);
1150
+ const relativeToBase = toPosix(path.relative(base, file));
1151
+ const globPath = resolved.rootScope === "external" ? relativeToBase : displayPathForFile;
1152
+ if (globPattern !== void 0 && !globPattern.test(globPath)) return;
1049
1153
  scannedFiles += 1;
1050
1154
  if (scannedFiles >= maxFiles) scanBudgetExhausted = true;
1051
1155
  const lines = buffer.toString("utf8").split(/\r?\n/);
1052
1156
  for (let index = 0; index < lines.length; index += 1) {
1053
1157
  const line = lines[index] ?? "";
1054
1158
  if (!(options.caseSensitive === true ? line : line.toLowerCase()).includes(needle)) continue;
1055
- const context = contextLines === 0 ? void 0 : lines.slice(Math.max(0, index - contextLines), index + contextLines + 1).join("\n").slice(0, 2e3);
1159
+ const directory = searchDirectory(globPath);
1160
+ directoryCounts.set(directory, (directoryCounts.get(directory) ?? 0) + 1);
1161
+ if (matches.length >= limit) {
1162
+ truncated = true;
1163
+ continue;
1164
+ }
1165
+ const contextStartIndex = Math.max(0, index - contextLines);
1166
+ const context = contextLines === 0 ? void 0 : lines.slice(contextStartIndex, index + contextLines + 1).join("\n").slice(0, 2e3);
1056
1167
  matches.push({
1057
- path: relativePath,
1168
+ path: displayPathForFile,
1058
1169
  line: index + 1,
1059
1170
  preview: line.trim().slice(0, 240),
1060
- ...context === void 0 ? {} : { context }
1171
+ ...context === void 0 ? {} : {
1172
+ context,
1173
+ contextStart: contextStartIndex + 1
1174
+ }
1061
1175
  });
1062
- if (matches.length > limit) {
1063
- truncated = true;
1064
- return;
1065
- }
1066
1176
  }
1067
1177
  };
1068
1178
  if ((await statOrThrow(base)).isFile()) {
1069
1179
  await searchFile(base);
1070
- if (matches.length > limit) {
1071
- matches.pop();
1072
- truncated = true;
1073
- }
1074
1180
  return {
1075
1181
  matches,
1076
1182
  truncated,
1077
1183
  scannedFiles,
1078
- scanBudgetExhausted
1184
+ scanBudgetExhausted,
1185
+ directories: sortedDirectories(directoryCounts),
1186
+ rootScope: resolved.rootScope
1079
1187
  };
1080
1188
  }
1081
1189
  const walk = async (dir) => {
1082
- if (truncated) return;
1190
+ if (scanBudgetExhausted) return;
1083
1191
  const entries = await readDirOrThrow(dir, { withFileTypes: true });
1084
1192
  entries.sort((left, right) => left.name.localeCompare(right.name));
1085
1193
  for (const entry of entries) {
1086
- if (truncated) return;
1194
+ if (scanBudgetExhausted) return;
1087
1195
  const absolute = path.join(dir, entry.name);
1088
- if (isIgnoredFile(toPosix(path.relative(rootReal, absolute)), entry.name, ignore) || entry.isSymbolicLink()) continue;
1196
+ if (isIgnoredFile(displayPath(rootReal, absolute, resolved.rootScope), entry.name, ignore) || entry.isSymbolicLink()) continue;
1089
1197
  if (entry.isDirectory()) await walk(absolute);
1090
1198
  else if (entry.isFile()) await searchFile(absolute);
1091
1199
  }
1092
1200
  };
1093
1201
  await walk(base);
1094
- if (matches.length > limit) {
1095
- matches.pop();
1096
- truncated = true;
1097
- }
1098
1202
  return {
1099
1203
  matches,
1100
1204
  truncated,
1101
1205
  scannedFiles,
1102
- scanBudgetExhausted
1206
+ scanBudgetExhausted,
1207
+ directories: sortedDirectories(directoryCounts),
1208
+ rootScope: resolved.rootScope
1103
1209
  };
1104
1210
  }
1105
1211
  /**
@@ -1196,30 +1302,96 @@ function diagnosePatch(text, error) {
1196
1302
  if (!/^--- /m.test(text) || !/^\+\+\+ /m.test(text)) return "missing ---/+++ file headers";
1197
1303
  return (error instanceof Error ? error.message : "").trim().slice(0, 160) || "unrecognized diff format";
1198
1304
  }
1199
- async function createTextFile(rootReal, options) {
1305
+ /**
1306
+ * Create or replace a text file. Unlike `createTextFile`, an existing file is
1307
+ * overwritten. Passing `expectedVersion` narrows the window for a concurrent
1308
+ * editor; without it the replacement is deliberate and unconditional.
1309
+ */
1310
+ async function writeTextFile(rootReal, options) {
1200
1311
  if (options.content.includes("\0")) throw new FileError("VALIDATION_ERROR", "content must be text");
1201
1312
  const bytes = Buffer.byteLength(options.content, "utf8");
1202
1313
  if (bytes > 1048576) throw new FileError("TOO_LARGE", `content exceeds ${MAX_WRITE_BYTES} bytes`, { bytes });
1314
+ if (options.expectedVersion !== void 0 && !/^[a-f0-9]{64}$/.test(options.expectedVersion)) throw new FileError("VALIDATION_ERROR", "expectedVersion must be a sha256 hex");
1203
1315
  const target = await resolveInput(rootReal, options.path);
1204
- await mkdir(path.dirname(target), { recursive: true });
1316
+ let existing = null;
1205
1317
  try {
1206
- await writeFile(target, options.content, {
1207
- encoding: "utf8",
1208
- flag: "wx",
1209
- mode: 420
1210
- });
1318
+ existing = await readFileOrThrow(target);
1211
1319
  } catch (error) {
1212
- const code = error.code;
1213
- if (code === "EEXIST") throw new FileError("VERSION_CONFLICT", "file already exists; read it and use apply_patch to change it", { currentVersion: hashContent(await readFile(target)) });
1214
- throw new FileError("INTERNAL", `cannot write file: ${code ?? "unknown"}`);
1320
+ if (!(error instanceof FileError) || error.code !== "NOT_FOUND") throw error;
1321
+ }
1322
+ let previousVersion;
1323
+ if (existing !== null) {
1324
+ assertNotBinary(existing, options.path);
1325
+ previousVersion = hashContent(existing);
1326
+ if (options.expectedVersion !== void 0 && options.expectedVersion !== previousVersion) throw new FileError("VERSION_CONFLICT", "file version does not match", { currentVersion: previousVersion });
1327
+ } else if (options.expectedVersion !== void 0) throw new FileError("VERSION_CONFLICT", "file does not exist", { currentVersion: null });
1328
+ await mkdir(path.dirname(target), { recursive: true });
1329
+ if (existing !== null && options.expectedVersion !== void 0) {
1330
+ const current = await readFileOrThrow(target);
1331
+ if (hashContent(current) !== options.expectedVersion) throw new FileError("VERSION_CONFLICT", "file changed while writing", { currentVersion: hashContent(current) });
1215
1332
  }
1216
- const buffer = await readFile(target);
1333
+ await writeFileOrThrow(target, options.content);
1334
+ const buffer = await readFileOrThrow(target);
1217
1335
  return {
1218
1336
  path: toPosix(path.relative(rootReal, target)),
1219
1337
  version: hashContent(buffer),
1338
+ ...previousVersion === void 0 ? {} : { previousVersion },
1220
1339
  bytes,
1221
1340
  lines: options.content.split("\n").length,
1222
- created: true
1341
+ created: existing === null
1342
+ };
1343
+ }
1344
+ function occurrenceIndexes(haystack, needle) {
1345
+ const indexes = [];
1346
+ let offset = 0;
1347
+ while (offset <= haystack.length) {
1348
+ const index = haystack.indexOf(needle, offset);
1349
+ if (index === -1) break;
1350
+ indexes.push(index);
1351
+ offset = index + needle.length;
1352
+ }
1353
+ return indexes;
1354
+ }
1355
+ /**
1356
+ * Replace literal text in an existing text file. The match is exact; when the
1357
+ * file uses CRLF, LF-only `oldString`/`newString` are converted to CRLF so a
1358
+ * model does not have to guess the line ending.
1359
+ */
1360
+ async function editTextFile(rootReal, options) {
1361
+ if (options.oldString.length === 0) throw new FileError("VALIDATION_ERROR", "oldString must not be empty");
1362
+ if (options.oldString === options.newString) throw new FileError("VALIDATION_ERROR", "oldString and newString must differ");
1363
+ const target = await resolveInput(rootReal, options.path);
1364
+ if (!(await statOrThrow(target)).isFile()) throw new FileError("VALIDATION_ERROR", "path is not a file");
1365
+ const originalBuffer = await readFileOrThrow(target);
1366
+ assertNotBinary(originalBuffer, options.path);
1367
+ const original = originalBuffer.toString("utf8");
1368
+ const previousVersion = hashContent(originalBuffer);
1369
+ let oldString = options.oldString;
1370
+ let newString = options.newString;
1371
+ let indexes = occurrenceIndexes(original, oldString);
1372
+ if (indexes.length === 0 && original.includes("\r\n") && !oldString.includes("\r\n")) {
1373
+ oldString = oldString.replace(/\r?\n/g, "\r\n");
1374
+ newString = newString.replace(/\r?\n/g, "\r\n");
1375
+ indexes = occurrenceIndexes(original, oldString);
1376
+ }
1377
+ if (indexes.length === 0) throw new FileError("INVALID_PATCH", "oldString was not found");
1378
+ if (indexes.length > 1 && options.replaceAll !== true) throw new FileError("INVALID_PATCH", `oldString matches ${indexes.length} times; include more context or set replaceAll`);
1379
+ const updated = options.replaceAll === true ? original.split(oldString).join(newString) : `${original.slice(0, indexes[0])}${newString}${original.slice(indexes[0] + oldString.length)}`;
1380
+ const currentBuffer = await readFileOrThrow(target);
1381
+ if (hashContent(currentBuffer) !== previousVersion) throw new FileError("VERSION_CONFLICT", "file changed while editing", { currentVersion: hashContent(currentBuffer) });
1382
+ await writeFileOrThrow(target, updated);
1383
+ const changes = diffLines(original, updated, { newlineIsToken: false });
1384
+ let additions = 0;
1385
+ let deletions = 0;
1386
+ for (const change of changes) if (change.added === true) additions += change.count ?? 0;
1387
+ else if (change.removed === true) deletions += change.count ?? 0;
1388
+ return {
1389
+ path: toPosix(path.relative(rootReal, target)),
1390
+ version: hashContent(Buffer.from(updated, "utf8")),
1391
+ previousVersion,
1392
+ replacements: indexes.length,
1393
+ additions,
1394
+ deletions
1223
1395
  };
1224
1396
  }
1225
1397
  async function applyPatch$1(rootReal, options) {
@@ -2077,28 +2249,6 @@ var ManagedPty = class {
2077
2249
  return this.#stop;
2078
2250
  }
2079
2251
  };
2080
- const PAIRING_CODE_TTL_MS = 3e5;
2081
- const PAIRING_REQUEST_TTL_MS = 6e5;
2082
- const ENROLLMENT_TTL_MS = 3e5;
2083
- function generatePairingCode() {
2084
- const characters = [];
2085
- const limit = 256;
2086
- while (characters.length < 10) {
2087
- const byte = randomInt(0, 256);
2088
- if (byte < limit) characters.push("0123456789ABCDEFGHJKMNPQRSTVWXYZ"[byte % 32] ?? "0");
2089
- }
2090
- return characters.join("");
2091
- }
2092
- function formatPairingCode(code) {
2093
- const normalized = normalizePairingCode(code);
2094
- return `${normalized.slice(0, 5)}-${normalized.slice(5)}`;
2095
- }
2096
- function normalizePairingCode(input) {
2097
- return input.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1");
2098
- }
2099
- function generateShortCode() {
2100
- return randomInt(0, 1e6).toString().padStart(6, "0");
2101
- }
2102
2252
  // src/dev-web/paths.ts
2103
2253
  const Manifest = z.object({
2104
2254
  dependencies: z.record(z.string(), z.string()).optional(),
@@ -2284,4 +2434,4 @@ function waitChildMessage(child, parse, signal, phase = "Server") {
2284
2434
  if (signal?.aborted) abort();
2285
2435
  });
2286
2436
  }
2287
- export { isInsideRoot as $, validateGitPath as A, saveEditableFile as B, gitPrefix as C, runGit as D, parseStatus as E, fileEntryVersion as F, createTextFile as G, DEFAULT_IGNORED as H, listDirectory as I, listFiles as J, hashContent as K, normalizeFilePath as L, scanWatchPath as M, FileManagerError as N, scopeStatusToPrefix as O, encodeEditableContent as P, canonicalDirectory as Q, readEditableFile as R, GitError as S, parseLog as T, FileError as U, searchFiles as V, applyPatch$1 as W, searchCode as X, readTextFile as Y, PathGuardError as Z, formatPairingCode as _, DevWebControl as a, resolveWindowsExecutable as at, normalizePairingCode as b, EntryConfigError as c, processCommandLine as ct, devWebCache as d, windowsTcpListeners as dt, resolveInsideRoot as et, isDevPath as f, commandEnvironment as ft, PAIRING_REQUEST_TTL_MS as g, OutputRedactor as gt, PAIRING_CODE_TTL_MS as h, windowsPowerShell as ht, DevWebAttachedSchema as i, stopCommandGroup as it, createDirectoryWatcher as j, snapshotOf as k, HMR_PATH as l, processSnapshot as lt, ENROLLMENT_TTL_MS as m, powerShellEncodedCommand as mt, receiveDevWebTarget as n, groupAlive as nt, DevWebTargetSchema as o, windowsLaunch as ot, permittedPath as p, powerShellArguments as pt, isIgnoredFile as q, waitChildMessage as r, runCommand as rt, DevWebUnavailable as s, processAlive as st, managedWebFiles as t, MAX_COMMAND_OUTPUT_BYTES as tt, NONCE_MARKER as u, terminateProcessTree as ut, generatePairingCode as v, parseBranches as w, ManagedPty as x, generateShortCode as y, resolveFilePath as z };
2437
+ export { resolveWindowsExecutable as $, normalizeFilePath as A, isIgnoredFile as B, validateGitPath as C, encodeEditableContent as D, FileManagerError as E, DEFAULT_IGNORED as F, PathGuardError as G, readTextFile as H, FileError as I, resolveInsideRoot as J, canonicalDirectory as K, applyPatch$1 as L, resolveFilePath as M, saveEditableFile as N, fileEntryVersion as O, searchFiles as P, stopCommandGroup as Q, editTextFile as R, snapshotOf as S, scanWatchPath as T, searchCode as U, listFiles as V, writeTextFile as W, groupAlive as X, MAX_COMMAND_OUTPUT_BYTES as Y, runCommand as Z, parseBranches as _, DevWebControl as a, windowsTcpListeners as at, runGit as b, EntryConfigError as c, powerShellEncodedCommand as ct, devWebCache as d, windowsLaunch as et, isDevPath as f, gitPrefix as g, GitError as h, DevWebAttachedSchema as i, terminateProcessTree as it, readEditableFile as j, listDirectory as k, HMR_PATH as l, windowsPowerShell as lt, ManagedPty as m, receiveDevWebTarget as n, processCommandLine as nt, DevWebTargetSchema as o, commandEnvironment as ot, permittedPath as p, isInsideRoot as q, waitChildMessage as r, processSnapshot as rt, DevWebUnavailable as s, powerShellArguments as st, managedWebFiles as t, processAlive as tt, NONCE_MARKER as u, OutputRedactor as ut, parseLog as v, createDirectoryWatcher as w, scopeStatusToPrefix as x, parseStatus as y, hashContent as z };
@@ -0,0 +1,77 @@
1
+ import { constants } from "node:fs";
2
+ import path from "node:path";
3
+ import { access, chmod, mkdir, stat } from "node:fs/promises";
4
+ import envPaths from "env-paths";
5
+ // src/platform/paths.ts
6
+ const DATA_SUBDIRS = [
7
+ "logs",
8
+ "backups",
9
+ "tmp",
10
+ "sessions",
11
+ "artifacts",
12
+ "secrets",
13
+ "ipc"
14
+ ];
15
+ var DataDirError = class extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "DataDirError";
19
+ }
20
+ };
21
+ function defaultDataDir() {
22
+ return envPaths("larness", { suffix: "" }).data;
23
+ }
24
+ function resolveDataDir(env = process.env) {
25
+ const override = env.LARNESS_DATA_DIR?.trim();
26
+ return override ? path.resolve(override) : defaultDataDir();
27
+ }
28
+ async function ensureDir(dir) {
29
+ try {
30
+ const info = await stat(dir);
31
+ if (!info.isDirectory()) throw new DataDirError(`data directory path is not a directory: ${dir}`);
32
+ let hardened = false;
33
+ if (process.platform !== "win32" && (info.mode & 63) !== 0) try {
34
+ await chmod(dir, 448);
35
+ hardened = true;
36
+ } catch (error) {
37
+ throw new DataDirError(`cannot restrict permissions on ${dir}: ${error.code}`);
38
+ }
39
+ return {
40
+ created: false,
41
+ hardened
42
+ };
43
+ } catch (error) {
44
+ if (error instanceof DataDirError) throw error;
45
+ if (error.code !== "ENOENT") throw new DataDirError(`cannot access data directory ${dir}: ${error.code}`);
46
+ try {
47
+ await mkdir(dir, {
48
+ recursive: true,
49
+ mode: 448
50
+ });
51
+ } catch (mkdirError) {
52
+ throw new DataDirError(`cannot create data directory ${dir}: ${mkdirError.code}`);
53
+ }
54
+ return {
55
+ created: true,
56
+ hardened: false
57
+ };
58
+ }
59
+ }
60
+ async function ensureDataDirs(dataDir) {
61
+ const root = await ensureDir(dataDir);
62
+ let hardened = root.hardened;
63
+ for (const name of DATA_SUBDIRS) {
64
+ const result = await ensureDir(path.join(dataDir, name));
65
+ hardened = hardened || result.hardened;
66
+ }
67
+ try {
68
+ await access(dataDir, constants.W_OK);
69
+ } catch {
70
+ throw new DataDirError(`data directory is not writable: ${dataDir}`);
71
+ }
72
+ return {
73
+ created: root.created,
74
+ hardened
75
+ };
76
+ }
77
+ export { ensureDataDirs as n, resolveDataDir as r, DATA_SUBDIRS as t };
@@ -1,7 +1,10 @@
1
- import { c as loadConfig, i as inspectDatabase, m as SERVER_VERSION, r as resolveDataDir } from "./paths-DUfwiH2X.js";
2
- import { n as inspectInstanceLock } from "./lock-DyEoZgG_.js";
1
+ import { i as inspectInstanceLock, l as loadConfig, t as inspectDatabase } from "./inspect-XgAc84F9.js";
2
+ import { t as findMainLogFile } from "./log-files-CFOaEy6O.js";
3
+ import { r as resolveDataDir } from "./paths-BhVn34MT.js";
4
+ import { t as SERVER_VERSION } from "./version-ui_X8H2k.js";
3
5
  import path from "node:path";
4
6
  // src/status.ts
7
+ const FORMAL_SERVICES_NOTE = "PM2 services run separately; larness stop does not stop or restart them";
5
8
  async function collectStatus(options = {}) {
6
9
  const env = options.env ?? process.env;
7
10
  const dataDir = options.dataDir ?? resolveDataDir(env);
@@ -12,6 +15,7 @@ async function collectStatus(options = {}) {
12
15
  });
13
16
  const lock = await inspectInstanceLock(dataDir);
14
17
  const database = inspectDatabase(path.join(dataDir, "larness.db"));
18
+ const mainLog = await findMainLogFile(dataDir);
15
19
  const running = lock?.alive === true;
16
20
  const record = lock?.record ?? null;
17
21
  const warnings = [];
@@ -43,7 +47,16 @@ async function collectStatus(options = {}) {
43
47
  origin: loaded.webAuthn.origin,
44
48
  reason: loaded.webAuthn.reason
45
49
  },
46
- warnings
50
+ warnings,
51
+ dataDir,
52
+ mode: running ? record?.mode ?? "unknown" : null,
53
+ dev: running && record?.dev === true,
54
+ logPath: mainLog,
55
+ daemonLogPath: running && record?.mode === "background" ? path.join(dataDir, "logs", "daemon.log") : null,
56
+ formalServices: {
57
+ managedSeparately: true,
58
+ note: FORMAL_SERVICES_NOTE
59
+ }
47
60
  };
48
61
  }
49
62
  export { collectStatus as t };
@@ -1,9 +1,27 @@
1
- import { n as connectIpc } from "./client-D88ULjn9.js";
2
- import { r as resolveDataDir } from "./paths-DUfwiH2X.js";
3
- import { t as collectStatus } from "./status-D2oSIMoj.js";
1
+ import { n as connectIpc } from "./client-D_Ni3Zpx.js";
2
+ import { r as resolveDataDir } from "./paths-BhVn34MT.js";
3
+ import { t as collectStatus } from "./status-CV_zWfs6.js";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
4
6
  // src/cli/status.ts
5
- async function readStatus() {
6
- const dataDir = resolveDataDir();
7
+ /**
8
+ * Merges the live IPC snapshot over the local report. A server started before
9
+ * this CLI version does not send the newer fields, so fall back per field
10
+ * instead of formatting an incomplete object.
11
+ */
12
+ function completeStatus(remote, fallback) {
13
+ const defined = Object.fromEntries(Object.entries(remote).filter(([, value]) => value !== void 0));
14
+ const merged = {
15
+ ...fallback,
16
+ ...defined
17
+ };
18
+ return {
19
+ ...merged,
20
+ warnings: merged.warnings.filter((warning) => !(merged.running && warning === "server is not running"))
21
+ };
22
+ }
23
+ async function readStatus(options = {}) {
24
+ const dataDir = options.dataDir ?? resolveDataDir(options.env ?? process.env);
7
25
  try {
8
26
  const client = await connectIpc({
9
27
  dataDir,
@@ -11,15 +29,25 @@ async function readStatus() {
11
29
  timeoutMs: 1500
12
30
  });
13
31
  try {
14
- return await client.request("system.status", {}, 1500);
32
+ return completeStatus(await client.request("system.status", {}, 1500), await collectStatus({
33
+ dataDir,
34
+ ...options.env === void 0 ? {} : { env: options.env }
35
+ }));
15
36
  } finally {
16
37
  client.close();
17
38
  }
18
39
  } catch {
19
- return collectStatus({ dataDir });
40
+ return collectStatus({
41
+ dataDir,
42
+ ...options.env === void 0 ? {} : { env: options.env }
43
+ });
20
44
  }
21
45
  }
22
- try {
46
+ function isEntryPoint() {
47
+ const entry = process.argv[1];
48
+ return entry !== void 0 && path.resolve(entry) === fileURLToPath(import.meta.url);
49
+ }
50
+ if (isEntryPoint()) try {
23
51
  const status = await readStatus();
24
52
  process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
25
53
  } catch (error) {
@@ -27,4 +55,4 @@ try {
27
55
  process.stderr.write(`[larness] status failed: ${message}\n`);
28
56
  process.exitCode = 1;
29
57
  }
30
- export {};
58
+ export { completeStatus, readStatus };