notesoup 0.51.7 → 0.51.9

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.
@@ -3,4 +3,4 @@ export declare const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment
3
3
  /** Claude's boot says history is missing rather than naming tools it cannot serve. */
4
4
  export declare const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
5
5
  /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
6
- export declare const CLAUDE_WARNING_PROMPT = "This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.\nBefore that, put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, end your turn; the reset runs after it.\nBrain emptied in 3\u2026 2\u2026";
6
+ export declare const CLAUDE_WARNING_PROMPT = "This brain is already spent. Whatever lives only in this brain goes with it \u2014 but the notes stay where they are, and history has the rest written down, though digging it back out is on you.\nUse the last of this brain to put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\n- and refresh the stale notes with what has changed since you last wrote them \u2014 the notes the next window gets are the old ones, unless you fix them now\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, end your turn; the reset runs after it.\nBrain emptied in 3\u2026 2\u2026";
@@ -1,15 +1,16 @@
1
1
  import { generateDiffString } from "@earendil-works/pi-coding-agent";
2
2
  import { notesWrite, notesUpdate, notesRead, notesList, notesSearch } from "../../../src/tools/notes.js";
3
3
  import { notesIdentityFromPi } from "./adapter.js";
4
+ import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
4
5
  import { NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
5
6
  function renderDiff(change) {
6
7
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
7
8
  }
8
9
  /** Register the five shared note operations; each one supplies Pi's session identity and nothing else. */
9
10
  export function registerNotesTools(pi) {
10
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
11
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE);
12
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
11
+ registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
12
+ registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
13
+ registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesReadRenderers);
13
14
  registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
14
15
  registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
15
16
  }
@@ -0,0 +1,40 @@
1
+ /** Pi TUI renderers for notesoup's own tools: collapsed one-line slips, expandable bodies. */
2
+ import { type AgentToolResult, type Theme } from "@earendil-works/pi-coding-agent";
3
+ import { type Component } from "@earendil-works/pi-tui";
4
+ import type { Static } from "typebox";
5
+ import { notesReadParameters, notesUpdateParameters, notesWriteParameters } from "../../src/tools/notes.js";
6
+ /** Only the render-context members these renderers read; the host's ToolRenderContext satisfies this. */
7
+ type CallContext<TArgs> = {
8
+ args: TArgs;
9
+ };
10
+ export type NotesWriteArgs = Static<typeof notesWriteParameters>;
11
+ export declare const notesWriteRenderers: {
12
+ renderCall: (args: NotesWriteArgs, theme: Theme) => Component;
13
+ renderResult(result: AgentToolResult<undefined>, options: {
14
+ expanded: boolean;
15
+ }, theme: Theme, context: CallContext<NotesWriteArgs>): Component;
16
+ };
17
+ export type NotesUpdateArgs = Static<typeof notesUpdateParameters>;
18
+ export declare const notesUpdateRenderers: {
19
+ renderCall(args: NotesUpdateArgs, theme: Theme): Component;
20
+ renderResult(result: AgentToolResult<undefined>, options: {
21
+ expanded: boolean;
22
+ }, theme: Theme, context: CallContext<NotesUpdateArgs>): Component;
23
+ };
24
+ export type NotesReadArgs = Static<typeof notesReadParameters>;
25
+ export declare const notesReadRenderers: {
26
+ renderCall: (args: NotesReadArgs, theme: Theme) => Component;
27
+ renderResult(result: AgentToolResult<undefined>, options: {
28
+ expanded: boolean;
29
+ }, theme: Theme): Component;
30
+ };
31
+ export type EmptyBrainArgs = {
32
+ last_word?: string;
33
+ };
34
+ export declare const emptyBrainRenderers: {
35
+ renderCall: (_args: EmptyBrainArgs, theme: Theme) => Component;
36
+ renderResult(result: AgentToolResult<unknown>, _options: {
37
+ expanded: boolean;
38
+ }, theme: Theme, context: CallContext<EmptyBrainArgs>): Component;
39
+ };
40
+ export {};
@@ -0,0 +1,168 @@
1
+ /** Pi TUI renderers for notesoup's own tools: collapsed one-line slips, expandable bodies. */
2
+ import { renderDiff } from "@earendil-works/pi-coding-agent";
3
+ import { Text, TruncatedText, visibleWidth } from "@earendil-works/pi-tui";
4
+ /** Expanded bodies show this many lines before a "more lines" marker; the full text is in the receipt. */
5
+ const EXPANDED_LINE_CAP = 80;
6
+ /** structuredContent is wireResult(outcome): the data itself, or {error, code}. Old sessions may lack it. */
7
+ function wireOf(result) {
8
+ const sc = result.structuredContent;
9
+ if (sc !== null && typeof sc === "object" && !Array.isArray(sc)) {
10
+ const obj = sc;
11
+ if (typeof obj.error === "string")
12
+ return { error: { error: obj.error, code: typeof obj.code === "string" ? obj.code : "error" } };
13
+ return { data: obj };
14
+ }
15
+ return {};
16
+ }
17
+ /** Results without a structured payload (resumed old sessions) fall back to the receipt's first line. */
18
+ function receiptFallback(result, theme) {
19
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
20
+ return new TruncatedText(theme.fg("dim", text.split("\n")[0] ?? ""), 0, 0);
21
+ }
22
+ function errorComponent(theme, error, expanded) {
23
+ if (!expanded)
24
+ return new TruncatedText(theme.fg("error", `${error.code}: ${error.error.split("\n")[0]}`), 0, 0);
25
+ return new Text(theme.fg("error", `${error.code}: ${error.error}`), 0, 0);
26
+ }
27
+ function addressText(theme, address) {
28
+ return theme.fg("accent", address);
29
+ }
30
+ function callLine(theme, tool, target, suffix = "") {
31
+ let line = theme.fg("toolTitle", theme.bold(tool));
32
+ if (target !== undefined && target !== "")
33
+ line += " " + addressText(theme, target);
34
+ if (suffix !== "")
35
+ line += theme.fg("dim", suffix);
36
+ return new TruncatedText(line, 0, 0);
37
+ }
38
+ /** First `+` line of a generateDiffString diff, without its line-number prefix: the sentence just written down. */
39
+ function firstAddedLine(diff) {
40
+ for (const line of diff.split("\n")) {
41
+ const match = /^\+(\s*\d*)?\s?(.*)$/.exec(line);
42
+ if (match)
43
+ return match[2];
44
+ }
45
+ return undefined;
46
+ }
47
+ function boundedLines(text, theme) {
48
+ const lines = text.split("\n");
49
+ if (lines.length <= EXPANDED_LINE_CAP)
50
+ return text;
51
+ return `${lines.slice(0, EXPANDED_LINE_CAP).join("\n")}\n${theme.fg("dim", `… ${lines.length - EXPANDED_LINE_CAP} more lines`)}`;
52
+ }
53
+ export const notesWriteRenderers = {
54
+ renderCall: (args, theme) => callLine(theme, "notes_write", args.address),
55
+ renderResult(result, options, theme, context) {
56
+ const { data, error } = wireOf(result);
57
+ if (error)
58
+ return errorComponent(theme, error, options.expanded);
59
+ if (!data)
60
+ return receiptFallback(result, theme);
61
+ const content = typeof context.args?.content === "string" ? context.args.content : "";
62
+ const qualifier = data.outcome === "created" ? "" : theme.fg("dim", ` · ${data.outcome}`);
63
+ const head = `wrote ${addressText(theme, data.address)}${qualifier}${theme.fg("dim", ` · ${Array.from(content).length} chars`)}`;
64
+ if (!options.expanded)
65
+ return new TruncatedText(head, 0, 0);
66
+ return new Text(`${head}\n\n${boundedLines(content, theme)}`, 0, 0);
67
+ },
68
+ };
69
+ export const notesUpdateRenderers = {
70
+ renderCall(args, theme) {
71
+ let suffix = "";
72
+ if (args.crumpled === true)
73
+ suffix = " · crumple";
74
+ else if (args.crumpled === false)
75
+ suffix = " · restore";
76
+ if (typeof args.rename_to === "string" && args.rename_to !== "")
77
+ suffix += ` → ${args.rename_to}`;
78
+ return callLine(theme, "notes_update", args.address, suffix);
79
+ },
80
+ renderResult(result, options, theme, context) {
81
+ const { data, error } = wireOf(result);
82
+ if (error)
83
+ return errorComponent(theme, error, options.expanded);
84
+ if (!data)
85
+ return receiptFallback(result, theme);
86
+ let head;
87
+ if (context.args?.crumpled === true) {
88
+ head = `✂ crumpled ${theme.strikethrough(theme.fg("dim", data.address))}`;
89
+ }
90
+ else if (context.args?.crumpled === false) {
91
+ head = `restored ${addressText(theme, data.address)}`;
92
+ }
93
+ else if (data.change_kind === "moved") {
94
+ head = `renamed ${theme.fg("dim", data.rename_from ?? "?")}${theme.fg("dim", " → ")}${addressText(theme, data.address)}`;
95
+ }
96
+ else if (data.change_kind === "none") {
97
+ head = theme.fg("dim", "unchanged ") + addressText(theme, data.address);
98
+ }
99
+ else {
100
+ head = `edited ${addressText(theme, data.address)}`;
101
+ const peek = firstAddedLine(data.diff);
102
+ if (peek !== undefined && peek !== "")
103
+ head += theme.fg("dim", " · ") + theme.fg("toolDiffAdded", `+ ${peek}`);
104
+ }
105
+ if (!options.expanded)
106
+ return new TruncatedText(head, 0, 0);
107
+ const parts = [head];
108
+ if (data.diff !== "")
109
+ parts.push("", renderDiff(data.diff));
110
+ if (data.change_kind !== "moved" && data.rename_from !== undefined)
111
+ parts.push(theme.fg("dim", `renamed from ${data.rename_from}`));
112
+ return new Text(parts.join("\n"), 0, 0);
113
+ },
114
+ };
115
+ export const notesReadRenderers = {
116
+ renderCall: (args, theme) => callLine(theme, "notes_read", args.address, args.offset_chars !== undefined && args.offset_chars !== 0 ? ` · offset ${args.offset_chars}` : ""),
117
+ renderResult(result, options, theme) {
118
+ const { data, error } = wireOf(result);
119
+ if (error)
120
+ return errorComponent(theme, error, options.expanded);
121
+ if (!data)
122
+ return receiptFallback(result, theme);
123
+ const truncated = data.next_offset_chars !== null;
124
+ let head = `read ${addressText(theme, data.address)}${theme.fg("dim", ` · ${data.total_chars} chars${truncated ? " · truncated" : ""}`)}`;
125
+ const peek = data.text.split("\n").find((line) => line.trim() !== "");
126
+ if (peek !== undefined)
127
+ head += theme.fg("dim", ` — ${peek.trim()}`);
128
+ if (!options.expanded)
129
+ return new TruncatedText(head, 0, 0);
130
+ const tail = truncated ? `\n${theme.fg("dim", `… continue at offset_chars=${data.next_offset_chars}`)}` : "";
131
+ return new Text(`${head}\n\n${boundedLines(data.text, theme)}${tail}`, 0, 0);
132
+ },
133
+ };
134
+ /** The empty_brain result is the JSON receipt text; there is no structured payload. */
135
+ function emptyBrainPayload(result) {
136
+ try {
137
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
138
+ const parsed = JSON.parse(text);
139
+ if (parsed !== null && typeof parsed === "object")
140
+ return parsed;
141
+ }
142
+ catch { /* a non-JSON receipt renders as a plain line */ }
143
+ return {};
144
+ }
145
+ export const emptyBrainRenderers = {
146
+ renderCall: (_args, theme) => callLine(theme, "empty_brain"),
147
+ renderResult(result, _options, theme, context) {
148
+ const payload = emptyBrainPayload(result);
149
+ if (result.isError || payload.error !== undefined) {
150
+ return new TruncatedText(theme.fg("error", `✂ brain refused to empty — ${payload.error ?? "unknown error"}`), 0, 0);
151
+ }
152
+ if (payload.status === "rollover_already_pending")
153
+ return new TruncatedText(theme.fg("dim", "✂ brain already being emptied"), 0, 0);
154
+ const lastWord = typeof context.args?.last_word === "string" && context.args.last_word !== "" ? context.args.last_word : undefined;
155
+ return {
156
+ invalidate() { },
157
+ render(width) {
158
+ const label = "✂ brain emptied";
159
+ const prefix = "── ";
160
+ const fill = Math.max(2, width - visibleWidth(prefix) - visibleWidth(label) - 1);
161
+ const lines = [theme.fg("dim", `${prefix}${label} ${"─".repeat(fill)}`)];
162
+ if (lastWord !== undefined)
163
+ lines.push(theme.fg("warning", theme.italic(`“${lastWord}”`)));
164
+ return lines;
165
+ },
166
+ };
167
+ },
168
+ };
@@ -4,6 +4,7 @@ import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
6
  import { output } from "./tool-result.js";
7
+ import { emptyBrainRenderers } from "./render.js";
7
8
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
8
9
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
10
  import { buildResetDrafts, LAST_WORD_ADVERTISED_CHARS, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
@@ -209,6 +210,8 @@ export function registerContext(pi, settingsManager) {
209
210
  label: "Empty Brain",
210
211
  description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to stick a tiny note on your forehead for after the wipe.",
211
212
  parameters: Type.Object({ last_word: Type.Optional(Type.String({ description: `A tiny sticky note, at most ${LAST_WORD_ADVERTISED_CHARS} characters. After the wipe it is slapped on your forehead; longer notes are refused.` })) }, { additionalProperties: false }),
213
+ renderCall: emptyBrainRenderers.renderCall,
214
+ renderResult: emptyBrainRenderers.renderResult,
212
215
  async execute(_id, params, _signal, _update, ctx) {
213
216
  if (!enabled)
214
217
  return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
@@ -1,5 +1,5 @@
1
1
  /** Pi transport for host-neutral operations. */
2
- import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
2
+ import { type ExtensionAPI, type ExtensionToolContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
3
  import type { Static, TSchema } from "typebox";
4
4
  import { type Operation, type Outcome } from "../../src/tools/result.js";
5
5
  /** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
@@ -18,5 +18,7 @@ export type ToolNamespace = {
18
18
  };
19
19
  export declare const NOTES_NAMESPACE: ToolNamespace;
20
20
  export declare const HISTORY_NAMESPACE: ToolNamespace;
21
+ /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
22
+ export type OperationRenderers<TParams extends TSchema> = Pick<ToolDefinition<TParams, undefined>, "renderCall" | "renderResult">;
21
23
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
22
- export declare function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(pi: ExtensionAPI, operation: Operation<TParams, TData, TRest>, run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>, namespace?: ToolNamespace): void;
24
+ export declare function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(pi: ExtensionAPI, operation: Operation<TParams, TData, TRest>, run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>, namespace?: ToolNamespace, renderers?: OperationRenderers<TParams>): void;
@@ -19,7 +19,7 @@ function piOperationResult(render, outcome) {
19
19
  export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
20
20
  export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
21
21
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
22
- export function registerOperation(pi, operation, run, namespace) {
22
+ export function registerOperation(pi, operation, run, namespace, renderers) {
23
23
  pi.registerTool(defineTool({
24
24
  name: operation.name,
25
25
  label: operation.label,
@@ -28,6 +28,7 @@ export function registerOperation(pi, operation, run, namespace) {
28
28
  outputSchema: operation.outputSchema,
29
29
  executionMode: operation.executionMode,
30
30
  ...(namespace ? { namespace } : {}),
31
+ ...renderers,
31
32
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
32
33
  return piOperationResult(operation.render, await run(params, ctx));
33
34
  },
@@ -17,8 +17,8 @@ export declare function selectContinuation(origin: ResetOrigin): string;
17
17
  * The shared warning body: the one text both hosts show before a reset. Only the closing
18
18
  * instruction differs — Pi can reset the model itself, Claude can only end the turn.
19
19
  */
20
- export declare const WARNING_BODY = "This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.\nBefore that, put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
21
- export declare const WARNING_CALL = "When the notes are ready, call `empty_brain` to reset now instead of being cut off mid-task.";
20
+ export declare const WARNING_BODY = "This brain is already spent. Whatever lives only in this brain goes with it \u2014 but the notes stay where they are, and history has the rest written down, though digging it back out is on you.\nUse the last of this brain to put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\n- and refresh the stale notes with what has changed since you last wrote them \u2014 the notes the next window gets are the old ones, unless you fix them now\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
21
+ export declare const WARNING_CALL = "The moment the notes are saved, call `empty_brain`. Not one more probe, not one more test \u2014 the next thing you do after saving is reset.";
22
22
  export declare function warningPrompt(): string;
23
23
  /**
24
24
  * The last line of the second-tier notice: it stops at 2 because the wipe lands at the end of the
@@ -25,8 +25,8 @@ export function selectContinuation(origin) {
25
25
  * The shared warning body: the one text both hosts show before a reset. Only the closing
26
26
  * instruction differs — Pi can reset the model itself, Claude can only end the turn.
27
27
  */
28
- export const WARNING_BODY = "This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.\nBefore that, put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
29
- export const WARNING_CALL = "When the notes are ready, call `empty_brain` to reset now instead of being cut off mid-task.";
28
+ export const WARNING_BODY = "This brain is already spent. Whatever lives only in this brain goes with it — but the notes stay where they are, and history has the rest written down, though digging it back out is on you.\nUse the last of this brain to put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\n- and refresh the stale notes with what has changed since you last wrote them — the notes the next window gets are the old ones, unless you fix them now\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
29
+ export const WARNING_CALL = "The moment the notes are saved, call `empty_brain`. Not one more probe, not one more test — the next thing you do after saving is reset.";
30
30
  export function warningPrompt() {
31
31
  return `${WARNING_BODY}\n${WARNING_CALL}`;
32
32
  }
@@ -17,8 +17,8 @@ Your notes don't go anywhere — no wipe reaches the shelves. History has it too
17
17
  What lives only in this brain leaves with it.
18
18
  A decent moment to put down where you are, while you still remember why.
19
19
  Ready when you are: \`{wipeTool}\`.`;
20
- const GOLDEN_WARNING = `This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.
21
- Before that, put down what the next window can't get back:
20
+ const GOLDEN_WARNING = `This brain is already spent. Whatever lives only in this brain goes with it — but the notes stay where they are, and history has the rest written down, though digging it back out is on you.
21
+ Use the last of this brain to put down what the next window can't get back:
22
22
  - what you're in the middle of, and how far it has progressed
23
23
  - decisions the human has made, in their words
24
24
  - what is blocked or pending
@@ -27,6 +27,7 @@ Before that, put down what the next window can't get back:
27
27
  - what failed, and why
28
28
  - skills to re-read, and history seqs, notes, or files to consult
29
29
  - anything else you expect to be useful after the reset
30
+ - and refresh the stale notes with what has changed since you last wrote them — the notes the next window gets are the old ones, unless you fix them now
30
31
  Correct or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.`;
31
32
  const GOLDEN_COUNTDOWN = "Brain emptied in 3… 2…";
32
33
  /**
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,89 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { initTheme } from "@earendil-works/pi-coding-agent";
4
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
5
+ import { emptyBrainRenderers, notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../plugins/pi/render.js";
6
+ import { success, wireResult } from "../src/tools/result.js";
7
+ /** Flat theme for content assertions; strikethrough marks its text so crumple stays visible. */
8
+ const flatTheme = {
9
+ fg: (_color, text) => text,
10
+ bold: (text) => text,
11
+ italic: (text) => text,
12
+ strikethrough: (text) => `~~${text}~~`,
13
+ };
14
+ function toolResult(outcome) {
15
+ return { content: [{ type: "text", text: "receipt" }], structuredContent: wireResult(outcome), isError: !outcome.ok, details: undefined };
16
+ }
17
+ function jsonResult(value, isError = false) {
18
+ return { content: [{ type: "text", text: JSON.stringify(value) }], isError, details: undefined };
19
+ }
20
+ function lines(component, width = 80) {
21
+ return component.render(width).map((line) => stripTerminalSequences(line).trimEnd()).join("\n");
22
+ }
23
+ test("notes_write collapsed: outcome, address and content size", () => {
24
+ const result = toolResult(success({ address: "@self/grudge.md", outcome: "created" }));
25
+ const component = notesWriteRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "@self/grudge.md", content: "hello" } });
26
+ assert.equal(lines(component), "wrote @self/grudge.md · 5 chars");
27
+ });
28
+ test("notes_write expanded: the written content follows the header", () => {
29
+ const result = toolResult(success({ address: "plan.md", outcome: "overwrote" }));
30
+ const component = notesWriteRenderers.renderResult(result, { expanded: true }, flatTheme, { args: { address: "plan.md", content: "one\ntwo" } });
31
+ assert.equal(lines(component), "wrote plan.md · overwrote · 7 chars\n\none\ntwo");
32
+ });
33
+ test("notes_update edited: collapsed peeks at the first added line", () => {
34
+ const result = toolResult(success({ address: "a.md", change_kind: "body", diff: " 1 old\n-2 gone\n+2 here" }));
35
+ const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md" } });
36
+ assert.equal(lines(component), "edited a.md · + here");
37
+ });
38
+ test("notes_update crumple: the address is struck through", () => {
39
+ const result = toolResult(success({ address: "@self/stale.md", change_kind: "metadata", diff: "" }));
40
+ const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "@self/stale.md", crumpled: true } });
41
+ assert.equal(lines(component), "✂ crumpled ~~@self/stale.md~~");
42
+ });
43
+ test("notes_update moved: both addresses stay on the line", () => {
44
+ const result = toolResult(success({ address: "@self/new.md", change_kind: "moved", diff: "rename a.md -> @self/new.md", rename_from: "a.md" }));
45
+ const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md", rename_to: "@self/new.md" } });
46
+ assert.equal(lines(component), "renamed a.md → @self/new.md");
47
+ });
48
+ test("notes_update unchanged keeps quiet", () => {
49
+ const result = toolResult(success({ address: "a.md", change_kind: "none", diff: "" }));
50
+ const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md" } });
51
+ assert.equal(lines(component), "unchanged a.md");
52
+ });
53
+ test("notes_read collapsed: size and a peek at the first line", () => {
54
+ const result = toolResult(success({ address: "@project/MAP.md", metadata: { origin: "self", created_at: "x", updated_at: "y", extra: {} }, text: "# MAP\n\nbody", total_chars: 11, next_offset_chars: null }));
55
+ const component = notesReadRenderers.renderResult(result, { expanded: false }, flatTheme);
56
+ assert.equal(lines(component), "read @project/MAP.md · 11 chars — # MAP");
57
+ });
58
+ test("notes_read expanded: truncation points at the next offset", () => {
59
+ const result = toolResult(success({ address: "a.md", metadata: { origin: "self", created_at: "x", updated_at: "y", extra: {} }, text: "part", total_chars: 10, next_offset_chars: 4 }));
60
+ const component = notesReadRenderers.renderResult(result, { expanded: true }, flatTheme);
61
+ assert.equal(lines(component), "read a.md · 10 chars · truncated — part\n\npart\n… continue at offset_chars=4");
62
+ });
63
+ test("refusals render as one error line with the code", () => {
64
+ const result = toolResult({ ok: false, error: { code: "not_found", message: "No note at x.md." } });
65
+ const component = notesReadRenderers.renderResult(result, { expanded: false }, flatTheme);
66
+ assert.equal(lines(component), "not_found: No note at x.md.");
67
+ });
68
+ test("results without a structured payload fall back to the receipt line", () => {
69
+ const result = { content: [{ type: "text", text: "created a.md" }], isError: false, details: undefined };
70
+ const component = notesWriteRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md", content: "x" } });
71
+ assert.equal(lines(component), "created a.md");
72
+ });
73
+ test("empty_brain: divider with the last word, refusals in one line", () => {
74
+ initTheme();
75
+ const ok = emptyBrainRenderers.renderResult(jsonResult({ status: "rollover_requested" }), { expanded: false }, flatTheme, { args: { last_word: "cake was worth it" } });
76
+ const rendered = lines(ok, 40).split("\n");
77
+ assert.match(rendered[0] ?? "", /^── ✂ brain emptied ─+$/);
78
+ assert.equal(rendered[1], "“cake was worth it”");
79
+ const refused = emptyBrainRenderers.renderResult(jsonResult({ error: "notesoup is off" }, true), { expanded: false }, flatTheme, { args: {} });
80
+ assert.equal(lines(refused), "✂ brain refused to empty — notesoup is off");
81
+ const pending = emptyBrainRenderers.renderResult(jsonResult({ status: "rollover_already_pending" }), { expanded: false }, flatTheme, { args: {} });
82
+ assert.equal(lines(pending), "✂ brain already being emptied");
83
+ });
84
+ test("notes_update expanded diff goes through the host's diff renderer", () => {
85
+ initTheme();
86
+ const result = toolResult(success({ address: "a.md", change_kind: "body", diff: " 1 old\n-2 gone\n+2 here" }));
87
+ const component = notesUpdateRenderers.renderResult(result, { expanded: true }, flatTheme, { args: { address: "a.md" } });
88
+ assert.equal(lines(component), "edited a.md · + here\n\n 1 old\n-2 gone\n+2 here");
89
+ });