docks-kit 0.24.0 → 0.26.0

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 (49) hide show
  1. package/AGENTS.md +21 -136
  2. package/README.md +54 -9
  3. package/cli/dist/docks-kit.js +24688 -0
  4. package/cli/docs/command-guards.md +1 -1
  5. package/cli/docs/install.md +30 -9
  6. package/cli/docs/omp-context.md +1 -1
  7. package/cli/docs/omp-models.md +5 -4
  8. package/cli/docs/sync-layers.md +46 -75
  9. package/cli/docs/toolchain.md +4 -5
  10. package/cli/src/agentDocs/agentFirstCheck.ts +786 -0
  11. package/cli/src/agentDocs/bridgeCheck.ts +226 -0
  12. package/cli/src/agentDocs/commands.ts +63 -0
  13. package/cli/src/agentDocs/prTemplate.ts +211 -0
  14. package/cli/src/agentDocs/services.ts +202 -0
  15. package/cli/src/agentDocs/shared.ts +730 -0
  16. package/cli/src/agentDocs/verifySkill.ts +136 -0
  17. package/cli/src/argv.ts +25 -1
  18. package/cli/src/commands/agentDocs.ts +29 -0
  19. package/cli/src/commands/plan.ts +29 -0
  20. package/cli/src/commands/skill.ts +29 -0
  21. package/cli/src/commands/update.ts +90 -31
  22. package/cli/src/engine-native/DESIGN.md +5 -6
  23. package/cli/src/engine-native/engineCtx.ts +0 -3
  24. package/cli/src/engine-native/failures.ts +2 -2
  25. package/cli/src/engine-native/ompChild.ts +1 -1
  26. package/cli/src/engine-native/ompKitPlugin.ts +7 -16
  27. package/cli/src/engine-native/ompPlugins.ts +205 -221
  28. package/cli/src/engine-native/ompSync.ts +5 -14
  29. package/cli/src/generated/sotPayload.ts +308 -12
  30. package/cli/src/main.ts +12 -3
  31. package/cli/src/plan/bytes.ts +110 -0
  32. package/cli/src/plan/checkout.ts +341 -0
  33. package/cli/src/plan/commands.ts +1192 -0
  34. package/cli/src/plan/github.ts +816 -0
  35. package/cli/src/plan/records.ts +623 -0
  36. package/cli/src/plan/repository.ts +53 -0
  37. package/cli/src/plan/reviews.ts +292 -0
  38. package/cli/src/plan/services.ts +256 -0
  39. package/cli/src/plan/types.ts +164 -0
  40. package/cli/src/skills/commands.ts +142 -0
  41. package/cli/src/skills/config.json +30 -0
  42. package/cli/src/skills/files.ts +74 -0
  43. package/cli/src/skills/frontmatter.ts +148 -0
  44. package/cli/src/skills/guard.ts +366 -0
  45. package/cli/src/skills/kitGate.ts +406 -0
  46. package/cli/src/skills/rubric.ts +143 -0
  47. package/cli/tsconfig.json +1 -0
  48. package/package.json +7 -4
  49. package/cli/src/engine-native/ompMarketplace.ts +0 -140
package/cli/src/main.ts CHANGED
@@ -26,6 +26,15 @@ const root = Command.make("docks-kit", {}, () =>
26
26
  yield* Console.log(
27
27
  " docks-kit tidy [--apply] [--repo <path>] [--report] remove safe agent leftovers",
28
28
  );
29
+ yield* Console.log(
30
+ " docks-kit plan <command> [...] GitHub-issue plan records (plan-manager helper)",
31
+ );
32
+ yield* Console.log(
33
+ " docks-kit agent-docs <helper> <command> [...] agent-doc checks (agent-first-setup helpers)",
34
+ );
35
+ yield* Console.log(
36
+ " docks-kit skill guard|score [...] SKILL.md validator and rubric score (write-skill helpers)",
37
+ );
29
38
  yield* Console.log("");
30
39
  yield* Console.log(
31
40
  "Run 'docks-kit --help' for full option listings (also: --wizard, --completions).",
@@ -40,11 +49,11 @@ const root = Command.make("docks-kit", {}, () =>
40
49
  );
41
50
 
42
51
  // v4's default formatter renders `name vversion`, but the `docks-kit` launcher
43
- // compares `--version` against the bare `package.json` version. The trailing
44
- // newline reproduces the characterized byte-for-byte output of the v3 CLI.
52
+ // compares `--version` against the bare `package.json` version. The CLI output
53
+ // presenter prints the result with `Console.log`, which adds the one newline.
45
54
  const bareVersionFormatter: CliOutput.Formatter = {
46
55
  ...CliOutput.defaultFormatter(),
47
- formatVersion: (_name, version) => `${version}\n`,
56
+ formatVersion: (_name, version) => version,
48
57
  };
49
58
 
50
59
  // Harness-private raw channel:
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Raw path bytes for `docks-kit plan`. A path is held as a string with one character per byte (latin1), so a byte
3
+ * that is not UTF-8 stays itself. The runtime decodes its arguments and `process.cwd()` as UTF-8 and puts U+FFFD in
4
+ * place of each byte that is not UTF-8, which cannot be told from a literal U+FFFD. On Linux, `/proc/self/cmdline`
5
+ * and `/proc/self/cwd` give the bytes. macOS paths and Windows arguments are Unicode, so there the runtime strings are
6
+ * exact. On another system without those files, `pwd -P` gives the working folder, which it inherits; an argument
7
+ * with a U+FFFD has no other source of its bytes, and its use fails closed.
8
+ */
9
+ import path from "node:path";
10
+
11
+ import { Effect } from "effect";
12
+
13
+ import { PlanFiles, PlanProcess } from "./services";
14
+
15
+ /** The bytes, or why they cannot be known. */
16
+ export type Recovered<A> =
17
+ | { readonly ok: true; readonly value: A }
18
+ | { readonly ok: false; readonly cause: string };
19
+
20
+ const ARGUMENT_WITHOUT_PROC = "the bytes of an argument cannot be recovered without /proc";
21
+ const ARGUMENT_UNMATCHED =
22
+ "the bytes of an argument cannot be recovered: /proc/self/cmdline does not match the arguments";
23
+ const WORKING_FOLDER_LOST =
24
+ "the bytes of the working folder cannot be recovered without /proc or pwd -P";
25
+
26
+ // Whether a path of this system is bytes that need not be UTF-8.
27
+ const PATHS_ARE_BYTES = process.platform !== "darwin" && process.platform !== "win32";
28
+
29
+ /** The /proc folder; `PLAN_CLI_PROC_ROOT` (a test hook) names another, such as an empty folder for a missing /proc. */
30
+ const procFile = (name: string): string =>
31
+ path.join(process.env["PLAN_CLI_PROC_ROOT"] || "/proc", "self", name);
32
+
33
+ /** A string of this process (UTF-8 text) as one character per byte. */
34
+ export const asBytes = (text: string): string => Buffer.from(text, "utf8").toString("latin1");
35
+
36
+ /** The text of a byte string when its bytes are UTF-8, or undefined when they are not. */
37
+ export const utf8Text = (bytes: string): string | undefined => {
38
+ const text = Buffer.from(bytes, "latin1").toString("utf8");
39
+ return asBytes(text) === bytes ? text : undefined;
40
+ };
41
+
42
+ // A run of U+FFFD, which one invalid sequence or several give, depending on the decoder.
43
+ const REPLACEMENTS = /\uFFFD+/g;
44
+
45
+ /**
46
+ * The bytes of `args`, the last words of the command line of this process, one byte string each. Each word of
47
+ * `/proc/self/cmdline` must decode to its argument, so a word maps to its argument and no other. Without a mapped
48
+ * word, the text of an argument is its bytes unless it holds a U+FFFD on a system whose paths are bytes.
49
+ */
50
+ export const argumentBytes = Effect.fn("plan.argumentBytes")(function* (
51
+ args: ReadonlyArray<string>,
52
+ ) {
53
+ const files = yield* PlanFiles;
54
+ // A /proc entry that exists but cannot be read (a sandbox can deny it) counts as no /proc.
55
+ const commandLine = yield* files
56
+ .readBytes(procFile("cmdline"))
57
+ .pipe(Effect.catchTag("FileError", () => Effect.undefined));
58
+ const lost = PATHS_ARE_BYTES && args.some((arg) => arg.includes("\uFFFD"));
59
+ if (commandLine === undefined) {
60
+ const recovered: Recovered<ReadonlyArray<string>> = lost
61
+ ? { ok: false, cause: ARGUMENT_WITHOUT_PROC }
62
+ : { ok: true, value: args.map(asBytes) };
63
+ return recovered;
64
+ }
65
+ // Each word ends with a NUL.
66
+ const words = commandLine.toString("latin1").split("\0").slice(0, -1);
67
+ const tail = args.length === 0 ? [] : words.slice(-args.length);
68
+ const decoded = (word: string): string =>
69
+ Buffer.from(word, "latin1").toString("utf8").replace(REPLACEMENTS, "\uFFFD");
70
+ const matched =
71
+ tail.length === args.length &&
72
+ tail.every((word, index) => decoded(word) === args[index]?.replace(REPLACEMENTS, "\uFFFD"));
73
+ const recovered: Recovered<ReadonlyArray<string>> = matched
74
+ ? { ok: true, value: tail }
75
+ : lost
76
+ ? { ok: false, cause: ARGUMENT_UNMATCHED }
77
+ : { ok: true, value: args.map(asBytes) };
78
+ return recovered;
79
+ });
80
+
81
+ /**
82
+ * The bytes of the working folder of this process: from `/proc/self/cwd`, else from the runtime string when it holds
83
+ * no U+FFFD or the system paths are Unicode, else from the `pwd -P` utility, whose output is the physical working
84
+ * folder that it inherits, read as bytes, without its one trailing newline.
85
+ */
86
+ export const workingFolderBytes = Effect.fn("plan.workingFolderBytes")(function* () {
87
+ const files = yield* PlanFiles;
88
+ const target = yield* files
89
+ .linkTarget(procFile("cwd"))
90
+ .pipe(Effect.catchTag("FileError", () => Effect.undefined));
91
+ if (target !== undefined) {
92
+ const recovered: Recovered<string> = { ok: true, value: target.toString("latin1") };
93
+ return recovered;
94
+ }
95
+ const cwd = process.cwd();
96
+ if (!PATHS_ARE_BYTES || !cwd.includes("\uFFFD")) {
97
+ const recovered: Recovered<string> = { ok: true, value: asBytes(cwd) };
98
+ return recovered;
99
+ }
100
+ const processes = yield* PlanProcess;
101
+ const printed = yield* processes
102
+ .run("pwd", ["-P"], { encoding: "latin1" })
103
+ .pipe(Effect.catchTag("SpawnError", () => Effect.undefined));
104
+ const folder =
105
+ printed?.error === undefined && printed?.status === 0 ? printed.stdout.replace(/\n$/, "") : "";
106
+ const recovered: Recovered<string> = folder.startsWith("/")
107
+ ? { ok: true, value: folder }
108
+ : { ok: false, cause: WORKING_FOLDER_LOST };
109
+ return recovered;
110
+ });
@@ -0,0 +1,341 @@
1
+ /**
2
+ * `docks-kit plan base-blob` and `docks-kit plan checkout-state`: the former shell helpers `base-blob.sh` and
3
+ * `checkout-state.sh`, over git, with their output and exit codes. Paths are byte strings (`bytes.ts`): the arguments
4
+ * and git output keep each byte as one character, and each byte is written back as the same byte. git prints its own
5
+ * errors on stderr, as it did under the shell scripts.
6
+ */
7
+ import path from "node:path";
8
+
9
+ import { Effect } from "effect";
10
+
11
+ import { argumentBytes, utf8Text, workingFolderBytes } from "./bytes";
12
+ import { PlanFiles, PlanProcess, type ProcessOptions, type ProcessResult } from "./services";
13
+ import type { FileError, SpawnError } from "./types";
14
+
15
+ const BASE_BLOB_USAGE = "usage: docks-kit plan base-blob <commit> <path>";
16
+ const CHECKOUT_STATE_USAGE = "usage: docks-kit plan checkout-state <checkout>";
17
+ // The walk follows at most 40 links, as git and Linux do. This also ends a loop.
18
+ const MAX_LINKS = 40;
19
+ const OBJECT_ID = /^[0-9a-f]{40,64}$/;
20
+
21
+ /** `$(command)` of a shell: the output without its trailing newlines. */
22
+ const substituted = (result: ProcessResult): string => result.stdout.replace(/\n+$/, "");
23
+
24
+ const printError = (line: string): Effect.Effect<void> =>
25
+ Effect.sync(() => {
26
+ process.stderr.write(`${line}\n`);
27
+ });
28
+
29
+ /** Run git, with its stderr passed through. A git that could not start prints why. */
30
+ const runGit = Effect.fn("plan.runGit")(function* (
31
+ args: ReadonlyArray<string>,
32
+ options: ProcessOptions = {},
33
+ ) {
34
+ const processes = yield* PlanProcess;
35
+ const result = yield* processes.run("git", args, {
36
+ ...options,
37
+ encoding: "latin1",
38
+ inheritStderr: true,
39
+ });
40
+ if (result.error) yield* printError(`git: ${result.error.message}`);
41
+ return { result, ok: result.error === undefined && result.status === 0 };
42
+ });
43
+
44
+ /**
45
+ * The tree-ish of the root of `<commit>` (a byte string), or undefined when git fails. A commit that is UTF-8 text
46
+ * goes to git as the argument, as under the shell script. Other bytes cannot pass on a command line, so git reads
47
+ * `<commit>^{tree}` from stdin and prints the tree id.
48
+ */
49
+ const rootTree = Effect.fn("plan.rootTree")(function* (commit: string) {
50
+ const text = utf8Text(commit);
51
+ if (text !== undefined) return text;
52
+ const resolved = yield* runGit(["cat-file", "--batch-check=%(objectname)"], {
53
+ input: Buffer.from(`${commit}^{tree}\n`, "latin1"),
54
+ });
55
+ if (!resolved.ok) return undefined;
56
+ const line = substituted(resolved.result);
57
+ if (OBJECT_ID.test(line)) return line;
58
+ // git prints `<name> missing` or `<name> ambiguous`, with the bytes of the name.
59
+ yield* Effect.sync(() => {
60
+ process.stderr.write(Buffer.from(`base-blob: ${line}\n`, "latin1"));
61
+ });
62
+ return undefined;
63
+ });
64
+
65
+ /** The mode and object id of a tree entry. */
66
+ interface TreeEntry {
67
+ readonly mode: string;
68
+ readonly oid: string;
69
+ }
70
+
71
+ /**
72
+ * The entry `name` of the tree `tree` (a commit names its root tree), undefined when the tree has no such entry, or
73
+ * 2 when git fails. `ls-tree -z` prints each name unquoted, as its raw bytes, so the name compares byte for byte, and
74
+ * no path passes to git.
75
+ */
76
+ const treeEntry = Effect.fn("plan.treeEntry")(function* (tree: string, name: string) {
77
+ const listed = yield* runGit(["ls-tree", "-z", "--full-tree", tree]);
78
+ if (!listed.ok) return 2 as const;
79
+ // A record is `<mode> <type> <object id><tab><name>`.
80
+ for (const record of listed.result.stdout.split("\0")) {
81
+ const tab = record.indexOf("\t");
82
+ if (tab < 0 || record.slice(tab + 1) !== name) continue;
83
+ const [mode = "", , oid = ""] = record.slice(0, tab).split(" ");
84
+ const entry: TreeEntry = { mode, oid };
85
+ return entry;
86
+ }
87
+ return undefined;
88
+ });
89
+
90
+ /**
91
+ * `base-blob <commit> <path>`: print the blob id of the file `<path>` in the tree of `<commit>`, as a checkout of
92
+ * `<commit>` would open it, and return 0. The arguments are read as bytes. The walk reads one path part at a time and
93
+ * looks it up in the listing of the tree that it has reached, by object id. A folder link and a file link resolve
94
+ * from the folder that holds the link, and `..` goes to the parent of the real folder that the walk has reached.
95
+ * Exit 1: absent (a missing path, a folder, a submodule, a file with more path parts after it, a link with an empty,
96
+ * absolute, or outside target, or more than 40 links). Exit 2: a git failure, wrong arguments, or an argument whose
97
+ * bytes cannot be recovered (a U+FFFD without /proc, see `bytes.ts`).
98
+ */
99
+ export const baseBlob = Effect.fn("plan.baseBlob")(function* (args: ReadonlyArray<string>) {
100
+ if (args.length !== 2 || !args[0]) {
101
+ yield* printError(BASE_BLOB_USAGE);
102
+ return 2;
103
+ }
104
+ const bytes = yield* argumentBytes(args);
105
+ if (!bytes.ok) {
106
+ yield* printError(`base-blob: ${bytes.cause}`);
107
+ return 2;
108
+ }
109
+ const [commit = "", target = ""] = bytes.value;
110
+ // The root, resolved at the first lookup, then the object id of each folder that the walk has entered; `..` drops
111
+ // the last one.
112
+ let root: string | undefined;
113
+ const trees: Array<string> = [];
114
+ let rest = target;
115
+ let links = 0;
116
+ while (rest !== "") {
117
+ let part: string;
118
+ const slash = rest.indexOf("/");
119
+ // A part after a slash stays, so that `file/` and a link to `dir/` keep a part.
120
+ if (slash >= 0) {
121
+ part = rest.slice(0, slash);
122
+ rest = rest.slice(slash + 1) || ".";
123
+ } else {
124
+ part = rest;
125
+ rest = "";
126
+ }
127
+ if (part === "" || part === ".") continue;
128
+ if (part === "..") {
129
+ if (trees.length === 0) return 1;
130
+ trees.pop();
131
+ continue;
132
+ }
133
+ root ??= yield* rootTree(commit);
134
+ if (root === undefined) return 2;
135
+ const entry = yield* treeEntry(trees.at(-1) ?? root, part);
136
+ if (entry === 2) return 2;
137
+ if (entry === undefined) return 1;
138
+ switch (entry.mode) {
139
+ case "040000":
140
+ trees.push(entry.oid);
141
+ break;
142
+ case "120000": {
143
+ links += 1;
144
+ if (links > MAX_LINKS) return 1;
145
+ const blob = yield* runGit(["cat-file", "blob", entry.oid]);
146
+ if (!blob.ok) return 2;
147
+ // The raw bytes of the target; its trailing newlines are part of its name.
148
+ const linkTarget = blob.result.stdout;
149
+ if (linkTarget === "" || linkTarget.startsWith("/")) return 1;
150
+ rest = rest ? `${linkTarget}/${rest}` : linkTarget;
151
+ break;
152
+ }
153
+ case "100644":
154
+ case "100755":
155
+ if (rest) return 1;
156
+ yield* Effect.sync(() => {
157
+ process.stdout.write(`${entry.oid}\n`);
158
+ });
159
+ return 0;
160
+ default:
161
+ return 1;
162
+ }
163
+ }
164
+ return 1;
165
+ });
166
+
167
+ /** The sorted listing lines of a checkout, or the exit code of a failed listing. */
168
+ type Listing = ReadonlyArray<string> | 1 | 2;
169
+
170
+ /** The links of one checkout-state run: their private scratch folder, made at the first link, and their count. */
171
+ interface GitFolders {
172
+ folder: string | undefined;
173
+ links: number;
174
+ }
175
+
176
+ /**
177
+ * A path that git takes on its command line for the absolute folder `bytes`: the folder itself when its bytes are
178
+ * UTF-8, otherwise a link with an ASCII name, in the scratch folder of the run, whose target holds the bytes. git
179
+ * runs in the real folder, so a path that it prints keeps its bytes.
180
+ */
181
+ const gitFolder = Effect.fn("plan.gitFolder")(function* (folders: GitFolders, bytes: string) {
182
+ const text = utf8Text(bytes);
183
+ if (text !== undefined) return text;
184
+ const files = yield* PlanFiles;
185
+ const folder = folders.folder ?? (yield* files.scratchFolder("plan-git-folders"));
186
+ folders.folder = folder;
187
+ const link = path.join(folder, String(folders.links));
188
+ folders.links += 1;
189
+ yield* files.symlink(Buffer.from(bytes, "latin1"), link);
190
+ return link;
191
+ });
192
+
193
+ /** `"<path>"` as `git hash-object --stdin-paths` reads a C-quoted path, so a quote, backslash, or CR keeps its byte. */
194
+ const quotedPath = (file: string): string =>
195
+ `"${file.replace(/[\\"]/g, "\\$&").replace(/\r/g, "\\r")}"`;
196
+
197
+ /** The listing of the checkout that holds the folder `checkout`, a path that git takes (see `gitFolder`). */
198
+ const checkoutListing: (
199
+ checkout: string,
200
+ folders: GitFolders,
201
+ ) => Effect.Effect<Listing, FileError | SpawnError, PlanProcess | PlanFiles> = Effect.fn(
202
+ "plan.checkoutListing",
203
+ )(function* (checkout: string, folders: GitFolders) {
204
+ const files = yield* PlanFiles;
205
+ const env = { ...process.env, LC_ALL: "C" };
206
+ const top = yield* runGit(["-C", checkout, "rev-parse", "--show-toplevel"], { env });
207
+ if (!top.ok) return 2;
208
+ const topPath = substituted(top.result);
209
+ const topFolder = yield* gitFolder(folders, topPath);
210
+ const listed = yield* runGit(
211
+ ["-C", topFolder, "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
212
+ { env },
213
+ );
214
+ if (!listed.ok) return 2;
215
+ if (/[\t\n]/.test(listed.result.stdout)) {
216
+ yield* printError("checkout-state: a path holds a tab or a newline");
217
+ return 1;
218
+ }
219
+ // An untracked repository is listed as `<path>/`. An unmerged path is listed once per stage; one line stays.
220
+ const names = listed.result.stdout.split("\0");
221
+ names.pop();
222
+ const paths = [...new Set(names.map((name) => name.replace(/\/$/, "")))].sort();
223
+ const lines: Array<string> = [];
224
+ const regular: Array<string> = [];
225
+ const executable: Array<string> = [];
226
+ for (const name of paths) {
227
+ const file = `${topPath}/${name}`;
228
+ const entry = yield* files.entry(Buffer.from(file, "latin1"));
229
+ switch (entry.kind) {
230
+ case "link":
231
+ if (entry.target.includes("\n")) {
232
+ yield* printError("checkout-state: a link target holds a newline");
233
+ return 1;
234
+ }
235
+ lines.push(`${name}\tlink\t${entry.target}`);
236
+ break;
237
+ case "file":
238
+ regular.push(name);
239
+ executable.push(entry.executable ? "x" : "");
240
+ break;
241
+ case "directory": {
242
+ const folder = yield* gitFolder(folders, file);
243
+ // A folder that is not a checkout gives the toplevel of the outer checkout.
244
+ const sub = yield* runGit(["-C", folder, "rev-parse", "--show-toplevel"], { env });
245
+ if (!sub.ok) return 2;
246
+ if (substituted(sub.result) !== file) {
247
+ lines.push(`${name}\tspecial`);
248
+ break;
249
+ }
250
+ const head = yield* runGit(["-C", folder, "rev-parse", "HEAD"], { env });
251
+ if (!head.ok) return 2;
252
+ lines.push(`${name}\tsubmodule\t${substituted(head.result)}`);
253
+ // The status of the submodule listing is the status of this listing.
254
+ const nested = yield* checkoutListing(folder, folders);
255
+ if (nested === 1 || nested === 2) return nested;
256
+ for (const line of nested) lines.push(`${name}/${line}`);
257
+ break;
258
+ }
259
+ case "special":
260
+ lines.push(`${name}\tspecial`);
261
+ break;
262
+ case "missing":
263
+ lines.push(`${name}\tmissing`);
264
+ break;
265
+ }
266
+ }
267
+ if (regular.length > 0) {
268
+ // One hash-object process reads all regular files, with the raw bytes on disk and no filter.
269
+ const input = Buffer.from(regular.map((name) => `${quotedPath(name)}\n`).join(""), "latin1");
270
+ const hashed = yield* runGit(
271
+ ["-C", topFolder, "hash-object", "--no-filters", "--stdin-paths"],
272
+ { env, input },
273
+ );
274
+ if (!hashed.ok) return 2;
275
+ const blobs = hashed.result.stdout.split("\n");
276
+ regular.forEach((name, index) =>
277
+ lines.push(`${name}\t${blobs[index] ?? ""}\t${executable[index]}`.replace(/\t$/, "")),
278
+ );
279
+ }
280
+ // Each character is one byte, so the default order is the byte order of `LC_ALL=C sort`.
281
+ return lines.sort();
282
+ });
283
+
284
+ /** The listing of the checkout that holds the argument `checkout`; the links of the run go away at its end. */
285
+ const listCheckout = Effect.fn("plan.listCheckout")(function* (checkout: string) {
286
+ const bytes = yield* argumentBytes([checkout]);
287
+ if (!bytes.ok) {
288
+ yield* printError(`checkout-state: ${bytes.cause}`);
289
+ return 1 as const;
290
+ }
291
+ let folderBytes = bytes.value[0] ?? "";
292
+ // A relative path that is UTF-8 goes to git as it is, and git resolves it from the working folder that it inherits;
293
+ // other bytes reach git through a link, whose target must be absolute.
294
+ if (utf8Text(folderBytes) === undefined && !path.isAbsolute(folderBytes)) {
295
+ const working = yield* workingFolderBytes();
296
+ if (!working.ok) {
297
+ yield* printError(`checkout-state: ${working.cause}`);
298
+ return 1 as const;
299
+ }
300
+ folderBytes = `${working.value}/${folderBytes}`;
301
+ }
302
+ return yield* Effect.acquireUseRelease(
303
+ Effect.sync((): GitFolders => ({ folder: undefined, links: 0 })),
304
+ (folders) =>
305
+ gitFolder(folders, folderBytes).pipe(
306
+ Effect.flatMap((folder) => checkoutListing(folder, folders)),
307
+ ),
308
+ ({ folder }) =>
309
+ folder === undefined ? Effect.void : PlanFiles.use((files) => files.removeFolder(folder)),
310
+ );
311
+ });
312
+
313
+ /**
314
+ * `checkout-state <checkout>`: print the state on disk of each cached or untracked, not ignored path of the checkout
315
+ * that holds `<checkout>`, one sorted line per path, and return 0. Lines: `<path>\t<blob id>[\tx]` for a regular file
316
+ * (raw bytes, `x` when executable), `<path>\tlink\t<target>`, `<path>\tsubmodule\t<head>` followed by the lines of the
317
+ * submodule under `<path>/`, `<path>\tmissing`, and `<path>\tspecial`. Paths keep their bytes, also when they are not
318
+ * UTF-8. Exit 1: a path with a tab or a newline, a link target with a newline, or a `<checkout>` whose bytes cannot
319
+ * be recovered (a U+FFFD without /proc, see `bytes.ts`). Exit 2: a failed command or wrong arguments. A failure
320
+ * prints nothing on stdout.
321
+ */
322
+ export const checkoutState = Effect.fn("plan.checkoutState")(function* (
323
+ args: ReadonlyArray<string>,
324
+ ) {
325
+ if (args.length !== 1 || !args[0]) {
326
+ yield* printError(CHECKOUT_STATE_USAGE);
327
+ return 2;
328
+ }
329
+ const listing = yield* listCheckout(args[0]).pipe(
330
+ Effect.catchTags({
331
+ FileError: (error) => printError(error.message).pipe(Effect.as(2 as const)),
332
+ SpawnError: (error) => printError(error.message).pipe(Effect.as(2 as const)),
333
+ }),
334
+ );
335
+ if (listing === 1 || listing === 2) return listing;
336
+ const output = Buffer.from(listing.map((line) => `${line}\n`).join(""), "latin1");
337
+ yield* Effect.sync(() => {
338
+ process.stdout.write(output);
339
+ });
340
+ return 0;
341
+ });