@nomadop/session-watcher-dsh 0.10.0 → 0.10.2

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/dist/index.js CHANGED
@@ -516,6 +516,7 @@ var C_RATIO_TABLE = [
516
516
  { match: /fable.?5.?1/i, ratio: { [DEFAULT_CACHE_TTL]: 50, [LONG_CACHE_TTL]: 80 } },
517
517
  { match: /(opus|sonnet).?5.?5/i, ratio: { [DEFAULT_CACHE_TTL]: 25, [LONG_CACHE_TTL]: 40 } },
518
518
  { match: /claude|opus|sonnet|haiku|fable/i, ratio: { [DEFAULT_CACHE_TTL]: 12.5, [LONG_CACHE_TTL]: 20 } },
519
+ { match: /6.?1.?(sol|terra)/i, ratio: { [DEFAULT_CACHE_TTL]: 25, [LONG_CACHE_TTL]: 50 } },
519
520
  { match: /deepseek.*pro/i, ratio: 30 },
520
521
  { match: /deepseek/i, ratio: 50 }
521
522
  ];
@@ -584,6 +585,7 @@ var GC_HANDOFF_MAX_AGE_DAYS = 90;
584
585
  var HANDOFF_MAX_PATHS = 50;
585
586
  var HANDOFF_MAX_SUMMARY_CHARS = 1e4;
586
587
  var HANDOFF_MAX_NEXT_TASK_CHARS = 2e3;
588
+ var LINEAGE_HEADLINE_TOKEN_BUDGET = 3e3;
587
589
  var HANDOFF_HOOK_TTL_DAYS = 7;
588
590
  var HANDOFF_HOOK_MAX_DISPLAY = 3;
589
591
  var HANDOFF_HOOK_QUERY_LIMIT = HANDOFF_HOOK_MAX_DISPLAY + 1;
@@ -1072,6 +1074,11 @@ var Store = class _Store {
1072
1074
  ORDER BY loaded_at DESC, handoff_id DESC LIMIT 1
1073
1075
  ) AS latest JOIN handoff AS h ON h.handoff_id = latest.handoff_id`),
1074
1076
  getHandoff: db.prepare("SELECT * FROM handoff WHERE handoff_id = ?"),
1077
+ // The whole retained catalog of one project, for a person to browse: no age window, no producer exclusion,
1078
+ // no cap. `delivered_at` alone splits the groups; the row's identity breaks a creation-time tie.
1079
+ listHandoffCandidates: db.prepare(`SELECT load_token, created_at, next_task, delivered_at FROM handoff
1080
+ WHERE project_id = ?
1081
+ ORDER BY delivered_at IS NOT NULL, created_at DESC, handoff_id DESC`),
1075
1082
  // Turn note CRUD
1076
1083
  // created_at is written on insert only and deliberately absent from the SET list: the first
1077
1084
  // write's timestamp is the row's own age, while a later submission only revises its content.
@@ -1791,6 +1798,19 @@ var Store = class _Store {
1791
1798
  if (rows.length > 1) return { status: "ambiguous", rows };
1792
1799
  return { status: "unique", row: rows[0] };
1793
1800
  }
1801
+ // Every retained handoff of one project in browsing order — undelivered first, then delivered, each newest
1802
+ // first — as `{ loadToken, createdAt, nextTask, deliveredAt }` rows. READ-ONLY: unlike `deliverHandoffByToken`
1803
+ // it stamps no delivery. A project that is null or empty names no catalog, and the rows stored without a
1804
+ // project are no project's.
1805
+ listHandoffCandidatesByProject(projectId) {
1806
+ if (!projectId) return [];
1807
+ return this._stmts.listHandoffCandidates.all(projectId).map((r) => ({
1808
+ loadToken: r.load_token,
1809
+ createdAt: r.created_at,
1810
+ nextTask: r.next_task,
1811
+ deliveredAt: r.delivered_at
1812
+ }));
1813
+ }
1794
1814
  // R1-H: project-scoped FTS search. Statement prepared LAZILY (handoff_fts may not exist).
1795
1815
  searchHandoff(matchExpr, { projectId = null, limit = 3 } = {}) {
1796
1816
  if (!this.ftsAvailable) return [];
@@ -1994,14 +2014,6 @@ function loadIsIgnored(cwd) {
1994
2014
  }
1995
2015
  }
1996
2016
 
1997
- // lib/project-key.js
1998
- import { resolve } from "node:path";
1999
- function resolveProjectKey({ claudeProjectDir, cwd } = {}) {
2000
- const raw = claudeProjectDir || cwd;
2001
- if (!raw) return null;
2002
- return resolve(raw);
2003
- }
2004
-
2005
2017
  // lib/harness/dsh/cache-ttl.js
2006
2018
  function cacheTtlForRetention(retention) {
2007
2019
  return retention === "long" ? LONG_CACHE_TTL : null;
@@ -2035,7 +2047,7 @@ function createResourcePolicy({ projectRoot = null, isIgnored = null } = {}) {
2035
2047
  if (relative && ignoreMatcher && ignoreMatcher(relative)) return "gitignore";
2036
2048
  return null;
2037
2049
  }
2038
- function resolve2(resourceKey) {
2050
+ function resolve3(resourceKey) {
2039
2051
  const defaultDiscardReason = discardReasonFor(resourceKey);
2040
2052
  return { selectedByDefault: defaultDiscardReason === null, defaultDiscardReason };
2041
2053
  }
@@ -2075,7 +2087,7 @@ function createResourcePolicy({ projectRoot = null, isIgnored = null } = {}) {
2075
2087
  }
2076
2088
  return inferred;
2077
2089
  }
2078
- return { resolve: resolve2, infer };
2090
+ return { resolve: resolve3, infer };
2079
2091
  }
2080
2092
 
2081
2093
  // lib/dialogue-fold.js
@@ -4193,6 +4205,12 @@ var SessionWatcher = class {
4193
4205
  }
4194
4206
  return this._handoff.searchResponse(results);
4195
4207
  }
4208
+ // The handoffs of this session's project a person may pick one from, in the Store's browsing order. Unlike
4209
+ // `deliverHandoff` it delivers nothing and applies no auto-match window, producer exclusion or cap; a null
4210
+ // project is an empty catalog, and a Store failure propagates.
4211
+ listHandoffCandidates() {
4212
+ return this._store.listHandoffCandidatesByProject(this._projectId);
4213
+ }
4196
4214
  // One session, segment and project captured at entry: the response is composed after the delivery
4197
4215
  // transaction commits, and it must describe the consumer that actually claimed the row.
4198
4216
  async deliverHandoff({ loadToken } = {}) {
@@ -5925,13 +5943,13 @@ async function Module2(moduleArg = {}) {
5925
5943
  }
5926
5944
  readAsync = /* @__PURE__ */ __name(async (url) => {
5927
5945
  if (isFileURI(url)) {
5928
- return new Promise((resolve2, reject) => {
5946
+ return new Promise((resolve3, reject) => {
5929
5947
  var xhr = new XMLHttpRequest();
5930
5948
  xhr.open("GET", url, true);
5931
5949
  xhr.responseType = "arraybuffer";
5932
5950
  xhr.onload = () => {
5933
5951
  if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
5934
- resolve2(xhr.response);
5952
+ resolve3(xhr.response);
5935
5953
  return;
5936
5954
  }
5937
5955
  reject(xhr.status);
@@ -6127,9 +6145,9 @@ async function Module2(moduleArg = {}) {
6127
6145
  __name(receiveInstantiationResult, "receiveInstantiationResult");
6128
6146
  var info2 = getWasmImports();
6129
6147
  if (Module["instantiateWasm"]) {
6130
- return new Promise((resolve2, reject) => {
6148
+ return new Promise((resolve3, reject) => {
6131
6149
  Module["instantiateWasm"](info2, (mod, inst) => {
6132
- resolve2(receiveInstance(mod, inst));
6150
+ resolve3(receiveInstance(mod, inst));
6133
6151
  });
6134
6152
  });
6135
6153
  }
@@ -7460,8 +7478,8 @@ async function Module2(moduleArg = {}) {
7460
7478
  if (runtimeInitialized) {
7461
7479
  moduleRtn = Module;
7462
7480
  } else {
7463
- moduleRtn = new Promise((resolve2, reject) => {
7464
- readyPromiseResolve = resolve2;
7481
+ moduleRtn = new Promise((resolve3, reject) => {
7482
+ readyPromiseResolve = resolve3;
7465
7483
  readyPromiseReject = reject;
7466
7484
  });
7467
7485
  }
@@ -9548,11 +9566,12 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
9548
9566
  const totalStock = usage.input + usage.cacheRead + usage.cacheWrite;
9549
9567
  const model = record.model ?? null;
9550
9568
  const firstOfEpoch = segmentSteps.length === 0;
9569
+ const totals = ledger.residentTotals();
9551
9570
  if (settlementCursor === null && totalStock > 0) {
9552
- dead = totalStock;
9571
+ dead = totalStock - Math.min(totalStock, residentTotalOf(totals));
9553
9572
  sessionFloor = totalStock;
9573
+ pendingResiduals = [];
9554
9574
  }
9555
- const totals = ledger.residentTotals();
9556
9575
  const residentTotal = residentTotalOf(totals);
9557
9576
  const miss = settlementCursor !== null && classifyMiss({ cacheRead: usage.cacheRead, prevL: settlementCursor.L });
9558
9577
  const L = miss ? totalStock : usage.cacheRead;
@@ -10096,10 +10115,18 @@ function deletePricingOverride(model) {
10096
10115
  getStore().deleteConfig(`pricing:${model}`);
10097
10116
  }
10098
10117
 
10118
+ // lib/project-key.js
10119
+ import { resolve } from "node:path";
10120
+ function resolveProjectKey({ claudeProjectDir, cwd } = {}) {
10121
+ const raw = claudeProjectDir || cwd;
10122
+ if (!raw) return null;
10123
+ return resolve(raw);
10124
+ }
10125
+
10099
10126
  // package.json
10100
10127
  var package_default = {
10101
10128
  name: "@nomadop/session-watcher",
10102
- version: "0.10.0",
10129
+ version: "0.10.2",
10103
10130
  description: "Local Claude Code context-cost monitor, transcript replay, buckets, and handoff",
10104
10131
  type: "module",
10105
10132
  license: "MIT",
@@ -10191,7 +10218,7 @@ function createResolver({ path: path3, homeDir }) {
10191
10218
  if (homeDir !== null && typeof homeDir !== "string") {
10192
10219
  throw new TypeError("Working Tree homeDir must be a string or null");
10193
10220
  }
10194
- return function resolve2(base, raw) {
10221
+ return function resolve3(base, raw) {
10195
10222
  if (typeof raw !== "string" || raw.length === 0) return null;
10196
10223
  let value = raw;
10197
10224
  if (homeDir !== null && raw === "~") value = homeDir;
@@ -10207,7 +10234,7 @@ function createResolver({ path: path3, homeDir }) {
10207
10234
  };
10208
10235
  }
10209
10236
  function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars } = {}) {
10210
- const resolve2 = createResolver({ path: path3, homeDir });
10237
+ const resolve3 = createResolver({ path: path3, homeDir });
10211
10238
  requireBound("cacheEntries", cacheEntries);
10212
10239
  requireBound("cacheChars", cacheChars);
10213
10240
  const cache = /* @__PURE__ */ new Map();
@@ -10235,7 +10262,7 @@ function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars
10235
10262
  }
10236
10263
  }
10237
10264
  return {
10238
- resolve: resolve2,
10265
+ resolve: resolve3,
10239
10266
  stat: (file) => orNull(() => {
10240
10267
  const st = statSync3(file);
10241
10268
  return { size: st.size, isFile: st.isFile() };
@@ -11222,12 +11249,38 @@ function createToolEvidenceInterpreter({ attribution, profile, limits } = {}) {
11222
11249
  return { interpretToolUse, completeToolResult, resourceKeysOf };
11223
11250
  }
11224
11251
 
11252
+ // lib/harness/dsh/load-message.js
11253
+ var LOAD_MESSAGE_KIND = "session-watcher-load";
11254
+ function loadMessageInput({ route, calls }) {
11255
+ return {
11256
+ content: calls.map(({ text }) => ({ type: "text", text })),
11257
+ source: {
11258
+ kind: LOAD_MESSAGE_KIND,
11259
+ route: { provider: route.provider, model: route.model },
11260
+ calls: calls.map(({ id, name: name3, arguments: args2 }) => ({ id, name: name3, arguments: args2 }))
11261
+ }
11262
+ };
11263
+ }
11264
+ function loadRouteOf(message) {
11265
+ return message?.source?.kind === LOAD_MESSAGE_KIND ? message.source.route : void 0;
11266
+ }
11267
+ var isId = (value) => typeof value === "string" && value !== "";
11268
+ var isCall = (call) => call !== null && typeof call === "object" && isId(call.id) && typeof call.name === "string" && typeof call.arguments === "string";
11269
+ var isTextBlock = (block) => block?.type === "text" && typeof block.text === "string";
11270
+ function loadCallsOf(message) {
11271
+ const calls = message?.source?.calls;
11272
+ const content = message?.content;
11273
+ if (!Array.isArray(calls) || !Array.isArray(content) || calls.length !== content.length) return null;
11274
+ if (!calls.every(isCall) || !content.every(isTextBlock)) return null;
11275
+ return calls.map(({ id, name: name3, arguments: args2 }, index) => ({ id, name: name3, arguments: args2, text: content[index].text }));
11276
+ }
11277
+
11225
11278
  // lib/harness/dsh/transcript-observation.js
11226
11279
  var SCOPE = "dsh-transcript-observation";
11227
11280
  var MESSAGE_NAMESPACE = "dsh:message:";
11228
11281
  var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
11229
11282
  var isIndex = (value) => Number.isSafeInteger(value) && value >= 0;
11230
- var isId = (value) => typeof value === "string" && value !== "";
11283
+ var isId2 = (value) => typeof value === "string" && value !== "";
11231
11284
  var isSurfaceOp = (value) => value === "append" || isObject2(value) && value.op === "replace";
11232
11285
  var nothing = () => ({ observations: [], diagnostics: [] });
11233
11286
  function violation(event, field) {
@@ -11247,7 +11300,7 @@ function baseOf2(event) {
11247
11300
  return { sourceOrdinal: event.seq, sourceEntryId: String(event.seq), timestamp: event.time };
11248
11301
  }
11249
11302
  var textShaped = (block) => block.type !== "text" || typeof block.text === "string";
11250
- var toolCallShaped = (block) => block.type !== "tool-call" || isId(block.id) && typeof block.name === "string" && typeof block.arguments === "string";
11303
+ var toolCallShaped = (block) => block.type !== "tool-call" || isId2(block.id) && typeof block.name === "string" && typeof block.arguments === "string";
11251
11304
  function isContent(content, ...shapes) {
11252
11305
  return Array.isArray(content) && content.every((block) => isObject2(block) && shapes.every((shaped) => shaped(block)));
11253
11306
  }
@@ -11279,7 +11332,7 @@ function reduceHumanMessage(event) {
11279
11332
  const { data } = event;
11280
11333
  const fault = faultOf([
11281
11334
  ...envelopeChecks(event),
11282
- ["data.id", isId(data.id)],
11335
+ ["data.id", isId2(data.id)],
11283
11336
  ["data.content", isContent(data.content, textShaped)]
11284
11337
  ]);
11285
11338
  if (fault !== null) return violation(event, fault);
@@ -11305,10 +11358,49 @@ function reduceCheckpoint(event) {
11305
11358
  if (fault !== null) return violation(event, fault);
11306
11359
  return { observations: [{ type: "epoch-boundary", ...baseOf2(event), provenance: "harness" }], diagnostics: [] };
11307
11360
  }
11361
+ var isRoute = (route) => isObject2(route) && typeof route.provider === "string" && typeof route.model === "string";
11362
+ function reduceLoadMessage(event) {
11363
+ const { data } = event;
11364
+ const calls = loadCallsOf(data);
11365
+ const fault = faultOf([
11366
+ ...envelopeChecks(event),
11367
+ ["data.id", isId2(data.id)],
11368
+ ["data.source.route", isRoute(loadRouteOf(data))],
11369
+ ["data.source.calls", calls !== null]
11370
+ ]);
11371
+ if (fault !== null) return violation(event, fault);
11372
+ const base = baseOf2(event);
11373
+ const messageId = MESSAGE_NAMESPACE + data.id;
11374
+ const { model } = loadRouteOf(data);
11375
+ const observations = calls.flatMap(({ id, name: name3, arguments: args2, text }) => [
11376
+ {
11377
+ type: "tool-use",
11378
+ messageId,
11379
+ model,
11380
+ cwd: null,
11381
+ toolUseId: id,
11382
+ name: name3,
11383
+ input: parseArguments(args2),
11384
+ ...base,
11385
+ provenance: "harness"
11386
+ },
11387
+ {
11388
+ type: "tool-result",
11389
+ toolUseId: id,
11390
+ content: text,
11391
+ isError: false,
11392
+ resultMeta: { meta: null, error: null },
11393
+ ...base,
11394
+ provenance: "harness"
11395
+ }
11396
+ ]);
11397
+ return { observations, diagnostics: [] };
11398
+ }
11308
11399
  function reduceUserMessage(event) {
11309
11400
  const kind = event.data?.source?.kind;
11310
11401
  if (kind === "user") return reduceHumanMessage(event);
11311
11402
  if (kind === "compact-checkpoint") return reduceCheckpoint(event);
11403
+ if (kind === LOAD_MESSAGE_KIND) return reduceLoadMessage(event);
11312
11404
  return typeof kind === "string" ? nothing() : violation(event, "data.source.kind");
11313
11405
  }
11314
11406
  function reduceAssistantMessage(event) {
@@ -11318,7 +11410,7 @@ function reduceAssistantMessage(event) {
11318
11410
  ...envelopeChecks(event),
11319
11411
  ["data.turn", isIndex(data?.turn)],
11320
11412
  ["data.step", isIndex(data?.step)],
11321
- ["data.message.id", isId(message?.id)],
11413
+ ["data.message.id", isId2(message?.id)],
11322
11414
  ["data.message.source.model", typeof message?.source?.model === "string"],
11323
11415
  ["data.message.content", isContent(message?.content, textShaped, toolCallShaped)],
11324
11416
  ["data.usage", data?.usage === void 0 || isUsage(data.usage)]
@@ -11367,7 +11459,7 @@ function reduceToolResult(event) {
11367
11459
  ...envelopeChecks(event),
11368
11460
  ["data.turn", isIndex(data?.turn)],
11369
11461
  ["data.step", isIndex(data?.step)],
11370
- ["data.message.toolCallId", isId(message?.toolCallId)],
11462
+ ["data.message.toolCallId", isId2(message?.toolCallId)],
11371
11463
  ["data.message.isError", message?.isError === void 0 || typeof message.isError === "boolean"],
11372
11464
  ["data.message.content", isContent(message?.content, textShaped)]
11373
11465
  ]);
@@ -12628,9 +12720,9 @@ function createWatcherTable({ compose, readSession, cacheTtlFor = () => null, mo
12628
12720
  if (entry.state === "live") return Promise.resolve(liveView(entry));
12629
12721
  if (entry.state === "failed") return Promise.reject(new Error(entry.diagnostic.message));
12630
12722
  if (signal.aborted) return Promise.reject(aborted(sessionId, signal));
12631
- return new Promise((resolve2, reject) => {
12723
+ return new Promise((resolve3, reject) => {
12632
12724
  const onAbort = () => reject(aborted(sessionId, signal));
12633
- const waiter = { resolve: resolve2, reject, release: () => signal.removeEventListener("abort", onAbort) };
12725
+ const waiter = { resolve: resolve3, reject, release: () => signal.removeEventListener("abort", onAbort) };
12634
12726
  entry.waiters.add(waiter);
12635
12727
  signal.addEventListener("abort", onAbort, { once: true });
12636
12728
  });
@@ -12654,9 +12746,10 @@ function pairOf(fields) {
12654
12746
  function pairOfEvent(event) {
12655
12747
  if (event?.type === "request/header") return pairOf(event.data?.header?.config);
12656
12748
  if (event?.type === "assistant/message") return pairOf(event.data?.message?.source);
12749
+ if (event?.type === "user/message") return pairOf(loadRouteOf(event.data));
12657
12750
  return void 0;
12658
12751
  }
12659
- function createModelNames({ resolve: resolve2 }) {
12752
+ function createModelNames({ resolve: resolve3 }) {
12660
12753
  const names = /* @__PURE__ */ new Map();
12661
12754
  const inFlight = /* @__PURE__ */ new Map();
12662
12755
  const store = (key) => ({ name: name3 }) => {
@@ -12670,7 +12763,7 @@ function createModelNames({ resolve: resolve2 }) {
12670
12763
  if (names.has(key)) continue;
12671
12764
  let pending = inFlight.get(key);
12672
12765
  if (pending === void 0) {
12673
- pending = resolve2(provider, model).then(store(key)).finally(() => inFlight.delete(key));
12766
+ pending = resolve3(provider, model).then(store(key)).finally(() => inFlight.delete(key));
12674
12767
  inFlight.set(key, pending);
12675
12768
  }
12676
12769
  waits.push(pending);
@@ -12686,11 +12779,14 @@ function createModelNames({ resolve: resolve2 }) {
12686
12779
  return [...pairs.values()];
12687
12780
  }
12688
12781
  function mapEvent(event) {
12689
- if (event?.type !== "assistant/message") return event;
12690
- const pair = pairOf(event.data?.message?.source);
12691
- const name3 = pair && nameOf(pair.provider, pair.model);
12782
+ const pair = pairOfEvent(event);
12783
+ if (pair === void 0 || event.type === "request/header") return event;
12784
+ const name3 = nameOf(pair.provider, pair.model);
12692
12785
  if (name3 === void 0) return event;
12693
12786
  const { data } = event;
12787
+ if (event.type === "user/message") {
12788
+ return { ...event, data: { ...data, source: { ...data.source, route: { ...data.source.route, model: name3 } } } };
12789
+ }
12694
12790
  const { message } = data;
12695
12791
  return { ...event, data: { ...data, message: { ...message, source: { ...message.source, model: name3 } } } };
12696
12792
  }
@@ -12760,6 +12856,53 @@ function lineageHeadlines({ store, lineage }) {
12760
12856
  return buildTurnBrowse({ store, lineage }).sections.map(({ label, headline }) => ({ label, headline }));
12761
12857
  }
12762
12858
 
12859
+ // lib/lineage-headlines.js
12860
+ var positionOf = (entry) => Number(entry.label.slice(1));
12861
+ var runOf2 = (from, to) => ({ label: from === to ? `S${from}` : `S${from}-S${to}`, omitted: true });
12862
+ function collapseRuns(entries) {
12863
+ const runs = [];
12864
+ let from = null;
12865
+ let to = null;
12866
+ for (const entry of entries) {
12867
+ const n = positionOf(entry);
12868
+ if (to !== null && n === to + 1) {
12869
+ to = n;
12870
+ continue;
12871
+ }
12872
+ if (to !== null) runs.push(runOf2(from, to));
12873
+ from = to = n;
12874
+ }
12875
+ if (to !== null) runs.push(runOf2(from, to));
12876
+ return runs;
12877
+ }
12878
+ function boundLineageHeadlines(entries, budget = LINEAGE_HEADLINE_TOKEN_BUDGET) {
12879
+ let start2 = entries.length;
12880
+ while (start2 > 0 && estimateWireTokens({ lineage: entries.slice(start2 - 1) }, DEFAULT_CTP) <= budget) {
12881
+ start2--;
12882
+ }
12883
+ return [...collapseRuns(entries.slice(0, start2)), ...entries.slice(start2)];
12884
+ }
12885
+ var ITEM = "[1-9][0-9]*(?:-[1-9][0-9]*)?";
12886
+ var POSITIONS = new RegExp(`^${ITEM}(?:,${ITEM})*$`);
12887
+ function parseLineagePositions(text) {
12888
+ if (typeof text !== "string" || !POSITIONS.test(text)) return null;
12889
+ const ranges = text.split(",").map((item) => {
12890
+ const [from, to = from] = item.split("-").map(Number);
12891
+ return [from, to];
12892
+ });
12893
+ return ranges.some(([from, to]) => from > to) ? null : ranges;
12894
+ }
12895
+ function selectLineagePositions(entries, ranges) {
12896
+ const positions = entries.map(positionOf);
12897
+ const inside = ([from, to], n) => n >= from && n <= to;
12898
+ const covered = ranges.every((range) => {
12899
+ const [from, to] = range;
12900
+ return positions.filter((n) => inside(range, n)).length === to - from + 1;
12901
+ });
12902
+ if (!covered) return null;
12903
+ return entries.filter((_, i2) => ranges.some((range) => inside(range, positions[i2])));
12904
+ }
12905
+
12763
12906
  // lib/wire.js
12764
12907
  function statusWire(status) {
12765
12908
  const { sourceLocator, ...rest } = status;
@@ -12865,7 +13008,7 @@ async function loadedHandoffPayload(core, { store, turnPageBuilder, dialogueSour
12865
13008
  const sessions = fromHandoff({ store, handoffId: core.handoff_id });
12866
13009
  return {
12867
13010
  ...core,
12868
- lineage: lineageHeadlines({ store, lineage: sessions }),
13011
+ lineage: boundLineageHeadlines(lineageHeadlines({ store, lineage: sessions })),
12869
13012
  ...turnPageWire(await turnPageBuilder({ store, lineage: sessions, dialogueSource, dialogueProjection, notice }))
12870
13013
  };
12871
13014
  } catch (err2) {
@@ -12874,6 +13017,18 @@ async function loadedHandoffPayload(core, { store, turnPageBuilder, dialogueSour
12874
13017
  }
12875
13018
  }
12876
13019
 
13020
+ // lib/handoff-discovery.js
13021
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
13022
+ function formatAge(createdAt) {
13023
+ const diffMs = Math.max(0, Date.now() - createdAt);
13024
+ const mins = Math.floor(diffMs / 6e4);
13025
+ if (mins < 60) return `${mins} min ago`;
13026
+ const hours = Math.floor(mins / 60);
13027
+ if (hours < 24) return `${hours}h ago`;
13028
+ const days = Math.floor(hours / 24);
13029
+ return `${days}d ago`;
13030
+ }
13031
+
12877
13032
  // dsh/src/rpc.js
12878
13033
  var failure = (code, message) => ({ ok: false, error: { code, message, details: {} } });
12879
13034
  var live = (payload) => ({ ok: true, value: { state: "live", payload } });
@@ -12937,7 +13092,17 @@ function createRpcHandler({ table, store, now = Date.now, publish = () => {
12937
13092
  }
12938
13093
  return writePricing(entry, (model) => savePricingOverride(model, { readPrice, writePrice, presetId: sanitizePresetId(presetId) }));
12939
13094
  },
12940
- "pricing/delete": (entry) => writePricing(entry, deletePricingOverride)
13095
+ "pricing/delete": (entry) => writePricing(entry, deletePricingOverride),
13096
+ // A Store failure rejects the call, which the carrier answers as a transport failure; no empty catalog stands in for it.
13097
+ // The Host shapes each item's age, since the Client imports no `lib/`.
13098
+ "handoff/list": ({ watcher }) => live({
13099
+ items: watcher.listHandoffCandidates().map(({ loadToken, createdAt, nextTask, deliveredAt }) => ({
13100
+ loadToken,
13101
+ age: formatAge(createdAt),
13102
+ nextTask,
13103
+ deliveredAt
13104
+ }))
13105
+ })
12941
13106
  };
12942
13107
  return async (endpoint, payload) => {
12943
13108
  if (!Object.hasOwn(endpoints, endpoint)) return failure("unknown_endpoint", `unknown endpoint ${endpoint}`);
@@ -13120,6 +13285,7 @@ var NO_HANDOFF_LOADED = Object.freeze({
13120
13285
  });
13121
13286
  var STALE_CURSOR_MESSAGE = "That before boundary resolves to nothing in this lineage. Omit before to start again from the newest page, or take a session label from the load reply's lineage.";
13122
13287
  var SCOPE_ABSENT_MESSAGE = "That S{k}:{T} scope names a turn this lineage does not contain. Call turn_locate for a current scope, or omit scope to cover the whole lineage.";
13288
+ var UNUSABLE_POSITIONS_MESSAGE = "k must be positions of this lineage: numbers and closed ranges separated by commas, such as 3, 2-5 or 1,4-6, with no spaces and no S prefix, and each number must name a session that has a headline. Take them from the labels of the load reply's lineage, where S2-S5 is 2-5.";
13123
13289
  var PAGE_IS_THE_FALLBACK = "Read the lineage with turn_page instead \u2014 it paginates deterministically over the same sessions and needs no query.";
13124
13290
  function withPageRecovery(result) {
13125
13291
  if (result?.error === "turn_page_unavailable") {
@@ -13154,6 +13320,12 @@ function withLocateRecovery(result, { hitRecovery } = {}) {
13154
13320
  }
13155
13321
  return result;
13156
13322
  }
13323
+ function withHeadlinesRecovery(result) {
13324
+ if (result?.error === "lineage_headlines_unavailable") {
13325
+ return { ...result, recovery: "Call lineage_headlines again; it reads the store afresh on every call." };
13326
+ }
13327
+ return result;
13328
+ }
13157
13329
  function withLoadRecovery(result) {
13158
13330
  if (result?.error === "handoff_delivery_unavailable") {
13159
13331
  return { ...result, recovery: "The delivery record could not be written, so this response carries no content. Call load_handoff again with the same token once the store is writable." };
@@ -13161,6 +13333,9 @@ function withLoadRecovery(result) {
13161
13333
  if (result?.turn_page_error) {
13162
13334
  return { ...result, recovery: "The handoff loaded and the rest of this response is complete; only its turn page and the lineage headlines beside it failed to build. Call turn_page to obtain the page." };
13163
13335
  }
13336
+ if (result?.lineage?.some((entry) => entry.omitted)) {
13337
+ return { ...result, recovery: "The older sessions of the lineage are collapsed into runs marked omitted, each run labelled by its first and last session. lineage_headlines reads the headlines of a run when the next task or what is already in context needs them: pass the run's numbers as k, where S2-S5 is 2-5." };
13338
+ }
13164
13339
  return result;
13165
13340
  }
13166
13341
 
@@ -13486,6 +13661,24 @@ function createTurnReadService({
13486
13661
  if (process.env.SW_DEBUG) console.error("[turn_locate_tool]", err2);
13487
13662
  return withLocateRecovery({ error: "locate_unavailable" });
13488
13663
  }
13664
+ },
13665
+ // The lineage resolves first, then `k`, then the headline reads: a caller that loaded nothing meets
13666
+ // no_handoff_loaded whatever it passed, and a `k` that cannot parse costs no turn-note read. The throw
13667
+ // stays outside the try so that it is not mistaken for a store failure.
13668
+ async lineageHeadlines({ k } = {}) {
13669
+ try {
13670
+ const lineage = forLoadedHandoff({ store: store(), sessionId: sessionId() });
13671
+ if (lineage.length === 0) return NO_HANDOFF_LOADED;
13672
+ const ranges = parseLineagePositions(k);
13673
+ if (ranges !== null) {
13674
+ const selected = selectLineagePositions(lineageHeadlines({ store: store(), lineage }), ranges);
13675
+ if (selected !== null) return { lineage: selected };
13676
+ }
13677
+ } catch (err2) {
13678
+ if (process.env.SW_DEBUG) console.error("[lineage_headlines_tool]", err2);
13679
+ return withHeadlinesRecovery({ error: "lineage_headlines_unavailable", retryable: true });
13680
+ }
13681
+ throw new Error(UNUSABLE_POSITIONS_MESSAGE);
13489
13682
  }
13490
13683
  };
13491
13684
  }
@@ -13511,19 +13704,52 @@ function assertBefore(before) {
13511
13704
  function assertScope(scope) {
13512
13705
  if (scope !== void 0 && !TURN_ADDRESS_RE.test(scope)) throw new Error("scope must be an S{k}:{T} turn address");
13513
13706
  }
13707
+ function assertPositions(k) {
13708
+ if (parseLineagePositions(k) === null) throw new Error(UNUSABLE_POSITIONS_MESSAGE);
13709
+ }
13514
13710
  function assertQuery(q) {
13515
13711
  if (typeof q !== "string" || q.trim() === "" || q.length > HISTORY_EXCERPT_CHARS) {
13516
13712
  throw new Error(`q must be a non-blank string of at most ${HISTORY_EXCERPT_CHARS} characters`);
13517
13713
  }
13518
13714
  }
13519
13715
  var lossless = (value) => JSON.parse(JSON.stringify(value));
13716
+ function createHandoffDelivery({ table, store, sessionTitle = () => void 0 }) {
13717
+ const recovery = createDshTurnRecovery();
13718
+ function retitle(session, handoffId) {
13719
+ try {
13720
+ const titles = sessionTitle();
13721
+ const nextTask = store.getHandoff(handoffId)?.nextTask;
13722
+ if (titles === void 0 || !nextTask?.trim()) return;
13723
+ titles.rename(session, nextTask);
13724
+ } catch (error) {
13725
+ writeDiagnostic(session.id, titleRenameFailed(error));
13726
+ }
13727
+ }
13728
+ async function payloadOf({ watcher, dialogueSource, dialogueProjection }, session, { load_token }) {
13729
+ const delivered = await watcher.deliverHandoff(load_token ? { loadToken: String(load_token) } : {});
13730
+ if (delivered.ok === false) return { error: delivered.error, retryable: delivered.retryable === true };
13731
+ if (!delivered.found) return delivered;
13732
+ retitle(session, delivered.handoff_id);
13733
+ return loadedHandoffPayload(delivered, {
13734
+ store,
13735
+ turnPageBuilder: buildTurnPage,
13736
+ dialogueSource,
13737
+ dialogueProjection,
13738
+ notice: recovery.notice
13739
+ });
13740
+ }
13741
+ return async ({ agent, signal, args: args2 }) => {
13742
+ const { session } = agent;
13743
+ const entry = await table.waitLive(session.id, signal);
13744
+ return lossless(withLoadRecovery(await payloadOf(entry, session, args2)));
13745
+ };
13746
+ }
13520
13747
  function createTools({
13521
13748
  defineTool: defineTool2,
13522
13749
  table,
13523
13750
  store,
13524
13751
  now = Date.now,
13525
- resolvePersisted = async () => null,
13526
- sessionTitle = () => void 0
13752
+ resolvePersisted = async () => null
13527
13753
  }) {
13528
13754
  const recovery = createDshTurnRecovery();
13529
13755
  const tool = ({ name: name3, description, parameters = {}, check = () => {
@@ -13546,30 +13772,6 @@ function createTools({
13546
13772
  dialogueProjection,
13547
13773
  recovery
13548
13774
  });
13549
- function retitle(session, handoffId) {
13550
- try {
13551
- const titles = sessionTitle();
13552
- const nextTask = store.getHandoff(handoffId)?.nextTask;
13553
- if (titles === void 0 || !nextTask?.trim()) return;
13554
- titles.rename(session, nextTask);
13555
- } catch (error) {
13556
- writeDiagnostic(session.id, titleRenameFailed(error));
13557
- }
13558
- }
13559
- async function loadHandoff({ watcher, session, dialogueSource, dialogueProjection }, { load_token, query, query_mode }) {
13560
- if (!load_token && query) return watcher.searchHandoffs({ query: String(query), queryMode: query_mode });
13561
- const delivered = await watcher.deliverHandoff(load_token ? { loadToken: String(load_token) } : {});
13562
- if (delivered.ok === false) return { error: delivered.error, retryable: delivered.retryable === true };
13563
- if (!delivered.found) return delivered;
13564
- retitle(session, delivered.handoff_id);
13565
- return loadedHandoffPayload(delivered, {
13566
- store,
13567
- turnPageBuilder: buildTurnPage,
13568
- dialogueSource,
13569
- dialogueProjection,
13570
- notice: recovery.notice
13571
- });
13572
- }
13573
13775
  return [
13574
13776
  defineTool2({
13575
13777
  name: "watcher_status",
@@ -13639,16 +13841,6 @@ function createTools({
13639
13841
  loadToken: load_token
13640
13842
  })
13641
13843
  }),
13642
- tool({
13643
- name: "load_handoff",
13644
- description: "Retrieve a prepared handoff package by token, by free-text search, or \u2014 with neither given \u2014 by auto-match over undelivered handoffs of this project from other sessions. A retrieved package carries the lineage behind it as one headline per lineage member, oldest to newest, beside the newest page of its turns.",
13645
- parameters: {
13646
- load_token: { type: "string", description: "Semantic token from prepare_handoff (exact match)" },
13647
- query: { type: "string", description: "Free-text search when the token is unknown; returns top matches" },
13648
- query_mode: { type: "string", enum: ["plain", "advanced"], description: "plain (default) escapes input; advanced passes raw FTS5 syntax" }
13649
- },
13650
- run: async (args2, entry) => withLoadRecovery(await loadHandoff(entry, args2))
13651
- }),
13652
13844
  tool({
13653
13845
  name: "get_turn_skeleton",
13654
13846
  description: "Write the current context epoch to a turn skeleton file and a notes file whose `## NOTE[T]` headings are the slot set, and return both paths, the snapshot id to submit against, and the protocol for filling them.",
@@ -13666,7 +13858,7 @@ function createTools({
13666
13858
  name: "turn_page",
13667
13859
  description: "Read a page of the history turns carried by the handoff loaded into this session, newest first.",
13668
13860
  parameters: {
13669
- before: { type: "string", description: "Where to read back from: an S{k}:{T} cursor from the next_before of the handoff load reply or of a previous page, which ends the page before that turn; or a bare S{k} session label from the load reply's lineage, which starts at that session's end. Omit for the newest page." }
13861
+ before: { type: "string", description: "Where to read back from: an S{k}:{T} cursor from the next_before of the handoff load reply or of a previous page, which ends the page before that turn; or a bare S{k} session label from the load reply's lineage, which starts at that session's end; a session inside an omitted run is addressed as S{k}, k being its own number. Omit for the newest page." }
13670
13862
  },
13671
13863
  check: ({ before }) => assertBefore(before),
13672
13864
  run: (args2, entry) => turnReads(entry).turnPage(args2)
@@ -13692,12 +13884,205 @@ function createTools({
13692
13884
  },
13693
13885
  check: ({ q }) => assertQuery(q),
13694
13886
  run: (args2, entry) => turnReads(entry).turnLocate(args2)
13887
+ }),
13888
+ tool({
13889
+ name: "lineage_headlines",
13890
+ description: "Read the headlines of chosen sessions of the lineage behind the handoff loaded into this session, such as an omitted run of the load reply's lineage. Returns one entry per chosen lineage member, oldest to newest.",
13891
+ parameters: {
13892
+ k: { type: "string", required: true, description: 'Positions in the lineage, as numbers and closed ranges separated by commas, such as "3", "2-5" or "1,4-6". Each number is the k of an S{k} label and must name a session that has a headline.' }
13893
+ },
13894
+ check: ({ k }) => assertPositions(k),
13895
+ run: (args2, entry) => turnReads(entry).lineageHeadlines(args2)
13695
13896
  })
13696
13897
  ];
13697
13898
  }
13698
13899
 
13699
13900
  // dsh/src/continue.js
13901
+ import { randomUUID as randomUUID2 } from "node:crypto";
13902
+
13903
+ // dsh/src/load.js
13700
13904
  import { randomUUID } from "node:crypto";
13905
+ import { statSync as statSync4 } from "node:fs";
13906
+ import { isAbsolute as isAbsolute3, resolve as resolve2 } from "node:path";
13907
+ var READ_LINE_CAP = 2e3;
13908
+ var HEAD_LINES = 40;
13909
+ var RANGED = /\(lines (\d+)-(\d+)\)/;
13910
+ var NO_ROUTE = "No model route is known for this session yet.";
13911
+ var messageOf2 = (error) => error instanceof Error ? error.message : String(error);
13912
+ function locate(path3, cwd, projectDir) {
13913
+ const candidates = isAbsolute3(path3) ? [path3] : [resolve2(cwd, path3), ...projectDir ? [resolve2(projectDir, path3)] : []];
13914
+ return candidates.find((candidate) => statSync4(candidate, { throwIfNoEntry: false })?.isFile()) ?? null;
13915
+ }
13916
+ function windowsOf(entry) {
13917
+ if (entry.lines?.length) return entry.lines.map(([from, to]) => [from, to]);
13918
+ const ranged = (entry.resolvedSymbols ?? []).map((text) => RANGED.exec(text)).filter(Boolean).map(([, from, to]) => [Number(from), Number(to)]);
13919
+ return ranged.length > 0 ? ranged : null;
13920
+ }
13921
+ function planReads({ paths_to_keep: entries = [], project_dir: projectDir }, { cwd }) {
13922
+ const reads = [];
13923
+ const skipped = [];
13924
+ const toPlace = [];
13925
+ for (const entry of entries) {
13926
+ const file = locate(entry.path, cwd, projectDir);
13927
+ if (file === null) {
13928
+ skipped.push({ path: entry.path, reason: "no regular file at this path under the working directory or the project directory" });
13929
+ continue;
13930
+ }
13931
+ const windows = windowsOf(entry);
13932
+ if (windows === null && entry.symbols?.length) toPlace.push({ path: file, names: entry.symbols });
13933
+ for (const [offset, end] of windows ?? [[1, HEAD_LINES]]) {
13934
+ reads.push({ file_path: file, offset, limit: Math.min(end - offset + 1, READ_LINE_CAP), end });
13935
+ }
13936
+ }
13937
+ return { reads, skipped, toPlace };
13938
+ }
13939
+ var textOf2 = (content) => (content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("");
13940
+ function routeOf(agent) {
13941
+ const selection = agent.model.current();
13942
+ return selection ? { provider: selection.provider, model: selection.model } : null;
13943
+ }
13944
+ function ambiguityText(candidates) {
13945
+ const lines = candidates.map(({ load_token: token, created_at: createdAt, next_task_preview: preview }) => `- ${token} (${formatAge(createdAt)})${preview ? ` \u2014 ${preview}` : ""}`);
13946
+ return ["Several handoffs are pending for this project; run /sw-load <token> with one of them:", ...lines].join("\n");
13947
+ }
13948
+ function refusalOf(payload, token) {
13949
+ if (payload.error !== void 0) return `Loading failed: ${payload.error}`;
13950
+ if (payload.ambiguous) return ambiguityText(payload.candidates);
13951
+ if (!payload.found) return `No handoff found${token ? ` for ${token}; it may have expired` : " pending for this project"}`;
13952
+ return null;
13953
+ }
13954
+ var failed = (reason) => ({ failed: { reason } });
13955
+ async function loadHandoffInto({ agent, session, tools, deliver, kit, signal, token, cwdOf }) {
13956
+ const route = routeOf(agent);
13957
+ if (route === null) return failed(NO_ROUTE);
13958
+ const args2 = token ? { load_token: token } : {};
13959
+ let payload;
13960
+ try {
13961
+ payload = await deliver({ agent, signal, args: args2 });
13962
+ } catch (error) {
13963
+ return failed(`Loading failed: ${messageOf2(error)}`);
13964
+ }
13965
+ const refusal = refusalOf(payload, token);
13966
+ if (refusal !== null) return failed(refusal);
13967
+ const plan = planReads(payload, { cwd: cwdOf(session) });
13968
+ const idPrefix = `sw-load-${randomUUID().slice(0, 8)}`;
13969
+ const calls = [{ id: `${idPrefix}-0`, name: "load_handoff", arguments: JSON.stringify(args2), text: JSON.stringify(payload) }];
13970
+ const skipped = [...plan.skipped];
13971
+ const unread = [];
13972
+ const contexts = [];
13973
+ for (const [index, { file_path, offset, limit, end }] of plan.reads.entries()) {
13974
+ const id = `${idPrefix}-${index + 1}`;
13975
+ const readArgs = { file_path, offset, limit };
13976
+ let batch;
13977
+ try {
13978
+ batch = await tools.execute({ calls: [{ type: "tool-call", id, name: "read", arguments: JSON.stringify(readArgs) }], signal, agent });
13979
+ } catch (error) {
13980
+ skipped.push({ path: file_path, reason: messageOf2(error) });
13981
+ continue;
13982
+ }
13983
+ contexts.push(...batch.additionalContexts);
13984
+ const { result } = batch.results[0];
13985
+ if (result.isError) {
13986
+ skipped.push({ path: file_path, reason: result.error.message });
13987
+ continue;
13988
+ }
13989
+ calls.push({ id, name: "read", arguments: JSON.stringify(readArgs), text: textOf2(result.content) });
13990
+ const { lines = [], totalLines = 0 } = result.meta ?? {};
13991
+ const last = lines.at(-1)?.number ?? offset - 1;
13992
+ if (last < end && last < totalLines) unread.push({ path: file_path, range: [last + 1, end] });
13993
+ }
13994
+ let message;
13995
+ try {
13996
+ message = kit.createUserMessage(loadMessageInput({ route, calls }));
13997
+ } catch (error) {
13998
+ return failed(`Loading did not finish: ${messageOf2(error)}`);
13999
+ }
14000
+ const readCalls = calls.slice(1);
14001
+ return {
14002
+ loaded: {
14003
+ token: payload.load_token,
14004
+ reads: readCalls.length,
14005
+ files: new Set(readCalls.map((call) => JSON.parse(call.arguments).file_path)).size,
14006
+ skipped,
14007
+ unread,
14008
+ toPlace: plan.toPlace,
14009
+ skills: payload.skills_to_keep ?? [],
14010
+ empty: (payload.paths_to_keep ?? []).length === 0,
14011
+ message,
14012
+ contexts
14013
+ }
14014
+ };
14015
+ }
14016
+ var quoted = (value) => JSON.stringify(value).replace(/(?<=\s)\//g, "\\/");
14017
+ var lineageStepOf = (listing, closing) => `1. Place the summary in its lineage. \`lineage\` in the payload runs oldest to newest. The sessions the budget left out are collapsed into runs marked \`omitted\`, ahead of the newest sessions' headlines, and the budget may keep none. When the next task or what is already in context needs the headlines of an omitted run, \`lineage_headlines\` with that run's numbers as \`k\` (\`S2-S5\` is \`2-5\`) reads them; read a run for that need only, not by default. The payload's turn page holds the newest turns. From the page, ${listing}. When a headline bears on the next task and the page does not reach that member, call \`turn_page\` with that member's label as \`before\`; a session inside an omitted run is \`S{k}\`, \`k\` being its own number.${closing}`;
14018
+ var presentStep = "3. Present, then hold. Run `git status --short && git log -1 --oneline` once, then write, from the kept paths and that output: the objective, in one line; the working state, each claim the summary makes about the current state set against what the kept paths and the git output show (matches, differs and how, or reaches neither and so unverified); the next task and its entry points, with where the names to place below sit and the turns step 1 named; blockers and risks; the kept paths now in context and the load token. Then stop and wait for the user to confirm or correct it. The next task's first act begins after the reply.";
14019
+ var resumeStep = "3. Resume. Run `git status --short && git log -1 --oneline` once and set each claim the summary makes about the current state against the kept paths and that output; a claim they do not reach counts as a deviation when your next step depends on it. Before your first step on the task, say in one sentence which task you are resuming and your next step, adding a deviation or risk only when it changes that step. Then carry the task on in this turn from the summary and the history, within what it was already authorized to do. A question, approval or permission the task left open still stands: ask it and wait. When a deviation from the summary leaves the task's direction or authorization, or a safe next step, undecided, ask one specific question about it and wait; otherwise carry on.";
14020
+ function loadedText({ token, skipped, unread, toPlace, skills, empty }, { resume = false } = {}) {
14021
+ const summaryOnly = resume ? "when the task calls for it" : "after the user agrees";
14022
+ const skillStep = skills.length > 0 ? `2. Load the kept skills: invoke ${skills.map(quoted).join(", ")} through the skill tool. A skill named only in the summary is invoked ${summaryOnly}.` : `2. The handoff keeps no skills; a skill named only in the summary is invoked through the skill tool ${summaryOnly}.`;
14023
+ const lineageStep = resume ? lineageStepOf("read the turns whose `A:` note bears on the next task", "") : lineageStepOf("list the turns whose `A:` note bears on the next task, by their `S{k}:{T}` address", " That list is what step 3 reports.");
14024
+ const sections = [
14025
+ `Handoff ${quoted(token)} is loaded. The harness has run its delivery, recorded as the \`load_handoff\` call, and the \`read\` calls for the kept ranges, except those listed as skipped below. Their results are in the message the harness placed before this one, in that order and as returned: the delivery's payload, then each read result, which opens with its \`<path>\` line. Do not repeat any of those calls; where a result says part of it was cut or failed, complete it as that result says.`,
14026
+ ["Then:", lineageStep, skillStep, resume ? resumeStep : presentStep].join("\n")
14027
+ ];
14028
+ if (skipped.length > 0) {
14029
+ sections.push(["Skipped, not read:", ...skipped.map(({ path: path3, reason }) => `- ${quoted(path3)}: ${quoted(reason)}`)].join("\n"));
14030
+ }
14031
+ if (unread.length > 0) {
14032
+ sections.push(["Not reached by its read; read the rest of the range:", ...unread.map(({ path: path3, range: [from, to] }) => `- ${quoted(path3)} lines ${from}-${to}`)].join("\n"));
14033
+ }
14034
+ if (toPlace.length > 0) {
14035
+ sections.push(["Names to place with a `grep -n` in the file:", ...toPlace.map(({ path: path3, names }) => `- ${quoted(path3)}: ${names.map(quoted).join(", ")}`)].join("\n"));
14036
+ }
14037
+ if (empty) sections.push(resume ? "The handoff keeps no paths: resume from the summary and the history." : "The handoff keeps no paths: ask the user what they are working on.");
14038
+ return sections.join("\n\n");
14039
+ }
14040
+ function handOver({ agent, loaded, resume }) {
14041
+ agent.inject(loaded.message);
14042
+ for (const context of loaded.contexts) agent.inject(context);
14043
+ agent.followup({
14044
+ id: randomUUID(),
14045
+ role: "user",
14046
+ content: [{ type: "text", text: loadedText(loaded, { resume }) }],
14047
+ source: { kind: "user" }
14048
+ });
14049
+ }
14050
+ var COMMAND_NAME = "sw-load";
14051
+ var COMMAND_DESCRIPTION = "Load a handoff into the session";
14052
+ var COMMAND_INPUT = { hint: "handoff token (optional)" };
14053
+ var USAGE = "Usage: /sw-load [token]";
14054
+ var NOT_IDLE = "/sw-load runs only while the agent is idle.";
14055
+ var failure2 = (text) => ({ kind: "error", text });
14056
+ var success = (text) => ({ kind: "success", text });
14057
+ function createLoadCommand({ deliver, tools, kit, cwdOf }) {
14058
+ async function handler({ agent, rawInput, signal }) {
14059
+ const token = rawInput.trim();
14060
+ if (/\s/.test(token)) return failure2(USAGE);
14061
+ let maintenance;
14062
+ try {
14063
+ maintenance = agent.runMaintenance(() => loadHandoffInto({
14064
+ agent,
14065
+ session: agent.session,
14066
+ tools,
14067
+ deliver,
14068
+ kit,
14069
+ signal,
14070
+ token,
14071
+ cwdOf
14072
+ }));
14073
+ } catch {
14074
+ return failure2(NOT_IDLE);
14075
+ }
14076
+ const outcome = await maintenance;
14077
+ if (outcome.failed) return failure2(outcome.failed.reason);
14078
+ const { loaded } = outcome;
14079
+ handOver({ agent, loaded });
14080
+ return success(`Loaded handoff ${loaded.token}: ${loaded.reads} reads over ${loaded.files} files, ${loaded.skipped.length} skipped.`);
14081
+ }
14082
+ return { name: COMMAND_NAME, description: COMMAND_DESCRIPTION, input: COMMAND_INPUT, handler };
14083
+ }
14084
+
14085
+ // dsh/src/continue.js
13701
14086
  var SUMMARY_PROVIDER = "session-watcher";
13702
14087
  var SUMMARY_MODEL = "sw-continue";
13703
14088
  var ClearError = class extends Error {
@@ -13707,21 +14092,21 @@ var ClearError = class extends Error {
13707
14092
  this.code = code;
13708
14093
  }
13709
14094
  };
13710
- var COMMAND_NAME = "sw-continue";
13711
- var COMMAND_DESCRIPTION = "Clear the session and resume from its last handoff";
13712
- var USAGE = "Usage: /sw-continue (no arguments)";
14095
+ var COMMAND_NAME2 = "sw-continue";
14096
+ var COMMAND_DESCRIPTION2 = "Clear the session and resume from its last handoff";
14097
+ var USAGE2 = "Usage: /sw-continue (no arguments)";
13713
14098
  var NO_HANDOFF = "No handoff has been prepared in this session. Run the sw-handoff skill first.";
13714
14099
  var STALE_HANDOFF = "The last handoff was prepared before the session's latest context reset. Run the sw-handoff skill again.";
13715
- var NOT_IDLE = "/sw-continue runs only while the agent is idle.";
14100
+ var NOT_IDLE2 = "/sw-continue runs only while the agent is idle.";
13716
14101
  var NOT_STARTED = "Clearing could not start; the session history is unchanged.";
13717
14102
  var NOT_FINISHED = "Clearing did not finish cleanly; some history may be shadowed. Inspect the session before retrying.";
13718
14103
  var NOT_SAVED = "Clearing finished, but the session could not be saved.";
13719
14104
  var NOTHING_TO_CLEAR = "No history to clear.";
13720
14105
  var checkpointText = (token) => `[Session Watcher] Context cleared by /sw-continue. Handoff token: ${token}`;
13721
- var followupText = (token) => `Continue from handoff ${token}: load it with the sw-load skill.`;
13722
- var clearedText = ({ count, shadowedTokenCount }, token) => `Cleared ${count} history items (~${shadowedTokenCount} tokens); loading handoff ${token}.`;
14106
+ var clearedText = ({ count, shadowedTokenCount }, token) => `Cleared ${count} history items (~${shadowedTokenCount} tokens); loaded handoff ${token}.`;
14107
+ var notLoadedText = (reason, token) => `Context cleared, but the handoff was not loaded: ${reason}. Run /sw-load ${token}.`;
13723
14108
  var textBlocks = (token) => [{ type: "text", text: checkpointText(token) }];
13724
- var messageOf2 = (error) => error instanceof Error ? error.message : String(error);
14109
+ var messageOf3 = (error) => error instanceof Error ? error.message : String(error);
13725
14110
  function nodesAfterHead(session, meter) {
13726
14111
  const { nodes } = meter.measure(session);
13727
14112
  const first = nodes.length > 0 && session.eventAt(nodes[0].seq).type === "system/message" ? 1 : 0;
@@ -13729,12 +14114,12 @@ function nodesAfterHead(session, meter) {
13729
14114
  }
13730
14115
  function closeWithError(session, lifecycle, cause) {
13731
14116
  try {
13732
- session.append("compaction/end", { ...lifecycle, error: messageOf2(cause) });
14117
+ session.append("compaction/end", { ...lifecycle, error: messageOf3(cause) });
13733
14118
  } catch {
13734
14119
  }
13735
14120
  }
13736
14121
  function clearSurface({ session, meter, kit, commandId, token }) {
13737
- const compactionId = kit.CompactionId(randomUUID());
14122
+ const compactionId = kit.CompactionId(randomUUID2());
13738
14123
  const lifecycle = { compactionId, sourceCommandId: commandId, turn: null };
13739
14124
  let range;
13740
14125
  let checkpoint;
@@ -13748,7 +14133,7 @@ function clearSurface({ session, meter, kit, commandId, token }) {
13748
14133
  });
13749
14134
  startEvent = session.append("compaction/start", lifecycle);
13750
14135
  } catch (cause) {
13751
- throw new ClearError("start", `clearing could not start: ${messageOf2(cause)}`, { cause });
14136
+ throw new ClearError("start", `clearing could not start: ${messageOf3(cause)}`, { cause });
13752
14137
  }
13753
14138
  const shadowedSeqs = range.map((node) => node.seq);
13754
14139
  const shadowedRange = { start: shadowedSeqs[0], end: shadowedSeqs.at(-1) };
@@ -13771,54 +14156,56 @@ function clearSurface({ session, meter, kit, commandId, token }) {
13771
14156
  });
13772
14157
  } catch (cause) {
13773
14158
  closeWithError(session, lifecycle, cause);
13774
- throw new ClearError("commit", `clearing did not finish: ${messageOf2(cause)}`, { cause });
14159
+ throw new ClearError("commit", `clearing did not finish: ${messageOf3(cause)}`, { cause });
13775
14160
  }
13776
14161
  try {
13777
14162
  session.append("compaction/end", lifecycle);
13778
14163
  } catch (cause) {
13779
- throw new ClearError("commit", `clearing did not close: ${messageOf2(cause)}`, { cause });
14164
+ throw new ClearError("commit", `clearing did not close: ${messageOf3(cause)}`, { cause });
13780
14165
  }
13781
14166
  return { count: shadowedSeqs.length, shadowedTokenCount };
13782
14167
  }
13783
- var failure2 = (text) => ({ kind: "error", text });
13784
- var success = (text) => ({ kind: "success", text });
13785
- function createContinueCommand({ table, store, kit, meter, flush }) {
14168
+ var failure3 = (text) => ({ kind: "error", text });
14169
+ var success2 = (text) => ({ kind: "success", text });
14170
+ function createContinueCommand({ table, store, kit, meter, flush, deliver, tools, cwdOf }) {
13786
14171
  async function handler({ commandId, agent, rawInput, signal }) {
13787
- if (rawInput.trim().length > 0) return failure2(USAGE);
14172
+ if (rawInput.trim().length > 0) return failure3(USAGE2);
13788
14173
  const { session } = agent;
13789
14174
  const handoff = store.loadHandoffBySession(session.id);
13790
- if (handoff === null) return failure2(NO_HANDOFF);
14175
+ if (handoff === null) return failure3(NO_HANDOFF);
13791
14176
  const { watcher } = await table.waitLive(session.id, signal);
13792
- if (handoff.segment !== watcher.getStatus().segment) return failure2(STALE_HANDOFF);
14177
+ if (handoff.segment !== watcher.getStatus().segment) return failure3(STALE_HANDOFF);
13793
14178
  const token = handoff.loadToken;
13794
14179
  let maintenance;
13795
14180
  try {
13796
14181
  maintenance = agent.runMaintenance(async () => {
13797
14182
  const cleared = clearSurface({ session, meter, kit, commandId, token });
13798
14183
  if (cleared === null) return { status: "empty" };
14184
+ const load = await loadHandoffInto({ agent, session, tools, deliver, kit, signal, token, cwdOf });
13799
14185
  try {
13800
14186
  await flush(session);
13801
14187
  } catch {
13802
14188
  return { status: "unsaved" };
13803
14189
  }
13804
- return { status: "cleared", cleared };
14190
+ return { status: "cleared", cleared, load };
13805
14191
  });
13806
14192
  } catch {
13807
- return failure2(NOT_IDLE);
14193
+ return failure3(NOT_IDLE2);
13808
14194
  }
13809
14195
  let outcome;
13810
14196
  try {
13811
14197
  outcome = await maintenance;
13812
14198
  } catch (error) {
13813
- if (error instanceof ClearError) return failure2(error.code === "start" ? NOT_STARTED : NOT_FINISHED);
14199
+ if (error instanceof ClearError) return failure3(error.code === "start" ? NOT_STARTED : NOT_FINISHED);
13814
14200
  throw error;
13815
14201
  }
13816
- if (outcome.status === "empty") return success(NOTHING_TO_CLEAR);
13817
- if (outcome.status === "unsaved") return failure2(NOT_SAVED);
13818
- agent.followup(kit.createUserMessage({ content: [{ type: "text", text: followupText(token) }], source: { kind: "user" } }));
13819
- return success(clearedText(outcome.cleared, token));
14202
+ if (outcome.status === "empty") return success2(NOTHING_TO_CLEAR);
14203
+ if (outcome.status === "unsaved") return failure3(NOT_SAVED);
14204
+ if (outcome.load.failed) return failure3(notLoadedText(outcome.load.failed.reason, token));
14205
+ handOver({ agent, loaded: outcome.load.loaded, resume: true });
14206
+ return success2(clearedText(outcome.cleared, token));
13820
14207
  }
13821
- return { name: COMMAND_NAME, description: COMMAND_DESCRIPTION, handler };
14208
+ return { name: COMMAND_NAME2, description: COMMAND_DESCRIPTION2, handler };
13822
14209
  }
13823
14210
 
13824
14211
  // dsh/src/skills.js
@@ -13849,100 +14236,9 @@ function registerSkills(ctx, { skillsDir }) {
13849
14236
  }
13850
14237
  }
13851
14238
 
13852
- // dsh/src/catalog.js
13853
- import { randomUUID as randomUUID2 } from "node:crypto";
13854
-
13855
- // lib/handoff-discovery.js
13856
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
13857
- function discoverHandoffs(dbPath, projectId, sessionId, { ttlDays, queryLimit }) {
13858
- if (!projectId || !sessionId) return [];
13859
- let db;
13860
- try {
13861
- db = new DatabaseSync2(dbPath, { readOnly: true });
13862
- const tableCheck = db.prepare(
13863
- "SELECT name FROM sqlite_master WHERE type='table' AND name='handoff'"
13864
- ).get();
13865
- if (!tableCheck) return [];
13866
- const cutoff = Date.now() - ttlDays * 24 * 3600 * 1e3;
13867
- const stmt = db.prepare(`SELECT load_token, next_task, created_at, summary_tokens, kept_tokens
13868
- FROM handoff
13869
- WHERE project_id = ? AND delivered_at IS NULL AND session_id <> ? AND created_at > ?
13870
- ORDER BY created_at DESC LIMIT ?`);
13871
- return stmt.all(projectId, sessionId, cutoff, queryLimit);
13872
- } catch {
13873
- return [];
13874
- } finally {
13875
- try {
13876
- if (db) db.close();
13877
- } catch {
13878
- }
13879
- }
13880
- }
13881
- function formatHandoffContext(rows, maxDisplay, taskPreviewChars) {
13882
- if (!rows || rows.length === 0) return null;
13883
- const hasMore = rows.length > maxDisplay;
13884
- const display = rows.slice(0, maxDisplay);
13885
- const formatTokens = (summaryTok, keptTok) => {
13886
- const total = (summaryTok || 0) + (keptTok || 0);
13887
- if (total === 0) return null;
13888
- if (total >= 1e3) return `~${Math.round(total / 1e3)}k tokens`;
13889
- return `~${total} tokens`;
13890
- };
13891
- const formatAge = (createdAt) => {
13892
- const diffMs = Math.max(0, Date.now() - createdAt);
13893
- const mins = Math.floor(diffMs / 6e4);
13894
- if (mins < 60) return `${mins} min ago`;
13895
- const hours = Math.floor(mins / 60);
13896
- if (hours < 24) return `${hours}h ago`;
13897
- const days = Math.floor(hours / 24);
13898
- return `${days}d ago`;
13899
- };
13900
- const truncTask = (task) => {
13901
- if (!task) return "";
13902
- if (task.length <= taskPreviewChars) return task;
13903
- return task.slice(0, taskPreviewChars - 3) + "...";
13904
- };
13905
- if (display.length === 1) {
13906
- const r = display[0];
13907
- const age = formatAge(r.created_at);
13908
- const tokens = formatTokens(r.summary_tokens, r.kept_tokens);
13909
- const tokStr = tokens ? `, ${tokens} to restore` : "";
13910
- const taskLine = r.next_task ? `
13911
- Task: ${truncTask(r.next_task)}` : "";
13912
- return `[Session Watcher] Handoff available (token: ${r.load_token}, ${age}${tokStr}).${taskLine}`;
13913
- }
13914
- const header = hasMore ? `[Session Watcher] ${maxDisplay}+ pending handoffs (showing newest ${maxDisplay}):` : `[Session Watcher] ${display.length} pending handoffs for this project:`;
13915
- const lines = display.map((r, i2) => {
13916
- const age = formatAge(r.created_at);
13917
- const tokens = formatTokens(r.summary_tokens, r.kept_tokens);
13918
- const tokStr = tokens ? `, ${tokens}` : "";
13919
- const task = truncTask(r.next_task);
13920
- const taskStr = task ? ` \u2014 ${task}` : "";
13921
- return `${i2 + 1}. ${r.load_token} (${age}${tokStr})${taskStr}`;
13922
- });
13923
- const footer = hasMore ? "(older handoffs available \u2014 use load_handoff with a query to search)" : "";
13924
- return [header, ...lines, footer].join("\n");
13925
- }
13926
-
13927
- // dsh/src/catalog.js
13928
- function catalogMessageFor({ dbPath, projectId, sessionId }) {
13929
- const rows = discoverHandoffs(dbPath, projectId, sessionId, {
13930
- ttlDays: HANDOFF_HOOK_TTL_DAYS,
13931
- queryLimit: HANDOFF_HOOK_QUERY_LIMIT
13932
- });
13933
- const text = formatHandoffContext(rows, HANDOFF_HOOK_MAX_DISPLAY, HANDOFF_HOOK_TASK_PREVIEW_CHARS);
13934
- if (text === null) return null;
13935
- return {
13936
- id: randomUUID2(),
13937
- role: "user",
13938
- content: [{ type: "text", text }],
13939
- source: { kind: "session-watcher", form: "catalog" }
13940
- };
13941
- }
13942
-
13943
14239
  // dsh/src/host.js
13944
14240
  var HOST_INJECT = ["sessions", "sessionQuery", "tools", "skills", "llm"];
13945
- function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, continueKit }) {
14241
+ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, commandKit }) {
13946
14242
  initStore(storePath);
13947
14243
  ctx.effect(() => () => {
13948
14244
  try {
@@ -13994,36 +14290,37 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
13994
14290
  table.feed(session.id, event);
13995
14291
  }));
13996
14292
  ctx.on("session/disposed", (session) => guarded(session.id, () => table.dispose(session.id)));
13997
- ctx.on("agent/created", ({ agent, source }) => guarded(agent.session.id, () => {
13998
- if (source !== "startup" && source !== "resume") return;
13999
- if (agent.session.header.origin === "subagent") return;
14000
- const message = catalogMessageFor({
14001
- dbPath: storePath,
14002
- projectId: resolveProjectKey({ cwd: agent.session.header.cwd }),
14003
- sessionId: agent.session.id
14004
- });
14005
- if (message !== null) agent.inject(message);
14006
- }));
14007
14293
  const sessionTitle = () => ctx.get("sessionTitle");
14008
- for (const definition of createTools({ defineTool: defineTool2, table, store: getStore(), resolvePersisted, sessionTitle })) ctx.tools.register(definition);
14294
+ for (const definition of createTools({ defineTool: defineTool2, table, store: getStore(), resolvePersisted })) ctx.tools.register(definition);
14295
+ const deliver = createHandoffDelivery({ table, store: getStore(), sessionTitle });
14009
14296
  registerSkills(ctx, { skillsDir });
14010
- ctx.inject(["commands", "tokenMeter"], (child) => {
14297
+ ctx.inject(["commands", "tokenMeter", "workingDirectory"], (child) => {
14011
14298
  child.commands.register(createContinueCommand({
14012
14299
  table,
14013
14300
  store: getStore(),
14014
- kit: continueKit,
14301
+ kit: commandKit,
14015
14302
  meter: child.tokenMeter,
14016
- flush: (session) => ctx.sessions.flush(session)
14303
+ flush: (session) => ctx.sessions.flush(session),
14304
+ deliver,
14305
+ tools: ctx.tools,
14306
+ cwdOf: (session) => child.workingDirectory.get(session)
14307
+ }));
14308
+ });
14309
+ ctx.inject(["commands", "workingDirectory"], (child) => {
14310
+ child.commands.register(createLoadCommand({
14311
+ deliver,
14312
+ tools: ctx.tools,
14313
+ kit: commandKit,
14314
+ cwdOf: (session) => child.workingDirectory.get(session)
14017
14315
  }));
14018
14316
  });
14019
- ctx.inject(["connection"], (child) => {
14020
- const remove = child.root.get("connection").rpc.handle("/session-watcher", createRpcHandler({
14317
+ ctx.inject(["connection", "webServer"], (child) => {
14318
+ child.extend({ webServer: child.webServer }).connection.rpc.handle("/session-watcher", createRpcHandler({
14021
14319
  table,
14022
14320
  store: getStore(),
14023
14321
  publish: hub.publish,
14024
14322
  resolvePersisted
14025
14323
  }));
14026
- child.effect(() => remove);
14027
14324
  child.connection.fetch.register(hub.route());
14028
14325
  child.effect(() => () => hub.closeAll());
14029
14326
  });
@@ -14050,7 +14347,7 @@ var inject = HOST_INJECT;
14050
14347
  function apply(ctx) {
14051
14348
  applyHost(ctx, {
14052
14349
  defineTool,
14053
- continueKit: { CompactionId, compactCheckpointSource, createUserMessage },
14350
+ commandKit: { CompactionId, compactCheckpointSource, createUserMessage },
14054
14351
  storePath: defaultDbPath(),
14055
14352
  turnNotesRoot: DSH_TURN_NOTES_ROOT,
14056
14353
  loadIsIgnored,