@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.
- package/CHANGELOG.md +21 -0
- package/README.md +65 -1
- package/README.zh-CN.md +58 -1
- package/package.json +7 -4
- package/src/features/keep/constants.ts +44 -0
- package/src/features/keep/format.ts +77 -0
- package/src/features/keep/index.ts +409 -0
- package/src/features/keep/keep.test.ts +955 -0
- package/src/features/keep/ledger.ts +340 -0
- package/src/features/keep/picker.ts +257 -0
- package/src/features/keep/store.ts +271 -0
- package/src/features/review-page/assets/index-CrDwcsqI.css +1 -0
- package/src/features/review-page/assets/index-DYxi32gA.js +1 -0
- package/src/features/{spec → review-page}/assets/index.html +2 -2
- package/src/features/{spec → review-page}/blocks.test.ts +17 -0
- package/src/features/{spec → review-page}/blocks.ts +9 -0
- package/src/features/review-page/headings.test.ts +44 -0
- package/src/features/review-page/headings.ts +67 -0
- package/src/features/spec/assets.test.ts +2 -2
- package/src/features/spec/diff.test.ts +1 -1
- package/src/features/spec/diff.ts +1 -1
- package/src/features/spec/feedback.test.ts +1 -1
- package/src/features/spec/feedback.ts +1 -1
- package/src/features/spec/index.test.ts +121 -0
- package/src/features/spec/index.ts +82 -23
- package/src/features/spec/server.test.ts +65 -2
- package/src/features/spec/server.ts +29 -5
- package/src/features/spec/store.ts +1 -1
- package/src/features/talk/index.test.ts +230 -0
- package/src/features/talk/index.ts +241 -0
- package/src/features/talk/message.test.ts +212 -0
- package/src/features/talk/message.ts +152 -0
- package/src/features/talk/reply.test.ts +116 -0
- package/src/features/talk/reply.ts +92 -0
- package/src/features/talk/sections.test.ts +39 -0
- package/src/features/talk/sections.ts +44 -0
- package/src/features/talk/server.test.ts +247 -0
- package/src/features/talk/server.ts +211 -0
- package/src/features/uat/ledger.ts +13 -62
- package/src/index.ts +7 -0
- package/src/lib/event-ledger.ts +112 -0
- package/src/features/spec/assets/index-CdTerMvN.css +0 -1
- package/src/features/spec/assets/index-Dv52AIjX.js +0 -1
- /package/src/features/{spec → review-page}/render.test.ts +0 -0
- /package/src/features/{spec → review-page}/render.ts +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { request } from "node:http";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { parseBlocks } from "../review-page/blocks.js";
|
|
4
|
+
import { renderBlockHtml } from "../review-page/render.js";
|
|
5
|
+
import { buildTalkState, sanitizeNotes, startTalkServer, type TalkServerHandle, type TalkSession } from "./server.js";
|
|
6
|
+
|
|
7
|
+
const REPLY = "## Approach\n\nfirst block\n\n## Milestones\n\nsecond block";
|
|
8
|
+
|
|
9
|
+
function makeSession(overrides: Partial<TalkSession> = {}): TalkSession {
|
|
10
|
+
const blocks = parseBlocks(REPLY);
|
|
11
|
+
return {
|
|
12
|
+
text: REPLY,
|
|
13
|
+
blocks,
|
|
14
|
+
headings: [],
|
|
15
|
+
model: "provider/model",
|
|
16
|
+
at: "2026-11-25T00:00:00.000Z",
|
|
17
|
+
entryId: "reply-entry",
|
|
18
|
+
fingerprint: "abc",
|
|
19
|
+
notes: {},
|
|
20
|
+
draft: "",
|
|
21
|
+
sent: false,
|
|
22
|
+
inContext: true,
|
|
23
|
+
...overrides,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function serve(
|
|
28
|
+
session: TalkSession,
|
|
29
|
+
overrides: Partial<Parameters<typeof startTalkServer>[0]> = {},
|
|
30
|
+
): Promise<TalkServerHandle> {
|
|
31
|
+
return startTalkServer({
|
|
32
|
+
session,
|
|
33
|
+
assetsDir: "/nonexistent-assets",
|
|
34
|
+
render: renderBlockHtml,
|
|
35
|
+
portStart: 45_000 + Math.floor(Math.random() * 2000),
|
|
36
|
+
portAttempts: 20,
|
|
37
|
+
bindHost: "127.0.0.1",
|
|
38
|
+
urlHost: "127.0.0.1",
|
|
39
|
+
closeDelayMs: 0,
|
|
40
|
+
...overrides,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface CallResult {
|
|
45
|
+
status: number;
|
|
46
|
+
text: string;
|
|
47
|
+
json: () => unknown;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function call(
|
|
51
|
+
port: number,
|
|
52
|
+
path: string,
|
|
53
|
+
options: { method?: string; token?: string; body?: unknown; headers?: Record<string, string> } = {},
|
|
54
|
+
): Promise<CallResult> {
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const headers: Record<string, string> = { ...(options.headers ?? {}) };
|
|
57
|
+
if (options.token) headers["x-plan-token"] = options.token;
|
|
58
|
+
if (options.body !== undefined) headers["content-type"] = "application/json";
|
|
59
|
+
const req = request(
|
|
60
|
+
{
|
|
61
|
+
host: "127.0.0.1",
|
|
62
|
+
port,
|
|
63
|
+
method: options.method ?? "GET",
|
|
64
|
+
path,
|
|
65
|
+
headers,
|
|
66
|
+
},
|
|
67
|
+
(res) => {
|
|
68
|
+
const chunks: Buffer[] = [];
|
|
69
|
+
res.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
70
|
+
res.on("end", () => {
|
|
71
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
72
|
+
resolve({ status: res.statusCode ?? 0, text, json: () => JSON.parse(text) as unknown });
|
|
73
|
+
});
|
|
74
|
+
},
|
|
75
|
+
);
|
|
76
|
+
req.on("error", reject);
|
|
77
|
+
if (options.body !== undefined) req.write(JSON.stringify(options.body));
|
|
78
|
+
req.end();
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
describe("buildTalkState", () => {
|
|
83
|
+
it("describes the snapshot without any version or diff fields", () => {
|
|
84
|
+
const session = makeSession();
|
|
85
|
+
const state = buildTalkState(session);
|
|
86
|
+
expect(state.mode).toBe("talk");
|
|
87
|
+
expect(state.reply).toEqual({ model: "provider/model", at: "2026-11-25T00:00:00.000Z", chars: REPLY.length });
|
|
88
|
+
expect(state.items).toHaveLength(4);
|
|
89
|
+
expect(state.items.every((item) => item.html === "")).toBe(true);
|
|
90
|
+
expect(state).not.toHaveProperty("version");
|
|
91
|
+
expect(state).not.toHaveProperty("history");
|
|
92
|
+
expect(state.sent).toBe(false);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe("sanitizeNotes", () => {
|
|
97
|
+
it("keeps only non-heading notes on blocks of this reply, with real text", () => {
|
|
98
|
+
const blocks = parseBlocks(REPLY);
|
|
99
|
+
const notes = sanitizeNotes(
|
|
100
|
+
{ [blocks[0].id]: "heading notes are not allowed", [blocks[1].id]: "keep", "stale#0": "drop", [blocks[2].id]: " ", [blocks[3].id]: 42 },
|
|
101
|
+
blocks,
|
|
102
|
+
);
|
|
103
|
+
expect(notes).toEqual({ [blocks[1].id]: "keep" });
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe("talk server", () => {
|
|
108
|
+
it("serves state with rendered blocks and the headings index", async () => {
|
|
109
|
+
const session = makeSession();
|
|
110
|
+
const server = await serve(session);
|
|
111
|
+
try {
|
|
112
|
+
const response = await call(server.port, `/api/state?t=${server.token}`);
|
|
113
|
+
expect(response.status).toBe(200);
|
|
114
|
+
const state = response.json() as {
|
|
115
|
+
mode: string;
|
|
116
|
+
items: Array<{ html: string }>;
|
|
117
|
+
headings: unknown[];
|
|
118
|
+
sent: boolean;
|
|
119
|
+
};
|
|
120
|
+
expect(state.mode).toBe("talk");
|
|
121
|
+
expect(state.items[0].html).toContain("<h2>");
|
|
122
|
+
expect(Array.isArray(state.headings)).toBe(true);
|
|
123
|
+
expect(state.sent).toBe(false);
|
|
124
|
+
} finally {
|
|
125
|
+
await server.close();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("stores notes and the draft so a page refresh does not lose them", async () => {
|
|
130
|
+
const session = makeSession();
|
|
131
|
+
const server = await serve(session);
|
|
132
|
+
try {
|
|
133
|
+
const blockId = session.blocks[1].id;
|
|
134
|
+
const posted = await call(server.port, "/api/notes", {
|
|
135
|
+
method: "POST",
|
|
136
|
+
token: server.token,
|
|
137
|
+
body: { notes: { [blockId]: "reword me" }, draft: "half-typed thought" },
|
|
138
|
+
});
|
|
139
|
+
expect(posted.status).toBe(200);
|
|
140
|
+
expect(session.notes).toEqual({ [blockId]: "reword me" });
|
|
141
|
+
const state = (await call(server.port, `/api/state?t=${server.token}`)).json() as {
|
|
142
|
+
notes: Record<string, string>;
|
|
143
|
+
draft: string;
|
|
144
|
+
};
|
|
145
|
+
expect(state.notes).toEqual({ [blockId]: "reword me" });
|
|
146
|
+
expect(state.draft).toBe("half-typed thought");
|
|
147
|
+
} finally {
|
|
148
|
+
await server.close();
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("accepts exactly one Continue and refuses every later write", async () => {
|
|
153
|
+
const session = makeSession();
|
|
154
|
+
const received: Array<{ notes: Record<string, string>; message: string }> = [];
|
|
155
|
+
const server = await serve(session, {
|
|
156
|
+
onContinue: (result) => received.push(result),
|
|
157
|
+
// Keep the socket open long enough that the follow-up writes hit the
|
|
158
|
+
// 409 guard instead of a closed port — that guard is what the test is about.
|
|
159
|
+
closeDelayMs: 400,
|
|
160
|
+
});
|
|
161
|
+
try {
|
|
162
|
+
const first = await call(server.port, "/api/continue", {
|
|
163
|
+
method: "POST",
|
|
164
|
+
token: server.token,
|
|
165
|
+
body: { notes: { [session.blocks[3].id]: "fix it" }, message: "go on" },
|
|
166
|
+
});
|
|
167
|
+
expect(first.status).toBe(200);
|
|
168
|
+
expect(received).toHaveLength(1);
|
|
169
|
+
expect(received[0].message).toBe("go on");
|
|
170
|
+
expect(server.active()).toBe(false);
|
|
171
|
+
|
|
172
|
+
const second = await call(server.port, "/api/continue", {
|
|
173
|
+
method: "POST",
|
|
174
|
+
token: server.token,
|
|
175
|
+
body: { message: "again" },
|
|
176
|
+
});
|
|
177
|
+
expect(second.status).toBe(409);
|
|
178
|
+
const notes = await call(server.port, "/api/notes", {
|
|
179
|
+
method: "POST",
|
|
180
|
+
token: server.token,
|
|
181
|
+
body: { notes: {} },
|
|
182
|
+
});
|
|
183
|
+
expect(notes.status).toBe(409);
|
|
184
|
+
expect(received).toHaveLength(1);
|
|
185
|
+
expect(session.sent).toBe(true);
|
|
186
|
+
} finally {
|
|
187
|
+
await server.close();
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it("refuses unauthenticated and cross-origin writes like the spec server", async () => {
|
|
192
|
+
const server = await serve(makeSession());
|
|
193
|
+
try {
|
|
194
|
+
expect((await call(server.port, "/api/state")).status).toBe(401);
|
|
195
|
+
const crossOrigin = await call(server.port, "/api/notes", {
|
|
196
|
+
method: "POST",
|
|
197
|
+
token: server.token,
|
|
198
|
+
body: { notes: {} },
|
|
199
|
+
headers: { origin: "http://evil.example" },
|
|
200
|
+
});
|
|
201
|
+
expect(crossOrigin.status).toBe(403);
|
|
202
|
+
} finally {
|
|
203
|
+
await server.close();
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it("broadcasts sent once so an open page can switch to the sent state", async () => {
|
|
208
|
+
const server = await serve(makeSession());
|
|
209
|
+
const seen: string[] = [];
|
|
210
|
+
try {
|
|
211
|
+
const response = await new Promise<{ status: number; text: string }>((resolve, reject) => {
|
|
212
|
+
const req = request(
|
|
213
|
+
{ host: "127.0.0.1", port: server.port, path: `/api/events?t=${server.token}` },
|
|
214
|
+
(res) => {
|
|
215
|
+
const chunks: string[] = [];
|
|
216
|
+
res.on("data", (chunk: Buffer) => {
|
|
217
|
+
chunks.push(chunk.toString());
|
|
218
|
+
const text = chunks.join("");
|
|
219
|
+
if (!text.includes("event: sent")) {
|
|
220
|
+
if (text.includes(": connected")) {
|
|
221
|
+
void call(server.port, "/api/continue", {
|
|
222
|
+
method: "POST",
|
|
223
|
+
token: server.token,
|
|
224
|
+
body: { message: "go" },
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
req.destroy();
|
|
230
|
+
for (const line of text.split("\n")) if (line.startsWith("event: ")) seen.push(line.slice(7));
|
|
231
|
+
resolve({ status: res.statusCode ?? 0, text });
|
|
232
|
+
});
|
|
233
|
+
},
|
|
234
|
+
);
|
|
235
|
+
req.on("error", (error) => {
|
|
236
|
+
if ((error as NodeJS.ErrnoException).code === "ECONNRESET") return;
|
|
237
|
+
reject(error);
|
|
238
|
+
});
|
|
239
|
+
req.end();
|
|
240
|
+
});
|
|
241
|
+
expect(response.status).toBe(200);
|
|
242
|
+
expect(seen).toContain("sent");
|
|
243
|
+
} finally {
|
|
244
|
+
await server.close();
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
});
|