@turri-dev/cli 0.5.0 → 0.5.1-next.4bafdf3

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.
@@ -0,0 +1,124 @@
1
+ import { basename } from "node:path";
2
+ import { Text, truncateToWidth } from "@earendil-works/pi-tui";
3
+ import { spinner } from "./terminal-marks.js";
4
+ import { skillProgressLine } from "./skill-progress.js";
5
+ /**
6
+ * A capture's progress above the chat's input, as its agent says it with capture_progress (the core's `captureProgress`
7
+ * events): its plan's phases on the first line, as a skill's are drawn - the ones done ticked, the one it is in turning
8
+ * - and under it the bar across the whole capture, what it is on and how long it has run.
9
+ *
10
+ * capture app ✓ Plan the modules ━━━━ ⠋ Write the modules ──── ○ Check the scenarios phase 2 of 3
11
+ *
12
+ * ██████████▍░░░░░░░░░░░░░ 43% module 4, orders · 3 of 12 · 12m 30s
13
+ *
14
+ * A blank line under the phases and one under the bar give it room, apart from pi's working line below it.
15
+ * The spinner stops while the agent's turn is over - it is asking the person, or was stopped - and the line says it
16
+ * waits. Before the agent gives a plan, the first line is the spinner and the capture's name alone.
17
+ */
18
+ const PLAIN = { heading: (t) => t, done: (t) => t, now: (t) => t, muted: (t) => t };
19
+ /** The cells of the bar. */
20
+ const BAR_CELLS = 24;
21
+ /** A cell's eighths, as the bar fills it: a part done is drawn to an eighth of a cell. */
22
+ const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];
23
+ /** The current phase's mark while the agent's turn is over. */
24
+ const PAUSED = "‖";
25
+ /** `40s`, `2m 10s`, `1h 05m`. */
26
+ export function duration(ms) {
27
+ const seconds = Math.max(0, Math.floor(ms / 1000));
28
+ if (seconds < 60)
29
+ return `${seconds}s`;
30
+ const minutes = Math.floor(seconds / 60);
31
+ if (minutes < 60)
32
+ return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
33
+ return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
34
+ }
35
+ /** `fraction` of the bar, 0 to 1, filled to an eighth of a cell: what is done in its colour, the rest muted. */
36
+ export function progressBar(fraction, style = PLAIN, cells = BAR_CELLS) {
37
+ const eighths = Math.round(Math.min(1, Math.max(0, fraction)) * cells * 8);
38
+ const full = Math.floor(eighths / 8);
39
+ const part = EIGHTHS[eighths % 8];
40
+ const rest = cells - full - (part === "" ? 0 : 1);
41
+ return style.done("█".repeat(full) + part) + style.muted("░".repeat(rest));
42
+ }
43
+ /** The progress as lines across `width`, the spinner at `frame` and the clock at `now`: the phases, the bar, a blank line after each. */
44
+ export function captureProgressLines(progress, at, style = PLAIN) {
45
+ const { phases, current } = progress;
46
+ const titles = phases.map((phase) => phase.title);
47
+ const head = skillProgressLine({ skill: `capture ${basename(progress.root)}`, phases: titles, current, attempt: 1, frame: progress.working ? at.frame : PAUSED }, at.width, style);
48
+ const finished = current >= 0 && current >= phases.length;
49
+ const on = finished ? "done" : (progress.doing ?? titles[current] ?? (phases.length === 0 ? "making its plan" : "about to start"));
50
+ const counts = !finished && progress.done !== undefined && progress.total !== undefined ? ` · ${progress.done} of ${progress.total}` : "";
51
+ const waiting = !progress.working && !finished ? " · waiting" : "";
52
+ const percent = `${String(Math.floor(progress.fraction * 100)).padStart(3)}%`;
53
+ const bar = ` ${progressBar(progress.fraction, style)} ${style.heading(percent)} ${progress.working ? style.now(on) : on}${style.muted(`${counts}${waiting} · ${duration(at.now - progress.started)}`)}`;
54
+ return [head, "", truncateToWidth(bar, at.width, "…"), ""];
55
+ }
56
+ const CAPTURE_WIDGET = "turri-capture";
57
+ /** A capture's progress above the chat's input; null takes it off. */
58
+ export function captureProgress(ui, progress) {
59
+ if (!progress)
60
+ return ui.setWidget(CAPTURE_WIDGET, undefined);
61
+ ui.setWidget(CAPTURE_WIDGET, (tui, theme) => {
62
+ const redraw = setInterval(() => tui.requestRender(), 1000);
63
+ redraw.unref?.();
64
+ const style = {
65
+ heading: (text) => theme.bold(theme.fg("accent", text)),
66
+ done: (text) => theme.fg("success", text),
67
+ now: (text) => theme.bold(theme.fg("accent", text)),
68
+ muted: (text) => theme.fg("muted", text),
69
+ };
70
+ return {
71
+ render: (width) => captureProgressLines(progress, { frame: spinner(Date.now()), now: Date.now(), width }, style),
72
+ invalidate: () => { },
73
+ dispose: () => clearInterval(redraw),
74
+ };
75
+ });
76
+ }
77
+ /** A capture_progress call in the transcript, from its result: one line where it gave a plan or started a phase, else nothing - the bar shows it. */
78
+ export function progressCallLine(details) {
79
+ if (details === undefined)
80
+ return undefined;
81
+ const lines = [
82
+ ...(details.plan !== undefined ? [`capture plan: ${details.plan.map((title, at) => `${at + 1}. ${title}`).join(" ")}`] : []),
83
+ ...(details.started !== undefined ? [`capture phase ${details.started.phase} of ${details.started.of}: ${details.started.title}`] : []),
84
+ ];
85
+ return lines.length > 0 ? lines.join("\n") : undefined;
86
+ }
87
+ /** capture_progress drawn as its result's line, or not at all: the agent calls it as often as the work moves. */
88
+ export function registerCaptureProgressCalls(pi) {
89
+ const nothing = { render: () => [], invalidate: () => { } };
90
+ const renderers = {
91
+ renderShell: "self",
92
+ renderCall: () => nothing,
93
+ renderResult: (result, _options, theme) => {
94
+ const details = result.details;
95
+ const line = details?.failed === true ? undefined : progressCallLine(details);
96
+ return line === undefined ? nothing : new Text(theme.fg("muted", line), 1, 0);
97
+ },
98
+ };
99
+ pi.registerToolRenderer((name, next) => (name === "capture_progress" ? renderers : next()));
100
+ }
101
+ /**
102
+ * A capture's progress as lines for a log - `turri capture` writes them to stderr, unattended: one as the plan is given,
103
+ * a phase starts, or what it is on changes, never the same twice.
104
+ */
105
+ export function progressLogger(write) {
106
+ let last = "";
107
+ return (progress) => {
108
+ if (progress === null)
109
+ return;
110
+ const { phases, current } = progress;
111
+ const percent = `${Math.floor(progress.fraction * 100)}%`;
112
+ const line = phases.length === 0
113
+ ? undefined
114
+ : current < 0
115
+ ? `capture: a plan of ${phases.length} phases - ${phases.map((phase) => phase.title).join(", ")}`
116
+ : current >= phases.length
117
+ ? "capture: every phase done - 100%"
118
+ : `capture: phase ${current + 1} of ${phases.length}, ${phases[current].title} - ${percent}${progress.doing !== undefined ? ` - ${progress.doing}` : ""}${progress.done !== undefined && progress.total !== undefined ? ` (${progress.done} of ${progress.total})` : ""}`;
119
+ if (line === undefined || line === last)
120
+ return;
121
+ last = line;
122
+ write(line);
123
+ };
124
+ }
@@ -146,6 +146,7 @@ export function driveTerminal(terminal, options = {}) {
146
146
  await rebind.apply(this, args);
147
147
  screen = this;
148
148
  runtime = this.runtimeHost;
149
+ terminal.leave = () => void this.shutdown();
149
150
  bound();
150
151
  };
151
152
  // Signed in or out - pi says how many providers it has again: every chat put on harness-model, where it can be now.
package/dist/cli.js CHANGED
@@ -15,11 +15,13 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
15
15
  return path;
16
16
  };
17
17
  import { spawnSync } from "node:child_process";
18
+ import { tmpdir } from "node:os";
18
19
  import { dirname, join } from "node:path";
19
20
  import { fileURLToPath } from "node:url";
20
21
  import { CLI_ROOT, extensionInstalledGlobally, themesInstalledGlobally, versionLine } from "./cli-root.js";
21
22
  import { dropNoise } from "./quiet.js";
22
23
  import { describeVersion } from "./turri-versions.js";
24
+ import { REOPEN_FILE_ENV, takeReopening } from "./reopen.js";
23
25
  /**
24
26
  * Start pi with this project's extension and themes already wired in.
25
27
  *
@@ -55,23 +57,35 @@ function chat(args) {
55
57
  // in as well: pi-launch.ts is told, and leaves it to that. turri doctor offers to remove the file.
56
58
  const inPi = extensionInstalledGlobally();
57
59
  const themes = themesInstalledGlobally() ? [] : ["--theme", join(CLI_ROOT, ".pi", "themes")];
58
- // turri's own theme, unless this run names another. For this run only: pi's settings
59
- // are left as they are, so a plain `pi` keeps its theme.
60
- const useTheme = args.some((arg) => arg === "--use-theme" || arg.startsWith("--use-theme=")) ? [] : ["--use-theme", DEFAULT_THEME];
61
- // Fullscreen: pi owns the viewport, so the conversation stays where it is scrolled to while the
62
- // jobs redraw - in the terminal's own scrollback, every redraw pulls it back to the bottom.
63
- const tuiMode = args.some((arg) => arg === "--tui-mode" || arg.startsWith("--tui-mode=")) ? [] : ["--tui-mode", "fullscreen"];
64
- // A condition passed directly to node (rather than through NODE_OPTIONS) must reach the chat too.
65
- const conditions = import.meta.resolve("@turri-dev/core/project").endsWith(".ts") ? ["--conditions=turri-source"] : [];
66
- // The models named - --harness-model, --coding-model - are the chat's to read (chat-models.ts): pi's arguments with them.
67
- const result = spawnSync(process.execPath, [...conditions, launcher, ...themes, ...useTheme, ...tuiMode, ...args], {
68
- stdio: "inherit",
69
- env: {
70
- ...process.env,
71
- ...(inPi ? { TURRI_EXTENSION_IN_PI: "1" } : {}),
72
- },
73
- });
74
- process.exit(result.status ?? 1);
60
+ // A chat that quits asking to open again elsewhere - after a capture, in the project it wrote - writes where in this
61
+ // file, and is started again there, as the first was (reopen.ts).
62
+ const reopenFile = join(tmpdir(), `turri-reopen-${process.pid}.json`);
63
+ let run = { cwd: process.cwd(), args, env: {} };
64
+ for (;;) {
65
+ // turri's own theme, unless this run names another. For this run only: pi's settings
66
+ // are left as they are, so a plain `pi` keeps its theme.
67
+ const useTheme = run.args.some((arg) => arg === "--use-theme" || arg.startsWith("--use-theme=")) ? [] : ["--use-theme", DEFAULT_THEME];
68
+ // Fullscreen: pi owns the viewport, so the conversation stays where it is scrolled to while the
69
+ // jobs redraw - in the terminal's own scrollback, every redraw pulls it back to the bottom.
70
+ const tuiMode = run.args.some((arg) => arg === "--tui-mode" || arg.startsWith("--tui-mode=")) ? [] : ["--tui-mode", "fullscreen"];
71
+ // A condition passed directly to node (rather than through NODE_OPTIONS) must reach the chat too.
72
+ const conditions = import.meta.resolve("@turri-dev/core/project").endsWith(".ts") ? ["--conditions=turri-source"] : [];
73
+ // The models named - --harness-model, --coding-model - are the chat's to read (chat-models.ts): pi's arguments with them.
74
+ const result = spawnSync(process.execPath, [...conditions, launcher, ...themes, ...useTheme, ...tuiMode, ...run.args], {
75
+ stdio: "inherit",
76
+ cwd: run.cwd,
77
+ env: {
78
+ ...process.env,
79
+ ...run.env,
80
+ [REOPEN_FILE_ENV]: reopenFile,
81
+ ...(inPi ? { TURRI_EXTENSION_IN_PI: "1" } : {}),
82
+ },
83
+ });
84
+ const next = takeReopening(reopenFile);
85
+ if (next === undefined)
86
+ process.exit(result.status ?? 1);
87
+ run = { cwd: next.dir, args: next.args, env: next.env };
88
+ }
75
89
  }
76
90
  const COMMANDS = {
77
91
  regenerate: { module: "./regenerate-cli.ts", blurb: "regenerate a module and its chain from the spec as it is (with module:func-ids: regenerate those again)" },
@@ -1,6 +1,6 @@
1
1
  import { getMarkdownTheme, UserMessageComponent } from "@earendil-works/pi-coding-agent";
2
- import { Box, Text } from "@earendil-works/pi-tui";
3
- import { COMMAND_OUTCOME, SKILL_MESSAGE_ENTRY, SIDE_ENTRY, SKILL_RUN_ENTRY, JOB_ENTRY, HISTORY_ENTRY, JOBS_LIST_ENTRY, MILESTONE_ENTRY, INTERVIEW_ENTRY } from "@turri-dev/core";
2
+ import { Box, Markdown, Text } from "@earendil-works/pi-tui";
3
+ import { CAPTURE_REPORT_MESSAGE, COMMAND_OUTCOME, SKILL_MESSAGE_ENTRY, SIDE_ENTRY, SKILL_RUN_ENTRY, JOB_ENTRY, HISTORY_ENTRY, JOBS_LIST_ENTRY, MILESTONE_ENTRY, INTERVIEW_ENTRY } from "@turri-dev/core";
4
4
  import { PANEL_KEY } from "./terminal-marks.js";
5
5
  /**
6
6
  * A skill's question as the transcript keeps it: who asked, what it said before asking - a brief to confirm, the choices
@@ -39,6 +39,13 @@ export function registerEntries(pi) {
39
39
  });
40
40
  // The sentinel's notices, their answers and its conclusions are the inbox's (terminal-notifications.ts): answered and
41
41
  // read there, and the chat says each conclusion in its own words. No renderer: pi draws none of them in the chat.
42
+ // The report of the capture that wrote this project, in the first chat opened here after it: Markdown, as the agent wrote it.
43
+ pi.registerMessageRenderer(CAPTURE_REPORT_MESSAGE, (message) => {
44
+ const text = typeof message.content === "string" ? message.content : message.content.map((part) => (part.type === "text" ? part.text : "")).join("");
45
+ const box = new Box(1, 0);
46
+ box.addChild(new Markdown(text, 0, 0, getMarkdownTheme()));
47
+ return box;
48
+ });
42
49
  pi.registerEntryRenderer(SKILL_RUN_ENTRY, (entry, _options, theme) => {
43
50
  const data = entry.data;
44
51
  if (data === undefined)
package/dist/pi-launch.js CHANGED
@@ -20,7 +20,9 @@ import { clientInfo } from "./cli-root.js";
20
20
  import { setProcessTurri } from "./extension.js";
21
21
  import { takeOverSettings } from "./pi-settings.js";
22
22
  import { adoptAsBound } from "./print-mode.js";
23
+ import { progressLogger } from "./capture-progress.js";
23
24
  import { quietBrandThemeOverrides } from "./pi-themes.js";
25
+ import { takeCaptured } from "./reopen.js";
24
26
  import { createTerminal } from "./terminal-view.js";
25
27
  /**
26
28
  * pi, started the way its own CLI starts it, for `turri`.
@@ -85,10 +87,13 @@ if (interactive) {
85
87
  restore = true;
86
88
  }
87
89
  const terminal = createTerminal();
90
+ const captured = takeCaptured();
88
91
  turri = await createTurri({
89
92
  frontend: { ...terminal.frontend, sessions: driveTerminal(terminal, { restore }) },
90
93
  client: clientInfo("chat"),
91
94
  overrides,
95
+ // Opened again in the project a capture wrote (reopen.ts): its summary, drawn in the first chat.
96
+ ...(captured !== undefined ? { captured } : {}),
92
97
  });
93
98
  terminal.attach(turri);
94
99
  }
@@ -98,6 +103,11 @@ else {
98
103
  const mode = args.find((arg) => arg.startsWith("--mode="))?.slice("--mode=".length) ?? (modeAt !== -1 ? args[modeAt + 1] : undefined) ?? "print";
99
104
  turri = await createTurri({ client: clientInfo(mode), overrides, persist: false });
100
105
  adoptAsBound(turri);
106
+ // `turri capture`, unattended: how far the capture has got, a line on stderr as it moves - stdout is the agent's answer.
107
+ if (mode === "print") {
108
+ const logProgress = progressLogger((line) => process.stderr.write(`${line}\n`));
109
+ turri.on("captureProgress", (event) => logProgress(event.progress));
110
+ }
101
111
  }
102
112
  setProcessTurri(turri);
103
113
  // turri built into pi here, in this process, rather than loaded from a file. An older turri installed into every pi
package/dist/reopen.js ADDED
@@ -0,0 +1,68 @@
1
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ /**
3
+ * turri opened again in another folder, in the same terminal, once its chat has quit: a chat works on the project of
4
+ * the folder it was opened in, and after a capture the work is in another - `plain/`, a project of its own. `turri`
5
+ * (cli.ts) starts the chat as a process of its own, with turri's theme, its screen and the folder's models, and names
6
+ * it a file to write in: a chat that is to open again elsewhere writes where, with what, and quits; `turri` reads it and
7
+ * starts the chat there as it started the first. The terminal asks for it as it hears a capture is done (`captureDone`,
8
+ * terminal-view.ts); the chat opened again shows the capture's report (`createTurri({ captured })`). The handoff is the
9
+ * CLI's own, between its two processes: the core knows nothing of it.
10
+ */
11
+ /** The file the chat `turri` started writes where it is to open again. */
12
+ export const REOPEN_FILE_ENV = "TURRI_CLI_REOPEN_FILE";
13
+ /** Said to the chat opened again after a capture, at its start: what the capture said of itself. */
14
+ export const CAPTURED_ENV = "TURRI_CLI_CAPTURED";
15
+ /** Whether this chat can open again in another folder: `turri` started it. */
16
+ export function canReopen(env = process.env) {
17
+ return (env[REOPEN_FILE_ENV] ?? "") !== "";
18
+ }
19
+ /** Ask `turri` to open the chat again in `dir` once it has quit - the caller quits it. False when it cannot (`canReopen`). */
20
+ export function reopenIn(dir, options = {}) {
21
+ const file = process.env[REOPEN_FILE_ENV];
22
+ if (file === undefined || file === "")
23
+ return false;
24
+ const reopening = { dir, args: options.args ?? [], env: options.env ?? {} };
25
+ writeFileSync(file, JSON.stringify(reopening));
26
+ return true;
27
+ }
28
+ /** What the chat that quit asked for, taken - its file removed - or undefined when it asked for nothing. */
29
+ export function takeReopening(file) {
30
+ let text;
31
+ try {
32
+ text = readFileSync(file, "utf8");
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ rmSync(file, { force: true });
38
+ try {
39
+ const parsed = JSON.parse(text);
40
+ if (typeof parsed.dir !== "string" || !Array.isArray(parsed.args) || parsed.args.some((arg) => typeof arg !== "string"))
41
+ return undefined;
42
+ const env = Object.fromEntries(Object.entries(parsed.env ?? {}).filter((entry) => typeof entry[1] === "string"));
43
+ return { dir: parsed.dir, args: parsed.args, env };
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ /** What the chat opened again after a capture is told at its start, in its environment. */
50
+ export function capturedEnv(summary) {
51
+ return { [CAPTURED_ENV]: JSON.stringify({ summary }) };
52
+ }
53
+ /** The capture a chat opened again after it tells - taken from its environment, once - or undefined when it is not that chat. */
54
+ export function takeCaptured(env = process.env) {
55
+ const told = env[CAPTURED_ENV];
56
+ delete env[CAPTURED_ENV];
57
+ if (told === undefined)
58
+ return undefined;
59
+ try {
60
+ const parsed = JSON.parse(told);
61
+ return typeof parsed.summary === "string" ? { summary: parsed.summary } : undefined;
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ }
67
+ /** What the person is asked once a capture in the chat is done - yes or no: the chat's agent has said where it is, and how to open it later. */
68
+ export const CAPTURE_OPEN_QUESTION = "Open turri in the newly captured ***plain project?";
@@ -40,6 +40,8 @@ export function skillProgressLine(progress, width, style = PLAIN) {
40
40
  function whereItIs(progress) {
41
41
  if (progress.current < 0)
42
42
  return "starting";
43
+ if (progress.current >= progress.phases.length)
44
+ return "done";
43
45
  return `phase ${progress.current + 1} of ${progress.phases.length}${progress.attempt > 1 ? `, attempt ${progress.attempt}` : ""}`;
44
46
  }
45
47
  /** Each phase as it is drawn: done ticked, the one it is in marked, the rest to come. */
@@ -6,7 +6,9 @@ import { createChatUi } from "./chat-ui.js";
6
6
  import { registerEntries } from "./entry-renderers.js";
7
7
  import { makePanel, registerNotifications, registerPanelKey, terminalAsk } from "./panel-view.js";
8
8
  import { openPiSettings } from "./pi-settings.js";
9
+ import { canReopen, CAPTURE_OPEN_QUESTION, capturedEnv, reopenIn } from "./reopen.js";
9
10
  import { skillProgress } from "./skill-progress.js";
11
+ import { captureProgress, registerCaptureProgressCalls } from "./capture-progress.js";
10
12
  import { TerminalNotifications } from "./terminal-notifications.js";
11
13
  /**
12
14
  * The terminal: turri's session as pi's screen shows it - one chat at a time, the others working behind it, regen in a
@@ -89,6 +91,19 @@ export function createTerminal() {
89
91
  const text = outOfReachLine(outOfReach);
90
92
  ui.setWidget(OUT_OF_REACH_WIDGET, (_tui, theme) => ({ render: (width) => [truncateToWidth(theme.fg("warning", text), width, "…")], invalidate() { } }));
91
93
  };
94
+ /**
95
+ * A capture in `chat` wrote a project of its own and is done (`captureDone`): turri closes here and opens again there -
96
+ * `turri` started this chat, and the person says yes - where the capture's report is shown.
97
+ */
98
+ const openCaptured = async (chat, dir, summary) => {
99
+ const ui = drawOn(chat);
100
+ if (!canReopen() || terminal.leave === undefined || ui === undefined)
101
+ return;
102
+ if ((await ui.select(CAPTURE_OPEN_QUESTION, ["Yes", "No"])) !== "Yes")
103
+ return;
104
+ if (reopenIn(dir, { env: capturedEnv(summary) }))
105
+ terminal.leave();
106
+ };
92
107
  const terminal = {
93
108
  get turri() {
94
109
  return turri();
@@ -127,6 +142,15 @@ export function createTerminal() {
127
142
  skillProgress(ui, event.progress);
128
143
  break;
129
144
  }
145
+ case "captureProgress": {
146
+ const ui = drawOn(event.chat);
147
+ if (ui !== undefined)
148
+ captureProgress(ui, event.progress);
149
+ break;
150
+ }
151
+ case "captureDone":
152
+ void openCaptured(event.chat, event.plainDir, event.summary);
153
+ break;
130
154
  case "outOfReach":
131
155
  showOutOfReach(event.chat, event.outOfReach);
132
156
  break;
@@ -195,6 +219,7 @@ export function createTerminal() {
195
219
  .catch((error) => terminal.notify(error instanceof Error ? error.message : String(error), "warning"));
196
220
  },
197
221
  panel: undefined,
222
+ leave: undefined,
198
223
  frontend: undefined,
199
224
  };
200
225
  terminal.panel = makePanel(terminal, () => {
@@ -204,7 +229,8 @@ export function createTerminal() {
204
229
  });
205
230
  terminal.frontend = {
206
231
  surface: TERMINAL_SURFACE,
207
- // In every chat, after turri's own: the entries drawn, the banner, the side panel's key, /notifications and /chat.
232
+ // In every chat, after turri's own: the entries drawn, the banner, the side panel's key, /notifications, /chat and
233
+ // capture_progress's calls, drawn as a line where they say something new.
208
234
  extensions: [
209
235
  (pi) => {
210
236
  registerEntries(pi);
@@ -212,6 +238,7 @@ export function createTerminal() {
212
238
  registerPanelKey(pi, terminal.panel);
213
239
  registerNotifications(pi, terminal.panel);
214
240
  registerChats(pi, terminal);
241
+ registerCaptureProgressCalls(pi);
215
242
  },
216
243
  ],
217
244
  // A question of no chat's - a skill run's, a start over - is put in the chat shown.
package/docs/capture.md CHANGED
@@ -17,8 +17,8 @@ The chat's own agent does the capture, there in the chat, from a map of the code
17
17
  The harness does what needs no model, then hands the work to the agent (`src/capture/`):
18
18
 
19
19
  1. **The checks.** The path must be a folder, and the folder the \*\*\*plain goes into - `<path>/plain`, or `--into` - must be new, empty, or a capture started before. A config in use that does not parse stops it, since the captured project starts as that config.
20
- 2. **The project.** `config.turri.yaml` is written once: the config in use where the capture was started - your models, thinking, reviews, limits - without what was that project's own (its `module`, testing scripts, `base-folder` and `test-dir`), with `conformance-tests: true` and the models the session was opened with. With no config in use, `init-config`'s. A `.gitignore` keeps the regenerated code's histories out.
21
- 3. **The map** (`map.ts`), in a second or two even for a hundred thousand lines. Every file of the codebase - what git sees, in a repo; every file but dependencies, caches and turri's own elsewhere - is sorted into code, tests and the rest. Each code file is parsed with [Tree-sitter](#the-map): its definitions, each with its header and lines; the code files it uses, from its imports resolved as its language would; and the tests that use it. Then the code in the order it is built - each file after the files it uses - cut into proposed modules of about 400 lines and slices of about 1,000, and the budget. It is written to `plain/.turri/capture/map.md`, and as data to `map.json`.
20
+ 2. **The project.** `config.turri.yaml` is written once: the config in use where the capture was started - your models, thinking, reviews, limits - without what was that project's own (its `module`, testing scripts, `base-folder` and `test-dir`) and without what turri does not read - a key it no longer has dropped, an old name of a renamed key written under its new one - with `conformance-tests: true` and the models the session was opened with. With no config in use, `init-config`'s. A `.gitignore` keeps the regenerated code's histories out.
21
+ 3. **The map** (`map.ts`), in a second or two even for a hundred thousand lines. Every file of the codebase - what git sees, in a repo; every file but dependencies, caches and turri's own elsewhere - is sorted into code, tests and the rest. Each code file is parsed with [Tree-sitter](#the-map): its definitions, each with its header and lines; the code files it uses, from its imports resolved as its language would; and the tests that use it. Then the code in the order it is built - each file after the files it uses - cut into slices of about 1,000 lines for writers. How many modules and functional specs capture it, the map does not say: that is the agent's to judge. It is written to `plain/.turri/capture/map.md`, and as data to `map.json`.
22
22
  4. **The brief.** The chat's agent is told what to capture into where, what must hold, the level the \*\*\*plain is written at, the map's summary, what it has, ways that work, and when it is done (`genome/prompts/capture/capture.md`). It is told hints, never steps: what it reads, in what order, what it plans and keeps on disk, and whether it has help are its own.
23
23
 
24
24
  What must hold:
@@ -26,10 +26,11 @@ What must hold:
26
26
  - The codebase is read, never written: the agent writes only in the captured project.
27
27
  - The \*\*\*plain says what the code does now - not what it should, nor what its docs claim. Every fact comes from the code, its tests or running it; behaviour that looks wrong is captured as it is, and said in the report.
28
28
  - Every \*\*\*plain rule holds: the chat and every sub-agent have them all in their system prompts.
29
+ - The testing scripts are written in the background while the agent captures, never waited for: as soon as the first module parses - it writes that one first - it starts both skills with `cultivate`, `implement-unit-testing-script` and `implement-conformance-testing-script` side by side, for that module - `cultivate` runs a skill for a module of another project in that project, so each writes its script there and names it in that project's config - and goes on. A part on a stack of its own has its own `config.turri.<module>.yaml` and its own scripts, started as its first module parses. They are no phase of its plan.
29
30
 
30
31
  **The level**, where captures most often go wrong: the \*\*\*plain is the software as its users see it - what goes in and comes out, the interface, outputs, messages, errors, the state it keeps. It never names a private function, an internal class or its fields, or the algorithm or library the code happens to use, unless the interface shows it - what callers call or import, what the original's tests use, what an output depends on: a functional spec another implementation with the same interface would fail says too much. It is far shorter than the code - what an operation achieves, not each step it takes - and exact where the interface is.
31
32
 
32
- What it has: the map, `map.md`, to plan from without reading every file and to check the \*\*\*plain against; the working folder, `plain/.turri/capture/`, for whatever it keeps - the chat's conversation is summed up as it grows, and what is on disk is what is kept; `subagent`, for helpers and writers side by side ([sub-agents](#sub-agents)); `capture_coverage` ([coverage](#coverage)); `parse`; and `cultivate`, for the testing scripts.
33
+ What it has: the map, `map.md`, to plan from without reading every file and to check the \*\*\*plain against; the working folder, `plain/.turri/capture/`, for whatever it keeps - the chat's conversation is summed up as it grows, and what is on disk is what is kept; `subagent`, for helpers and writers side by side ([sub-agents](#sub-agents)); `capture_coverage` ([coverage](#coverage)); `parse`; `cultivate`, for the testing scripts; and `submit_capture`, to end it ([how it ends](#how-it-ends)).
33
34
 
34
35
  **Ways that work** - hints, not steps, like a skill's: the agent takes what helps the codebase and leaves the rest.
35
36
 
@@ -38,24 +39,46 @@ What it has: the map, `map.md`, to plan from without reading every file and to c
38
39
  - Read a small codebase whole, several files a call; a large one module by module, from the map.
39
40
  - Pin the interface early - a linked resource listing it exactly - and the import modules; then the modules, in build order.
40
41
  - Hand a sub-agent a subtask that would cost time or context: studying the original's tests, an edge case of the code, code the map could not parse, checking a module's scenarios against the original - several side by side while the chat goes on.
41
- - Writers, for a codebase too large to read and hold whole - most past some ten thousand lines of code: a sub-agent for each slice of the map, about 1,000 lines of code - small, so its conversation stays small, since every call reads it all again - all started in one turn, each writing in a folder of the working folder and returning what it wrote. The chat tells each the level, the interface its modules cover and what the modules before it define, reads what each returns against the whole before it lands - a concept defined once, behaviour specified once - and copies it in, editing what does not fit, never typing it out again. Below that size, writers cost more time than they save: each spends minutes getting to know its part, and sees only that part.
42
+ - Writers, for a codebase too large to read and hold whole - most past some ten thousand lines of code: a sub-agent for each slice of the map, about 1,000 lines of code - small, so its conversation stays small, since every call reads it all again - all started in one turn, each writing in a folder of the working folder and returning what it wrote. The chat tells each the level, the modules its code goes into, the interface they cover and what the modules before them define, reads what each returns against the whole before it lands - a concept defined once, behaviour specified once - and copies it in, editing what does not fit, never typing it out again. Below that size, writers cost more time than they save: each spends minutes getting to know its part, and sees only that part.
42
43
  - Check scenarios in batches, never one at a time - past a few modules, by sub-agents side by side, each a few modules' scenarios on its copy - and each check written once, as the scenario, never again in a harness.
43
44
  - Review the work with sub-agents only when the capture is too large to hold; a small one is checked as it is written.
44
45
  - Send the tool calls that do not wait on each other in one turn: they run side by side, and every turn waits for the model to start answering.
45
- - Start the testing scripts as soon as the first module parses: they run in the background.
46
46
 
47
47
  It is done when:
48
48
 
49
- 1. **The modules**, each one concern of about 400 lines of code, require each other in a chain - each builds only on what is before it, the code that runs everything last - and the stack, the conventions and the shared concepts are import modules in `plain/template`, each defined once.
49
+ 1. **The modules**, each one concern, require each other in a chain - each builds only on what is before it, the code that runs everything last - and the stack, the conventions and the shared concepts are import modules in `plain/template`, each defined once.
50
50
  2. **What the software needs that is not code** - prompts, templates, assets, data, anything it reads as it runs - is copied, at the paths it has, into `plain/base`, named `base-folder: base`, so the regenerated code starts from it ([the base folder](regenerating.md#the-base-folder)); what is not the software - vendored, generated, tooling, docs - is left out.
51
51
  3. **All the code is accounted for**: captured, or left out with why.
52
52
  4. **Every scenario holds**: each functional spec that needs scenarios by the rules has its test plain file, and every scenario has been run on the original, as its conformance test will be, from outside through the interface.
53
53
  5. **The interface is exact**: regenerated, the software must have the same interface - a library's every public function, class and method with its parameters, defaults, results and errors; a server's every route, method, parameter, body, header and status code; a command line's every command, argument and option, each of its names, with its default, output and exit code; a user interface's every screen and control; and for all of them environment variables, configuration files and keys, files read and written, and formats - checked against the definitions the map shows the entry points, the callers and the original's tests reach. A long exact list may be a linked resource.
54
- 6. **The testing scripts** are written, with the skills, `implement-unit-testing-script` then `implement-conformance-testing-script`, for the first module of the captured project - `cultivate` runs a skill for a module of another project in that project, so each writes its script there and names it in that project's config.
55
- 7. **Every module parses**, and the report is written; you are told where it is: turri opened in `plain/` regenerates it.
54
+ 6. **The testing scripts** are written - `submit_capture` waits for any still being written.
55
+ 7. **Every module parses, and every config file does** - a setting changed in a line of its own, every comment line kept whole - and the report is written.
56
+
57
+ Then it calls `submit_capture`, before it tells you anything ([how it ends](#how-it-ends)).
56
58
 
57
59
  **Attended or not.** In a chat, the agent asks you only what the code cannot tell it and what changes the capture, deciding the rest and saying it in the report. Unattended, it never asks.
58
60
 
61
+ ## How far it has got
62
+
63
+ The agent shows you how far the capture has got with `capture_progress` (`src/capture/progress.ts`). First, from the map and before any other work of the capture, it gives its plan: the phases it will go through - planning the modules, writing them, checking the scenarios, the report - each with its share of the work, the longest the largest. Then it moves it as it goes: each phase as it starts it, how many of that phase's items are done - modules written, scenarios checked - and what it is on now. turri works out the fraction of the whole from that - the shares of the phases behind it and the done part of the one it is in - so every front end draws the same bar.
64
+
65
+ - **In the terminal**, above the input: the plan's phases on one line, as a skill's are drawn - the ones done ticked, the one it is in turning, the rest to come - and under it the bar, the percentage, what it is on, the count and how long it has run. The spinner stops, and the line says it waits, while the agent's turn is over - asking you something, or stopped. A call that gives a plan or starts a phase leaves a line in the transcript; the rest only move the bar.
66
+ - **Unattended**, `turri capture` writes a line to stderr as the plan is given, a phase starts or what it is on changes.
67
+ - **A host** hears it as `captureProgress` events for the chat, and draws it as it draws ([the core](core.md)); `null` once the turn that ended the capture is over.
68
+
69
+ The plan and the place are kept in `plain/.turri/capture/progress.json`: a capture that goes on shows where it was, and its agent says the phase it is in, giving the plan again only if it changed. A plan whose every phase was done is a finished run's and is not shown again: a capture gone on with after one starts with no plan, and its agent gives one for what is left.
70
+
71
+ ## How it ends
72
+
73
+ The agent ends the capture with `submit_capture`, giving the report in a few lines - before it tells you anything, so nothing it says is the end of a capture that is not done:
74
+
75
+ 1. **It waits for the testing scripts.** The testing-script skills run in the background; while either is writing its script for the captured project, `submit_capture` waits for it to land.
76
+ 2. **It checks what it can without a model** (`captureUnfinished` in `src/capture/capture.ts`): the report is written, and in this run - a capture gone on with after one that finished has the earlier run's there, which is not this one's; every config file of the captured project parses - read as empty otherwise, it would regenerate nothing; every module parses in its project, with no step of adding tests skipped; and the unit and conformance testing scripts are there for every module. What is not done goes back to the agent, each with what puts it right, and it calls `submit_capture` again once it has.
77
+ 3. **Done, the agent tells you** its summary, the report's path, and that turri opened in `plain/` regenerates it.
78
+ 4. **Every front end is told.** As that turn ends, turri sends `captureDone` - the chat, the codebase, the project, the agent's summary and this run's report - once a run, and never for a turn that ended part-way or was stopped. The terminal asks *Open turri in the newly captured \*\*\*plain project?*, yes or no; on a yes, turri closes here and opens again in `plain/`, where the first chat shows the report - its agent reading it too, so it can be asked about - and `/regenerate` builds it. On a no, `cd plain && turri` opens it later. Unattended, nothing is offered: the summary is the run's last words.
79
+
80
+ An agent's `write` and `edit` - the chat's, the testing-script skills' - never leave a config file that parses not parsing: such an edit is refused and the file put back ([a config that does not parse](config.md#a-config-that-does-not-parse)).
81
+
59
82
  ## The map
60
83
 
61
84
  `mapCodebase` (`src/capture/map.ts`) parses with [Tree-sitter](https://tree-sitter.github.io), through `@vscode/tree-sitter-wasm`: its runtime and grammars are WebAssembly, the same on Linux, macOS and Windows, and loaded only when a map is made. It reads Python, JavaScript, TypeScript and TSX, Go, Java, C#, Rust, Ruby, PHP, C and C++, Bash and PowerShell.
@@ -64,7 +87,7 @@ It is done when:
64
87
  - **Definitions**: functions, classes, methods, interfaces, types - each with its lines and its header, the text up to its body. Members are named after their container, `Greeter.hello`; what is defined inside a function is its own.
65
88
  - **What uses what.** An import is resolved as its language does: a relative path from the importing file, a Python module - `from pkg import loaders` naming the module before the package - a Rust or PHP path, a Go package's folder; an import of a library links nothing. In Python, JavaScript and TypeScript, whose files import everything they use from the codebase, only imports link files; elsewhere - a Go or Java package, Ruby, C - so do the names a file calls, makes and extends, when no more than three files define them and they are not too common to tell apart.
66
89
  - **The build order.** Files that use each other in a loop are kept together, ordered by how few of the others each uses, and said; then each file after the files it uses, reached from what nothing uses. A loop of more than half the code in ten files or more is a knot: the brief has the agent order those by the software's entry points instead.
67
- - **The budget**, from the lines of code alone - not tests, not the rest: about one functional spec for every 50 lines, and 3 more; a module for about 400. A guide, not a target - a capture far outside it says why in its report. The order is cut into slices too, of about 1,000 lines - small, so writers, eight at a time, finish together soon - for when the agent has writers.
90
+ - **Slices.** The order is cut into slices of about 1,000 lines of code, at file boundaries - small, so writers, eight at a time, finish together soon - for when the agent has writers. The map gives no number of modules or functional specs: how the code is cut into those is the agent's.
68
91
 
69
92
  It is a hint, never a gate: a call made by name at runtime or through a framework is not in it. A file no grammar reads, one too large or minified, or one that will not read is listed as not parsed, for the agent to read itself or have a sub-agent read; one with syntax errors is read around them, the lines it could not parse listed. Line counts and the coverage check need no parsing, so a codebase in bad shape is planned all the same - from reading where the map is thin.
70
93
 
@@ -105,10 +128,14 @@ my-app/
105
128
  .turri/capture/ the working files:
106
129
  map.md, map.json the map of the code
107
130
  report.md the report
131
+ progress.json the plan and how far it has got
108
132
  ... whatever else the agent keeps: a plan, writers' folders, notes
133
+ .turri/ledger/ what the capture's chat did, as facts - the ledger
109
134
  ```
110
135
 
111
- **The report** says what was captured, the modules in order, the functional specs against the budget, what was left out and why, every decision, what the agent was unsure of, and what to do next.
136
+ **The original is left as it was.** turri keeps nothing of its own in the folder a session is opened in unless that folder is a turri project - a config file, or `plain_modules/`: no [ledger](using.md#the-ledger), no record of its chats. A chat capturing a codebase records what it does in the project it writes, from `/capture` on. Opened on a codebase that is a turri project, the session keeps its ledger there as it always does - but the capture's chat records into `plain/`.
137
+
138
+ **The report** says what was captured, the modules in order, their functional specs, what was left out and why, every decision, what the agent was unsure of, and what to do next.
112
139
 
113
140
  ## Stopped, run again
114
141
 
@@ -120,7 +147,7 @@ The chat's agent writes the \*\*\*plain on `harness-model`, as the chat always r
120
147
 
121
148
  ## After a capture
122
149
 
123
- 1. **Read the \*\*\*plain and the report,** in turri opened in `plain/`. From now on the \*\*\*plain is the source of truth.
150
+ 1. **Read the \*\*\*plain and the report,** in turri opened in `plain/` - the terminal asks whether to open it there as the capture ends, and its first chat shows the report. From now on the \*\*\*plain is the source of truth.
124
151
  2. **Regenerate,** first module first: `/regenerate`. Any testing script the report says was not written, ask turri for (`implement-unit-testing-script`, `implement-conformance-testing-script`).
125
152
  3. **Compare with the original**: its own tests, the scenarios' conformance tests, a look at what is launched. Each difference becomes a \*\*\*plain change.
126
153
  4. **Abandon the original** once you are satisfied.
package/docs/chats.md CHANGED
@@ -56,7 +56,7 @@ On macOS, `alt` is Option (⌥), and reaches turri only when the terminal sends
56
56
 
57
57
  `turri --continue` (`-c`) opens every chat of the last session here again, in their order - the first of yours shown, the others beside it, the sentinel among them. A plain `turri` starts with one fresh chat and deletes nothing: the chats of the sessions before stay on disk, and `--continue` opens the most recent one's - the last session that recorded a chat.
58
58
 
59
- turri records which chats are open in `.turri/chats.json` - a run a session, each chat with its title and [pi](https://pi.dev)'s saved conversation - and keeps it from piling up:
59
+ turri records which chats are open in `.turri/chats.json` - a run a session, each chat with its title and [pi](https://pi.dev)'s saved conversation - in a turri project only: a folder that is not one, such as a codebase turri was opened on to capture it, is left as it was, and `turri --continue` there reopens nothing. It keeps the record from piling up:
60
60
 
61
61
  - **a chat closed** is gone: out of the record, its conversation deleted - it cannot be resumed;
62
62
  - **a chat nothing was said in** is never recorded;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turri-dev/cli",
3
- "version": "0.5.0",
3
+ "version": "0.5.1-next.4bafdf3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  "dependencies": {
39
39
  "@earendil-works/pi-coding-agent": "1.6.0",
40
40
  "@earendil-works/pi-tui": "1.6.0",
41
- "@turri-dev/core": "0.3.0"
41
+ "@turri-dev/core": "0.3.1-next.26167ca"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^24.0.0",