@andares/pi-toolkits 1.1.0 → 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 (35) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +24 -1
  3. package/README.zh-CN.md +23 -1
  4. package/package.json +5 -3
  5. package/src/features/review-page/assets/index-CrDwcsqI.css +1 -0
  6. package/src/features/review-page/assets/index-DYxi32gA.js +1 -0
  7. package/src/features/{spec → review-page}/assets/index.html +2 -2
  8. package/src/features/{spec → review-page}/blocks.test.ts +17 -0
  9. package/src/features/{spec → review-page}/blocks.ts +9 -0
  10. package/src/features/review-page/headings.test.ts +44 -0
  11. package/src/features/review-page/headings.ts +67 -0
  12. package/src/features/spec/assets.test.ts +2 -2
  13. package/src/features/spec/diff.test.ts +1 -1
  14. package/src/features/spec/diff.ts +1 -1
  15. package/src/features/spec/feedback.test.ts +1 -1
  16. package/src/features/spec/feedback.ts +1 -1
  17. package/src/features/spec/index.ts +1 -1
  18. package/src/features/spec/server.test.ts +16 -2
  19. package/src/features/spec/server.ts +11 -3
  20. package/src/features/spec/store.ts +1 -1
  21. package/src/features/talk/index.test.ts +230 -0
  22. package/src/features/talk/index.ts +241 -0
  23. package/src/features/talk/message.test.ts +212 -0
  24. package/src/features/talk/message.ts +152 -0
  25. package/src/features/talk/reply.test.ts +116 -0
  26. package/src/features/talk/reply.ts +92 -0
  27. package/src/features/talk/sections.test.ts +39 -0
  28. package/src/features/talk/sections.ts +44 -0
  29. package/src/features/talk/server.test.ts +247 -0
  30. package/src/features/talk/server.ts +211 -0
  31. package/src/index.ts +4 -0
  32. package/src/features/spec/assets/index-CdTerMvN.css +0 -1
  33. package/src/features/spec/assets/index-Dv52AIjX.js +0 -1
  34. /package/src/features/{spec → review-page}/render.test.ts +0 -0
  35. /package/src/features/{spec → review-page}/render.ts +0 -0
@@ -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
+ });
@@ -0,0 +1,152 @@
1
+ /**
2
+ * talk message — what `Continue` sends back.
3
+ *
4
+ * Two parts, and nothing else:
5
+ * 1. every note, each with the reply text it is attached to quoted above it;
6
+ * 2. the operator's overall message from the composer.
7
+ *
8
+ * The full reply is deliberately NOT echoed: it is already in the model's
9
+ * context, so quoting it again buys nothing and costs the whole answer. The
10
+ * quote exists to locate a block, which is why it is clipped.
11
+ *
12
+ * The one exception is a reply that compaction pushed out of the context — then
13
+ * the quotes point at text the model can no longer see, so the reply is sent
14
+ * once, in full. That is a rare, explicitly expensive path.
15
+ */
16
+ import type { Block } from "../review-page/blocks.js";
17
+ import { blockLabel } from "../review-page/blocks.js";
18
+ import { sectionPaths } from "./sections.js";
19
+
20
+ /** Longest quote — enough to find the block, not a second copy of the reply. */
21
+ export const QUOTE_LIMIT = 600;
22
+
23
+ export interface TalkNote {
24
+ blockId: string;
25
+ text: string;
26
+ }
27
+
28
+ export interface ReplyMessageInput {
29
+ blocks: readonly Block[];
30
+ /** Notes in any order; they are emitted in document order. */
31
+ notes: readonly TalkNote[];
32
+ /** Composer text. */
33
+ message: string;
34
+ /** Whether the whole reply is still in the model's active context. */
35
+ inContext: boolean;
36
+ replyText: string;
37
+ }
38
+
39
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
40
+
41
+ /**
42
+ * Clip a block for quoting, at a line boundary, closing an open fence.
43
+ *
44
+ * Line boundaries matter: half a code line reads as corruption, and a quote
45
+ * that leaves a fence open would swallow the rest of the message into a code
46
+ * block when the model's markdown renderer sees it.
47
+ */
48
+ export function clipForQuote(text: string, limit = QUOTE_LIMIT): string {
49
+ const trimmed = text.trim();
50
+ if (trimmed.length <= limit) return trimmed;
51
+
52
+ const lines = trimmed.split("\n");
53
+ const kept: string[] = [];
54
+ let size = 0;
55
+ for (const line of lines) {
56
+ // +2: the newline plus the ellipsis we may have to append.
57
+ if (size + line.length + 2 > limit) break;
58
+ kept.push(line);
59
+ size += line.length + 1;
60
+ }
61
+ if (kept.length === 0) return `${trimmed.slice(0, limit - 1)}…`;
62
+
63
+ let fence: { char: string; length: number } | undefined;
64
+ for (const line of kept) {
65
+ const match = FENCE_RE.exec(line);
66
+ if (!match) continue;
67
+ if (!fence) fence = { char: match[1][0], length: match[1].length };
68
+ else if (match[1][0] === fence.char && match[1].length >= fence.length) fence = undefined;
69
+ }
70
+ // The ellipsis goes INSIDE the fence: a marker after the closing run would read
71
+ // as prose continuing after the code block, which is not what was cut.
72
+ kept.push("…");
73
+ if (fence) kept.push(fence.char.repeat(fence.length));
74
+
75
+ return kept.join("\n");
76
+ }
77
+
78
+ /**
79
+ * Quote a block for the message body.
80
+ *
81
+ * A heading is quoted without its `#` markers: `> ## Alpha` right under the
82
+ * `### Alpha` label reads as a nested heading inside a blockquote, which is noise
83
+ * the model has to strip mentally. The text is what locates the block.
84
+ */
85
+ function quote(block: Block, limit = QUOTE_LIMIT): string {
86
+ const clipped = clipForQuote(block.text, limit);
87
+ const body =
88
+ block.kind === "heading"
89
+ ? clipped
90
+ .split("\n")
91
+ .map((line) => line.replace(/^ {0,3}#{1,6}\s+/, ""))
92
+ .join("\n")
93
+ : clipped;
94
+ return body
95
+ .split("\n")
96
+ .map((line) => (line === "" ? ">" : `> ${line}`))
97
+ .join("\n");
98
+ }
99
+
100
+ const HEADER = "## Notes on your last reply";
101
+ const INTRO =
102
+ "Address every note below; each one is attached to the part of your reply it quotes.";
103
+ const MESSAGE_HEADER = "## Operator's message";
104
+
105
+ /** Block label used when a section path cannot be resolved (defensive only). */
106
+ function fallbackLabel(block: Block): string {
107
+ return blockLabel(block, 60) || "reply";
108
+ }
109
+
110
+ export function buildReplyMessage(input: ReplyMessageInput): string {
111
+ const message = input.message.trim();
112
+ const paths = sectionPaths(input.blocks);
113
+
114
+ // Document order, not the order the notes were written in: the model reads
115
+ // them while scrolling the reply it is being asked to fix.
116
+ const ordered = input.blocks
117
+ .filter((block) => input.notes.some((note) => note.blockId === block.id))
118
+ .map((block) => ({ block, note: input.notes.find((note) => note.blockId === block.id)! }))
119
+ .filter(({ note }) => note.text.trim() !== "");
120
+
121
+ if (ordered.length === 0) {
122
+ // No notes: the composer text IS the message. No wrapper, nothing to parse.
123
+ return message;
124
+ }
125
+
126
+ const sections = ordered.map(({ block, note }) => {
127
+ const locus = paths.get(block.id) || fallbackLabel(block);
128
+ return [`### ${locus}`, quote(block), "", `- ${note.text.trim().replace(/\n+/g, "\n ")}`].join(
129
+ "\n",
130
+ );
131
+ });
132
+
133
+ const parts = [HEADER, "", INTRO, "", sections.join("\n\n")];
134
+ if (!input.inContext) {
135
+ parts.push(
136
+ "",
137
+ "## Your last reply (full text)",
138
+ "",
139
+ "The reply quoted above is no longer in your active context, so it is repeated here in full.",
140
+ "",
141
+ input.replyText.trim(),
142
+ );
143
+ }
144
+ if (message !== "") parts.push("", MESSAGE_HEADER, "", message);
145
+ return parts.join("\n");
146
+ }
147
+
148
+ /** True when a note points at a block that is not in the reply (stale page). */
149
+ export function hasUnknownNote(input: ReplyMessageInput): boolean {
150
+ const ids = new Set(input.blocks.map((block) => block.id));
151
+ return input.notes.some((note) => !ids.has(note.blockId) && note.text.trim() !== "");
152
+ }
@@ -0,0 +1,116 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { extractLastReply } from "./reply.js";
3
+
4
+ function user(text: string): object {
5
+ return { id: `u-${text}`, type: "message", message: { role: "user", content: [{ type: "text", text }] } };
6
+ }
7
+
8
+ function assistant(content: unknown[], extra: Record<string, unknown> = {}): object {
9
+ return {
10
+ id: `a-${Math.random().toString(36).slice(2)}`,
11
+ type: "message",
12
+ message: { role: "assistant", content, model: "provider/model", timestamp: 1_700_000_000_000, ...extra },
13
+ };
14
+ }
15
+
16
+ describe("extractLastReply", () => {
17
+ it("returns the text of the last assistant message", () => {
18
+ const reply = extractLastReply([user("hi"), assistant([{ type: "text", text: " hello there " }])]);
19
+ expect(reply?.text).toBe("hello there");
20
+ expect(reply?.model).toBe("provider/model");
21
+ expect(reply?.at).toBe(new Date(1_700_000_000_000).toISOString());
22
+ });
23
+
24
+ it("excludes thinking and tool calls", () => {
25
+ const reply = extractLastReply([
26
+ user("hi"),
27
+ assistant([
28
+ { type: "thinking", thinking: "internal reasoning" },
29
+ { type: "toolCall", name: "bash", arguments: {} },
30
+ { type: "text", text: "the answer" },
31
+ ]),
32
+ ]);
33
+ expect(reply?.text).toBe("the answer");
34
+ });
35
+
36
+ it("drops commentary before a tool call inside the SAME assistant message", () => {
37
+ const reply = extractLastReply([
38
+ user("hi"),
39
+ assistant([
40
+ { type: "text", text: "I will check that first" },
41
+ { type: "toolCall", name: "read", arguments: {} },
42
+ { type: "text", text: "the actual answer" },
43
+ ]),
44
+ ]);
45
+ expect(reply?.text).toBe("the actual answer");
46
+ });
47
+
48
+ it("drops commentary before late thinking inside the SAME assistant message", () => {
49
+ const reply = extractLastReply([
50
+ user("hi"),
51
+ assistant([
52
+ { type: "text", text: "draft" },
53
+ { type: "thinking", thinking: "more reasoning" },
54
+ { type: "text", text: "final" },
55
+ ]),
56
+ ]);
57
+ expect(reply?.text).toBe("final");
58
+ });
59
+
60
+ it("takes only the final assistant message of a multi-step turn", () => {
61
+ const reply = extractLastReply([
62
+ user("do the thing"),
63
+ assistant([{ type: "text", text: "let me check" }]),
64
+ { id: "t1", type: "message", message: { role: "toolResult", content: [{ type: "text", text: "ok" }] } },
65
+ assistant([{ type: "text", text: "done, here is what changed" }]),
66
+ ]);
67
+ expect(reply?.text).toBe("done, here is what changed");
68
+ });
69
+
70
+ it("skips a tool-only assistant message instead of reporting no reply", () => {
71
+ const reply = extractLastReply([
72
+ user("go"),
73
+ assistant([{ type: "text", text: "the real answer" }]),
74
+ assistant([{ type: "toolCall", name: "read", arguments: {} }]),
75
+ ]);
76
+ expect(reply?.text).toBe("the real answer");
77
+ });
78
+
79
+ it("stops at the user message — an earlier turn is never the reply", () => {
80
+ const reply = extractLastReply([
81
+ user("first question"),
82
+ assistant([{ type: "text", text: "first answer" }]),
83
+ user("second question"),
84
+ ]);
85
+ expect(reply).toBeUndefined();
86
+ });
87
+
88
+ it("stops at a custom message", () => {
89
+ expect(
90
+ extractLastReply([
91
+ user("q"),
92
+ assistant([{ type: "text", text: "a" }]),
93
+ { id: "c1", type: "custom_message", customType: "keep:resumed", content: "note" },
94
+ ]),
95
+ ).toBeUndefined();
96
+ });
97
+
98
+ it("reports no reply for an empty turn", () => {
99
+ expect(extractLastReply([user("hi")])).toBeUndefined();
100
+ expect(extractLastReply([])).toBeUndefined();
101
+ });
102
+
103
+ it("fingerprints the text, so a refresh can tell same from different", () => {
104
+ const a = extractLastReply([user("q"), assistant([{ type: "text", text: "same" }])]);
105
+ const b = extractLastReply([user("q"), assistant([{ type: "text", text: "same" }])]);
106
+ const c = extractLastReply([user("q"), assistant([{ type: "text", text: "different" }])]);
107
+ expect(a?.fingerprint).toBe(b?.fingerprint);
108
+ expect(a?.fingerprint).not.toBe(c?.fingerprint);
109
+ });
110
+
111
+ it("carries the entry id so callers can test compaction survival", () => {
112
+ const entry = assistant([{ type: "text", text: "x" }]) as { id: string };
113
+ const reply = extractLastReply([user("q"), entry]);
114
+ expect(reply?.entryId).toBe(entry.id);
115
+ });
116
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * reply capture — "the agent's last formal reply", as text.
3
+ *
4
+ * The page annotates the answer, not the work that produced it: thinking blocks
5
+ * and tool calls are separate content types on the assistant message. Only the
6
+ * trailing run of `text` blocks is used, so commentary before a tool call inside
7
+ * the same message is excluded too. The other rule is the turn boundary — a run may contain several assistant messages ("let me check
8
+ * that first" → tools → the actual answer), and only the last one is the reply.
9
+ *
10
+ * The scan therefore walks backwards and stops at the first user/custom message
11
+ * (or compaction boundary). Anything older than that belongs to a previous turn
12
+ * and annotating it would be confusing: the model already moved on.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+
16
+ export interface ReplySnapshot {
17
+ text: string;
18
+ /** Session entry id, so callers can ask whether it survived compaction. */
19
+ entryId: string;
20
+ model?: string;
21
+ /** ISO timestamp of the assistant message, when the host recorded one. */
22
+ at: string;
23
+ /** Hash of the text — how a re-run decides "same reply, keep the notes". */
24
+ fingerprint: string;
25
+ }
26
+
27
+ interface ContentBlock {
28
+ type?: unknown;
29
+ text?: unknown;
30
+ }
31
+
32
+ interface MessageLike {
33
+ role?: unknown;
34
+ content?: unknown;
35
+ model?: unknown;
36
+ timestamp?: unknown;
37
+ }
38
+
39
+ interface EntryLike {
40
+ id?: unknown;
41
+ type?: unknown;
42
+ message?: MessageLike;
43
+ }
44
+
45
+ function textOf(message: MessageLike): string {
46
+ if (!Array.isArray(message.content)) return "";
47
+ let parts: string[] = [];
48
+ for (const block of message.content as ContentBlock[]) {
49
+ if (block?.type === "text" && typeof block.text === "string") {
50
+ parts.push(block.text);
51
+ } else {
52
+ // Thinking and tool calls can occur BETWEEN text blocks in one assistant
53
+ // message. Text before that boundary is commentary, not the final reply.
54
+ parts = [];
55
+ }
56
+ }
57
+ return parts.join("").trim();
58
+ }
59
+
60
+ function isTurnBoundary(entry: EntryLike): boolean {
61
+ if (entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary") {
62
+ return true;
63
+ }
64
+ return entry.type === "message" && entry.message?.role === "user";
65
+ }
66
+
67
+ /**
68
+ * Last formal reply on the branch, or undefined when the current turn has none.
69
+ *
70
+ * `entries` is `ctx.sessionManager.getBranch()` (oldest → newest).
71
+ */
72
+ export function extractLastReply(entries: readonly unknown[]): ReplySnapshot | undefined {
73
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
74
+ const entry = entries[i] as EntryLike;
75
+ if (!entry || typeof entry !== "object") continue;
76
+ if (isTurnBoundary(entry)) return undefined;
77
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
78
+ const text = textOf(entry.message);
79
+ // An assistant message with no text is a tool-only step of the same turn;
80
+ // keep walking instead of reporting "no reply".
81
+ if (text === "") continue;
82
+ const timestamp = typeof entry.message.timestamp === "number" ? entry.message.timestamp : undefined;
83
+ return {
84
+ text,
85
+ entryId: typeof entry.id === "string" ? entry.id : "",
86
+ model: typeof entry.message.model === "string" ? entry.message.model : undefined,
87
+ at: new Date(timestamp ?? Date.now()).toISOString(),
88
+ fingerprint: createHash("sha1").update(text).digest("hex").slice(0, 16),
89
+ };
90
+ }
91
+ return undefined;
92
+ }
@@ -0,0 +1,39 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseBlocks } from "../review-page/blocks.js";
3
+ import { headingDepth, sectionPaths } from "./sections.js";
4
+
5
+ describe("sectionPaths", () => {
6
+ it("labels every block with the chain of headings above it", () => {
7
+ const blocks = parseBlocks(
8
+ "# Plan\n\nintro\n\n## Approach\n\nbody\n\n### Milestones\n\ndetail\n\n## Risks\n\nrisk",
9
+ );
10
+ const paths = sectionPaths(blocks);
11
+ expect(paths.get(blocks[0].id)).toBe("Plan");
12
+ expect(paths.get(blocks[1].id)).toBe("Plan");
13
+ expect(paths.get(blocks[3].id)).toBe("Plan > Approach");
14
+ expect(paths.get(blocks[4].id)).toBe("Plan > Approach > Milestones");
15
+ expect(paths.get(blocks[5].id)).toBe("Plan > Approach > Milestones");
16
+ expect(paths.get(blocks[7].id)).toBe("Plan > Risks");
17
+ });
18
+
19
+ it("leaves blocks before the first heading without a path", () => {
20
+ const blocks = parseBlocks("preamble\n\n## Later\n\nbody");
21
+ expect(sectionPaths(blocks).get(blocks[0].id)).toBe("");
22
+ });
23
+
24
+ it("closes deeper sections when a shallower heading appears", () => {
25
+ const blocks = parseBlocks("## A\n\n### B\n\ntext\n\n## C\n\ntext");
26
+ const paths = sectionPaths(blocks);
27
+ expect(paths.get(blocks[2].id)).toBe("A > B");
28
+ expect(paths.get(blocks[4].id)).toBe("C");
29
+ });
30
+ });
31
+
32
+ describe("headingDepth", () => {
33
+ it("maps the levels actually present onto 0..3", () => {
34
+ expect(headingDepth(2, [2, 3, 4])).toBe(0);
35
+ expect(headingDepth(3, [2, 3, 4])).toBe(1);
36
+ expect(headingDepth(6, [2, 3, 4, 5, 6])).toBe(3);
37
+ expect(headingDepth(9, [2, 3])).toBe(0);
38
+ });
39
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * sections — which chapter a block belongs to.
3
+ *
4
+ * Two consumers, one answer: the page indents outline rows by this, and the
5
+ * message back to the model labels each quote with the chapter it came from
6
+ * ("where exactly are you talking about?"). Both read the same structure, so a
7
+ * note can never be filed under a heading the operator did not see.
8
+ *
9
+ * Paths are outermost → nearest ("Approach > M2 · the review page"): the model
10
+ * is locating text, and the top-level chapters are what it remembers best.
11
+ */
12
+ import type { Block } from "../review-page/blocks.js";
13
+ import { headingOf } from "../review-page/headings.js";
14
+
15
+ export interface SectionEntry {
16
+ level: number;
17
+ text: string;
18
+ }
19
+
20
+ /** One breadcrumb string per block id (blocks outside any heading get ""). */
21
+ export function sectionPaths(blocks: readonly Block[]): Map<string, string> {
22
+ const paths = new Map<string, string>();
23
+ const stack: SectionEntry[] = [];
24
+ for (const block of blocks) {
25
+ const heading = headingOf(block);
26
+ if (heading) {
27
+ // A new heading closes every open section at the same or deeper level.
28
+ while (stack.length > 0 && (stack.at(-1)?.level ?? 0) >= heading.level) stack.pop();
29
+ stack.push(heading);
30
+ }
31
+ paths.set(
32
+ block.id,
33
+ stack.map((entry) => entry.text).join(" > "),
34
+ );
35
+ }
36
+ return paths;
37
+ }
38
+
39
+ /** Depth of a heading inside its outline (0 = top level present in the doc). */
40
+ export function headingDepth(level: number, levels: readonly number[]): number {
41
+ const distinct = [...new Set(levels)].sort((a, b) => a - b);
42
+ const index = distinct.indexOf(level);
43
+ return index < 0 ? 0 : Math.min(index, 3);
44
+ }