@andares/pi-toolkits 1.0.2 → 1.2.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 (45) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +65 -1
  3. package/README.zh-CN.md +58 -1
  4. package/package.json +7 -4
  5. package/src/features/keep/constants.ts +44 -0
  6. package/src/features/keep/format.ts +77 -0
  7. package/src/features/keep/index.ts +409 -0
  8. package/src/features/keep/keep.test.ts +955 -0
  9. package/src/features/keep/ledger.ts +340 -0
  10. package/src/features/keep/picker.ts +257 -0
  11. package/src/features/keep/store.ts +271 -0
  12. package/src/features/review-page/assets/index-CrDwcsqI.css +1 -0
  13. package/src/features/review-page/assets/index-DYxi32gA.js +1 -0
  14. package/src/features/{spec → review-page}/assets/index.html +2 -2
  15. package/src/features/{spec → review-page}/blocks.test.ts +17 -0
  16. package/src/features/{spec → review-page}/blocks.ts +9 -0
  17. package/src/features/review-page/headings.test.ts +44 -0
  18. package/src/features/review-page/headings.ts +67 -0
  19. package/src/features/spec/assets.test.ts +2 -2
  20. package/src/features/spec/diff.test.ts +1 -1
  21. package/src/features/spec/diff.ts +1 -1
  22. package/src/features/spec/feedback.test.ts +1 -1
  23. package/src/features/spec/feedback.ts +1 -1
  24. package/src/features/spec/index.test.ts +121 -0
  25. package/src/features/spec/index.ts +82 -23
  26. package/src/features/spec/server.test.ts +65 -2
  27. package/src/features/spec/server.ts +29 -5
  28. package/src/features/spec/store.ts +1 -1
  29. package/src/features/talk/index.test.ts +230 -0
  30. package/src/features/talk/index.ts +241 -0
  31. package/src/features/talk/message.test.ts +212 -0
  32. package/src/features/talk/message.ts +152 -0
  33. package/src/features/talk/reply.test.ts +116 -0
  34. package/src/features/talk/reply.ts +92 -0
  35. package/src/features/talk/sections.test.ts +39 -0
  36. package/src/features/talk/sections.ts +44 -0
  37. package/src/features/talk/server.test.ts +247 -0
  38. package/src/features/talk/server.ts +211 -0
  39. package/src/features/uat/ledger.ts +13 -62
  40. package/src/index.ts +7 -0
  41. package/src/lib/event-ledger.ts +112 -0
  42. package/src/features/spec/assets/index-CdTerMvN.css +0 -1
  43. package/src/features/spec/assets/index-Dv52AIjX.js +0 -1
  44. /package/src/features/{spec → review-page}/render.test.ts +0 -0
  45. /package/src/features/{spec → review-page}/render.ts +0 -0
@@ -0,0 +1,230 @@
1
+ /**
2
+ * `/ask-talk` wiring, with a real HTTP server.
3
+ *
4
+ * The pure reply/message tests cannot catch the dangerous part of this feature:
5
+ * which snapshot the still-open page is actually talking to after a new reply.
6
+ * These tests go through the registered command and its routes for that reason.
7
+ */
8
+ import { afterEach, describe, expect, it, vi } from "vitest";
9
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import { registerTalk, TALK_COMMAND } from "./index.js";
11
+
12
+ type Handler = (event: unknown, ctx: ExtensionContext) => void;
13
+
14
+ interface Harness {
15
+ command: (args?: string) => Promise<void>;
16
+ ctx: ExtensionContext;
17
+ entries: unknown[];
18
+ setReply: (text: string) => void;
19
+ opened: ReturnType<typeof vi.fn>;
20
+ messages: ReturnType<typeof vi.fn>;
21
+ notify: ReturnType<typeof vi.fn>;
22
+ shutdown: () => void;
23
+ start: (sessionId?: string) => void;
24
+ }
25
+
26
+ const cleanups: Array<() => void> = [];
27
+
28
+ afterEach(() => {
29
+ for (const cleanup of cleanups.splice(0)) cleanup();
30
+ });
31
+
32
+ function assistant(text: string): object {
33
+ return {
34
+ id: `a-${Math.random().toString(36).slice(2)}`,
35
+ type: "message",
36
+ message: {
37
+ role: "assistant",
38
+ content: [{ type: "text", text }],
39
+ model: "test/model",
40
+ timestamp: 1_700_000_000_000,
41
+ },
42
+ };
43
+ }
44
+
45
+ function harness(): Harness {
46
+ const commands = new Map<string, { handler: (args: string, ctx: ExtensionContext) => Promise<void> }>();
47
+ const handlers = new Map<string, Handler[]>();
48
+ const opened = vi.fn();
49
+ const messages = vi.fn();
50
+ const notify = vi.fn();
51
+ let entries: unknown[] = [];
52
+ let idle = true;
53
+
54
+ const pi = {
55
+ registerCommand: (name: string, definition: { handler: (args: string, ctx: ExtensionContext) => Promise<void> }) => {
56
+ commands.set(name, definition);
57
+ },
58
+ on: (event: string, handler: Handler) => {
59
+ handlers.set(event, [...(handlers.get(event) ?? []), handler]);
60
+ },
61
+ sendUserMessage: messages,
62
+ } as unknown as ExtensionAPI;
63
+
64
+ const ctx = {
65
+ isIdle: () => idle,
66
+ ui: { notify },
67
+ sessionManager: {
68
+ getSessionId: () => "session-one",
69
+ getBranch: () => entries,
70
+ buildContextEntries: () => entries,
71
+ },
72
+ } as unknown as ExtensionContext;
73
+
74
+ const portStart = 48_000 + Math.floor(Math.random() * 1500);
75
+ registerTalk(pi, { openBrowser: opened, portStart, portAttempts: 20, closeDelayMs: 30 });
76
+ const definition = commands.get(TALK_COMMAND);
77
+ if (!definition) throw new Error("ask-talk was not registered");
78
+
79
+ const result: Harness = {
80
+ command: (args = "") => definition.handler(args, ctx),
81
+ ctx,
82
+ get entries() {
83
+ return entries;
84
+ },
85
+ setReply: (text) => {
86
+ entries = [
87
+ { id: "u1", type: "message", message: { role: "user", content: [{ type: "text", text: "q" }] } },
88
+ assistant(text),
89
+ ];
90
+ },
91
+ opened,
92
+ messages,
93
+ notify,
94
+ shutdown: () => {
95
+ for (const handler of handlers.get("session_shutdown") ?? []) handler({}, ctx);
96
+ },
97
+ start: (sessionId = "session-one") => {
98
+ (ctx.sessionManager as unknown as { getSessionId: () => string }).getSessionId = () => sessionId;
99
+ for (const handler of handlers.get("session_start") ?? []) handler({}, ctx);
100
+ },
101
+ };
102
+ result.setReply("## Alpha\n\nfirst reply");
103
+ cleanups.push(result.shutdown);
104
+ return result;
105
+ }
106
+
107
+ /** Use loopback even on WSL, where the opener URL advertises the LAN address. */
108
+ function localUrl(url: string, path: string): string {
109
+ const parsed = new URL(url);
110
+ parsed.hostname = "127.0.0.1";
111
+ parsed.pathname = path;
112
+ return parsed.toString();
113
+ }
114
+
115
+ async function state(url: string): Promise<{
116
+ items: Array<{ id: string; label: string }>;
117
+ notes: Record<string, string>;
118
+ draft: string;
119
+ sent: boolean;
120
+ }> {
121
+ const response = await fetch(localUrl(url, "/api/state"));
122
+ expect(response.status).toBe(200);
123
+ return (await response.json()) as Awaited<ReturnType<typeof state>>;
124
+ }
125
+
126
+ async function post(url: string, path: string, body: unknown): Promise<Response> {
127
+ return fetch(localUrl(url, path), {
128
+ method: "POST",
129
+ headers: { "content-type": "application/json" },
130
+ body: JSON.stringify(body),
131
+ });
132
+ }
133
+
134
+ describe("ask-talk command", () => {
135
+ it("refuses a running agent and a session with no reply", async () => {
136
+ const h = harness();
137
+ (h.ctx as unknown as { isIdle: () => boolean }).isIdle = () => false;
138
+ await h.command();
139
+ expect(h.opened).not.toHaveBeenCalled();
140
+ expect(h.notify.mock.calls.at(-1)?.[0]).toContain("still running");
141
+
142
+ (h.ctx as unknown as { isIdle: () => boolean }).isIdle = () => true;
143
+ h.entries.length = 0;
144
+ await h.command();
145
+ expect(h.opened).not.toHaveBeenCalled();
146
+ expect(h.notify.mock.calls.at(-1)?.[0]).toContain("no reply");
147
+ });
148
+
149
+ it("opens a snapshot, retains notes for the same reply, and closes with off", async () => {
150
+ const h = harness();
151
+ await h.command();
152
+ const url = h.opened.mock.calls[0]?.[0] as string;
153
+ const initial = await state(url);
154
+ expect(initial.items.map((item) => item.label)).toEqual(["## Alpha", "first reply"]);
155
+
156
+ await post(url, "/api/notes", { notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
157
+ await h.command();
158
+ expect(h.opened).toHaveBeenCalledTimes(1);
159
+ expect(await state(url)).toMatchObject({ notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
160
+
161
+ await h.command("off");
162
+ expect((await fetch(localUrl(url, "/api/state")).catch(() => undefined))?.ok ?? false).toBe(false);
163
+ });
164
+
165
+ it("serves the NEW reply on the existing page and clears the old notes", async () => {
166
+ const h = harness();
167
+ await h.command();
168
+ const url = h.opened.mock.calls[0]?.[0] as string;
169
+ const before = await state(url);
170
+ await post(url, "/api/notes", { notes: { [before.items[1].id]: "old note" }, draft: "old draft" });
171
+
172
+ h.setReply("## Beta\n\nsecond reply");
173
+ await h.command();
174
+
175
+ const after = await state(url);
176
+ expect(after.items.map((item) => item.label)).toEqual(["## Beta", "second reply"]);
177
+ expect(after.notes).toEqual({});
178
+ expect(after.draft).toBe("");
179
+ expect(h.opened).toHaveBeenCalledTimes(1);
180
+ });
181
+
182
+ it("sends notes for the CURRENT snapshot when Continue arrives", async () => {
183
+ const h = harness();
184
+ await h.command();
185
+ const url = h.opened.mock.calls[0]?.[0] as string;
186
+ h.setReply("## Beta\n\nsecond reply");
187
+ await h.command();
188
+ const current = await state(url);
189
+
190
+ const response = await post(url, "/api/continue", {
191
+ notes: { [current.items[1].id]: "change this" },
192
+ message: "carry on",
193
+ });
194
+ expect(response.status).toBe(200);
195
+ expect(h.messages).toHaveBeenCalledTimes(1);
196
+ const message = h.messages.mock.calls[0]?.[0] as string;
197
+ expect(message).toContain("### Beta");
198
+ expect(message).toContain("> second reply");
199
+ expect(message).toContain("- change this");
200
+ expect(message).toContain("## Operator's message\n\ncarry on");
201
+ expect(message).not.toContain("first reply");
202
+ });
203
+
204
+ it("rechecks context survival when Continue arrives, not only when the page opens", async () => {
205
+ const h = harness();
206
+ await h.command();
207
+ const url = h.opened.mock.calls[0]?.[0] as string;
208
+ const current = await state(url);
209
+ (h.ctx.sessionManager as unknown as { buildContextEntries: () => unknown[] }).buildContextEntries = () => [];
210
+ const response = await post(url, "/api/continue", {
211
+ notes: { [current.items[1].id]: "still applies" },
212
+ message: "",
213
+ });
214
+ expect(response.status).toBe(200);
215
+ const message = h.messages.mock.calls[0]?.[0] as string;
216
+ expect(message).toContain("## Your last reply (full text)");
217
+ expect(message).toContain("## Alpha\n\nfirst reply");
218
+ });
219
+
220
+ it("drops the page when the session changes, but not on a duplicate start event", async () => {
221
+ const h = harness();
222
+ h.start();
223
+ await h.command();
224
+ const url = h.opened.mock.calls[0]?.[0] as string;
225
+ h.start();
226
+ expect((await state(url)).sent).toBe(false);
227
+ h.start("session-two");
228
+ expect((await fetch(localUrl(url, "/api/state")).catch(() => undefined))?.ok ?? false).toBe(false);
229
+ });
230
+ });
@@ -0,0 +1,241 @@
1
+ /**
2
+ * `/ask-talk` — annotate the agent's last reply in the browser.
3
+ *
4
+ * Deliberately NOT a phase: it registers no tool, changes no tool set, touches no
5
+ * permission mode and adds nothing to the system prompt, so it costs nothing
6
+ * until the operator types it, and it works inside `/ask`, `/ask-spec` and
7
+ * `/ask-uat` alike.
8
+ *
9
+ * The page is a snapshot. Running the command again refreshes it: same reply ⇒
10
+ * notes and draft survive, different reply ⇒ they are cleared (the block ids are
11
+ * content hashes, so a new reply means new ids and every note would be orphaned).
12
+ */
13
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import { openInBrowser } from "../../lib/opener.js";
15
+ import { parseBlocks } from "../review-page/blocks.js";
16
+ import { extractHeadings } from "../review-page/headings.js";
17
+ import { buildReplyMessage, type TalkNote } from "./message.js";
18
+ import { extractLastReply } from "./reply.js";
19
+ import { startTalkServer, type TalkServerHandle, type TalkSession } from "./server.js";
20
+
21
+ export const TALK_COMMAND = "ask-talk";
22
+ /** 3501 — a different pool from spec/uat (3401), so a URL says which page it is. */
23
+ const PORT_START = 3501;
24
+
25
+ export interface TalkOptions {
26
+ openBrowser?: (url: string) => unknown;
27
+ portStart?: number;
28
+ portAttempts?: number;
29
+ closeDelayMs?: number;
30
+ }
31
+
32
+ function sessionIdOf(ctx: ExtensionContext): string {
33
+ try {
34
+ return ctx.sessionManager.getSessionId();
35
+ } catch {
36
+ return `pid-${process.pid}`;
37
+ }
38
+ }
39
+
40
+ /** Notes as an ordered list, for the message builder. */
41
+ function noteList(notes: Record<string, string>): TalkNote[] {
42
+ return Object.entries(notes).map(([blockId, text]) => ({ blockId, text }));
43
+ }
44
+
45
+ export function registerTalk(pi: ExtensionAPI, options: TalkOptions = {}): void {
46
+ const open = options.openBrowser ?? openInBrowser;
47
+
48
+ let session: TalkSession | undefined;
49
+ let server: TalkServerHandle | undefined;
50
+ let talkSessionId: string | undefined;
51
+ let ctxRef: ExtensionContext | undefined;
52
+
53
+ function closeServer(): void {
54
+ if (!server) return;
55
+ const closing = server;
56
+ server = undefined;
57
+ void closing.close();
58
+ }
59
+
60
+ /** Start (or restart) a server for this snapshot, with one consistent error path. */
61
+ async function openFresh(current: TalkSession, ctx: ExtensionContext): Promise<void> {
62
+ closeServer();
63
+ try {
64
+ const handle = await startServer(current);
65
+ server = handle;
66
+ open(handle.url);
67
+ ctx.ui.notify(`ask-talk: review open at ${handle.url}`, "info");
68
+ } catch (error) {
69
+ ctx.ui.notify(
70
+ `ask-talk: cannot start the review server — ${error instanceof Error ? error.message : String(error)}`,
71
+ "warning",
72
+ );
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Whether the annotated reply is still in the model's active context.
78
+ *
79
+ * A compaction can summarize away the very message being annotated; the
80
+ * message builder then repeats the reply once, because the quotes would
81
+ * otherwise point at text the model cannot see.
82
+ */
83
+ function replyInContext(ctx: ExtensionContext, entryId: string): boolean {
84
+ if (entryId === "") return true;
85
+ try {
86
+ const entries = ctx.sessionManager.buildContextEntries() as Array<{ id?: unknown }>;
87
+ return entries.some((entry) => entry.id === entryId);
88
+ } catch {
89
+ // Unknown shape on an older host: assume context is intact rather than
90
+ // paying for a full re-send of the reply on every Continue.
91
+ return true;
92
+ }
93
+ }
94
+
95
+ function startServer(current: TalkSession): Promise<TalkServerHandle> {
96
+ return startTalkServer({
97
+ session: current,
98
+ portStart: options.portStart ?? PORT_START,
99
+ portAttempts: options.portAttempts,
100
+ closeDelayMs: options.closeDelayMs,
101
+ onContinue: ({ notes, message }) => {
102
+ // off / shutdown / a session switch invalidates the snapshot at once;
103
+ // an already in-flight HTTP request must not leak into the next session.
104
+ if (session !== current) return;
105
+ // The operator may have started another run (and a compaction) while the
106
+ // page was open. Context survival is a property of Continue time, not of
107
+ // the moment the page was opened.
108
+ current.inContext = ctxRef ? replyInContext(ctxRef, current.entryId) : current.inContext;
109
+ const text = buildReplyMessage({
110
+ blocks: current.blocks,
111
+ notes: noteList(notes),
112
+ message,
113
+ inContext: current.inContext,
114
+ replyText: current.text,
115
+ });
116
+ if (text.trim() === "") return;
117
+ pi.sendUserMessage(text);
118
+ },
119
+ });
120
+ }
121
+
122
+ const command = {
123
+ description:
124
+ "Annotate the agent's last reply in the browser: block notes plus a message, sent back as one short message. `off` closes the page.",
125
+ handler: async (args: string, ctx: ExtensionContext) => {
126
+ const arg = args.trim();
127
+ ctxRef = ctx;
128
+
129
+ if (arg === "off") {
130
+ if (!session && !server) {
131
+ ctx.ui.notify("ask-talk: nothing open.", "info");
132
+ return;
133
+ }
134
+ closeServer();
135
+ session = undefined;
136
+ ctx.ui.notify("ask-talk: closed.", "info");
137
+ return;
138
+ }
139
+
140
+ if (arg !== "") {
141
+ ctx.ui.notify("ask-talk: takes no arguments (use `off` to close the page).", "warning");
142
+ return;
143
+ }
144
+
145
+ // The host persists an assistant message on `message_end`, so while a run
146
+ // is in flight the branch still ends with the PREVIOUS reply. Showing it
147
+ // would be silently wrong; say so instead.
148
+ if (!ctx.isIdle()) {
149
+ ctx.ui.notify(
150
+ "ask-talk: the agent is still running — finish or abort first, then run /ask-talk.",
151
+ "warning",
152
+ );
153
+ return;
154
+ }
155
+
156
+ let entries: unknown[] = [];
157
+ try {
158
+ entries = ctx.sessionManager.getBranch() as unknown[];
159
+ } catch {
160
+ entries = [];
161
+ }
162
+ const reply = extractLastReply(entries);
163
+ if (!reply) {
164
+ ctx.ui.notify(
165
+ "ask-talk: no reply to annotate yet — send a prompt and wait for the answer.",
166
+ "warning",
167
+ );
168
+ return;
169
+ }
170
+
171
+ const inContext = replyInContext(ctx, reply.entryId);
172
+ const sameReply =
173
+ session !== undefined && !session.sent && session.fingerprint === reply.fingerprint;
174
+
175
+ if (sameReply && session) {
176
+ session.inContext = inContext;
177
+ if (server?.active() !== true) {
178
+ await openFresh(session, ctx);
179
+ return;
180
+ }
181
+ // Nothing about the snapshot changed. Re-fetching here would overwrite
182
+ // keystrokes still inside the page's save debounce window.
183
+ ctx.ui.notify(`ask-talk: already showing this reply — ${server.url}`, "info");
184
+ return;
185
+ }
186
+
187
+ const blocks = parseBlocks(reply.text);
188
+ const next: TalkSession = {
189
+ text: reply.text,
190
+ blocks,
191
+ headings: extractHeadings(blocks),
192
+ entryId: reply.entryId,
193
+ model: reply.model,
194
+ at: reply.at,
195
+ fingerprint: reply.fingerprint,
196
+ notes: {},
197
+ draft: "",
198
+ sent: false,
199
+ inContext,
200
+ };
201
+
202
+ const previous = session;
203
+ const replaced = previous !== undefined && previous.fingerprint !== reply.fingerprint;
204
+ talkSessionId = sessionIdOf(ctx);
205
+
206
+ if (previous && server?.active()) {
207
+ // The routes and the Continue callback both close over the object passed
208
+ // to startTalkServer. Replace its CONTENTS, not just the `session`
209
+ // variable, or a refresh would serve and submit the previous reply.
210
+ Object.assign(previous, next);
211
+ session = previous;
212
+ server.broadcast("refresh", {});
213
+ ctx.ui.notify(
214
+ `ask-talk: review refreshed${replaced ? " (notes cleared — this is a new reply)" : ""} — ${server.url}`,
215
+ "info",
216
+ );
217
+ return;
218
+ }
219
+
220
+ session = next;
221
+ await openFresh(next, ctx);
222
+ },
223
+ };
224
+
225
+ pi.registerCommand(TALK_COMMAND, command);
226
+
227
+ pi.on("session_shutdown", () => {
228
+ closeServer();
229
+ session = undefined;
230
+ });
231
+
232
+ pi.on("session_start", (_event, ctx) => {
233
+ const nextSessionId = sessionIdOf(ctx);
234
+ ctxRef = ctx;
235
+ if (nextSessionId === talkSessionId) return;
236
+ // A different session must not keep a page bound to the old reply.
237
+ talkSessionId = undefined;
238
+ session = undefined;
239
+ closeServer();
240
+ });
241
+ }
@@ -0,0 +1,212 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseBlocks } from "../review-page/blocks.js";
3
+ import { buildReplyMessage, clipForQuote, hasUnknownNote, QUOTE_LIMIT } from "./message.js";
4
+
5
+ const REPLY = [
6
+ "## Approach",
7
+ "",
8
+ "The page reads the blocks the server ships, never the rendered HTML.",
9
+ "",
10
+ "## Milestones",
11
+ "",
12
+ "M1 captures the reply, M2 renders the page.",
13
+ ].join("\n");
14
+
15
+ function build(notes: Array<{ blockId: string; text: string }>, message: string) {
16
+ const blocks = parseBlocks(REPLY);
17
+ const resolved = notes.map((note) => ({
18
+ blockId: note.blockId === "approach" ? blocks[1].id : note.blockId,
19
+ text: note.text,
20
+ }));
21
+ return {
22
+ text: buildReplyMessage({
23
+ blocks,
24
+ notes: resolved,
25
+ message,
26
+ inContext: true,
27
+ replyText: REPLY,
28
+ }),
29
+ blocks,
30
+ };
31
+ }
32
+
33
+ describe("buildReplyMessage", () => {
34
+ it("writes the two parts in a fixed shape", () => {
35
+ const { text } = build(
36
+ [
37
+ {
38
+ blockId: "approach",
39
+ text: "this reverses the order: ship the headings first",
40
+ },
41
+ ],
42
+ "also keep it short",
43
+ );
44
+ expect(text).toBe(
45
+ [
46
+ "## Notes on your last reply",
47
+ "",
48
+ "Address every note below; each one is attached to the part of your reply it quotes.",
49
+ "",
50
+ "### Approach",
51
+ "> The page reads the blocks the server ships, never the rendered HTML.",
52
+ "",
53
+ "- this reverses the order: ship the headings first",
54
+ "",
55
+ "## Operator's message",
56
+ "",
57
+ "also keep it short",
58
+ ].join("\n"),
59
+ );
60
+ });
61
+
62
+ it("sends bare composer text when there are no notes", () => {
63
+ const { text } = build([], "just this sentence");
64
+ expect(text).toBe("just this sentence");
65
+ });
66
+
67
+ it("sends only the notes when the composer is empty", () => {
68
+ const { text } = build([{ blockId: "approach", text: "wrong" }], "");
69
+ expect(text.startsWith("## Notes on your last reply")).toBe(true);
70
+ expect(text).not.toContain("## Operator's message");
71
+ expect(text.endsWith("- wrong")).toBe(true);
72
+ });
73
+
74
+ it("quotes a heading without its markers", () => {
75
+ const blocks = parseBlocks(REPLY);
76
+ const text = buildReplyMessage({
77
+ blocks,
78
+ notes: [{ blockId: blocks[0].id, text: "rename" }],
79
+ message: "",
80
+ inContext: true,
81
+ replyText: REPLY,
82
+ });
83
+ expect(text).toContain("### Approach");
84
+ expect(text).toContain("> Approach\n");
85
+ expect(text).not.toContain("> ## Approach");
86
+ });
87
+
88
+ it("uses the section path as the note heading", () => {
89
+ const blocks = parseBlocks(REPLY);
90
+ const { text } = build([{ blockId: blocks[3].id, text: "order is wrong" }], "");
91
+ expect(text).toContain("### Milestones");
92
+ });
93
+
94
+ it("labels notes above the first heading with the block label", () => {
95
+ const blocks = parseBlocks("preamble paragraph\n\n## Section\n\nbody");
96
+ const text = buildReplyMessage({
97
+ blocks,
98
+ notes: [{ blockId: blocks[0].id, text: "reword" }],
99
+ message: "",
100
+ inContext: true,
101
+ replyText: "",
102
+ });
103
+ expect(text).toContain("### preamble paragraph");
104
+ });
105
+
106
+ it("keeps document order, not the order the notes were written", () => {
107
+ const blocks = parseBlocks(REPLY);
108
+ const text = buildReplyMessage({
109
+ blocks,
110
+ notes: [
111
+ { blockId: blocks[3].id, text: "second note" },
112
+ { blockId: blocks[1].id, text: "first note" },
113
+ ],
114
+ message: "",
115
+ inContext: true,
116
+ replyText: REPLY,
117
+ });
118
+ expect(text.indexOf("first note")).toBeLessThan(text.indexOf("second note"));
119
+ });
120
+
121
+ it("keeps multi-line notes inside one bullet", () => {
122
+ const blocks = parseBlocks(REPLY);
123
+ const text = buildReplyMessage({
124
+ blocks,
125
+ notes: [{ blockId: blocks[1].id, text: "1. no\n2. yes" }],
126
+ message: "",
127
+ inContext: true,
128
+ replyText: REPLY,
129
+ });
130
+ expect(text).toContain("- 1. no\n 2. yes");
131
+ });
132
+
133
+ it("repeats the reply only when compaction pushed it out of context", () => {
134
+ const blocks = parseBlocks(REPLY);
135
+ const text = buildReplyMessage({
136
+ blocks,
137
+ notes: [{ blockId: blocks[1].id, text: "fix it" }],
138
+ message: "",
139
+ inContext: false,
140
+ replyText: REPLY,
141
+ });
142
+ expect(text).toContain("## Your last reply (full text)");
143
+ expect(text).toContain("M1 captures the reply");
144
+ });
145
+
146
+ it("drops blank notes instead of emitting an empty bullet", () => {
147
+ const blocks = parseBlocks(REPLY);
148
+ const text = buildReplyMessage({
149
+ blocks,
150
+ notes: [{ blockId: blocks[1].id, text: " " }],
151
+ message: "hello",
152
+ inContext: true,
153
+ replyText: REPLY,
154
+ });
155
+ expect(text).toBe("hello");
156
+ });
157
+ });
158
+
159
+ describe("clipForQuote", () => {
160
+ it("keeps short blocks intact", () => {
161
+ expect(clipForQuote("short block")).toBe("short block");
162
+ });
163
+
164
+ it("clips at a line boundary and marks the cut", () => {
165
+ const long = Array.from({ length: 40 }, (_, i) => `line ${i} of a long block`).join("\n");
166
+ const clipped = clipForQuote(long, 120);
167
+ expect(clipped.length).toBeLessThanOrEqual(140);
168
+ expect(clipped.endsWith("…")).toBe(true);
169
+ expect(clipped.split("\n").slice(0, -2).every((line) => /^line \d+ of a long block$/.test(line))).toBe(
170
+ true,
171
+ );
172
+ });
173
+
174
+ it("closes a fence it cut through", () => {
175
+ const long = ["```ts", ...Array.from({ length: 60 }, (_, i) => `const x${i} = ${i};`), "```"].join(
176
+ "\n",
177
+ );
178
+ const clipped = clipForQuote(long, 120);
179
+ expect(clipped.split("```").length % 2).toBe(1);
180
+ expect(clipped.trimEnd().endsWith("```")).toBe(true);
181
+ });
182
+
183
+ it("falls back to a hard slice when the first line alone exceeds the limit", () => {
184
+ const clipped = clipForQuote("x".repeat(QUOTE_LIMIT * 2), 50);
185
+ expect(clipped.length).toBe(50);
186
+ expect(clipped.endsWith("…")).toBe(true);
187
+ });
188
+ });
189
+
190
+ describe("hasUnknownNote", () => {
191
+ it("flags notes for blocks the reply does not contain", () => {
192
+ const blocks = parseBlocks(REPLY);
193
+ expect(
194
+ hasUnknownNote({
195
+ blocks,
196
+ notes: [{ blockId: "gone#0", text: "stale" }],
197
+ message: "",
198
+ inContext: true,
199
+ replyText: "",
200
+ }),
201
+ ).toBe(true);
202
+ expect(
203
+ hasUnknownNote({
204
+ blocks,
205
+ notes: [{ blockId: blocks[0].id, text: "fine" }],
206
+ message: "",
207
+ inContext: true,
208
+ replyText: "",
209
+ }),
210
+ ).toBe(false);
211
+ });
212
+ });