@whybebabo/dsh-file-review-tab 0.7.0 → 0.7.1

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/lib/index.js CHANGED
@@ -2,6 +2,69 @@ import { lstat, readFile, realpath } from "node:fs/promises";
2
2
  import { isAbsolute, relative, resolve } from "node:path";
3
3
  import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
4
4
  import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
5
+ //#region src/mutation-order.ts
6
+ /**
7
+ * Order settlements by their recorded event sequence, so undo/redo walk the
8
+ * file's history in the order it actually happened.
9
+ *
10
+ * This is what keeps a `run_code` mutation and a model-direct edit to the same
11
+ * file from being applied out of order: the two arrive through different
12
+ * channels (the conversation snapshot vs. the Host recorder) and are merged
13
+ * asynchronously, so the array order is a merge artifact rather than history.
14
+ *
15
+ * Only when EVERY entry carries a sequence is the order provable. A partially
16
+ * stamped list keeps its incoming order, which is the conservative choice —
17
+ * guessing at the position of an unstamped settlement could silently corrupt a
18
+ * file. The sort is stable, so entries sharing one sequence (a single
19
+ * `run_code` root's nested dispatch chain) keep their dispatch order.
20
+ *
21
+ * @param entries - Settlements or events carrying an optional `seq`.
22
+ * @returns A new array in ascending event order, or the same order when unprovable.
23
+ */
24
+ function orderBySequence(entries) {
25
+ if (entries.some((entry) => entry.seq === void 0)) return [...entries];
26
+ return [...entries].sort((left, right) => left.seq - right.seq);
27
+ }
28
+ /**
29
+ * Split one path's hunks into contiguous same-coordinate groups, in settlement
30
+ * order. Hunks that carry no `mutation` form a single group.
31
+ * @param diffs - One path's accumulated hunks, in settlement order.
32
+ * @returns The groups, in settlement order.
33
+ */
34
+ function mutationGroups(diffs) {
35
+ const groups = [];
36
+ let current = null;
37
+ let currentStamp;
38
+ for (const diff of diffs) {
39
+ if (current === null || diff.mutation !== currentStamp) {
40
+ current = [];
41
+ currentStamp = diff.mutation;
42
+ groups.push(current);
43
+ }
44
+ current.push(diff);
45
+ }
46
+ return groups;
47
+ }
48
+ /**
49
+ * The order one settlement's hunks must be applied in: back-to-front by the
50
+ * anchor of the direction being applied, because a hunk that changes the line
51
+ * count would otherwise shift the anchors of the hunks behind it. This is what
52
+ * makes a multi-hunk redo land on the coordinates the hunks recorded instead of
53
+ * the ones left over after the first hunk moved them.
54
+ *
55
+ * Hunks without a line anchor are content-matched and so coordinate-free; they
56
+ * sort after the anchored ones, where they cannot invalidate a pending anchor.
57
+ * @param group - One settlement's hunks.
58
+ * @param action - Direction being applied.
59
+ * @returns The hunks in application order (descending anchor).
60
+ */
61
+ function hunksForApply(group, action) {
62
+ const anchorOf = (diff) => {
63
+ return (action === "undo" ? diff.newStart : diff.oldStart) ?? Number.NEGATIVE_INFINITY;
64
+ };
65
+ return [...group].sort((left, right) => anchorOf(right) - anchorOf(left));
66
+ }
67
+ //#endregion
5
68
  //#region src/file-review-service.ts
6
69
  /** Host-side, workspace-contained undo / redo service for produced text diffs. */
7
70
  /**
@@ -75,9 +138,13 @@ function hunkSupported(diff, path) {
75
138
  /** Apply a complete file's hunk sequence in memory, or report a strict mismatch. */
76
139
  function transformFile(text, file, action) {
77
140
  if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return null;
78
- const diffs = action === "undo" ? [...file.diffs].reverse() : file.diffs;
141
+ const groups = orderBySequence(mutationGroups(file.diffs).map((group) => ({
142
+ seq: group[0]?.seq,
143
+ diffs: group
144
+ }))).map((settlement) => settlement.diffs);
145
+ const ordered = action === "undo" ? [...groups].reverse() : groups;
79
146
  let next = text;
80
- for (const diff of diffs) {
147
+ for (const group of ordered) for (const diff of hunksForApply(group, action)) {
81
148
  const source = action === "undo" ? diff.newText : diff.oldText;
82
149
  const replacement = action === "undo" ? diff.oldText : diff.newText;
83
150
  if (source === null || replacement === null) return null;
@@ -36,7 +36,11 @@ const diffSchema = z.object({
36
36
  oldText: z.string().nullable(),
37
37
  newText: z.string(),
38
38
  oldStart: z.number().int().min(1).optional(),
39
- newStart: z.number().int().min(1).optional()
39
+ newStart: z.number().int().min(1).optional(),
40
+ /** Coordinate space, so hunks from several settlements stay separable. */
41
+ mutation: z.number().int().min(0).optional(),
42
+ /** Event sequence, so settlements merge in the order they happened. */
43
+ seq: z.number().int().min(0).optional()
40
44
  });
41
45
  const requestSchema = z.object({
42
46
  action: z.enum(["undo", "redo"]),
@@ -20,6 +20,34 @@ export interface ProducedFileDiff {
20
20
  * Host recorder's `before === null`.
21
21
  */
22
22
  readonly created?: true;
23
+ /**
24
+ * Coordinate space this hunk's `oldStart`/`newStart` are expressed in.
25
+ *
26
+ * One path mutated several times in one turn accumulates hunks from several
27
+ * settlements, and each settlement's line numbers refer to the text the
28
+ * PREVIOUS settlement left behind — they are not interchangeable. Hunks
29
+ * sharing this stamp are anchored in the same text and must be applied
30
+ * back-to-front within it; groups apply in settlement order forward and in
31
+ * reverse order backward (see `mutation-order.ts`).
32
+ *
33
+ * Optional: absent means "all of this path's hunks share one coordinate
34
+ * space", the correct reading for the single-settlement payloads that
35
+ * predate the field.
36
+ */
37
+ readonly mutation?: number | undefined;
38
+ /**
39
+ * Event sequence this settlement happened at, used to order settlements.
40
+ *
41
+ * A file's history can be split across two channels — the conversation
42
+ * snapshot (model-direct `edit`/`write`) and the Host recorder (nested
43
+ * `run_code` dispatches) — which the tab merges asynchronously. Array order is
44
+ * therefore a merge artifact, not history; this sequence is what restores the
45
+ * real order. For a snapshot settlement it is the tool-result node's `seq`,
46
+ * and for a recorded one the owning `run_code` root's `seq`.
47
+ *
48
+ * Optional: when absent the order is not provable and the array order stands.
49
+ */
50
+ readonly seq?: number | undefined;
23
51
  }
24
52
  /** One produced file and the applied hunks available for review. */
25
53
  export interface ProducedFileReview {
@@ -22,6 +22,51 @@ export interface FileReviewSeed {
22
22
  /** Monotonic publish id; a new value means a new link to replay. */
23
23
  readonly nonce: number;
24
24
  }
25
+ /** A row a deep link resolved to, keyed the way the tab keys its state. */
26
+ export interface DeepLinkRow {
27
+ readonly turn: number;
28
+ readonly path: string;
29
+ }
30
+ /** Everything one replay must do, computed without touching component state. */
31
+ export interface DeepLinkPlan {
32
+ /** Rows to expand, as `turn|path` state keys. */
33
+ readonly expanded: readonly string[];
34
+ /** The row to scroll to (the first match), or null when nothing matched. */
35
+ readonly first: DeepLinkRow | null;
36
+ /**
37
+ * Archive section to reveal: a link into an auto-archived turn must render
38
+ * that turn before its row can be scrolled to. Null when the target is
39
+ * already in the main list.
40
+ */
41
+ readonly archive: {
42
+ readonly pages: number;
43
+ } | null;
44
+ }
45
+ /**
46
+ * Resolve a deep link against EVERY change the tab can render, including turns
47
+ * still hidden behind a closed archive section.
48
+ *
49
+ * The target is deliberately resolved against the full change set rather than
50
+ * the currently mounted rows. A link into an archived turn is replayed in the
51
+ * same commit that opens the archive, so at that moment its rows are not
52
+ * mounted yet; resolving against the mounted set made the match fail, the
53
+ * pending scroll get cleared, and the link land nowhere with no retry.
54
+ *
55
+ * @param turns - Every turn, ascending (the source of truth for all rows).
56
+ * @param archivedTurns - The auto-archived subset, newest first.
57
+ * @param paths - Paths the link targets.
58
+ * @param targetTurn - Turn anchor, or undefined for a path-only (legacy) link.
59
+ * @returns The expand set, the scroll target, and the archive reveal to apply.
60
+ */
61
+ export declare function planDeepLink(turns: readonly {
62
+ readonly turn: number;
63
+ readonly live: boolean;
64
+ readonly files: readonly {
65
+ readonly path: string;
66
+ }[];
67
+ }[], archivedTurns: readonly {
68
+ readonly turn: number;
69
+ }[], paths: readonly string[], targetTurn: number | undefined): DeepLinkPlan;
25
70
  type SeedListener = (sessionId: string, seed: FileReviewSeed) => void;
26
71
  type InvalidationListener = (sessionId: string) => void;
27
72
  /** Publish a deep link for one session and return the stored seed. */
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Pacing for the client's `recorded` (Code Mode mutation) fetch.
3
+ *
4
+ * The fetch re-arms whenever a root's settled-dispatch count changes, and a busy
5
+ * `run_code` can change it rapidly. Two ways to get that wrong, both of which
6
+ * leave the tab showing only the mutations recorded before it first looked:
7
+ *
8
+ * - Debouncing from each update (restarting the timer whenever one arrives)
9
+ * pushes the fetch out for as long as updates keep coming.
10
+ * - Anchoring on "the last fetch" alone starves the FIRST fetch: while updates
11
+ * keep arriving, no fetch has completed, so the anchor never exists and the
12
+ * window is re-armed forever.
13
+ *
14
+ * So the delay is always measured from a real instant — the last fetch, or the
15
+ * moment the fetch was first armed when none has completed yet. An update can
16
+ * then only ever schedule the next fetch for `anchor + interval`, and nothing an
17
+ * update does can push it later.
18
+ */
19
+ /** Minimum gap between two `recorded` fetches, in milliseconds. */
20
+ export declare const RECORDED_FETCH_INTERVAL = 200;
21
+ /**
22
+ * Delay before the next `recorded` fetch.
23
+ * @param anchor - Timestamp of the last completed fetch, or of the moment the
24
+ * fetch was first armed when none has completed yet. Must never be a value that
25
+ * an incoming update can reset, or the fetch starves.
26
+ * @param now - Current timestamp.
27
+ * @returns Milliseconds to wait; 0 once the interval has already elapsed.
28
+ */
29
+ export declare function recordedFetchDelay(anchor: number, now: number): number;
30
+ //# sourceMappingURL=recorded-fetch.d.ts.map
@@ -19,6 +19,13 @@ export interface SessionFileChange {
19
19
  readonly diffs: readonly ProducedFileDiff[];
20
20
  /** Terminal commands deleted this path in this turn (display-only). */
21
21
  readonly deleted?: true;
22
+ /**
23
+ * Event sequence the pending deletion happened at. A deletion is an event, so
24
+ * a cross-channel write with a LATER sequence proves the path was recreated
25
+ * and clears the flag. Absent when the snapshot omitted the sequence, in which
26
+ * case the deletion is kept (the conservative reading).
27
+ */
28
+ readonly deletedSeq?: number | undefined;
22
29
  }
23
30
  /** One turn's produced files, in first-seen order. */
24
31
  export interface TurnFileChanges {
@@ -40,17 +47,44 @@ export interface SessionRoot {
40
47
  readonly turn: number;
41
48
  readonly live: boolean;
42
49
  readonly rootCallId: string;
50
+ /**
51
+ * The root node's event sequence, or undefined when the snapshot omitted it.
52
+ * A recorded mutation is a nested dispatch of this root, so this is the
53
+ * sequence its changes are ordered by — it is what lets a `run_code` edit be
54
+ * merged into the right position among the turn's model-direct edits. When it
55
+ * is unknown the merge keeps array order rather than guessing.
56
+ */
57
+ readonly seq: number | undefined;
58
+ /**
59
+ * How many nested dispatches of this root have SETTLED so far.
60
+ *
61
+ * The Host recorder keeps appending mutations under the SAME `rootCallId`
62
+ * while a long `run_code` runs, so a call-id-only dependency would never
63
+ * re-arm the client's `recorded` fetch: the tab would show only the mutations
64
+ * that landed before its first fetch. A nested dispatch settles exactly when
65
+ * the recorder sees it, so this count grows with the recorded data and gives
66
+ * the fetch a dependency that tracks it.
67
+ */
68
+ readonly progress: number;
43
69
  }
44
70
  /** Every `run_code` tool-result node whose nested changes are not in the snapshot. */
45
71
  export declare function deriveSessionRoots(snapshot: ConversationSnapshot): SessionRoot[];
46
72
  /**
47
73
  * Merge Host-recorded Code Mode mutations into the snapshot-derived turns:
48
- * hunks rebuilt from the full before/after are appended to the owning turn's
49
- * file groups (same-path entries stay one row, hunks appended in dispatch
50
- * order), so the tab's diff rendering, status inspection and undo all work on
51
- * programmatic edits exactly like model-direct ones. All inputs are immutable;
52
- * the result is a fresh array only when a recorded mutation matched a visible
53
- * root.
74
+ * hunks rebuilt from the full before/after are inserted into the owning turn's
75
+ * file groups at the position their EVENT SEQUENCE puts them (same-path entries
76
+ * stay one row), so the tab's diff rendering, status inspection and undo all
77
+ * work on programmatic edits exactly like model-direct ones.
78
+ *
79
+ * Ordering is by sequence rather than "snapshot first, recorded after": the two
80
+ * sources are separate channels merged asynchronously, so appending recorded
81
+ * mutations could invert them. A `run_code` insert at the top of a file followed
82
+ * by a model-direct edit near its end must replay in that order — reversed, the
83
+ * rear edit's line anchors describe text the front insert already shifted, and
84
+ * BOTH undo and redo fail on a file that was perfectly reviewable.
85
+ *
86
+ * All inputs are immutable; the result is a fresh array only when a recorded
87
+ * mutation matched a visible root.
54
88
  */
55
89
  export declare function mergeRecordedTurns(turns: readonly TurnFileChanges[], roots: readonly SessionRoot[], recorded: readonly RecordedMutation[]): readonly TurnFileChanges[];
56
90
  /** Count distinct changed paths across every turn (the sidebar badge count). */
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Mutation grouping: the coordinate space each recorded hunk is anchored in.
3
+ *
4
+ * One file is often mutated several times in a single turn (`edit`, then
5
+ * `write`, then a Code Mode dispatch), and the review surfaces concatenate every
6
+ * mutation's hunks into ONE list per path. Those hunks do NOT share a coordinate
7
+ * space: mutation 1's `oldStart` is a line number in the text as it existed
8
+ * before mutation 1, mutation 2's is a line number in the text mutation 1 left
9
+ * behind, and so on. Replaying them as one flat list therefore applies hunks
10
+ * against coordinates that no longer exist.
11
+ *
12
+ * A group is the set of hunks one settlement produced (one tool result's
13
+ * `meta.diffs`, or one Code Mode `before`/`after` pair). Two rules follow:
14
+ *
15
+ * - settlements replay in settlement order going forward (redo) and in reverse
16
+ * order going back (undo), because each one is anchored in the text the
17
+ * previous one produced;
18
+ * - inside ONE settlement the hunks are anchored in the same text, so a hunk
19
+ * that changes the line count shifts every anchor still waiting behind it —
20
+ * they must be applied back-to-front.
21
+ *
22
+ * `mutation` is optional so a payload produced before this field existed
23
+ * degrades to a single group, which for the overwhelmingly common
24
+ * one-mutation payload is exactly the correct answer.
25
+ */
26
+ import type { ProducedFileDiff } from './change-types.ts';
27
+ /**
28
+ * Append one settlement's hunks, stamping them with the coordinate space they
29
+ * were recorded in and the event sequence that orders them.
30
+ *
31
+ * The stamp is the accumulator's current length, which is strictly increasing
32
+ * per path, so two settlements can never share one — that uniqueness is what
33
+ * lets {@link mutationGroups} split a path's hunks back into settlements.
34
+ *
35
+ * `seq` is the ordering key: the conversation node's sequence for a
36
+ * snapshot-derived settlement, or the owning `run_code` root's sequence for a
37
+ * Host-recorded one. It is recorded separately from `mutation` because the two
38
+ * answer different questions — a chain of nested dispatches produces several
39
+ * distinct settlements that all share one node sequence.
40
+ *
41
+ * @param target - The path's accumulated hunks, mutated in place.
42
+ * @param diffs - One settlement's hunks, all anchored in the same text.
43
+ * @param seq - Event sequence that orders this settlement, when known.
44
+ */
45
+ export declare function appendMutation(target: ProducedFileDiff[], diffs: readonly ProducedFileDiff[], seq?: number | undefined): void;
46
+ /**
47
+ * Order settlements by their recorded event sequence, so undo/redo walk the
48
+ * file's history in the order it actually happened.
49
+ *
50
+ * This is what keeps a `run_code` mutation and a model-direct edit to the same
51
+ * file from being applied out of order: the two arrive through different
52
+ * channels (the conversation snapshot vs. the Host recorder) and are merged
53
+ * asynchronously, so the array order is a merge artifact rather than history.
54
+ *
55
+ * Only when EVERY entry carries a sequence is the order provable. A partially
56
+ * stamped list keeps its incoming order, which is the conservative choice —
57
+ * guessing at the position of an unstamped settlement could silently corrupt a
58
+ * file. The sort is stable, so entries sharing one sequence (a single
59
+ * `run_code` root's nested dispatch chain) keep their dispatch order.
60
+ *
61
+ * @param entries - Settlements or events carrying an optional `seq`.
62
+ * @returns A new array in ascending event order, or the same order when unprovable.
63
+ */
64
+ export declare function orderBySequence<T extends {
65
+ readonly seq: number | undefined;
66
+ }>(entries: readonly T[]): T[];
67
+ /** One settlement recovered from a path's accumulated hunks. */
68
+ export interface Settlement {
69
+ readonly seq: number | undefined;
70
+ readonly diffs: readonly ProducedFileDiff[];
71
+ }
72
+ /**
73
+ * Recover the settlements one path's flat hunk list was built from.
74
+ * @param diffs - One path's accumulated hunks.
75
+ * @returns One entry per coordinate space, in the order they were appended.
76
+ */
77
+ export declare function settlementsOf(diffs: readonly ProducedFileDiff[]): Settlement[];
78
+ /**
79
+ * Re-stamp a settlement list back into one flat hunk list, in event order.
80
+ *
81
+ * Stamps are reassigned rather than preserved because they encode POSITION
82
+ * (`mutation` is the append offset), and reordering invalidates the old values;
83
+ * leaving them stale would make {@link mutationGroups} split the same
84
+ * coordinate space into several groups.
85
+ *
86
+ * @param settlements - Settlements, in any order.
87
+ * @returns The flat hunk list, ordered by `seq` with fresh stamps.
88
+ */
89
+ export declare function flattenSettlements(settlements: readonly Settlement[]): ProducedFileDiff[];
90
+ /**
91
+ * Split one path's hunks into contiguous same-coordinate groups, in settlement
92
+ * order. Hunks that carry no `mutation` form a single group.
93
+ * @param diffs - One path's accumulated hunks, in settlement order.
94
+ * @returns The groups, in settlement order.
95
+ */
96
+ export declare function mutationGroups(diffs: readonly ProducedFileDiff[]): readonly (readonly ProducedFileDiff[])[];
97
+ /**
98
+ * The order one settlement's hunks must be applied in: back-to-front by the
99
+ * anchor of the direction being applied, because a hunk that changes the line
100
+ * count would otherwise shift the anchors of the hunks behind it. This is what
101
+ * makes a multi-hunk redo land on the coordinates the hunks recorded instead of
102
+ * the ones left over after the first hunk moved them.
103
+ *
104
+ * Hunks without a line anchor are content-matched and so coordinate-free; they
105
+ * sort after the anchored ones, where they cannot invalidate a pending anchor.
106
+ * @param group - One settlement's hunks.
107
+ * @param action - Direction being applied.
108
+ * @returns The hunks in application order (descending anchor).
109
+ */
110
+ export declare function hunksForApply(group: readonly ProducedFileDiff[], action: 'undo' | 'redo'): readonly ProducedFileDiff[];
111
+ //# sourceMappingURL=mutation-order.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@whybebabo/dsh-file-review-tab",
3
3
  "description": "Review agent-produced file changes (line-level red/green diff + undo) both as a chat turn-tail row and as a dsh-better-sidebar tab; a port of left0ver's dsh-file-review.",
4
- "version": "0.7.0",
4
+ "version": "0.7.1",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -74,7 +74,8 @@
74
74
  "build:types": "tsc --emitDeclarationOnly --outDir lib/types",
75
75
  "build": "npm run build:types && tsdown",
76
76
  "typecheck": "tsc --noEmit",
77
- "test": "node test/typert-descriptors.mjs && node test/slot-registration.mjs && node test/host-apply.mjs && node test/review-invalidation.mjs && node test/diff-hunks.mjs && node test/client-bundle.mjs && node test/card-render.mjs && node test/tab-render.mjs && node test/diff-render.mjs"
77
+ "pretest": "npm run build",
78
+ "test": "node test/typert-descriptors.mjs && node test/slot-registration.mjs && node test/host-apply.mjs && node test/undo-redo.mjs && node test/interleaved-mutations.mjs && node test/review-invalidation.mjs && node test/deep-link.mjs && node test/diff-hunks.mjs && node test/mutation-order.mjs && node test/deleted-paths.mjs && node test/client-bundle.mjs && node test/card-render.mjs && node test/tab-render.mjs && node test/diff-render.mjs"
78
79
  },
79
80
  "pnpm": {
80
81
  "ignoredBuiltDependencies": [