dsh-better-edit 0.8.2 → 1.0.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +158 -99
  2. package/README.md +2 -2
  3. package/README.zh.md +3 -3
  4. package/cordis.patch.yml +1 -1
  5. package/lib/constants.js +19 -4
  6. package/lib/contract.js +136 -79
  7. package/lib/domain-errors.js +570 -0
  8. package/lib/edit-diff.js +33 -7
  9. package/lib/file-encoding-state.js +27 -7
  10. package/lib/file-view.js +305 -82
  11. package/lib/fs-bridge.js +23 -7
  12. package/lib/hash-store.js +404 -278
  13. package/lib/hashline/anchor-pipeline.js +586 -378
  14. package/lib/hashline/hash-assign.js +21 -22
  15. package/lib/hashline/hash.js +6 -6
  16. package/lib/hashline/index.js +1 -1
  17. package/lib/hashline/resolve.js +1 -1
  18. package/lib/hashline/served-guard.js +181 -0
  19. package/lib/index.js +1 -1
  20. package/lib/mutation/engine.js +392 -96
  21. package/lib/mutation.js +22 -130
  22. package/lib/noop-guard.js +20 -9
  23. package/lib/prompts.js +20 -18
  24. package/lib/read-and-serve.js +44 -20
  25. package/lib/sandbox.js +1 -1
  26. package/lib/session-view.js +57 -43
  27. package/lib/snapshot-store/index.js +97 -0
  28. package/lib/snapshot-store/lineage-store.js +400 -0
  29. package/lib/snapshot-store/migrate.js +80 -0
  30. package/lib/snapshot-store/pairing.js +412 -0
  31. package/lib/snapshot-store/txn.js +63 -0
  32. package/lib/snapshot-store/vacuum.js +243 -0
  33. package/lib/store-lifecycle.js +13 -1
  34. package/lib/store-retry.js +34 -0
  35. package/lib/tool-edit.js +90 -44
  36. package/lib/tool-read.js +29 -1
  37. package/lib/tool-str-replace-editor.js +26 -18
  38. package/lib/tool-undo.js +25 -8
  39. package/lib/types/constants.d.ts +5 -2
  40. package/lib/types/contract.d.ts +76 -71
  41. package/lib/types/domain-errors.d.ts +410 -0
  42. package/lib/types/edit-response.d.ts +1 -1
  43. package/lib/types/file-encoding-state.d.ts +1 -0
  44. package/lib/types/file-view.d.ts +35 -6
  45. package/lib/types/hash-store.d.ts +38 -19
  46. package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
  47. package/lib/types/hashline/hash-assign.d.ts +5 -5
  48. package/lib/types/hashline/hash.d.ts +1 -1
  49. package/lib/types/hashline/index.d.ts +2 -2
  50. package/lib/types/hashline/served-guard.d.ts +100 -0
  51. package/lib/types/index.d.ts +2 -2
  52. package/lib/types/mutation/engine.d.ts +49 -30
  53. package/lib/types/mutation.d.ts +1 -39
  54. package/lib/types/noop-guard.d.ts +4 -4
  55. package/lib/types/prompts.d.ts +1 -1
  56. package/lib/types/read-and-serve.d.ts +6 -0
  57. package/lib/types/sandbox.d.ts +1 -1
  58. package/lib/types/session-view.d.ts +38 -9
  59. package/lib/types/snapshot-store/index.d.ts +28 -0
  60. package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
  61. package/lib/types/snapshot-store/migrate.d.ts +16 -0
  62. package/lib/types/snapshot-store/pairing.d.ts +99 -0
  63. package/lib/types/snapshot-store/txn.d.ts +12 -0
  64. package/lib/types/snapshot-store/vacuum.d.ts +79 -0
  65. package/lib/types/store-lifecycle.d.ts +0 -1
  66. package/lib/types/store-retry.d.ts +6 -0
  67. package/lib/types/tool-edit.d.ts +2 -2
  68. package/lib/types/tool-str-replace-editor.d.ts +2 -2
  69. package/lib/types/utils.d.ts +5 -6
  70. package/lib/types/workspace-context.d.ts +0 -1
  71. package/lib/undo-edit.js +27 -11
  72. package/lib/utils.js +12 -12
  73. package/lib/workspace-context.js +4 -8
  74. package/lib/write-hook.js +13 -4
  75. package/package.json +9 -10
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import xxhash from "xxhash-wasm";
17
17
  import { splitLines } from "../utils.js";
18
+ import { DomainError } from "../domain-errors.js";
18
19
  let hasher = null;
19
20
  export function getH() {
20
21
  if (hasher)
@@ -52,15 +53,17 @@ export const HASH_SEP = "│";
52
53
  export const HASH_SPACE = ALPH.length ** HASH_LEN;
53
54
  // MAX_HASH_LINES is the anchor-space size (62³), not a line-count limit.
54
55
  // File line-count limits use maxLines (e.g. 200k) and report E_LARGE_FILE;
55
- // anchor-space exhaustion reports E_ANCHOR_SPACE_EXHAUSTED — see nextZeroBit.
56
+ // anchor-space exhaustion reports E_LARGE_FILE with limitKind "hash-space" — see nextZeroBit.
56
57
  export const MAX_HASH_LINES = HASH_SPACE;
57
58
  export const HASH_PROBE_STRIDE = ALPH.length ** 2 + ALPH.length + 1;
58
- export class AnchorSpaceExhaustedError extends Error {
59
- code = "E_ANCHOR_SPACE_EXHAUSTED";
59
+ export class AnchorSpaceExhaustedError extends DomainError {
60
60
  retiredCount;
61
61
  servedCount;
62
- constructor(retiredCount, servedCount, reservedCount) {
63
- super(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion will clear retired — re-read recommended, stale-anchor checks degraded until next full read.`);
62
+ // F10.3: reserved count removed — the registry payload carries the limit,
63
+ // not the probe state.
64
+ constructor(retiredCount, servedCount) {
65
+ // Channel rule: hard capacity refusal the model must route around → MODEL via the registry.
66
+ super("E_LARGE_FILE", { limitKind: "hash-space", limit: HASH_SPACE });
64
67
  this.name = "AnchorSpaceExhaustedError";
65
68
  this.retiredCount = retiredCount;
66
69
  this.servedCount = servedCount;
@@ -83,14 +86,6 @@ export function hashAt(idx) {
83
86
  }
84
87
  return hash;
85
88
  }
86
- const hashToCanon = new Map();
87
- export function rememberHashCanon(hash, canonText) {
88
- if (!hashToCanon.has(hash))
89
- hashToCanon.set(hash, canonText);
90
- }
91
- export function getCanonForHash(hash) {
92
- return hashToCanon.get(hash);
93
- }
94
89
  export const HL_PREFIX_PLUS_RE = new RegExp(`^\\+${HASH_CLASS}│`);
95
90
  export const HL_PREFIX_MINUS_RE = new RegExp(`^-(?:${HASH_CLASS}│| {${ANCHOR_LEN}}│)`);
96
91
  export const HL_BARE_PREFIX_RE = new RegExp(`^\\s*(${HASH_CLASS})│`);
@@ -99,6 +94,10 @@ const CANON_RE = /[ \t\r\n]+/g;
99
94
  export function canon(line) {
100
95
  return line.replace(CANON_RE, "");
101
96
  }
97
+ /** Single definition of served_leases.canon_hash / line_lineage.canon_hash (CP2). */
98
+ export function canonDigest(line) {
99
+ return String(xxh32(canon(line)));
100
+ }
102
101
  function getCanon(cache, line) {
103
102
  let v = cache.get(line);
104
103
  if (v !== undefined)
@@ -124,7 +123,7 @@ function nextZeroBit(bits, start) {
124
123
  if (idx >= totalBits)
125
124
  idx -= totalBits;
126
125
  }
127
- throw new Error(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted — probing failed over ${HASH_SPACE} slots (reserved full).`);
126
+ throw new Error(`Anchor space exhausted — probing failed over ${HASH_SPACE} slots (reserved full).`);
128
127
  }
129
128
  function assignHash(used, baseIdx, hint) {
130
129
  if (!getBit(used, baseIdx)) {
@@ -153,16 +152,16 @@ retiredCount, servedCount) {
153
152
  const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
154
153
  const h = assignHash(used, baseIdx, hint);
155
154
  hashes[i] = h;
156
- rememberHashCanon(h, c);
157
155
  }
158
156
  }
159
157
  catch (e) {
160
158
  const msg = e instanceof Error ? e.message : String(e);
161
- if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED") || msg.includes("Cannot allocate")) {
159
+ if (e instanceof AnchorSpaceExhaustedError)
160
+ throw e;
161
+ if (msg.includes("probing failed over") || msg.includes("Cannot allocate")) {
162
162
  const rc = retiredCount ?? reservedHashes.size;
163
163
  const sc = servedCount ?? 0;
164
- const reserved = reservedHashes.size;
165
- throw new AnchorSpaceExhaustedError(rc, sc, reserved);
164
+ throw new AnchorSpaceExhaustedError(rc, sc);
166
165
  }
167
166
  throw e;
168
167
  }
@@ -268,7 +267,6 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
268
267
  const newIdx = candidates.splice(pos, 1)[0];
269
268
  newHashes[newIdx] = entry.hash;
270
269
  markUsed(entry.hash);
271
- rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
272
270
  }
273
271
  try {
274
272
  for (let i = 0; i < newLines.length; i++) {
@@ -278,15 +276,16 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
278
276
  const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
279
277
  const h = assignHash(used, baseIdx, hint);
280
278
  newHashes[i] = h;
281
- rememberHashCanon(h, c);
282
279
  }
283
280
  }
284
281
  catch (e) {
285
282
  const msg = e instanceof Error ? e.message : String(e);
286
- if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED")) {
283
+ if (e instanceof AnchorSpaceExhaustedError)
284
+ throw e;
285
+ if (msg.includes("probing failed over") || msg.includes("Cannot allocate")) {
287
286
  const rc = retiredCount ?? reservedHashes.size;
288
287
  const sc = servedCount ?? 0;
289
- throw new AnchorSpaceExhaustedError(rc, sc, reservedHashes.size);
288
+ throw new AnchorSpaceExhaustedError(rc, sc);
290
289
  }
291
290
  throw e;
292
291
  }
@@ -19,8 +19,8 @@ export function snapshotIOFor(store) {
19
19
  if (store) {
20
20
  return {
21
21
  get: (path, content, deleteCorrupt) => Promise.resolve(store.getSnapshot(path, content, deleteCorrupt)),
22
- upsert: (path, checksum, lineCount, hashes) => {
23
- store.upsertSnapshot(path, checksum, lineCount, hashes);
22
+ upsert: (path, checksum, lineCount, hashes, content) => {
23
+ store.upsertSnapshot(path, checksum, lineCount, hashes, content);
24
24
  return Promise.resolve();
25
25
  },
26
26
  };
@@ -30,9 +30,9 @@ export function snapshotIOFor(store) {
30
30
  const s = await loadHashStore();
31
31
  return s.getSnapshot(path, content, deleteCorrupt);
32
32
  },
33
- upsert: async (path, checksum, lineCount, hashes) => {
33
+ upsert: async (path, checksum, lineCount, hashes, content) => {
34
34
  const s = await loadHashStore();
35
- s.upsertSnapshot(path, checksum, lineCount, hashes);
35
+ s.upsertSnapshot(path, checksum, lineCount, hashes, content);
36
36
  },
37
37
  });
38
38
  }
@@ -57,7 +57,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
57
57
  const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes, retiredHashes.size, previous.hashes.length);
58
58
  if (persist !== false && io) {
59
59
  try {
60
- await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
60
+ await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes, content);
61
61
  }
62
62
  catch (e) {
63
63
  console.error("Failed to persist hash snapshot:", e);
@@ -79,7 +79,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
79
79
  const newHashes = lineHashesPure(content, reservedHashes, retiredHashes.size, 0);
80
80
  if (persist !== false && io) {
81
81
  try {
82
- await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
82
+ await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes, content);
83
83
  }
84
84
  catch (e) {
85
85
  console.error("Failed to persist hash snapshot:", e);
@@ -7,4 +7,4 @@ export { CANON_VERSION, ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX
7
7
  export { lineHashes } from "./hash.js";
8
8
  export { parseHashRef, parseText } from "./parse.js";
9
9
  export { resEdit } from "./anchor-pipeline.js";
10
- export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
10
+ export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isAnchorMismatch, verifyServedRange, verifyRebasedSpan, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
@@ -1,3 +1,3 @@
1
1
  // @deprecated — private to AnchorPipeline seam. Use `from "./anchor-pipeline.js"` instead.
2
- // stripBarePrefixes, stripDiffPrefixes, swapReversedRanges, valEdit, findNewEdge are @internal to AnchorPipeline.
2
+ // stripBarePrefixes, stripDiffPrefixes, swapReversedRanges, valEdit are @internal to AnchorPipeline.
3
3
  export * from "./anchor-pipeline.js";
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Served-prefix guard tiers — FU-5 port of upstream
3
+ * `pi-better-edit@b92e0ec:src/hashline/served-guard.ts`.
4
+ *
5
+ * Three tiers beside the served-echo refusal gate (owned by
6
+ * `anchor-pipeline.ts`'s `findEditHashEcho`, unchanged here):
7
+ * - exact reproduction of a served line → the gate refuses (E_SUSPICIOUS_TEXT);
8
+ * - served anchor, differing content (`W_SERVED_PREFIX_MISMATCH`) → applied-only
9
+ * note, fires per occurrence, never blocks, never rewrites;
10
+ * - anchor-shaped prefix never served (`W_NEVER_SERVED_SHAPE`) → shape-only soft
11
+ * hint, fires regardless of the literal declaration.
12
+ *
13
+ * Evidence adaptation (disclosed in ADR-0025's FU-5 amendment): upstream judges
14
+ * the remainder against lease-derived canon DIGESTS (#151,
15
+ * `canonDigest(remainder) === served_leases.canon_hash`); this tree's parallel
16
+ * evidence is `servedCanons` — raw canon STRINGS recorded at serve time
17
+ * (`read-and-serve.ts:173`), so the comparison is `canon(tail) === servedCanons[pos]`.
18
+ * The tier semantics are identical; only the comparison space differs.
19
+ *
20
+ * Not ported (measured): upstream's `buildServedWritePrefixNote` stage
21
+ * (`lifecycle-hooks/index.ts:188-197`) — the local write channel
22
+ * (`src/write-hook.ts`) is outside this lane's target files; `findServedHashEcho`
23
+ * — the local gate stays `findEditHashEcho`.
24
+ *
25
+ * @module dsh-better-edit/hashline/served-guard
26
+ */
27
+ import { formatWarning } from "../domain-errors.js";
28
+ import { HASH_CLASS, HASH_SEP, canon } from "./hash-assign.js";
29
+ /**
30
+ * Owner of the anchor-shape parse for the warn tiers (diff-marker strip, length,
31
+ * separator, class); the class derives from hash-assign's HASH_CLASS, never a copy.
32
+ * Deliberately NOT a repo-wide parser: the sibling accepts (anchor-pipeline's
33
+ * `ANCHOR_ROW_RE`, hash-assign's prefix regexes, `parseRef`) differ in marker classes,
34
+ * error semantics and matching basis (measured FU-R R4) — unifying would change what
35
+ * each accepts.
36
+ */
37
+ const ANCHOR_SHAPE_RE = new RegExp(`^${HASH_CLASS}$`);
38
+ function anchorShapeFromLine(line) {
39
+ let text = line;
40
+ if (text.length > 0 && (text[0] === "+" || text[0] === "-" || text[0] === " ")) {
41
+ text = text.slice(1);
42
+ }
43
+ if (text.length < 4)
44
+ return undefined;
45
+ if (text[3] !== HASH_SEP)
46
+ return undefined;
47
+ const anchor = text.slice(0, 3);
48
+ if (!ANCHOR_SHAPE_RE.test(anchor))
49
+ return undefined;
50
+ return { anchor, tail: text.slice(4) };
51
+ }
52
+ /**
53
+ * SAFETY: Shared anchor index plus candidate scan for the served prefix
54
+ * mismatch tier. Builds the anchor-to-served map once, then parses each
55
+ * candidate (one optional leading diff marker, anchor, separator) in submitted
56
+ * order. Reported ordering never diverges because the tiers share this scan.
57
+ */
58
+ function collectServedAnchorHits(lines, served, servedCanons) {
59
+ const byAnchor = new Map();
60
+ for (let pos = 0; pos < served.length; pos++) {
61
+ const anchor = served[pos];
62
+ if (anchor === null || anchor === undefined)
63
+ continue;
64
+ const lineCanon = pos < servedCanons.length ? (servedCanons[pos] ?? null) : null;
65
+ if (lineCanon === null)
66
+ continue;
67
+ const list = byAnchor.get(anchor);
68
+ const entry = { servedLine: pos + 1, canon: lineCanon };
69
+ if (list)
70
+ list.push(entry);
71
+ else
72
+ byAnchor.set(anchor, [entry]);
73
+ }
74
+ if (byAnchor.size === 0)
75
+ return [];
76
+ const hits = [];
77
+ for (let index = 0; index < lines.length; index++) {
78
+ const parsed = anchorShapeFromLine(lines[index]);
79
+ if (!parsed)
80
+ continue;
81
+ const entries = byAnchor.get(parsed.anchor);
82
+ if (!entries)
83
+ continue;
84
+ hits.push({ index, anchor: parsed.anchor, entries, candidateCanon: canon(parsed.tail) });
85
+ }
86
+ return hits;
87
+ }
88
+ /**
89
+ * SAFETY: Served prefix mismatch — the middle tier beside the served-echo gate.
90
+ *
91
+ * A candidate reports here when it opens with an anchor served for this session
92
+ * and file, yet its remainder canon matches none of the canons recorded for
93
+ * that anchor's served line. Position-agnostic like the gate: `start` only
94
+ * shifts the reported `line` and never narrows matching. Empty or all-null
95
+ * `servedCanons` means no served content to compare against, so the result
96
+ * stays empty — never a shape-only report. Exact reproductions are excluded
97
+ * (the gate owns them), so callers scan for this tier only after the gate stays
98
+ * silent. Pure with no retained state: fires per occurrence, never suppressed.
99
+ */
100
+ export function findServedPrefixMismatches(lines, served, servedCanons, start = 1) {
101
+ const out = [];
102
+ for (const hit of collectServedAnchorHits(lines, served, servedCanons)) {
103
+ let exact = false;
104
+ for (const entry of hit.entries) {
105
+ if (entry.canon === hit.candidateCanon) {
106
+ exact = true;
107
+ break;
108
+ }
109
+ }
110
+ if (exact)
111
+ continue;
112
+ out.push({
113
+ k: hit.index + 1,
114
+ line: start + hit.index,
115
+ anchor: hit.anchor,
116
+ servedLine: hit.entries[0].servedLine,
117
+ });
118
+ }
119
+ return out;
120
+ }
121
+ /**
122
+ * SAFETY: the canonical remedy shared verbatim by both applied-hint builders:
123
+ * the bytes were applied, so a retry is knowably safe, and the remedy names the
124
+ * exact failing shape. Pinned byte-identical by test so builders cannot drift.
125
+ */
126
+ export const ANCHOR_PREFIX_REMEDY = "If the hash anchor prefix was unintended, `undo_last_edit`, then retry " +
127
+ "with the same `anchor_from`/`anchor_to` and drop the anchor prefix from `replace_with`.";
128
+ /**
129
+ * SAFETY: Model note for an applied edit carrying a served prefix mismatch.
130
+ * Applied-only, bytes untouched, never blocks: the post-edit diff already
131
+ * carries the written line, this note only tells the model the prefix
132
+ * reproduces a served anchor with differing content and names the remedy.
133
+ */
134
+ export function buildServedEditPrefixNote(args) {
135
+ return `${formatWarning("W_SERVED_PREFIX_MISMATCH", {
136
+ k: args.k,
137
+ anchor: args.anchor,
138
+ servedLine: args.servedLine,
139
+ })} ${ANCHOR_PREFIX_REMEDY}`;
140
+ }
141
+ /**
142
+ * SAFETY: Never-served anchor-shaped lines — the soft-hint tier beside the
143
+ * refusal gate and the served prefix mismatch tier.
144
+ *
145
+ * A candidate reports here when it opens with an anchor-shaped prefix
146
+ * (3 alphanumerics plus the separator, after one optional leading diff marker)
147
+ * whose anchor was never served for this session and file. Shape-only by design:
148
+ * the hint never blocks and never rewrites, so evidence gating does not apply.
149
+ * Served anchors are excluded (the gate and the mismatch tier own them).
150
+ * Pure with no retained state: fires per occurrence, never suppressed.
151
+ */
152
+ export function findNeverServedAnchorShapes(lines, served, start = 1) {
153
+ const servedSet = new Set();
154
+ for (const anchor of served) {
155
+ if (anchor !== null && anchor !== undefined)
156
+ servedSet.add(anchor);
157
+ }
158
+ const out = [];
159
+ for (let index = 0; index < lines.length; index++) {
160
+ const parsed = anchorShapeFromLine(lines[index]);
161
+ if (!parsed)
162
+ continue;
163
+ if (servedSet.has(parsed.anchor))
164
+ continue;
165
+ out.push({ k: index + 1, line: start + index, anchor: parsed.anchor });
166
+ }
167
+ return out;
168
+ }
169
+ /**
170
+ * SAFETY: Soft hint for an applied edit carrying never-served anchor-shaped lines.
171
+ * Applied-only, bytes untouched, never blocks: the bytes were written as-is with
172
+ * no rewrite. `count` states how many replacement lines match the tool's own row
173
+ * shape with anchors never served for this session and file. The trailing clause
174
+ * is gated on `if ... unintended` — a conditional reference, not an order.
175
+ * The per-item count travels as data (`neverServedCount`, anchor-pipeline); the batch engine
176
+ * aggregates, rendering ONE counted hint per CALL.
177
+ * Surfaced through the warnings seam (rendered by warnBlock) on the model-visible channel.
178
+ */
179
+ export function buildNeverServedEditHint(args) {
180
+ return `${formatWarning("W_NEVER_SERVED_SHAPE", { count: args.count })} ${ANCHOR_PREFIX_REMEDY}`;
181
+ }
package/lib/index.js CHANGED
@@ -124,7 +124,7 @@ export function apply(rootCtx) {
124
124
  rootCtx.logger.warn(`dsh-better-edit: guidance materialization failed: ${error instanceof Error ? error.message : String(error)}`);
125
125
  });
126
126
  const registered = new WeakSet();
127
- rootCtx.on("agent/session-start", ({ agent }) => {
127
+ rootCtx.on("agent/created", ({ agent }) => {
128
128
  // throttled central janitor on session-start (inside same handler to avoid extra listener)
129
129
  onSessionStart().catch((e) => rootCtx.logger.warn(`dsh-better-edit: central janitor failed: ${e instanceof Error ? e.message : String(e)}`));
130
130
  if (registered.has(agent))