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,623 @@
1
+ /**
2
+ * Plan records: parse, normalize, and render a plan body, the export provenance digest, the line diff, the status
3
+ * derivation, and the advice that depends only on the body. Pure: no process, file, or GitHub access.
4
+ */
5
+ import { createHash } from "node:crypto";
6
+
7
+ import { fail, type NamedLabel, type StatusSource } from "./types";
8
+
9
+ export const PLAN_STATUSES: ReadonlySet<string> = new Set([
10
+ "drafting",
11
+ "planned",
12
+ "ongoing",
13
+ "blocked",
14
+ ]);
15
+ export const STEP_STATUSES: ReadonlySet<string> = new Set([
16
+ "planned",
17
+ "in-flight",
18
+ "done",
19
+ "blocked",
20
+ "skipped",
21
+ ]);
22
+ const STEP_EFFECTS: ReadonlySet<string> = new Set([
23
+ "local",
24
+ "probe",
25
+ "production_access",
26
+ "publish",
27
+ "push",
28
+ "release",
29
+ "deploy",
30
+ ]);
31
+ export const STEPS_HEADER = "| # | Id | Task | Files | Depends | Effect | Status | Done when |";
32
+ export const STEPS_SEPARATOR = "|---:|---|---|---|---|---|---|---|";
33
+ export const ACCEPTANCE_HEADER = "| ID | Command | Expected |";
34
+ export const ACCEPTANCE_SEPARATOR = "|---|---|---|";
35
+ export const PLAN_LABELS = [
36
+ "plan",
37
+ "plan:drafting",
38
+ "plan:planned",
39
+ "plan:ongoing",
40
+ "plan:blocked",
41
+ ] as const;
42
+ // A machine path points into a user or root home, a mount, a named temporary or runtime directory,
43
+ // a Windows drive, or a network share. URL routes, slash prose, and portable system paths such as
44
+ // /usr/bin/env or a bare /tmp do not match (#71). The match runs to the next space or delimiter.
45
+ const MACHINE_PATH =
46
+ /(?<=^|[\s("'`[{=:;,>]|file:\/\/)(?:\/(?:home|Users|root|mnt|media|Volumes|run\/(?:user|media))\/[^\s/`'")]|\/(?:private\/)?(?:tmp|var\/tmp)\/[^\s/`'")]|\/(?:private\/)?var\/folders\/|[A-Za-z]:[\\/]|\\\\[\w.$-]+\\[\w.$-])[^\s`'"()[\]{}|,;]*/gm;
47
+ const SECTIONS = [
48
+ "Goal",
49
+ "Research",
50
+ "Steps",
51
+ "Acceptance",
52
+ "Do not touch",
53
+ "Open questions",
54
+ "Verification Results",
55
+ ];
56
+ export const MARKER = "<!-- plan-contract: v5 -->";
57
+ export const LEGACY_MARKER = "<!-- plan-contract: v4 -->";
58
+ // Budgets above the largest plan of this repository (41,607 characters, 17 steps, 22 comments). A plan that passes
59
+ // one gets the advice to split into child plans (E4).
60
+ const BODY_BYTE_BUDGET = 50_000;
61
+ const STEP_BUDGET = 20;
62
+ const COMMENT_BUDGET = 60;
63
+ const RETIRED_SECTIONS: ReadonlySet<string> = new Set(["review"]);
64
+ // A drafted plan holds this placeholder until research is published (#78).
65
+ export const RESEARCH_PLACEHOLDER = "_Not researched yet._";
66
+ // A plan-review pass covers the body that the reviewer read (#78). In a yolo plan, the Mode line and the
67
+ // delegation line record what the yolo invocation decided, not reviewed work, so they need no new round (#111).
68
+ const PLANNED_WORK_SECTIONS = ["Goal", "Research", "Steps", "Acceptance", "Do not touch"];
69
+ export const YOLO_DELEGATION_LINE =
70
+ "Yolo: the user delegated every decision except the merge to the agent.";
71
+ const CONTRACT_MARKER = /^\s*<!-- plan-contract: v([345]) -->/i;
72
+ // A reopen that races GitHub's close can leave an issue closed with reason REOPENED, and GitHub then refuses every
73
+ // state change on it, also in the web page (#90). The derived status stays `unreadable`.
74
+ export const STUCK_ADVICE =
75
+ "GitHub left this issue closed with reason REOPENED and refuses every state change; ask GitHub Support to repair it, and record step results in an issue comment until then";
76
+ // The Done when cell of a parent row (E1).
77
+ const CHILD_ROW = /^child #([1-9]\d*) finished$/;
78
+
79
+ /** One row of the Steps table, with its cells in table order. */
80
+ export interface Step {
81
+ display: string;
82
+ id: string;
83
+ task: string;
84
+ files: string;
85
+ depends: string;
86
+ effect: string;
87
+ status: string;
88
+ doneWhen: string;
89
+ }
90
+
91
+ export interface ParsedPlan {
92
+ readonly sections: Map<string, string>;
93
+ readonly malformedSteps: ReadonlyArray<{ readonly line: number; readonly cells: number }>;
94
+ readonly steps: Array<Step>;
95
+ readonly acceptance: Array<Array<string>>;
96
+ }
97
+
98
+ export interface NormalizeOptions {
99
+ readonly mode?: string | undefined;
100
+ readonly marker?: string;
101
+ }
102
+
103
+ export function blankFencedRegions(text: string): string {
104
+ let fence: string | undefined;
105
+ return text
106
+ .split("\n")
107
+ .map((line) => {
108
+ const openingFence = fence ? undefined : /^ {0,3}(`{3,}|~{3,})/.exec(line);
109
+ if (openingFence) fence = openingFence[1];
110
+ else if (!fence) return line;
111
+ else if (new RegExp(`^ {0,3}${fence[0]}{${fence.length},}[ \\t]*$`).test(line))
112
+ fence = undefined;
113
+ return line.replace(/[^\r]/g, " ");
114
+ })
115
+ .join("\n");
116
+ }
117
+
118
+ export function unquoteCode(value: string): string {
119
+ return /^`[^`]+`$/.test(value) ? value.slice(1, -1) : value;
120
+ }
121
+
122
+ export const token = (value: string): string => unquoteCode(value.trim()).trim().toLowerCase();
123
+ export const stepId = (value: string): string => token(value).replaceAll("-", "_");
124
+ export const terminal = (status: string | undefined): boolean =>
125
+ status === "done" || status === "skipped";
126
+ const trimBlankLines = (text: string): string =>
127
+ text.replace(/^(?:[ \t]*\n)+/, "").replace(/\s+$/, "");
128
+
129
+ export function labelNames(labels: ReadonlyArray<NamedLabel> | undefined): Array<string> {
130
+ return (labels ?? []).map((label) => token(label.name));
131
+ }
132
+
133
+ export const contractVersion = (body: string): number =>
134
+ Number(CONTRACT_MARKER.exec(body)?.[1] ?? 0);
135
+
136
+ function sectionMap(body: string): Map<string, string> {
137
+ const headings = [...blankFencedRegions(body).matchAll(/^ {0,3}##[ \t]+([^\n]+)$/gm)];
138
+ const sections = new Map<string, string>();
139
+ headings.forEach((heading, index) => {
140
+ const title = heading[1].trim();
141
+ const name = SECTIONS.find((known) => known.toLowerCase() === title.toLowerCase());
142
+ if (!name && !RETIRED_SECTIONS.has(title.toLowerCase()))
143
+ fail(
144
+ `unknown section heading: ${title}; use only ${SECTIONS.join(", ")} or write it below an existing section as ### or plain text`,
145
+ );
146
+ const key = name ?? title;
147
+ if (sections.has(key)) fail(`duplicate section heading: ${key}`);
148
+ const start = (heading.index ?? 0) + heading[0].length;
149
+ sections.set(key, trimBlankLines(body.slice(start, headings[index + 1]?.index ?? body.length)));
150
+ });
151
+ return sections;
152
+ }
153
+
154
+ // Split a table row on pipes that are not escaped; a pipe is escaped only when an odd
155
+ // run of backslashes precedes it, so `\\|` is a literal backslash followed by a delimiter.
156
+ function splitCells(row: string): Array<string> {
157
+ const cells: Array<string> = [];
158
+ let cell = "";
159
+ let backslashes = 0;
160
+ for (const char of row) {
161
+ if (char === "|" && backslashes % 2 === 0) {
162
+ cells.push(cell);
163
+ cell = "";
164
+ } else cell += char;
165
+ backslashes = char === "\\" ? backslashes + 1 : 0;
166
+ }
167
+ cells.push(cell);
168
+ if (cells.length > 1 && cells[0].trim() === "") cells.shift();
169
+ if (cells.length > 1 && (cells.at(-1) ?? "").trim() === "") cells.pop();
170
+ return cells;
171
+ }
172
+
173
+ interface Table {
174
+ readonly lines: Array<string>;
175
+ readonly start: number;
176
+ readonly end: number;
177
+ readonly rows: Array<Array<string>>;
178
+ }
179
+
180
+ function table(text: string, header: string): Table {
181
+ const lines = text.split("\n");
182
+ const scan = blankFencedRegions(text)
183
+ .split("\n")
184
+ .map((line) => (/^(?: {4}|\t)/.test(line) ? "" : line));
185
+ const cells = (line: string): Array<string> => splitCells(line.trim()).map((cell) => cell.trim());
186
+ const headerKey = cells(header).map(token).join("|");
187
+ const start = scan.findIndex((line) => cells(line).map(token).join("|") === headerKey);
188
+ if (start < 0) return { lines, start, end: start, rows: [] };
189
+ const isSeparator = (line: string): boolean => cells(line).every((cell) => /^:?-+:?$/.test(cell));
190
+ const first = start + 1 + (scan[start + 1] !== undefined && isSeparator(scan[start + 1]) ? 1 : 0);
191
+ let end = first;
192
+ while (end < scan.length && scan[end].trim().startsWith("|")) end++;
193
+ return { lines, start, end, rows: lines.slice(first, end).map(cells) };
194
+ }
195
+
196
+ export const render = (sections: ReadonlyMap<string, string>, marker = MARKER): string =>
197
+ `${marker}\n\n${SECTIONS.map((name) => `## ${name}\n\n${sections.get(name) ?? ""}`.trimEnd()).join("\n\n")}\n`;
198
+
199
+ export function replaceTable(
200
+ sections: Map<string, string>,
201
+ name: string,
202
+ header: string,
203
+ separator: string,
204
+ rows: ReadonlyArray<ReadonlyArray<string>>,
205
+ ): void {
206
+ const parsed = table(sections.get(name) ?? "", header);
207
+ if (parsed.start < 0) return;
208
+ parsed.lines.splice(
209
+ parsed.start,
210
+ parsed.end - parsed.start,
211
+ header,
212
+ separator,
213
+ ...rows.map((cells) => `| ${cells.join(" | ")} |`),
214
+ );
215
+ sections.set(name, parsed.lines.join("\n"));
216
+ }
217
+
218
+ /** The cells of a step in table order. */
219
+ export const stepCells = (step: Step): Array<string> => [
220
+ step.display,
221
+ step.id,
222
+ step.task,
223
+ step.files,
224
+ step.depends,
225
+ step.effect,
226
+ step.status,
227
+ step.doneWhen,
228
+ ];
229
+
230
+ interface StepRef {
231
+ readonly display: string;
232
+ readonly id: string;
233
+ }
234
+
235
+ // Returns the step that a Depends entry names. An entry is a display, or a step id: normalizePlan keeps the id when
236
+ // the display holds a comma. A display match wins, as in normalizePlan. `steps` holds objects with display and id.
237
+ export const dependencyStep = <S extends StepRef>(
238
+ steps: ReadonlyArray<S>,
239
+ entry: string,
240
+ ): S | undefined =>
241
+ steps.find((step) => step.display === entry) ?? steps.find((step) => step.id === stepId(entry));
242
+
243
+ // The paths of a Files cell.
244
+ export const filePaths = (cell: string): Set<string> =>
245
+ new Set(
246
+ cell
247
+ .split(",")
248
+ .map((part) => unquoteCode(part.trim()).trim())
249
+ .filter((part) => part && part !== "-"),
250
+ );
251
+
252
+ // Steps that edit the same path need a Depends order, or parallel work collides (#78).
253
+ function sharedFilesAdvice(rows: ReadonlyArray<ReadonlyArray<string>>): Array<string> {
254
+ const paths = rows.map((row) => filePaths(row[3]));
255
+ const steps = rows.map(([display, id]) => ({ display, id }));
256
+ const dependencies = new Map(
257
+ rows.map((row) => [
258
+ row[0],
259
+ row[4] === "-"
260
+ ? []
261
+ : row[4]
262
+ .split(",")
263
+ .map((part) => dependencyStep(steps, part.trim())?.display ?? part.trim()),
264
+ ]),
265
+ );
266
+ const reaches = (from: string, to: string, seen = new Set<string>()): boolean => {
267
+ if (seen.has(from)) return false;
268
+ seen.add(from);
269
+ return (dependencies.get(from) ?? []).some((next) => next === to || reaches(next, to, seen));
270
+ };
271
+ const advice: Array<string> = [];
272
+ rows.forEach((row, index) => {
273
+ for (let other = index + 1; other < rows.length; other += 1) {
274
+ const shared = [...paths[index]].filter((entry) => paths[other].has(entry));
275
+ if (shared.length && !reaches(row[0], rows[other][0]) && !reaches(rows[other][0], row[0]))
276
+ advice.push(
277
+ `steps ${row[1]} and ${rows[other][1]} share ${shared.join(", ")} with no Depends link`,
278
+ );
279
+ }
280
+ });
281
+ return advice;
282
+ }
283
+
284
+ export function normalizePlan(
285
+ text: string,
286
+ { mode: explicitMode, marker = MARKER }: NormalizeOptions = {},
287
+ ): { body: string; advice: Array<string> } {
288
+ const advice: Array<string> = [];
289
+ const cleaned = text
290
+ .replace(/\r\n/g, "\n")
291
+ .split("\n")
292
+ .map((line) =>
293
+ (line.includes("\u2014")
294
+ ? line.replaceAll("\u2014", " - ").replace(/ {2,}/g, " ")
295
+ : line
296
+ ).trimEnd(),
297
+ )
298
+ .join("\n");
299
+ const sections = sectionMap(cleaned);
300
+ const goal = sections.get("Goal") ?? "";
301
+ const goalLines = goal.split("\n");
302
+ const modeLines = blankFencedRegions(goal)
303
+ .split("\n")
304
+ .map((line, index) => (/^ {0,3}Mode:/i.test(line) ? index : -1))
305
+ .filter((index) => index >= 0);
306
+ const mode = modeLines.length
307
+ ? /^ {0,3}Mode:\s*(.*?)\s*$/i.exec(goalLines[modeLines[modeLines.length - 1]])
308
+ : undefined;
309
+ const value = (explicitMode ?? mode?.[1] ?? "").toLowerCase();
310
+ const valid = ["plan-only", "plan-and-implement"].includes(value);
311
+ if (!valid) advice.push("Mode defaulted to plan-only; implementation needs an explicit mode.");
312
+ const goalWithoutMode = goalLines.filter((_, index) => !modeLines.includes(index)).join("\n");
313
+ sections.set(
314
+ "Goal",
315
+ trimBlankLines(`${trimBlankLines(goalWithoutMode)}\n\nMode: ${valid ? value : "plan-only"}`),
316
+ );
317
+ const rows = table(sections.get("Steps") ?? "", STEPS_HEADER).rows;
318
+ for (const row of rows) {
319
+ if (row.length !== 8) continue;
320
+ row[1] = stepId(row[1]);
321
+ row[5] = token(row[5]);
322
+ row[6] = token(row[6]);
323
+ if (!STEP_EFFECTS.has(row[5])) advice.push(`unknown Effect: ${row[5]}`);
324
+ if (!STEP_STATUSES.has(row[6])) advice.push(`unknown Status: ${row[6]}`);
325
+ // A done or skipped step does not run again, so it needs no ask.
326
+ if (row[5] !== "local" && !terminal(row[6]))
327
+ advice.push(`step ${row[1]} Effect ${row[5]} needs an in-session ask before it runs.`);
328
+ }
329
+ const numbers = new Map(rows.filter((row) => row.length === 8).map((row) => [row[1], row[0]]));
330
+ const displays = new Set(numbers.values());
331
+ const dependency = (part: string): string => {
332
+ const trimmed = part.trim();
333
+ if (displays.has(trimmed)) return trimmed;
334
+ // Depends is a comma-separated list, so a display that holds a comma cannot replace an id: the next pass would
335
+ // split it into new parts, and the cell would change again.
336
+ const display = numbers.get(stepId(trimmed));
337
+ return display === undefined || display.includes(",") ? trimmed : display;
338
+ };
339
+ for (const row of rows)
340
+ if (row.length === 8)
341
+ row[4] = row[4] === "-" ? "-" : row[4].split(",").map(dependency).join(", ");
342
+ advice.push(...sharedFilesAdvice(rows.filter((row) => row.length === 8)));
343
+ replaceTable(sections, "Steps", STEPS_HEADER, STEPS_SEPARATOR, rows);
344
+ replaceTable(
345
+ sections,
346
+ "Acceptance",
347
+ ACCEPTANCE_HEADER,
348
+ ACCEPTANCE_SEPARATOR,
349
+ table(sections.get("Acceptance") ?? "", ACCEPTANCE_HEADER).rows,
350
+ );
351
+ const machinePaths = new Set(
352
+ Array.from(cleaned.matchAll(MACHINE_PATH), ([match]) => match.replace(/[.:]+$/, "")),
353
+ );
354
+ for (const machinePath of machinePaths)
355
+ advice.push(`body contains an absolute machine path: ${machinePath}`);
356
+ return { body: render(sections, marker), advice };
357
+ }
358
+
359
+ export function parsePlan(text: string): ParsedPlan {
360
+ const { body } = normalizePlan(text);
361
+ const sections = sectionMap(body);
362
+ const steps = table(sections.get("Steps") ?? "", STEPS_HEADER).rows;
363
+ return {
364
+ sections,
365
+ malformedSteps: steps
366
+ .map((row, index) => ({ line: index + 1, cells: row.length }))
367
+ .filter((row) => row.cells !== 8),
368
+ steps: steps
369
+ .filter((row) => row.length === 8)
370
+ .map(([display, id, task, files, depends, effect, status, doneWhen]) => ({
371
+ display,
372
+ id,
373
+ task,
374
+ files,
375
+ depends,
376
+ effect,
377
+ status,
378
+ doneWhen,
379
+ })),
380
+ acceptance: table(sections.get("Acceptance") ?? "", ACCEPTANCE_HEADER).rows,
381
+ };
382
+ }
383
+
384
+ // Compare the whole section: research prose may quote the placeholder.
385
+ export function researchFilled(plan: ParsedPlan): boolean {
386
+ const research = (plan.sections.get("Research") ?? "").trim();
387
+ return research !== "" && research !== RESEARCH_PLACEHOLDER;
388
+ }
389
+
390
+ /** The advice lines that `printAdvice` of plan.mjs prints, without the `advice: ` prefix. */
391
+ export function adviceLines(
392
+ text: string,
393
+ status: string,
394
+ extra: ReadonlyArray<string> = [],
395
+ options: NormalizeOptions = {},
396
+ ): Array<string> {
397
+ const result = normalizePlan(text, options);
398
+ if (status !== "drafting" && !researchFilled(parsePlan(text)))
399
+ result.advice.push("Research is not filled after drafting.");
400
+ return [...result.advice, ...extra];
401
+ }
402
+
403
+ // The trimmed live lines of Goal text with their indexes: a fenced or indented code line is example text.
404
+ export const liveGoalLines = (
405
+ goal: string,
406
+ ): Array<{ readonly index: number; readonly text: string }> =>
407
+ blankFencedRegions(goal)
408
+ .split("\n")
409
+ .flatMap((line, index) => (/^(?: {4}|\t)/.test(line) ? [] : [{ index, text: line.trim() }]));
410
+ // The indexes of the live delegation lines of Goal text. A fenced or indented code line that quotes the delegation
411
+ // line is example text, so it stays reviewed work.
412
+ const liveDelegationLines = (goal: string): Set<number> =>
413
+ new Set(
414
+ liveGoalLines(goal).flatMap(({ index, text }) =>
415
+ text === YOLO_DELEGATION_LINE ? [index] : [],
416
+ ),
417
+ );
418
+ // Normalization ends Goal with its one canonical Mode line. The comparison removes each live delegation line with the
419
+ // blank line that separated it from the text before it, the blank lines that a leading delegation line leaves at the
420
+ // start, and the blank lines at the end. Every other blank line and indentation stays, because example text can
421
+ // depend on them.
422
+ function goalWork(goal: string): string {
423
+ const lines = goal.replace(/(?:^|\n)Mode: [^\n]*$/, "").split("\n");
424
+ const live = liveDelegationLines(lines.join("\n"));
425
+ const kept: Array<string> = [];
426
+ let removedAtStart = false;
427
+ lines.forEach((line, index) => {
428
+ if (live.has(index)) {
429
+ if (kept.length === 0) removedAtStart = true;
430
+ else if (kept[kept.length - 1].trim() === "" && (lines[index + 1] ?? "").trim() === "")
431
+ kept.pop();
432
+ } else if (!(removedAtStart && kept.length === 0 && line.trim() === "")) kept.push(line);
433
+ });
434
+ return kept.join("\n").trimEnd();
435
+ }
436
+
437
+ export function plannedWorkChanges(before: ParsedPlan, after: ParsedPlan): Array<string> {
438
+ const yoloGoal = liveDelegationLines(after.sections.get("Goal") ?? "").size > 0;
439
+ return PLANNED_WORK_SECTIONS.filter((name) => {
440
+ const was = before.sections.get(name) ?? "";
441
+ const now = after.sections.get(name) ?? "";
442
+ return name === "Goal" && yoloGoal ? goalWork(was) !== goalWork(now) : was !== now;
443
+ });
444
+ }
445
+
446
+ export function bodyDigest(body: string): string {
447
+ return createHash("sha256").update(body, "utf8").digest("hex");
448
+ }
449
+
450
+ export function changedLines(before: string, after: string): Array<string> {
451
+ const left = before.split("\n");
452
+ const right = after.split("\n");
453
+ const lengths = Array.from({ length: left.length + 1 }, () => new Uint32Array(right.length + 1));
454
+ for (let i = left.length - 1; i >= 0; i -= 1) {
455
+ for (let j = right.length - 1; j >= 0; j -= 1) {
456
+ lengths[i][j] =
457
+ left[i] === right[j]
458
+ ? lengths[i + 1][j + 1] + 1
459
+ : Math.max(lengths[i + 1][j], lengths[i][j + 1]);
460
+ }
461
+ }
462
+ const changes: Array<string> = [];
463
+ let i = 0;
464
+ let j = 0;
465
+ while (i < left.length || j < right.length) {
466
+ if (i < left.length && j < right.length && left[i] === right[j]) {
467
+ i += 1;
468
+ j += 1;
469
+ } else if (i < left.length && (j === right.length || lengths[i + 1][j] >= lengths[i][j + 1])) {
470
+ changes.push(`-${left[i]}`);
471
+ i += 1;
472
+ } else {
473
+ changes.push(`+${right[j]}`);
474
+ j += 1;
475
+ }
476
+ }
477
+ return changes;
478
+ }
479
+
480
+ export function parseIssueNumber(value: string | undefined, kind = "plan issue"): number {
481
+ const match = /^#?([1-9]\d*)$/.exec(String(value ?? ""));
482
+ if (!match) return fail(`invalid ${kind}: ${value ?? "(missing)"}`);
483
+ return Number(match[1]);
484
+ }
485
+
486
+ /** The flag values of `args`, read in pairs. A repeatable flag collects a list. */
487
+ export interface ParsedOptions {
488
+ readonly values: ReadonlyMap<string, string>;
489
+ readonly lists: ReadonlyMap<string, ReadonlyArray<string>>;
490
+ }
491
+
492
+ export function parseOptions(
493
+ args: ReadonlyArray<string>,
494
+ allowed: ReadonlySet<string>,
495
+ repeatable: ReadonlySet<string> = new Set(),
496
+ ): ParsedOptions {
497
+ const values = new Map<string, string>();
498
+ const lists = new Map<string, Array<string>>();
499
+ for (let index = 0; index < args.length; index += 2) {
500
+ const flag = args[index];
501
+ const value = args[index + 1];
502
+ if (!allowed.has(flag) || value === undefined || (!repeatable.has(flag) && values.has(flag))) {
503
+ fail(`invalid option: ${flag ?? "(missing)"}`);
504
+ }
505
+ if (repeatable.has(flag)) {
506
+ const list = lists.get(flag) ?? [];
507
+ list.push(value);
508
+ lists.set(flag, list);
509
+ } else values.set(flag, value);
510
+ }
511
+ return { values, lists };
512
+ }
513
+
514
+ function statusFromLabels(labels: ReadonlyArray<NamedLabel>): string {
515
+ const statuses = labelNames(labels)
516
+ .filter((label) => label.startsWith("plan:") && PLAN_STATUSES.has(label.slice(5)))
517
+ .map((label) => label.slice(5));
518
+ if (statuses.length === 0) return "unlabelled";
519
+ return statuses.length === 1 ? statuses[0] : "unreadable";
520
+ }
521
+
522
+ export function statusFromIssue(issue: StatusSource): string {
523
+ if (String(issue.state).toUpperCase() !== "CLOSED") return statusFromLabels(issue.labels);
524
+ switch (String(issue.stateReason).toUpperCase()) {
525
+ case "COMPLETED":
526
+ return "finished";
527
+ case "NOT_PLANNED":
528
+ return "retired";
529
+ case "DUPLICATE":
530
+ return "duplicate";
531
+ default:
532
+ return "unreadable";
533
+ }
534
+ }
535
+
536
+ export function stuckClosed(issue: Pick<StatusSource, "state" | "stateReason">): boolean {
537
+ return (
538
+ String(issue.state).toUpperCase() === "CLOSED" &&
539
+ String(issue.stateReason).toUpperCase() === "REOPENED"
540
+ );
541
+ }
542
+
543
+ export function refuseStuck(
544
+ issue: Pick<StatusSource, "state" | "stateReason"> & { readonly number: number },
545
+ ): void {
546
+ if (stuckClosed(issue))
547
+ fail(
548
+ `GitHub left plan #${issue.number} closed with reason REOPENED and refuses every state change; ask GitHub Support to repair it`,
549
+ );
550
+ }
551
+
552
+ /** The `plan:` labels to remove, all but `plan:<target>` when a target is given. */
553
+ export function labelsToRemove(labels: ReadonlyArray<NamedLabel>, target?: string): Array<string> {
554
+ return labels
555
+ .map((label) => label.name)
556
+ .filter(
557
+ (label) => token(label).startsWith("plan:") && (!target || token(label) !== `plan:${target}`),
558
+ );
559
+ }
560
+
561
+ // Whether a label is a phase label: `plan:` and a plan status.
562
+ export const isPhaseLabel = (name: string): boolean =>
563
+ token(name).startsWith("plan:") && PLAN_STATUSES.has(token(name).slice(5));
564
+
565
+ export function headerStrip(
566
+ issue: { readonly number: number; readonly title: string; readonly url: string },
567
+ status: string,
568
+ ): string {
569
+ return `#${issue.number} · ${status} · ${issue.title} · ${issue.url}`;
570
+ }
571
+
572
+ // Each budget that a plan passes gets one advice line (E4).
573
+ export function budgetAdvice(body: string, plan: ParsedPlan, comments: number): Array<string> {
574
+ const bytes = Buffer.byteLength(body, "utf8");
575
+ const steps = plan.steps.length + plan.malformedSteps.length;
576
+ const reasons: Array<string> = [];
577
+ if (bytes > BODY_BYTE_BUDGET) reasons.push(`body is ${bytes} bytes (budget ${BODY_BYTE_BUDGET})`);
578
+ if (steps > STEP_BUDGET) reasons.push(`${steps} steps (budget ${STEP_BUDGET})`);
579
+ if (comments > COMMENT_BUDGET) reasons.push(`${comments} comments (budget ${COMMENT_BUDGET})`);
580
+ return reasons.map((reason) => `split into child plans: ${reason}`);
581
+ }
582
+
583
+ // The helper cannot tell new scope from a repair, so each change of this shape on a started v5 plan gets the advice to
584
+ // move new work into a child plan: a new step, a new path in the Files cell of a step, or a changed Task or Done when.
585
+ export function scopeChanged(before: ParsedPlan, after: ParsedPlan): boolean {
586
+ return after.steps.some((row) => {
587
+ const was = before.steps.find((step) => step.id === row.id);
588
+ if (!was) return true;
589
+ const paths = filePaths(was.files);
590
+ return (
591
+ row.task !== was.task ||
592
+ row.doneWhen !== was.doneWhen ||
593
+ [...filePaths(row.files)].some((entry) => !paths.has(entry))
594
+ );
595
+ });
596
+ }
597
+
598
+ export function refuseMalformedSteps(plan: ParsedPlan): void {
599
+ const [first] = plan.malformedSteps;
600
+ if (first)
601
+ fail(
602
+ `Steps row ${first.line} has ${first.cells} cells; expected 8. Escape a literal pipe as \\| so the row is preserved.`,
603
+ );
604
+ }
605
+
606
+ // The children that the Steps rows of a parent name: every row has Files `-` and Done when `child #<c> finished` (E1).
607
+ // Undefined for a plan without rows or with a row of its own landing work.
608
+ export function parentRowChildren(parsed: ParsedPlan): Array<number> | undefined {
609
+ const named = parsed.steps.map((step) =>
610
+ unquoteCode(step.files.trim()).trim() === "-"
611
+ ? Number(CHILD_ROW.exec(step.doneWhen)?.[1])
612
+ : Number.NaN,
613
+ );
614
+ return named.length > 0 && named.every((child) => !Number.isNaN(child)) ? named : undefined;
615
+ }
616
+
617
+ export function hasClosingKeyword(body: string, number: number, nameWithOwner: string): boolean {
618
+ const repo = nameWithOwner.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
619
+ return new RegExp(
620
+ String.raw`\b(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved):?[ \t]+(?:#|${repo}#)${number}(?![A-Za-z0-9_])`,
621
+ "i",
622
+ ).test(body);
623
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Local folders of `docks-kit plan`: the `docks-review` folder of the git repository that holds the working directory,
3
+ * and the private state folder for the temporary body files of gh writes.
4
+ */
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+
8
+ import { Effect } from "effect";
9
+
10
+ import { workingFolderBytes } from "./bytes";
11
+ import { PlanFiles, PlanProcess } from "./services";
12
+ import { GitError, PlanRefusal } from "./types";
13
+
14
+ /**
15
+ * `git rev-parse --git-path docks-review`, resolved from the working directory, as a byte string (one character per
16
+ * byte): git prints the path as bytes, and the working folder is read as bytes, so a path that is not UTF-8 and a
17
+ * path with a literal U+FFFD both keep their bytes.
18
+ */
19
+ export const reviewDirectory = Effect.fn("plan.reviewDirectory")(function* () {
20
+ const processes = yield* PlanProcess;
21
+ const result = yield* processes.run("git", ["rev-parse", "--git-path", "docks-review"], {
22
+ encoding: "latin1",
23
+ });
24
+ if (result.error?.code === "ENOENT")
25
+ return yield* new GitError({ message: "git is not installed or not on PATH" });
26
+ if (result.error)
27
+ return yield* new GitError({ message: `git rev-parse failed: ${result.error.message}` });
28
+ if (result.status !== 0) {
29
+ const detail = Buffer.from(result.stderr, "latin1").toString("utf8").trim();
30
+ return yield* new GitError({
31
+ message: `git rev-parse failed: ${detail || `exit ${result.status}`}`,
32
+ });
33
+ }
34
+ // ASCII white space only: a trim of all white space would also cut the byte 0xa0 that ends a UTF-8 character.
35
+ const gitPath = result.stdout.replace(/^[\t\n\v\f\r ]+|[\t\n\v\f\r ]+$/g, "");
36
+ if (!gitPath) return yield* new GitError({ message: "git rev-parse failed: empty git path" });
37
+ // An absolute path from git does not need the working folder.
38
+ if (path.isAbsolute(gitPath)) return path.resolve(gitPath);
39
+ const working = yield* workingFolderBytes();
40
+ if (!working.ok) return yield* new PlanRefusal({ message: working.cause });
41
+ return path.resolve(working.value, gitPath);
42
+ });
43
+
44
+ /** `$XDG_STATE_HOME/docks/plan` (default `~/.local/state/docks/plan`), created with mode 0700. */
45
+ export const stateDirectory = Effect.fn("plan.stateDirectory")(function* () {
46
+ const files = yield* PlanFiles;
47
+ const base =
48
+ process.env["XDG_STATE_HOME"] ||
49
+ path.join(process.env["HOME"] || os.homedir(), ".local", "state");
50
+ const directory = path.join(base, "docks", "plan");
51
+ yield* files.ensurePrivateDirectory(directory);
52
+ return directory;
53
+ });