docks-kit 0.25.0 → 0.27.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 (46) hide show
  1. package/AGENTS.md +12 -10
  2. package/README.md +40 -30
  3. package/cli/dist/docks-kit.js +24701 -0
  4. package/cli/docs/command-guards.md +8 -5
  5. package/cli/docs/install.md +41 -32
  6. package/cli/docs/omp-context.md +1 -1
  7. package/cli/docs/omp-models.md +1 -1
  8. package/cli/docs/overview.md +3 -3
  9. package/cli/docs/platforms.md +8 -8
  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 -66
  22. package/cli/src/engine-native/DESIGN.md +10 -9
  23. package/cli/src/engine-native/os/targets.ts +6 -19
  24. package/cli/src/engine.ts +0 -6
  25. package/cli/src/generated/sotPayload.ts +51 -79
  26. package/cli/src/kitHome.ts +7 -10
  27. package/cli/src/main.ts +12 -4
  28. package/cli/src/plan/bytes.ts +110 -0
  29. package/cli/src/plan/checkout.ts +379 -0
  30. package/cli/src/plan/commands.ts +1192 -0
  31. package/cli/src/plan/github.ts +816 -0
  32. package/cli/src/plan/records.ts +623 -0
  33. package/cli/src/plan/repository.ts +53 -0
  34. package/cli/src/plan/reviews.ts +292 -0
  35. package/cli/src/plan/services.ts +256 -0
  36. package/cli/src/plan/types.ts +164 -0
  37. package/cli/src/skills/commands.ts +142 -0
  38. package/cli/src/skills/config.json +30 -0
  39. package/cli/src/skills/files.ts +74 -0
  40. package/cli/src/skills/frontmatter.ts +148 -0
  41. package/cli/src/skills/guard.ts +366 -0
  42. package/cli/src/skills/kitGate.ts +406 -0
  43. package/cli/src/skills/rubric.ts +143 -0
  44. package/docks-kit +9 -40
  45. package/docks-kit.ps1 +10 -61
  46. package/package.json +10 -8
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Review comments, trusted comments, archive records, and delegation grants. Pure: no process, file, or GitHub
3
+ * access.
4
+ */
5
+ import { liveGoalLines, YOLO_DELEGATION_LINE } from "./records";
6
+ import type { IssueComment, ParentLink } from "./types";
7
+
8
+ export type ReviewKind = "plan" | "code";
9
+ export type Verdict = "pass" | "repair" | "fixes-required" | "blocked";
10
+
11
+ /** The fields of a plan issue that the trust rule reads. */
12
+ export interface CommentSource {
13
+ readonly assignees: ReadonlyArray<{ readonly login: string }>;
14
+ readonly comments: ReadonlyArray<IssueComment>;
15
+ }
16
+
17
+ // Reviewers write Markdown: read review keywords through emphasis, code marks, quotes, and list markers (#49).
18
+ function reviewText(line: string): string {
19
+ return line
20
+ .replace(/[*_`]/g, "")
21
+ .trim()
22
+ .replace(/^(?:>\s*)+/, "")
23
+ .replace(/^(?:[-+]|\d+[.)])\s+/, "")
24
+ .trim();
25
+ }
26
+ const REVIEW_HEADING = /^(?:#+\s*)?(plan|code) review/i;
27
+ const REVIEW_VERDICT = /^(plan|code)[- ]review:\s*([a-z]+(?:-[a-z]+)*)/i;
28
+ const severeFinding = (text: string): boolean =>
29
+ /\[(?:critical|high)\]/i.test(text) ||
30
+ /^(?:critical|high)\s*:/i.test(text) ||
31
+ /^severity\s*:\s*(?:critical|high)\b/i.test(text);
32
+ // One comment can hold several blocks of the same kind, such as the lens blocks of one code-review round (#98).
33
+ // A block starts at the first line or at a later Markdown heading line that names the comment's review kind. A
34
+ // quoted or list-item heading is prose, so a block that quotes an earlier round cannot open a block of its own. A
35
+ // block's verdict is its first verdict line of that kind; later verdict-like lines are prose, such as a quoted
36
+ // verdict of an earlier round. The most severe block verdict wins, so no block can hide another's failure.
37
+ // A heading line has `#` after at most three spaces, so a `*` list marker is not emphasis here; only the title after
38
+ // the `#` markers is read through emphasis and code marks.
39
+ function blockHeadingKind(rawLine: string): string | undefined {
40
+ const heading = /^ {0,3}#+(.*)$/.exec(rawLine);
41
+ if (!heading) return undefined;
42
+ return /^\s*(plan|code) review/i.exec(heading[1].replace(/[*_`]/g, ""))?.[1].toLowerCase();
43
+ }
44
+ const VERDICT_SEVERITY: Readonly<Record<Verdict, number>> = {
45
+ pass: 0,
46
+ repair: 1,
47
+ "fixes-required": 1,
48
+ blocked: 2,
49
+ };
50
+ function verdictFor(kind: ReviewKind, alias: string): Verdict | undefined {
51
+ if (["pass", "ok", "approved"].includes(alias)) return "pass";
52
+ if (["repair", "changes", "fixes-required"].includes(alias))
53
+ return kind === "plan" ? "repair" : "fixes-required";
54
+ return alias === "blocked" ? "blocked" : undefined;
55
+ }
56
+ // The manager's response to round k follows the review blocks of round k+1 in the same comment (E5). The response
57
+ // quotes findings, so the parser reads no block heading, verdict, or severity from its heading line to the end.
58
+ const MANAGER_RESPONSE_HEADING = /^ {0,3}#### Manager response to round \d+[ \t]*$/;
59
+
60
+ export function parseReviewComment(
61
+ body: unknown,
62
+ ): { kind: ReviewKind; verdict: Verdict } | undefined {
63
+ if (typeof body !== "string") return undefined;
64
+ const commentLines = body.trim().split(/\r?\n/);
65
+ const response = commentLines.findIndex(
66
+ (line, index) => index > 0 && MANAGER_RESPONSE_HEADING.test(line),
67
+ );
68
+ const rawLines = response < 0 ? commentLines : commentLines.slice(0, response);
69
+ const lines = rawLines.map(reviewText);
70
+ const heading = REVIEW_HEADING.exec(lines[0]);
71
+ if (!heading) return undefined;
72
+ const kind: ReviewKind = heading[1].toLowerCase() === "plan" ? "plan" : "code";
73
+ const blocks: Array<Array<string>> = [[]];
74
+ for (const [index, line] of lines.entries()) {
75
+ if (index === 0) continue;
76
+ if (blockHeadingKind(rawLines[index]) === kind) blocks.push([]);
77
+ else blocks[blocks.length - 1].push(line);
78
+ }
79
+ const firstVerdict = (block: ReadonlyArray<string>): RegExpExecArray | undefined =>
80
+ block
81
+ .map((line) => REVIEW_VERDICT.exec(line))
82
+ .find((match) => match?.[1].toLowerCase() === kind) ?? undefined;
83
+ // A later block without a verdict line is a heading inside the previous block; the first block needs a verdict.
84
+ const matches = blocks.map(firstVerdict).filter((match, index) => match || index === 0);
85
+ const verdicts: Array<Verdict> = [];
86
+ for (const match of matches) {
87
+ if (!match) return undefined;
88
+ const verdict = verdictFor(kind, match[2].toLowerCase());
89
+ if (verdict === undefined) return undefined;
90
+ verdicts.push(verdict);
91
+ }
92
+ let verdict = verdicts.reduce((worst, next) =>
93
+ VERDICT_SEVERITY[next] > VERDICT_SEVERITY[worst] ? next : worst,
94
+ );
95
+ if (kind === "code" && verdict === "pass" && lines.some(severeFinding))
96
+ verdict = "fixes-required";
97
+ return { kind, verdict };
98
+ }
99
+
100
+ // The comments that the trust rule accepts, oldest first: the issue has one assignee, and that assignee wrote them.
101
+ export function trustedComments(issue: CommentSource): Array<IssueComment> {
102
+ const owners = issue.assignees;
103
+ if (owners.length !== 1) return [];
104
+ return issue.comments
105
+ .map((comment, index) => ({ comment, index }))
106
+ .sort(
107
+ (a, b) =>
108
+ Date.parse(a.comment.createdAt) - Date.parse(b.comment.createdAt) || a.index - b.index,
109
+ )
110
+ .map(({ comment }) => comment)
111
+ .filter((comment) => comment.author?.login === owners[0].login);
112
+ }
113
+
114
+ export function reviewVerdicts(issue: CommentSource): Partial<Record<ReviewKind, Verdict>> {
115
+ const verdicts: Partial<Record<ReviewKind, Verdict>> = {};
116
+ for (const comment of trustedComments(issue)) {
117
+ const review = parseReviewComment(comment.body);
118
+ if (review) verdicts[review.kind] = review.verdict;
119
+ }
120
+ return verdicts;
121
+ }
122
+
123
+ // The archive record that `archive` posts with each successful archive, so that a later recovery knows which archive
124
+ // rule finished the plan (E1). A reopen comment ends the record of the archive before it.
125
+ export const parentRecord = (children: ReadonlyArray<{ readonly number: number }>): string =>
126
+ `Archived as parent: children ${children.map((child) => `#${child.number}`).join(", ")}`;
127
+ export const landingRecord = (pr: number): string => `Archived with landing pull request #${pr}`;
128
+ // A reopen comment of `reopen` or `archive` ends the archive cycle before it.
129
+ const isReopenComment = (comment: IssueComment): boolean =>
130
+ comment.body.trim().startsWith("Reopened: ");
131
+
132
+ export function archiveKind(issue: CommentSource): "parent" | "landing" | undefined {
133
+ let kind: "parent" | "landing" | undefined;
134
+ for (const comment of trustedComments(issue)) {
135
+ const lines = comment.body.split(/\r?\n/).map((line) => line.trim());
136
+ if (isReopenComment(comment)) kind = undefined;
137
+ if (lines.some((line) => /^Archived as parent: children #\d+(?:, #\d+)*$/.test(line)))
138
+ kind = "parent";
139
+ if (lines.some((line) => /^Archived with landing pull request #\d+$/.test(line)))
140
+ kind = "landing";
141
+ }
142
+ return kind;
143
+ }
144
+
145
+ // The trusted comments of the current archive cycle: the ones after the latest trusted reopen comment.
146
+ export function cycleComments(issue: CommentSource): Array<IssueComment> {
147
+ const trusted = trustedComments(issue);
148
+ let reopened = -1;
149
+ trusted.forEach((comment, index) => {
150
+ if (isReopenComment(comment)) reopened = index;
151
+ });
152
+ return trusted.slice(reopened + 1);
153
+ }
154
+
155
+ // Whether the current archive cycle already holds a trusted comment with the line `record`, so that a rerun does not
156
+ // post the record again, while the archive after a reopen gets its own record.
157
+ export const recorded = (issue: CommentSource, record: string): boolean =>
158
+ cycleComments(issue).some((comment) =>
159
+ comment.body.split(/\r?\n/).some((line) => line.trim() === record),
160
+ );
161
+
162
+ // Authority events (contract, Delegated decisions). The parsing is not symmetric because each misreading must fail
163
+ // closed: a wrong `in force` gives the agent authority that the user did not give, and a wrong end only sends the
164
+ // questions back to the user. So a grant's first line must be exact, and a quoted or decorated grant is no event;
165
+ // a revocation's first line is read through emphasis, code marks, and case, so a hand-typed revocation still ends
166
+ // the grant; and a parent that the helper cannot read or check gives no grant.
167
+ const GRANT_EVENT = /^Delegation grant: (?:(yolo): )?(.*\S)$/;
168
+ const PARENT_EVENT = /^Parent event:(.*)$/;
169
+ const DELEGATED_LINE =
170
+ /^Delegated: the user delegated the design and tradeoff decisions to the agent\. User: (.*)$/;
171
+
172
+ export type AuthorityEvent =
173
+ | { readonly id: string; readonly createdAt: string; readonly kind: "revocation" }
174
+ | {
175
+ readonly id: string;
176
+ readonly createdAt: string;
177
+ readonly kind: "yolo" | "delegated";
178
+ readonly quote: string;
179
+ readonly parentEvent: string | undefined;
180
+ };
181
+
182
+ // A quote compares after trimming and without one pair of surrounding double quotes.
183
+ function delegationQuote(quote: string): string {
184
+ const text = quote.trim();
185
+ return /^".*"$/s.test(text) ? text.slice(1, -1) : text;
186
+ }
187
+
188
+ function authorityEvent(comment: IssueComment): AuthorityEvent | undefined {
189
+ const { fullDatabaseId: id, createdAt, body } = comment;
190
+ const revocation = body.trim().split(/\r?\n/)[0].replace(/[*_`]/g, "").trim().toLowerCase();
191
+ if (revocation === "delegation revoked") return { id, createdAt, kind: "revocation" };
192
+ const [first, second = ""] = body.split(/\r?\n/);
193
+ const grant = GRANT_EVENT.exec(first);
194
+ if (!grant) return undefined;
195
+ // A malformed `Parent event:` value still counts as a link, and it never matches a parent event.
196
+ const parentEvent = PARENT_EVENT.exec(second)?.[1].trim();
197
+ return {
198
+ id,
199
+ createdAt,
200
+ kind: grant[1] ? "yolo" : "delegated",
201
+ quote: grant[2],
202
+ parentEvent,
203
+ };
204
+ }
205
+
206
+ export const authorityEvents = (issue: CommentSource): Array<AuthorityEvent> =>
207
+ trustedComments(issue).flatMap((comment) => authorityEvent(comment) ?? []);
208
+
209
+ export interface GrantState {
210
+ readonly line: string;
211
+ readonly advice: ReadonlyArray<string>;
212
+ }
213
+
214
+ /** The plan fields that the grant rule reads. */
215
+ export interface GrantSource extends CommentSource {
216
+ readonly parent: ParentLink | null | undefined;
217
+ }
218
+
219
+ /** The read of the parent plan: its authority events, or a read that failed. */
220
+ export type ParentRead =
221
+ | { readonly kind: "read"; readonly events: ReadonlyArray<AuthorityEvent> }
222
+ | { readonly kind: "unreadable" };
223
+
224
+ // The `grant:` line of `show` and its advice. The plan's latest trusted event decides. A child's grant then holds only
225
+ // while its parent allows it, and the parent is read only for a child whose latest event is a grant. Last, the one
226
+ // live delegation line of Goal must match the deciding event in kind and quote. When the rule needs the parent and
227
+ // `parentRead` is undefined, the result names the parent to read; the caller reads it and calls again.
228
+ export function grantState(
229
+ issue: GrantSource,
230
+ goal: string,
231
+ repositoryName: string,
232
+ parentRead?: ParentRead,
233
+ ): GrantState | { readonly readParent: number } {
234
+ const latest = authorityEvents(issue).at(-1);
235
+ const lines = liveGoalLines(goal)
236
+ .map(({ text }) => text)
237
+ .filter((text) => text === YOLO_DELEGATION_LINE || DELEGATED_LINE.test(text));
238
+ const none = (reason?: string): GrantState => ({
239
+ line: reason ? `grant: none; ${reason}` : "grant: none",
240
+ advice: [],
241
+ });
242
+ if (!latest)
243
+ return none(
244
+ lines.length ? "the Goal delegation line has no trusted authority event" : undefined,
245
+ );
246
+ if (latest.kind === "revocation")
247
+ return { line: `grant: ended by revocation comment ${latest.id}`, advice: [] };
248
+ const { parent } = issue;
249
+ if (!parent && latest.parentEvent !== undefined)
250
+ return none(`comment ${latest.id} names a parent event, but the plan has no parent`);
251
+ if (parent) {
252
+ if (parent.repository.nameWithOwner !== repositoryName)
253
+ return none(
254
+ `parent #${parent.number} is in another repository (${parent.repository.nameWithOwner})`,
255
+ );
256
+ if (parentRead === undefined) return { readParent: parent.number };
257
+ if (parentRead.kind === "unreadable") return none(`parent #${parent.number} cannot be read`);
258
+ const parentLatest = parentRead.events.at(-1);
259
+ // A linked grant holds only while the named event is the parent's latest, whatever the timestamps say; an
260
+ // unlinked grant ends at any parent event that is not older than it. Equal timestamps cannot prove the order, so
261
+ // a parent event with the same time ends the grant too (fail closed).
262
+ const ended =
263
+ latest.parentEvent === undefined
264
+ ? parentLatest !== undefined &&
265
+ Date.parse(parentLatest.createdAt) >= Date.parse(latest.createdAt)
266
+ : parentLatest?.id !== latest.parentEvent;
267
+ if (ended && !parentLatest)
268
+ return none(`parent #${parent.number} has no trusted authority event`);
269
+ if (ended && parentLatest)
270
+ return {
271
+ line: `grant: ended by parent #${parent.number} comment ${parentLatest.id}`,
272
+ advice: lines.length
273
+ ? [
274
+ `parent #${parent.number} comment ${parentLatest.id} ended the grant; remove the delegation line from Goal, with no new event`,
275
+ ]
276
+ : [],
277
+ };
278
+ }
279
+ if (lines.length !== 1)
280
+ return none(
281
+ lines.length
282
+ ? `the Goal has ${lines.length} delegation lines for comment ${latest.id}`
283
+ : `the Goal has no delegation line for comment ${latest.id}`,
284
+ );
285
+ const quote = DELEGATED_LINE.exec(lines[0])?.[1];
286
+ const matches =
287
+ latest.kind === "yolo"
288
+ ? lines[0] === YOLO_DELEGATION_LINE
289
+ : quote !== undefined && delegationQuote(quote) === delegationQuote(latest.quote);
290
+ if (!matches) return none(`the Goal delegation line does not match comment ${latest.id}`);
291
+ return { line: `grant: in force (${latest.kind}) by comment ${latest.id}`, advice: [] };
292
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * The Effect services of `docks-kit plan`: child processes (gh and git), files, waits, and the repository that the
3
+ * latest GitHub read named. The command entry provides `PlanServicesLive`; tests provide their own layers.
4
+ */
5
+ import { spawnSync } from "node:child_process";
6
+ import fs from "node:fs";
7
+
8
+ import { Context, Duration, Effect, Layer, Predicate } from "effect";
9
+
10
+ import { engineHome } from "../engine-native/ompSession";
11
+ import { createScratchDir, scratchRoot } from "../engine-native/scratch";
12
+ import { FileError, SpawnError, type RepositoryInfo } from "./types";
13
+
14
+ // plan.mjs reads gh output up to this size; a larger output is a refusal, not a cut.
15
+ export const MAX_OUTPUT_MIB = 256;
16
+
17
+ export interface ProcessOptions {
18
+ readonly cwd?: string;
19
+ readonly input?: string | Uint8Array;
20
+ /** `latin1` keeps each byte of the output as one character, for byte-exact path output. */
21
+ readonly encoding?: "utf8" | "latin1";
22
+ readonly env?: NodeJS.ProcessEnv;
23
+ /** Pass the child's stderr through to this process, as a shell script does. */
24
+ readonly inheritStderr?: boolean;
25
+ }
26
+
27
+ export interface ProcessResult {
28
+ readonly status: number | null;
29
+ readonly stdout: string;
30
+ readonly stderr: string;
31
+ /** Set when the child could not start or its output passed the limit. */
32
+ readonly error: { readonly code: string | undefined; readonly message: string } | undefined;
33
+ }
34
+
35
+ /** A file path as text, or as raw bytes for a path that is not UTF-8. */
36
+ export type FilePath = string | Buffer;
37
+
38
+ const errorCode = (error: unknown): string | undefined => {
39
+ const code = Predicate.hasProperty(error, "code") ? error.code : undefined;
40
+ return Predicate.isString(code) ? code : undefined;
41
+ };
42
+
43
+ const errorMessage = (error: unknown): string =>
44
+ error instanceof Error ? error.message : String(error);
45
+
46
+ /** Runs a child process with an argv and no shell, and waits for it. */
47
+ export class PlanProcess extends Context.Service<
48
+ PlanProcess,
49
+ {
50
+ readonly run: (
51
+ command: string,
52
+ args: ReadonlyArray<string>,
53
+ options?: ProcessOptions,
54
+ ) => Effect.Effect<ProcessResult, SpawnError>;
55
+ }
56
+ >()("docks-kit/plan/PlanProcess") {
57
+ static readonly layer = Layer.effect(
58
+ PlanProcess,
59
+ Effect.sync(() => {
60
+ const run = Effect.fn("PlanProcess.run")(function* (
61
+ command: string,
62
+ args: ReadonlyArray<string>,
63
+ options: ProcessOptions = {},
64
+ ) {
65
+ const result = yield* Effect.try({
66
+ try: () =>
67
+ spawnSync(command, [...args], {
68
+ encoding: options.encoding ?? "utf8",
69
+ maxBuffer: MAX_OUTPUT_MIB * 1024 * 1024,
70
+ cwd: options.cwd,
71
+ input: options.input,
72
+ env: options.env,
73
+ stdio: ["pipe", "pipe", options.inheritStderr === true ? "inherit" : "pipe"],
74
+ }),
75
+ catch: (error) => new SpawnError({ message: errorMessage(error) }),
76
+ });
77
+ const processResult: ProcessResult = {
78
+ status: result.status,
79
+ stdout: result.stdout ?? "",
80
+ stderr: result.stderr ?? "",
81
+ error:
82
+ result.error === undefined
83
+ ? undefined
84
+ : { code: errorCode(result.error), message: result.error.message },
85
+ };
86
+ return processResult;
87
+ });
88
+ return PlanProcess.of({ run });
89
+ }),
90
+ );
91
+ }
92
+
93
+ const fileOperation = <A>(operation: () => A): Effect.Effect<A, FileError> =>
94
+ Effect.try({
95
+ try: operation,
96
+ catch: (error) => new FileError({ message: errorMessage(error), code: errorCode(error) }),
97
+ });
98
+
99
+ /** What a path of a checkout holds on disk, as the `test` operators of a shell script see it. */
100
+ export type CheckoutEntry =
101
+ | { readonly kind: "link"; readonly target: string }
102
+ | { readonly kind: "file"; readonly executable: boolean }
103
+ | { readonly kind: "directory" }
104
+ | { readonly kind: "special" }
105
+ | { readonly kind: "missing" };
106
+
107
+ function checkoutEntry(path: Buffer): CheckoutEntry {
108
+ let stats: fs.Stats;
109
+ try {
110
+ stats = fs.lstatSync(path);
111
+ } catch {
112
+ return { kind: "missing" };
113
+ }
114
+ if (stats.isSymbolicLink())
115
+ return {
116
+ kind: "link",
117
+ target: fs.readlinkSync(path, { encoding: "buffer" }).toString("latin1"),
118
+ };
119
+ if (stats.isFile()) {
120
+ let executable = true;
121
+ try {
122
+ fs.accessSync(path, fs.constants.X_OK);
123
+ } catch {
124
+ executable = false;
125
+ }
126
+ return { kind: "file", executable };
127
+ }
128
+ return stats.isDirectory() ? { kind: "directory" } : { kind: "special" };
129
+ }
130
+
131
+ /** A file read whose missing file gives undefined. */
132
+ const unlessMissing = <A>(operation: () => A): Effect.Effect<A | undefined, FileError> =>
133
+ fileOperation(() => {
134
+ try {
135
+ return operation();
136
+ } catch (error) {
137
+ if (errorCode(error) === "ENOENT") return undefined;
138
+ throw error;
139
+ }
140
+ });
141
+
142
+ /** File access. A failure carries the Node error message and code. */
143
+ export class PlanFiles extends Context.Service<
144
+ PlanFiles,
145
+ {
146
+ /**
147
+ * What the path holds on disk; the bytes of a link target are latin1 characters. Only a failed link read fails.
148
+ */
149
+ readonly entry: (path: Buffer) => Effect.Effect<CheckoutEntry, FileError>;
150
+ /** The bytes of a file, or undefined when it does not exist. */
151
+ readonly readBytes: (path: string) => Effect.Effect<Buffer | undefined, FileError>;
152
+ /** The target bytes of a symbolic link, or undefined when the link does not exist. */
153
+ readonly linkTarget: (path: string) => Effect.Effect<Buffer | undefined, FileError>;
154
+ /** Create the symbolic link `path` to `target`. */
155
+ readonly symlink: (target: Buffer, path: string) => Effect.Effect<void, FileError>;
156
+ /** Create a private folder under the kit scratch root and return its path. */
157
+ readonly scratchFolder: (label: string) => Effect.Effect<string, FileError>;
158
+ /** Remove a folder and what it holds, without following a link in it. */
159
+ readonly removeFolder: (path: string) => Effect.Effect<void, FileError>;
160
+ /** Create the directory and its parents, and set its mode to 0700. */
161
+ readonly ensurePrivateDirectory: (path: FilePath) => Effect.Effect<void, FileError>;
162
+ /** Write a UTF-8 file; `mode` applies when the write creates it. */
163
+ readonly writeFile: (
164
+ path: FilePath,
165
+ data: string,
166
+ mode?: number,
167
+ ) => Effect.Effect<void, FileError>;
168
+ readonly chmod: (path: FilePath, mode: number) => Effect.Effect<void, FileError>;
169
+ readonly readFile: (path: FilePath) => Effect.Effect<string, FileError>;
170
+ /** Create a new file that must not exist yet, write it, and close it. */
171
+ readonly createExclusive: (
172
+ path: string,
173
+ data: string,
174
+ mode: number,
175
+ ) => Effect.Effect<void, FileError>;
176
+ /** Remove a file; a missing file is no failure. */
177
+ readonly remove: (path: string) => Effect.Effect<void, FileError>;
178
+ }
179
+ >()("docks-kit/plan/PlanFiles") {
180
+ static readonly layer = Layer.effect(
181
+ PlanFiles,
182
+ Effect.sync(() =>
183
+ PlanFiles.of({
184
+ entry: (path) => fileOperation(() => checkoutEntry(path)),
185
+ readBytes: (path) => unlessMissing(() => fs.readFileSync(path)),
186
+ linkTarget: (path) => unlessMissing(() => fs.readlinkSync(path, { encoding: "buffer" })),
187
+ symlink: (target, path) => fileOperation(() => fs.symlinkSync(target, path)),
188
+ scratchFolder: (label) =>
189
+ fileOperation(() => createScratchDir(scratchRoot(engineHome()), label)),
190
+ removeFolder: (path) =>
191
+ fileOperation(() => fs.rmSync(path, { recursive: true, force: true })),
192
+ ensurePrivateDirectory: (path) =>
193
+ fileOperation(() => {
194
+ fs.mkdirSync(path, { recursive: true, mode: 0o700 });
195
+ fs.chmodSync(path, 0o700);
196
+ }),
197
+ writeFile: (path, data, mode) =>
198
+ fileOperation(() =>
199
+ fs.writeFileSync(path, data, mode === undefined ? "utf8" : { encoding: "utf8", mode }),
200
+ ),
201
+ chmod: (path, mode) => fileOperation(() => fs.chmodSync(path, mode)),
202
+ readFile: (path) => fileOperation(() => fs.readFileSync(path, "utf8")),
203
+ createExclusive: (path, data, mode) =>
204
+ fileOperation(() => {
205
+ const descriptor = fs.openSync(path, "wx", mode);
206
+ try {
207
+ fs.writeFileSync(descriptor, data, "utf8");
208
+ } finally {
209
+ fs.closeSync(descriptor);
210
+ }
211
+ }),
212
+ remove: (path) => fileOperation(() => fs.rmSync(path, { force: true })),
213
+ }),
214
+ ),
215
+ );
216
+ }
217
+
218
+ /**
219
+ * The pauses of `reopen` and `archive`, on the Effect clock. With `PLAN_CLI_SKIP_WAITS=1` (a test hook), a pause
220
+ * returns at once and appends its length in milliseconds and a newline to the file that `PLAN_CLI_WAIT_LOG` names.
221
+ */
222
+ export class PlanWaits extends Context.Service<
223
+ PlanWaits,
224
+ { readonly sleep: (milliseconds: number) => Effect.Effect<void, FileError> }
225
+ >()("docks-kit/plan/PlanWaits") {
226
+ static readonly layer = Layer.effect(
227
+ PlanWaits,
228
+ Effect.sync(() => {
229
+ const sleep = Effect.fn("PlanWaits.sleep")(function* (milliseconds: number) {
230
+ if (process.env["PLAN_CLI_SKIP_WAITS"] !== "1")
231
+ return yield* Effect.sleep(Duration.millis(milliseconds));
232
+ const log = process.env["PLAN_CLI_WAIT_LOG"];
233
+ if (log) yield* fileOperation(() => fs.appendFileSync(log, `${milliseconds}\n`));
234
+ });
235
+ return PlanWaits.of({ sleep });
236
+ }),
237
+ );
238
+ }
239
+
240
+ /** The repository that the latest snapshot read named; one per command run. */
241
+ export class PlanRepository extends Context.Service<
242
+ PlanRepository,
243
+ { current: RepositoryInfo | undefined }
244
+ >()("docks-kit/plan/PlanRepository") {
245
+ static readonly layer = Layer.effect(
246
+ PlanRepository,
247
+ Effect.sync(() => PlanRepository.of({ current: undefined })),
248
+ );
249
+ }
250
+
251
+ export const PlanServicesLive = Layer.mergeAll(
252
+ PlanProcess.layer,
253
+ PlanFiles.layer,
254
+ PlanWaits.layer,
255
+ PlanRepository.layer,
256
+ );