@cueloop/schema 0.1.0-alpha.7 → 0.1.0-alpha.71
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/package.json +17 -17
- package/src/anchor.test.ts +268 -40
- package/src/anchor.ts +355 -43
- package/src/diff.test.ts +42 -25
- package/src/diff.ts +112 -77
- package/src/feedback.test.ts +313 -36
- package/src/feedback.ts +219 -50
- package/src/fuzzy.test.ts +110 -0
- package/src/fuzzy.ts +115 -0
- package/src/herdr.test.ts +50 -0
- package/src/herdr.ts +54 -0
- package/src/history.test.ts +395 -0
- package/src/history.ts +419 -0
- package/src/index.ts +6 -0
- package/src/inline.test.ts +195 -0
- package/src/inline.ts +240 -0
- package/src/markdown.test.ts +76 -21
- package/src/markdown.ts +123 -72
- package/src/participants.test.ts +58 -0
- package/src/participants.ts +34 -0
- package/src/path-view.test.ts +201 -0
- package/src/path-view.ts +85 -0
- package/src/types.test.ts +45 -1
- package/src/types.ts +198 -12
- package/src/working-copy.test.ts +70 -23
- package/src/working-copy.ts +24 -5
package/src/feedback.ts
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* feedback.md: the ONE structured markdown document the agent receives on
|
|
3
|
-
* resolve
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* resolve. Directive framing - soft phrasing gets ignored by models: the plan
|
|
4
|
+
* diff is applied verbatim first, then every annotation is addressed, located
|
|
5
|
+
* by quoted text.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import
|
|
9
|
-
|
|
8
|
+
import {
|
|
9
|
+
annotationTarget,
|
|
10
|
+
isAddressed,
|
|
11
|
+
isAgentNote,
|
|
12
|
+
type Annotation,
|
|
13
|
+
type ArtifactType,
|
|
14
|
+
type Thread,
|
|
15
|
+
type VerdictKind,
|
|
16
|
+
} from "./types";
|
|
17
|
+
import { parseBlocks, sectionOf, type Block } from "./markdown";
|
|
10
18
|
import { resolveAnchor } from "./anchor";
|
|
11
19
|
import { unifiedDiffText } from "./diff";
|
|
12
20
|
|
|
@@ -15,19 +23,63 @@ export interface FeedbackInput {
|
|
|
15
23
|
summary: string;
|
|
16
24
|
/** The submitted artifact content (latest revision). */
|
|
17
25
|
artifactContent: string;
|
|
18
|
-
/** The reviewer's working copy; undefined = no direct edits.
|
|
26
|
+
/** The reviewer's working copy; undefined = no direct edits. For a diff it is
|
|
27
|
+
* the curated patch (accepted hunks); for a plan it is the edited source. */
|
|
19
28
|
workingCopy?: string;
|
|
29
|
+
/** Artifact kind; defaults to "plan". A diff working copy is already a patch. */
|
|
30
|
+
artifactType?: ArtifactType;
|
|
20
31
|
annotations: Annotation[];
|
|
21
|
-
/** Path the agent knows the plan
|
|
22
|
-
|
|
32
|
+
/** Path the agent knows the artifact by (plan or prototype), for direct reference. */
|
|
33
|
+
artifactPath?: string;
|
|
34
|
+
/** Session id, so the document can teach the addressed-ids resubmit call. */
|
|
35
|
+
sessionId?: string;
|
|
36
|
+
/** cueloop quick-action name -> body; a `/name` reference in a comment expands to it for the agent. */
|
|
37
|
+
actionBodies?: Record<string, string>;
|
|
23
38
|
}
|
|
24
39
|
|
|
25
|
-
const quoteLines = (
|
|
40
|
+
const quoteLines = (text: string) => "> " + text.replace(/\n/g, "\n> ");
|
|
41
|
+
|
|
42
|
+
function expandActionRefs(body: string, actionBodies: Record<string, string> | undefined): string {
|
|
43
|
+
if (!actionBodies) return body;
|
|
44
|
+
|
|
45
|
+
return body.replace(/(^|\s)\/([A-Za-z0-9-]+)/g, (whole, lead: string, name: string) =>
|
|
46
|
+
actionBodies[name] !== undefined ? `${lead}${actionBodies[name]}` : whole,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
26
49
|
|
|
27
50
|
export function renderFeedback(input: FeedbackInput): string {
|
|
28
|
-
|
|
29
|
-
|
|
51
|
+
// The document the agent revises: a reply's feedback references reply.md so
|
|
52
|
+
// the resubmit instruction never points a reply review at plan.md.
|
|
53
|
+
const path = input.artifactPath ?? (input.artifactType === "reply" ? "reply.md" : "plan.md");
|
|
54
|
+
// agent notes are the submitter's own context - never echoed back as
|
|
55
|
+
// feedback - and annotations a previous revision already addressed stay out
|
|
56
|
+
// of the next document, so the agent only ever sees the open items
|
|
57
|
+
const open = input.annotations.filter(
|
|
58
|
+
(annotation) => !isAgentNote(annotation) && !isAddressed(annotation),
|
|
59
|
+
);
|
|
60
|
+
// a discussion is one item: the root comment, then its replies in order. A
|
|
61
|
+
// reply whose root was addressed leaves with it; only a reply whose root is
|
|
62
|
+
// gone entirely stands on its own
|
|
63
|
+
const openIds = new Set(open.map((annotation) => annotation.id));
|
|
64
|
+
const knownIds = new Set(input.annotations.map((annotation) => annotation.id));
|
|
65
|
+
const annotations = open.filter(
|
|
66
|
+
(annotation) =>
|
|
67
|
+
annotation.replyTo === undefined ||
|
|
68
|
+
(!openIds.has(annotation.replyTo) && !knownIds.has(annotation.replyTo)),
|
|
69
|
+
);
|
|
70
|
+
const repliesTo = (root: Annotation): Annotation[] =>
|
|
71
|
+
open
|
|
72
|
+
.filter((annotation) => annotation.replyTo === root.id)
|
|
73
|
+
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
74
|
+
const isDiff = input.artifactType === "diff";
|
|
75
|
+
const isPrototype = input.artifactType === "prototype";
|
|
76
|
+
// A diff's annotations anchor to the submitted patch rows; resolve against it,
|
|
77
|
+
// not the curated working copy (which may drop the rejected rows).
|
|
78
|
+
const blocks = parseBlocks(
|
|
79
|
+
isDiff ? input.artifactContent : (input.workingCopy ?? input.artifactContent),
|
|
80
|
+
);
|
|
30
81
|
const lines: string[] = [];
|
|
82
|
+
|
|
31
83
|
lines.push("# Review: " + input.verdictKind.replace("_", " "));
|
|
32
84
|
lines.push("");
|
|
33
85
|
if (input.summary.trim()) {
|
|
@@ -35,66 +87,183 @@ export function renderFeedback(input: FeedbackInput): string {
|
|
|
35
87
|
lines.push("");
|
|
36
88
|
}
|
|
37
89
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
if (
|
|
41
|
-
|
|
90
|
+
let hasEdits = false;
|
|
91
|
+
|
|
92
|
+
if (isDiff && input.workingCopy !== undefined) {
|
|
93
|
+
// The diff working copy is already the curated patch - the accepted subset
|
|
94
|
+
// of the submitted changes - so hand it back verbatim, not a diff of diffs.
|
|
95
|
+
hasEdits = true;
|
|
96
|
+
lines.push("## Curated changes");
|
|
42
97
|
lines.push("");
|
|
43
|
-
|
|
44
|
-
|
|
98
|
+
if (input.workingCopy.trim()) {
|
|
99
|
+
lines.push("The reviewer accepted a subset of your proposed changes. Apply this");
|
|
100
|
+
lines.push("exact unified diff; it replaces what you submitted.");
|
|
101
|
+
lines.push("");
|
|
102
|
+
lines.push("```diff");
|
|
103
|
+
lines.push(input.workingCopy);
|
|
104
|
+
lines.push("```");
|
|
105
|
+
} else {
|
|
106
|
+
lines.push("The reviewer rejected all of your proposed changes.");
|
|
107
|
+
}
|
|
45
108
|
lines.push("");
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
109
|
+
} else {
|
|
110
|
+
const diff =
|
|
111
|
+
input.workingCopy !== undefined
|
|
112
|
+
? unifiedDiffText(input.artifactContent, input.workingCopy, path)
|
|
113
|
+
: null;
|
|
114
|
+
|
|
115
|
+
if (diff) {
|
|
116
|
+
hasEdits = true;
|
|
117
|
+
// The edits section names the markdown artifact it edited (plan or reply)
|
|
118
|
+
// so the directive is not mislabelled when the artifact is not a plan.
|
|
119
|
+
lines.push(input.artifactType === "reply" ? "## Reply edits" : "## Plan edits");
|
|
120
|
+
lines.push("");
|
|
121
|
+
lines.push(`The reviewer edited ${path} directly. Apply this exact diff first;`);
|
|
122
|
+
lines.push("it is a unified diff against the version you submitted.");
|
|
123
|
+
lines.push("");
|
|
124
|
+
lines.push("```diff");
|
|
125
|
+
lines.push(diff);
|
|
126
|
+
lines.push("```");
|
|
127
|
+
lines.push("");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (annotations.length) {
|
|
132
|
+
lines.push(
|
|
133
|
+
...annotationSectionLines(
|
|
134
|
+
annotations,
|
|
135
|
+
blocks,
|
|
136
|
+
path,
|
|
137
|
+
isPrototype,
|
|
138
|
+
repliesTo,
|
|
139
|
+
input.actionBodies,
|
|
140
|
+
),
|
|
141
|
+
);
|
|
142
|
+
if (input.sessionId) {
|
|
143
|
+
lines.push("## Reporting what you addressed");
|
|
144
|
+
lines.push("");
|
|
145
|
+
lines.push("When you resubmit the revised plan, list the annotation ids you acted on -");
|
|
146
|
+
lines.push("they are marked addressed for the reviewer and leave the open list:");
|
|
147
|
+
lines.push("");
|
|
148
|
+
lines.push("```sh");
|
|
149
|
+
lines.push(
|
|
150
|
+
`cueloop session submit-revision ${input.sessionId} --content-file ${path} --addressed <id,id,...>`,
|
|
151
|
+
);
|
|
152
|
+
lines.push("```");
|
|
153
|
+
lines.push("");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (!hasEdits && !annotations.length) {
|
|
158
|
+
lines.push("_No edits or annotations._");
|
|
49
159
|
lines.push("");
|
|
50
160
|
}
|
|
51
161
|
|
|
52
|
-
|
|
53
|
-
|
|
162
|
+
return lines.join("\n");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The annotation body of the feedback, grouped by the surface each note was made on: the reviewed
|
|
167
|
+
* artifact first (resolved against its blocks for a section locator), then one section per file, so a
|
|
168
|
+
* note left on a file comes back beside that file rather than mixed into the plan's list.
|
|
169
|
+
*/
|
|
170
|
+
function annotationSectionLines(
|
|
171
|
+
annotations: Annotation[],
|
|
172
|
+
blocks: Block[],
|
|
173
|
+
path: string,
|
|
174
|
+
isPrototype: boolean,
|
|
175
|
+
repliesTo: (root: Annotation) => Annotation[],
|
|
176
|
+
actionBodies: Record<string, string> | undefined,
|
|
177
|
+
): string[] {
|
|
178
|
+
const lines: string[] = [];
|
|
179
|
+
const artifactNotes = annotations.filter(
|
|
180
|
+
(annotation) => annotationTarget(annotation).kind === "artifact",
|
|
181
|
+
);
|
|
182
|
+
const fileGroups = new Map<string, Annotation[]>();
|
|
183
|
+
|
|
184
|
+
for (const annotation of annotations) {
|
|
185
|
+
const target = annotationTarget(annotation);
|
|
186
|
+
|
|
187
|
+
if (target.kind !== "file") continue;
|
|
188
|
+
const group = fileGroups.get(target.path) ?? [];
|
|
189
|
+
|
|
190
|
+
group.push(annotation);
|
|
191
|
+
fileGroups.set(target.path, group);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const pushNote = (annotation: Annotation, index: number, location: string, orphan: string) => {
|
|
195
|
+
lines.push(`### ${index + 1}. ${capitalize(annotation.kind)}${location}${orphan}`);
|
|
196
|
+
lines.push("");
|
|
197
|
+
lines.push(quoteLines(annotation.anchor.quote));
|
|
54
198
|
lines.push("");
|
|
55
|
-
lines.push(
|
|
199
|
+
lines.push(expandActionRefs(annotation.body, actionBodies));
|
|
56
200
|
lines.push("");
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
lines.push(
|
|
64
|
-
lines.push("");
|
|
65
|
-
lines.push("Replace:");
|
|
66
|
-
lines.push(quoteLines(a.anchor.quote));
|
|
67
|
-
lines.push("With:");
|
|
68
|
-
lines.push(quoteLines(a.body));
|
|
69
|
-
} else {
|
|
70
|
-
lines.push(`### ${i + 1}. ${capitalize(a.kind)}${loc}${flag}`);
|
|
71
|
-
lines.push("");
|
|
72
|
-
lines.push(quoteLines(a.anchor.quote));
|
|
73
|
-
lines.push("");
|
|
74
|
-
lines.push(a.body);
|
|
75
|
-
}
|
|
201
|
+
const replies = repliesTo(annotation);
|
|
202
|
+
|
|
203
|
+
if (replies.length > 0) {
|
|
204
|
+
lines.push("Replies:");
|
|
205
|
+
lines.push("");
|
|
206
|
+
for (const reply of replies)
|
|
207
|
+
lines.push(`- ${expandActionRefs(reply.body, actionBodies).replace(/\n/g, "\n ")}`);
|
|
76
208
|
lines.push("");
|
|
209
|
+
}
|
|
210
|
+
lines.push(`annotation id: \`${annotation.id}\``);
|
|
211
|
+
lines.push("");
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
if (artifactNotes.length) {
|
|
215
|
+
lines.push(`## Annotations (${artifactNotes.length})`);
|
|
216
|
+
lines.push("");
|
|
217
|
+
lines.push(
|
|
218
|
+
isPrototype
|
|
219
|
+
? `Address every item. Locate each one in ${path} by its CSS selector.`
|
|
220
|
+
: `Address every item. Locate each one in ${path} by its quoted text.`,
|
|
221
|
+
);
|
|
222
|
+
lines.push("");
|
|
223
|
+
artifactNotes.forEach((annotation, index) => {
|
|
224
|
+
// a prototype selector anchor never resolves or orphans against blocks; a quote anchor does
|
|
225
|
+
const selector = annotation.anchor.selector;
|
|
226
|
+
const resolved = selector ? null : resolveAnchor(annotation.anchor, blocks);
|
|
227
|
+
const sectionTitle = resolved ? sectionOf(blocks, resolved.blockIndex) : "";
|
|
228
|
+
const location = selector ? ` (${selector})` : sectionTitle ? ` (§ ${sectionTitle})` : "";
|
|
229
|
+
const orphan =
|
|
230
|
+
!selector && resolved === null
|
|
231
|
+
? " [orphaned anchor: the quoted text is no longer present]"
|
|
232
|
+
: "";
|
|
233
|
+
|
|
234
|
+
pushNote(annotation, index, location, orphan);
|
|
77
235
|
});
|
|
78
236
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
lines.push("
|
|
237
|
+
for (const [filePath, notes] of fileGroups) {
|
|
238
|
+
lines.push(`## ${filePath} (${notes.length})`);
|
|
239
|
+
lines.push("");
|
|
240
|
+
lines.push(`Address every item. Locate each one in ${filePath} by its quoted text.`);
|
|
82
241
|
lines.push("");
|
|
242
|
+
notes.forEach((annotation, index) => pushNote(annotation, index, "", ""));
|
|
83
243
|
}
|
|
84
|
-
|
|
244
|
+
|
|
245
|
+
return lines;
|
|
85
246
|
}
|
|
86
247
|
|
|
87
|
-
export function feedbackForSession(
|
|
248
|
+
export function feedbackForSession(
|
|
249
|
+
session: Thread,
|
|
250
|
+
verdictKind: VerdictKind,
|
|
251
|
+
summary: string,
|
|
252
|
+
actionBodies?: Record<string, string>,
|
|
253
|
+
): string {
|
|
88
254
|
return renderFeedback({
|
|
89
255
|
verdictKind,
|
|
90
256
|
summary,
|
|
91
257
|
artifactContent: session.artifact.content,
|
|
92
258
|
workingCopy: session.workingCopy,
|
|
259
|
+
artifactType: session.artifact.type,
|
|
93
260
|
annotations: session.annotations,
|
|
94
|
-
|
|
261
|
+
artifactPath: session.artifact.meta.prototypePath ?? session.artifact.meta.planPath,
|
|
262
|
+
sessionId: session.id,
|
|
263
|
+
actionBodies,
|
|
95
264
|
});
|
|
96
265
|
}
|
|
97
266
|
|
|
98
|
-
function capitalize(
|
|
99
|
-
return
|
|
267
|
+
function capitalize(word: string): string {
|
|
268
|
+
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
100
269
|
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { fuzzyFindBestMatch, levenshteinDistance, similarityRatio } from "./fuzzy";
|
|
3
|
+
|
|
4
|
+
describe("levenshteinDistance", () => {
|
|
5
|
+
test("identical strings cost nothing", () => {
|
|
6
|
+
// Arrange / Act / Assert
|
|
7
|
+
expect(levenshteinDistance("anchor", "anchor")).toBe(0);
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test("counts a single substitution", () => {
|
|
11
|
+
// Arrange / Act / Assert
|
|
12
|
+
expect(levenshteinDistance("plan", "plane")).toBe(1);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test("empty against non-empty costs the whole length", () => {
|
|
16
|
+
// Arrange / Act / Assert
|
|
17
|
+
expect(levenshteinDistance("", "quote")).toBe(5);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("is symmetric", () => {
|
|
21
|
+
// Arrange / Act / Assert
|
|
22
|
+
expect(levenshteinDistance("kitten", "sitting")).toBe(levenshteinDistance("sitting", "kitten"));
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe("similarityRatio", () => {
|
|
27
|
+
test("two empty strings are identical", () => {
|
|
28
|
+
// Arrange / Act / Assert
|
|
29
|
+
expect(similarityRatio("", "")).toBe(1);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("identical strings score one", () => {
|
|
33
|
+
// Arrange / Act / Assert
|
|
34
|
+
expect(similarityRatio("review", "review")).toBe(1);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("a one-character typo in a long string stays close to one", () => {
|
|
38
|
+
// Arrange
|
|
39
|
+
const original = "demonstration plan";
|
|
40
|
+
|
|
41
|
+
// Act
|
|
42
|
+
const ratio = similarityRatio(original, "demonstration plann");
|
|
43
|
+
|
|
44
|
+
// Assert
|
|
45
|
+
expect(ratio).toBeGreaterThan(0.9);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("unrelated strings score low", () => {
|
|
49
|
+
// Arrange / Act / Assert
|
|
50
|
+
expect(similarityRatio("abcdef", "zyxwvu")).toBeLessThan(0.2);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
describe("fuzzyFindBestMatch", () => {
|
|
55
|
+
test("finds a lightly edited window and reports its offsets", () => {
|
|
56
|
+
// Arrange
|
|
57
|
+
const haystack = "the quick brown fox jumps";
|
|
58
|
+
|
|
59
|
+
// Act
|
|
60
|
+
const match = fuzzyFindBestMatch("quikc brown", haystack, 0.75)!;
|
|
61
|
+
|
|
62
|
+
// Assert
|
|
63
|
+
expect(match).not.toBeNull();
|
|
64
|
+
expect(haystack.slice(match.start, match.end)).toBe("quick brown");
|
|
65
|
+
expect(match.similarity).toBeGreaterThan(0.75);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("returns null when nothing clears the similarity floor", () => {
|
|
69
|
+
// Arrange / Act
|
|
70
|
+
const match = fuzzyFindBestMatch("completely unrelated", "short text", 0.75);
|
|
71
|
+
|
|
72
|
+
// Assert
|
|
73
|
+
expect(match).toBeNull();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("an empty needle or haystack never matches", () => {
|
|
77
|
+
// Arrange / Act / Assert
|
|
78
|
+
expect(fuzzyFindBestMatch("", "text", 0.75)).toBeNull();
|
|
79
|
+
expect(fuzzyFindBestMatch("text", "", 0.75)).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("ties keep the earliest window", () => {
|
|
83
|
+
// Arrange
|
|
84
|
+
const haystack = "word word";
|
|
85
|
+
|
|
86
|
+
// Act
|
|
87
|
+
const match = fuzzyFindBestMatch("word", haystack, 0.9)!;
|
|
88
|
+
|
|
89
|
+
// Assert
|
|
90
|
+
expect(match.start).toBe(0);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("a long quote fuzzed over a long document bails within its work budget", () => {
|
|
94
|
+
// Arrange - a stale multi-line anchor whose text is gone, over a large document; the naive
|
|
95
|
+
// scan is O(haystack * needle^3) and would pin the CPU for a minute
|
|
96
|
+
const needle = Array.from({ length: 200 }, (_unused, index) => `token-${index}`).join(" ");
|
|
97
|
+
const haystack = Array.from(
|
|
98
|
+
{ length: 400 },
|
|
99
|
+
(_unused, index) => `line ${index} of the diff`,
|
|
100
|
+
).join("\n");
|
|
101
|
+
|
|
102
|
+
// Act
|
|
103
|
+
const started = Date.now();
|
|
104
|
+
const match = fuzzyFindBestMatch(needle, haystack, 0.75);
|
|
105
|
+
|
|
106
|
+
// Assert - it returns (here: no match clears the bar) fast, never spinning
|
|
107
|
+
expect(match).toBeNull();
|
|
108
|
+
expect(Date.now() - started).toBeLessThan(2000);
|
|
109
|
+
});
|
|
110
|
+
});
|
package/src/fuzzy.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Approximate string matching for anchor re-binding. The anchor resolver falls
|
|
3
|
+
* back to these when exact and marker-normalized quote lookups both miss - the
|
|
4
|
+
* quoted text is still present but was lightly edited (a word changed, a typo
|
|
5
|
+
* fixed, punctuation adjusted). Everything here is pure and offset-exact so it
|
|
6
|
+
* can be tested in isolation from the resolver.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** A window of the haystack that best matches the needle. */
|
|
10
|
+
export interface FuzzyMatch {
|
|
11
|
+
/** Inclusive start offset into the haystack. */
|
|
12
|
+
start: number;
|
|
13
|
+
/** Exclusive end offset into the haystack. */
|
|
14
|
+
end: number;
|
|
15
|
+
/** Similarity of the matched window to the needle, in [0, 1]. */
|
|
16
|
+
similarity: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Levenshtein edit distance: the fewest single-character insertions, deletions,
|
|
21
|
+
* or substitutions that turn `left` into `right`. Uses two rolling rows, so it
|
|
22
|
+
* costs O(left.length * right.length) time and O(right.length) space.
|
|
23
|
+
*/
|
|
24
|
+
export function levenshteinDistance(left: string, right: string): number {
|
|
25
|
+
if (left === right) return 0;
|
|
26
|
+
if (left.length === 0) return right.length;
|
|
27
|
+
if (right.length === 0) return left.length;
|
|
28
|
+
|
|
29
|
+
let previousRow: number[] = Array.from({ length: right.length + 1 }, (_unused, column) => column);
|
|
30
|
+
let currentRow: number[] = Array.from({ length: right.length + 1 }, () => 0);
|
|
31
|
+
|
|
32
|
+
for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {
|
|
33
|
+
currentRow[0] = leftIndex;
|
|
34
|
+
for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {
|
|
35
|
+
const substitutionCost = left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1;
|
|
36
|
+
|
|
37
|
+
currentRow[rightIndex] = Math.min(
|
|
38
|
+
currentRow[rightIndex - 1]! + 1, // insertion
|
|
39
|
+
previousRow[rightIndex]! + 1, // deletion
|
|
40
|
+
previousRow[rightIndex - 1]! + substitutionCost, // substitution
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
const swap = previousRow;
|
|
44
|
+
|
|
45
|
+
previousRow = currentRow;
|
|
46
|
+
currentRow = swap;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return previousRow[right.length]!;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Similarity of two strings in [0, 1]: 1 is identical, 0 shares nothing. Derived
|
|
54
|
+
* from the edit distance normalized by the longer string. Two empty strings are
|
|
55
|
+
* defined as identical (1).
|
|
56
|
+
*/
|
|
57
|
+
export function similarityRatio(left: string, right: string): number {
|
|
58
|
+
const longestLength = Math.max(left.length, right.length);
|
|
59
|
+
|
|
60
|
+
if (longestLength === 0) return 1;
|
|
61
|
+
|
|
62
|
+
return 1 - levenshteinDistance(left, right) / longestLength;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Character comparisons this scan may spend before it gives up and returns the
|
|
67
|
+
* best window found so far (or null). The scan is O(haystack * needle^3) - a
|
|
68
|
+
* long quote fuzzed over a long document (a stale multi-block anchor whose text
|
|
69
|
+
* is gone) would otherwise pin the CPU for a minute; a passage that is truly gone
|
|
70
|
+
* is better left orphaned than fuzzed. Small everyday quotes never approach it.
|
|
71
|
+
*/
|
|
72
|
+
const FUZZY_WORK_BUDGET = 150_000_000;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Find the haystack window most similar to the needle, or null when nothing
|
|
76
|
+
* clears `minimumSimilarity`. Windows range around the needle length so the
|
|
77
|
+
* match tolerates a few inserted or deleted characters, not only substitutions.
|
|
78
|
+
* Ties keep the earliest window. Offsets index the haystack directly. The scan
|
|
79
|
+
* stops once it has spent `FUZZY_WORK_BUDGET`, returning the best window so far.
|
|
80
|
+
*/
|
|
81
|
+
export function fuzzyFindBestMatch(
|
|
82
|
+
needle: string,
|
|
83
|
+
haystack: string,
|
|
84
|
+
minimumSimilarity: number,
|
|
85
|
+
): FuzzyMatch | null {
|
|
86
|
+
if (needle === "" || haystack === "") return null;
|
|
87
|
+
|
|
88
|
+
const lengthTolerance = Math.max(2, Math.round(needle.length * 0.25));
|
|
89
|
+
const minimumWindowLength = Math.max(1, needle.length - lengthTolerance);
|
|
90
|
+
const maximumWindowLength = needle.length + lengthTolerance;
|
|
91
|
+
|
|
92
|
+
let bestMatch: FuzzyMatch | null = null;
|
|
93
|
+
let remainingWork = FUZZY_WORK_BUDGET;
|
|
94
|
+
|
|
95
|
+
for (let start = 0; start < haystack.length; start++) {
|
|
96
|
+
for (
|
|
97
|
+
let windowLength = minimumWindowLength;
|
|
98
|
+
windowLength <= maximumWindowLength && start + windowLength <= haystack.length;
|
|
99
|
+
windowLength++
|
|
100
|
+
) {
|
|
101
|
+
// each window costs a needle x window edit-distance pass; spend that from the budget
|
|
102
|
+
remainingWork -= needle.length * windowLength;
|
|
103
|
+
if (remainingWork <= 0) return bestMatch;
|
|
104
|
+
const window = haystack.slice(start, start + windowLength);
|
|
105
|
+
const similarity = similarityRatio(needle, window);
|
|
106
|
+
|
|
107
|
+
if (similarity < minimumSimilarity) continue;
|
|
108
|
+
if (bestMatch === null || similarity > bestMatch.similarity) {
|
|
109
|
+
bestMatch = { start, end: start + windowLength, similarity };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return bestMatch;
|
|
115
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { detectHerdr, insideHerdr, returnPaneFor } from "./herdr";
|
|
3
|
+
|
|
4
|
+
describe("detectHerdr", () => {
|
|
5
|
+
test("null outside herdr, context inside", () => {
|
|
6
|
+
expect(detectHerdr({})).toBeNull();
|
|
7
|
+
// no HERDR_ENV or no pane id means we are not in a usable herdr pane
|
|
8
|
+
expect(detectHerdr({ HERDR_PANE_ID: "p1" })).toBeNull();
|
|
9
|
+
expect(detectHerdr({ HERDR_ENV: "1" })).toBeNull();
|
|
10
|
+
// herdr 0.8.0 sets no HERDR_BIN_PATH: the binary defaults to `herdr` on PATH
|
|
11
|
+
expect(detectHerdr({ HERDR_ENV: "1", HERDR_PANE_ID: "p1" })).toEqual({
|
|
12
|
+
paneId: "p1",
|
|
13
|
+
binPath: "herdr",
|
|
14
|
+
});
|
|
15
|
+
// an explicit HERDR_BIN_PATH (tests, or a pinned install) still wins
|
|
16
|
+
expect(
|
|
17
|
+
detectHerdr({ HERDR_ENV: "1", HERDR_PANE_ID: "p1", HERDR_BIN_PATH: "/x/herdr" }),
|
|
18
|
+
).toEqual({
|
|
19
|
+
paneId: "p1",
|
|
20
|
+
binPath: "/x/herdr",
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe("insideHerdr", () => {
|
|
26
|
+
test("true only when HERDR_ENV is exactly 1", () => {
|
|
27
|
+
expect(insideHerdr({})).toBeFalse();
|
|
28
|
+
expect(insideHerdr({ HERDR_ENV: "0" })).toBeFalse();
|
|
29
|
+
expect(insideHerdr({ HERDR_ENV: "1" })).toBeTrue();
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("returnPaneFor", () => {
|
|
34
|
+
test("outside herdr there is never a return target", () => {
|
|
35
|
+
expect(returnPaneFor("w1:p1", {})).toBeUndefined();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("env override wins, session meta is the fallback", () => {
|
|
39
|
+
// Arrange
|
|
40
|
+
const inside = { HERDR_ENV: "1", HERDR_PANE_ID: "w1:p9" };
|
|
41
|
+
|
|
42
|
+
// Assert
|
|
43
|
+
expect(returnPaneFor("w1:p1", inside)).toBe("w1:p1");
|
|
44
|
+
expect(returnPaneFor("w1:p1", { ...inside, CUELOOP_RETURN_PANE: "w1:p2" })).toBe("w1:p2");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("returning to our own pane is a no-op", () => {
|
|
48
|
+
expect(returnPaneFor("w1:p1", { HERDR_ENV: "1", HERDR_PANE_ID: "w1:p1" })).toBeUndefined();
|
|
49
|
+
});
|
|
50
|
+
});
|
package/src/herdr.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The herdr ambient env contract, single-sourced. A process running inside a
|
|
3
|
+
* herdr pane sees HERDR_ENV=1 plus the pane id; the herdr CLI itself reaches
|
|
4
|
+
* the app over HERDR_SOCKET_PATH (which the spawned `herdr` reads from the
|
|
5
|
+
* inherited env), so the binary is just `herdr` on PATH. Both the agent-side
|
|
6
|
+
* reporter (adapters) and the reviewer-side return-focus (client) read this
|
|
7
|
+
* contract; decoding it in one place stops the two sides drifting on which
|
|
8
|
+
* vars are required. Pure: no IO, env is only the default argument so callers
|
|
9
|
+
* can pass a fixture.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export interface HerdrContext {
|
|
13
|
+
paneId: string;
|
|
14
|
+
binPath: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type HerdrEnv = Record<string, string | undefined>;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The pane's full contract - pane id and binary path - or null outside a
|
|
21
|
+
* functioning herdr. Required by anything that spawns the herdr CLI.
|
|
22
|
+
*/
|
|
23
|
+
export function detectHerdr(env: HerdrEnv = process.env): HerdrContext | null {
|
|
24
|
+
if (env.HERDR_ENV !== "1") return null;
|
|
25
|
+
const paneId = env.HERDR_PANE_ID;
|
|
26
|
+
|
|
27
|
+
if (!paneId) return null;
|
|
28
|
+
// herdr 0.8.0 exposes no HERDR_BIN_PATH; the CLI is `herdr` on PATH and finds
|
|
29
|
+
// the app over HERDR_SOCKET_PATH from the inherited env. Tests still override
|
|
30
|
+
// HERDR_BIN_PATH to point the spawn at a stub script.
|
|
31
|
+
const binPath = env.HERDR_BIN_PATH ?? "herdr";
|
|
32
|
+
|
|
33
|
+
return { paneId, binPath };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** True whenever this process runs inside a herdr pane. */
|
|
37
|
+
export function insideHerdr(env: HerdrEnv = process.env): boolean {
|
|
38
|
+
return env.HERDR_ENV === "1";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The pane a closing review should hand focus back to: the opener's
|
|
43
|
+
* CUELOOP_RETURN_PANE, or the session's recorded pane, but never this pane
|
|
44
|
+
* itself. Undefined outside herdr or when the only candidate is our own pane.
|
|
45
|
+
*/
|
|
46
|
+
export function returnPaneFor(
|
|
47
|
+
sessionHerdrPane?: string,
|
|
48
|
+
env: HerdrEnv = process.env,
|
|
49
|
+
): string | undefined {
|
|
50
|
+
if (!insideHerdr(env)) return undefined;
|
|
51
|
+
const pane = env.CUELOOP_RETURN_PANE ?? sessionHerdrPane;
|
|
52
|
+
|
|
53
|
+
return pane && pane !== env.HERDR_PANE_ID ? pane : undefined;
|
|
54
|
+
}
|