@visual-z/xeno 0.1.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 +498 -0
- package/docs/install.md +130 -0
- package/package.json +43 -0
- package/src/apps/approve.ts +49 -0
- package/src/apps/cli.ts +37 -0
- package/src/apps/commands.ts +226 -0
- package/src/apps/completions.ts +28 -0
- package/src/apps/input.ts +297 -0
- package/src/apps/render.ts +207 -0
- package/src/apps/shell.ts +2353 -0
- package/src/apps/startup.ts +1302 -0
- package/src/core/benchmark.ts +195 -0
- package/src/core/boundary.ts +174 -0
- package/src/core/churn.ts +59 -0
- package/src/core/completion-review.ts +66 -0
- package/src/core/context-policy.ts +60 -0
- package/src/core/context-window.ts +54 -0
- package/src/core/continuation.ts +114 -0
- package/src/core/cycle.ts +17 -0
- package/src/core/data-query.ts +201 -0
- package/src/core/deadline.ts +39 -0
- package/src/core/derive.ts +489 -0
- package/src/core/edit-plan.ts +200 -0
- package/src/core/environment.ts +29 -0
- package/src/core/event-validation.ts +99 -0
- package/src/core/events.ts +486 -0
- package/src/core/evidence-links.ts +71 -0
- package/src/core/evidence.ts +89 -0
- package/src/core/execution.ts +12 -0
- package/src/core/exhaustive.ts +18 -0
- package/src/core/experiment.ts +40 -0
- package/src/core/export.ts +169 -0
- package/src/core/file-references.ts +35 -0
- package/src/core/frontmatter.ts +213 -0
- package/src/core/handoff.ts +397 -0
- package/src/core/harness-comparison.ts +90 -0
- package/src/core/history-query.ts +103 -0
- package/src/core/history.ts +100 -0
- package/src/core/json-event.ts +135 -0
- package/src/core/json-pointer.ts +46 -0
- package/src/core/keymap.ts +241 -0
- package/src/core/observation-view.ts +87 -0
- package/src/core/outcome.ts +45 -0
- package/src/core/overflow.ts +59 -0
- package/src/core/permissions.ts +182 -0
- package/src/core/policy-evaluation.ts +55 -0
- package/src/core/progress.ts +101 -0
- package/src/core/project.ts +372 -0
- package/src/core/prompts.ts +83 -0
- package/src/core/queue.ts +60 -0
- package/src/core/read-bounds.ts +15 -0
- package/src/core/recall-analysis.ts +90 -0
- package/src/core/recall-trial.ts +153 -0
- package/src/core/response-recovery.ts +46 -0
- package/src/core/scheduling.ts +8 -0
- package/src/core/settings.ts +174 -0
- package/src/core/skills.ts +121 -0
- package/src/core/stall.ts +48 -0
- package/src/core/text-normalize.ts +81 -0
- package/src/core/theme.ts +179 -0
- package/src/core/tokens.ts +149 -0
- package/src/core/tool-contract.ts +102 -0
- package/src/core/tool-input.ts +38 -0
- package/src/core/transcript.ts +60 -0
- package/src/core/window-trial.ts +65 -0
- package/src/core/work-state.ts +103 -0
- package/src/core/yaml.ts +282 -0
- package/src/index.ts +10 -0
- package/src/runtime/auth.ts +255 -0
- package/src/runtime/benchmark.ts +187 -0
- package/src/runtime/catalog.ts +365 -0
- package/src/runtime/evidence-notes.ts +33 -0
- package/src/runtime/exec-sessions.ts +214 -0
- package/src/runtime/execution-control.ts +39 -0
- package/src/runtime/harness-comparison.ts +356 -0
- package/src/runtime/history-tools.ts +108 -0
- package/src/runtime/loop.ts +1983 -0
- package/src/runtime/model.ts +614 -0
- package/src/runtime/models-fetch.ts +155 -0
- package/src/runtime/oauth-device.ts +86 -0
- package/src/runtime/oauth.ts +759 -0
- package/src/runtime/openai-responses.ts +286 -0
- package/src/runtime/openai.ts +675 -0
- package/src/runtime/provider.ts +498 -0
- package/src/runtime/recall-trial.ts +226 -0
- package/src/runtime/resume.ts +66 -0
- package/src/runtime/retry.ts +297 -0
- package/src/runtime/tools.ts +1193 -0
- package/src/runtime/usage.ts +225 -0
- package/src/runtime/window-trial.ts +140 -0
- package/src/runtime/working-notes.ts +30 -0
- package/src/store/atomic.ts +31 -0
- package/src/store/auth-store.ts +50 -0
- package/src/store/blobs.ts +142 -0
- package/src/store/command.ts +75 -0
- package/src/store/config.ts +69 -0
- package/src/store/context-files.ts +356 -0
- package/src/store/file-index.ts +81 -0
- package/src/store/git-branch.ts +35 -0
- package/src/store/history-search.ts +19 -0
- package/src/store/log.ts +642 -0
- package/src/store/models.ts +41 -0
- package/src/store/observations.ts +181 -0
- package/src/store/query-source.ts +44 -0
- package/src/store/recovery.ts +39 -0
- package/src/store/replay.ts +63 -0
- package/src/store/resources.ts +361 -0
- package/src/store/restore.ts +302 -0
- package/src/store/search.ts +644 -0
- package/src/store/serial.ts +13 -0
- package/src/store/sessions.ts +463 -0
- package/src/store/trust.ts +69 -0
- package/src/store/workspace.ts +256 -0
- package/src/store/worktree.ts +233 -0
- package/src/tui/ansi.ts +67 -0
- package/src/tui/autocomplete.ts +29 -0
- package/src/tui/complete.ts +87 -0
- package/src/tui/diff.ts +160 -0
- package/src/tui/editor.ts +893 -0
- package/src/tui/exhaustive.ts +14 -0
- package/src/tui/fuzzy.ts +75 -0
- package/src/tui/host.ts +223 -0
- package/src/tui/input.ts +69 -0
- package/src/tui/keys.ts +378 -0
- package/src/tui/markdown.ts +17 -0
- package/src/tui/render.ts +153 -0
- package/src/tui/select.ts +240 -0
- package/src/tui/settings.ts +40 -0
- package/src/tui/statusline.ts +162 -0
- package/src/tui/style.ts +205 -0
- package/src/tui/terminal.ts +30 -0
- package/src/tui/text.ts +52 -0
- package/src/tui/toolview.ts +386 -0
- package/src/tui/transcript.ts +71 -0
- package/src/tui/tree.ts +405 -0
- package/src/tui/width.ts +567 -0
- package/src/vendor/pi-tui/LICENSE.upstream +21 -0
- package/src/vendor/pi-tui/VENDOR.md +23 -0
- package/src/vendor/pi-tui/alt-screen-search.ts +327 -0
- package/src/vendor/pi-tui/autocomplete.ts +835 -0
- package/src/vendor/pi-tui/components/alt-screen-flash.ts +51 -0
- package/src/vendor/pi-tui/components/box.ts +167 -0
- package/src/vendor/pi-tui/components/cancellable-loader.ts +40 -0
- package/src/vendor/pi-tui/components/editor.ts +2470 -0
- package/src/vendor/pi-tui/components/h-stack.ts +44 -0
- package/src/vendor/pi-tui/components/image.ts +127 -0
- package/src/vendor/pi-tui/components/input.ts +494 -0
- package/src/vendor/pi-tui/components/loader.ts +101 -0
- package/src/vendor/pi-tui/components/markdown.ts +1015 -0
- package/src/vendor/pi-tui/components/mouse-region.ts +33 -0
- package/src/vendor/pi-tui/components/scroll-view.ts +224 -0
- package/src/vendor/pi-tui/components/select-list.ts +273 -0
- package/src/vendor/pi-tui/components/settings-list.ts +328 -0
- package/src/vendor/pi-tui/components/spacer.ts +28 -0
- package/src/vendor/pi-tui/components/stack.ts +154 -0
- package/src/vendor/pi-tui/components/text.ts +107 -0
- package/src/vendor/pi-tui/components/truncated-text.ts +65 -0
- package/src/vendor/pi-tui/components/v-stack.ts +33 -0
- package/src/vendor/pi-tui/editor-component.ts +74 -0
- package/src/vendor/pi-tui/fuzzy.ts +138 -0
- package/src/vendor/pi-tui/index.ts +156 -0
- package/src/vendor/pi-tui/keybindings.ts +320 -0
- package/src/vendor/pi-tui/keys.ts +1401 -0
- package/src/vendor/pi-tui/kill-ring.ts +46 -0
- package/src/vendor/pi-tui/latex.ts +1506 -0
- package/src/vendor/pi-tui/layout-node.ts +51 -0
- package/src/vendor/pi-tui/layout.ts +449 -0
- package/src/vendor/pi-tui/native-modifiers.ts +13 -0
- package/src/vendor/pi-tui/native-module-path.ts +31 -0
- package/src/vendor/pi-tui/native-platform.ts +63 -0
- package/src/vendor/pi-tui/stdin-buffer.ts +444 -0
- package/src/vendor/pi-tui/terminal-colors.ts +73 -0
- package/src/vendor/pi-tui/terminal-image.ts +696 -0
- package/src/vendor/pi-tui/terminal.ts +547 -0
- package/src/vendor/pi-tui/tui-alt-screen.ts +1742 -0
- package/src/vendor/pi-tui/tui-main-screen.ts +655 -0
- package/src/vendor/pi-tui/tui.ts +1456 -0
- package/src/vendor/pi-tui/undo-stack.ts +28 -0
- package/src/vendor/pi-tui/utils.ts +1345 -0
- package/src/vendor/pi-tui/word-navigation.ts +117 -0
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* deriveHandoff: segment events + previous handoff -> next handoff.
|
|
3
|
+
*
|
|
4
|
+
* Pure and total. No I/O, no clock, no randomness, no model call. Same inputs
|
|
5
|
+
* always produce the same object, which is what makes the handoff diffable,
|
|
6
|
+
* unit-testable and cheap enough that segments can be short (decisions D1, D2).
|
|
7
|
+
*
|
|
8
|
+
* Evidence freshness rule: a completion claim must cite an event from the SAME
|
|
9
|
+
* segment. A gate that passed three segments ago is not proof about code that has
|
|
10
|
+
* changed since -- that is the stale-evidence problem, so the citation fails.
|
|
11
|
+
* Verification status, by contrast, carries forward as last-known with its
|
|
12
|
+
* original timestamp, which is honest about what it is.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type {
|
|
16
|
+
LogEvent, LineRange, NodeRef, EventId, CarryableEvent,
|
|
17
|
+
} from "./events.ts";
|
|
18
|
+
import { CARRYABLE_EVENTS } from "./events.ts";
|
|
19
|
+
import { deriveWorkItems } from "./work-state.ts";
|
|
20
|
+
import { deriveEvidenceLinks } from "./evidence-links.ts";
|
|
21
|
+
import { deriveProgress } from "./progress.ts";
|
|
22
|
+
import { isCommandResult, resolveEvidence, evidenceStale, eligibleProgressChecks } from "./evidence.ts";
|
|
23
|
+
import type { BranchRecord } from "./handoff.ts";
|
|
24
|
+
import {
|
|
25
|
+
HANDOFF_VERSION,
|
|
26
|
+
type Handoff, type CompletedItem, type UnverifiedClaim, type InFlightItem,
|
|
27
|
+
type BlockedItem, type DecisionItem, type PitfallItem, type FileAnchor,
|
|
28
|
+
type VerificationItem, type UserTurnRecord,
|
|
29
|
+
} from "./handoff.ts";
|
|
30
|
+
|
|
31
|
+
export interface DeriveConfig {
|
|
32
|
+
/** Where the agent can grep for anything a cap dropped. */
|
|
33
|
+
manifestPath: string;
|
|
34
|
+
maxUserTurns: number;
|
|
35
|
+
maxUserTurnBytes: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Marks the open questions this module generates from branch state, so they
|
|
40
|
+
* can be rebuilt each derivation instead of accumulating.
|
|
41
|
+
*/
|
|
42
|
+
const UNRESOLVED_BRANCH_PREFIX = "branch ";
|
|
43
|
+
|
|
44
|
+
export const DEFAULT_DERIVE_CONFIG: DeriveConfig = {
|
|
45
|
+
manifestPath: "log/manifest.json",
|
|
46
|
+
maxUserTurns: 200,
|
|
47
|
+
maxUserTurnBytes: 64_000,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export interface DeriveInput {
|
|
51
|
+
/** Previous segment's handoff, or null for segment 0. */
|
|
52
|
+
prev: Handoff | null;
|
|
53
|
+
/**
|
|
54
|
+
* Length of the path from the root to this node, inclusive.
|
|
55
|
+
*
|
|
56
|
+
* Supplied by the caller rather than derived from a node number, because
|
|
57
|
+
* allocation order is not an ordering over the tree: a node forked from an
|
|
58
|
+
* earlier one has a short path and a high number. deriveHandoff is pure and
|
|
59
|
+
* cannot read the log to count it, but readAncestry already returns
|
|
60
|
+
* `visited`, so the caller has the length in hand.
|
|
61
|
+
*/
|
|
62
|
+
depth: number;
|
|
63
|
+
events: readonly LogEvent[];
|
|
64
|
+
/** Ref to the segment being closed, recorded as the next segment's predecessor. */
|
|
65
|
+
self: NodeRef;
|
|
66
|
+
config?: Partial<DeriveConfig>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// --- helpers ---------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
/** Coalesce overlapping or adjacent ranges into a minimal sorted set. */
|
|
72
|
+
export function mergeRanges(ranges: readonly LineRange[]): LineRange[] {
|
|
73
|
+
if (ranges.length === 0) return [];
|
|
74
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
75
|
+
const out: LineRange[] = [[sorted[0]![0], sorted[0]![1]]];
|
|
76
|
+
for (let i = 1; i < sorted.length; i++) {
|
|
77
|
+
const cur = sorted[i]!;
|
|
78
|
+
const last = out[out.length - 1]!;
|
|
79
|
+
if (cur[0] <= last[1] + 1) {
|
|
80
|
+
out[out.length - 1] = [last[0], Math.max(last[1], cur[1])];
|
|
81
|
+
} else {
|
|
82
|
+
out.push([cur[0], cur[1]]);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** First occurrence wins, so accumulation across segments is order-stable. */
|
|
89
|
+
function dedupe<T>(items: readonly T[], key: (t: T) => string): T[] {
|
|
90
|
+
const seen = new Set<string>();
|
|
91
|
+
const out: T[] = [];
|
|
92
|
+
for (const it of items) {
|
|
93
|
+
const k = key(it);
|
|
94
|
+
if (!seen.has(k)) {
|
|
95
|
+
seen.add(k);
|
|
96
|
+
out.push(it);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// --- main ------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
export function deriveHandoff(input: DeriveInput): Handoff {
|
|
105
|
+
const cfg = { ...DEFAULT_DERIVE_CONFIG, ...input.config };
|
|
106
|
+
const { prev, depth, events } = input;
|
|
107
|
+
|
|
108
|
+
// Command results in this segment, in log order. The evidence index and the
|
|
109
|
+
// verification table are both built from this and nothing else -- exit codes,
|
|
110
|
+
// never the model's account of them.
|
|
111
|
+
const commands = events.filter(isCommandResult);
|
|
112
|
+
|
|
113
|
+
// -- objective: verbatim, set once, never rewritten -----------------------
|
|
114
|
+
// Skip user events a later interrupt cancelled: an abandoned prompt is not
|
|
115
|
+
// what the next segment is doing. If every user event in the segment was
|
|
116
|
+
// abandoned, keep the last one so EMPTY_OBJECTIVE cannot fire -- the mark
|
|
117
|
+
// lives on user_turns, not by blanking the field.
|
|
118
|
+
const abandonedIds = new Set(
|
|
119
|
+
events.filter((e): e is Extract<LogEvent, { t: "interrupt" }> => e.t === "interrupt")
|
|
120
|
+
.map((e) => e.user_id),
|
|
121
|
+
);
|
|
122
|
+
const users = events.filter((e): e is Extract<LogEvent, { t: "user" }> => e.t === "user");
|
|
123
|
+
const liveUsers = users.filter((e) => !abandonedIds.has(e.id));
|
|
124
|
+
const firstUser = liveUsers[0] ?? users.at(-1);
|
|
125
|
+
const objective = prev?.objective ?? (firstUser !== undefined ? firstUser.text : "");
|
|
126
|
+
|
|
127
|
+
// -- user turns: all of them, verbatim, accumulated ----------------------
|
|
128
|
+
// Abandoned turns stay: deleting them would rewrite history. The interrupt
|
|
129
|
+
// is a later record, so the mark is derived here rather than written back
|
|
130
|
+
// onto the user event (D8).
|
|
131
|
+
const newTurns: UserTurnRecord[] = users.map((e) => ({
|
|
132
|
+
at: e.at,
|
|
133
|
+
text: e.text,
|
|
134
|
+
...(abandonedIds.has(e.id) ? { abandoned: true as const } : {}),
|
|
135
|
+
}));
|
|
136
|
+
const userTurns: UserTurnRecord[] = [...(prev?.user_turns ?? []), ...newTurns];
|
|
137
|
+
|
|
138
|
+
let dropped = prev?.user_turns_truncated?.dropped ?? 0;
|
|
139
|
+
// Drop oldest first: the very first turn survives in `objective` regardless.
|
|
140
|
+
while (
|
|
141
|
+
userTurns.length > cfg.maxUserTurns ||
|
|
142
|
+
(userTurns.length > 1 &&
|
|
143
|
+
userTurns.reduce((n, t) => n + t.text.length, 0) > cfg.maxUserTurnBytes)
|
|
144
|
+
) {
|
|
145
|
+
userTurns.shift();
|
|
146
|
+
dropped++;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// -- completion claims resolved against the log --------------------------
|
|
150
|
+
const newCompleted: CompletedItem[] = [];
|
|
151
|
+
const unverified: UnverifiedClaim[] = [];
|
|
152
|
+
|
|
153
|
+
for (let i = 0; i < events.length; i++) {
|
|
154
|
+
const e = events[i]!;
|
|
155
|
+
if (e.t !== "claim" || e.work_id !== undefined) continue;
|
|
156
|
+
// Resolve against the most recent match AT OR BEFORE the claim. A claim is a
|
|
157
|
+
// statement about evidence available when it was made, so a later run must not
|
|
158
|
+
// retroactively change it -- that non-locality would mean appending an event
|
|
159
|
+
// could silently rewrite an earlier conclusion. Whether the gate is red *now*
|
|
160
|
+
// is separate information, carried by `verification` and repeated inline as
|
|
161
|
+
// `evidence_superseded` below.
|
|
162
|
+
const resolved = resolveEvidence(events.slice(0, i), e.evidence);
|
|
163
|
+
if (resolved.ok) newCompleted.push({ what: e.what, evidence: resolved.evidence });
|
|
164
|
+
else unverified.push({ what: e.what, claimed: e.evidence, reason: resolved.reason,
|
|
165
|
+
...(resolved.exit !== undefined ? { exit: resolved.exit } : {}) });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const workItems = deriveWorkItems(prev?.state.work_items ?? [], events);
|
|
169
|
+
const identifiedCompleted: CompletedItem[] = workItems.flatMap(item => item.status === "completed" && item.evidence
|
|
170
|
+
? [{ work_id: item.id, what: item.what, evidence: item.evidence }] : []);
|
|
171
|
+
const legacyCompleted = dedupe([...(prev?.state.completed ?? []).filter(item => item.work_id === undefined), ...newCompleted], c => c.what);
|
|
172
|
+
const completed = [...legacyCompleted, ...identifiedCompleted];
|
|
173
|
+
const completedSet = new Set(legacyCompleted.map(c => c.what));
|
|
174
|
+
|
|
175
|
+
// -- in flight: latest note per item wins --------------------------------
|
|
176
|
+
const inFlightMap = new Map<string, InFlightItem>();
|
|
177
|
+
for (const i of prev?.state.in_flight ?? []) if (i.work_id === undefined) inFlightMap.set(i.what, i);
|
|
178
|
+
for (const e of events) {
|
|
179
|
+
if (e.t === "next_action" && e.work_id === undefined) inFlightMap.set(e.what, { what: e.what, next_action: e.next_action });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// -- blocked -------------------------------------------------------------
|
|
183
|
+
const blockedItems: BlockedItem[] = [
|
|
184
|
+
...(prev?.state.blocked ?? []).filter(item => item.work_id === undefined),
|
|
185
|
+
...events.filter((e): e is Extract<LogEvent, { t: "blocked" }> => e.t === "blocked" && e.work_id === undefined)
|
|
186
|
+
.map((e) => ({ what: e.what, reason: e.reason })),
|
|
187
|
+
];
|
|
188
|
+
const legacyBlocked = dedupe(blockedItems, b => b.what).filter(b => !completedSet.has(b.what));
|
|
189
|
+
const blocked = [...legacyBlocked, ...workItems.filter(item => item.status === "blocked")
|
|
190
|
+
.map(item => ({ work_id: item.id, what: item.what, reason: item.reason ?? "blocked" }))];
|
|
191
|
+
const blockedSet = new Set(legacyBlocked.map(b => b.what));
|
|
192
|
+
|
|
193
|
+
// Completed beats blocked beats in-flight, so an item never appears twice.
|
|
194
|
+
const inFlight = [...inFlightMap.values()].filter(
|
|
195
|
+
(i) => !completedSet.has(i.what) && !blockedSet.has(i.what),
|
|
196
|
+
).concat(workItems.filter(item => item.status === "active")
|
|
197
|
+
.map(item => ({ work_id: item.id, what: item.what, next_action: item.next_action ?? "" })));
|
|
198
|
+
|
|
199
|
+
// -- branches: what this node opened, and what became of it --------------
|
|
200
|
+
//
|
|
201
|
+
// Spawn creates the record; joined attaches the reference; adopt and
|
|
202
|
+
// discard resolve it. An unresolved branch stays visible rather than
|
|
203
|
+
// silently accumulating, which is the whole of D16.
|
|
204
|
+
const branchMap = new Map<number, BranchRecord>();
|
|
205
|
+
for (const b of prev?.branches ?? []) branchMap.set(b.node, b);
|
|
206
|
+
for (const e of events) {
|
|
207
|
+
if (e.t === "spawn") {
|
|
208
|
+
branchMap.set(e.branch.node, {
|
|
209
|
+
node: e.branch.node,
|
|
210
|
+
spawned_at: e.id,
|
|
211
|
+
purpose: e.purpose,
|
|
212
|
+
resolution: null,
|
|
213
|
+
});
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (e.t !== "joined" && e.t !== "adopt" && e.t !== "discard") continue;
|
|
217
|
+
// A lifecycle event for a branch this node never spawned still records
|
|
218
|
+
// the branch: dropping it would hide a branch that exists.
|
|
219
|
+
const existing = branchMap.get(e.branch.node) ?? {
|
|
220
|
+
node: e.branch.node,
|
|
221
|
+
spawned_at: e.id,
|
|
222
|
+
purpose: "(spawn not recorded in this node)",
|
|
223
|
+
resolution: null,
|
|
224
|
+
};
|
|
225
|
+
if (e.t === "joined") {
|
|
226
|
+
branchMap.set(e.branch.node, {
|
|
227
|
+
...existing,
|
|
228
|
+
handoff_ref: e.handoff_ref,
|
|
229
|
+
summary: e.summary,
|
|
230
|
+
...(e.outcome ? { outcome: e.outcome } : {}),
|
|
231
|
+
});
|
|
232
|
+
} else {
|
|
233
|
+
branchMap.set(e.branch.node, {
|
|
234
|
+
...existing,
|
|
235
|
+
resolution: e.t === "adopt" ? "merged" : "discarded",
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const branches = [...branchMap.values()].sort((a, b) => a.node - b.node);
|
|
240
|
+
|
|
241
|
+
// -- decisions / pitfalls / questions ------------------------------------
|
|
242
|
+
const decisions = dedupe<DecisionItem>(
|
|
243
|
+
[
|
|
244
|
+
...(prev?.decisions ?? []),
|
|
245
|
+
...events.filter((e): e is Extract<LogEvent, { t: "decision" }> => e.t === "decision")
|
|
246
|
+
.map((e) => ({
|
|
247
|
+
chose: e.chose, because: e.because,
|
|
248
|
+
...(e.rejected !== undefined ? { rejected: e.rejected } : {}),
|
|
249
|
+
})),
|
|
250
|
+
],
|
|
251
|
+
(d) => JSON.stringify([d.chose, d.because]),
|
|
252
|
+
);
|
|
253
|
+
|
|
254
|
+
const pitfalls = dedupe<PitfallItem>(
|
|
255
|
+
[
|
|
256
|
+
...(prev?.pitfalls ?? []),
|
|
257
|
+
...events.filter((e): e is Extract<LogEvent, { t: "pitfall" }> => e.t === "pitfall")
|
|
258
|
+
.map((e) => ({ tried: e.tried, failed_because: e.failed_because })),
|
|
259
|
+
],
|
|
260
|
+
(p) => JSON.stringify([p.tried, p.failed_because]),
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
const openQuestions = dedupe(
|
|
264
|
+
[
|
|
265
|
+
...(prev?.open_questions ?? []).filter((q) => !q.startsWith(UNRESOLVED_BRANCH_PREFIX)),
|
|
266
|
+
...events.filter((e): e is Extract<LogEvent, { t: "question" }> => e.t === "question")
|
|
267
|
+
.map((e) => e.text),
|
|
268
|
+
// Rebuilt from the current branch state each time rather than carried,
|
|
269
|
+
// so resolving a branch removes its question instead of leaving a stale
|
|
270
|
+
// one behind. The text names the node and the handoff so the next
|
|
271
|
+
// context can go read it rather than only learning that it exists.
|
|
272
|
+
...branches
|
|
273
|
+
.filter((b) => b.resolution === null)
|
|
274
|
+
.map((b) =>
|
|
275
|
+
`${UNRESOLVED_BRANCH_PREFIX}${b.node} (${b.purpose}) is unresolved` +
|
|
276
|
+
`${b.handoff_ref ? `; it joined with ${b.handoff_ref}` : "; it has not joined yet"}` +
|
|
277
|
+
` -- adopt it or discard it`,
|
|
278
|
+
),
|
|
279
|
+
],
|
|
280
|
+
(q) => q,
|
|
281
|
+
);
|
|
282
|
+
|
|
283
|
+
// -- file anchors: reference plus fingerprint, never content -------------
|
|
284
|
+
const anchors = new Map<string, {
|
|
285
|
+
path: string; sha256: string; ranges: LineRange[]; touched: Set<"read" | "edit">; stale?: true;
|
|
286
|
+
}>();
|
|
287
|
+
for (const a of prev?.file_anchors ?? []) {
|
|
288
|
+
anchors.set(a.path, {
|
|
289
|
+
path: a.path, sha256: a.sha256,
|
|
290
|
+
ranges: [...(a.read_ranges ?? [])], touched: new Set(a.touched),
|
|
291
|
+
...(a.stale ? { stale: true } : {}),
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
for (const e of events) {
|
|
295
|
+
if (e.t === "snapshot") {
|
|
296
|
+
for (const [path, anchor] of anchors) {
|
|
297
|
+
const now = e.changed[path] ?? e.added[path];
|
|
298
|
+
if (e.removed.includes(path) || (now !== undefined && now !== anchor.sha256)) anchor.stale = true;
|
|
299
|
+
else if (now === anchor.sha256) delete anchor.stale;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (e.t !== "tool_result" || !e.effect) continue;
|
|
303
|
+
const eff = e.effect;
|
|
304
|
+
if (eff.kind === "read") {
|
|
305
|
+
const cur = anchors.get(eff.path) ?? {
|
|
306
|
+
path: eff.path, sha256: eff.sha256, ranges: [], touched: new Set<"read" | "edit">(),
|
|
307
|
+
};
|
|
308
|
+
cur.sha256 = eff.sha256;
|
|
309
|
+
delete cur.stale;
|
|
310
|
+
cur.ranges.push(...(eff.ranges ?? []));
|
|
311
|
+
cur.touched.add("read");
|
|
312
|
+
anchors.set(eff.path, cur);
|
|
313
|
+
} else if (eff.kind === "edit") {
|
|
314
|
+
const cur = anchors.get(eff.path) ?? {
|
|
315
|
+
path: eff.path, sha256: eff.sha256_after, ranges: [], touched: new Set<"read" | "edit">(),
|
|
316
|
+
};
|
|
317
|
+
cur.sha256 = eff.sha256_after;
|
|
318
|
+
delete cur.stale;
|
|
319
|
+
cur.touched.add("edit");
|
|
320
|
+
anchors.set(eff.path, cur);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const fileAnchors: FileAnchor[] = [...anchors.values()]
|
|
324
|
+
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
|
|
325
|
+
.map((a) => {
|
|
326
|
+
const merged = mergeRanges(a.ranges);
|
|
327
|
+
return {
|
|
328
|
+
path: a.path, sha256: a.sha256,
|
|
329
|
+
...(a.stale ? { stale: true } : {}),
|
|
330
|
+
...(merged.length > 0 ? { read_ranges: merged } : {}),
|
|
331
|
+
touched: (["read", "edit"] as const).filter((k) => a.touched.has(k)),
|
|
332
|
+
};
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
// -- verification: last run per gate; unrun gates stay not_run -----------
|
|
336
|
+
const gateState = new Map<string, VerificationItem>();
|
|
337
|
+
for (const item of prev?.verification ?? []) gateState.set(item.gate, { ...item });
|
|
338
|
+
for (const c of commands) {
|
|
339
|
+
const gate = c.effect.gate;
|
|
340
|
+
if (gate === undefined) continue;
|
|
341
|
+
gateState.set(gate, {
|
|
342
|
+
gate, status: c.effect.exit === 0 ? "pass" : "fail", at: c.at, exit: c.effect.exit,
|
|
343
|
+
...(c.effect.workspace_sha256 ? { workspace_sha256: c.effect.workspace_sha256 } : {}),
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
const verification = [...gateState.values()].sort((a, b) =>
|
|
347
|
+
a.gate < b.gate ? -1 : a.gate > b.gate ? 1 : 0,
|
|
348
|
+
);
|
|
349
|
+
for (const item of verification) {
|
|
350
|
+
const hit = commands.filter((c) => c.effect.gate === item.gate).at(-1);
|
|
351
|
+
if (evidenceStale(events, { command: hit?.effect.cmd ?? "", event_id: hit?.id ?? "", at: item.at ?? "", exit: item.exit ?? -1,
|
|
352
|
+
...(item.workspace_sha256 ? { workspace_sha256: item.workspace_sha256 } : {}),
|
|
353
|
+
}, item.stale)) item.stale = true;
|
|
354
|
+
else delete item.stale;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// -- mark completions whose gate has since gone red -------------------------
|
|
358
|
+
const failingGates = new Map(
|
|
359
|
+
verification.filter((v) => v.status === "fail").map((v) => [v.gate, v]),
|
|
360
|
+
);
|
|
361
|
+
const completedMarked: CompletedItem[] = completed.map((original) => {
|
|
362
|
+
const { evidence_stale: _old, ...base } = original;
|
|
363
|
+
const item: CompletedItem = evidenceStale(events, original.evidence, original.evidence_stale)
|
|
364
|
+
? { ...base, evidence_stale: true } : base;
|
|
365
|
+
const gate = item.evidence.gate;
|
|
366
|
+
const failing = gate === undefined ? undefined : failingGates.get(gate);
|
|
367
|
+
if (!failing) {
|
|
368
|
+
// Drop any stale marker: the gate went green again.
|
|
369
|
+
const { evidence_superseded: _drop, ...rest } = item;
|
|
370
|
+
return rest;
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
...item,
|
|
374
|
+
evidence_superseded: {
|
|
375
|
+
gate: failing.gate,
|
|
376
|
+
status: "fail" as const,
|
|
377
|
+
...(failing.exit !== undefined ? { exit: failing.exit } : {}),
|
|
378
|
+
...(failing.at !== undefined ? { at: failing.at } : {}),
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
// -- last activity: derived, so it is present even with zero annotations --
|
|
384
|
+
let lastActivity: string | null = null;
|
|
385
|
+
for (const e of events) {
|
|
386
|
+
if (e.t === "tool_result" && e.effect) {
|
|
387
|
+
const eff = e.effect;
|
|
388
|
+
lastActivity =
|
|
389
|
+
eff.kind === "command" ? `ran ${eff.cmd} (exit ${eff.exit})`
|
|
390
|
+
: eff.kind === "edit" ? `edited ${eff.path}`
|
|
391
|
+
: `read ${eff.path}`;
|
|
392
|
+
} else if (e.t === "assistant") {
|
|
393
|
+
const text = e.blocks.find((b) => b.type === "text");
|
|
394
|
+
if (text && text.type === "text" && text.text.trim()) {
|
|
395
|
+
lastActivity = firstLine(text.text);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (lastActivity === null) lastActivity = prev?.state.last_activity ?? null;
|
|
400
|
+
|
|
401
|
+
// -- progress (decision D9) ----------------------------------------------
|
|
402
|
+
const eligibleChecks = eligibleProgressChecks(events, new Set([...newCompleted, ...identifiedCompleted].map(item => item.evidence.event_id)), failingGates);
|
|
403
|
+
// A bounded view is presentation, not derivation input. Refuse to forget an
|
|
404
|
+
// omitted ledger, which would make old observations appear new after a cut.
|
|
405
|
+
if (prev?.history && Object.values(prev.history.sections).some((range) => range.offset > 0)) {
|
|
406
|
+
throw new Error("deriveHandoff requires full replay state, not a paginated handoff");
|
|
407
|
+
}
|
|
408
|
+
const progress = deriveProgress(prev?.progress_evidence ?? [], events, input.self.node, eligibleChecks);
|
|
409
|
+
const links = deriveEvidenceLinks(prev?.evidence_links ?? [], events);
|
|
410
|
+
|
|
411
|
+
const hasRemaining = inFlight.length > 0 || blocked.length > 0 || openQuestions.length > 0;
|
|
412
|
+
const hasNextAction = inFlight.some((i) => i.next_action.trim().length > 0);
|
|
413
|
+
|
|
414
|
+
return {
|
|
415
|
+
handoff_version: HANDOFF_VERSION,
|
|
416
|
+
predecessor: input.self,
|
|
417
|
+
objective,
|
|
418
|
+
user_turns: userTurns,
|
|
419
|
+
...(dropped > 0
|
|
420
|
+
? { user_turns_truncated: { dropped, recover_from: [cfg.manifestPath] } }
|
|
421
|
+
: {}),
|
|
422
|
+
state: {
|
|
423
|
+
...(workItems.length > 0 ? { work_items: workItems } : {}),
|
|
424
|
+
completed: completedMarked,
|
|
425
|
+
unverified_claims: dedupe([...(prev?.state.unverified_claims ?? []), ...unverified], (c) => JSON.stringify(c))
|
|
426
|
+
.filter((c) => !completedSet.has(c.what)),
|
|
427
|
+
in_flight: inFlight,
|
|
428
|
+
blocked,
|
|
429
|
+
last_activity: lastActivity,
|
|
430
|
+
},
|
|
431
|
+
decisions,
|
|
432
|
+
pitfalls,
|
|
433
|
+
file_anchors: fileAnchors,
|
|
434
|
+
verification,
|
|
435
|
+
branches,
|
|
436
|
+
open_questions: openQuestions,
|
|
437
|
+
progress_evidence: progress.evidence,
|
|
438
|
+
...(links.length > 0 ? { evidence_links: links } : {}),
|
|
439
|
+
continuation_valid: hasRemaining && hasNextAction,
|
|
440
|
+
budget: {
|
|
441
|
+
nodes_on_path: depth,
|
|
442
|
+
nodes_without_progress: progress.progressed
|
|
443
|
+
? 0
|
|
444
|
+
: (prev?.budget.nodes_without_progress ?? 0) + 1,
|
|
445
|
+
},
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function firstLine(s: string): string {
|
|
450
|
+
const line = s.trim().split("\n")[0] ?? "";
|
|
451
|
+
return line.length > 200 ? line.slice(0, 197) + "..." : line;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Events an adopt carries into the node it opens.
|
|
456
|
+
*
|
|
457
|
+
* Adopting a branch replaces the mainline with it, and the branch's ancestry
|
|
458
|
+
* stops at the fork point -- so everything the parent recorded after forking
|
|
459
|
+
* is outside it, including the decision that chose the branch. That is the
|
|
460
|
+
* least disposable record in the log, so it is carried rather than lost.
|
|
461
|
+
*
|
|
462
|
+
* Only annotations are carried. Harness events are either already in the
|
|
463
|
+
* branch's ancestry (before the fork) or are parent actions the branch never
|
|
464
|
+
* saw and should not inherit. Carrying annotations is free in context terms
|
|
465
|
+
* because they never replay as messages; only derivation reads them.
|
|
466
|
+
*
|
|
467
|
+
* A fork point that is not in `events` carries nothing, rather than falling
|
|
468
|
+
* back to all of them: an unknown fork point means the caller's picture of
|
|
469
|
+
* the tree is wrong, and carrying everything would silently duplicate work
|
|
470
|
+
* the branch already has.
|
|
471
|
+
*/
|
|
472
|
+
export function carryForward(
|
|
473
|
+
events: readonly LogEvent[],
|
|
474
|
+
since: EventId,
|
|
475
|
+
fromNode = 0,
|
|
476
|
+
): CarryableEvent[] {
|
|
477
|
+
const at = events.findIndex((e) => e.id === since);
|
|
478
|
+
if (at < 0) return [];
|
|
479
|
+
const carryable = new Set<string>(CARRYABLE_EVENTS);
|
|
480
|
+
return events
|
|
481
|
+
.slice(at + 1)
|
|
482
|
+
.filter((e): e is CarryableEvent => carryable.has(e.t))
|
|
483
|
+
.map((e) => ({
|
|
484
|
+
...e,
|
|
485
|
+
// Provenance, so the handoff can tell what this node produced from what
|
|
486
|
+
// it inherited through an adopt.
|
|
487
|
+
carried_from: e.carried_from ?? { node: fromNode, event: e.id },
|
|
488
|
+
}));
|
|
489
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* O.3: exact edits remain exact; a loose match is never silent.
|
|
3
|
+
*
|
|
4
|
+
* planEdit is the original single exact replacement and stays as it was.
|
|
5
|
+
* planEdits is what the tool uses: several edits, matched on the view read
|
|
6
|
+
* shows (see text-normalize.ts), with a loose fallback that is reported as
|
|
7
|
+
* such in the result rather than applied quietly.
|
|
8
|
+
*/
|
|
9
|
+
import { editDistance, fromView, normalizeLoose, similarity, toLF, toView } from "./text-normalize.ts";
|
|
10
|
+
|
|
11
|
+
export function lineDiff(before: string, after: string): { diff: string; firstLine: number } {
|
|
12
|
+
const a = before.split("\n"), b = after.split("\n");
|
|
13
|
+
let prefix = 0, suffix = 0;
|
|
14
|
+
while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix++;
|
|
15
|
+
while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - suffix - 1] === b[b.length - suffix - 1]) suffix++;
|
|
16
|
+
const removed = a.slice(prefix, a.length - suffix), added = b.slice(prefix, b.length - suffix);
|
|
17
|
+
return { firstLine: prefix + 1,
|
|
18
|
+
diff: before === after ? "(content unchanged)" : `@@ -${prefix + 1},${removed.length} +${prefix + 1},${added.length} @@\n` +
|
|
19
|
+
[...removed.map(line => `-${line}`), ...added.map(line => `+${line}`)].join("\n") };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function planEdit(before: string, oldText: string, newText: string, all: boolean):
|
|
23
|
+
{ ok: true; after: string; replacements: number; diff: string; firstLine: number } |
|
|
24
|
+
{ ok: false; code: "invalid_input" | "not_found" | "ambiguous_edit"; occurrences: number } {
|
|
25
|
+
if (!oldText) return { ok: false, code: "invalid_input", occurrences: 0 };
|
|
26
|
+
const occurrences = before.split(oldText).length - 1;
|
|
27
|
+
if (occurrences === 0) return { ok: false, code: "not_found", occurrences };
|
|
28
|
+
if (occurrences > 1 && !all) return { ok: false, code: "ambiguous_edit", occurrences };
|
|
29
|
+
// split/join avoids replacement-string interpolation of literal $&, $` or $'.
|
|
30
|
+
const at = before.indexOf(oldText);
|
|
31
|
+
const after = all ? before.split(oldText).join(newText) : before.slice(0, at) + newText + before.slice(at + oldText.length);
|
|
32
|
+
const a = before.split("\n"), b = after.split("\n");
|
|
33
|
+
let prefix = 0, suffix = 0;
|
|
34
|
+
while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix++;
|
|
35
|
+
while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - suffix - 1] === b[b.length - suffix - 1]) suffix++;
|
|
36
|
+
const removed = a.slice(prefix, a.length - suffix), added = b.slice(prefix, b.length - suffix);
|
|
37
|
+
return { ok: true, after, replacements: all ? occurrences : 1, firstLine: prefix + 1,
|
|
38
|
+
diff: before === after ? "(content unchanged)" : `@@ -${prefix + 1},${removed.length} +${prefix + 1},${added.length} @@\n` +
|
|
39
|
+
[...removed.map(line => `-${line}`), ...added.map(line => `+${line}`)].join("\n") };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
export interface EditSpec { old_string: string; new_string: string; replace_all?: boolean }
|
|
44
|
+
|
|
45
|
+
export interface ClosestMatch {
|
|
46
|
+
/** 1-indexed, inclusive, in the view read shows. */
|
|
47
|
+
startLine: number;
|
|
48
|
+
endLine: number;
|
|
49
|
+
score: number;
|
|
50
|
+
/** First line of old_string that differs from the file, and the file's line there. */
|
|
51
|
+
expected: string;
|
|
52
|
+
actual: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type EditsPlan =
|
|
56
|
+
| { ok: true; after: string; replacements: number; fuzzy: boolean; diff: string; firstLine: number }
|
|
57
|
+
| { ok: false; code: "invalid_input" | "not_found" | "ambiguous_edit"; edit: number; occurrences: number;
|
|
58
|
+
message: string; closest?: ClosestMatch };
|
|
59
|
+
|
|
60
|
+
/** A replacement in view coordinates: [start, end) becomes text. */
|
|
61
|
+
interface Span { start: number; end: number; text: string; edit: number }
|
|
62
|
+
|
|
63
|
+
function occurrences(haystack: string, needle: string): number[] {
|
|
64
|
+
const found: number[] = [];
|
|
65
|
+
for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + needle.length)) found.push(at);
|
|
66
|
+
return found;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Offsets of each line start in `text`, plus a sentinel one past the end. */
|
|
70
|
+
function lineStarts(text: string): number[] {
|
|
71
|
+
const starts = [0];
|
|
72
|
+
for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
|
|
73
|
+
starts.push(text.length + 1);
|
|
74
|
+
return starts;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const lineOf = (starts: readonly number[], offset: number) => {
|
|
78
|
+
let lo = 0, hi = starts.length - 2;
|
|
79
|
+
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid]! <= offset) lo = mid; else hi = mid - 1; }
|
|
80
|
+
return lo;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Loose matches mapped back onto whole original lines.
|
|
85
|
+
*
|
|
86
|
+
* normalizeLoose keeps the line count, so a match starting on normalized line
|
|
87
|
+
* i covers original lines i..j. Those lines -- and only those -- are replaced
|
|
88
|
+
* by their normalized form with the substitution applied. Rewriting the whole
|
|
89
|
+
* normalized file instead would quietly straighten every quote in it.
|
|
90
|
+
*/
|
|
91
|
+
function looseSpans(text: string, spec: { old: string; next: string; all: boolean }, edit: number):
|
|
92
|
+
{ spans: Span[] } | { count: number } {
|
|
93
|
+
const loose = normalizeLoose(text);
|
|
94
|
+
const needle = normalizeLoose(spec.old);
|
|
95
|
+
if (needle.trim().length === 0) return { count: 0 };
|
|
96
|
+
const found = occurrences(loose, needle);
|
|
97
|
+
if (found.length === 0 || (found.length > 1 && !spec.all)) return { count: found.length };
|
|
98
|
+
const looseStarts = lineStarts(loose), starts = lineStarts(text);
|
|
99
|
+
const spans: Span[] = [];
|
|
100
|
+
for (const at of found) {
|
|
101
|
+
const first = lineOf(looseStarts, at), last = lineOf(looseStarts, at + needle.length - 1);
|
|
102
|
+
const from = looseStarts[first]!, to = looseStarts[last + 1]! - 1;
|
|
103
|
+
const segment = loose.slice(from, to);
|
|
104
|
+
const local = at - from;
|
|
105
|
+
spans.push({ start: starts[first]!, end: starts[last + 1]! - 1, edit,
|
|
106
|
+
text: segment.slice(0, local) + spec.next + segment.slice(local + needle.length) });
|
|
107
|
+
}
|
|
108
|
+
return { spans };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Where old_string most nearly occurs, for a failure message that lets the
|
|
113
|
+
* model fix its copy instead of rereading the file (omp reports the same:
|
|
114
|
+
* `crates/pi-edit/src/fuzzy.rs`). Candidates are anchored on lines of
|
|
115
|
+
* old_string that occur verbatim (trimmed); failing that, on the most similar
|
|
116
|
+
* single line, which is only computed for files small enough to afford it.
|
|
117
|
+
*/
|
|
118
|
+
export function closestMatch(text: string, old: string): ClosestMatch | undefined {
|
|
119
|
+
const lines = text.split("\n");
|
|
120
|
+
const want = old.split("\n");
|
|
121
|
+
if (want.length > lines.length) return undefined;
|
|
122
|
+
const clip = (line: string) => line.trim().slice(0, 200);
|
|
123
|
+
const starts = new Set<number>();
|
|
124
|
+
const index = new Map<string, number[]>();
|
|
125
|
+
lines.forEach((line, i) => { const key = clip(line); if (key.length >= 4) index.set(key, [...(index.get(key) ?? []), i]); });
|
|
126
|
+
want.forEach((line, k) => {
|
|
127
|
+
for (const i of index.get(clip(line)) ?? []) if (i - k >= 0 && i - k + want.length <= lines.length) starts.add(i - k);
|
|
128
|
+
});
|
|
129
|
+
if (starts.size === 0 && lines.length <= 5_000) {
|
|
130
|
+
const anchor = want.findIndex((line) => clip(line).length > 0);
|
|
131
|
+
if (anchor === -1) return undefined;
|
|
132
|
+
const target = clip(want[anchor]!).slice(0, 80);
|
|
133
|
+
let best = -1, bestScore = 0;
|
|
134
|
+
lines.forEach((line, i) => {
|
|
135
|
+
const candidate = clip(line).slice(0, 80);
|
|
136
|
+
if (Math.abs(candidate.length - target.length) > target.length / 2) return;
|
|
137
|
+
const score = similarity(candidate, target);
|
|
138
|
+
if (score > bestScore && i - anchor >= 0 && i - anchor + want.length <= lines.length) { best = i - anchor; bestScore = score; }
|
|
139
|
+
});
|
|
140
|
+
if (best >= 0) starts.add(best);
|
|
141
|
+
}
|
|
142
|
+
let result: ClosestMatch | undefined;
|
|
143
|
+
const block = want.join("\n").slice(0, 2_000);
|
|
144
|
+
for (const start of [...starts].slice(0, 20)) {
|
|
145
|
+
const window = lines.slice(start, start + want.length);
|
|
146
|
+
const score = 1 - editDistance(window.join("\n").slice(0, 2_000), block) / Math.max(1, Math.max(block.length, window.join("\n").slice(0, 2_000).length));
|
|
147
|
+
if (result !== undefined && score <= result.score) continue;
|
|
148
|
+
const differs = want.findIndex((line, k) => line !== window[k]);
|
|
149
|
+
result = { startLine: start + 1, endLine: start + want.length, score,
|
|
150
|
+
expected: want[Math.max(0, differs)] ?? "", actual: window[Math.max(0, differs)] ?? "" };
|
|
151
|
+
}
|
|
152
|
+
return result !== undefined && result.score >= 0.5 ? result : undefined;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Several edits, all located in the original before any is applied, so one
|
|
157
|
+
* edit can never match text another just wrote. All succeed or none do.
|
|
158
|
+
*/
|
|
159
|
+
export function planEdits(raw: string, edits: readonly EditSpec[]): EditsPlan {
|
|
160
|
+
const view = toView(raw);
|
|
161
|
+
const text = view.text;
|
|
162
|
+
if (edits.length === 0) return { ok: false, code: "invalid_input", edit: 0, occurrences: 0, message: "no edits given" };
|
|
163
|
+
const spans: Span[] = [];
|
|
164
|
+
let fuzzy = false;
|
|
165
|
+
for (let e = 0; e < edits.length; e++) {
|
|
166
|
+
const spec = { old: toLF(edits[e]!.old_string), next: toLF(edits[e]!.new_string), all: edits[e]!.replace_all === true };
|
|
167
|
+
const which = edits.length > 1 ? `edit ${e + 1}: ` : "";
|
|
168
|
+
if (spec.old.length === 0) return { ok: false, code: "invalid_input", edit: e, occurrences: 0, message: `${which}old_string must not be empty` };
|
|
169
|
+
const exact = occurrences(text, spec.old);
|
|
170
|
+
if (exact.length > 1 && !spec.all) {
|
|
171
|
+
return { ok: false, code: "ambiguous_edit", edit: e, occurrences: exact.length,
|
|
172
|
+
message: `${which}old_string appears ${exact.length} times; add surrounding lines to make it unique or pass replace_all` };
|
|
173
|
+
}
|
|
174
|
+
if (exact.length > 0) {
|
|
175
|
+
for (const at of exact) spans.push({ start: at, end: at + spec.old.length, text: spec.next, edit: e });
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const loose = looseSpans(text, spec, e);
|
|
179
|
+
if ("spans" in loose) { spans.push(...loose.spans); fuzzy = true; continue; }
|
|
180
|
+
if (loose.count > 1) {
|
|
181
|
+
return { ok: false, code: "ambiguous_edit", edit: e, occurrences: loose.count,
|
|
182
|
+
message: `${which}old_string has no exact match and ${loose.count} matches ignoring whitespace and quote style; add surrounding lines to make it unique` };
|
|
183
|
+
}
|
|
184
|
+
const closest = closestMatch(text, spec.old);
|
|
185
|
+
return { ok: false, code: "not_found", edit: e, occurrences: 0,
|
|
186
|
+
message: `${which}old_string not found` + (closest === undefined ? "; read the current file before retrying" : ""),
|
|
187
|
+
...(closest === undefined ? {} : { closest }) };
|
|
188
|
+
}
|
|
189
|
+
spans.sort((a, b) => a.start - b.start);
|
|
190
|
+
for (let i = 1; i < spans.length; i++) {
|
|
191
|
+
if (spans[i]!.start < spans[i - 1]!.end) {
|
|
192
|
+
return { ok: false, code: "invalid_input", edit: spans[i]!.edit, occurrences: 0,
|
|
193
|
+
message: `edits ${spans[i - 1]!.edit + 1} and ${spans[i]!.edit + 1} overlap; merge them into one edit` };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
let after = text;
|
|
197
|
+
for (let i = spans.length - 1; i >= 0; i--) after = after.slice(0, spans[i]!.start) + spans[i]!.text + after.slice(spans[i]!.end);
|
|
198
|
+
if (after === text) return { ok: false, code: "invalid_input", edit: 0, occurrences: 0, message: "no change: new_string produces the current content" };
|
|
199
|
+
return { ok: true, after: fromView(view, after), replacements: spans.length, fuzzy, ...lineDiff(text, after) };
|
|
200
|
+
}
|