@andares/pi-toolkits 0.12.3 → 0.13.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/README.md +100 -15
- package/README.zh-CN.md +94 -14
- package/package.json +19 -10
- package/src/features/ask/index.ts +6 -0
- package/src/features/init/apply.ts +32 -12
- package/src/features/init/audit-uat.test.ts +103 -0
- package/src/features/init/audit.ts +148 -0
- package/src/features/init/detect.ts +4 -0
- package/src/features/init/index.ts +47 -2
- package/src/features/init/plan.ts +11 -0
- package/src/features/init/refresh.test.ts +208 -0
- package/src/features/init/refresh.ts +255 -0
- package/src/features/init/spec.ts +20 -0
- package/src/features/init/templates/agents-skeleton.md +2 -0
- package/src/features/init/templates/uat-readme.md +53 -0
- package/src/features/init/templates/workflow-block.md +21 -0
- package/src/features/init/templates.test.ts +3 -1
- package/src/features/init/templates.ts +2 -0
- package/src/features/init/types.ts +12 -1
- package/src/features/permission/index.ts +32 -0
- package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
- package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
- package/src/features/plan/assets/index.html +14 -0
- package/src/features/plan/assets.test.ts +64 -0
- package/src/features/plan/blocks.test.ts +77 -0
- package/src/features/plan/blocks.ts +153 -0
- package/src/features/plan/diff.test.ts +144 -0
- package/src/features/plan/diff.ts +193 -0
- package/src/features/plan/feedback.test.ts +233 -0
- package/src/features/plan/feedback.ts +182 -0
- package/src/features/plan/index.test.ts +385 -0
- package/src/features/plan/index.ts +433 -0
- package/src/features/plan/prompt.test.ts +91 -0
- package/src/features/plan/prompt.ts +110 -0
- package/src/features/plan/render.test.ts +94 -0
- package/src/features/plan/render.ts +131 -0
- package/src/features/plan/server.test.ts +374 -0
- package/src/features/plan/server.ts +272 -0
- package/src/features/plan/store.test.ts +145 -0
- package/src/features/plan/store.ts +244 -0
- package/src/features/review/index.ts +54 -28
- package/src/features/review/review.test.ts +46 -1
- package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
- package/src/features/uat/assets/index-DCBQCsli.js +1 -0
- package/src/features/uat/assets/index.html +14 -0
- package/src/features/uat/constants.ts +23 -0
- package/src/features/uat/index.test.ts +404 -0
- package/src/features/uat/index.ts +329 -0
- package/src/features/uat/item-tool.ts +280 -0
- package/src/features/uat/ledger.test.ts +249 -0
- package/src/features/uat/ledger.ts +504 -0
- package/src/features/uat/prompt.ts +78 -0
- package/src/features/uat/record-tool.ts +167 -0
- package/src/features/uat/records.test.ts +145 -0
- package/src/features/uat/records.ts +268 -0
- package/src/features/uat/server.ts +181 -0
- package/src/features/uat/state.test.ts +41 -0
- package/src/features/uat/state.ts +67 -0
- package/src/index.ts +10 -1
- package/src/lib/ask-control.ts +25 -0
- package/src/lib/opener.test.ts +72 -0
- package/src/lib/opener.ts +121 -0
- package/src/lib/permission-control.ts +39 -0
- package/src/lib/startup.test.ts +1 -1
- package/src/lib/web-review.ts +341 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { blockLabel, hashBlockText, normalizeBlockText, parseBlocks } from "./blocks.js";
|
|
3
|
+
|
|
4
|
+
describe("parseBlocks", () => {
|
|
5
|
+
it("splits paragraphs on blank lines", () => {
|
|
6
|
+
const blocks = parseBlocks("first para\n\nsecond para\n\nthird");
|
|
7
|
+
expect(blocks.map((block) => block.text)).toEqual(["first para", "second para", "third"]);
|
|
8
|
+
expect(blocks.map((block) => block.index)).toEqual([0, 1, 2]);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it("keeps a fenced code block whole even with blank lines inside", () => {
|
|
12
|
+
const markdown = ["intro", "", "```ts", "const a = 1;", "", "const b = 2;", "```", "", "tail"].join("\n");
|
|
13
|
+
const blocks = parseBlocks(markdown);
|
|
14
|
+
expect(blocks).toHaveLength(3);
|
|
15
|
+
expect(blocks[1]?.kind).toBe("code");
|
|
16
|
+
expect(blocks[1]?.text).toBe("```ts\nconst a = 1;\n\nconst b = 2;\n```");
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("closes a fence only on a run as long as the opener", () => {
|
|
20
|
+
const markdown = ["~~~~", "```", "still code", "```", "~~~", "still code", "~~~~"].join("\n");
|
|
21
|
+
const blocks = parseBlocks(markdown);
|
|
22
|
+
expect(blocks).toHaveLength(1);
|
|
23
|
+
expect(blocks[0]?.kind).toBe("code");
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("treats a heading line as its own block", () => {
|
|
27
|
+
const blocks = parseBlocks("## Title\n\ntext");
|
|
28
|
+
expect(blocks[0]?.kind).toBe("heading");
|
|
29
|
+
expect(blocks[1]?.kind).toBe("text");
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("classifies lists, quotes and tables", () => {
|
|
33
|
+
const blocks = parseBlocks("- one\n- two\n\n> quoted\n\n| a | b |\n| --- | --- |\n| 1 | 2 |");
|
|
34
|
+
expect(blocks.map((block) => block.kind)).toEqual(["list", "quote", "table"]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("gives duplicate paragraphs distinct ids", () => {
|
|
38
|
+
const blocks = parseBlocks("same\n\nsame");
|
|
39
|
+
expect(blocks[0]?.hash).toBe(blocks[1]?.hash);
|
|
40
|
+
expect(blocks[0]?.id).not.toBe(blocks[1]?.id);
|
|
41
|
+
expect(blocks[0]?.id.endsWith("#0")).toBe(true);
|
|
42
|
+
expect(blocks[1]?.id.endsWith("#1")).toBe(true);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("reports 1-based start lines", () => {
|
|
46
|
+
const blocks = parseBlocks("a\n\nb\n\n\nc");
|
|
47
|
+
expect(blocks.map((block) => block.line)).toEqual([1, 3, 6]);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("normalizes CRLF", () => {
|
|
51
|
+
const blocks = parseBlocks("a\r\n\r\nb\r\n");
|
|
52
|
+
expect(blocks.map((block) => block.text)).toEqual(["a", "b"]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("returns nothing for an empty or blank-only document", () => {
|
|
56
|
+
expect(parseBlocks("")).toEqual([]);
|
|
57
|
+
expect(parseBlocks("\n\n \n\n")).toEqual([]);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe("block identity", () => {
|
|
62
|
+
it("ignores reflow and indentation when hashing", () => {
|
|
63
|
+
expect(normalizeBlockText("one two\n three")).toBe("one two three");
|
|
64
|
+
expect(hashBlockText("one two\n three")).toBe(hashBlockText("one two three"));
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("is case sensitive — a rename is a change", () => {
|
|
68
|
+
expect(hashBlockText("Plan")).not.toBe(hashBlockText("plan"));
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe("blockLabel", () => {
|
|
73
|
+
it("uses the first line and clips it", () => {
|
|
74
|
+
const [block] = parseBlocks("## A very long heading that keeps going and going\n\nbody");
|
|
75
|
+
expect(blockLabel(block!, 20)).toBe("## A very long head…");
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* plan blocks — the review unit of `/ask-plan`.
|
|
3
|
+
*
|
|
4
|
+
* A block is one blank-line-separated paragraph of the plan markdown: that is
|
|
5
|
+
* the granularity the operator annotates at ("this step is wrong"), so there is
|
|
6
|
+
* deliberately no AST here — no inline spans, no line-level addressing.
|
|
7
|
+
*
|
|
8
|
+
* Two rules make the model survive edits:
|
|
9
|
+
* - a fenced code block is ONE block, even though it usually contains blank
|
|
10
|
+
* lines (splitting it would turn a snippet into nonsense fragments);
|
|
11
|
+
* - a block's identity is a hash of its normalized text, so reflowing prose
|
|
12
|
+
* or re-indenting does not read as "changed", while any word change does.
|
|
13
|
+
*
|
|
14
|
+
* Duplicate paragraphs are legal in a plan (two identical steps, two identical
|
|
15
|
+
* bullets), so the id carries the occurrence index: `hash#0`, `hash#1`, …
|
|
16
|
+
*/
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
|
|
19
|
+
export type BlockKind = "heading" | "text" | "list" | "code" | "table" | "quote";
|
|
20
|
+
|
|
21
|
+
export interface Block {
|
|
22
|
+
/** `hash#occurrence` — stable across reflow, distinguishes duplicates. */
|
|
23
|
+
id: string;
|
|
24
|
+
kind: BlockKind;
|
|
25
|
+
/** Raw markdown of the block (trimmed, inner blank lines kept). */
|
|
26
|
+
text: string;
|
|
27
|
+
/** Hash of the normalized text — equal hash means "not changed". */
|
|
28
|
+
hash: string;
|
|
29
|
+
/** 0-based position in the document. */
|
|
30
|
+
index: number;
|
|
31
|
+
/** 1-based line number of the block's first line. */
|
|
32
|
+
line: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
36
|
+
const HEADING_RE = /^ {0,3}#{1,6}\s/;
|
|
37
|
+
const QUOTE_RE = /^ {0,3}>\s?/;
|
|
38
|
+
const LIST_RE = /^ {0,3}(?:[-*+]|\d{1,9}[.)])\s/;
|
|
39
|
+
const TABLE_SEPARATOR_RE = /^ {0,3}\|?[\s:-]*-{3,}[\s:|-]*$/;
|
|
40
|
+
|
|
41
|
+
/** Normalize a block for hashing: reflow-insensitive, case-sensitive. */
|
|
42
|
+
export function normalizeBlockText(text: string): string {
|
|
43
|
+
return text
|
|
44
|
+
.split("\n")
|
|
45
|
+
.map((line) => line.trim())
|
|
46
|
+
.join(" ")
|
|
47
|
+
.replace(/\s+/g, " ")
|
|
48
|
+
.trim();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 12 hex chars of sha1 — short enough to read in an id, wide enough to not collide. */
|
|
52
|
+
export function hashBlockText(text: string): string {
|
|
53
|
+
return createHash("sha1").update(normalizeBlockText(text)).digest("hex").slice(0, 12);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function classify(lines: readonly string[]): BlockKind {
|
|
57
|
+
const first = lines[0] ?? "";
|
|
58
|
+
if (FENCE_RE.test(first)) return "code";
|
|
59
|
+
if (HEADING_RE.test(first)) return "heading";
|
|
60
|
+
if (QUOTE_RE.test(first)) return "quote";
|
|
61
|
+
if (lines.length >= 2 && first.includes("|") && TABLE_SEPARATOR_RE.test(lines[1] ?? "")) {
|
|
62
|
+
return "table";
|
|
63
|
+
}
|
|
64
|
+
if (LIST_RE.test(first)) return "list";
|
|
65
|
+
return "text";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface Chunk {
|
|
69
|
+
lines: string[];
|
|
70
|
+
line: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Split markdown into chunks: blank-line separated, fence-aware. */
|
|
74
|
+
function splitChunks(markdown: string): Chunk[] {
|
|
75
|
+
const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
|
|
76
|
+
const chunks: Chunk[] = [];
|
|
77
|
+
let current: string[] = [];
|
|
78
|
+
let startLine = 1;
|
|
79
|
+
/** Open fence: its character and its opening run length. */
|
|
80
|
+
let fence: { char: string; length: number } | null = null;
|
|
81
|
+
|
|
82
|
+
const flush = (): void => {
|
|
83
|
+
if (current.length === 0) return;
|
|
84
|
+
chunks.push({ lines: current, line: startLine });
|
|
85
|
+
current = [];
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
89
|
+
const line = lines[i] ?? "";
|
|
90
|
+
const fenceMatch = FENCE_RE.exec(line);
|
|
91
|
+
|
|
92
|
+
if (fence) {
|
|
93
|
+
if (current.length === 0) startLine = i + 1;
|
|
94
|
+
current.push(line);
|
|
95
|
+
// Close only on a run of the same character at least as long as the
|
|
96
|
+
// opener (CommonMark): ``` inside a ~~~~ block is content.
|
|
97
|
+
if (
|
|
98
|
+
fenceMatch &&
|
|
99
|
+
fenceMatch[1]?.startsWith(fence.char) &&
|
|
100
|
+
fenceMatch[1].length >= fence.length
|
|
101
|
+
) {
|
|
102
|
+
fence = null;
|
|
103
|
+
}
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (fenceMatch) {
|
|
108
|
+
if (current.length === 0) startLine = i + 1;
|
|
109
|
+
fence = { char: fenceMatch[1][0], length: fenceMatch[1].length };
|
|
110
|
+
current.push(line);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (line.trim() === "") {
|
|
115
|
+
flush();
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (current.length === 0) startLine = i + 1;
|
|
120
|
+
current.push(line);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
flush();
|
|
124
|
+
return chunks;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Parse plan markdown into blocks. An empty document yields no blocks; a
|
|
129
|
+
* document that is only blank lines yields none either (never a phantom block).
|
|
130
|
+
*/
|
|
131
|
+
export function parseBlocks(markdown: string): Block[] {
|
|
132
|
+
const seen = new Map<string, number>();
|
|
133
|
+
return splitChunks(markdown).map((chunk, index) => {
|
|
134
|
+
const text = chunk.lines.join("\n").trim();
|
|
135
|
+
const hash = hashBlockText(text);
|
|
136
|
+
const occurrence = seen.get(hash) ?? 0;
|
|
137
|
+
seen.set(hash, occurrence + 1);
|
|
138
|
+
return {
|
|
139
|
+
id: `${hash}#${occurrence}`,
|
|
140
|
+
kind: classify(chunk.lines),
|
|
141
|
+
text,
|
|
142
|
+
hash,
|
|
143
|
+
index,
|
|
144
|
+
line: chunk.line,
|
|
145
|
+
};
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** One-line label for a block: its first line, clipped — used in feedback text. */
|
|
150
|
+
export function blockLabel(block: Block, maxLength = 80): string {
|
|
151
|
+
const first = (block.text.split("\n")[0] ?? "").trim();
|
|
152
|
+
return first.length > maxLength ? `${first.slice(0, maxLength - 1)}…` : first;
|
|
153
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { parseBlocks } from "./blocks.js";
|
|
3
|
+
import { blockSimilarity, countChanged, diffBlocks } from "./diff.js";
|
|
4
|
+
|
|
5
|
+
const parse = (markdown: string) => parseBlocks(markdown);
|
|
6
|
+
|
|
7
|
+
describe("diffBlocks", () => {
|
|
8
|
+
it("reports everything unchanged for identical revisions", () => {
|
|
9
|
+
const doc = parse("alpha\n\nbeta\n\ngamma");
|
|
10
|
+
const entries = diffBlocks(doc, parse("alpha\n\nbeta\n\ngamma"));
|
|
11
|
+
expect(entries.map((entry) => entry.status)).toEqual(["unchanged", "unchanged", "unchanged"]);
|
|
12
|
+
expect(countChanged(entries)).toBe(0);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it("calls a reworded block modified, not added+removed", () => {
|
|
16
|
+
const before = parse("Write the parser first, then the server.");
|
|
17
|
+
const after = parse("Write the block parser first, then the HTTP server.");
|
|
18
|
+
const entries = diffBlocks(before, after);
|
|
19
|
+
expect(entries).toHaveLength(1);
|
|
20
|
+
expect(entries[0]?.status).toBe("modified");
|
|
21
|
+
expect(entries[0]?.prevId).toBe(before[0]?.id);
|
|
22
|
+
expect(entries[0]?.id).toBe(after[0]?.id);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("reports an appended block as added", () => {
|
|
26
|
+
const before = parse("alpha\n\nbeta");
|
|
27
|
+
const after = parse("alpha\n\nbeta\n\ngamma");
|
|
28
|
+
const entries = diffBlocks(before, after);
|
|
29
|
+
expect(entries.map((entry) => entry.status)).toEqual(["unchanged", "unchanged", "added"]);
|
|
30
|
+
expect(entries[2]?.id).toBe(after[2]?.id);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("reports a deleted block as removed, in the position it left", () => {
|
|
34
|
+
const before = parse("alpha\n\nbeta\n\ngamma");
|
|
35
|
+
const after = parse("alpha\n\ngamma");
|
|
36
|
+
const entries = diffBlocks(before, after);
|
|
37
|
+
expect(entries.map((entry) => entry.status)).toEqual(["unchanged", "removed", "unchanged"]);
|
|
38
|
+
expect(entries[1]?.id).toBe(before[1]?.id);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("reports a block that only changed position as moved", () => {
|
|
42
|
+
const before = parse("alpha\n\nbeta");
|
|
43
|
+
const after = parse("beta\n\nalpha");
|
|
44
|
+
const entries = diffBlocks(before, after);
|
|
45
|
+
expect(entries).toHaveLength(2);
|
|
46
|
+
// Which of the two keeps the anchor is arbitrary; the contract is that
|
|
47
|
+
// exactly one is unchanged and the other is moved — never add+remove.
|
|
48
|
+
expect(entries.map((entry) => entry.status).sort()).toEqual(["moved", "unchanged"]);
|
|
49
|
+
expect(countChanged(entries)).toBe(1);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("does not pair unrelated blocks as modified", () => {
|
|
53
|
+
const before = parse("Deploy the worker container.");
|
|
54
|
+
const after = parse("Buy milk and eggs.");
|
|
55
|
+
const entries = diffBlocks(before, after);
|
|
56
|
+
expect(entries.map((entry) => entry.status)).toEqual(["removed", "added"]);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("handles a full rewrite without inventing modifications", () => {
|
|
60
|
+
const before = parse("one\n\ntwo\n\nthree");
|
|
61
|
+
const after = parse("alpha\n\nbeta\n\ngamma");
|
|
62
|
+
const entries = diffBlocks(before, after);
|
|
63
|
+
expect(countChanged(entries)).toBe(6);
|
|
64
|
+
expect(entries.some((entry) => entry.status === "unchanged")).toBe(false);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("keeps a rotation as one move, not as edits", () => {
|
|
68
|
+
const before = parse("one\n\ntwo\n\nthree");
|
|
69
|
+
const after = parse("three\n\none\n\ntwo");
|
|
70
|
+
const entries = diffBlocks(before, after);
|
|
71
|
+
expect(entries.filter((entry) => entry.status === "modified")).toHaveLength(0);
|
|
72
|
+
expect(entries.filter((entry) => entry.status === "moved")).toHaveLength(1);
|
|
73
|
+
expect(entries.filter((entry) => entry.status === "unchanged")).toHaveLength(2);
|
|
74
|
+
expect(entries).toHaveLength(3);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("keeps reading order: removals before the blocks that replace them", () => {
|
|
78
|
+
const before = parse("keep\n\nold block to delete\n\ntail");
|
|
79
|
+
const after = parse("keep\n\nnew block entirely\n\ntail");
|
|
80
|
+
const entries = diffBlocks(before, after);
|
|
81
|
+
expect(entries.map((entry) => entry.status)).toEqual([
|
|
82
|
+
"unchanged",
|
|
83
|
+
"removed",
|
|
84
|
+
"added",
|
|
85
|
+
"unchanged",
|
|
86
|
+
]);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("diffs against an empty previous revision as pure additions", () => {
|
|
90
|
+
const after = parse("alpha\n\nbeta");
|
|
91
|
+
const entries = diffBlocks([], after);
|
|
92
|
+
expect(entries.map((entry) => entry.status)).toEqual(["added", "added"]);
|
|
93
|
+
});
|
|
94
|
+
it("accounts for every old and new block exactly once across reorder/edit churn", () => {
|
|
95
|
+
let seed = 17;
|
|
96
|
+
const random = () => {
|
|
97
|
+
seed = (seed * 1103515245 + 12345) % 2147483648;
|
|
98
|
+
return seed / 2147483648;
|
|
99
|
+
};
|
|
100
|
+
const vocabulary = ["alpha step", "beta step", "gamma step", "delta step", "epsilon step"];
|
|
101
|
+
for (let round = 0; round < 80; round += 1) {
|
|
102
|
+
const before = vocabulary
|
|
103
|
+
.map((text) => ({ text, score: random() }))
|
|
104
|
+
.sort((a, b) => a.score - b.score)
|
|
105
|
+
.slice(0, 3 + Math.floor(random() * 3))
|
|
106
|
+
.map((entry) => entry.text);
|
|
107
|
+
const after = before.map((text) => (random() < 0.35 ? `${text} with detail` : text));
|
|
108
|
+
if (random() < 0.5) after.push("zeta step");
|
|
109
|
+
// Deterministic rotation instead of a biased random comparator.
|
|
110
|
+
const shift = Math.floor(random() * Math.max(after.length, 1));
|
|
111
|
+
after.push(...after.splice(0, shift));
|
|
112
|
+
const previous = parse(before.join("\n\n"));
|
|
113
|
+
const next = parse(after.join("\n\n"));
|
|
114
|
+
const entries = diffBlocks(previous, next);
|
|
115
|
+
expect(
|
|
116
|
+
entries.filter((entry) => entry.status !== "removed").map((entry) => entry.id),
|
|
117
|
+
).toEqual(next.map((block) => block.id));
|
|
118
|
+
const coveredPrevious = entries.flatMap((entry) => {
|
|
119
|
+
if (entry.status === "added") return [];
|
|
120
|
+
if (entry.status === "unchanged") return [entry.id];
|
|
121
|
+
return entry.prevId ? [entry.prevId] : [];
|
|
122
|
+
});
|
|
123
|
+
expect(new Set(coveredPrevious).size).toBe(previous.length);
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
describe("blockSimilarity", () => {
|
|
129
|
+
it("is 1 for identical text and low for unrelated text", () => {
|
|
130
|
+
const a = parse("Write the block parser.")[0]!;
|
|
131
|
+
const b = parse("Write the block parser.")[0]!;
|
|
132
|
+
const c = parse("Completely different sentence about cooking.")[0]!;
|
|
133
|
+
expect(blockSimilarity(a, b)).toBe(1);
|
|
134
|
+
expect(blockSimilarity(a, c)).toBeLessThan(0.2);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("works on CJK text (bigrams, not words)", () => {
|
|
138
|
+
const a = parse("先做块模型,再做服务器。")[0]!;
|
|
139
|
+
const b = parse("先做块模型,然后做服务器。")[0]!;
|
|
140
|
+
const c = parse("今天天气不错,出去走走。")[0]!;
|
|
141
|
+
expect(blockSimilarity(a, b)).toBeGreaterThan(0.5);
|
|
142
|
+
expect(blockSimilarity(a, c)).toBeLessThan(0.2);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* plan block diff — round-over-round change detection at block granularity.
|
|
3
|
+
*
|
|
4
|
+
* A plan revision is compared against the previous one to answer one question
|
|
5
|
+
* per block: unchanged, moved, modified, added, or removed. That answer drives
|
|
6
|
+
* the badges in the review UI and the "(modified)" tag in the feedback text the
|
|
7
|
+
* agent reads, so it has to be honest: a block with three swapped words is
|
|
8
|
+
* "modified", not "one deleted + one added", and a paragraph that only changed
|
|
9
|
+
* position is "moved", not an edit — otherwise every small revision looks like
|
|
10
|
+
* a rewrite and the operator stops trusting the badges.
|
|
11
|
+
*
|
|
12
|
+
* How, in order:
|
|
13
|
+
* 1. Blocks with the same id (identical normalized text) are matched. The
|
|
14
|
+
* longest increasing subsequence of those matches is the set of anchors
|
|
15
|
+
* ("unchanged") — the largest subset that keeps its order.
|
|
16
|
+
* 2. Matched blocks outside that subsequence changed position → "moved".
|
|
17
|
+
* 3. Id-less blocks are paired by text similarity (character-bigram Jaccard
|
|
18
|
+
* ≥ 0.5) → "modified"; the leftovers are "added" / "removed".
|
|
19
|
+
*
|
|
20
|
+
* No dependency: the LIS is patience-style on tens of blocks, and similarity is
|
|
21
|
+
* bigrams because plans mix English and CJK (word splitting would collapse a
|
|
22
|
+
* Chinese sentence into one token).
|
|
23
|
+
*/
|
|
24
|
+
import type { Block } from "./blocks.js";
|
|
25
|
+
|
|
26
|
+
export type BlockStatus = "unchanged" | "moved" | "modified" | "added" | "removed";
|
|
27
|
+
|
|
28
|
+
export interface DiffEntry {
|
|
29
|
+
status: BlockStatus;
|
|
30
|
+
/** Block id in the new version; for `removed` this is the old id. */
|
|
31
|
+
id: string;
|
|
32
|
+
/** Previous id, set for `moved`, `modified` and `removed`. */
|
|
33
|
+
prevId?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Jaccard threshold for calling two unmatched blocks "the same block, edited". */
|
|
37
|
+
const SIMILARITY_THRESHOLD = 0.5;
|
|
38
|
+
|
|
39
|
+
/** Character bigrams of a block's normalized text. */
|
|
40
|
+
function bigrams(text: string): Set<string> {
|
|
41
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
42
|
+
const set = new Set<string>();
|
|
43
|
+
for (let i = 0; i < flat.length - 1; i += 1) set.add(flat.slice(i, i + 2));
|
|
44
|
+
if (flat.length === 1) set.add(flat);
|
|
45
|
+
return set;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Jaccard similarity of two blocks, 0…1. */
|
|
49
|
+
export function blockSimilarity(a: Pick<Block, "text">, b: Pick<Block, "text">): number {
|
|
50
|
+
const left = bigrams(a.text);
|
|
51
|
+
const right = bigrams(b.text);
|
|
52
|
+
if (left.size === 0 && right.size === 0) return 1;
|
|
53
|
+
let shared = 0;
|
|
54
|
+
for (const gram of left) if (right.has(gram)) shared += 1;
|
|
55
|
+
return shared / (left.size + right.size - shared);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Longest increasing subsequence of `values` (patience sorting), returned as
|
|
60
|
+
* the indices into `values` that survive. Ties keep the earliest possible set,
|
|
61
|
+
* which makes the "unchanged" choice deterministic.
|
|
62
|
+
*/
|
|
63
|
+
function longestIncreasing(values: readonly number[]): Set<number> {
|
|
64
|
+
const tails: number[] = []; // tails[k] = index in `values` of the smallest tail of a run of length k+1
|
|
65
|
+
const previous: number[] = new Array<number>(values.length).fill(-1);
|
|
66
|
+
for (let i = 0; i < values.length; i += 1) {
|
|
67
|
+
let low = 0;
|
|
68
|
+
let high = tails.length;
|
|
69
|
+
while (low < high) {
|
|
70
|
+
const mid = (low + high) >> 1;
|
|
71
|
+
if (values[tails[mid]] < values[i]) low = mid + 1;
|
|
72
|
+
else high = mid;
|
|
73
|
+
}
|
|
74
|
+
if (low > 0) previous[i] = tails[low - 1];
|
|
75
|
+
tails[low] = i;
|
|
76
|
+
}
|
|
77
|
+
const keep = new Set<number>();
|
|
78
|
+
let cursor = tails.length > 0 ? tails[tails.length - 1] : -1;
|
|
79
|
+
while (cursor !== -1) {
|
|
80
|
+
keep.add(cursor);
|
|
81
|
+
cursor = previous[cursor];
|
|
82
|
+
}
|
|
83
|
+
return keep;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Greedy best-first pairing of unmatched old/new blocks inside one gap. */
|
|
87
|
+
function pairBySimilarity(
|
|
88
|
+
prevIndices: readonly number[],
|
|
89
|
+
nextIndices: readonly number[],
|
|
90
|
+
prev: readonly Block[],
|
|
91
|
+
next: readonly Block[],
|
|
92
|
+
): Map<number, number> {
|
|
93
|
+
const candidates: Array<{ nextIndex: number; prevIndex: number; score: number }> = [];
|
|
94
|
+
for (const nextIndex of nextIndices) {
|
|
95
|
+
for (const prevIndex of prevIndices) {
|
|
96
|
+
const score = blockSimilarity(prev[prevIndex], next[nextIndex]);
|
|
97
|
+
if (score >= SIMILARITY_THRESHOLD) {
|
|
98
|
+
candidates.push({ nextIndex, prevIndex, score });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
candidates.sort((a, b) => b.score - a.score);
|
|
103
|
+
const pairing = new Map<number, number>(); // next index -> prev index
|
|
104
|
+
const usedPrev = new Set<number>();
|
|
105
|
+
for (const candidate of candidates) {
|
|
106
|
+
if (pairing.has(candidate.nextIndex) || usedPrev.has(candidate.prevIndex)) continue;
|
|
107
|
+
pairing.set(candidate.nextIndex, candidate.prevIndex);
|
|
108
|
+
usedPrev.add(candidate.prevIndex);
|
|
109
|
+
}
|
|
110
|
+
return pairing;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Diff two revisions. Entries are in reading order of the new revision, with
|
|
115
|
+
* removed blocks surfacing where they vanished — which is how a reviewer reads
|
|
116
|
+
* a change.
|
|
117
|
+
*/
|
|
118
|
+
export function diffBlocks(prev: readonly Block[], next: readonly Block[]): DiffEntry[] {
|
|
119
|
+
const prevIndexById = new Map<string, number>();
|
|
120
|
+
prev.forEach((block, index) => prevIndexById.set(block.id, index));
|
|
121
|
+
|
|
122
|
+
// Same id ⇒ same normalized text, wherever it sits now.
|
|
123
|
+
const matches: Array<{ nextIndex: number; prevIndex: number }> = [];
|
|
124
|
+
next.forEach((block, nextIndex) => {
|
|
125
|
+
const prevIndex = prevIndexById.get(block.id);
|
|
126
|
+
if (prevIndex !== undefined) matches.push({ nextIndex, prevIndex });
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const anchors = longestIncreasing(matches.map((match) => match.prevIndex));
|
|
130
|
+
const movedOf = new Map<number, number>(); // next index -> prev index, moved
|
|
131
|
+
matches.forEach((match, position) => {
|
|
132
|
+
if (!anchors.has(position)) movedOf.set(match.nextIndex, match.prevIndex);
|
|
133
|
+
});
|
|
134
|
+
const consumedPrev = new Set(matches.map((match) => match.prevIndex));
|
|
135
|
+
|
|
136
|
+
const entries: DiffEntry[] = [];
|
|
137
|
+
let prevCursor = 0;
|
|
138
|
+
let nextCursor = 0;
|
|
139
|
+
const anchorPairs = matches.filter((_match, position) => anchors.has(position));
|
|
140
|
+
|
|
141
|
+
// Anchors alone delimit the gaps. Moved blocks are emitted at their position
|
|
142
|
+
// in the NEW document, never used as a second set of boundaries — doing that
|
|
143
|
+
// reorders the review and makes a moved paragraph appear under the wrong
|
|
144
|
+
// section.
|
|
145
|
+
for (const anchor of [...anchorPairs, undefined]) {
|
|
146
|
+
const prevEnd = anchor?.prevIndex ?? prev.length;
|
|
147
|
+
const nextEnd = anchor?.nextIndex ?? next.length;
|
|
148
|
+
const removable: number[] = [];
|
|
149
|
+
for (let index = prevCursor; index < prevEnd; index += 1) {
|
|
150
|
+
if (!consumedPrev.has(index)) removable.push(index);
|
|
151
|
+
}
|
|
152
|
+
const gap: number[] = [];
|
|
153
|
+
for (let index = nextCursor; index < nextEnd; index += 1) gap.push(index);
|
|
154
|
+
const plain = gap.filter((nextIndex) => !movedOf.has(nextIndex));
|
|
155
|
+
const pairing = pairBySimilarity(removable, plain, prev, next);
|
|
156
|
+
const pairedPrev = new Set(pairing.values());
|
|
157
|
+
|
|
158
|
+
for (const prevIndex of removable) {
|
|
159
|
+
if (pairedPrev.has(prevIndex)) continue;
|
|
160
|
+
entries.push({ status: "removed", id: prev[prevIndex].id, prevId: prev[prevIndex].id });
|
|
161
|
+
}
|
|
162
|
+
for (const nextIndex of gap) {
|
|
163
|
+
const movedFrom = movedOf.get(nextIndex);
|
|
164
|
+
if (movedFrom !== undefined) {
|
|
165
|
+
entries.push({
|
|
166
|
+
status: "moved",
|
|
167
|
+
id: next[nextIndex].id,
|
|
168
|
+
prevId: prev[movedFrom].id,
|
|
169
|
+
});
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const pairedWith = pairing.get(nextIndex);
|
|
173
|
+
if (pairedWith !== undefined) {
|
|
174
|
+
entries.push({
|
|
175
|
+
status: "modified",
|
|
176
|
+
id: next[nextIndex].id,
|
|
177
|
+
prevId: prev[pairedWith].id,
|
|
178
|
+
});
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
entries.push({ status: "added", id: next[nextIndex].id });
|
|
182
|
+
}
|
|
183
|
+
if (anchor) entries.push({ status: "unchanged", id: next[anchor.nextIndex].id });
|
|
184
|
+
prevCursor = prevEnd + (anchor ? 1 : 0);
|
|
185
|
+
nextCursor = nextEnd + (anchor ? 1 : 0);
|
|
186
|
+
}
|
|
187
|
+
return entries;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Count of blocks whose status is not `unchanged` (what the UI calls "changed"). */
|
|
191
|
+
export function countChanged(entries: readonly DiffEntry[]): number {
|
|
192
|
+
return entries.filter((entry) => entry.status !== "unchanged").length;
|
|
193
|
+
}
|