@intellectual-frontiers/ergonex 0.3.1 → 0.3.2

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 (54) hide show
  1. package/dist/desired.d.ts +1 -1
  2. package/dist/mod.js +769 -909
  3. package/dist/modules/external.d.ts +1 -1
  4. package/dist/modules/registry.d.ts +1 -1
  5. package/dist/modules/types.d.ts +2 -2
  6. package/dist/plan.d.ts +1 -1
  7. package/dist/render.d.ts +2 -2
  8. package/dist/state-record.d.ts +2 -2
  9. package/dist/tools/catalog.d.ts +1 -1
  10. package/dist/vendor/ts/runtime/http-client.d.ts +1 -1
  11. package/ergonex.mjs +2249 -2250
  12. package/package.json +3 -2
  13. package/dist/vendor/ts/kernel/archive.d.ts +0 -147
  14. package/dist/vendor/ts/kernel/assess.d.ts +0 -247
  15. package/dist/vendor/ts/kernel/attest.d.ts +0 -164
  16. package/dist/vendor/ts/kernel/base64.d.ts +0 -24
  17. package/dist/vendor/ts/kernel/cbor.d.ts +0 -39
  18. package/dist/vendor/ts/kernel/cms.d.ts +0 -106
  19. package/dist/vendor/ts/kernel/cose.d.ts +0 -34
  20. package/dist/vendor/ts/kernel/crypt.d.ts +0 -30
  21. package/dist/vendor/ts/kernel/csv.d.ts +0 -38
  22. package/dist/vendor/ts/kernel/der.d.ts +0 -67
  23. package/dist/vendor/ts/kernel/documentation.d.ts +0 -118
  24. package/dist/vendor/ts/kernel/dsse.d.ts +0 -137
  25. package/dist/vendor/ts/kernel/evidence.d.ts +0 -212
  26. package/dist/vendor/ts/kernel/glob.d.ts +0 -64
  27. package/dist/vendor/ts/kernel/grc.d.ts +0 -356
  28. package/dist/vendor/ts/kernel/http.d.ts +0 -46
  29. package/dist/vendor/ts/kernel/json5.d.ts +0 -46
  30. package/dist/vendor/ts/kernel/layers.d.ts +0 -35
  31. package/dist/vendor/ts/kernel/md5.d.ts +0 -19
  32. package/dist/vendor/ts/kernel/media-types.d.ts +0 -28
  33. package/dist/vendor/ts/kernel/mod.d.ts +0 -89
  34. package/dist/vendor/ts/kernel/ocsf-types.auto.d.ts +0 -4374
  35. package/dist/vendor/ts/kernel/ocsf.d.ts +0 -160
  36. package/dist/vendor/ts/kernel/oscal.d.ts +0 -356
  37. package/dist/vendor/ts/kernel/otel.d.ts +0 -365
  38. package/dist/vendor/ts/kernel/otlp.d.ts +0 -83
  39. package/dist/vendor/ts/kernel/png.d.ts +0 -124
  40. package/dist/vendor/ts/kernel/render.d.ts +0 -111
  41. package/dist/vendor/ts/kernel/schedule.d.ts +0 -207
  42. package/dist/vendor/ts/kernel/semver.d.ts +0 -94
  43. package/dist/vendor/ts/kernel/sha256.d.ts +0 -29
  44. package/dist/vendor/ts/kernel/signals.d.ts +0 -371
  45. package/dist/vendor/ts/kernel/sigv4.d.ts +0 -67
  46. package/dist/vendor/ts/kernel/test-record.d.ts +0 -222
  47. package/dist/vendor/ts/kernel/test-report.d.ts +0 -294
  48. package/dist/vendor/ts/kernel/toml.d.ts +0 -51
  49. package/dist/vendor/ts/kernel/trace.d.ts +0 -169
  50. package/dist/vendor/ts/kernel/ts-literal.d.ts +0 -62
  51. package/dist/vendor/ts/kernel/uuid.d.ts +0 -53
  52. package/dist/vendor/ts/kernel/webauthn.d.ts +0 -212
  53. package/dist/vendor/ts/kernel/xml.d.ts +0 -73
  54. package/dist/vendor/ts/kernel/yaml.d.ts +0 -44
package/ergonex.mjs CHANGED
@@ -414,7 +414,7 @@ function helpOf(program, summary, spec, operands = []) {
414
414
  ].join(`
415
415
  `);
416
416
  }
417
- // ../ts/kernel/base64.ts
417
+ // ../formats/src/base64.ts
418
418
  function toBase64(bytes) {
419
419
  let s = "";
420
420
  for (let i = 0;i < bytes.length; i += 32768)
@@ -432,7 +432,7 @@ function fromBase64(text) {
432
432
  return ok(out);
433
433
  }
434
434
 
435
- // ../ts/kernel/archive.ts
435
+ // ../formats/src/archive.ts
436
436
  function formatArchiveError(e) {
437
437
  switch (e.kind) {
438
438
  case "damaged":
@@ -744,7 +744,7 @@ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } fr
744
744
  import process2 from "node:process";
745
745
  import { fileURLToPath } from "node:url";
746
746
 
747
- // ../ts/kernel/glob.ts
747
+ // ../formats/src/glob.ts
748
748
  var ESCAPE_OUTSIDE = new Set(["!", "$", "(", ")", "*", "+", ".", "=", "?", "[", "\\", "^", "{", "|"]);
749
749
  var ESCAPE_INSIDE = new Set(["-", "\\", "]"]);
750
750
  var CLASSES = new Map([
@@ -1149,15 +1149,10 @@ import * as os from "node:os";
1149
1149
  import { basename as basename4, delimiter as delimiter3, join as join4, resolve as resolvePath } from "node:path";
1150
1150
  import process3 from "node:process";
1151
1151
 
1152
- // ../ts/kernel/http.ts
1152
+ // ../formats/src/http.ts
1153
1153
  var SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS", "TRACE"]);
1154
1154
 
1155
- // ../ts/kernel/sha256.ts
1156
- var SHA256 = /^[0-9a-f]{64}$/;
1157
- function sha256Of(text) {
1158
- const t = text.trim().toLowerCase();
1159
- return SHA256.test(t) ? t : undefined;
1160
- }
1155
+ // ../formats/src/hex.ts
1161
1156
  function toHex(bytes) {
1162
1157
  let out = "";
1163
1158
  for (const b of bytes)
@@ -1172,19 +1167,6 @@ function fromHex(text) {
1172
1167
  out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
1173
1168
  return out;
1174
1169
  }
1175
- async function sha256(data) {
1176
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
1177
- const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
1178
- return toHex(new Uint8Array(digest));
1179
- }
1180
- function sameSha256(a, b) {
1181
- if (a.length !== b.length)
1182
- return false;
1183
- let d = 0;
1184
- for (let i = 0;i < a.length; i++)
1185
- d |= a.charCodeAt(i) ^ b.charCodeAt(i);
1186
- return d === 0;
1187
- }
1188
1170
 
1189
1171
  // ../ts/kernel/otel.ts
1190
1172
  var TRACE_ID = /^[0-9a-f]{32}$/;
@@ -2474,7 +2456,7 @@ var riskDecoder = object({
2474
2456
  reviewBy: instantDecoder
2475
2457
  }, { description: string, controls: array(string) });
2476
2458
 
2477
- // ../ts/kernel/json5.ts
2459
+ // ../formats/src/json5.ts
2478
2460
  class Stop extends Error {
2479
2461
  at;
2480
2462
  constructor(at, message) {
@@ -2675,7 +2657,7 @@ function parseJson5(text) {
2675
2657
  return err({ kind: "json5", line: before.length, column: (before.at(-1)?.length ?? 0) + 1, message: `expected ${e.message}` });
2676
2658
  }
2677
2659
  }
2678
- // ../ts/kernel/toml.ts
2660
+ // ../formats/src/toml.ts
2679
2661
  var CONTROL = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8, 10)}-${String.fromCharCode(31, 127)}]`);
2680
2662
 
2681
2663
  // ../ts/runtime/grc.ts
@@ -2745,7 +2727,27 @@ var FINDING_SEVERITY = {
2745
2727
  critical: SEVERITY.FATAL
2746
2728
  };
2747
2729
  var telemetries = new WeakMap;
2748
- // ../ts/kernel/sigv4.ts
2730
+ // ../crypto/src/sha256.ts
2731
+ var SHA256 = /^[0-9a-f]{64}$/;
2732
+ function sha256Of(text) {
2733
+ const t = text.trim().toLowerCase();
2734
+ return SHA256.test(t) ? t : undefined;
2735
+ }
2736
+ async function sha256(data) {
2737
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
2738
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
2739
+ return toHex(new Uint8Array(digest));
2740
+ }
2741
+ function sameSha256(a, b) {
2742
+ if (a.length !== b.length)
2743
+ return false;
2744
+ let d = 0;
2745
+ for (let i = 0;i < a.length; i++)
2746
+ d |= a.charCodeAt(i) ^ b.charCodeAt(i);
2747
+ return d === 0;
2748
+ }
2749
+
2750
+ // ../crypto/src/sigv4.ts
2749
2751
  var UNSIGNED_HEADERS = new Set(["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id", "traceparent", "tracestate"]);
2750
2752
  var encoder = new TextEncoder;
2751
2753
 
@@ -2920,7 +2922,7 @@ async function acquireLock(path, options) {
2920
2922
  process5.on("exit", release);
2921
2923
  return { holder, release };
2922
2924
  }
2923
- // ../ts/kernel/dsse.ts
2925
+ // ../crypto/src/dsse.ts
2924
2926
  var utf8 = new TextEncoder;
2925
2927
  var lowerHex = (input, path = "$") => typeof input === "string" && /^(?:[0-9a-f]{2})+$/.test(input) ? ok(input) : err({ kind: "decode", path, expected: "lower-case hexadecimal", found: describe(input) });
2926
2928
  var resourceDescriptorDecoder = object({ name: string, digest: record(lowerHex) }, { uri: string, mediaType: string, annotations: record(unknownValue) });
@@ -2930,7 +2932,7 @@ var envelopeDecoder = object({
2930
2932
  payloadType: string,
2931
2933
  signatures: array(object({ sig: base64Text }, { keyid: string }))
2932
2934
  });
2933
- // ../ts/kernel/xml.ts
2935
+ // ../formats/src/xml.ts
2934
2936
  var FORBIDDEN = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(11, 12)}${String.fromCharCode(14)}-${String.fromCharCode(31)}\\ufffe\\uffff]`, "g");
2935
2937
  // ../ts/runtime/stdio.ts
2936
2938
  import { writeSync as fdWriteSync } from "node:fs";
@@ -3162,26 +3164,11 @@ var which2 = which;
3162
3164
  var stderr2 = stderr;
3163
3165
  var stdin2 = stdin;
3164
3166
  var stdout2 = stdout;
3165
- // ../ts/kernel/evidence.ts
3166
- var GENESIS = "0".repeat(64);
3167
- var sha256Decoder = (input, path = "$") => {
3168
- const s = typeof input === "string" && /^[0-9a-f]{64}$/.test(input) ? sha256Of(input) : undefined;
3169
- return s === undefined ? err({ kind: "decode", path, expected: "a SHA-256 (64 lower-case hexadecimal digits)", found: typeof input }) : ok(s);
3170
- };
3171
- var ledgerEntryDecoder = object({
3172
- seq: refine(integer, "positive", (n) => n >= 1),
3173
- prev: sha256Decoder,
3174
- at: instantDecoder,
3175
- kind: string,
3176
- subject: object({ kind: string, id: string }),
3177
- evidence: sha256Decoder,
3178
- digest: sha256Decoder
3179
- });
3180
- var manifestDecoder = object({
3181
- files: array(object({ path: string, size: refine(integer, "size", (n) => n >= 0), sha256: sha256Decoder }))
3182
- });
3183
-
3184
- // ../ts/kernel/uuid.ts
3167
+ // ../formats/src/cbor.ts
3168
+ var UTF8 = new TextDecoder("utf-8", { fatal: true });
3169
+ // ../crypto/src/md5.ts
3170
+ var T = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0);
3171
+ // ../crypto/src/uuid.ts
3185
3172
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3186
3173
  function uuidOf(text) {
3187
3174
  const t = text.trim().toLowerCase();
@@ -3229,2272 +3216,1703 @@ function nameOf(parts) {
3229
3216
  function uuidV5Of(namespace, parts) {
3230
3217
  return uuidV5(namespace, nameOf(parts));
3231
3218
  }
3219
+ // ../crypto/src/webauthn.ts
3220
+ var clientData = object({ type: string, challenge: string, origin: string }, { crossOrigin: boolean, topOrigin: string });
3221
+ var kind = literal("public-key");
3222
+ var extensionResults = record(unknownValue);
3223
+ // src/platform/r-lock.ts
3224
+ var acquireLock2 = acquireLock;
3225
+ var describeHolder2 = describeHolder;
3226
+ var readHolder2 = readHolder;
3232
3227
 
3233
- // ../ts/kernel/attest.ts
3234
- var PASSING = new Set(["pass"]);
3235
- // ../ts/kernel/cbor.ts
3236
- var UTF8 = new TextDecoder("utf-8", { fatal: true });
3237
- // ../ts/kernel/md5.ts
3238
- var T = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0);
3239
- // ../ts/kernel/semver.ts
3240
- var PATTERN = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
3241
- function parseSemVer(text) {
3242
- const m = PATTERN.exec(text.trim());
3243
- if (m === null)
3244
- return err(`${JSON.stringify(text)} is not a semantic version (major.minor.patch[-pre][+build])`);
3245
- const [, major = "", minor = "", patch = "", pre, build] = m;
3246
- const parts = [Number(major), Number(minor), Number(patch)];
3247
- if (!parts.every(Number.isSafeInteger))
3248
- return err(`${JSON.stringify(text)} has a number too large`);
3249
- return ok({
3250
- major: parts[0],
3251
- minor: parts[1],
3252
- patch: parts[2],
3253
- ...pre === undefined ? {} : { pre },
3254
- ...build === undefined ? {} : { build }
3255
- });
3228
+ // src/portable.ts
3229
+ function describePortableError(e) {
3230
+ switch (e.kind) {
3231
+ case "empty":
3232
+ return "a path segment is empty";
3233
+ case "dot":
3234
+ return `the path segment ${JSON.stringify(e.segment)} would leave its folder`;
3235
+ case "forbidden-character":
3236
+ return `the path segment ${JSON.stringify(e.segment)} holds ${JSON.stringify(e.character)}, which Windows does not allow in a name`;
3237
+ case "control-character":
3238
+ return `the path segment ${JSON.stringify(e.segment)} holds a control character`;
3239
+ case "trailing-dot-or-space":
3240
+ return `the path segment ${JSON.stringify(e.segment)} ends in a dot or a space, which Windows drops`;
3241
+ case "device-name":
3242
+ return `the path segment ${JSON.stringify(e.segment)} is the Windows device name ${e.device}, with or without an extension, in any case`;
3243
+ case "too-long":
3244
+ return `the path segment is ${e.bytes} bytes in UTF-8, and a name may have 255`;
3245
+ case "not-nfc":
3246
+ return `the path segment ${JSON.stringify(e.segment)} is not in Unicode normalization form NFC, so it would be another name on macOS`;
3247
+ default:
3248
+ return absurd(e);
3249
+ }
3256
3250
  }
3257
- function dottedParts(version) {
3258
- return version.trim().replace(/^v/, "").split(/[.+_-]/).map((p) => Number.parseInt(p, 10)).map((n) => Number.isNaN(n) ? 0 : n);
3251
+ var FORBIDDEN2 = new Set(["<", ">", ":", '"', "/", "\\", "|", "?", "*"]);
3252
+ var DEVICE = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9\u00b9\u00b2\u00b3]|LPT[0-9\u00b9\u00b2\u00b3])$/i;
3253
+ function isDeviceName(name) {
3254
+ return DEVICE.test((name.split(".")[0] ?? "").replace(/ +$/, ""));
3259
3255
  }
3260
- function compareDotted(a, b) {
3261
- const x = dottedParts(a);
3262
- const y = dottedParts(b);
3263
- for (let i = 0;i < Math.max(x.length, y.length); i++) {
3264
- const d = (x[i] ?? 0) - (y[i] ?? 0);
3265
- if (d !== 0)
3266
- return Math.sign(d);
3256
+ var MAX_SEGMENT_BYTES = 255;
3257
+ function segment(text) {
3258
+ if (text === "")
3259
+ return err({ kind: "empty" });
3260
+ if (text === "." || text === "..")
3261
+ return err({ kind: "dot", segment: text });
3262
+ for (const ch of text) {
3263
+ const code = ch.codePointAt(0) ?? 0;
3264
+ if (code < 32 || code === 127)
3265
+ return err({ kind: "control-character", segment: text });
3266
+ if (FORBIDDEN2.has(ch))
3267
+ return err({ kind: "forbidden-character", segment: text, character: ch });
3267
3268
  }
3268
- return 0;
3269
- }
3270
- function atLeast(have, want) {
3271
- return compareDotted(have, want) >= 0;
3269
+ if (text.endsWith(".") || text.endsWith(" "))
3270
+ return err({ kind: "trailing-dot-or-space", segment: text });
3271
+ const stem = (text.split(".")[0] ?? "").replace(/ +$/, "");
3272
+ if (isDeviceName(text))
3273
+ return err({
3274
+ kind: "device-name",
3275
+ segment: text,
3276
+ device: stem.toUpperCase()
3277
+ });
3278
+ const bytes = new TextEncoder().encode(text).length;
3279
+ if (bytes > MAX_SEGMENT_BYTES)
3280
+ return err({ kind: "too-long", segment: text.slice(0, 40), bytes });
3281
+ if (text !== text.normalize("NFC"))
3282
+ return err({ kind: "not-nfc", segment: text });
3283
+ return ok(text);
3272
3284
  }
3273
- function versionIn(text) {
3274
- return /\d+(?:\.\d+)+/.exec(text)?.[0];
3285
+ function repoPath(segments) {
3286
+ if (segments.length === 0)
3287
+ return err({ kind: "empty" });
3288
+ const made = [];
3289
+ for (const s of segments) {
3290
+ const r = segment(s);
3291
+ if (r.kind === "err")
3292
+ return r;
3293
+ made.push(r.value);
3294
+ }
3295
+ return ok(made.join("/"));
3275
3296
  }
3276
- var IDENT = "(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)";
3277
- var PART = "(0|[1-9][0-9]*|[xX*])";
3278
- var PARTIAL = new RegExp(`^v?${PART}(?:\\.${PART}(?:\\.${PART}(?:-(${IDENT}(?:\\.${IDENT})*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)?)?$`);
3279
- var ver = (major, minor, patch, pre) => ({
3280
- major,
3281
- minor,
3282
- patch,
3283
- ...pre === undefined ? {} : { pre }
3284
- });
3285
- var at = (op, version) => ({ op, version });
3286
- var NOTHING = [at("<", ver(0, 0, 0, "0"))];
3287
- // ../ts/kernel/oscal.ts
3288
- var OPEN_OUTCOMES = new Set(["fail", "warn", "gap", "error", "accepted"]);
3289
- // ../ts/kernel/png.ts
3290
- var MAX_PIXELS = 2 ** 24;
3291
- var COLOUR_TYPES = new Map([
3292
- [0, { samples: 1, depths: [1, 2, 4, 8, 16], name: "greyscale" }],
3293
- [2, { samples: 3, depths: [8, 16], name: "RGB" }],
3294
- [3, { samples: 1, depths: [1, 2, 4, 8], name: "palette" }],
3295
- [4, { samples: 2, depths: [8, 16], name: "greyscale with alpha" }],
3296
- [6, { samples: 4, depths: [8, 16], name: "RGBA" }]
3297
- ]);
3298
- var PRECISION_BITS = 32 - 8 - 2;
3299
- var ONE = 2 ** PRECISION_BITS;
3300
- // ../ts/kernel/test-record.ts
3301
- var OUTCOMES = ["pass", "fail", "skip", "todo", "cancelled"];
3302
- function isOutcome(text) {
3303
- return OUTCOMES.includes(text);
3297
+ function segmentsOf(path) {
3298
+ return path.split("/");
3304
3299
  }
3305
- function isRisk(text) {
3306
- return text === "high" || text === "not-high";
3300
+ function nativePath(root, path, separator) {
3301
+ const base = root.replace(/[\\/]+$/, "");
3302
+ return [base, ...segmentsOf(path)].join(separator);
3307
3303
  }
3308
- function isStepOutcome(text) {
3309
- return text === "pass" || text === "fail" || text === "skip";
3304
+ function foldKey(path) {
3305
+ return path.normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
3310
3306
  }
3311
- var TEST_SCOPE = { name: "ifc-test", version: "1" };
3312
- var TEST_SPAN = "test";
3313
- var STEP_SPAN = "test step";
3314
- var RUN_SPAN = "test run";
3315
- var EVENTS = {
3316
- case: "ifc.test.case",
3317
- start: "ifc.test.start",
3318
- review: "ifc.test.review",
3319
- runner: "ifc.test.runner",
3320
- warning: "ifc.test.warning"
3321
- };
3322
- function testId(file, name) {
3323
- return sha256(`${file}\x00${name}`);
3307
+ function collisions(items) {
3308
+ const groups = new Map;
3309
+ for (const item of items) {
3310
+ const key = foldKey(item.path);
3311
+ const group = groups.get(key);
3312
+ if (group === undefined)
3313
+ groups.set(key, [{ ...item }]);
3314
+ else
3315
+ group.push({ ...item });
3316
+ }
3317
+ return [...groups.entries()].filter(([, members]) => members.length > 1).map(([key, members]) => ({ key, members }));
3324
3318
  }
3325
- function isPersonAttribute(key) {
3326
- return key.startsWith("user.") || key.startsWith("enduser.") || key === "host.name" || key === "host.id";
3319
+ var WINDOWS_PATH_LIMIT = 259;
3320
+ function checkPathLength(windowsPath, longPathsEnabled) {
3321
+ if (longPathsEnabled || windowsPath.length <= WINDOWS_PATH_LIMIT)
3322
+ return ok(windowsPath);
3323
+ return err({
3324
+ kind: "path-too-long",
3325
+ path: windowsPath,
3326
+ length: windowsPath.length,
3327
+ limit: WINDOWS_PATH_LIMIT
3328
+ });
3327
3329
  }
3328
- var ARCH = { x86_64: "amd64", x64: "amd64", aarch64: "arm64", arm: "arm32", ia32: "x86", x86: "x86" };
3329
- function hostArch(arch) {
3330
- return ARCH[arch] ?? arch;
3330
+ var REPO_PATH_ROOM = 150;
3331
+ function repoPathLength(root, path, separator) {
3332
+ const length = nativePath(root, path, separator).length;
3333
+ if (length > WINDOWS_PATH_LIMIT)
3334
+ return { kind: "too-long", length };
3335
+ if (length > REPO_PATH_ROOM)
3336
+ return { kind: "no-room", length };
3337
+ return { kind: "fits", length };
3331
3338
  }
3332
- var SHA256_TEXT = /^[0-9a-f]{64}$/;
3333
- function installationFromEnv(self, env) {
3334
- const warnings = [];
3335
- const get = (k) => {
3336
- const v = env[k]?.trim();
3337
- return v === undefined || v === "" ? undefined : v;
3338
- };
3339
- const fallback = get("CI") === undefined || get("CI") === "false" ? "developer" : "ci";
3340
- const given = get("IFC_TEST_ROLE");
3341
- let role = fallback;
3342
- if (given !== undefined) {
3343
- if (roleOf(given) === undefined)
3344
- warnings.push(`IFC_TEST_ROLE is not a role (lower-case words, never a person); ${fallback} is used`);
3345
- else
3346
- role = given;
3339
+
3340
+ // ../ts/githost/capabilities.ts
3341
+ var COMMON_CAPABILITIES = ["CloneUrl", "Credentials", "DefaultBranch", "SignedCommits"];
3342
+ var HOSTED = [...COMMON_CAPABILITIES, "ProtectedBranches", "Issues", "ChangeRequests"];
3343
+ var CAPABILITIES = {
3344
+ Github: new Set(HOSTED),
3345
+ Gitlab: new Set([...HOSTED, "NestedGroups"]),
3346
+ Git: new Set(COMMON_CAPABILITIES)
3347
+ };
3348
+ function supports(kind, capability) {
3349
+ return CAPABILITIES[kind].has(capability);
3350
+ }
3351
+ function maxDepth(kind) {
3352
+ return supports(kind, "NestedGroups") ? Number.POSITIVE_INFINITY : 2;
3353
+ }
3354
+
3355
+ // ../ts/githost/remote.ts
3356
+ function describeRemoteError(e) {
3357
+ switch (e.kind) {
3358
+ case "empty":
3359
+ return "the remote is empty";
3360
+ case "local-path":
3361
+ return "the remote is a path on this computer, not a repository on a Git host";
3362
+ case "unsupported-scheme":
3363
+ return `the remote's scheme ${e.scheme}: is not https, http, git or ssh`;
3364
+ case "no-host":
3365
+ return "the remote names no host";
3366
+ case "no-path":
3367
+ return "the remote names no owner and repository";
3368
+ case "bad-segment":
3369
+ return `the remote's path is not valid: ${e.reason}`;
3370
+ default:
3371
+ return absurd(e);
3347
3372
  }
3348
- const digest = (k) => {
3349
- const v = get(k)?.toLowerCase();
3350
- if (v === undefined)
3351
- return;
3352
- if (SHA256_TEXT.test(v))
3353
- return v;
3354
- warnings.push(`${k} is not a SHA-256; it is left out`);
3373
+ }
3374
+ function hostKindOf(host, hostKinds = {}) {
3375
+ const h = host.toLowerCase();
3376
+ if (h === "github.com")
3377
+ return "Github";
3378
+ if (h === "gitlab.com")
3379
+ return "Gitlab";
3380
+ const named = Object.hasOwn(hostKinds, h) ? hostKinds[h] : undefined;
3381
+ return named ?? "Git";
3382
+ }
3383
+ function safeDecode(segment) {
3384
+ try {
3385
+ return decodeURIComponent(segment);
3386
+ } catch {
3355
3387
  return;
3356
- };
3357
- const revision = get("IFC_TEST_REVISION") ?? get("GITHUB_SHA");
3358
- const lockfileSha256 = digest("IFC_TEST_LOCKFILE_SHA256");
3359
- const pinsSha256 = digest("IFC_TEST_PINS_SHA256");
3360
- return {
3361
- installation: {
3362
- runtime: self.runtime,
3363
- runtimeVersion: self.runtimeVersion,
3364
- os: self.os,
3365
- arch: hostArch(self.arch),
3366
- ...revision === undefined ? {} : { revision },
3367
- ...lockfileSha256 === undefined ? {} : { lockfileSha256 },
3368
- ...pinsSha256 === undefined ? {} : { pinsSha256 },
3369
- role
3370
- },
3371
- warnings
3372
- };
3388
+ }
3373
3389
  }
3374
- function installationResource(i) {
3375
- return {
3376
- attributes: {
3377
- "service.name": "ifc-test",
3378
- "process.runtime.name": i.runtime,
3379
- "process.runtime.version": i.runtimeVersion,
3380
- "os.type": i.os,
3381
- "host.arch": i.arch,
3382
- ...i.revision === undefined ? {} : { "vcs.ref.head.revision": i.revision },
3383
- ...i.lockfileSha256 === undefined ? {} : { "ifc.test.lockfile.sha256": i.lockfileSha256 },
3384
- ...i.pinsSha256 === undefined ? {} : { "ifc.test.pins.sha256": i.pinsSha256 },
3385
- "ifc.test.role": i.role
3386
- }
3387
- };
3390
+ function refOf(host, rawPath, hostKinds) {
3391
+ const hostName = host.toLowerCase();
3392
+ if (hostName === "")
3393
+ return err({ kind: "no-host" });
3394
+ const trimmed = rawPath.replace(/[?#].*$/s, "").replace(/\/+$/, "");
3395
+ const segments = [];
3396
+ for (const raw of trimmed.split("/")) {
3397
+ if (raw === "")
3398
+ continue;
3399
+ const s = safeDecode(raw);
3400
+ if (s === undefined)
3401
+ return err({ kind: "bad-segment", reason: "a percent escape is not valid" });
3402
+ if (s.includes("/") || s.includes("\\"))
3403
+ return err({ kind: "bad-segment", reason: "a segment holds a separator" });
3404
+ segments.push(s);
3405
+ }
3406
+ const last = segments.at(-1);
3407
+ if (last === undefined)
3408
+ return err({ kind: "no-path" });
3409
+ segments[segments.length - 1] = last.replace(/\.git$/i, "");
3410
+ if (segments.length < 2 || segments.some((s) => s === ""))
3411
+ return err({ kind: "no-path" });
3412
+ return ok({ kind: hostKindOf(hostName, hostKinds), host: hostName, path: segments });
3388
3413
  }
3389
- function attributeText(a, key) {
3390
- const v = a[key];
3391
- return typeof v === "string" ? v : undefined;
3414
+ function hostOfAuthority(authority) {
3415
+ const afterAt = authority.slice(authority.lastIndexOf("@") + 1);
3416
+ if (afterAt.startsWith("["))
3417
+ return afterAt.slice(0, afterAt.indexOf("]") + 1);
3418
+ const colon = afterAt.indexOf(":");
3419
+ return colon < 0 ? afterAt : afterAt.slice(0, colon);
3392
3420
  }
3393
- function attributeTexts(a, key) {
3394
- const v = a[key];
3395
- return Array.isArray(v) && v.every((e) => typeof e === "string") ? v : [];
3421
+ function parseRemote(url, hostKinds = {}) {
3422
+ const text = url.trim();
3423
+ if (text === "")
3424
+ return err({ kind: "empty" });
3425
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(text);
3426
+ if (scheme !== null) {
3427
+ const name = (scheme[1] ?? "").toLowerCase();
3428
+ if (name === "file")
3429
+ return err({ kind: "local-path" });
3430
+ if (!["https", "http", "git", "ssh", "git+ssh", "ssh+git"].includes(name))
3431
+ return err({ kind: "unsupported-scheme", scheme: name });
3432
+ const rest = text.slice(scheme[0].length);
3433
+ const slash = rest.indexOf("/");
3434
+ const authority = slash < 0 ? rest : rest.slice(0, slash);
3435
+ return refOf(hostOfAuthority(authority), slash < 0 ? "" : rest.slice(slash), hostKinds);
3436
+ }
3437
+ if (/^[A-Za-z]:[\\/]/.test(text) || text.startsWith("/") || text.startsWith(".") || text.startsWith("~"))
3438
+ return err({ kind: "local-path" });
3439
+ const colon = text.indexOf(":");
3440
+ const slash = text.indexOf("/");
3441
+ if (colon < 0 || slash >= 0 && slash < colon)
3442
+ return err({ kind: "local-path" });
3443
+ return refOf(hostOfAuthority(text.slice(0, colon)), text.slice(colon + 1), hostKinds);
3396
3444
  }
3397
- function attributeInteger(a, key) {
3398
- const v = a[key];
3399
- if (typeof v === "bigint")
3400
- return Number(v);
3401
- return typeof v === "number" && Number.isInteger(v) ? v : undefined;
3445
+ var HOSTNAME = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+(?::\d+)?$/;
3446
+ function webPage(path) {
3447
+ const m = /^(.*?)\/(?:-\/)?(?:tree|blob|commits|raw)\/([^/?#]+)(?:[/?#].*)?$/s.exec(path);
3448
+ if (m === null)
3449
+ return { path };
3450
+ const branch = safeDecode(m[2] ?? "");
3451
+ return branch === undefined ? { path } : { path: m[1] ?? path, branch };
3402
3452
  }
3403
- function installationOf(r) {
3404
- const a = r.attributes;
3405
- const revision = attributeText(a, "vcs.ref.head.revision");
3406
- const lockfileSha256 = attributeText(a, "ifc.test.lockfile.sha256");
3407
- const pinsSha256 = attributeText(a, "ifc.test.pins.sha256");
3408
- return {
3409
- runtime: attributeText(a, "process.runtime.name") ?? "unknown",
3410
- runtimeVersion: attributeText(a, "process.runtime.version") ?? "unknown",
3411
- os: attributeText(a, "os.type") ?? "unknown",
3412
- arch: attributeText(a, "host.arch") ?? "unknown",
3413
- ...revision === undefined ? {} : { revision },
3414
- ...lockfileSha256 === undefined ? {} : { lockfileSha256 },
3415
- ...pinsSha256 === undefined ? {} : { pinsSha256 },
3416
- role: attributeText(a, "ifc.test.role") ?? "unknown"
3453
+ function readRemote(input, hostKinds = {}) {
3454
+ const text = input.trim();
3455
+ const strict = parseRemote(text, hostKinds);
3456
+ const asIs = () => strict.kind === "err" ? strict : ok({ ref: strict.value });
3457
+ const viaPage = (origin, path) => {
3458
+ const page = webPage(path);
3459
+ const r = parseRemote(`${origin}${page.path}`, hostKinds);
3460
+ return r.kind === "err" ? r : ok(page.branch === undefined ? { ref: r.value } : { ref: r.value, branch: page.branch });
3417
3461
  };
3462
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/]*)(\/.*)?$/.exec(text);
3463
+ if (scheme !== null)
3464
+ return strict.kind === "err" && scheme[1]?.toLowerCase() === "file" ? strict : viaPage(`${scheme[1]}://${scheme[2]}`, scheme[3] ?? "");
3465
+ if (text === "" || /^[A-Za-z]:[\\/]/.test(text) || /^[/.~]/.test(text))
3466
+ return asIs();
3467
+ const named = /^(github|gitlab):([^/].*)$/i.exec(text);
3468
+ if (named !== null)
3469
+ return viaPage(`https://${(named[1] ?? "").toLowerCase()}.com/`, named[2] ?? "");
3470
+ const colon = text.indexOf(":");
3471
+ const slash = text.indexOf("/");
3472
+ if (colon >= 0 && (slash < 0 || colon < slash))
3473
+ return asIs();
3474
+ const first = slash < 0 ? text : text.slice(0, slash);
3475
+ if (slash >= 0 && HOSTNAME.test(first))
3476
+ return viaPage(`https://${first}`, text.slice(slash));
3477
+ if (/^[^/\s]+\/[^/\s]+$/.test(text))
3478
+ return viaPage("https://github.com/", text);
3479
+ return asIs();
3418
3480
  }
3419
- function caseAttributes(c) {
3420
- const status = c.outcome === "pass" ? "pass" : c.outcome === "fail" || c.outcome === "cancelled" ? "fail" : undefined;
3421
- return {
3422
- "test.case.name": c.name,
3423
- ...status === undefined ? {} : { "test.case.result.status": status },
3424
- "test.suite.name": c.file,
3425
- "code.file.path": c.file,
3426
- "ifc.test.id": c.id,
3427
- "ifc.test.requirements": [...c.requirements],
3428
- "ifc.test.risk": c.risk,
3429
- "ifc.test.outcome": c.outcome,
3430
- "ifc.test.attempt": BigInt(c.attempt),
3431
- ...c.characteristic === undefined ? {} : { "ifc.test.characteristic": c.characteristic },
3432
- ...c.reason === undefined ? {} : { "ifc.test.reason": c.reason },
3433
- ...c.message === undefined ? {} : { "ifc.test.message": c.message },
3434
- ...c.expected === undefined ? {} : { "ifc.test.expected": c.expected },
3435
- ...c.actual === undefined ? {} : { "ifc.test.actual": c.actual },
3436
- ...c.steps === undefined || c.steps.length === 0 ? {} : { "ifc.test.steps": stepPaths(c.steps) }
3437
- };
3481
+ function cloneUrlOf(ref) {
3482
+ return `https://${ref.host}/${ref.path.map(encodeURIComponent).join("/")}.git`;
3438
3483
  }
3439
- function stepPaths(steps, within = []) {
3440
- return steps.flatMap((s) => [...stepPaths(s.steps ?? [], [...within, s.name]), [...within, s.name].join(" > ")]);
3484
+ function describeRef(ref) {
3485
+ return `${ref.host}/${ref.path.join("/")}`;
3441
3486
  }
3442
- function testCaseSpan(c, ctx) {
3443
- const failed = c.outcome === "fail" || c.outcome === "cancelled";
3444
- return {
3445
- name: TEST_SPAN,
3446
- context: { traceId: ctx.traceId, spanId: ctx.spanId, traceFlags: 1, traceState: [], isRemote: false },
3447
- ...ctx.parentSpanId === undefined ? {} : { parentSpanId: ctx.parentSpanId },
3448
- kind: "internal",
3449
- startTime: c.start,
3450
- endTime: c.end,
3451
- attributes: caseAttributes(c),
3452
- events: [],
3453
- links: [],
3454
- status: failed ? { kind: "error", message: c.message ?? c.reason ?? c.outcome } : c.outcome === "pass" ? { kind: "ok" } : { kind: "unset" },
3455
- droppedAttributesCount: 0,
3456
- droppedEventsCount: 0,
3457
- droppedLinksCount: 0
3458
- };
3487
+ function sameRepository(a, b) {
3488
+ return a.host.toLowerCase() === b.host.toLowerCase() && a.path.length === b.path.length && a.path.every((s, i) => s.toLowerCase() === (b.path[i] ?? "").toLowerCase());
3459
3489
  }
3460
- function testCaseLog(c, ctx) {
3461
- const failed = c.outcome === "fail" || c.outcome === "cancelled";
3462
- return {
3463
- time: c.end,
3464
- observedTime: c.end,
3465
- severityNumber: failed ? SEVERITY.ERROR : SEVERITY.INFO,
3466
- severityText: failed ? "ERROR" : "INFO",
3467
- body: `${c.outcome} ${c.name}`,
3468
- attributes: caseAttributes(c),
3469
- droppedAttributesCount: 0,
3470
- eventName: EVENTS.case,
3471
- traceId: ctx.traceId,
3472
- spanId: ctx.spanId,
3473
- traceFlags: 1
3474
- };
3475
- }
3476
- function plainLog(eventName, time, body, attributes, warn = false) {
3477
- return {
3478
- time,
3479
- observedTime: time,
3480
- severityNumber: warn ? SEVERITY.WARN : SEVERITY.INFO,
3481
- severityText: warn ? "WARN" : "INFO",
3482
- body,
3483
- attributes,
3484
- droppedAttributesCount: 0,
3485
- eventName
3486
- };
3490
+
3491
+ // ../ts/githost/github.ts
3492
+ var repoShape = object({ private: boolean, default_branch: string, clone_url: string, archived: boolean }, { visibility: string });
3493
+ var issueShape = object({ number: integer, title: string, state: literal("open", "closed"), html_url: string }, { body: nullable(string), labels: array(oneOf(string, object({ name: string }))), pull_request: unknownValue });
3494
+ var subIssuesShape = array(object({ number: integer }));
3495
+ var pullShape = object({
3496
+ number: integer,
3497
+ title: string,
3498
+ state: literal("open", "closed"),
3499
+ html_url: string,
3500
+ head: object({ ref: string }),
3501
+ base: object({ ref: string })
3502
+ }, { merged: boolean, merged_at: nullable(string) });
3503
+ var branchShape = object({ name: string, protected: boolean });
3504
+ var protectionShape = object({}, { required_pull_request_reviews: unknownValue, allow_force_pushes: object({ enabled: boolean }) });
3505
+ var commitShape = object({ commit: object({ verification: object({ verified: boolean }) }) });
3506
+
3507
+ // ../ts/githost/gitlab.ts
3508
+ var projectShape = object({ http_url_to_repo: string }, { archived: boolean, visibility: literal("public", "internal", "private"), default_branch: nullable(string) });
3509
+ var issueShape2 = object({ iid: integer, title: string, state: literal("opened", "closed"), web_url: string }, { description: nullable(string), labels: array(string) });
3510
+ var mergeRequestShape = object({
3511
+ iid: integer,
3512
+ title: string,
3513
+ state: literal("opened", "closed", "merged", "locked"),
3514
+ web_url: string,
3515
+ source_branch: string,
3516
+ target_branch: string
3517
+ });
3518
+ var branchShape2 = object({ name: string, protected: boolean });
3519
+ var protectedShape = object({ name: string, allow_force_push: boolean }, { code_owner_approval_required: boolean, push_access_levels: array(object({ access_level: integer })) });
3520
+ var signatureShape = object({ verification_status: string });
3521
+ // src/state.ts
3522
+ function holdsLocalWork(kind) {
3523
+ switch (kind) {
3524
+ case "Missing":
3525
+ case "Clean":
3526
+ case "Behind":
3527
+ return false;
3528
+ case "Dirty":
3529
+ case "Ahead":
3530
+ case "Diverged":
3531
+ case "Locked":
3532
+ case "Detached":
3533
+ case "WrongRemote":
3534
+ case "NotARepo":
3535
+ return true;
3536
+ default:
3537
+ return absurd(kind);
3538
+ }
3487
3539
  }
3488
- function reviewLog(r, time, traceId) {
3489
- const base = plainLog(EVENTS.review, time, `reviewed ${r.requirement}`, {
3490
- "ifc.test.requirement": r.requirement,
3491
- "ifc.test.reason": r.reason
3492
- });
3493
- return traceId === undefined ? base : { ...base, traceId };
3540
+ function describeRemote(remote) {
3541
+ if (remote === undefined || remote.trim() === "")
3542
+ return "(none)";
3543
+ const r = parseRemote(remote);
3544
+ return r.kind === "ok" ? describeRef(r.value) : "(not a remote of a host)";
3494
3545
  }
3495
- function warningLog(message, time) {
3496
- return plainLog(EVENTS.warning, time, message, { "ifc.test.warning": message }, true);
3546
+ function isExpectedRemote(remote, expected) {
3547
+ if (remote === undefined)
3548
+ return false;
3549
+ const r = parseRemote(remote);
3550
+ return r.kind === "ok" && sameRepository(r.value, expected);
3497
3551
  }
3498
- function runnerLog(r, time) {
3499
- const attributes = r.kind === "exited" ? { "process.runtime.name": r.runtime, "ifc.test.runner.found": true, "process.exit.code": BigInt(r.code) } : { "process.runtime.name": r.runtime, "ifc.test.runner.found": false };
3500
- return plainLog(EVENTS.runner, time, r.kind === "exited" ? `${r.runtime} exited with ${r.code}` : `${r.runtime} is not installed`, attributes, r.kind === "missing" || r.kind === "exited" && r.code !== 0);
3552
+ function classify(facts, expected) {
3553
+ switch (facts.kind) {
3554
+ case "absent":
3555
+ return { kind: "Missing" };
3556
+ case "not-a-repository":
3557
+ return { kind: "NotARepo" };
3558
+ case "repository": {
3559
+ if (!isExpectedRemote(facts.remote, expected))
3560
+ return { kind: "WrongRemote", found: describeRemote(facts.remote) };
3561
+ if (facts.lockFile)
3562
+ return { kind: "Locked" };
3563
+ if (facts.detached)
3564
+ return { kind: "Detached" };
3565
+ if (facts.dirty)
3566
+ return { kind: "Dirty" };
3567
+ if (facts.ahead > 0 && facts.behind > 0)
3568
+ return { kind: "Diverged", ahead: facts.ahead, behind: facts.behind };
3569
+ if (facts.ahead > 0)
3570
+ return { kind: "Ahead", commits: facts.ahead };
3571
+ if (facts.behind > 0)
3572
+ return { kind: "Behind", commits: facts.behind };
3573
+ return { kind: "Clean" };
3574
+ }
3575
+ default:
3576
+ return absurd(facts);
3577
+ }
3501
3578
  }
3502
- function formatRecordError(e) {
3503
- switch (e.kind) {
3504
- case "json":
3505
- return `line ${e.line} is not JSON: ${e.reason}`;
3506
- case "otlp":
3507
- return `line ${e.line} is not OTLP JSON: ${formatDecodeError(e.error)}`;
3508
- case "person":
3509
- return `the record names a person or a machine of one (${e.key}), which a test record must not`;
3510
- case "test":
3511
- return `the test span ${e.spanId} is not a test record: ${e.reason}`;
3512
- case "no-run":
3513
- return `the record has no run: ${e.reason}`;
3579
+
3580
+ // src/plan.ts
3581
+ function isDestructive(action) {
3582
+ const kind = typeof action === "string" ? action : action.kind;
3583
+ switch (kind) {
3584
+ case "RemoveGenerated":
3585
+ return true;
3586
+ case "Clone":
3587
+ case "FastForward":
3588
+ case "CreateWorktree":
3589
+ case "ConfigureRepo":
3590
+ case "ConfigureHost":
3591
+ case "WriteGenerated":
3592
+ case "InstallTool":
3593
+ case "Skip":
3594
+ case "Refuse":
3595
+ return false;
3514
3596
  default:
3515
- return absurd(e);
3597
+ return absurd(kind);
3516
3598
  }
3517
3599
  }
3518
- function decodeRecordDocument(value, line) {
3519
- const t = decodeTraces(value);
3520
- if (t.kind === "err")
3521
- return err({ kind: "otlp", line, error: t.error });
3522
- const l = decodeLogs(value);
3523
- if (l.kind === "err")
3524
- return err({ kind: "otlp", line, error: l.error });
3525
- return ok({ traces: t.value, logs: l.value });
3600
+ function isHostChange(action) {
3601
+ const kind = typeof action === "string" ? action : action.kind;
3602
+ switch (kind) {
3603
+ case "ConfigureHost":
3604
+ case "InstallTool":
3605
+ return true;
3606
+ case "Clone":
3607
+ case "FastForward":
3608
+ case "CreateWorktree":
3609
+ case "ConfigureRepo":
3610
+ case "WriteGenerated":
3611
+ case "RemoveGenerated":
3612
+ case "Skip":
3613
+ case "Refuse":
3614
+ return false;
3615
+ default:
3616
+ return absurd(kind);
3617
+ }
3526
3618
  }
3527
- function resourceKey(r, s) {
3528
- const keys = Object.keys(r.attributes).sort();
3529
- const enc = (v) => typeof v === "bigint" ? `${v}n` : v instanceof Uint8Array ? [...v] : Array.isArray(v) ? v.map((x) => typeof x === "bigint" ? `${x}n` : x) : v;
3530
- return JSON.stringify([s.name, s.version ?? "", keys.map((k) => [k, enc(r.attributes[k])])]);
3619
+ function describeAction(action) {
3620
+ switch (action.kind) {
3621
+ case "Clone":
3622
+ return `clone ${action.url} into ${action.target}`;
3623
+ case "FastForward":
3624
+ return `fast-forward ${action.target} by ${action.commits} commit${action.commits === 1 ? "" : "s"}`;
3625
+ case "CreateWorktree":
3626
+ return `add a worktree of ${action.repo} for ${action.branch} at ${action.target}`;
3627
+ case "ConfigureRepo":
3628
+ return `set ${Object.keys(action.settings).sort().join(", ")} in the local Git configuration of ${action.target}`;
3629
+ case "ConfigureHost":
3630
+ return `change the host: ${action.what}`;
3631
+ case "WriteGenerated":
3632
+ return `write the generated file ${action.target}`;
3633
+ case "RemoveGenerated":
3634
+ return `remove the generated file ${action.target}`;
3635
+ case "InstallTool":
3636
+ return `install ${action.tool} ${action.version}`;
3637
+ case "Skip":
3638
+ return `skip ${action.target}: ${describeSkip(action.why)}`;
3639
+ case "Refuse":
3640
+ return `refuse ${action.target}: ${describeRefusal(action.why)}`;
3641
+ default:
3642
+ return absurd(action);
3643
+ }
3531
3644
  }
3532
- function mergeBatches(signals) {
3533
- const t = new Map;
3534
- for (const b of signals.traces) {
3535
- const k = resourceKey(b.resource, b.scope);
3536
- const at = t.get(k) ?? { resource: b.resource, scope: b.scope, spans: [] };
3537
- at.spans.push(...b.spans);
3538
- t.set(k, at);
3645
+ function describeSkip(why) {
3646
+ switch (why.kind) {
3647
+ case "in-sync":
3648
+ return "it is up to date";
3649
+ case "uncommitted-changes":
3650
+ return "it has uncommitted changes, which are never touched";
3651
+ case "ahead":
3652
+ return `it has ${why.commits} commit${why.commits === 1 ? "" : "s"} its remote does not`;
3653
+ case "diverged":
3654
+ return `it has ${why.ahead} commit${why.ahead === 1 ? "" : "s"} its remote does not and the remote has ${why.behind} it does not; only a person merges`;
3655
+ case "locked":
3656
+ return "a Git lock file is there, so another process may be working in it; the lock is not removed";
3657
+ case "detached":
3658
+ return "HEAD is on no branch";
3659
+ case "worktree-unneeded":
3660
+ return "nobody else is working in the repository and it has no uncommitted work, so its own checkout is the place to work";
3661
+ case "worktree-exists":
3662
+ return "the worktree is there";
3663
+ case "base-unavailable":
3664
+ return `its repository is ${why.state}`;
3665
+ case "file-current":
3666
+ return "its bytes are the generated ones";
3667
+ case "file-absent":
3668
+ return "it is not there and is not wanted";
3669
+ default:
3670
+ return absurd(why);
3539
3671
  }
3540
- const l = new Map;
3541
- for (const b of signals.logs) {
3542
- const k = resourceKey(b.resource, b.scope);
3543
- const at = l.get(k) ?? { resource: b.resource, scope: b.scope, records: [] };
3544
- at.records.push(...b.records);
3545
- l.set(k, at);
3672
+ }
3673
+ function describeRefusal(why) {
3674
+ switch (why.kind) {
3675
+ case "wrong-remote":
3676
+ return `a repository of ${why.found} is at that path, not the one the manifest names, and it is never overwritten`;
3677
+ case "not-a-repository":
3678
+ return "something that is not a Git repository is at that path, and it is never overwritten";
3679
+ case "generated-edited":
3680
+ return "its bytes are not the ones the state record holds, so it was edited by hand; `--force` replaces it";
3681
+ default:
3682
+ return absurd(why);
3546
3683
  }
3547
- return { traces: [...t.values()], logs: [...l.values()] };
3548
3684
  }
3549
- function closeOrphans(signals, at) {
3550
- const ended = new Set(signals.traces.flatMap((b) => b.spans.filter((s) => s.name === TEST_SPAN).map((s) => s.context.spanId)));
3551
- const extra = [];
3552
- for (const b of signals.logs) {
3553
- const spans = [];
3554
- for (const r of b.records) {
3555
- if (r.eventName !== EVENTS.start || r.spanId === undefined || r.traceId === undefined || ended.has(r.spanId))
3556
- continue;
3557
- ended.add(r.spanId);
3558
- const a = r.attributes;
3559
- const risk = attributeText(a, "ifc.test.risk") ?? "not-high";
3560
- const parent = attributeText(a, "ifc.test.parent");
3561
- const characteristic = attributeText(a, "ifc.test.characteristic");
3562
- const parentSpanId = parent === undefined ? undefined : parseSpanId(parent);
3563
- const c = {
3564
- id: attributeText(a, "ifc.test.id") ?? "",
3565
- file: attributeText(a, "test.suite.name") ?? "",
3566
- name: attributeText(a, "test.case.name") ?? "",
3567
- requirements: attributeTexts(a, "ifc.test.requirements"),
3568
- risk: isRisk(risk) ? risk : "not-high",
3569
- ...characteristic === undefined ? {} : { characteristic },
3570
- start: r.time,
3571
- end: at > r.time ? at : r.time,
3572
- outcome: "cancelled",
3573
- reason: "its process ended before the test did",
3574
- attempt: attributeInteger(a, "ifc.test.attempt") ?? 1
3685
+ function forState(repo, state) {
3686
+ const target = repo.path;
3687
+ switch (state.kind) {
3688
+ case "Missing":
3689
+ return { kind: "Clone", target, url: repo.cloneUrl, branch: repo.branch };
3690
+ case "Behind":
3691
+ return { kind: "FastForward", target, commits: state.commits };
3692
+ case "Clean":
3693
+ return { kind: "Skip", target, why: { kind: "in-sync" } };
3694
+ case "Dirty":
3695
+ return { kind: "Skip", target, why: { kind: "uncommitted-changes" } };
3696
+ case "Ahead":
3697
+ return {
3698
+ kind: "Skip",
3699
+ target,
3700
+ why: { kind: "ahead", commits: state.commits }
3575
3701
  };
3576
- spans.push(testCaseSpan(c, {
3577
- traceId: r.traceId,
3578
- spanId: r.spanId,
3579
- ...parentSpanId?.kind === "ok" ? { parentSpanId: parentSpanId.value } : {}
3580
- }));
3581
- }
3582
- if (spans.length > 0)
3583
- extra.push({ resource: b.resource, scope: b.scope, spans });
3702
+ case "Diverged":
3703
+ return {
3704
+ kind: "Skip",
3705
+ target,
3706
+ why: { kind: "diverged", ahead: state.ahead, behind: state.behind }
3707
+ };
3708
+ case "Locked":
3709
+ return { kind: "Skip", target, why: { kind: "locked" } };
3710
+ case "Detached":
3711
+ return { kind: "Skip", target, why: { kind: "detached" } };
3712
+ case "WrongRemote":
3713
+ return {
3714
+ kind: "Refuse",
3715
+ target,
3716
+ why: { kind: "wrong-remote", found: state.found }
3717
+ };
3718
+ case "NotARepo":
3719
+ return { kind: "Refuse", target, why: { kind: "not-a-repository" } };
3720
+ default:
3721
+ return absurd(state);
3584
3722
  }
3585
- return extra.length === 0 ? signals : mergeBatches({ traces: [...signals.traces, ...extra], logs: signals.logs });
3586
- }
3587
- // ../ts/kernel/test-report.ts
3588
- var byText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
3589
- function testOf(s, runtime) {
3590
- const a = s.attributes;
3591
- const no = (reason) => err({ kind: "test", spanId: s.context.spanId, reason });
3592
- const id = attributeText(a, "ifc.test.id");
3593
- const name = attributeText(a, "test.case.name");
3594
- const file = attributeText(a, "test.suite.name");
3595
- const outcome = attributeText(a, "ifc.test.outcome") ?? "";
3596
- const risk = attributeText(a, "ifc.test.risk") ?? "";
3597
- if (id === undefined)
3598
- return no("it has no ifc.test.id");
3599
- if (name === undefined)
3600
- return no("it has no test.case.name");
3601
- if (file === undefined)
3602
- return no("it has no test.suite.name");
3603
- if (!isOutcome(outcome))
3604
- return no(`its outcome ${JSON.stringify(outcome)} is not one of ${OUTCOMES.join(", ")}`);
3605
- if (!isRisk(risk))
3606
- return no(`its risk ${JSON.stringify(risk)} is not high or not-high`);
3607
- const reason = attributeText(a, "ifc.test.reason");
3608
- const message = attributeText(a, "ifc.test.message");
3609
- const expected = attributeText(a, "ifc.test.expected");
3610
- const actual = attributeText(a, "ifc.test.actual");
3611
- const characteristic = attributeText(a, "ifc.test.characteristic");
3612
- return ok({
3613
- id,
3614
- file,
3615
- name,
3616
- requirements: attributeTexts(a, "ifc.test.requirements"),
3617
- risk,
3618
- ...characteristic === undefined ? {} : { characteristic },
3619
- start: s.startTime,
3620
- end: s.endTime,
3621
- outcome,
3622
- ...reason === undefined ? {} : { reason },
3623
- ...message === undefined ? {} : { message },
3624
- ...expected === undefined ? {} : { expected },
3625
- ...actual === undefined ? {} : { actual },
3626
- attempt: attributeInteger(a, "ifc.test.attempt") ?? 1,
3627
- runtime,
3628
- spanId: s.context.spanId
3629
- });
3630
- }
3631
- function compareTests(a, b) {
3632
- return byText(a.runtime, b.runtime) || byText(a.file, b.file) || byText(a.name, b.name) || a.attempt - b.attempt || (a.start < b.start ? -1 : a.start > b.start ? 1 : 0) || byText(a.spanId, b.spanId);
3633
- }
3634
- function stepsUnder(parent, children) {
3635
- return (children.get(parent) ?? []).flatMap((s) => {
3636
- const name = attributeText(s.attributes, "ifc.test.step.name");
3637
- const outcome = attributeText(s.attributes, "ifc.test.outcome") ?? "";
3638
- if (name === undefined || !isStepOutcome(outcome))
3639
- return [];
3640
- const message = attributeText(s.attributes, "ifc.test.message");
3641
- const inner = stepsUnder(s.context.spanId, children);
3642
- return [
3643
- {
3644
- name,
3645
- start: s.startTime,
3646
- end: s.endTime,
3647
- outcome,
3648
- ...message === undefined ? {} : { message },
3649
- ...inner.length === 0 ? {} : { steps: inner }
3650
- }
3651
- ];
3652
- }).sort((a, b) => a.end < b.end ? -1 : a.end > b.end ? 1 : 0);
3653
3723
  }
3654
- function testsOf(signals) {
3655
- const tests = [];
3656
- const children = new Map;
3657
- for (const b of signals.traces) {
3658
- for (const s of b.spans) {
3659
- if (s.name !== STEP_SPAN || s.parentSpanId === undefined)
3660
- continue;
3661
- const at = children.get(s.parentSpanId) ?? [];
3662
- at.push(s);
3663
- children.set(s.parentSpanId, at);
3664
- }
3665
- }
3666
- for (const b of signals.traces) {
3667
- const runtime = attributeText(b.resource.attributes, "process.runtime.name") ?? "unknown";
3668
- for (const s of b.spans) {
3669
- if (s.name !== TEST_SPAN)
3670
- continue;
3671
- const t = testOf(s, runtime);
3672
- if (t.kind === "err")
3673
- return t;
3674
- const steps = stepsUnder(s.context.spanId, children);
3675
- tests.push(steps.length === 0 ? t.value : { ...t.value, steps });
3676
- }
3724
+ function takesConfiguration(state) {
3725
+ switch (state.kind) {
3726
+ case "Missing":
3727
+ case "Clean":
3728
+ case "Dirty":
3729
+ case "Ahead":
3730
+ case "Behind":
3731
+ case "Diverged":
3732
+ case "Detached":
3733
+ return true;
3734
+ case "Locked":
3735
+ case "WrongRemote":
3736
+ case "NotARepo":
3737
+ return false;
3738
+ default:
3739
+ return absurd(state);
3677
3740
  }
3678
- return ok(tests.sort(compareTests));
3679
3741
  }
3680
- function reviewsOf(signals) {
3681
- const seen = new Map;
3682
- for (const b of signals.logs) {
3683
- for (const r of b.records) {
3684
- if (r.eventName !== EVENTS.review)
3685
- continue;
3686
- const requirement = attributeText(r.attributes, "ifc.test.requirement");
3687
- const reason = attributeText(r.attributes, "ifc.test.reason");
3688
- if (requirement === undefined || reason === undefined)
3689
- continue;
3690
- seen.set(JSON.stringify([requirement, reason]), { requirement, reason });
3691
- }
3742
+ var ABSENT = {
3743
+ state: { kind: "Missing" },
3744
+ config: {},
3745
+ busy: false
3746
+ };
3747
+ var byPath = (a, b) => foldKey(a.path) < foldKey(b.path) ? -1 : foldKey(a.path) > foldKey(b.path) ? 1 : a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
3748
+ function settingsToSet(repo, observed) {
3749
+ const diff = {};
3750
+ for (const key of Object.keys(repo.settings).sort()) {
3751
+ const want = repo.settings[key];
3752
+ if (want !== undefined && observed.config[key] !== want)
3753
+ diff[key] = want;
3692
3754
  }
3693
- return [...seen.entries()].sort(([a], [b]) => byText(a, b)).map(([, r]) => r);
3694
- }
3695
- function countsOf(tests) {
3696
- const n = (o) => tests.filter((t) => t.outcome === o).length;
3697
- return { tests: tests.length, passed: n("pass"), failed: n("fail"), skipped: n("skip"), todo: n("todo"), cancelled: n("cancelled") };
3698
- }
3699
- function requirementsOf(tests, reviews, required) {
3700
- const ids = new Set([...required, ...reviews.map((r) => r.requirement), ...tests.flatMap((t) => t.requirements)]);
3701
- const listed = new Set(required);
3702
- return [...ids].sort(byText).map((id) => {
3703
- const proving = tests.filter((t) => t.requirements.includes(id));
3704
- const reasons = [...new Set(reviews.filter((r) => r.requirement === id).map((r) => r.reason))].sort(byText);
3705
- const outcomes = new Set(proving.map((t) => t.outcome));
3706
- const state = outcomes.has("fail") || outcomes.has("cancelled") ? "failing" : outcomes.has("pass") ? "proven" : reasons.length > 0 ? "reviewed" : proving.length > 0 ? "skipped" : "unproven";
3707
- return {
3708
- id,
3709
- required: listed.has(id),
3710
- risk: proving.some((t) => t.risk === "high") ? "high" : "not-high",
3711
- state,
3712
- tests: proving.map((t) => ({ id: t.id, name: t.name, runtime: t.runtime, outcome: t.outcome })),
3713
- reviews: reasons
3714
- };
3715
- });
3755
+ return Object.keys(diff).length === 0 ? undefined : diff;
3716
3756
  }
3717
- function judge2(input) {
3718
- const failures = [];
3719
- const counts = countsOf(input.tests);
3720
- const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
3721
- if (counts.failed > 0)
3722
- failures.push(`${plural(counts.failed, "test", "tests")} failed`);
3723
- if (counts.cancelled > 0)
3724
- failures.push(`${plural(counts.cancelled, "test was", "tests were")} cancelled`);
3725
- for (const r of input.runners) {
3726
- switch (r.kind) {
3727
- case "exited":
3728
- if (r.code !== 0)
3729
- failures.push(`the ${r.runtime} runner exited with ${r.code}`);
3730
- break;
3731
- case "missing":
3732
- failures.push(`${r.runtime} is not installed`);
3733
- break;
3734
- default:
3735
- absurd(r);
3736
- }
3757
+ function plan(desired, observed, options = {}) {
3758
+ const actions = [];
3759
+ for (const repo of [...desired.repos].sort(byPath)) {
3760
+ const seen = Object.hasOwn(observed.repos, repo.path) ? observed.repos[repo.path] ?? ABSENT : ABSENT;
3761
+ actions.push(forState(repo, seen.state));
3762
+ const settings = takesConfiguration(seen.state) ? settingsToSet(repo, seen) : undefined;
3763
+ if (settings !== undefined)
3764
+ actions.push({ kind: "ConfigureRepo", target: repo.path, settings });
3737
3765
  }
3738
- const unproven = requirementsOf(input.tests, input.reviews, input.required).filter((r) => r.required && (r.state === "unproven" || r.state === "skipped")).map((r) => r.id);
3739
- if (unproven.length > 0)
3740
- failures.push(`${plural(unproven.length, "requirement is", "requirements are")} neither proven nor reviewed: ${unproven.join(", ")}`);
3741
- return { status: failures.length === 0 ? "success" : "failure", failures, unproven };
3742
- }
3743
- function assembleRecord(input) {
3744
- const closed = closeOrphans(mergeBatches(input.signals), input.end);
3745
- const tests = testsOf(closed);
3746
- if (tests.kind === "err")
3747
- return tests;
3748
- const reviews = [...reviewsOf(closed), ...input.reviews ?? []];
3749
- const judgement = judge2({ tests: tests.value, runners: input.runners, required: input.required, reviews });
3750
- const resource = installationResource(input.runner);
3751
- const runSpan = {
3752
- name: RUN_SPAN,
3753
- context: { traceId: input.traceId, spanId: input.spanId, traceFlags: 1, traceState: [], isRemote: false },
3754
- kind: "internal",
3755
- startTime: input.start,
3756
- endTime: input.end,
3757
- attributes: {
3758
- "test.suite.name": "ifc test",
3759
- "test.suite.run.status": judgement.status,
3760
- "ifc.test.unproven": [...judgement.unproven],
3761
- "ifc.test.required": [...input.required],
3762
- "ifc.test.failures": [...judgement.failures],
3763
- "ifc.test.runtimes": input.runners.map((r) => r.runtime)
3764
- },
3765
- events: [],
3766
- links: [],
3767
- status: judgement.status === "success" ? { kind: "ok" } : { kind: "error", message: judgement.failures.join("; ") },
3768
- droppedAttributesCount: 0,
3769
- droppedEventsCount: 0,
3770
- droppedLinksCount: 0
3771
- };
3772
- const own = [
3773
- ...input.runners.map((r) => ({ ...runnerLog(r, input.end), traceId: input.traceId, spanId: input.spanId })),
3774
- ...(input.reviews ?? []).map((r) => ({ ...reviewLog(r, input.end, input.traceId), spanId: input.spanId })),
3775
- ...(input.warnings ?? []).map((w) => ({ ...warningLog(w, input.end), traceId: input.traceId, spanId: input.spanId }))
3776
- ];
3777
- const merged = mergeBatches({
3778
- traces: [{ resource, scope: TEST_SCOPE, spans: [runSpan] }, ...closed.traces],
3779
- logs: [...own.length === 0 ? [] : [{ resource, scope: TEST_SCOPE, records: own }], ...closed.logs]
3780
- });
3781
- return ok({ record: { ...encodeTraces(merged.traces), ...encodeLogs(merged.logs) }, judgement });
3782
- }
3783
- function recordText(record) {
3784
- return `${JSON.stringify(record)}
3785
- `;
3786
- }
3787
- function readRecord(input) {
3788
- let value = input;
3789
- if (typeof input === "string") {
3790
- try {
3791
- value = JSON.parse(input);
3792
- } catch (e) {
3793
- return err({ kind: "json", line: 1, reason: e instanceof Error ? e.message : String(e) });
3766
+ for (const wt of [...desired.worktrees].sort(byPath)) {
3767
+ const there = Object.hasOwn(observed.worktrees, wt.path) ? observed.worktrees[wt.path] : undefined;
3768
+ if (there !== undefined && there.kind !== "Missing") {
3769
+ actions.push({
3770
+ kind: "Skip",
3771
+ target: wt.path,
3772
+ why: { kind: "worktree-exists" }
3773
+ });
3774
+ continue;
3794
3775
  }
3795
- }
3796
- const d = decodeRecordDocument(value, 1);
3797
- if (d.kind === "err")
3798
- return d;
3799
- const signals = d.value;
3800
- for (const b of [...signals.traces, ...signals.logs]) {
3801
- const key = Object.keys(b.resource.attributes).find(isPersonAttribute);
3802
- if (key !== undefined)
3803
- return err({ kind: "person", key });
3804
- }
3805
- const runs = signals.traces.flatMap((b) => b.spans.filter((s) => s.name === RUN_SPAN).map((s) => ({ s, resource: b.resource })));
3806
- const run = runs[0];
3807
- if (run === undefined)
3808
- return err({ kind: "no-run", reason: `no span is named ${JSON.stringify(RUN_SPAN)}` });
3809
- if (runs.length > 1)
3810
- return err({ kind: "no-run", reason: `${runs.length} spans are named ${JSON.stringify(RUN_SPAN)}` });
3811
- const status = attributeText(run.s.attributes, "test.suite.run.status");
3812
- if (status !== "success" && status !== "failure")
3813
- return err({ kind: "no-run", reason: "its span has no test.suite.run.status of success or failure" });
3814
- const tests = testsOf(signals);
3815
- if (tests.kind === "err")
3816
- return tests;
3817
- const reviews = reviewsOf(signals);
3818
- const required = attributeTexts(run.s.attributes, "ifc.test.required");
3819
- const runners = [];
3820
- const warnings = [];
3821
- for (const b of signals.logs) {
3822
- for (const r of b.records) {
3823
- if (r.eventName === EVENTS.runner) {
3824
- const runtime = attributeText(r.attributes, "process.runtime.name") ?? "unknown";
3825
- const code = attributeInteger(r.attributes, "process.exit.code");
3826
- runners.push(r.attributes["ifc.test.runner.found"] === false || code === undefined ? { kind: "missing", runtime } : { kind: "exited", runtime, code });
3827
- } else if (r.eventName === EVENTS.warning) {
3828
- warnings.push(attributeText(r.attributes, "ifc.test.warning") ?? "");
3829
- }
3776
+ const base = Object.hasOwn(observed.repos, wt.repo) ? observed.repos[wt.repo] ?? ABSENT : ABSENT;
3777
+ switch (base.state.kind) {
3778
+ case "Missing":
3779
+ actions.push({
3780
+ kind: "Skip",
3781
+ target: wt.path,
3782
+ why: { kind: "worktree-unneeded" }
3783
+ });
3784
+ break;
3785
+ case "Locked":
3786
+ case "WrongRemote":
3787
+ case "NotARepo":
3788
+ actions.push({
3789
+ kind: "Skip",
3790
+ target: wt.path,
3791
+ why: { kind: "base-unavailable", state: base.state.kind }
3792
+ });
3793
+ break;
3794
+ case "Dirty":
3795
+ actions.push({
3796
+ kind: "CreateWorktree",
3797
+ target: wt.path,
3798
+ repo: wt.repo,
3799
+ branch: wt.branch
3800
+ });
3801
+ break;
3802
+ case "Clean":
3803
+ case "Ahead":
3804
+ case "Behind":
3805
+ case "Diverged":
3806
+ case "Detached":
3807
+ actions.push(base.busy ? {
3808
+ kind: "CreateWorktree",
3809
+ target: wt.path,
3810
+ repo: wt.repo,
3811
+ branch: wt.branch
3812
+ } : {
3813
+ kind: "Skip",
3814
+ target: wt.path,
3815
+ why: { kind: "worktree-unneeded" }
3816
+ });
3817
+ break;
3818
+ default:
3819
+ return absurd(base.state);
3830
3820
  }
3831
3821
  }
3832
- const installations = new Map;
3833
- for (const b of signals.traces) {
3834
- if (b.spans.some((s) => s.name === TEST_SPAN)) {
3835
- const i = installationOf(b.resource);
3836
- installations.set(JSON.stringify([i.runtime, i.runtimeVersion, i.os, i.arch, i.role, i.revision ?? ""]), i);
3837
- }
3822
+ const wanted = new Set(desired.files.map((f) => f.path));
3823
+ const files = [];
3824
+ for (const f of desired.files) {
3825
+ const seen = Object.hasOwn(observed.files, f.path) ? observed.files[f.path] ?? {} : {};
3826
+ if (seen.onDisk === f.sha256)
3827
+ files.push({
3828
+ kind: "Skip",
3829
+ target: f.path,
3830
+ why: { kind: "file-current" }
3831
+ });
3832
+ else if (seen.onDisk === undefined || seen.onDisk === seen.recorded)
3833
+ files.push({ kind: "WriteGenerated", target: f.path, sha256: f.sha256 });
3834
+ else
3835
+ files.push({
3836
+ kind: "Refuse",
3837
+ target: f.path,
3838
+ why: { kind: "generated-edited" }
3839
+ });
3838
3840
  }
3839
- return ok({
3840
- traceId: run.s.context.traceId,
3841
- spanId: run.s.context.spanId,
3842
- start: run.s.startTime,
3843
- end: run.s.endTime,
3844
- status,
3845
- failures: attributeTexts(run.s.attributes, "ifc.test.failures"),
3846
- unproven: attributeTexts(run.s.attributes, "ifc.test.unproven"),
3847
- required,
3848
- runner: installationOf(run.resource),
3849
- installations: [...installations.entries()].sort(([a], [b]) => byText(a, b)).map(([, i]) => i),
3850
- runners,
3851
- tests: tests.value,
3852
- reviews,
3853
- warnings: [...new Set(warnings)].sort(byText),
3854
- requirements: requirementsOf(tests.value, reviews, required),
3855
- counts: countsOf(tests.value)
3856
- });
3841
+ for (const [path, seen] of Object.entries(observed.files)) {
3842
+ if (wanted.has(path) || seen.recorded === undefined)
3843
+ continue;
3844
+ const target = path;
3845
+ if (seen.onDisk === undefined)
3846
+ files.push({ kind: "Skip", target, why: { kind: "file-absent" } });
3847
+ else if (seen.onDisk === seen.recorded)
3848
+ files.push({ kind: "RemoveGenerated", target });
3849
+ else
3850
+ files.push({ kind: "Refuse", target, why: { kind: "generated-edited" } });
3851
+ }
3852
+ actions.push(...files.sort((a, b) => foldKey(a.target) < foldKey(b.target) ? -1 : foldKey(a.target) > foldKey(b.target) ? 1 : 0));
3853
+ if (options.setupApply === true)
3854
+ for (const c of desired.hostChanges)
3855
+ actions.push({ ...c });
3856
+ return { actions };
3857
3857
  }
3858
- var STYLE = "body{font:15px/1.5 system-ui,sans-serif;margin:2rem auto;max-width:72rem;padding:0 1rem;color:#1b1b1b;background:#fff}" + "table{border-collapse:collapse;margin:.5rem 0;width:100%}th,td{border:1px solid #c8c8c8;padding:.25rem .5rem;text-align:left;vertical-align:top;overflow-wrap:anywhere}" + "th{background:#f0f0f0}h1{font-size:1.6rem}h2{font-size:1.2rem;margin-top:2rem}" + "@media (prefers-color-scheme:dark){body{color:#e8e8e8;background:#161616}th{background:#2a2a2a}th,td{border-color:#444}}";
3859
- // ../ts/kernel/ts-literal.ts
3860
- class Stop2 extends Error {
3861
- at;
3862
- expected;
3863
- constructor(at, expected) {
3864
- super(`not a literal at ${at}: expected ${expected}`);
3865
- this.at = at;
3866
- this.expected = expected;
3858
+ async function planDigest(p) {
3859
+ return await sha256(JSON.stringify(p.actions));
3860
+ }
3861
+ function isSettled(p) {
3862
+ return p.actions.every((a) => a.kind === "Skip");
3863
+ }
3864
+
3865
+ // src/findings.ts
3866
+ var SEVERITIES2 = ["Informational", "Warning", "Error"];
3867
+ function sarifLevel(severity) {
3868
+ switch (severity) {
3869
+ case "Informational":
3870
+ return "note";
3871
+ case "Warning":
3872
+ return "warning";
3873
+ case "Error":
3874
+ return "error";
3875
+ default:
3876
+ return absurd(severity);
3867
3877
  }
3868
3878
  }
3869
- function parseTsLiteral(text, start = 0) {
3870
- let i = start;
3871
- const ws = () => {
3872
- for (;; ) {
3873
- while (i < text.length && /\s/.test(text[i] ?? ""))
3874
- i++;
3875
- if (!text.startsWith("//", i))
3876
- return;
3877
- while (i < text.length && text[i] !== `
3878
- `)
3879
- i++;
3880
- }
3881
- };
3882
- const fail = (expected) => {
3883
- throw new Stop2(i, expected);
3884
- };
3885
- const str = () => {
3886
- const m = /^"(?:[^"\\\n]|\\.)*"/.exec(text.slice(i));
3887
- if (m === null)
3888
- return fail("a complete string");
3889
- i += m[0].length;
3890
- const s = JSON.parse(m[0]);
3891
- return typeof s === "string" ? s : fail("a string");
3892
- };
3893
- const value = () => {
3894
- ws();
3895
- const c = text[i];
3896
- if (c === "{") {
3897
- i++;
3898
- const o = {};
3899
- for (;; ) {
3900
- ws();
3901
- if (text[i] === "}") {
3902
- i++;
3903
- return o;
3904
- }
3905
- let k;
3906
- if (text[i] === '"')
3907
- k = str();
3908
- else {
3909
- const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(text.slice(i));
3910
- if (m === null)
3911
- return fail("a key");
3912
- k = m[0];
3913
- i += k.length;
3914
- }
3915
- ws();
3916
- if (text[i] !== ":")
3917
- fail("a colon");
3918
- i++;
3919
- Object.defineProperty(o, k, { value: value(), enumerable: true, writable: true, configurable: true });
3920
- ws();
3921
- if (text[i] === ",")
3922
- i++;
3923
- else if (text[i] !== "}")
3924
- fail("a comma or }");
3925
- }
3926
- }
3927
- if (c === "[") {
3928
- i++;
3929
- const a = [];
3930
- for (;; ) {
3931
- ws();
3932
- if (text[i] === "]") {
3933
- i++;
3934
- return a;
3935
- }
3936
- a.push(value());
3937
- ws();
3938
- if (text[i] === ",")
3939
- i++;
3940
- else if (text[i] !== "]")
3941
- fail("a comma or ]");
3942
- }
3943
- }
3944
- if (c === '"')
3945
- return str();
3946
- const m = /^(-?\d+(\.\d+)?([eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
3947
- if (m === null)
3948
- return fail("a value");
3949
- i += m[0].length;
3950
- const v = JSON.parse(m[0]);
3951
- return typeof v === "number" || typeof v === "boolean" || v === null ? v : fail("a value");
3952
- };
3953
- try {
3954
- const v = value();
3955
- return ok({ value: v, end: i });
3956
- } catch (e) {
3957
- if (e instanceof Stop2)
3958
- return err({ kind: "literal", at: e.at, expected: e.expected });
3959
- throw e;
3960
- }
3879
+ function worst(findings) {
3880
+ let top;
3881
+ for (const f of findings)
3882
+ if (top === undefined || SEVERITIES2.indexOf(f.severity) > SEVERITIES2.indexOf(top))
3883
+ top = f.severity;
3884
+ return top;
3961
3885
  }
3962
- function exportedLiteral(source, name) {
3963
- const m = new RegExp(`export const ${name}(?:\\s*:\\s*[A-Za-z_$][\\w$.<>, \\[\\]]*)?\\s*=\\s*`).exec(source);
3886
+ function exitStatusOf(findings) {
3887
+ const top = worst(findings);
3888
+ return top === "Warning" || top === "Error" ? "Findings" : "Ok";
3889
+ }
3890
+ var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
3891
+ function dayNumber(day) {
3892
+ const m = DAY.exec(day);
3964
3893
  if (m === null)
3965
- return err({ kind: "literal", at: 0, expected: `export const ${name}` });
3966
- const r = parseTsLiteral(source, m.index + m[0].length);
3967
- return r.kind === "ok" ? ok(r.value.value) : r;
3894
+ return;
3895
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
3896
+ const ms = Date.UTC(y, mo - 1, d);
3897
+ const back = new Date(ms);
3898
+ if (back.getUTCFullYear() !== y || back.getUTCMonth() !== mo - 1 || back.getUTCDate() !== d)
3899
+ return;
3900
+ return Math.round(ms / 86400000);
3901
+ }
3902
+ function daysBetween(from, to) {
3903
+ const a = dayNumber(from);
3904
+ const b = dayNumber(to);
3905
+ if (a === undefined)
3906
+ return err(`${JSON.stringify(from)} is not a day (YYYY-MM-DD)`);
3907
+ if (b === undefined)
3908
+ return err(`${JSON.stringify(to)} is not a day (YYYY-MM-DD)`);
3909
+ return ok(b - a);
3910
+ }
3911
+ var UNAPPROVED_GRACE_DAYS = 90;
3912
+ function unapprovedSeverity(firstSeen, today, graceDays = UNAPPROVED_GRACE_DAYS) {
3913
+ const age = daysBetween(firstSeen, today);
3914
+ return age.kind === "ok" && age.value > graceDays ? "Warning" : "Informational";
3915
+ }
3916
+ function firstSeenOf(previous, key, today) {
3917
+ const before = Object.hasOwn(previous, key) ? previous[key] : undefined;
3918
+ return before !== undefined && dayNumber(before) !== undefined ? before : today;
3919
+ }
3920
+ function toSarif(findings, tool = "ergonex") {
3921
+ const rules = [...new Set(findings.map((f) => f.ruleId))].sort().map((id) => ({ id }));
3922
+ return {
3923
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
3924
+ version: "2.1.0",
3925
+ runs: [
3926
+ {
3927
+ tool: {
3928
+ driver: {
3929
+ name: tool,
3930
+ informationUri: "https://intellectual-frontiers.github.io/.github/",
3931
+ rules
3932
+ }
3933
+ },
3934
+ results: findings.map((f) => ({
3935
+ ruleId: f.ruleId,
3936
+ level: sarifLevel(f.severity),
3937
+ message: { text: f.message },
3938
+ locations: [{ logicalLocations: [{ name: f.subject }] }],
3939
+ properties: { firstSeen: f.firstSeen }
3940
+ }))
3941
+ }
3942
+ ]
3943
+ };
3968
3944
  }
3969
- // ../ts/kernel/webauthn.ts
3970
- var clientData = object({ type: string, challenge: string, origin: string }, { crossOrigin: boolean, topOrigin: string });
3971
- var kind = literal("public-key");
3972
- var extensionResults = record(unknownValue);
3973
- // src/platform/r-lock.ts
3974
- var acquireLock2 = acquireLock;
3975
- var describeHolder2 = describeHolder;
3976
- var readHolder2 = readHolder;
3977
3945
 
3978
- // src/portable.ts
3979
- function describePortableError(e) {
3946
+ // src/render.ts
3947
+ function describeGenerateError(e) {
3980
3948
  switch (e.kind) {
3981
- case "empty":
3982
- return "a path segment is empty";
3983
- case "dot":
3984
- return `the path segment ${JSON.stringify(e.segment)} would leave its folder`;
3985
- case "forbidden-character":
3986
- return `the path segment ${JSON.stringify(e.segment)} holds ${JSON.stringify(e.character)}, which Windows does not allow in a name`;
3987
- case "control-character":
3988
- return `the path segment ${JSON.stringify(e.segment)} holds a control character`;
3989
- case "trailing-dot-or-space":
3990
- return `the path segment ${JSON.stringify(e.segment)} ends in a dot or a space, which Windows drops`;
3991
- case "device-name":
3992
- return `the path segment ${JSON.stringify(e.segment)} is the Windows device name ${e.device}, with or without an extension, in any case`;
3993
- case "too-long":
3994
- return `the path segment is ${e.bytes} bytes in UTF-8, and a name may have 255`;
3995
- case "not-nfc":
3996
- return `the path segment ${JSON.stringify(e.segment)} is not in Unicode normalization form NFC, so it would be another name on macOS`;
3949
+ case "bad-path":
3950
+ return `${JSON.stringify(e.path)} cannot be the path of a generated file: ${e.reason}`;
3951
+ case "not-auto":
3952
+ return `${e.path} is a generated file whose name does not carry .auto. (only a Git hook in .ergonex/hooks/ may lack it)`;
3953
+ case "collision":
3954
+ return `${e.path} is the same path as ${e.other} after Unicode normalization and case folding; both are refused`;
3955
+ case "inside-repository":
3956
+ return `${e.path} is inside the working tree of ${e.repository}; a generated file is never written into a repository`;
3957
+ case "bad-data":
3958
+ return `${e.what}: ${e.reason}`;
3997
3959
  default:
3998
3960
  return absurd(e);
3999
3961
  }
4000
3962
  }
4001
- var FORBIDDEN2 = new Set(["<", ">", ":", '"', "/", "\\", "|", "?", "*"]);
4002
- var DEVICE = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9\u00b9\u00b2\u00b3]|LPT[0-9\u00b9\u00b2\u00b3])$/i;
4003
- function isDeviceName(name) {
4004
- return DEVICE.test((name.split(".")[0] ?? "").replace(/ +$/, ""));
3963
+ var HOOKS_FOLDER = ".ergonex/hooks";
3964
+ function headerText(generator) {
3965
+ return `Generated by ${generator}. Do not edit by hand: change workspace.ts and run \`ergonex render\`.`;
4005
3966
  }
4006
- var MAX_SEGMENT_BYTES = 255;
4007
- function segment(text) {
4008
- if (text === "")
4009
- return err({ kind: "empty" });
4010
- if (text === "." || text === "..")
4011
- return err({ kind: "dot", segment: text });
4012
- for (const ch of text) {
4013
- const code = ch.codePointAt(0) ?? 0;
4014
- if (code < 32 || code === 127)
4015
- return err({ kind: "control-character", segment: text });
4016
- if (FORBIDDEN2.has(ch))
4017
- return err({ kind: "forbidden-character", segment: text, character: ch });
4018
- }
4019
- if (text.endsWith(".") || text.endsWith(" "))
4020
- return err({ kind: "trailing-dot-or-space", segment: text });
4021
- const stem = (text.split(".")[0] ?? "").replace(/ +$/, "");
4022
- if (isDeviceName(text))
3967
+ function normalizeText(text) {
3968
+ const lf = text.replace(/^/, "").replaceAll(`\r
3969
+ `, `
3970
+ `).replaceAll("\r", `
3971
+ `);
3972
+ return `${lf.replace(/\n+$/, "")}
3973
+ `;
3974
+ }
3975
+ function isAutoName(name) {
3976
+ return name.includes(".auto.") || name.endsWith(".auto");
3977
+ }
3978
+ function generatedPath(path) {
3979
+ const made = repoPath(path.split("/"));
3980
+ if (made.kind === "err")
4023
3981
  return err({
4024
- kind: "device-name",
4025
- segment: text,
4026
- device: stem.toUpperCase()
3982
+ kind: "bad-path",
3983
+ path,
3984
+ reason: describePortableError(made.error)
4027
3985
  });
4028
- const bytes = new TextEncoder().encode(text).length;
4029
- if (bytes > MAX_SEGMENT_BYTES)
4030
- return err({ kind: "too-long", segment: text.slice(0, 40), bytes });
4031
- if (text !== text.normalize("NFC"))
4032
- return err({ kind: "not-nfc", segment: text });
4033
- return ok(text);
3986
+ return made;
4034
3987
  }
4035
- function repoPath(segments) {
4036
- if (segments.length === 0)
4037
- return err({ kind: "empty" });
4038
- const made = [];
4039
- for (const s of segments) {
4040
- const r = segment(s);
4041
- if (r.kind === "err")
4042
- return r;
4043
- made.push(r.value);
3988
+ var noBom = (text) => text.replace(/^\uFEFF/, "");
3989
+ function contentOf(body, generator) {
3990
+ const header = headerText(generator);
3991
+ switch (body.format) {
3992
+ case "json":
3993
+ return normalizeText(JSON.stringify({ _generated: header, ...body.value }, null, 2));
3994
+ case "markdown":
3995
+ return normalizeText(`<!-- ${header} -->
3996
+
3997
+ ${noBom(body.text)}`);
3998
+ case "yaml":
3999
+ case "gitconfig":
4000
+ case "envrc":
4001
+ return normalizeText(`# ${header}
4002
+
4003
+ ${noBom(body.text)}`);
4004
+ case "sh": {
4005
+ const text = noBom(body.text);
4006
+ const m = /^(#![^\n]*)\n/.exec(text);
4007
+ return m === null ? normalizeText(`# ${header}
4008
+ ${text}`) : normalizeText(`${m[1]}
4009
+ # ${header}
4010
+ ${text.slice(m[0].length)}`);
4011
+ }
4012
+ default:
4013
+ return absurd(body);
4044
4014
  }
4045
- return ok(made.join("/"));
4046
4015
  }
4047
- function segmentsOf(path) {
4048
- return path.split("/");
4049
- }
4050
- function nativePath(root, path, separator) {
4051
- const base = root.replace(/[\\/]+$/, "");
4052
- return [base, ...segmentsOf(path)].join(separator);
4053
- }
4054
- function foldKey(path) {
4055
- return path.normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
4056
- }
4057
- function collisions(items) {
4058
- const groups = new Map;
4059
- for (const item of items) {
4060
- const key = foldKey(item.path);
4061
- const group = groups.get(key);
4062
- if (group === undefined)
4063
- groups.set(key, [{ ...item }]);
4064
- else
4065
- group.push({ ...item });
4066
- }
4067
- return [...groups.entries()].filter(([, members]) => members.length > 1).map(([key, members]) => ({ key, members }));
4068
- }
4069
- var WINDOWS_PATH_LIMIT = 259;
4070
- function checkPathLength(windowsPath, longPathsEnabled) {
4071
- if (longPathsEnabled || windowsPath.length <= WINDOWS_PATH_LIMIT)
4072
- return ok(windowsPath);
4073
- return err({
4074
- kind: "path-too-long",
4075
- path: windowsPath,
4076
- length: windowsPath.length,
4077
- limit: WINDOWS_PATH_LIMIT
4016
+ function generated(path, body, options) {
4017
+ const made = generatedPath(path);
4018
+ if (made.kind === "err")
4019
+ return made;
4020
+ const name = made.value.split("/").at(-1) ?? "";
4021
+ const isHook = made.value.startsWith(`${HOOKS_FOLDER}/`) && made.value.split("/").length === 3;
4022
+ if (!isAutoName(name) && !isHook)
4023
+ return err({ kind: "not-auto", path });
4024
+ return ok({
4025
+ path: made.value,
4026
+ content: contentOf(body, options.generator),
4027
+ mode: options.mode ?? "0644",
4028
+ generator: options.generator
4078
4029
  });
4079
4030
  }
4080
- var REPO_PATH_ROOM = 150;
4081
- function repoPathLength(root, path, separator) {
4082
- const length = nativePath(root, path, separator).length;
4083
- if (length > WINDOWS_PATH_LIMIT)
4084
- return { kind: "too-long", length };
4085
- if (length > REPO_PATH_ROOM)
4086
- return { kind: "no-room", length };
4087
- return { kind: "fits", length };
4031
+ function fileDigest(file) {
4032
+ return sha256(file.content);
4033
+ }
4034
+ function checkFiles(files, repositories) {
4035
+ const errors = [];
4036
+ for (const c of collisions(files.map((f) => ({ id: f.path, path: f.path })))) {
4037
+ for (const m of c.members) {
4038
+ const other = c.members.find((o) => o !== m);
4039
+ errors.push({
4040
+ kind: "collision",
4041
+ path: m.path,
4042
+ other: other?.path ?? m.path
4043
+ });
4044
+ }
4045
+ }
4046
+ for (const f of files) {
4047
+ const key = foldKey(f.path);
4048
+ const inside = repositories.find((r) => key.startsWith(`${foldKey(r)}/`));
4049
+ if (inside !== undefined)
4050
+ errors.push({
4051
+ kind: "inside-repository",
4052
+ path: f.path,
4053
+ repository: inside
4054
+ });
4055
+ }
4056
+ if (errors.length > 0)
4057
+ return err(errors);
4058
+ return ok([...files].sort((a, b) => foldKey(a.path) < foldKey(b.path) ? -1 : foldKey(a.path) > foldKey(b.path) ? 1 : 0));
4088
4059
  }
4089
4060
 
4090
- // ../ts/githost/capabilities.ts
4091
- var COMMON_CAPABILITIES = ["CloneUrl", "Credentials", "DefaultBranch", "SignedCommits"];
4092
- var HOSTED = [...COMMON_CAPABILITIES, "ProtectedBranches", "Issues", "ChangeRequests"];
4093
- var CAPABILITIES = {
4094
- Github: new Set(HOSTED),
4095
- Gitlab: new Set([...HOSTED, "NestedGroups"]),
4096
- Git: new Set(COMMON_CAPABILITIES)
4061
+ // src/state-record.ts
4062
+ var ERGONEX_VERSION = "0.3.2";
4063
+ var STATE_RECORD_PATH = ".ergonex/state.auto.json";
4064
+ var EMPTY_RECORD = {
4065
+ ergonex: ERGONEX_VERSION,
4066
+ files: {},
4067
+ firstSeen: {}
4097
4068
  };
4098
- function supports(kind, capability) {
4099
- return CAPABILITIES[kind].has(capability);
4069
+ var hash = (input, path = "$") => {
4070
+ const s = typeof input === "string" ? sha256Of(input) : undefined;
4071
+ return s === undefined ? err({
4072
+ kind: "decode",
4073
+ path,
4074
+ expected: "a SHA-256 (64 hexadecimal digits)",
4075
+ found: typeof input
4076
+ }) : ok(s);
4077
+ };
4078
+ var day = (input, path = "$") => typeof input === "string" && dayNumber(input) !== undefined ? ok(input) : err({
4079
+ kind: "decode",
4080
+ path,
4081
+ expected: "a day (YYYY-MM-DD)",
4082
+ found: typeof input
4083
+ });
4084
+ var shape = object({
4085
+ ergonex: string,
4086
+ files: record(object({ sha256: hash, generator: string })),
4087
+ firstSeen: record(day)
4088
+ }, { plan: hash });
4089
+ function decodeStateRecord(text) {
4090
+ const r = json(text, shape);
4091
+ return r.kind === "ok" ? ok(r.value) : err(formatDecodeError(r.error));
4100
4092
  }
4101
- function maxDepth(kind) {
4102
- return supports(kind, "NestedGroups") ? Number.POSITIVE_INFINITY : 2;
4093
+ function encodeStateRecord(r) {
4094
+ const sorted = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
4095
+ const value = {
4096
+ _generated: headerText("ergonex state"),
4097
+ ergonex: r.ergonex,
4098
+ ...r.plan === undefined ? {} : { plan: r.plan },
4099
+ files: sorted(r.files),
4100
+ firstSeen: sorted(r.firstSeen)
4101
+ };
4102
+ return `${JSON.stringify(value, null, 2)}
4103
+ `;
4103
4104
  }
4104
-
4105
- // ../ts/githost/remote.ts
4106
- function describeRemoteError(e) {
4107
- switch (e.kind) {
4108
- case "empty":
4109
- return "the remote is empty";
4110
- case "local-path":
4111
- return "the remote is a path on this computer, not a repository on a Git host";
4112
- case "unsupported-scheme":
4113
- return `the remote's scheme ${e.scheme}: is not https, http, git or ssh`;
4114
- case "no-host":
4115
- return "the remote names no host";
4116
- case "no-path":
4117
- return "the remote names no owner and repository";
4118
- case "bad-segment":
4119
- return `the remote's path is not valid: ${e.reason}`;
4120
- default:
4121
- return absurd(e);
4122
- }
4105
+ function withFile(r, file, digest) {
4106
+ return {
4107
+ ...r,
4108
+ files: {
4109
+ ...r.files,
4110
+ [file.path]: { sha256: digest, generator: file.generator }
4111
+ }
4112
+ };
4123
4113
  }
4124
- function hostKindOf(host, hostKinds = {}) {
4125
- const h = host.toLowerCase();
4126
- if (h === "github.com")
4127
- return "Github";
4128
- if (h === "gitlab.com")
4129
- return "Gitlab";
4130
- const named = Object.hasOwn(hostKinds, h) ? hostKinds[h] : undefined;
4131
- return named ?? "Git";
4114
+ function withoutFile(r, path) {
4115
+ return {
4116
+ ...r,
4117
+ files: Object.fromEntries(Object.entries(r.files).filter(([p]) => p !== path))
4118
+ };
4132
4119
  }
4133
- function safeDecode(segment) {
4134
- try {
4135
- return decodeURIComponent(segment);
4136
- } catch {
4137
- return;
4120
+ function verifyFindings(facts, today) {
4121
+ const out = [];
4122
+ for (const f of facts) {
4123
+ const at = (ruleId, severity, message) => void out.push({
4124
+ ruleId,
4125
+ severity,
4126
+ message,
4127
+ subject: f.path,
4128
+ firstSeen: today
4129
+ });
4130
+ if (f.recorded !== undefined && f.onDisk === undefined) {
4131
+ at("ergonex/generated-missing", "Warning", `${f.path} is recorded as written and is not there; run \`ergonex render\` to write it again`);
4132
+ } else if (f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded) {
4133
+ at("ergonex/generated-edited", "Error", `${f.path} was edited by hand (its bytes are not the ones recorded); \`ergonex render --force\` replaces it`);
4134
+ } else if (f.recorded === undefined && f.onDisk !== undefined) {
4135
+ at("ergonex/generated-unrecorded", "Warning", `${f.path} is a generated file the state record does not hold; run \`ergonex render\` to record it, or remove it`);
4136
+ }
4137
+ const edited = f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded;
4138
+ const missing = f.recorded !== undefined && f.onDisk === undefined;
4139
+ if (f.wanted !== undefined && f.onDisk !== f.wanted && !edited && !missing) {
4140
+ at("ergonex/generated-drift", "Warning", f.onDisk === undefined ? `${f.path} is not written yet; run \`ergonex render\`` : `${f.path} would be written differently by the templates now; run \`ergonex render\``);
4141
+ }
4138
4142
  }
4143
+ return out;
4139
4144
  }
4140
- function refOf(host, rawPath, hostKinds) {
4141
- const hostName = host.toLowerCase();
4142
- if (hostName === "")
4143
- return err({ kind: "no-host" });
4144
- const trimmed = rawPath.replace(/[?#].*$/s, "").replace(/\/+$/, "");
4145
- const segments = [];
4146
- for (const raw of trimmed.split("/")) {
4147
- if (raw === "")
4148
- continue;
4149
- const s = safeDecode(raw);
4150
- if (s === undefined)
4151
- return err({ kind: "bad-segment", reason: "a percent escape is not valid" });
4152
- if (s.includes("/") || s.includes("\\"))
4153
- return err({ kind: "bad-segment", reason: "a segment holds a separator" });
4154
- segments.push(s);
4145
+
4146
+ // src/platform/r-errors.ts
4147
+ var NotFound2 = errors.NotFound;
4148
+
4149
+ // src/host/observe.ts
4150
+ var ENV = {
4151
+ GIT_TERMINAL_PROMPT: "0",
4152
+ GIT_PAGER: "cat",
4153
+ PAGER: "cat",
4154
+ GIT_OPTIONAL_LOCKS: "0",
4155
+ LC_ALL: "C",
4156
+ LANGUAGE: "C"
4157
+ };
4158
+ async function git(folder, args, options) {
4159
+ const program = options.program ?? "git";
4160
+ try {
4161
+ const r = await output2([program, "--no-pager", "-C", folder, ...args], {
4162
+ env: { ...ENV, ...options.env }
4163
+ });
4164
+ return ok({
4165
+ code: r.code,
4166
+ stdout: new TextDecoder().decode(r.stdout).trim()
4167
+ });
4168
+ } catch (e) {
4169
+ if (e instanceof NotFound2)
4170
+ return err({ kind: "git-missing", program });
4171
+ throw e;
4155
4172
  }
4156
- const last = segments.at(-1);
4157
- if (last === undefined)
4158
- return err({ kind: "no-path" });
4159
- segments[segments.length - 1] = last.replace(/\.git$/i, "");
4160
- if (segments.length < 2 || segments.some((s) => s === ""))
4161
- return err({ kind: "no-path" });
4162
- return ok({ kind: hostKindOf(hostName, hostKinds), host: hostName, path: segments });
4163
4173
  }
4164
- function hostOfAuthority(authority) {
4165
- const afterAt = authority.slice(authority.lastIndexOf("@") + 1);
4166
- if (afterAt.startsWith("["))
4167
- return afterAt.slice(0, afterAt.indexOf("]") + 1);
4168
- const colon = afterAt.indexOf(":");
4169
- return colon < 0 ? afterAt : afterAt.slice(0, colon);
4170
- }
4171
- function parseRemote(url, hostKinds = {}) {
4172
- const text = url.trim();
4173
- if (text === "")
4174
- return err({ kind: "empty" });
4175
- const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(text);
4176
- if (scheme !== null) {
4177
- const name = (scheme[1] ?? "").toLowerCase();
4178
- if (name === "file")
4179
- return err({ kind: "local-path" });
4180
- if (!["https", "http", "git", "ssh", "git+ssh", "ssh+git"].includes(name))
4181
- return err({ kind: "unsupported-scheme", scheme: name });
4182
- const rest = text.slice(scheme[0].length);
4183
- const slash = rest.indexOf("/");
4184
- const authority = slash < 0 ? rest : rest.slice(0, slash);
4185
- return refOf(hostOfAuthority(authority), slash < 0 ? "" : rest.slice(slash), hostKinds);
4174
+ function hasLockFile(gitDir) {
4175
+ const walk = (dir, depth) => {
4176
+ let entries;
4177
+ try {
4178
+ entries = readDirSync2(dir);
4179
+ } catch {
4180
+ return false;
4181
+ }
4182
+ for (const e of entries) {
4183
+ if (e.isFile && e.name.endsWith(".lock"))
4184
+ return true;
4185
+ if (e.isDirectory && depth > 0 && walk(join6(dir, e.name), depth - 1))
4186
+ return true;
4187
+ }
4188
+ return false;
4189
+ };
4190
+ const top = readDirSync2(gitDir).some((e) => e.isFile && e.name.endsWith(".lock"));
4191
+ return top || existsSync2(join6(gitDir, "refs")) && walk(join6(gitDir, "refs"), 6);
4192
+ }
4193
+ async function observeFacts(folder, options = {}) {
4194
+ if (!existsSync2(folder))
4195
+ return ok({ kind: "absent" });
4196
+ if (!lstatSync3(folder).isDirectory)
4197
+ return ok({ kind: "not-a-repository" });
4198
+ if (readDirSync2(folder).length === 0)
4199
+ return ok({ kind: "absent" });
4200
+ if (!existsSync2(join6(folder, ".git")))
4201
+ return ok({ kind: "not-a-repository" });
4202
+ const dir = await git(folder, ["rev-parse", "--absolute-git-dir"], options);
4203
+ if (dir.kind === "err")
4204
+ return dir;
4205
+ if (dir.value.code !== 0 || dir.value.stdout === "")
4206
+ return ok({ kind: "not-a-repository" });
4207
+ const remote = await git(folder, ["config", "--get", "remote.origin.url"], options);
4208
+ if (remote.kind === "err")
4209
+ return remote;
4210
+ const originUrl = remote.value.code === 0 && remote.value.stdout !== "" ? remote.value.stdout : undefined;
4211
+ if (options.fetch === true && originUrl !== undefined) {
4212
+ const f = await git(folder, ["fetch", "--quiet", "origin"], options);
4213
+ if (f.kind === "err")
4214
+ return f;
4186
4215
  }
4187
- if (/^[A-Za-z]:[\\/]/.test(text) || text.startsWith("/") || text.startsWith(".") || text.startsWith("~"))
4188
- return err({ kind: "local-path" });
4189
- const colon = text.indexOf(":");
4190
- const slash = text.indexOf("/");
4191
- if (colon < 0 || slash >= 0 && slash < colon)
4192
- return err({ kind: "local-path" });
4193
- return refOf(hostOfAuthority(text.slice(0, colon)), text.slice(colon + 1), hostKinds);
4216
+ const head = await git(folder, ["symbolic-ref", "-q", "HEAD"], options);
4217
+ if (head.kind === "err")
4218
+ return head;
4219
+ const detached = head.value.code !== 0;
4220
+ const status = await git(folder, ["status", "--porcelain=v1", "-z", "--untracked-files=normal", "--ignore-submodules=none"], options);
4221
+ if (status.kind === "err")
4222
+ return status;
4223
+ const dirty = status.value.code === 0 && status.value.stdout !== "";
4224
+ let ahead = 0;
4225
+ let behind = 0;
4226
+ if (!detached) {
4227
+ const counts = await git(folder, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], options);
4228
+ if (counts.kind === "err")
4229
+ return counts;
4230
+ const m = counts.value.code === 0 ? /^(\d+)\s+(\d+)$/.exec(counts.value.stdout) : null;
4231
+ if (m !== null) {
4232
+ ahead = Number(m[1]);
4233
+ behind = Number(m[2]);
4234
+ } else {
4235
+ const own = await git(folder, ["rev-list", "--count", "HEAD", "--not", "--remotes"], options);
4236
+ if (own.kind === "err")
4237
+ return own;
4238
+ ahead = own.value.code === 0 && /^\d+$/.test(own.value.stdout) ? Number(own.value.stdout) : 0;
4239
+ }
4240
+ }
4241
+ return ok({
4242
+ kind: "repository",
4243
+ remote: originUrl,
4244
+ lockFile: hasLockFile(dir.value.stdout),
4245
+ detached,
4246
+ dirty,
4247
+ ahead,
4248
+ behind
4249
+ });
4194
4250
  }
4195
- var HOSTNAME = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+(?::\d+)?$/;
4196
- function webPage(path) {
4197
- const m = /^(.*?)\/(?:-\/)?(?:tree|blob|commits|raw)\/([^/?#]+)(?:[/?#].*)?$/s.exec(path);
4198
- if (m === null)
4199
- return { path };
4200
- const branch = safeDecode(m[2] ?? "");
4201
- return branch === undefined ? { path } : { path: m[1] ?? path, branch };
4251
+ async function observe(folder, expected, options = {}) {
4252
+ const facts = await observeFacts(folder, options);
4253
+ return facts.kind === "err" ? facts : ok(classify(facts.value, expected));
4202
4254
  }
4203
- function readRemote(input, hostKinds = {}) {
4204
- const text = input.trim();
4205
- const strict = parseRemote(text, hostKinds);
4206
- const asIs = () => strict.kind === "err" ? strict : ok({ ref: strict.value });
4207
- const viaPage = (origin, path) => {
4208
- const page = webPage(path);
4209
- const r = parseRemote(`${origin}${page.path}`, hostKinds);
4210
- return r.kind === "err" ? r : ok(page.branch === undefined ? { ref: r.value } : { ref: r.value, branch: page.branch });
4211
- };
4212
- const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/]*)(\/.*)?$/.exec(text);
4213
- if (scheme !== null)
4214
- return strict.kind === "err" && scheme[1]?.toLowerCase() === "file" ? strict : viaPage(`${scheme[1]}://${scheme[2]}`, scheme[3] ?? "");
4215
- if (text === "" || /^[A-Za-z]:[\\/]/.test(text) || /^[/.~]/.test(text))
4216
- return asIs();
4217
- const named = /^(github|gitlab):([^/].*)$/i.exec(text);
4218
- if (named !== null)
4219
- return viaPage(`https://${(named[1] ?? "").toLowerCase()}.com/`, named[2] ?? "");
4220
- const colon = text.indexOf(":");
4221
- const slash = text.indexOf("/");
4222
- if (colon >= 0 && (slash < 0 || colon < slash))
4223
- return asIs();
4224
- const first = slash < 0 ? text : text.slice(0, slash);
4225
- if (slash >= 0 && HOSTNAME.test(first))
4226
- return viaPage(`https://${first}`, text.slice(slash));
4227
- if (/^[^/\s]+\/[^/\s]+$/.test(text))
4228
- return viaPage("https://github.com/", text);
4229
- return asIs();
4255
+
4256
+ // src/host/worktrees.ts
4257
+ var ENV2 = {
4258
+ GIT_TERMINAL_PROMPT: "0",
4259
+ GIT_PAGER: "cat",
4260
+ PAGER: "cat",
4261
+ LC_ALL: "C",
4262
+ LANGUAGE: "C"
4263
+ };
4264
+ async function git2(folder, args) {
4265
+ const r = await run2(["git", "-C", folder, ...args], { env: ENV2 });
4266
+ return r.success ? ok(r.stdout.trim()) : err((r.stderr.split(`
4267
+ `).find((l) => l.trim() !== "") ?? "git failed").trim());
4230
4268
  }
4231
- function cloneUrlOf(ref) {
4232
- return `https://${ref.host}/${ref.path.map(encodeURIComponent).join("/")}.git`;
4269
+ async function listWorktrees(folder) {
4270
+ const r = await git2(folder, ["worktree", "list", "--porcelain"]);
4271
+ if (r.kind === "err")
4272
+ return r;
4273
+ const out = [];
4274
+ for (const block of r.value.split(/\n\s*\n/)) {
4275
+ const lines = block.split(`
4276
+ `);
4277
+ const path = lines.find((l) => l.startsWith("worktree "))?.slice("worktree ".length);
4278
+ if (path === undefined)
4279
+ continue;
4280
+ const branch = lines.find((l) => l.startsWith("branch "))?.slice("branch ".length).replace(/^refs\/heads\//, "");
4281
+ out.push({ path, branch, main: out.length === 0 });
4282
+ }
4283
+ return ok(out);
4233
4284
  }
4234
- function describeRef(ref) {
4235
- return `${ref.host}/${ref.path.join("/")}`;
4285
+ async function localWork(worktree) {
4286
+ const status = await git2(worktree, ["status", "--porcelain=v1", "--untracked-files=normal"]);
4287
+ if (status.kind === "err")
4288
+ return status;
4289
+ const own = await git2(worktree, ["rev-list", "--count", "HEAD", "--not", "--remotes"]);
4290
+ if (own.kind === "err")
4291
+ return own;
4292
+ return ok({ dirty: status.value !== "", unpushed: Number(own.value) || 0 });
4236
4293
  }
4237
- function sameRepository(a, b) {
4238
- return a.host.toLowerCase() === b.host.toLowerCase() && a.path.length === b.path.length && a.path.every((s, i) => s.toLowerCase() === (b.path[i] ?? "").toLowerCase());
4294
+ async function createWorktree(folder, target, branch) {
4295
+ if (existsSync2(target))
4296
+ return err(`${target} exists`);
4297
+ await mkdir3(dirname4(target), { recursive: true });
4298
+ const exists = await git2(folder, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]);
4299
+ const r = await git2(folder, exists.kind === "ok" ? ["worktree", "add", target, branch] : ["worktree", "add", "-b", branch, target]);
4300
+ return r.kind === "ok" ? ok(`worktree for ${branch}`) : r;
4301
+ }
4302
+ async function removeWorktree(folder, worktree) {
4303
+ const work = await localWork(worktree);
4304
+ if (work.kind === "err")
4305
+ return work;
4306
+ if (work.value.dirty)
4307
+ return err("it has uncommitted changes");
4308
+ if (work.value.unpushed > 0)
4309
+ return err(`it has ${work.value.unpushed} commit${work.value.unpushed === 1 ? "" : "s"} that are on no remote`);
4310
+ const r = await git2(folder, ["worktree", "remove", worktree]);
4311
+ return r.kind === "ok" ? ok("removed") : r;
4239
4312
  }
4240
4313
 
4241
- // ../ts/githost/github.ts
4242
- var repoShape = object({ private: boolean, default_branch: string, clone_url: string, archived: boolean }, { visibility: string });
4243
- var issueShape = object({ number: integer, title: string, state: literal("open", "closed"), html_url: string }, { body: nullable(string), labels: array(oneOf(string, object({ name: string }))), pull_request: unknownValue });
4244
- var subIssuesShape = array(object({ number: integer }));
4245
- var pullShape = object({
4246
- number: integer,
4247
- title: string,
4248
- state: literal("open", "closed"),
4249
- html_url: string,
4250
- head: object({ ref: string }),
4251
- base: object({ ref: string })
4252
- }, { merged: boolean, merged_at: nullable(string) });
4253
- var branchShape = object({ name: string, protected: boolean });
4254
- var protectionShape = object({}, { required_pull_request_reviews: unknownValue, allow_force_pushes: object({ enabled: boolean }) });
4255
- var commitShape = object({ commit: object({ verification: object({ verified: boolean }) }) });
4256
-
4257
- // ../ts/githost/gitlab.ts
4258
- var projectShape = object({ http_url_to_repo: string }, { archived: boolean, visibility: literal("public", "internal", "private"), default_branch: nullable(string) });
4259
- var issueShape2 = object({ iid: integer, title: string, state: literal("opened", "closed"), web_url: string }, { description: nullable(string), labels: array(string) });
4260
- var mergeRequestShape = object({
4261
- iid: integer,
4262
- title: string,
4263
- state: literal("opened", "closed", "merged", "locked"),
4264
- web_url: string,
4265
- source_branch: string,
4266
- target_branch: string
4267
- });
4268
- var branchShape2 = object({ name: string, protected: boolean });
4269
- var protectedShape = object({ name: string, allow_force_push: boolean }, { code_owner_approval_required: boolean, push_access_levels: array(object({ access_level: integer })) });
4270
- var signatureShape = object({ verification_status: string });
4271
- // src/state.ts
4272
- function holdsLocalWork(kind) {
4273
- switch (kind) {
4274
- case "Missing":
4275
- case "Clean":
4276
- case "Behind":
4277
- return false;
4278
- case "Dirty":
4279
- case "Ahead":
4280
- case "Diverged":
4281
- case "Locked":
4282
- case "Detached":
4283
- case "WrongRemote":
4284
- case "NotARepo":
4285
- return true;
4286
- default:
4287
- return absurd(kind);
4314
+ // src/desired.ts
4315
+ function settingsOf(manifest, facts) {
4316
+ const settings = {
4317
+ "core.hooksPath": `${facts.homePosix.replace(/\/+$/, "")}/.ergonex/hooks`
4318
+ };
4319
+ if (manifest.policy.requiresSignedCommits) {
4320
+ settings["commit.gpgsign"] = "true";
4321
+ if (manifest.signing !== undefined) {
4322
+ settings["gpg.format"] = manifest.signing.format;
4323
+ if (manifest.signing.key !== undefined)
4324
+ settings["user.signingkey"] = manifest.signing.key;
4325
+ }
4326
+ }
4327
+ if (manifest.identity !== undefined) {
4328
+ settings["user.name"] = manifest.identity.name;
4329
+ settings["user.email"] = manifest.identity.email;
4288
4330
  }
4331
+ if (facts.windows)
4332
+ settings["core.longpaths"] = "true";
4333
+ return settings;
4289
4334
  }
4290
- function describeRemote(remote) {
4291
- if (remote === undefined || remote.trim() === "")
4292
- return "(none)";
4293
- const r = parseRemote(remote);
4294
- return r.kind === "ok" ? describeRef(r.value) : "(not a remote of a host)";
4295
- }
4296
- function isExpectedRemote(remote, expected) {
4297
- if (remote === undefined)
4298
- return false;
4299
- const r = parseRemote(remote);
4300
- return r.kind === "ok" && sameRepository(r.value, expected);
4301
- }
4302
- function classify(facts, expected) {
4303
- switch (facts.kind) {
4304
- case "absent":
4305
- return { kind: "Missing" };
4306
- case "not-a-repository":
4307
- return { kind: "NotARepo" };
4308
- case "repository": {
4309
- if (!isExpectedRemote(facts.remote, expected))
4310
- return { kind: "WrongRemote", found: describeRemote(facts.remote) };
4311
- if (facts.lockFile)
4312
- return { kind: "Locked" };
4313
- if (facts.detached)
4314
- return { kind: "Detached" };
4315
- if (facts.dirty)
4316
- return { kind: "Dirty" };
4317
- if (facts.ahead > 0 && facts.behind > 0)
4318
- return { kind: "Diverged", ahead: facts.ahead, behind: facts.behind };
4319
- if (facts.ahead > 0)
4320
- return { kind: "Ahead", commits: facts.ahead };
4321
- if (facts.behind > 0)
4322
- return { kind: "Behind", commits: facts.behind };
4323
- return { kind: "Clean" };
4324
- }
4325
- default:
4326
- return absurd(facts);
4327
- }
4335
+ async function desiredOf(manifest, files, facts) {
4336
+ const settings = settingsOf(manifest, facts);
4337
+ const repos = manifest.repositories.map((r) => ({
4338
+ path: r.path,
4339
+ ref: r.ref,
4340
+ cloneUrl: r.cloneUrl,
4341
+ branch: r.branch,
4342
+ settings
4343
+ }));
4344
+ const worktrees = manifest.repositories.flatMap((r) => r.worktrees.map((w) => ({ path: w.path, repo: r.path, branch: w.branch })));
4345
+ const desiredFiles = [];
4346
+ for (const f of files)
4347
+ desiredFiles.push({ path: f.path, sha256: await fileDigest(f) });
4348
+ return { repos, worktrees, files: desiredFiles, hostChanges: [] };
4328
4349
  }
4329
4350
 
4330
- // src/plan.ts
4331
- function isDestructive(action) {
4332
- const kind = typeof action === "string" ? action : action.kind;
4333
- switch (kind) {
4334
- case "RemoveGenerated":
4335
- return true;
4336
- case "Clone":
4337
- case "FastForward":
4338
- case "CreateWorktree":
4339
- case "ConfigureRepo":
4340
- case "ConfigureHost":
4341
- case "WriteGenerated":
4342
- case "InstallTool":
4343
- case "Skip":
4344
- case "Refuse":
4345
- return false;
4346
- default:
4347
- return absurd(kind);
4348
- }
4351
+ // src/places.ts
4352
+ var APP = ".ergonex";
4353
+ function movedKind(rest) {
4354
+ if (rest === "state.auto.json" || rest === "ergonex.lock" || rest === "evidence" || rest.startsWith("evidence/"))
4355
+ return "state";
4356
+ if (rest === "tools" || rest.startsWith("tools/"))
4357
+ return "tools";
4358
+ return;
4349
4359
  }
4350
- function isHostChange(action) {
4351
- const kind = typeof action === "string" ? action : action.kind;
4352
- switch (kind) {
4353
- case "ConfigureHost":
4354
- case "InstallTool":
4355
- return true;
4356
- case "Clone":
4357
- case "FastForward":
4358
- case "CreateWorktree":
4359
- case "ConfigureRepo":
4360
- case "WriteGenerated":
4361
- case "RemoveGenerated":
4362
- case "Skip":
4363
- case "Refuse":
4364
- return false;
4365
- default:
4366
- return absurd(kind);
4367
- }
4360
+ function movedPath(places, path) {
4361
+ if (path !== APP && !path.startsWith(`${APP}/`))
4362
+ return;
4363
+ const rest = path === APP ? "" : path.slice(APP.length + 1);
4364
+ const sep = places.os === "windows" ? "\\" : "/";
4365
+ const under = (base, parts) => [base.replace(/[\\/]+$/, ""), ...parts].join(sep);
4366
+ const kind = movedKind(rest);
4367
+ if (kind === "state")
4368
+ return under(places.state, rest.split("/"));
4369
+ if (kind === "tools")
4370
+ return under(places.tools, rest.split("/").slice(1));
4371
+ return;
4368
4372
  }
4369
- function describeAction(action) {
4370
- switch (action.kind) {
4371
- case "Clone":
4372
- return `clone ${action.url} into ${action.target}`;
4373
- case "FastForward":
4374
- return `fast-forward ${action.target} by ${action.commits} commit${action.commits === 1 ? "" : "s"}`;
4375
- case "CreateWorktree":
4376
- return `add a worktree of ${action.repo} for ${action.branch} at ${action.target}`;
4377
- case "ConfigureRepo":
4378
- return `set ${Object.keys(action.settings).sort().join(", ")} in the local Git configuration of ${action.target}`;
4379
- case "ConfigureHost":
4380
- return `change the host: ${action.what}`;
4381
- case "WriteGenerated":
4382
- return `write the generated file ${action.target}`;
4383
- case "RemoveGenerated":
4384
- return `remove the generated file ${action.target}`;
4385
- case "InstallTool":
4386
- return `install ${action.tool} ${action.version}`;
4387
- case "Skip":
4388
- return `skip ${action.target}: ${describeSkip(action.why)}`;
4389
- case "Refuse":
4390
- return `refuse ${action.target}: ${describeRefusal(action.why)}`;
4391
- default:
4392
- return absurd(action);
4393
- }
4373
+ // ../formats/src/semver.ts
4374
+ var PATTERN = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
4375
+ function parseSemVer(text) {
4376
+ const m = PATTERN.exec(text.trim());
4377
+ if (m === null)
4378
+ return err(`${JSON.stringify(text)} is not a semantic version (major.minor.patch[-pre][+build])`);
4379
+ const [, major = "", minor = "", patch = "", pre, build] = m;
4380
+ const parts = [Number(major), Number(minor), Number(patch)];
4381
+ if (!parts.every(Number.isSafeInteger))
4382
+ return err(`${JSON.stringify(text)} has a number too large`);
4383
+ return ok({
4384
+ major: parts[0],
4385
+ minor: parts[1],
4386
+ patch: parts[2],
4387
+ ...pre === undefined ? {} : { pre },
4388
+ ...build === undefined ? {} : { build }
4389
+ });
4394
4390
  }
4395
- function describeSkip(why) {
4396
- switch (why.kind) {
4397
- case "in-sync":
4398
- return "it is up to date";
4399
- case "uncommitted-changes":
4400
- return "it has uncommitted changes, which are never touched";
4401
- case "ahead":
4402
- return `it has ${why.commits} commit${why.commits === 1 ? "" : "s"} its remote does not`;
4403
- case "diverged":
4404
- return `it has ${why.ahead} commit${why.ahead === 1 ? "" : "s"} its remote does not and the remote has ${why.behind} it does not; only a person merges`;
4405
- case "locked":
4406
- return "a Git lock file is there, so another process may be working in it; the lock is not removed";
4407
- case "detached":
4408
- return "HEAD is on no branch";
4409
- case "worktree-unneeded":
4410
- return "nobody else is working in the repository and it has no uncommitted work, so its own checkout is the place to work";
4411
- case "worktree-exists":
4412
- return "the worktree is there";
4413
- case "base-unavailable":
4414
- return `its repository is ${why.state}`;
4415
- case "file-current":
4416
- return "its bytes are the generated ones";
4417
- case "file-absent":
4418
- return "it is not there and is not wanted";
4419
- default:
4420
- return absurd(why);
4421
- }
4391
+ function dottedParts(version) {
4392
+ return version.trim().replace(/^v/, "").split(/[.+_-]/).map((p) => Number.parseInt(p, 10)).map((n) => Number.isNaN(n) ? 0 : n);
4422
4393
  }
4423
- function describeRefusal(why) {
4424
- switch (why.kind) {
4425
- case "wrong-remote":
4426
- return `a repository of ${why.found} is at that path, not the one the manifest names, and it is never overwritten`;
4427
- case "not-a-repository":
4428
- return "something that is not a Git repository is at that path, and it is never overwritten";
4429
- case "generated-edited":
4430
- return "its bytes are not the ones the state record holds, so it was edited by hand; `--force` replaces it";
4431
- default:
4432
- return absurd(why);
4394
+ function compareDotted(a, b) {
4395
+ const x = dottedParts(a);
4396
+ const y = dottedParts(b);
4397
+ for (let i = 0;i < Math.max(x.length, y.length); i++) {
4398
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
4399
+ if (d !== 0)
4400
+ return Math.sign(d);
4433
4401
  }
4402
+ return 0;
4434
4403
  }
4435
- function forState(repo, state) {
4436
- const target = repo.path;
4437
- switch (state.kind) {
4438
- case "Missing":
4439
- return { kind: "Clone", target, url: repo.cloneUrl, branch: repo.branch };
4440
- case "Behind":
4441
- return { kind: "FastForward", target, commits: state.commits };
4442
- case "Clean":
4443
- return { kind: "Skip", target, why: { kind: "in-sync" } };
4444
- case "Dirty":
4445
- return { kind: "Skip", target, why: { kind: "uncommitted-changes" } };
4446
- case "Ahead":
4447
- return {
4448
- kind: "Skip",
4449
- target,
4450
- why: { kind: "ahead", commits: state.commits }
4451
- };
4452
- case "Diverged":
4453
- return {
4454
- kind: "Skip",
4455
- target,
4456
- why: { kind: "diverged", ahead: state.ahead, behind: state.behind }
4457
- };
4458
- case "Locked":
4459
- return { kind: "Skip", target, why: { kind: "locked" } };
4460
- case "Detached":
4461
- return { kind: "Skip", target, why: { kind: "detached" } };
4462
- case "WrongRemote":
4463
- return {
4464
- kind: "Refuse",
4465
- target,
4466
- why: { kind: "wrong-remote", found: state.found }
4467
- };
4468
- case "NotARepo":
4469
- return { kind: "Refuse", target, why: { kind: "not-a-repository" } };
4470
- default:
4471
- return absurd(state);
4472
- }
4404
+ function atLeast(have, want) {
4405
+ return compareDotted(have, want) >= 0;
4473
4406
  }
4474
- function takesConfiguration(state) {
4475
- switch (state.kind) {
4476
- case "Missing":
4477
- case "Clean":
4478
- case "Dirty":
4479
- case "Ahead":
4480
- case "Behind":
4481
- case "Diverged":
4482
- case "Detached":
4483
- return true;
4484
- case "Locked":
4485
- case "WrongRemote":
4486
- case "NotARepo":
4487
- return false;
4488
- default:
4489
- return absurd(state);
4490
- }
4407
+ function versionIn(text) {
4408
+ return /\d+(?:\.\d+)+/.exec(text)?.[0];
4491
4409
  }
4492
- var ABSENT = {
4493
- state: { kind: "Missing" },
4494
- config: {},
4495
- busy: false
4496
- };
4497
- var byPath = (a, b) => foldKey(a.path) < foldKey(b.path) ? -1 : foldKey(a.path) > foldKey(b.path) ? 1 : a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
4498
- function settingsToSet(repo, observed) {
4499
- const diff = {};
4500
- for (const key of Object.keys(repo.settings).sort()) {
4501
- const want = repo.settings[key];
4502
- if (want !== undefined && observed.config[key] !== want)
4503
- diff[key] = want;
4410
+ var IDENT = "(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)";
4411
+ var PART = "(0|[1-9][0-9]*|[xX*])";
4412
+ var PARTIAL = new RegExp(`^v?${PART}(?:\\.${PART}(?:\\.${PART}(?:-(${IDENT}(?:\\.${IDENT})*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)?)?$`);
4413
+ var ver = (major, minor, patch, pre) => ({
4414
+ major,
4415
+ minor,
4416
+ patch,
4417
+ ...pre === undefined ? {} : { pre }
4418
+ });
4419
+ var at = (op, version) => ({ op, version });
4420
+ var NOTHING = [at("<", ver(0, 0, 0, "0"))];
4421
+ // ../formats/src/png.ts
4422
+ var MAX_PIXELS = 2 ** 24;
4423
+ var COLOUR_TYPES = new Map([
4424
+ [0, { samples: 1, depths: [1, 2, 4, 8, 16], name: "greyscale" }],
4425
+ [2, { samples: 3, depths: [8, 16], name: "RGB" }],
4426
+ [3, { samples: 1, depths: [1, 2, 4, 8], name: "palette" }],
4427
+ [4, { samples: 2, depths: [8, 16], name: "greyscale with alpha" }],
4428
+ [6, { samples: 4, depths: [8, 16], name: "RGBA" }]
4429
+ ]);
4430
+ var PRECISION_BITS = 32 - 8 - 2;
4431
+ var ONE = 2 ** PRECISION_BITS;
4432
+ // ../formats/src/ts-literal.ts
4433
+ class Stop2 extends Error {
4434
+ at;
4435
+ expected;
4436
+ constructor(at, expected) {
4437
+ super(`not a literal at ${at}: expected ${expected}`);
4438
+ this.at = at;
4439
+ this.expected = expected;
4504
4440
  }
4505
- return Object.keys(diff).length === 0 ? undefined : diff;
4506
4441
  }
4507
- function plan(desired, observed, options = {}) {
4508
- const actions = [];
4509
- for (const repo of [...desired.repos].sort(byPath)) {
4510
- const seen = Object.hasOwn(observed.repos, repo.path) ? observed.repos[repo.path] ?? ABSENT : ABSENT;
4511
- actions.push(forState(repo, seen.state));
4512
- const settings = takesConfiguration(seen.state) ? settingsToSet(repo, seen) : undefined;
4513
- if (settings !== undefined)
4514
- actions.push({ kind: "ConfigureRepo", target: repo.path, settings });
4515
- }
4516
- for (const wt of [...desired.worktrees].sort(byPath)) {
4517
- const there = Object.hasOwn(observed.worktrees, wt.path) ? observed.worktrees[wt.path] : undefined;
4518
- if (there !== undefined && there.kind !== "Missing") {
4519
- actions.push({
4520
- kind: "Skip",
4521
- target: wt.path,
4522
- why: { kind: "worktree-exists" }
4523
- });
4524
- continue;
4442
+ function parseTsLiteral(text, start = 0) {
4443
+ let i = start;
4444
+ const ws = () => {
4445
+ for (;; ) {
4446
+ while (i < text.length && /\s/.test(text[i] ?? ""))
4447
+ i++;
4448
+ if (!text.startsWith("//", i))
4449
+ return;
4450
+ while (i < text.length && text[i] !== `
4451
+ `)
4452
+ i++;
4525
4453
  }
4526
- const base = Object.hasOwn(observed.repos, wt.repo) ? observed.repos[wt.repo] ?? ABSENT : ABSENT;
4527
- switch (base.state.kind) {
4528
- case "Missing":
4529
- actions.push({
4530
- kind: "Skip",
4531
- target: wt.path,
4532
- why: { kind: "worktree-unneeded" }
4533
- });
4534
- break;
4535
- case "Locked":
4536
- case "WrongRemote":
4537
- case "NotARepo":
4538
- actions.push({
4539
- kind: "Skip",
4540
- target: wt.path,
4541
- why: { kind: "base-unavailable", state: base.state.kind }
4542
- });
4543
- break;
4544
- case "Dirty":
4545
- actions.push({
4546
- kind: "CreateWorktree",
4547
- target: wt.path,
4548
- repo: wt.repo,
4549
- branch: wt.branch
4550
- });
4551
- break;
4552
- case "Clean":
4553
- case "Ahead":
4554
- case "Behind":
4555
- case "Diverged":
4556
- case "Detached":
4557
- actions.push(base.busy ? {
4558
- kind: "CreateWorktree",
4559
- target: wt.path,
4560
- repo: wt.repo,
4561
- branch: wt.branch
4562
- } : {
4563
- kind: "Skip",
4564
- target: wt.path,
4565
- why: { kind: "worktree-unneeded" }
4566
- });
4567
- break;
4568
- default:
4569
- return absurd(base.state);
4454
+ };
4455
+ const fail = (expected) => {
4456
+ throw new Stop2(i, expected);
4457
+ };
4458
+ const str = () => {
4459
+ const m = /^"(?:[^"\\\n]|\\.)*"/.exec(text.slice(i));
4460
+ if (m === null)
4461
+ return fail("a complete string");
4462
+ i += m[0].length;
4463
+ const s = JSON.parse(m[0]);
4464
+ return typeof s === "string" ? s : fail("a string");
4465
+ };
4466
+ const value = () => {
4467
+ ws();
4468
+ const c = text[i];
4469
+ if (c === "{") {
4470
+ i++;
4471
+ const o = {};
4472
+ for (;; ) {
4473
+ ws();
4474
+ if (text[i] === "}") {
4475
+ i++;
4476
+ return o;
4477
+ }
4478
+ let k;
4479
+ if (text[i] === '"')
4480
+ k = str();
4481
+ else {
4482
+ const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(text.slice(i));
4483
+ if (m === null)
4484
+ return fail("a key");
4485
+ k = m[0];
4486
+ i += k.length;
4487
+ }
4488
+ ws();
4489
+ if (text[i] !== ":")
4490
+ fail("a colon");
4491
+ i++;
4492
+ Object.defineProperty(o, k, { value: value(), enumerable: true, writable: true, configurable: true });
4493
+ ws();
4494
+ if (text[i] === ",")
4495
+ i++;
4496
+ else if (text[i] !== "}")
4497
+ fail("a comma or }");
4498
+ }
4570
4499
  }
4500
+ if (c === "[") {
4501
+ i++;
4502
+ const a = [];
4503
+ for (;; ) {
4504
+ ws();
4505
+ if (text[i] === "]") {
4506
+ i++;
4507
+ return a;
4508
+ }
4509
+ a.push(value());
4510
+ ws();
4511
+ if (text[i] === ",")
4512
+ i++;
4513
+ else if (text[i] !== "]")
4514
+ fail("a comma or ]");
4515
+ }
4516
+ }
4517
+ if (c === '"')
4518
+ return str();
4519
+ const m = /^(-?\d+(\.\d+)?([eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
4520
+ if (m === null)
4521
+ return fail("a value");
4522
+ i += m[0].length;
4523
+ const v = JSON.parse(m[0]);
4524
+ return typeof v === "number" || typeof v === "boolean" || v === null ? v : fail("a value");
4525
+ };
4526
+ try {
4527
+ const v = value();
4528
+ return ok({ value: v, end: i });
4529
+ } catch (e) {
4530
+ if (e instanceof Stop2)
4531
+ return err({ kind: "literal", at: e.at, expected: e.expected });
4532
+ throw e;
4571
4533
  }
4572
- const wanted = new Set(desired.files.map((f) => f.path));
4573
- const files = [];
4574
- for (const f of desired.files) {
4575
- const seen = Object.hasOwn(observed.files, f.path) ? observed.files[f.path] ?? {} : {};
4576
- if (seen.onDisk === f.sha256)
4577
- files.push({
4578
- kind: "Skip",
4579
- target: f.path,
4580
- why: { kind: "file-current" }
4581
- });
4582
- else if (seen.onDisk === undefined || seen.onDisk === seen.recorded)
4583
- files.push({ kind: "WriteGenerated", target: f.path, sha256: f.sha256 });
4584
- else
4585
- files.push({
4586
- kind: "Refuse",
4587
- target: f.path,
4588
- why: { kind: "generated-edited" }
4589
- });
4590
- }
4591
- for (const [path, seen] of Object.entries(observed.files)) {
4592
- if (wanted.has(path) || seen.recorded === undefined)
4593
- continue;
4594
- const target = path;
4595
- if (seen.onDisk === undefined)
4596
- files.push({ kind: "Skip", target, why: { kind: "file-absent" } });
4597
- else if (seen.onDisk === seen.recorded)
4598
- files.push({ kind: "RemoveGenerated", target });
4599
- else
4600
- files.push({ kind: "Refuse", target, why: { kind: "generated-edited" } });
4601
- }
4602
- actions.push(...files.sort((a, b) => foldKey(a.target) < foldKey(b.target) ? -1 : foldKey(a.target) > foldKey(b.target) ? 1 : 0));
4603
- if (options.setupApply === true)
4604
- for (const c of desired.hostChanges)
4605
- actions.push({ ...c });
4606
- return { actions };
4607
- }
4608
- async function planDigest(p) {
4609
- return await sha256(JSON.stringify(p.actions));
4610
4534
  }
4611
- function isSettled(p) {
4612
- return p.actions.every((a) => a.kind === "Skip");
4535
+ function exportedLiteral(source, name) {
4536
+ const m = new RegExp(`export const ${name}(?:\\s*:\\s*[A-Za-z_$][\\w$.<>, \\[\\]]*)?\\s*=\\s*`).exec(source);
4537
+ if (m === null)
4538
+ return err({ kind: "literal", at: 0, expected: `export const ${name}` });
4539
+ const r = parseTsLiteral(source, m.index + m[0].length);
4540
+ return r.kind === "ok" ? ok(r.value.value) : r;
4613
4541
  }
4614
-
4615
- // src/findings.ts
4616
- var SEVERITIES2 = ["Informational", "Warning", "Error"];
4617
- function sarifLevel(severity) {
4618
- switch (severity) {
4619
- case "Informational":
4620
- return "note";
4621
- case "Warning":
4622
- return "warning";
4623
- case "Error":
4624
- return "error";
4542
+ // src/types.ts
4543
+ function describeBrandError(e) {
4544
+ switch (e.kind) {
4545
+ case "git-host":
4546
+ return `${JSON.stringify(e.text)} is not a Git host name: ${e.reason}`;
4547
+ case "branch-name":
4548
+ return `${JSON.stringify(e.text)} is not a branch name: ${e.reason}`;
4549
+ case "sha":
4550
+ return `${JSON.stringify(e.text)} is not a commit id (40 or 64 lower-case hexadecimal digits)`;
4551
+ case "version":
4552
+ return `${JSON.stringify(e.text)} is not a pinned version: ${e.reason}`;
4625
4553
  default:
4626
- return absurd(severity);
4554
+ return absurd(e);
4627
4555
  }
4628
4556
  }
4629
- function worst(findings) {
4630
- let top;
4631
- for (const f of findings)
4632
- if (top === undefined || SEVERITIES2.indexOf(f.severity) > SEVERITIES2.indexOf(top))
4633
- top = f.severity;
4634
- return top;
4635
- }
4636
- function exitStatusOf(findings) {
4637
- const top = worst(findings);
4638
- return top === "Warning" || top === "Error" ? "Findings" : "Ok";
4639
- }
4640
- var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
4641
- function dayNumber(day) {
4642
- const m = DAY.exec(day);
4643
- if (m === null)
4644
- return;
4645
- const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
4646
- const ms = Date.UTC(y, mo - 1, d);
4647
- const back = new Date(ms);
4648
- if (back.getUTCFullYear() !== y || back.getUTCMonth() !== mo - 1 || back.getUTCDate() !== d)
4649
- return;
4650
- return Math.round(ms / 86400000);
4651
- }
4652
- function daysBetween(from, to) {
4653
- const a = dayNumber(from);
4654
- const b = dayNumber(to);
4655
- if (a === undefined)
4656
- return err(`${JSON.stringify(from)} is not a day (YYYY-MM-DD)`);
4657
- if (b === undefined)
4658
- return err(`${JSON.stringify(to)} is not a day (YYYY-MM-DD)`);
4659
- return ok(b - a);
4660
- }
4661
- var UNAPPROVED_GRACE_DAYS = 90;
4662
- function unapprovedSeverity(firstSeen, today, graceDays = UNAPPROVED_GRACE_DAYS) {
4663
- const age = daysBetween(firstSeen, today);
4664
- return age.kind === "ok" && age.value > graceDays ? "Warning" : "Informational";
4557
+ function gitHost(text) {
4558
+ const host = text.toLowerCase();
4559
+ if (host === "")
4560
+ return err({ kind: "git-host", text, reason: "it is empty" });
4561
+ if (!/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/.test(host)) {
4562
+ return err({
4563
+ kind: "git-host",
4564
+ text,
4565
+ reason: "it holds a character a host name does not (a port, a path, a scheme, a credential and non-ASCII letters are not part of the name)"
4566
+ });
4567
+ }
4568
+ if (host.includes(".."))
4569
+ return err({ kind: "git-host", text, reason: "it holds an empty label" });
4570
+ return ok(host);
4665
4571
  }
4666
- function firstSeenOf(previous, key, today) {
4667
- const before = Object.hasOwn(previous, key) ? previous[key] : undefined;
4668
- return before !== undefined && dayNumber(before) !== undefined ? before : today;
4572
+ function branchName(text) {
4573
+ const bad = (reason) => err({ kind: "branch-name", text, reason });
4574
+ if (text === "")
4575
+ return bad("it is empty");
4576
+ if (text === "@")
4577
+ return bad("it is `@`");
4578
+ if (text.startsWith("-"))
4579
+ return bad("it starts with `-`");
4580
+ if (text.startsWith("/") || text.endsWith("/") || text.includes("//"))
4581
+ return bad("it has an empty component");
4582
+ if (text.endsWith("."))
4583
+ return bad("it ends in a dot");
4584
+ if (text.includes(".."))
4585
+ return bad("it holds `..`");
4586
+ if (text.includes("@{"))
4587
+ return bad("it holds `@{`");
4588
+ if (/[\u0000- \u007f~^:?*[\\]/.test(text))
4589
+ return bad("it holds a control character, a space or one of ~ ^ : ? * [ \\");
4590
+ for (const part of text.split("/")) {
4591
+ if (part.startsWith("."))
4592
+ return bad("a component starts with a dot");
4593
+ if (part.endsWith(".lock"))
4594
+ return bad("a component ends in `.lock`");
4595
+ }
4596
+ return ok(text);
4669
4597
  }
4670
- function toSarif(findings, tool = "ergonex") {
4671
- const rules = [...new Set(findings.map((f) => f.ruleId))].sort().map((id) => ({ id }));
4672
- return {
4673
- $schema: "https://json.schemastore.org/sarif-2.1.0.json",
4674
- version: "2.1.0",
4675
- runs: [
4676
- {
4677
- tool: {
4678
- driver: {
4679
- name: tool,
4680
- informationUri: "https://intellectual-frontiers.github.io/.github/",
4681
- rules
4682
- }
4683
- },
4684
- results: findings.map((f) => ({
4685
- ruleId: f.ruleId,
4686
- level: sarifLevel(f.severity),
4687
- message: { text: f.message },
4688
- locations: [{ logicalLocations: [{ name: f.subject }] }],
4689
- properties: { firstSeen: f.firstSeen }
4690
- }))
4691
- }
4692
- ]
4693
- };
4598
+ function version(text) {
4599
+ if (text === "latest")
4600
+ return err({ kind: "version", text, reason: "`latest` is not a version" });
4601
+ if (!/^\d/.test(text))
4602
+ return err({
4603
+ kind: "version",
4604
+ text,
4605
+ reason: "it is not major.minor.patch (a range or a tag is not a pin)"
4606
+ });
4607
+ const parsed = parseSemVer(text);
4608
+ if (parsed.kind === "err")
4609
+ return err({
4610
+ kind: "version",
4611
+ text,
4612
+ reason: "it is not major.minor.patch with an optional pre-release or build"
4613
+ });
4614
+ return ok(text);
4694
4615
  }
4695
4616
 
4696
- // src/render.ts
4697
- function describeGenerateError(e) {
4617
+ // src/layout.ts
4618
+ var WORKSPACE_FOLDERS = [".worktrees", ".ergonex", ".git"];
4619
+ function describeLayoutError(e) {
4698
4620
  switch (e.kind) {
4699
- case "bad-path":
4700
- return `${JSON.stringify(e.path)} cannot be the path of a generated file: ${e.reason}`;
4701
- case "not-auto":
4702
- return `${e.path} is a generated file whose name does not carry .auto. (only a Git hook in .ergonex/hooks/ may lack it)`;
4703
- case "collision":
4704
- return `${e.path} is the same path as ${e.other} after Unicode normalization and case folding; both are refused`;
4705
- case "inside-repository":
4706
- return `${e.path} is inside the working tree of ${e.repository}; a generated file is never written into a repository`;
4707
- case "bad-data":
4708
- return `${e.what}: ${e.reason}`;
4621
+ case "portable":
4622
+ return describePortableError(e.cause);
4623
+ case "host":
4624
+ return describeBrandError(e.cause);
4625
+ case "workspace-folder":
4626
+ return `${JSON.stringify(e.segment)} is named like a folder of the workspace (${WORKSPACE_FOLDERS.join(", ")}), which a remote may not be`;
4627
+ case "too-deep":
4628
+ return `${e.path.join("/")} has ${e.path.length} segments, and ${e.manager} offers no nested groups: at most ${e.limit} (an owner and a repository)`;
4629
+ case "too-shallow":
4630
+ return `${e.path.join("/")} is not an owner and a repository`;
4631
+ case "not-in-layout":
4632
+ return `${e.path} is not a repository path of the workspace`;
4709
4633
  default:
4710
4634
  return absurd(e);
4711
4635
  }
4712
4636
  }
4713
- var HOOKS_FOLDER = ".ergonex/hooks";
4714
- function headerText(generator) {
4715
- return `Generated by ${generator}. Do not edit by hand: change workspace.ts and run \`ergonex render\`.`;
4716
- }
4717
- function normalizeText(text) {
4718
- const lf = text.replace(/^/, "").replaceAll(`\r
4719
- `, `
4720
- `).replaceAll("\r", `
4721
- `);
4722
- return `${lf.replace(/\n+$/, "")}
4723
- `;
4724
- }
4725
- function isAutoName(name) {
4726
- return name.includes(".auto.") || name.endsWith(".auto");
4637
+ var portable = (cause) => ({
4638
+ kind: "portable",
4639
+ cause
4640
+ });
4641
+ function notWorkspaceFolder(name) {
4642
+ return WORKSPACE_FOLDERS.some((f) => foldKey(f) === foldKey(name)) ? err({ kind: "workspace-folder", segment: name }) : ok(name);
4727
4643
  }
4728
- function generatedPath(path) {
4729
- const made = repoPath(path.split("/"));
4730
- if (made.kind === "err")
4731
- return err({
4732
- kind: "bad-path",
4733
- path,
4734
- reason: describePortableError(made.error)
4735
- });
4736
- return made;
4644
+ function gitHostOf(ref) {
4645
+ const h = gitHost(ref.host);
4646
+ if (h.kind === "err")
4647
+ return err({ kind: "host", cause: h.error });
4648
+ const free = notWorkspaceFolder(h.value);
4649
+ if (free.kind === "err")
4650
+ return free;
4651
+ const s = segment(h.value);
4652
+ return s.kind === "err" ? err(portable(s.error)) : h;
4737
4653
  }
4738
- var noBom = (text) => text.replace(/^\uFEFF/, "");
4739
- function contentOf(body, generator) {
4740
- const header = headerText(generator);
4741
- switch (body.format) {
4742
- case "json":
4743
- return normalizeText(JSON.stringify({ _generated: header, ...body.value }, null, 2));
4744
- case "markdown":
4745
- return normalizeText(`<!-- ${header} -->
4746
-
4747
- ${noBom(body.text)}`);
4748
- case "yaml":
4749
- case "gitconfig":
4750
- case "envrc":
4751
- return normalizeText(`# ${header}
4752
-
4753
- ${noBom(body.text)}`);
4754
- case "sh": {
4755
- const text = noBom(body.text);
4756
- const m = /^(#![^\n]*)\n/.exec(text);
4757
- return m === null ? normalizeText(`# ${header}
4758
- ${text}`) : normalizeText(`${m[1]}
4759
- # ${header}
4760
- ${text.slice(m[0].length)}`);
4761
- }
4762
- default:
4763
- return absurd(body);
4654
+ function segmentsOfRef(ref) {
4655
+ if (ref.path.length < 2)
4656
+ return err({ kind: "too-shallow", path: ref.path });
4657
+ const limit = maxDepth(ref.kind);
4658
+ if (ref.path.length > limit)
4659
+ return err({ kind: "too-deep", manager: ref.kind, path: ref.path, limit });
4660
+ const host = gitHostOf(ref);
4661
+ if (host.kind === "err")
4662
+ return host;
4663
+ for (const s of ref.path) {
4664
+ const free = notWorkspaceFolder(s);
4665
+ if (free.kind === "err")
4666
+ return free;
4764
4667
  }
4668
+ return ok([host.value, ...ref.path]);
4765
4669
  }
4766
- function generated(path, body, options) {
4767
- const made = generatedPath(path);
4768
- if (made.kind === "err")
4769
- return made;
4770
- const name = made.value.split("/").at(-1) ?? "";
4771
- const isHook = made.value.startsWith(`${HOOKS_FOLDER}/`) && made.value.split("/").length === 3;
4772
- if (!isAutoName(name) && !isHook)
4773
- return err({ kind: "not-auto", path });
4774
- return ok({
4775
- path: made.value,
4776
- content: contentOf(body, options.generator),
4777
- mode: options.mode ?? "0644",
4778
- generator: options.generator
4779
- });
4670
+ function repoPathOf(ref) {
4671
+ const segments = segmentsOfRef(ref);
4672
+ if (segments.kind === "err")
4673
+ return segments;
4674
+ const p = repoPath(segments.value);
4675
+ return p.kind === "err" ? err(portable(p.error)) : p;
4780
4676
  }
4781
- function fileDigest(file) {
4782
- return sha256(file.content);
4677
+ function slugOf(text) {
4678
+ const replaced = text.normalize("NFC").replace(/[\u0000-\u001f\u007f<>:"/\\|?*~^[\]\s]+/g, "-");
4679
+ let slug = replaced.replace(/-{2,}/g, "-").replace(/[-. ]+$/, "").replace(/^[-.]+/, "");
4680
+ if (isDeviceName(slug)) {
4681
+ const dot = slug.indexOf(".");
4682
+ slug = dot < 0 ? `${slug}_` : `${slug.slice(0, dot)}_${slug.slice(dot)}`;
4683
+ }
4684
+ return segment(slug);
4783
4685
  }
4784
- function checkFiles(files, repositories) {
4785
- const errors = [];
4786
- for (const c of collisions(files.map((f) => ({ id: f.path, path: f.path })))) {
4787
- for (const m of c.members) {
4788
- const other = c.members.find((o) => o !== m);
4789
- errors.push({
4790
- kind: "collision",
4791
- path: m.path,
4792
- other: other?.path ?? m.path
4793
- });
4794
- }
4795
- }
4796
- for (const f of files) {
4797
- const key = foldKey(f.path);
4798
- const inside = repositories.find((r) => key.startsWith(`${foldKey(r)}/`));
4799
- if (inside !== undefined)
4800
- errors.push({
4801
- kind: "inside-repository",
4802
- path: f.path,
4803
- repository: inside
4804
- });
4805
- }
4806
- if (errors.length > 0)
4807
- return err(errors);
4808
- return ok([...files].sort((a, b) => foldKey(a.path) < foldKey(b.path) ? -1 : foldKey(a.path) > foldKey(b.path) ? 1 : 0));
4686
+ function worktreePathOf(ref, branch) {
4687
+ const segments = segmentsOfRef(ref);
4688
+ if (segments.kind === "err")
4689
+ return segments;
4690
+ const slug = slugOf(branch);
4691
+ if (slug.kind === "err")
4692
+ return err(portable(slug.error));
4693
+ const p = repoPath([".worktrees", ...segments.value, slug.value]);
4694
+ return p.kind === "err" ? err(portable(p.error)) : p;
4809
4695
  }
4810
-
4811
- // src/state-record.ts
4812
- var ERGONEX_VERSION = "0.3.1";
4813
- var STATE_RECORD_PATH = ".ergonex/state.auto.json";
4814
- var EMPTY_RECORD = {
4815
- ergonex: ERGONEX_VERSION,
4816
- files: {},
4817
- firstSeen: {}
4818
- };
4819
- var hash = (input, path = "$") => {
4820
- const s = typeof input === "string" ? sha256Of(input) : undefined;
4821
- return s === undefined ? err({
4822
- kind: "decode",
4823
- path,
4824
- expected: "a SHA-256 (64 hexadecimal digits)",
4825
- found: typeof input
4826
- }) : ok(s);
4827
- };
4828
- var day = (input, path = "$") => typeof input === "string" && dayNumber(input) !== undefined ? ok(input) : err({
4829
- kind: "decode",
4830
- path,
4831
- expected: "a day (YYYY-MM-DD)",
4832
- found: typeof input
4833
- });
4834
- var shape = object({
4835
- ergonex: string,
4836
- files: record(object({ sha256: hash, generator: string })),
4837
- firstSeen: record(day)
4838
- }, { plan: hash });
4839
- function decodeStateRecord(text) {
4840
- const r = json(text, shape);
4841
- return r.kind === "ok" ? ok(r.value) : err(formatDecodeError(r.error));
4696
+ function homeOf2(facts) {
4697
+ const nonEmpty = (s) => s === undefined || s.trim() === "" ? undefined : s;
4698
+ const explicit = nonEmpty(facts.override) ?? nonEmpty(facts.workspacesHome);
4699
+ if (explicit !== undefined)
4700
+ return ok(explicit);
4701
+ const home = nonEmpty(facts.home);
4702
+ if (home === undefined)
4703
+ return err({ kind: "no-home" });
4704
+ return ok(`${home.replace(/[\\/]+$/, "")}${facts.windows ? "\\" : "/"}workspaces`);
4842
4705
  }
4843
- function encodeStateRecord(r) {
4844
- const sorted = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
4845
- const value = {
4846
- _generated: headerText("ergonex state"),
4847
- ergonex: r.ergonex,
4848
- ...r.plan === undefined ? {} : { plan: r.plan },
4849
- files: sorted(r.files),
4850
- firstSeen: sorted(r.firstSeen)
4851
- };
4852
- return `${JSON.stringify(value, null, 2)}
4853
- `;
4706
+ function worktreeWanted(facts) {
4707
+ return facts.uncommittedWork || facts.otherWorker;
4854
4708
  }
4855
- function withFile(r, file, digest) {
4856
- return {
4857
- ...r,
4858
- files: {
4859
- ...r.files,
4860
- [file.path]: { sha256: digest, generator: file.generator }
4861
- }
4862
- };
4709
+
4710
+ // src/modules/name.ts
4711
+ var MAX_MODULE_NAME = 32;
4712
+ function describeNameError(e) {
4713
+ switch (e.kind) {
4714
+ case "empty":
4715
+ return "a module name is not empty";
4716
+ case "too-long":
4717
+ return `a module name has at most ${MAX_MODULE_NAME} characters, not ${e.length}`;
4718
+ case "bad-start":
4719
+ return `${JSON.stringify(e.text)} does not begin with a lower-case letter, as a module name must`;
4720
+ case "bad-character":
4721
+ return `${JSON.stringify(e.text)} holds ${JSON.stringify(e.character)}, and a module name is lower-case letters, digits and hyphens`;
4722
+ default:
4723
+ return absurd(e);
4724
+ }
4863
4725
  }
4864
- function withoutFile(r, path) {
4865
- return {
4866
- ...r,
4867
- files: Object.fromEntries(Object.entries(r.files).filter(([p]) => p !== path))
4868
- };
4726
+ function moduleName(text) {
4727
+ if (text === "")
4728
+ return err({ kind: "empty" });
4729
+ if (text.length > MAX_MODULE_NAME)
4730
+ return err({ kind: "too-long", length: text.length });
4731
+ if (!/^[a-z]/.test(text))
4732
+ return err({ kind: "bad-start", text });
4733
+ const bad = /[^a-z0-9-]/u.exec(text);
4734
+ if (bad !== null)
4735
+ return err({ kind: "bad-character", text, character: bad[0] });
4736
+ return ok(text);
4869
4737
  }
4870
- function verifyFindings(facts, today) {
4871
- const out = [];
4872
- for (const f of facts) {
4873
- const at = (ruleId, severity, message) => void out.push({
4874
- ruleId,
4875
- severity,
4876
- message,
4877
- subject: f.path,
4878
- firstSeen: today
4879
- });
4880
- if (f.recorded !== undefined && f.onDisk === undefined) {
4881
- at("ergonex/generated-missing", "Warning", `${f.path} is recorded as written and is not there; run \`ergonex render\` to write it again`);
4882
- } else if (f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded) {
4883
- at("ergonex/generated-edited", "Error", `${f.path} was edited by hand (its bytes are not the ones recorded); \`ergonex render --force\` replaces it`);
4884
- } else if (f.recorded === undefined && f.onDisk !== undefined) {
4885
- at("ergonex/generated-unrecorded", "Warning", `${f.path} is a generated file the state record does not hold; run \`ergonex render\` to record it, or remove it`);
4886
- }
4887
- const edited = f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded;
4888
- const missing = f.recorded !== undefined && f.onDisk === undefined;
4889
- if (f.wanted !== undefined && f.onDisk !== f.wanted && !edited && !missing) {
4890
- at("ergonex/generated-drift", "Warning", f.onDisk === undefined ? `${f.path} is not written yet; run \`ergonex render\`` : `${f.path} would be written differently by the templates now; run \`ergonex render\``);
4891
- }
4892
- }
4893
- return out;
4738
+ function nearestNames(word, names) {
4739
+ return names.map((n) => ({ n, d: editDistance(word, n) })).filter((x) => x.d <= 2).sort((a, b) => a.d - b.d || (a.n < b.n ? -1 : a.n > b.n ? 1 : 0)).slice(0, 3).map((x) => x.n);
4894
4740
  }
4895
4741
 
4896
- // src/platform/r-errors.ts
4897
- var NotFound2 = errors.NotFound;
4898
-
4899
- // src/host/observe.ts
4900
- var ENV = {
4901
- GIT_TERMINAL_PROMPT: "0",
4902
- GIT_PAGER: "cat",
4903
- PAGER: "cat",
4904
- GIT_OPTIONAL_LOCKS: "0",
4905
- LC_ALL: "C",
4906
- LANGUAGE: "C"
4907
- };
4908
- async function git(folder, args, options) {
4909
- const program = options.program ?? "git";
4910
- try {
4911
- const r = await output2([program, "--no-pager", "-C", folder, ...args], {
4912
- env: { ...ENV, ...options.env }
4913
- });
4914
- return ok({
4915
- code: r.code,
4916
- stdout: new TextDecoder().decode(r.stdout).trim()
4917
- });
4918
- } catch (e) {
4919
- if (e instanceof NotFound2)
4920
- return err({ kind: "git-missing", program });
4921
- throw e;
4922
- }
4923
- }
4924
- function hasLockFile(gitDir) {
4925
- const walk = (dir, depth) => {
4926
- let entries;
4927
- try {
4928
- entries = readDirSync2(dir);
4929
- } catch {
4930
- return false;
4931
- }
4932
- for (const e of entries) {
4933
- if (e.isFile && e.name.endsWith(".lock"))
4934
- return true;
4935
- if (e.isDirectory && depth > 0 && walk(join6(dir, e.name), depth - 1))
4936
- return true;
4937
- }
4742
+ // src/tools/catalog.ts
4743
+ var PROBED_TOOLS = ["git", "bun", "node"];
4744
+ var artifactShape = object({
4745
+ os: literal("linux", "macos", "windows"),
4746
+ arch: literal("x64", "arm64"),
4747
+ url: string,
4748
+ sha256: string
4749
+ }, { kind: literal("file", "tar.gz", "zip"), bin: string });
4750
+ var toolShape = object({ name: string, version: string, artifacts: array(artifactShape) }, { provides: array(string) });
4751
+ var catalogShape = array(toolShape);
4752
+ var NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
4753
+ function safeInnerPath(path) {
4754
+ if (path === "" || path.startsWith("/") || path.includes("\\") || /^[A-Za-z]:/.test(path))
4938
4755
  return false;
4939
- };
4940
- const top = readDirSync2(gitDir).some((e) => e.isFile && e.name.endsWith(".lock"));
4941
- return top || existsSync2(join6(gitDir, "refs")) && walk(join6(gitDir, "refs"), 6);
4756
+ return path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
4942
4757
  }
4943
- async function observeFacts(folder, options = {}) {
4944
- if (!existsSync2(folder))
4945
- return ok({ kind: "absent" });
4946
- if (!lstatSync3(folder).isDirectory)
4947
- return ok({ kind: "not-a-repository" });
4948
- if (readDirSync2(folder).length === 0)
4949
- return ok({ kind: "absent" });
4950
- if (!existsSync2(join6(folder, ".git")))
4951
- return ok({ kind: "not-a-repository" });
4952
- const dir = await git(folder, ["rev-parse", "--absolute-git-dir"], options);
4953
- if (dir.kind === "err")
4954
- return dir;
4955
- if (dir.value.code !== 0 || dir.value.stdout === "")
4956
- return ok({ kind: "not-a-repository" });
4957
- const remote = await git(folder, ["config", "--get", "remote.origin.url"], options);
4958
- if (remote.kind === "err")
4959
- return remote;
4960
- const originUrl = remote.value.code === 0 && remote.value.stdout !== "" ? remote.value.stdout : undefined;
4961
- if (options.fetch === true && originUrl !== undefined) {
4962
- const f = await git(folder, ["fetch", "--quiet", "origin"], options);
4963
- if (f.kind === "err")
4964
- return f;
4758
+ function urlProblem(text, loopbackHttp = false) {
4759
+ let url;
4760
+ try {
4761
+ url = new URL(text);
4762
+ } catch {
4763
+ return "it is not a URL";
4965
4764
  }
4966
- const head = await git(folder, ["symbolic-ref", "-q", "HEAD"], options);
4967
- if (head.kind === "err")
4968
- return head;
4969
- const detached = head.value.code !== 0;
4970
- const status = await git(folder, ["status", "--porcelain=v1", "-z", "--untracked-files=normal", "--ignore-submodules=none"], options);
4971
- if (status.kind === "err")
4972
- return status;
4973
- const dirty = status.value.code === 0 && status.value.stdout !== "";
4974
- let ahead = 0;
4975
- let behind = 0;
4976
- if (!detached) {
4977
- const counts = await git(folder, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], options);
4978
- if (counts.kind === "err")
4979
- return counts;
4980
- const m = counts.value.code === 0 ? /^(\d+)\s+(\d+)$/.exec(counts.value.stdout) : null;
4981
- if (m !== null) {
4982
- ahead = Number(m[1]);
4983
- behind = Number(m[2]);
4984
- } else {
4985
- const own = await git(folder, ["rev-list", "--count", "HEAD", "--not", "--remotes"], options);
4986
- if (own.kind === "err")
4987
- return own;
4988
- ahead = own.value.code === 0 && /^\d+$/.test(own.value.stdout) ? Number(own.value.stdout) : 0;
4765
+ const loopback = loopbackHttp && url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]");
4766
+ if (url.protocol !== "https:" && !loopback)
4767
+ return "a pinned artifact is fetched over https only";
4768
+ if (url.username !== "" || url.password !== "")
4769
+ return "it holds a credential";
4770
+ if (/[?&](key|api_key|apikey|access_token|token|password|passwd|signature|sig)=/i.test(url.search))
4771
+ return "its query holds a credential";
4772
+ if (url.pathname.split("/").some((p) => p.toLowerCase() === "latest"))
4773
+ return "it names `latest`, which is not a version";
4774
+ return;
4775
+ }
4776
+ function decodeCatalog(input, loopbackHttp = false) {
4777
+ const shaped = catalogShape(input, "$.tools");
4778
+ if (shaped.kind === "err") {
4779
+ return err([
4780
+ {
4781
+ rule: "ergonex/catalog-shape",
4782
+ path: shaped.error.path,
4783
+ message: `the tool catalog is not what is expected: ${formatDecodeError(shaped.error)}`
4784
+ }
4785
+ ]);
4786
+ }
4787
+ const issues = [];
4788
+ const tools = [];
4789
+ const seenTool = new Set;
4790
+ for (const [i, raw] of shaped.value.entries()) {
4791
+ const at = `$.tools[${i}]`;
4792
+ const bad = (path, message) => issues.push({ rule: "ergonex/catalog-tool", path, message });
4793
+ if (!NAME.test(raw.name))
4794
+ bad(`${at}.name`, `${JSON.stringify(raw.name)} is not a tool name (lower-case letters, digits, \`.\`, \`_\` and \`-\`)`);
4795
+ else if (PROBED_TOOLS.includes(raw.name))
4796
+ bad(`${at}.name`, `${raw.name} is verified by a probe of its version and never installed, so it is not a tool of the catalog (0002-workspace-model FR-038)`);
4797
+ else if (seenTool.has(raw.name))
4798
+ bad(`${at}.name`, `${raw.name} is in the catalog twice; one pinned version each`);
4799
+ seenTool.add(raw.name);
4800
+ const v = version(raw.version);
4801
+ if (v.kind === "err")
4802
+ bad(`${at}.version`, describeBrandError(v.error));
4803
+ const artifacts = [];
4804
+ const seen = new Set;
4805
+ for (const [j, a] of raw.artifacts.entries()) {
4806
+ const where = `${at}.artifacts[${j}]`;
4807
+ const problem = urlProblem(a.url, loopbackHttp);
4808
+ if (problem !== undefined)
4809
+ bad(`${where}.url`, `the URL is not a pin: ${problem}`);
4810
+ const sum = sha256Of(a.sha256);
4811
+ if (sum === undefined)
4812
+ bad(`${where}.sha256`, "the hash is not a SHA-256 (64 lower-case hexadecimal digits)");
4813
+ const kind = a.kind ?? "file";
4814
+ const bin = a.bin ?? (kind === "file" ? a.url.split("/").pop() ?? "" : "");
4815
+ if (!safeInnerPath(bin))
4816
+ bad(`${where}.bin`, `${JSON.stringify(bin)} is not a safe path to the executable (name it, relative, with \`/\` between parts and no \`..\`)`);
4817
+ const key = `${a.os}/${a.arch}`;
4818
+ if (seen.has(key))
4819
+ bad(`${where}`, `${raw.name} has two artifacts for ${key}`);
4820
+ seen.add(key);
4821
+ if (problem === undefined && sum !== undefined && safeInnerPath(bin))
4822
+ artifacts.push({
4823
+ os: a.os,
4824
+ arch: a.arch,
4825
+ url: a.url,
4826
+ sha256: sum,
4827
+ kind,
4828
+ bin
4829
+ });
4989
4830
  }
4831
+ if (v.kind === "ok")
4832
+ tools.push({
4833
+ name: raw.name,
4834
+ version: v.value,
4835
+ provides: raw.provides ?? [raw.name],
4836
+ artifacts
4837
+ });
4990
4838
  }
4991
- return ok({
4992
- kind: "repository",
4993
- remote: originUrl,
4994
- lockFile: hasLockFile(dir.value.stdout),
4995
- detached,
4996
- dirty,
4997
- ahead,
4998
- behind
4999
- });
5000
- }
5001
- async function observe(folder, expected, options = {}) {
5002
- const facts = await observeFacts(folder, options);
5003
- return facts.kind === "err" ? facts : ok(classify(facts.value, expected));
5004
- }
5005
-
5006
- // src/host/worktrees.ts
5007
- var ENV2 = {
5008
- GIT_TERMINAL_PROMPT: "0",
5009
- GIT_PAGER: "cat",
5010
- PAGER: "cat",
5011
- LC_ALL: "C",
5012
- LANGUAGE: "C"
5013
- };
5014
- async function git2(folder, args) {
5015
- const r = await run2(["git", "-C", folder, ...args], { env: ENV2 });
5016
- return r.success ? ok(r.stdout.trim()) : err((r.stderr.split(`
5017
- `).find((l) => l.trim() !== "") ?? "git failed").trim());
4839
+ return issues.length > 0 ? err(issues) : ok({ tools });
5018
4840
  }
5019
- async function listWorktrees(folder) {
5020
- const r = await git2(folder, ["worktree", "list", "--porcelain"]);
5021
- if (r.kind === "err")
5022
- return r;
5023
- const out = [];
5024
- for (const block of r.value.split(/\n\s*\n/)) {
5025
- const lines = block.split(`
5026
- `);
5027
- const path = lines.find((l) => l.startsWith("worktree "))?.slice("worktree ".length);
5028
- if (path === undefined)
5029
- continue;
5030
- const branch = lines.find((l) => l.startsWith("branch "))?.slice("branch ".length).replace(/^refs\/heads\//, "");
5031
- out.push({ path, branch, main: out.length === 0 });
5032
- }
5033
- return ok(out);
4841
+ function toolNamed(catalog, name) {
4842
+ return catalog.tools.find((t) => t.name === name);
5034
4843
  }
5035
- async function localWork(worktree) {
5036
- const status = await git2(worktree, ["status", "--porcelain=v1", "--untracked-files=normal"]);
5037
- if (status.kind === "err")
5038
- return status;
5039
- const own = await git2(worktree, ["rev-list", "--count", "HEAD", "--not", "--remotes"]);
5040
- if (own.kind === "err")
5041
- return own;
5042
- return ok({ dirty: status.value !== "", unpushed: Number(own.value) || 0 });
4844
+ function artifactFor(tool, os, arch) {
4845
+ return tool.artifacts.find((a) => a.os === os && a.arch === arch);
5043
4846
  }
5044
- async function createWorktree(folder, target, branch) {
5045
- if (existsSync2(target))
5046
- return err(`${target} exists`);
5047
- await mkdir3(dirname4(target), { recursive: true });
5048
- const exists = await git2(folder, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]);
5049
- const r = await git2(folder, exists.kind === "ok" ? ["worktree", "add", target, branch] : ["worktree", "add", "-b", branch, target]);
5050
- return r.kind === "ok" ? ok(`worktree for ${branch}`) : r;
4847
+ function installDirOf(tool) {
4848
+ return `${tool.name}/${tool.version}`;
5051
4849
  }
5052
- async function removeWorktree(folder, worktree) {
5053
- const work = await localWork(worktree);
5054
- if (work.kind === "err")
5055
- return work;
5056
- if (work.value.dirty)
5057
- return err("it has uncommitted changes");
5058
- if (work.value.unpushed > 0)
5059
- return err(`it has ${work.value.unpushed} commit${work.value.unpushed === 1 ? "" : "s"} that are on no remote`);
5060
- const r = await git2(folder, ["worktree", "remove", worktree]);
5061
- return r.kind === "ok" ? ok("removed") : r;
4850
+ function providedBy(catalog, command) {
4851
+ return catalog.tools.find((t) => t.name === command || t.provides.includes(command));
5062
4852
  }
5063
4853
 
5064
- // src/desired.ts
5065
- function settingsOf(manifest, facts) {
5066
- const settings = {
5067
- "core.hooksPath": `${facts.homePosix.replace(/\/+$/, "")}/.ergonex/hooks`
4854
+ // src/policy.ts
4855
+ function policyOf(input = {}) {
4856
+ const regulatedDomain = input.regulatedDomain ?? [];
4857
+ return {
4858
+ requiresSignedCommits: regulatedDomain.length > 0 || input.requiresSignedCommits === true,
4859
+ regulatedDomain,
4860
+ unapprovedGraceDays: input.unapprovedGraceDays ?? UNAPPROVED_GRACE_DAYS,
4861
+ allowedGitHost: (input.allowedGitHost ?? []).map((h) => h.toLowerCase())
5068
4862
  };
5069
- if (manifest.policy.requiresSignedCommits) {
5070
- settings["commit.gpgsign"] = "true";
5071
- if (manifest.signing !== undefined) {
5072
- settings["gpg.format"] = manifest.signing.format;
5073
- if (manifest.signing.key !== undefined)
5074
- settings["user.signingkey"] = manifest.signing.key;
5075
- }
5076
- }
5077
- if (manifest.identity !== undefined) {
5078
- settings["user.name"] = manifest.identity.name;
5079
- settings["user.email"] = manifest.identity.email;
5080
- }
5081
- if (facts.windows)
5082
- settings["core.longpaths"] = "true";
5083
- return settings;
5084
- }
5085
- async function desiredOf(manifest, files, facts) {
5086
- const settings = settingsOf(manifest, facts);
5087
- const repos = manifest.repositories.map((r) => ({
5088
- path: r.path,
5089
- ref: r.ref,
5090
- cloneUrl: r.cloneUrl,
5091
- branch: r.branch,
5092
- settings
5093
- }));
5094
- const worktrees = manifest.repositories.flatMap((r) => r.worktrees.map((w) => ({ path: w.path, repo: r.path, branch: w.branch })));
5095
- const desiredFiles = [];
5096
- for (const f of files)
5097
- desiredFiles.push({ path: f.path, sha256: await fileDigest(f) });
5098
- return { repos, worktrees, files: desiredFiles, hostChanges: [] };
5099
4863
  }
5100
-
5101
- // src/places.ts
5102
- var APP = ".ergonex";
5103
- function movedKind(rest) {
5104
- if (rest === "state.auto.json" || rest === "ergonex.lock" || rest === "evidence" || rest.startsWith("evidence/"))
5105
- return "state";
5106
- if (rest === "tools" || rest.startsWith("tools/"))
5107
- return "tools";
5108
- return;
4864
+ function isRegulated(policy) {
4865
+ return policy.regulatedDomain.length > 0;
5109
4866
  }
5110
- function movedPath(places, path) {
5111
- if (path !== APP && !path.startsWith(`${APP}/`))
4867
+ function unsignedCommitSeverity(policy, signedAndVerified) {
4868
+ if (signedAndVerified)
5112
4869
  return;
5113
- const rest = path === APP ? "" : path.slice(APP.length + 1);
5114
- const sep = places.os === "windows" ? "\\" : "/";
5115
- const under = (base, parts) => [base.replace(/[\\/]+$/, ""), ...parts].join(sep);
5116
- const kind = movedKind(rest);
5117
- if (kind === "state")
5118
- return under(places.state, rest.split("/"));
5119
- if (kind === "tools")
5120
- return under(places.tools, rest.split("/").slice(1));
5121
- return;
4870
+ return isRegulated(policy) ? "Error" : "Warning";
5122
4871
  }
5123
-
5124
- // src/types.ts
5125
- function describeBrandError(e) {
5126
- switch (e.kind) {
5127
- case "git-host":
5128
- return `${JSON.stringify(e.text)} is not a Git host name: ${e.reason}`;
5129
- case "branch-name":
5130
- return `${JSON.stringify(e.text)} is not a branch name: ${e.reason}`;
5131
- case "sha":
5132
- return `${JSON.stringify(e.text)} is not a commit id (40 or 64 lower-case hexadecimal digits)`;
5133
- case "version":
5134
- return `${JSON.stringify(e.text)} is not a pinned version: ${e.reason}`;
5135
- default:
5136
- return absurd(e);
5137
- }
4872
+ function hookFailsWhenUnableToCheck(policy) {
4873
+ return isRegulated(policy);
5138
4874
  }
5139
- function gitHost(text) {
5140
- const host = text.toLowerCase();
5141
- if (host === "")
5142
- return err({ kind: "git-host", text, reason: "it is empty" });
5143
- if (!/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/.test(host)) {
5144
- return err({
5145
- kind: "git-host",
5146
- text,
5147
- reason: "it holds a character a host name does not (a port, a path, a scheme, a credential and non-ASCII letters are not part of the name)"
5148
- });
5149
- }
5150
- if (host.includes(".."))
5151
- return err({ kind: "git-host", text, reason: "it holds an empty label" });
5152
- return ok(host);
5153
- }
5154
- function branchName(text) {
5155
- const bad = (reason) => err({ kind: "branch-name", text, reason });
5156
- if (text === "")
5157
- return bad("it is empty");
5158
- if (text === "@")
5159
- return bad("it is `@`");
5160
- if (text.startsWith("-"))
5161
- return bad("it starts with `-`");
5162
- if (text.startsWith("/") || text.endsWith("/") || text.includes("//"))
5163
- return bad("it has an empty component");
5164
- if (text.endsWith("."))
5165
- return bad("it ends in a dot");
5166
- if (text.includes(".."))
5167
- return bad("it holds `..`");
5168
- if (text.includes("@{"))
5169
- return bad("it holds `@{`");
5170
- if (/[\u0000- \u007f~^:?*[\\]/.test(text))
5171
- return bad("it holds a control character, a space or one of ~ ^ : ? * [ \\");
5172
- for (const part of text.split("/")) {
5173
- if (part.startsWith("."))
5174
- return bad("a component starts with a dot");
5175
- if (part.endsWith(".lock"))
5176
- return bad("a component ends in `.lock`");
5177
- }
5178
- return ok(text);
5179
- }
5180
- function version(text) {
5181
- if (text === "latest")
5182
- return err({ kind: "version", text, reason: "`latest` is not a version" });
5183
- if (!/^\d/.test(text))
5184
- return err({
5185
- kind: "version",
5186
- text,
5187
- reason: "it is not major.minor.patch (a range or a tag is not a pin)"
5188
- });
5189
- const parsed = parseSemVer(text);
5190
- if (parsed.kind === "err")
5191
- return err({
5192
- kind: "version",
5193
- text,
5194
- reason: "it is not major.minor.patch with an optional pre-release or build"
5195
- });
5196
- return ok(text);
4875
+ function hostAllowed(policy, host) {
4876
+ return policy.allowedGitHost.length === 0 || policy.allowedGitHost.includes(host.toLowerCase());
5197
4877
  }
5198
4878
 
5199
- // src/layout.ts
5200
- var WORKSPACE_FOLDERS = [".worktrees", ".ergonex", ".git"];
5201
- function describeLayoutError(e) {
5202
- switch (e.kind) {
5203
- case "portable":
5204
- return describePortableError(e.cause);
5205
- case "host":
5206
- return describeBrandError(e.cause);
5207
- case "workspace-folder":
5208
- return `${JSON.stringify(e.segment)} is named like a folder of the workspace (${WORKSPACE_FOLDERS.join(", ")}), which a remote may not be`;
5209
- case "too-deep":
5210
- return `${e.path.join("/")} has ${e.path.length} segments, and ${e.manager} offers no nested groups: at most ${e.limit} (an owner and a repository)`;
5211
- case "too-shallow":
5212
- return `${e.path.join("/")} is not an owner and a repository`;
5213
- case "not-in-layout":
5214
- return `${e.path} is not a repository path of the workspace`;
5215
- default:
5216
- return absurd(e);
5217
- }
5218
- }
5219
- var portable = (cause) => ({
5220
- kind: "portable",
5221
- cause
4879
+ // src/manifest.ts
4880
+ var repositoryShape = object({ remote: string }, { branch: string, group: string, worktrees: array(string) });
4881
+ var manifestShape = object({ repositories: array(repositoryShape) }, {
4882
+ gitlabHosts: array(string),
4883
+ policy: object({}, {
4884
+ requiresSignedCommits: boolean,
4885
+ regulatedDomain: array(string),
4886
+ unapprovedGraceDays: integer,
4887
+ allowedGitHost: array(string)
4888
+ }),
4889
+ identity: object({ name: string, email: string }),
4890
+ signing: object({ format: string }, { key: string }),
4891
+ direnv: boolean,
4892
+ tools: unknownValue,
4893
+ modules: array(object({ name: string, program: string }, { sha256: string, summary: string }))
5222
4894
  });
5223
- function notWorkspaceFolder(name) {
5224
- return WORKSPACE_FOLDERS.some((f) => foldKey(f) === foldKey(name)) ? err({ kind: "workspace-folder", segment: name }) : ok(name);
5225
- }
5226
- function gitHostOf(ref) {
5227
- const h = gitHost(ref.host);
5228
- if (h.kind === "err")
5229
- return err({ kind: "host", cause: h.error });
5230
- const free = notWorkspaceFolder(h.value);
5231
- if (free.kind === "err")
5232
- return free;
5233
- const s = segment(h.value);
5234
- return s.kind === "err" ? err(portable(s.error)) : h;
5235
- }
5236
- function segmentsOfRef(ref) {
5237
- if (ref.path.length < 2)
5238
- return err({ kind: "too-shallow", path: ref.path });
5239
- const limit = maxDepth(ref.kind);
5240
- if (ref.path.length > limit)
5241
- return err({ kind: "too-deep", manager: ref.kind, path: ref.path, limit });
5242
- const host = gitHostOf(ref);
5243
- if (host.kind === "err")
5244
- return host;
5245
- for (const s of ref.path) {
5246
- const free = notWorkspaceFolder(s);
5247
- if (free.kind === "err")
5248
- return free;
5249
- }
5250
- return ok([host.value, ...ref.path]);
5251
- }
5252
- function repoPathOf(ref) {
5253
- const segments = segmentsOfRef(ref);
5254
- if (segments.kind === "err")
5255
- return segments;
5256
- const p = repoPath(segments.value);
5257
- return p.kind === "err" ? err(portable(p.error)) : p;
5258
- }
5259
- function slugOf(text) {
5260
- const replaced = text.normalize("NFC").replace(/[\u0000-\u001f\u007f<>:"/\\|?*~^[\]\s]+/g, "-");
5261
- let slug = replaced.replace(/-{2,}/g, "-").replace(/[-. ]+$/, "").replace(/^[-.]+/, "");
5262
- if (isDeviceName(slug)) {
5263
- const dot = slug.indexOf(".");
5264
- slug = dot < 0 ? `${slug}_` : `${slug.slice(0, dot)}_${slug.slice(dot)}`;
5265
- }
5266
- return segment(slug);
5267
- }
5268
- function worktreePathOf(ref, branch) {
5269
- const segments = segmentsOfRef(ref);
5270
- if (segments.kind === "err")
5271
- return segments;
5272
- const slug = slugOf(branch);
5273
- if (slug.kind === "err")
5274
- return err(portable(slug.error));
5275
- const p = repoPath([".worktrees", ...segments.value, slug.value]);
5276
- return p.kind === "err" ? err(portable(p.error)) : p;
5277
- }
5278
- function homeOf2(facts) {
5279
- const nonEmpty = (s) => s === undefined || s.trim() === "" ? undefined : s;
5280
- const explicit = nonEmpty(facts.override) ?? nonEmpty(facts.workspacesHome);
5281
- if (explicit !== undefined)
5282
- return ok(explicit);
5283
- const home = nonEmpty(facts.home);
5284
- if (home === undefined)
5285
- return err({ kind: "no-home" });
5286
- return ok(`${home.replace(/[\\/]+$/, "")}${facts.windows ? "\\" : "/"}workspaces`);
5287
- }
5288
- function worktreeWanted(facts) {
5289
- return facts.uncommittedWork || facts.otherWorker;
5290
- }
5291
-
5292
- // src/modules/name.ts
5293
- var MAX_MODULE_NAME = 32;
5294
- function describeNameError(e) {
5295
- switch (e.kind) {
5296
- case "empty":
5297
- return "a module name is not empty";
5298
- case "too-long":
5299
- return `a module name has at most ${MAX_MODULE_NAME} characters, not ${e.length}`;
5300
- case "bad-start":
5301
- return `${JSON.stringify(e.text)} does not begin with a lower-case letter, as a module name must`;
5302
- case "bad-character":
5303
- return `${JSON.stringify(e.text)} holds ${JSON.stringify(e.character)}, and a module name is lower-case letters, digits and hyphens`;
5304
- default:
5305
- return absurd(e);
5306
- }
5307
- }
5308
- function moduleName(text) {
5309
- if (text === "")
5310
- return err({ kind: "empty" });
5311
- if (text.length > MAX_MODULE_NAME)
5312
- return err({ kind: "too-long", length: text.length });
5313
- if (!/^[a-z]/.test(text))
5314
- return err({ kind: "bad-start", text });
5315
- const bad = /[^a-z0-9-]/u.exec(text);
5316
- if (bad !== null)
5317
- return err({ kind: "bad-character", text, character: bad[0] });
5318
- return ok(text);
5319
- }
5320
- function nearestNames(word, names) {
5321
- return names.map((n) => ({ n, d: editDistance(word, n) })).filter((x) => x.d <= 2).sort((a, b) => a.d - b.d || (a.n < b.n ? -1 : a.n > b.n ? 1 : 0)).slice(0, 3).map((x) => x.n);
5322
- }
5323
-
5324
- // src/tools/catalog.ts
5325
- var PROBED_TOOLS = ["git", "bun", "node"];
5326
- var artifactShape = object({
5327
- os: literal("linux", "macos", "windows"),
5328
- arch: literal("x64", "arm64"),
5329
- url: string,
5330
- sha256: string
5331
- }, { kind: literal("file", "tar.gz", "zip"), bin: string });
5332
- var toolShape = object({ name: string, version: string, artifacts: array(artifactShape) }, { provides: array(string) });
5333
- var catalogShape = array(toolShape);
5334
- var NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
5335
- function safeInnerPath(path) {
5336
- if (path === "" || path.startsWith("/") || path.includes("\\") || /^[A-Za-z]:/.test(path))
5337
- return false;
5338
- return path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
5339
- }
5340
- function urlProblem(text, loopbackHttp = false) {
5341
- let url;
5342
- try {
5343
- url = new URL(text);
5344
- } catch {
5345
- return "it is not a URL";
5346
- }
5347
- const loopback = loopbackHttp && url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]");
5348
- if (url.protocol !== "https:" && !loopback)
5349
- return "a pinned artifact is fetched over https only";
5350
- if (url.username !== "" || url.password !== "")
5351
- return "it holds a credential";
5352
- if (/[?&](key|api_key|apikey|access_token|token|password|passwd|signature|sig)=/i.test(url.search))
5353
- return "its query holds a credential";
5354
- if (url.pathname.split("/").some((p) => p.toLowerCase() === "latest"))
5355
- return "it names `latest`, which is not a version";
5356
- return;
4895
+ function issueFinding(issue, today) {
4896
+ return {
4897
+ ruleId: issue.rule,
4898
+ severity: "Error",
4899
+ message: issue.message,
4900
+ subject: issue.path,
4901
+ firstSeen: today
4902
+ };
5357
4903
  }
5358
- function decodeCatalog(input, loopbackHttp = false) {
5359
- const shaped = catalogShape(input, "$.tools");
4904
+ function decodeManifest(input, options = {}) {
4905
+ const shaped = manifestShape(input);
5360
4906
  if (shaped.kind === "err") {
5361
4907
  return err([
5362
4908
  {
5363
- rule: "ergonex/catalog-shape",
4909
+ rule: "ergonex/manifest-shape",
5364
4910
  path: shaped.error.path,
5365
- message: `the tool catalog is not what is expected: ${formatDecodeError(shaped.error)}`
4911
+ message: `the manifest is not what is expected: ${formatDecodeError(shaped.error)}`
5366
4912
  }
5367
4913
  ]);
5368
4914
  }
5369
- const issues = [];
5370
- const tools = [];
5371
- const seenTool = new Set;
5372
- for (const [i, raw] of shaped.value.entries()) {
5373
- const at = `$.tools[${i}]`;
5374
- const bad = (path, message) => issues.push({ rule: "ergonex/catalog-tool", path, message });
5375
- if (!NAME.test(raw.name))
5376
- bad(`${at}.name`, `${JSON.stringify(raw.name)} is not a tool name (lower-case letters, digits, \`.\`, \`_\` and \`-\`)`);
5377
- else if (PROBED_TOOLS.includes(raw.name))
5378
- bad(`${at}.name`, `${raw.name} is verified by a probe of its version and never installed, so it is not a tool of the catalog (0002-workspace-model FR-038)`);
5379
- else if (seenTool.has(raw.name))
5380
- bad(`${at}.name`, `${raw.name} is in the catalog twice; one pinned version each`);
5381
- seenTool.add(raw.name);
5382
- const v = version(raw.version);
5383
- if (v.kind === "err")
5384
- bad(`${at}.version`, describeBrandError(v.error));
5385
- const artifacts = [];
5386
- const seen = new Set;
5387
- for (const [j, a] of raw.artifacts.entries()) {
5388
- const where = `${at}.artifacts[${j}]`;
5389
- const problem = urlProblem(a.url, loopbackHttp);
5390
- if (problem !== undefined)
5391
- bad(`${where}.url`, `the URL is not a pin: ${problem}`);
5392
- const sum = sha256Of(a.sha256);
5393
- if (sum === undefined)
5394
- bad(`${where}.sha256`, "the hash is not a SHA-256 (64 lower-case hexadecimal digits)");
5395
- const kind = a.kind ?? "file";
5396
- const bin = a.bin ?? (kind === "file" ? a.url.split("/").pop() ?? "" : "");
5397
- if (!safeInnerPath(bin))
5398
- bad(`${where}.bin`, `${JSON.stringify(bin)} is not a safe path to the executable (name it, relative, with \`/\` between parts and no \`..\`)`);
5399
- const key = `${a.os}/${a.arch}`;
5400
- if (seen.has(key))
5401
- bad(`${where}`, `${raw.name} has two artifacts for ${key}`);
5402
- seen.add(key);
5403
- if (problem === undefined && sum !== undefined && safeInnerPath(bin))
5404
- artifacts.push({
5405
- os: a.os,
5406
- arch: a.arch,
5407
- url: a.url,
5408
- sha256: sum,
5409
- kind,
5410
- bin
5411
- });
5412
- }
5413
- if (v.kind === "ok")
5414
- tools.push({
5415
- name: raw.name,
5416
- version: v.value,
5417
- provides: raw.provides ?? [raw.name],
5418
- artifacts
5419
- });
5420
- }
5421
- return issues.length > 0 ? err(issues) : ok({ tools });
5422
- }
5423
- function toolNamed(catalog, name) {
5424
- return catalog.tools.find((t) => t.name === name);
5425
- }
5426
- function artifactFor(tool, os, arch) {
5427
- return tool.artifacts.find((a) => a.os === os && a.arch === arch);
5428
- }
5429
- function installDirOf(tool) {
5430
- return `${tool.name}/${tool.version}`;
5431
- }
5432
- function providedBy(catalog, command) {
5433
- return catalog.tools.find((t) => t.name === command || t.provides.includes(command));
5434
- }
5435
-
5436
- // src/policy.ts
5437
- function policyOf(input = {}) {
5438
- const regulatedDomain = input.regulatedDomain ?? [];
5439
- return {
5440
- requiresSignedCommits: regulatedDomain.length > 0 || input.requiresSignedCommits === true,
5441
- regulatedDomain,
5442
- unapprovedGraceDays: input.unapprovedGraceDays ?? UNAPPROVED_GRACE_DAYS,
5443
- allowedGitHost: (input.allowedGitHost ?? []).map((h) => h.toLowerCase())
5444
- };
5445
- }
5446
- function isRegulated(policy) {
5447
- return policy.regulatedDomain.length > 0;
5448
- }
5449
- function unsignedCommitSeverity(policy, signedAndVerified) {
5450
- if (signedAndVerified)
5451
- return;
5452
- return isRegulated(policy) ? "Error" : "Warning";
5453
- }
5454
- function hookFailsWhenUnableToCheck(policy) {
5455
- return isRegulated(policy);
5456
- }
5457
- function hostAllowed(policy, host) {
5458
- return policy.allowedGitHost.length === 0 || policy.allowedGitHost.includes(host.toLowerCase());
5459
- }
5460
-
5461
- // src/manifest.ts
5462
- var repositoryShape = object({ remote: string }, { branch: string, group: string, worktrees: array(string) });
5463
- var manifestShape = object({ repositories: array(repositoryShape) }, {
5464
- gitlabHosts: array(string),
5465
- policy: object({}, {
5466
- requiresSignedCommits: boolean,
5467
- regulatedDomain: array(string),
5468
- unapprovedGraceDays: integer,
5469
- allowedGitHost: array(string)
5470
- }),
5471
- identity: object({ name: string, email: string }),
5472
- signing: object({ format: string }, { key: string }),
5473
- direnv: boolean,
5474
- tools: unknownValue,
5475
- modules: array(object({ name: string, program: string }, { sha256: string, summary: string }))
5476
- });
5477
- function issueFinding(issue, today) {
5478
- return {
5479
- ruleId: issue.rule,
5480
- severity: "Error",
5481
- message: issue.message,
5482
- subject: issue.path,
5483
- firstSeen: today
5484
- };
5485
- }
5486
- function decodeManifest(input, options = {}) {
5487
- const shaped = manifestShape(input);
5488
- if (shaped.kind === "err") {
5489
- return err([
5490
- {
5491
- rule: "ergonex/manifest-shape",
5492
- path: shaped.error.path,
5493
- message: `the manifest is not what is expected: ${formatDecodeError(shaped.error)}`
5494
- }
5495
- ]);
5496
- }
5497
- const raw = shaped.value;
4915
+ const raw = shaped.value;
5498
4916
  const issues = [];
5499
4917
  const hostKinds = {};
5500
4918
  for (const [i, h] of (raw.gitlabHosts ?? []).entries()) {
@@ -7410,14 +6828,14 @@ var commandDecoder = object({
7410
6828
  name: string,
7411
6829
  summary: string
7412
6830
  });
7413
- var manifestDecoder2 = object({
6831
+ var manifestDecoder = object({
7414
6832
  contract: integer,
7415
6833
  name: string,
7416
6834
  summary: string,
7417
6835
  commands: array(commandDecoder)
7418
6836
  });
7419
6837
  function decodeExternalManifest(text) {
7420
- const r = json(text, manifestDecoder2);
6838
+ const r = json(text, manifestDecoder);
7421
6839
  if (r.kind === "err")
7422
6840
  return err(formatDecodeError(r.error));
7423
6841
  const m = r.value;
@@ -8071,7 +7489,7 @@ function decodeDecisions(input) {
8071
7489
  return r;
8072
7490
  return ok(r.value.map((d) => ({ id: d.id, approvedBy: d.approvedBy, covers: d.covers, ...d.record === undefined ? {} : { record: d.record } })));
8073
7491
  }
8074
- function formatRecordError2(e) {
7492
+ function formatRecordError(e) {
8075
7493
  switch (e.kind) {
8076
7494
  case "decode":
8077
7495
  return e.message;
@@ -8136,7 +7554,7 @@ async function readSigningWaivers(root, repositories) {
8136
7554
  if (record.kind === "err") {
8137
7555
  notes.push({
8138
7556
  repo,
8139
- reason: `${RECORD_FILE} could not be read as data: ${formatRecordError2(record.error)}`
7557
+ reason: `${RECORD_FILE} could not be read as data: ${formatRecordError(record.error)}`
8140
7558
  });
8141
7559
  continue;
8142
7560
  }
@@ -8614,7 +8032,7 @@ var helpModule = {
8614
8032
  var TARGET = String.raw`((?:[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)?)#(\d+)`;
8615
8033
  var OWN_LINE = new RegExp(String.raw`^(refs|closes):?\s+${TARGET}\s*$`, "i");
8616
8034
  var CLOSING_WORD = new RegExp(String.raw`\b(close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved):?\s+${TARGET}`, "gi");
8617
- function requirementsOf2(value) {
8035
+ function requirementsOf(value) {
8618
8036
  const out = [];
8619
8037
  for (const group of value.split(";")) {
8620
8038
  const spec = /^\s*(\d{3,4}[a-z0-9-]*)\s/.exec(group)?.[1];
@@ -8656,7 +8074,7 @@ function parseMessage(message) {
8656
8074
  }
8657
8075
  const departure = /^departs:\s*(.*)$/i.exec(line);
8658
8076
  if (departure?.[1] !== undefined)
8659
- departs.push(...requirementsOf2(departure[1]));
8077
+ departs.push(...requirementsOf(departure[1]));
8660
8078
  const decision = /^decision:\s*(\S+)\s*$/i.exec(line);
8661
8079
  if (decision?.[1] !== undefined)
8662
8080
  decisions.push(decision[1]);
@@ -11236,100 +10654,681 @@ var prune = defineCommand({
11236
10654
  const folder = native(loaded, repo.path);
11237
10655
  if (!existsSync2(folder))
11238
10656
  continue;
11239
- const all = await listWorktrees(folder);
11240
- if (all.kind === "err")
10657
+ const all = await listWorktrees(folder);
10658
+ if (all.kind === "err")
10659
+ continue;
10660
+ for (const w of all.value.filter((x) => !x.main && foldKey(x.path.replaceAll("\\", "/")).startsWith(foldKey(base)))) {
10661
+ const work = await localWork(w.path);
10662
+ if (work.kind === "err") {
10663
+ lines.push(`kept ${w.path}: ${work.error}`);
10664
+ continue;
10665
+ }
10666
+ if (work.value.dirty || work.value.unpushed > 0) {
10667
+ lines.push(`kept ${w.path}: it has ${work.value.dirty ? "uncommitted changes" : ""}${work.value.dirty && work.value.unpushed > 0 ? " and " : ""}${work.value.unpushed > 0 ? `${work.value.unpushed} unpushed commit(s)` : ""}`);
10668
+ continue;
10669
+ }
10670
+ if (!args.options.allowDestructive) {
10671
+ lines.push(`would remove ${w.path}: it holds no work; give --allow-destructive to remove it`);
10672
+ continue;
10673
+ }
10674
+ const gone = await removeWorktree(folder, w.path);
10675
+ lines.push(gone.kind === "ok" ? `removed ${w.path}` : `kept ${w.path}: ${gone.error}`);
10676
+ if (gone.kind === "ok")
10677
+ done.push(w.path);
10678
+ }
10679
+ }
10680
+ return ok({
10681
+ text: lines.length === 0 ? "no worktree of the workspace to prune" : lines.join(`
10682
+ `),
10683
+ data: { removed: done },
10684
+ findings: []
10685
+ });
10686
+ })
10687
+ });
10688
+ var worktreeModule = {
10689
+ name: "worktree",
10690
+ summary: "Make, list and prune the worktrees of the managed repositories.",
10691
+ commands: [create, list3, prune]
10692
+ };
10693
+
10694
+ // src/commands/mod.ts
10695
+ var BUILTIN_MODULES = [
10696
+ initModule,
10697
+ addModule,
10698
+ removeModule,
10699
+ adoptModule,
10700
+ planModule,
10701
+ applyModule,
10702
+ statusModule,
10703
+ doctorModule,
10704
+ verifyModule,
10705
+ renderModule,
10706
+ worktreeModule,
10707
+ listModule,
10708
+ helpModule,
10709
+ shellModule,
10710
+ pathsModule,
10711
+ setupModule,
10712
+ toolsModule,
10713
+ hookModule
10714
+ ];
10715
+
10716
+ // src/commands/guidance.ts
10717
+ function guidanceFor(f) {
10718
+ if (f.home === undefined) {
10719
+ return [
10720
+ "Ergonex sets up and looks after the repositories you work on.",
10721
+ "",
10722
+ "It cannot find a folder to keep them in. Say where with:",
10723
+ "",
10724
+ " ergonex init --home <a folder>"
10725
+ ].join(`
10726
+ `);
10727
+ }
10728
+ if (!f.hasWorkspace) {
10729
+ return [
10730
+ "Ergonex sets up and looks after the repositories you work on.",
10731
+ "",
10732
+ "You have no workspace yet. To make one, run:",
10733
+ "",
10734
+ " ergonex init",
10735
+ "",
10736
+ `It makes the folder ${f.home}, puts ergonex where every terminal can find it, and tells you what to do next.`
10737
+ ].join(`
10738
+ `);
10739
+ }
10740
+ return [
10741
+ `Your workspace is at ${f.home}.`,
10742
+ "",
10743
+ " ergonex status shows each repository and whether it is up to date",
10744
+ " ergonex doctor checks your workspace and says what to fix",
10745
+ " ergonex plan shows what ergonex would change, and changes nothing",
10746
+ " ergonex help lists everything ergonex can do"
10747
+ ].join(`
10748
+ `);
10749
+ }
10750
+ // ../ts/kernel/evidence.ts
10751
+ var GENESIS = "0".repeat(64);
10752
+ var sha256Decoder = (input, path = "$") => {
10753
+ const s = typeof input === "string" && /^[0-9a-f]{64}$/.test(input) ? sha256Of(input) : undefined;
10754
+ return s === undefined ? err({ kind: "decode", path, expected: "a SHA-256 (64 lower-case hexadecimal digits)", found: typeof input }) : ok(s);
10755
+ };
10756
+ var ledgerEntryDecoder = object({
10757
+ seq: refine(integer, "positive", (n) => n >= 1),
10758
+ prev: sha256Decoder,
10759
+ at: instantDecoder,
10760
+ kind: string,
10761
+ subject: object({ kind: string, id: string }),
10762
+ evidence: sha256Decoder,
10763
+ digest: sha256Decoder
10764
+ });
10765
+ var manifestDecoder2 = object({
10766
+ files: array(object({ path: string, size: refine(integer, "size", (n) => n >= 0), sha256: sha256Decoder }))
10767
+ });
10768
+
10769
+ // ../ts/kernel/attest.ts
10770
+ var PASSING = new Set(["pass"]);
10771
+ // ../ts/kernel/oscal.ts
10772
+ var OPEN_OUTCOMES = new Set(["fail", "warn", "gap", "error", "accepted"]);
10773
+ // ../ts/kernel/test-record.ts
10774
+ var OUTCOMES = ["pass", "fail", "skip", "todo", "cancelled"];
10775
+ function isOutcome(text) {
10776
+ return OUTCOMES.includes(text);
10777
+ }
10778
+ function isRisk(text) {
10779
+ return text === "high" || text === "not-high";
10780
+ }
10781
+ function isStepOutcome(text) {
10782
+ return text === "pass" || text === "fail" || text === "skip";
10783
+ }
10784
+ var TEST_SCOPE = { name: "ifc-test", version: "1" };
10785
+ var TEST_SPAN = "test";
10786
+ var STEP_SPAN = "test step";
10787
+ var RUN_SPAN = "test run";
10788
+ var EVENTS = {
10789
+ case: "ifc.test.case",
10790
+ start: "ifc.test.start",
10791
+ review: "ifc.test.review",
10792
+ runner: "ifc.test.runner",
10793
+ warning: "ifc.test.warning"
10794
+ };
10795
+ function testId(file, name) {
10796
+ return sha256(`${file}\x00${name}`);
10797
+ }
10798
+ function isPersonAttribute(key) {
10799
+ return key.startsWith("user.") || key.startsWith("enduser.") || key === "host.name" || key === "host.id";
10800
+ }
10801
+ var ARCH = { x86_64: "amd64", x64: "amd64", aarch64: "arm64", arm: "arm32", ia32: "x86", x86: "x86" };
10802
+ function hostArch(arch) {
10803
+ return ARCH[arch] ?? arch;
10804
+ }
10805
+ var SHA256_TEXT = /^[0-9a-f]{64}$/;
10806
+ function installationFromEnv(self, env) {
10807
+ const warnings = [];
10808
+ const get = (k) => {
10809
+ const v = env[k]?.trim();
10810
+ return v === undefined || v === "" ? undefined : v;
10811
+ };
10812
+ const fallback = get("CI") === undefined || get("CI") === "false" ? "developer" : "ci";
10813
+ const given = get("IFC_TEST_ROLE");
10814
+ let role = fallback;
10815
+ if (given !== undefined) {
10816
+ if (roleOf(given) === undefined)
10817
+ warnings.push(`IFC_TEST_ROLE is not a role (lower-case words, never a person); ${fallback} is used`);
10818
+ else
10819
+ role = given;
10820
+ }
10821
+ const digest = (k) => {
10822
+ const v = get(k)?.toLowerCase();
10823
+ if (v === undefined)
10824
+ return;
10825
+ if (SHA256_TEXT.test(v))
10826
+ return v;
10827
+ warnings.push(`${k} is not a SHA-256; it is left out`);
10828
+ return;
10829
+ };
10830
+ const revision = get("IFC_TEST_REVISION") ?? get("GITHUB_SHA");
10831
+ const lockfileSha256 = digest("IFC_TEST_LOCKFILE_SHA256");
10832
+ const pinsSha256 = digest("IFC_TEST_PINS_SHA256");
10833
+ return {
10834
+ installation: {
10835
+ runtime: self.runtime,
10836
+ runtimeVersion: self.runtimeVersion,
10837
+ os: self.os,
10838
+ arch: hostArch(self.arch),
10839
+ ...revision === undefined ? {} : { revision },
10840
+ ...lockfileSha256 === undefined ? {} : { lockfileSha256 },
10841
+ ...pinsSha256 === undefined ? {} : { pinsSha256 },
10842
+ role
10843
+ },
10844
+ warnings
10845
+ };
10846
+ }
10847
+ function installationResource(i) {
10848
+ return {
10849
+ attributes: {
10850
+ "service.name": "ifc-test",
10851
+ "process.runtime.name": i.runtime,
10852
+ "process.runtime.version": i.runtimeVersion,
10853
+ "os.type": i.os,
10854
+ "host.arch": i.arch,
10855
+ ...i.revision === undefined ? {} : { "vcs.ref.head.revision": i.revision },
10856
+ ...i.lockfileSha256 === undefined ? {} : { "ifc.test.lockfile.sha256": i.lockfileSha256 },
10857
+ ...i.pinsSha256 === undefined ? {} : { "ifc.test.pins.sha256": i.pinsSha256 },
10858
+ "ifc.test.role": i.role
10859
+ }
10860
+ };
10861
+ }
10862
+ function attributeText(a, key) {
10863
+ const v = a[key];
10864
+ return typeof v === "string" ? v : undefined;
10865
+ }
10866
+ function attributeTexts(a, key) {
10867
+ const v = a[key];
10868
+ return Array.isArray(v) && v.every((e) => typeof e === "string") ? v : [];
10869
+ }
10870
+ function attributeInteger(a, key) {
10871
+ const v = a[key];
10872
+ if (typeof v === "bigint")
10873
+ return Number(v);
10874
+ return typeof v === "number" && Number.isInteger(v) ? v : undefined;
10875
+ }
10876
+ function installationOf(r) {
10877
+ const a = r.attributes;
10878
+ const revision = attributeText(a, "vcs.ref.head.revision");
10879
+ const lockfileSha256 = attributeText(a, "ifc.test.lockfile.sha256");
10880
+ const pinsSha256 = attributeText(a, "ifc.test.pins.sha256");
10881
+ return {
10882
+ runtime: attributeText(a, "process.runtime.name") ?? "unknown",
10883
+ runtimeVersion: attributeText(a, "process.runtime.version") ?? "unknown",
10884
+ os: attributeText(a, "os.type") ?? "unknown",
10885
+ arch: attributeText(a, "host.arch") ?? "unknown",
10886
+ ...revision === undefined ? {} : { revision },
10887
+ ...lockfileSha256 === undefined ? {} : { lockfileSha256 },
10888
+ ...pinsSha256 === undefined ? {} : { pinsSha256 },
10889
+ role: attributeText(a, "ifc.test.role") ?? "unknown"
10890
+ };
10891
+ }
10892
+ function caseAttributes(c) {
10893
+ const status = c.outcome === "pass" ? "pass" : c.outcome === "fail" || c.outcome === "cancelled" ? "fail" : undefined;
10894
+ return {
10895
+ "test.case.name": c.name,
10896
+ ...status === undefined ? {} : { "test.case.result.status": status },
10897
+ "test.suite.name": c.file,
10898
+ "code.file.path": c.file,
10899
+ "ifc.test.id": c.id,
10900
+ "ifc.test.requirements": [...c.requirements],
10901
+ "ifc.test.risk": c.risk,
10902
+ "ifc.test.outcome": c.outcome,
10903
+ "ifc.test.attempt": BigInt(c.attempt),
10904
+ ...c.characteristic === undefined ? {} : { "ifc.test.characteristic": c.characteristic },
10905
+ ...c.reason === undefined ? {} : { "ifc.test.reason": c.reason },
10906
+ ...c.message === undefined ? {} : { "ifc.test.message": c.message },
10907
+ ...c.expected === undefined ? {} : { "ifc.test.expected": c.expected },
10908
+ ...c.actual === undefined ? {} : { "ifc.test.actual": c.actual },
10909
+ ...c.steps === undefined || c.steps.length === 0 ? {} : { "ifc.test.steps": stepPaths(c.steps) }
10910
+ };
10911
+ }
10912
+ function stepPaths(steps, within = []) {
10913
+ return steps.flatMap((s) => [...stepPaths(s.steps ?? [], [...within, s.name]), [...within, s.name].join(" > ")]);
10914
+ }
10915
+ function testCaseSpan(c, ctx) {
10916
+ const failed = c.outcome === "fail" || c.outcome === "cancelled";
10917
+ return {
10918
+ name: TEST_SPAN,
10919
+ context: { traceId: ctx.traceId, spanId: ctx.spanId, traceFlags: 1, traceState: [], isRemote: false },
10920
+ ...ctx.parentSpanId === undefined ? {} : { parentSpanId: ctx.parentSpanId },
10921
+ kind: "internal",
10922
+ startTime: c.start,
10923
+ endTime: c.end,
10924
+ attributes: caseAttributes(c),
10925
+ events: [],
10926
+ links: [],
10927
+ status: failed ? { kind: "error", message: c.message ?? c.reason ?? c.outcome } : c.outcome === "pass" ? { kind: "ok" } : { kind: "unset" },
10928
+ droppedAttributesCount: 0,
10929
+ droppedEventsCount: 0,
10930
+ droppedLinksCount: 0
10931
+ };
10932
+ }
10933
+ function testCaseLog(c, ctx) {
10934
+ const failed = c.outcome === "fail" || c.outcome === "cancelled";
10935
+ return {
10936
+ time: c.end,
10937
+ observedTime: c.end,
10938
+ severityNumber: failed ? SEVERITY.ERROR : SEVERITY.INFO,
10939
+ severityText: failed ? "ERROR" : "INFO",
10940
+ body: `${c.outcome} ${c.name}`,
10941
+ attributes: caseAttributes(c),
10942
+ droppedAttributesCount: 0,
10943
+ eventName: EVENTS.case,
10944
+ traceId: ctx.traceId,
10945
+ spanId: ctx.spanId,
10946
+ traceFlags: 1
10947
+ };
10948
+ }
10949
+ function plainLog(eventName, time, body, attributes, warn = false) {
10950
+ return {
10951
+ time,
10952
+ observedTime: time,
10953
+ severityNumber: warn ? SEVERITY.WARN : SEVERITY.INFO,
10954
+ severityText: warn ? "WARN" : "INFO",
10955
+ body,
10956
+ attributes,
10957
+ droppedAttributesCount: 0,
10958
+ eventName
10959
+ };
10960
+ }
10961
+ function reviewLog(r, time, traceId) {
10962
+ const base = plainLog(EVENTS.review, time, `reviewed ${r.requirement}`, {
10963
+ "ifc.test.requirement": r.requirement,
10964
+ "ifc.test.reason": r.reason
10965
+ });
10966
+ return traceId === undefined ? base : { ...base, traceId };
10967
+ }
10968
+ function warningLog(message, time) {
10969
+ return plainLog(EVENTS.warning, time, message, { "ifc.test.warning": message }, true);
10970
+ }
10971
+ function runnerLog(r, time) {
10972
+ const attributes = r.kind === "exited" ? { "process.runtime.name": r.runtime, "ifc.test.runner.found": true, "process.exit.code": BigInt(r.code) } : { "process.runtime.name": r.runtime, "ifc.test.runner.found": false };
10973
+ return plainLog(EVENTS.runner, time, r.kind === "exited" ? `${r.runtime} exited with ${r.code}` : `${r.runtime} is not installed`, attributes, r.kind === "missing" || r.kind === "exited" && r.code !== 0);
10974
+ }
10975
+ function formatRecordError2(e) {
10976
+ switch (e.kind) {
10977
+ case "json":
10978
+ return `line ${e.line} is not JSON: ${e.reason}`;
10979
+ case "otlp":
10980
+ return `line ${e.line} is not OTLP JSON: ${formatDecodeError(e.error)}`;
10981
+ case "person":
10982
+ return `the record names a person or a machine of one (${e.key}), which a test record must not`;
10983
+ case "test":
10984
+ return `the test span ${e.spanId} is not a test record: ${e.reason}`;
10985
+ case "no-run":
10986
+ return `the record has no run: ${e.reason}`;
10987
+ default:
10988
+ return absurd(e);
10989
+ }
10990
+ }
10991
+ function decodeRecordDocument(value, line) {
10992
+ const t = decodeTraces(value);
10993
+ if (t.kind === "err")
10994
+ return err({ kind: "otlp", line, error: t.error });
10995
+ const l = decodeLogs(value);
10996
+ if (l.kind === "err")
10997
+ return err({ kind: "otlp", line, error: l.error });
10998
+ return ok({ traces: t.value, logs: l.value });
10999
+ }
11000
+ function resourceKey(r, s) {
11001
+ const keys = Object.keys(r.attributes).sort();
11002
+ const enc = (v) => typeof v === "bigint" ? `${v}n` : v instanceof Uint8Array ? [...v] : Array.isArray(v) ? v.map((x) => typeof x === "bigint" ? `${x}n` : x) : v;
11003
+ return JSON.stringify([s.name, s.version ?? "", keys.map((k) => [k, enc(r.attributes[k])])]);
11004
+ }
11005
+ function mergeBatches(signals) {
11006
+ const t = new Map;
11007
+ for (const b of signals.traces) {
11008
+ const k = resourceKey(b.resource, b.scope);
11009
+ const at = t.get(k) ?? { resource: b.resource, scope: b.scope, spans: [] };
11010
+ at.spans.push(...b.spans);
11011
+ t.set(k, at);
11012
+ }
11013
+ const l = new Map;
11014
+ for (const b of signals.logs) {
11015
+ const k = resourceKey(b.resource, b.scope);
11016
+ const at = l.get(k) ?? { resource: b.resource, scope: b.scope, records: [] };
11017
+ at.records.push(...b.records);
11018
+ l.set(k, at);
11019
+ }
11020
+ return { traces: [...t.values()], logs: [...l.values()] };
11021
+ }
11022
+ function closeOrphans(signals, at) {
11023
+ const ended = new Set(signals.traces.flatMap((b) => b.spans.filter((s) => s.name === TEST_SPAN).map((s) => s.context.spanId)));
11024
+ const extra = [];
11025
+ for (const b of signals.logs) {
11026
+ const spans = [];
11027
+ for (const r of b.records) {
11028
+ if (r.eventName !== EVENTS.start || r.spanId === undefined || r.traceId === undefined || ended.has(r.spanId))
11029
+ continue;
11030
+ ended.add(r.spanId);
11031
+ const a = r.attributes;
11032
+ const risk = attributeText(a, "ifc.test.risk") ?? "not-high";
11033
+ const parent = attributeText(a, "ifc.test.parent");
11034
+ const characteristic = attributeText(a, "ifc.test.characteristic");
11035
+ const parentSpanId = parent === undefined ? undefined : parseSpanId(parent);
11036
+ const c = {
11037
+ id: attributeText(a, "ifc.test.id") ?? "",
11038
+ file: attributeText(a, "test.suite.name") ?? "",
11039
+ name: attributeText(a, "test.case.name") ?? "",
11040
+ requirements: attributeTexts(a, "ifc.test.requirements"),
11041
+ risk: isRisk(risk) ? risk : "not-high",
11042
+ ...characteristic === undefined ? {} : { characteristic },
11043
+ start: r.time,
11044
+ end: at > r.time ? at : r.time,
11045
+ outcome: "cancelled",
11046
+ reason: "its process ended before the test did",
11047
+ attempt: attributeInteger(a, "ifc.test.attempt") ?? 1
11048
+ };
11049
+ spans.push(testCaseSpan(c, {
11050
+ traceId: r.traceId,
11051
+ spanId: r.spanId,
11052
+ ...parentSpanId?.kind === "ok" ? { parentSpanId: parentSpanId.value } : {}
11053
+ }));
11054
+ }
11055
+ if (spans.length > 0)
11056
+ extra.push({ resource: b.resource, scope: b.scope, spans });
11057
+ }
11058
+ return extra.length === 0 ? signals : mergeBatches({ traces: [...signals.traces, ...extra], logs: signals.logs });
11059
+ }
11060
+ // ../ts/kernel/test-report.ts
11061
+ var byText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11062
+ function testOf(s, runtime) {
11063
+ const a = s.attributes;
11064
+ const no = (reason) => err({ kind: "test", spanId: s.context.spanId, reason });
11065
+ const id = attributeText(a, "ifc.test.id");
11066
+ const name = attributeText(a, "test.case.name");
11067
+ const file = attributeText(a, "test.suite.name");
11068
+ const outcome = attributeText(a, "ifc.test.outcome") ?? "";
11069
+ const risk = attributeText(a, "ifc.test.risk") ?? "";
11070
+ if (id === undefined)
11071
+ return no("it has no ifc.test.id");
11072
+ if (name === undefined)
11073
+ return no("it has no test.case.name");
11074
+ if (file === undefined)
11075
+ return no("it has no test.suite.name");
11076
+ if (!isOutcome(outcome))
11077
+ return no(`its outcome ${JSON.stringify(outcome)} is not one of ${OUTCOMES.join(", ")}`);
11078
+ if (!isRisk(risk))
11079
+ return no(`its risk ${JSON.stringify(risk)} is not high or not-high`);
11080
+ const reason = attributeText(a, "ifc.test.reason");
11081
+ const message = attributeText(a, "ifc.test.message");
11082
+ const expected = attributeText(a, "ifc.test.expected");
11083
+ const actual = attributeText(a, "ifc.test.actual");
11084
+ const characteristic = attributeText(a, "ifc.test.characteristic");
11085
+ return ok({
11086
+ id,
11087
+ file,
11088
+ name,
11089
+ requirements: attributeTexts(a, "ifc.test.requirements"),
11090
+ risk,
11091
+ ...characteristic === undefined ? {} : { characteristic },
11092
+ start: s.startTime,
11093
+ end: s.endTime,
11094
+ outcome,
11095
+ ...reason === undefined ? {} : { reason },
11096
+ ...message === undefined ? {} : { message },
11097
+ ...expected === undefined ? {} : { expected },
11098
+ ...actual === undefined ? {} : { actual },
11099
+ attempt: attributeInteger(a, "ifc.test.attempt") ?? 1,
11100
+ runtime,
11101
+ spanId: s.context.spanId
11102
+ });
11103
+ }
11104
+ function compareTests(a, b) {
11105
+ return byText(a.runtime, b.runtime) || byText(a.file, b.file) || byText(a.name, b.name) || a.attempt - b.attempt || (a.start < b.start ? -1 : a.start > b.start ? 1 : 0) || byText(a.spanId, b.spanId);
11106
+ }
11107
+ function stepsUnder(parent, children) {
11108
+ return (children.get(parent) ?? []).flatMap((s) => {
11109
+ const name = attributeText(s.attributes, "ifc.test.step.name");
11110
+ const outcome = attributeText(s.attributes, "ifc.test.outcome") ?? "";
11111
+ if (name === undefined || !isStepOutcome(outcome))
11112
+ return [];
11113
+ const message = attributeText(s.attributes, "ifc.test.message");
11114
+ const inner = stepsUnder(s.context.spanId, children);
11115
+ return [
11116
+ {
11117
+ name,
11118
+ start: s.startTime,
11119
+ end: s.endTime,
11120
+ outcome,
11121
+ ...message === undefined ? {} : { message },
11122
+ ...inner.length === 0 ? {} : { steps: inner }
11123
+ }
11124
+ ];
11125
+ }).sort((a, b) => a.end < b.end ? -1 : a.end > b.end ? 1 : 0);
11126
+ }
11127
+ function testsOf(signals) {
11128
+ const tests = [];
11129
+ const children = new Map;
11130
+ for (const b of signals.traces) {
11131
+ for (const s of b.spans) {
11132
+ if (s.name !== STEP_SPAN || s.parentSpanId === undefined)
11133
+ continue;
11134
+ const at = children.get(s.parentSpanId) ?? [];
11135
+ at.push(s);
11136
+ children.set(s.parentSpanId, at);
11137
+ }
11138
+ }
11139
+ for (const b of signals.traces) {
11140
+ const runtime = attributeText(b.resource.attributes, "process.runtime.name") ?? "unknown";
11141
+ for (const s of b.spans) {
11142
+ if (s.name !== TEST_SPAN)
11143
+ continue;
11144
+ const t = testOf(s, runtime);
11145
+ if (t.kind === "err")
11146
+ return t;
11147
+ const steps = stepsUnder(s.context.spanId, children);
11148
+ tests.push(steps.length === 0 ? t.value : { ...t.value, steps });
11149
+ }
11150
+ }
11151
+ return ok(tests.sort(compareTests));
11152
+ }
11153
+ function reviewsOf(signals) {
11154
+ const seen = new Map;
11155
+ for (const b of signals.logs) {
11156
+ for (const r of b.records) {
11157
+ if (r.eventName !== EVENTS.review)
11158
+ continue;
11159
+ const requirement = attributeText(r.attributes, "ifc.test.requirement");
11160
+ const reason = attributeText(r.attributes, "ifc.test.reason");
11161
+ if (requirement === undefined || reason === undefined)
11241
11162
  continue;
11242
- for (const w of all.value.filter((x) => !x.main && foldKey(x.path.replaceAll("\\", "/")).startsWith(foldKey(base)))) {
11243
- const work = await localWork(w.path);
11244
- if (work.kind === "err") {
11245
- lines.push(`kept ${w.path}: ${work.error}`);
11246
- continue;
11247
- }
11248
- if (work.value.dirty || work.value.unpushed > 0) {
11249
- lines.push(`kept ${w.path}: it has ${work.value.dirty ? "uncommitted changes" : ""}${work.value.dirty && work.value.unpushed > 0 ? " and " : ""}${work.value.unpushed > 0 ? `${work.value.unpushed} unpushed commit(s)` : ""}`);
11250
- continue;
11251
- }
11252
- if (!args.options.allowDestructive) {
11253
- lines.push(`would remove ${w.path}: it holds no work; give --allow-destructive to remove it`);
11254
- continue;
11255
- }
11256
- const gone = await removeWorktree(folder, w.path);
11257
- lines.push(gone.kind === "ok" ? `removed ${w.path}` : `kept ${w.path}: ${gone.error}`);
11258
- if (gone.kind === "ok")
11259
- done.push(w.path);
11163
+ seen.set(JSON.stringify([requirement, reason]), { requirement, reason });
11164
+ }
11165
+ }
11166
+ return [...seen.entries()].sort(([a], [b]) => byText(a, b)).map(([, r]) => r);
11167
+ }
11168
+ function countsOf(tests) {
11169
+ const n = (o) => tests.filter((t) => t.outcome === o).length;
11170
+ return { tests: tests.length, passed: n("pass"), failed: n("fail"), skipped: n("skip"), todo: n("todo"), cancelled: n("cancelled") };
11171
+ }
11172
+ function requirementsOf2(tests, reviews, required) {
11173
+ const ids = new Set([...required, ...reviews.map((r) => r.requirement), ...tests.flatMap((t) => t.requirements)]);
11174
+ const listed = new Set(required);
11175
+ return [...ids].sort(byText).map((id) => {
11176
+ const proving = tests.filter((t) => t.requirements.includes(id));
11177
+ const reasons = [...new Set(reviews.filter((r) => r.requirement === id).map((r) => r.reason))].sort(byText);
11178
+ const outcomes = new Set(proving.map((t) => t.outcome));
11179
+ const state = outcomes.has("fail") || outcomes.has("cancelled") ? "failing" : outcomes.has("pass") ? "proven" : reasons.length > 0 ? "reviewed" : proving.length > 0 ? "skipped" : "unproven";
11180
+ return {
11181
+ id,
11182
+ required: listed.has(id),
11183
+ risk: proving.some((t) => t.risk === "high") ? "high" : "not-high",
11184
+ state,
11185
+ tests: proving.map((t) => ({ id: t.id, name: t.name, runtime: t.runtime, outcome: t.outcome })),
11186
+ reviews: reasons
11187
+ };
11188
+ });
11189
+ }
11190
+ function judge2(input) {
11191
+ const failures = [];
11192
+ const counts = countsOf(input.tests);
11193
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
11194
+ if (counts.failed > 0)
11195
+ failures.push(`${plural(counts.failed, "test", "tests")} failed`);
11196
+ if (counts.cancelled > 0)
11197
+ failures.push(`${plural(counts.cancelled, "test was", "tests were")} cancelled`);
11198
+ for (const r of input.runners) {
11199
+ switch (r.kind) {
11200
+ case "exited":
11201
+ if (r.code !== 0)
11202
+ failures.push(`the ${r.runtime} runner exited with ${r.code}`);
11203
+ break;
11204
+ case "missing":
11205
+ failures.push(`${r.runtime} is not installed`);
11206
+ break;
11207
+ default:
11208
+ absurd(r);
11209
+ }
11210
+ }
11211
+ const unproven = requirementsOf2(input.tests, input.reviews, input.required).filter((r) => r.required && (r.state === "unproven" || r.state === "skipped")).map((r) => r.id);
11212
+ if (unproven.length > 0)
11213
+ failures.push(`${plural(unproven.length, "requirement is", "requirements are")} neither proven nor reviewed: ${unproven.join(", ")}`);
11214
+ return { status: failures.length === 0 ? "success" : "failure", failures, unproven };
11215
+ }
11216
+ function assembleRecord(input) {
11217
+ const closed = closeOrphans(mergeBatches(input.signals), input.end);
11218
+ const tests = testsOf(closed);
11219
+ if (tests.kind === "err")
11220
+ return tests;
11221
+ const reviews = [...reviewsOf(closed), ...input.reviews ?? []];
11222
+ const judgement = judge2({ tests: tests.value, runners: input.runners, required: input.required, reviews });
11223
+ const resource = installationResource(input.runner);
11224
+ const runSpan = {
11225
+ name: RUN_SPAN,
11226
+ context: { traceId: input.traceId, spanId: input.spanId, traceFlags: 1, traceState: [], isRemote: false },
11227
+ kind: "internal",
11228
+ startTime: input.start,
11229
+ endTime: input.end,
11230
+ attributes: {
11231
+ "test.suite.name": "ifc test",
11232
+ "test.suite.run.status": judgement.status,
11233
+ "ifc.test.unproven": [...judgement.unproven],
11234
+ "ifc.test.required": [...input.required],
11235
+ "ifc.test.failures": [...judgement.failures],
11236
+ "ifc.test.runtimes": input.runners.map((r) => r.runtime)
11237
+ },
11238
+ events: [],
11239
+ links: [],
11240
+ status: judgement.status === "success" ? { kind: "ok" } : { kind: "error", message: judgement.failures.join("; ") },
11241
+ droppedAttributesCount: 0,
11242
+ droppedEventsCount: 0,
11243
+ droppedLinksCount: 0
11244
+ };
11245
+ const own = [
11246
+ ...input.runners.map((r) => ({ ...runnerLog(r, input.end), traceId: input.traceId, spanId: input.spanId })),
11247
+ ...(input.reviews ?? []).map((r) => ({ ...reviewLog(r, input.end, input.traceId), spanId: input.spanId })),
11248
+ ...(input.warnings ?? []).map((w) => ({ ...warningLog(w, input.end), traceId: input.traceId, spanId: input.spanId }))
11249
+ ];
11250
+ const merged = mergeBatches({
11251
+ traces: [{ resource, scope: TEST_SCOPE, spans: [runSpan] }, ...closed.traces],
11252
+ logs: [...own.length === 0 ? [] : [{ resource, scope: TEST_SCOPE, records: own }], ...closed.logs]
11253
+ });
11254
+ return ok({ record: { ...encodeTraces(merged.traces), ...encodeLogs(merged.logs) }, judgement });
11255
+ }
11256
+ function recordText(record) {
11257
+ return `${JSON.stringify(record)}
11258
+ `;
11259
+ }
11260
+ function readRecord(input) {
11261
+ let value = input;
11262
+ if (typeof input === "string") {
11263
+ try {
11264
+ value = JSON.parse(input);
11265
+ } catch (e) {
11266
+ return err({ kind: "json", line: 1, reason: e instanceof Error ? e.message : String(e) });
11267
+ }
11268
+ }
11269
+ const d = decodeRecordDocument(value, 1);
11270
+ if (d.kind === "err")
11271
+ return d;
11272
+ const signals = d.value;
11273
+ for (const b of [...signals.traces, ...signals.logs]) {
11274
+ const key = Object.keys(b.resource.attributes).find(isPersonAttribute);
11275
+ if (key !== undefined)
11276
+ return err({ kind: "person", key });
11277
+ }
11278
+ const runs = signals.traces.flatMap((b) => b.spans.filter((s) => s.name === RUN_SPAN).map((s) => ({ s, resource: b.resource })));
11279
+ const run = runs[0];
11280
+ if (run === undefined)
11281
+ return err({ kind: "no-run", reason: `no span is named ${JSON.stringify(RUN_SPAN)}` });
11282
+ if (runs.length > 1)
11283
+ return err({ kind: "no-run", reason: `${runs.length} spans are named ${JSON.stringify(RUN_SPAN)}` });
11284
+ const status = attributeText(run.s.attributes, "test.suite.run.status");
11285
+ if (status !== "success" && status !== "failure")
11286
+ return err({ kind: "no-run", reason: "its span has no test.suite.run.status of success or failure" });
11287
+ const tests = testsOf(signals);
11288
+ if (tests.kind === "err")
11289
+ return tests;
11290
+ const reviews = reviewsOf(signals);
11291
+ const required = attributeTexts(run.s.attributes, "ifc.test.required");
11292
+ const runners = [];
11293
+ const warnings = [];
11294
+ for (const b of signals.logs) {
11295
+ for (const r of b.records) {
11296
+ if (r.eventName === EVENTS.runner) {
11297
+ const runtime = attributeText(r.attributes, "process.runtime.name") ?? "unknown";
11298
+ const code = attributeInteger(r.attributes, "process.exit.code");
11299
+ runners.push(r.attributes["ifc.test.runner.found"] === false || code === undefined ? { kind: "missing", runtime } : { kind: "exited", runtime, code });
11300
+ } else if (r.eventName === EVENTS.warning) {
11301
+ warnings.push(attributeText(r.attributes, "ifc.test.warning") ?? "");
11260
11302
  }
11261
11303
  }
11262
- return ok({
11263
- text: lines.length === 0 ? "no worktree of the workspace to prune" : lines.join(`
11264
- `),
11265
- data: { removed: done },
11266
- findings: []
11267
- });
11268
- })
11269
- });
11270
- var worktreeModule = {
11271
- name: "worktree",
11272
- summary: "Make, list and prune the worktrees of the managed repositories.",
11273
- commands: [create, list3, prune]
11274
- };
11275
-
11276
- // src/commands/mod.ts
11277
- var BUILTIN_MODULES = [
11278
- initModule,
11279
- addModule,
11280
- removeModule,
11281
- adoptModule,
11282
- planModule,
11283
- applyModule,
11284
- statusModule,
11285
- doctorModule,
11286
- verifyModule,
11287
- renderModule,
11288
- worktreeModule,
11289
- listModule,
11290
- helpModule,
11291
- shellModule,
11292
- pathsModule,
11293
- setupModule,
11294
- toolsModule,
11295
- hookModule
11296
- ];
11297
-
11298
- // src/commands/guidance.ts
11299
- function guidanceFor(f) {
11300
- if (f.home === undefined) {
11301
- return [
11302
- "Ergonex sets up and looks after the repositories you work on.",
11303
- "",
11304
- "It cannot find a folder to keep them in. Say where with:",
11305
- "",
11306
- " ergonex init --home <a folder>"
11307
- ].join(`
11308
- `);
11309
11304
  }
11310
- if (!f.hasWorkspace) {
11311
- return [
11312
- "Ergonex sets up and looks after the repositories you work on.",
11313
- "",
11314
- "You have no workspace yet. To make one, run:",
11315
- "",
11316
- " ergonex init",
11317
- "",
11318
- `It makes the folder ${f.home}, puts ergonex where every terminal can find it, and tells you what to do next.`
11319
- ].join(`
11320
- `);
11305
+ const installations = new Map;
11306
+ for (const b of signals.traces) {
11307
+ if (b.spans.some((s) => s.name === TEST_SPAN)) {
11308
+ const i = installationOf(b.resource);
11309
+ installations.set(JSON.stringify([i.runtime, i.runtimeVersion, i.os, i.arch, i.role, i.revision ?? ""]), i);
11310
+ }
11321
11311
  }
11322
- return [
11323
- `Your workspace is at ${f.home}.`,
11324
- "",
11325
- " ergonex status shows each repository and whether it is up to date",
11326
- " ergonex doctor checks your workspace and says what to fix",
11327
- " ergonex plan shows what ergonex would change, and changes nothing",
11328
- " ergonex help lists everything ergonex can do"
11329
- ].join(`
11330
- `);
11312
+ return ok({
11313
+ traceId: run.s.context.traceId,
11314
+ spanId: run.s.context.spanId,
11315
+ start: run.s.startTime,
11316
+ end: run.s.endTime,
11317
+ status,
11318
+ failures: attributeTexts(run.s.attributes, "ifc.test.failures"),
11319
+ unproven: attributeTexts(run.s.attributes, "ifc.test.unproven"),
11320
+ required,
11321
+ runner: installationOf(run.resource),
11322
+ installations: [...installations.entries()].sort(([a], [b]) => byText(a, b)).map(([, i]) => i),
11323
+ runners,
11324
+ tests: tests.value,
11325
+ reviews,
11326
+ warnings: [...new Set(warnings)].sort(byText),
11327
+ requirements: requirementsOf2(tests.value, reviews, required),
11328
+ counts: countsOf(tests.value)
11329
+ });
11331
11330
  }
11332
-
11331
+ var STYLE = "body{font:15px/1.5 system-ui,sans-serif;margin:2rem auto;max-width:72rem;padding:0 1rem;color:#1b1b1b;background:#fff}" + "table{border-collapse:collapse;margin:.5rem 0;width:100%}th,td{border:1px solid #c8c8c8;padding:.25rem .5rem;text-align:left;vertical-align:top;overflow-wrap:anywhere}" + "th{background:#f0f0f0}h1{font-size:1.6rem}h2{font-size:1.2rem;margin-top:2rem}" + "@media (prefers-color-scheme:dark){body{color:#e8e8e8;background:#161616}th{background:#2a2a2a}th,td{border-color:#444}}";
11333
11332
  // src/platform/k-otel.ts
11334
11333
  var parseSpanId2 = parseSpanId;
11335
11334
  var parseTraceId2 = parseTraceId;
@@ -11360,7 +11359,7 @@ var NO_GRADE = "E0";
11360
11359
  function formatQualityError(e) {
11361
11360
  switch (e.kind) {
11362
11361
  case "record":
11363
- return formatRecordError(e.error);
11362
+ return formatRecordError2(e.error);
11364
11363
  case "otlp":
11365
11364
  return `the record is not OTLP JSON: ${formatDecodeError(e.error)}`;
11366
11365
  case "case":