osborn 0.9.290 → 0.9.292

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 (86) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +5 -4
  2. package/.claude/skills/browser-apply/candidate.example.env +4 -1
  3. package/.claude/skills/browser-apply/fill.mjs +13 -2
  4. package/.claude/skills/meetings/SKILL.md +26 -7
  5. package/.env.example +6 -0
  6. package/dist/agent-store.d.ts +6 -0
  7. package/dist/agent-store.js +36 -6
  8. package/dist/approval-policy.d.ts +99 -0
  9. package/dist/approval-policy.js +196 -0
  10. package/dist/claude-llm.d.ts +6 -2
  11. package/dist/claude-llm.js +68 -20
  12. package/dist/config.d.ts +12 -16
  13. package/dist/config.js +75 -21
  14. package/dist/content/compaction-lens-worker.d.ts +5 -0
  15. package/dist/content/compaction-lens-worker.js +78 -7
  16. package/dist/content/content-llm.d.ts +14 -3
  17. package/dist/content/content-llm.js +33 -142
  18. package/dist/content/lens-db.d.ts +16 -5
  19. package/dist/content/lens-db.js +58 -11
  20. package/dist/content/lens-ingest.d.ts +1 -0
  21. package/dist/content/lens-ingest.js +1 -1
  22. package/dist/content/lens-launch.d.ts +42 -1
  23. package/dist/content/lens-launch.js +202 -40
  24. package/dist/content/lens-library-digest.d.ts +85 -0
  25. package/dist/content/lens-library-digest.js +305 -0
  26. package/dist/content/lens-library-index.d.ts +14 -3
  27. package/dist/content/lens-library-index.js +35 -8
  28. package/dist/content/lens-library-select.d.ts +1 -1
  29. package/dist/content/lens-library-select.js +1 -1
  30. package/dist/content/lens-library-sweep.d.ts +36 -0
  31. package/dist/content/lens-library-sweep.js +331 -0
  32. package/dist/content/lens-library.d.ts +29 -0
  33. package/dist/content/lens-library.js +130 -20
  34. package/dist/content/lens-model.d.ts +4 -0
  35. package/dist/content/lens-model.js +5 -0
  36. package/dist/content/lens-paths.d.ts +72 -0
  37. package/dist/content/lens-paths.js +248 -5
  38. package/dist/content/period-run.js +2 -2
  39. package/dist/content/secret-rules.d.ts +51 -0
  40. package/dist/content/secret-rules.js +185 -0
  41. package/dist/content/transcript-sanitizer.d.ts +1 -41
  42. package/dist/content/transcript-sanitizer.js +4 -171
  43. package/dist/data-sender-auth.d.ts +112 -3
  44. package/dist/data-sender-auth.js +165 -39
  45. package/dist/env-keys.d.ts +10 -2
  46. package/dist/env-keys.js +26 -5
  47. package/dist/index.js +616 -109
  48. package/dist/phone-code.d.ts +76 -0
  49. package/dist/phone-code.js +124 -0
  50. package/dist/phone-voice-actions.d.ts +132 -0
  51. package/dist/phone-voice-actions.js +223 -0
  52. package/dist/pipeline-direct-llm.d.ts +8 -1
  53. package/dist/pipeline-direct-llm.js +13 -1
  54. package/dist/prompts/library-digest.md +11 -0
  55. package/dist/prompts.d.ts +4 -0
  56. package/dist/prompts.js +6 -2
  57. package/dist/pushover.d.ts +2 -1
  58. package/dist/pushover.js +7 -6
  59. package/dist/risk-tier.d.ts +14 -0
  60. package/dist/risk-tier.js +140 -0
  61. package/dist/session-store.d.ts +1 -0
  62. package/dist/session-store.js +3 -2
  63. package/dist/session-switch.d.ts +22 -7
  64. package/dist/session-switch.js +58 -24
  65. package/dist/steward-verdict.d.ts +16 -3
  66. package/dist/steward-verdict.js +37 -18
  67. package/dist/watch-gateway.js +3 -1
  68. package/package.json +1 -1
  69. package/dist/bridge-llm.d.ts +0 -22
  70. package/dist/bridge-llm.js +0 -39
  71. package/dist/codex-handler.d.ts +0 -38
  72. package/dist/codex-handler.js +0 -83
  73. package/dist/codex-llm.d.ts +0 -40
  74. package/dist/codex-llm.js +0 -144
  75. package/dist/fast-brain.d.ts +0 -176
  76. package/dist/fast-brain.js +0 -1887
  77. package/dist/index-3-2-26-legacy.d.ts +0 -1
  78. package/dist/index-3-2-26-legacy.js +0 -2233
  79. package/dist/leagcyprompts2.d.ts +0 -0
  80. package/dist/leagcyprompts2.js +0 -573
  81. package/dist/prompts-2-25-26.d.ts +0 -0
  82. package/dist/prompts-2-25-26.js +0 -518
  83. package/dist/prompts-3-2-26.d.ts +0 -78
  84. package/dist/prompts-3-2-26.js +0 -1319
  85. package/dist/summary-index.d.ts +0 -90
  86. package/dist/summary-index.js +0 -585
@@ -9,10 +9,14 @@
9
9
  * OSBORN_CONTENT_DAILY_USD default 2.00 (UTC day, per MACHINE: $OSBORN_HOME or ~/.osborn/content-spend-ledger.json,
10
10
  * locked read-modify-write so concurrent workers across projects share one cap)
11
11
  * OSBORN_CONTENT_MAX_PIECES default 4 (1 highlight + up to 3 how-tos)
12
+ * OSBORN_LIBRARY_DAILY_USD default 1.00 (UTC day, per MACHINE): the Library catch-up sweep's own cap
13
+ * (period pages + daily digests), kept in the same ledger file under its
14
+ * own key ("<day>:library"), so the sweep never uses the content step's cap
12
15
  * Every call reserves its WORST case (prompt + max output) against both caps up
13
16
  * front and writes it to the ledger before the fetch; it is reconciled to the
14
17
  * actual cost after. A failed call is charged the worst case, and a hard exit
15
- * mid-call leaves the worst case in the ledger, so the caps stay hard.
18
+ * mid-call leaves the worst case in the ledger, so the caps stay hard; such an
19
+ * unsettled reservation expires with its UTC day (the ledger is keyed by day).
16
20
  * All outbound prompt text goes through the caller's scrub() first.
17
21
  */
18
22
  export declare const LEDGER_FILE = "content-spend-ledger.json";
@@ -50,7 +54,10 @@ interface Ledger {
50
54
  /** The machine ledger (UTC day → USD). */
51
55
  export declare function readLedger(): Ledger;
52
56
  /** Spend recorded (incl. open reservations) on this machine today, across every project. */
53
- export declare function daySpent(now?: number): number;
57
+ export declare function daySpent(now?: number, scope?: string): number;
58
+ /** The Library sweep's own daily cap (OSBORN_LIBRARY_DAILY_USD, default $1), on ledger scope LIBRARY_LEDGER_SCOPE. */
59
+ export declare const LIBRARY_LEDGER_SCOPE = "library";
60
+ export declare const libraryDailyUsd: () => number;
54
61
  export type CapKind = 'period' | 'day' | 'time';
55
62
  export declare class CapError extends Error {
56
63
  readonly cap: CapKind;
@@ -77,6 +84,8 @@ export declare class SpendGuard {
77
84
  periodUsd: number;
78
85
  /** Epoch ms after which reserve() refuses new calls (CapError 'time'). */
79
86
  readonly deadline: number | null;
87
+ /** Ledger key scope: none = the content step's daily cap; e.g. LIBRARY_LEDGER_SCOPE for the sweep. */
88
+ readonly scope?: string;
80
89
  runUsd: number;
81
90
  calls: number;
82
91
  capHit: CapKind | null;
@@ -86,7 +95,9 @@ export declare class SpendGuard {
86
95
  /** Spend already recorded for this period by earlier runs. */
87
96
  periodUsd?: number,
88
97
  /** Epoch ms after which reserve() refuses new calls (CapError 'time'). */
89
- deadline?: number | null);
98
+ deadline?: number | null,
99
+ /** Ledger key scope: none = the content step's daily cap; e.g. LIBRARY_LEDGER_SCOPE for the sweep. */
100
+ scope?: string);
90
101
  /**
91
102
  * Reserve a worst-case spend of `usd`: throws CapError if it would cross a cap
92
103
  * (or the deadline passed); otherwise writes it to the machine ledger BEFORE the
@@ -9,17 +9,21 @@
9
9
  * OSBORN_CONTENT_DAILY_USD default 2.00 (UTC day, per MACHINE: $OSBORN_HOME or ~/.osborn/content-spend-ledger.json,
10
10
  * locked read-modify-write so concurrent workers across projects share one cap)
11
11
  * OSBORN_CONTENT_MAX_PIECES default 4 (1 highlight + up to 3 how-tos)
12
+ * OSBORN_LIBRARY_DAILY_USD default 1.00 (UTC day, per MACHINE): the Library catch-up sweep's own cap
13
+ * (period pages + daily digests), kept in the same ledger file under its
14
+ * own key ("<day>:library"), so the sweep never uses the content step's cap
12
15
  * Every call reserves its WORST case (prompt + max output) against both caps up
13
16
  * front and writes it to the ledger before the fetch; it is reconciled to the
14
17
  * actual cost after. A failed call is charged the worst case, and a hard exit
15
- * mid-call leaves the worst case in the ledger, so the caps stay hard.
18
+ * mid-call leaves the worst case in the ledger, so the caps stay hard; such an
19
+ * unsettled reservation expires with its UTC day (the ledger is keyed by day).
16
20
  * All outbound prompt text goes through the caller's scrub() first.
17
21
  */
18
- import { closeSync, fstatSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
19
- import { randomBytes } from 'node:crypto';
22
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
20
23
  import { homedir } from 'node:os';
21
24
  import { join } from 'node:path';
22
25
  import { isContentLensEnabled } from './lens-launch.js';
26
+ import { withFileLock } from './lens-paths.js';
23
27
  const OPENROUTER = 'https://openrouter.ai/api/v1';
24
28
  const OFF = ['0', 'off', 'false', 'no'];
25
29
  export const LEDGER_FILE = 'content-spend-ledger.json';
@@ -88,153 +92,36 @@ export function readLedger() {
88
92
  return readLedgerAt(ledgerPath());
89
93
  }
90
94
  /** Spend recorded (incl. open reservations) on this machine today, across every project. */
91
- export function daySpent(now = Date.now()) {
92
- return Number(readLedger().days[today(now)]) || 0;
95
+ export function daySpent(now = Date.now(), scope) {
96
+ return Number(readLedger().days[ledgerKey(today(now), scope)]) || 0;
93
97
  }
94
- const LOCK_STALE_MS = 30_000;
98
+ /** The ledger key of a day: the content step's is the bare day; another spender's is "<day>:<scope>" (pruned with its day). */
99
+ const ledgerKey = (day, scope) => (scope ? `${day}:${scope}` : day);
100
+ /** The Library sweep's own daily cap (OSBORN_LIBRARY_DAILY_USD, default $1), on ledger scope LIBRARY_LEDGER_SCOPE. */
101
+ export const LIBRARY_LEDGER_SCOPE = 'library';
102
+ export const libraryDailyUsd = () => envNum('OSBORN_LIBRARY_DAILY_USD', 1.0);
95
103
  const LOCK_TRIES = 40;
96
- const LOCK_WAIT_MS = 50;
97
- const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
98
- const lockToken = () => `${process.pid}.${randomBytes(8).toString('hex')}`;
99
104
  /**
100
- * Remove `path` if it is stale: rename it to a unique name (only ONE caller's
101
- * rename can succeed), check the renamed file is the same stale file we judged
102
- * (inode, mtime, content), and put it back with link() if a fresh one was
103
- * swapped in (link fails rather than clobbers). True only to the caller that
104
- * removed a stale file; any error = keep waiting.
105
- */
106
- function removeIfStale(path) {
107
- let seen;
108
- try {
109
- const fd = openSync(path, 'r');
110
- try {
111
- const st = fstatSync(fd);
112
- if (Date.now() - st.mtimeMs <= LOCK_STALE_MS)
113
- return false;
114
- seen = { ino: st.ino, mtimeMs: st.mtimeMs, body: readFileSync(fd, 'utf-8') };
115
- }
116
- finally {
117
- closeSync(fd);
118
- }
119
- }
120
- catch {
121
- return false; // vanished between calls
122
- }
123
- const claimed = `${path}.stale.${process.pid}.${randomBytes(6).toString('hex')}`;
124
- try {
125
- renameSync(path, claimed);
126
- }
127
- catch {
128
- return false; // another caller claimed it first
129
- }
130
- let same = false;
131
- try {
132
- const st = statSync(claimed);
133
- same = st.ino === seen.ino && st.mtimeMs === seen.mtimeMs && readFileSync(claimed, 'utf-8') === seen.body;
134
- }
135
- catch {
136
- /* treat as not ours */
137
- }
138
- if (!same) {
139
- try {
140
- linkSync(claimed, path); // a live file was swapped in: restore it
141
- }
142
- catch {
143
- /* a newer one already exists */
144
- }
145
- }
146
- try {
147
- unlinkSync(claimed);
148
- }
149
- catch {
150
- /* already gone */
151
- }
152
- return same;
153
- }
154
- /**
155
- * Claim a stale ledger lock. The judge-then-rename step runs under a short
156
- * `<lock>.reap` guard so two waiters can never both act on one stale lock (or
157
- * rename away the fresh lock the other just created). A guard left by a crash
158
- * goes stale too and is removed the same way.
159
- */
160
- function claimStaleLock(lock) {
161
- const guard = `${lock}.reap`;
162
- let g;
163
- try {
164
- g = openSync(guard, 'wx');
165
- }
166
- catch {
167
- removeIfStale(guard);
168
- return false;
169
- }
170
- const token = lockToken();
171
- try {
172
- writeSync(g, token);
173
- return removeIfStale(lock);
174
- }
175
- catch {
176
- return false;
177
- }
178
- finally {
179
- closeSync(g);
180
- releaseLock(guard, token);
181
- }
182
- }
183
- /** Release only a lock this holder owns (its token is still in the file). */
184
- function releaseLock(lock, token) {
185
- try {
186
- if (readFileSync(lock, 'utf-8') === token)
187
- unlinkSync(lock);
188
- }
189
- catch {
190
- /* already gone */
191
- }
192
- }
193
- /**
194
- * Atomic read-modify-write of the machine ledger under a short `wx` lock file
195
- * holding a unique token (stale after 30s, claimed via rename so only one waiter
196
- * can remove it). `fn` returns the new ledger, or null to leave it unchanged.
105
+ * Atomic read-modify-write of the machine ledger under its lock file (withFileLock in
106
+ * lens-paths.ts). `fn` returns the new ledger, or null to leave it unchanged.
197
107
  * Returns false when the lock could not be taken (callers decide fail-closed vs best-effort).
198
108
  */
199
109
  function withLedger(fn, tries = LOCK_TRIES) {
200
110
  const dir = ledgerDir();
201
111
  mkdirSync(dir, { recursive: true });
202
112
  const path = join(dir, LEDGER_FILE);
203
- const lock = `${path}.lock`;
204
- for (let i = 0; i < tries; i++) {
205
- let fd;
206
- try {
207
- fd = openSync(lock, 'wx');
208
- }
209
- catch (e) {
210
- if (e?.code !== 'EEXIST')
211
- throw e;
212
- if (claimStaleLock(lock))
213
- continue; // we removed the stale lock: retry the wx create now
214
- sleepSync(LOCK_WAIT_MS);
215
- continue;
113
+ return withFileLock(`${path}.lock`, () => {
114
+ const next = fn(readLedgerAt(path));
115
+ if (next) {
116
+ const cutoff = today(Date.now() - 14 * 86_400_000);
117
+ for (const k of Object.keys(next.days))
118
+ if (k < cutoff)
119
+ delete next.days[k];
120
+ const tmp = `${path}.${process.pid}.tmp`;
121
+ writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', 'utf-8');
122
+ renameSync(tmp, path);
216
123
  }
217
- const token = lockToken();
218
- try {
219
- writeSync(fd, token);
220
- const next = fn(readLedgerAt(path));
221
- if (next) {
222
- const cutoff = today(Date.now() - 14 * 86_400_000);
223
- for (const k of Object.keys(next.days))
224
- if (k < cutoff)
225
- delete next.days[k];
226
- const tmp = `${path}.${process.pid}.tmp`;
227
- writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', 'utf-8');
228
- renameSync(tmp, path);
229
- }
230
- return true;
231
- }
232
- finally {
233
- closeSync(fd);
234
- releaseLock(lock, token);
235
- }
236
- }
237
- return false;
124
+ }, tries);
238
125
  }
239
126
  export class CapError extends Error {
240
127
  cap;
@@ -255,6 +142,7 @@ export class SpendGuard {
255
142
  caps;
256
143
  periodUsd;
257
144
  deadline;
145
+ scope;
258
146
  runUsd = 0;
259
147
  calls = 0;
260
148
  capHit = null;
@@ -264,11 +152,14 @@ export class SpendGuard {
264
152
  /** Spend already recorded for this period by earlier runs. */
265
153
  periodUsd = 0,
266
154
  /** Epoch ms after which reserve() refuses new calls (CapError 'time'). */
267
- deadline = null) {
155
+ deadline = null,
156
+ /** Ledger key scope: none = the content step's daily cap; e.g. LIBRARY_LEDGER_SCOPE for the sweep. */
157
+ scope) {
268
158
  this.projectDir = projectDir;
269
159
  this.caps = caps;
270
160
  this.periodUsd = periodUsd;
271
161
  this.deadline = deadline;
162
+ this.scope = scope;
272
163
  }
273
164
  /**
274
165
  * Reserve a worst-case spend of `usd`: throws CapError if it would cross a cap
@@ -281,7 +172,7 @@ export class SpendGuard {
281
172
  throw this.hit('time', usd);
282
173
  if (this.periodUsd + usd > this.caps.periodUsd)
283
174
  throw this.hit('period', usd);
284
- const day = today();
175
+ const day = ledgerKey(today(), this.scope);
285
176
  let over = false;
286
177
  let locked;
287
178
  try {
@@ -42,13 +42,24 @@ export interface DbLoad {
42
42
  };
43
43
  }
44
44
  export declare const CHARS_PER_TOKEN = 4;
45
- /**
46
- * Resolve session.db for a session id: <projectDir>/osb/<sid>/session.db, then
47
- * the cwd slug, then a scan of every project's osb dir (same layout as
48
- * session-store.ts getStorePath / recall-cli listStores).
49
- */
50
45
  export declare function resolveSessionDb(sessionId: string, projectDir?: string | null, cwd?: string): string | null;
46
+ export interface SessionStore {
47
+ sessionId: string;
48
+ db: string;
49
+ projectDir: string;
50
+ }
51
+ /** Every session store on this machine (the Library catch-up sweep). */
52
+ export declare function listSessionDbs(): SessionStore[];
51
53
  export declare function includeSubagents(): boolean;
54
+ /**
55
+ * Ids and timestamps of the same conversation rows loadConversationRows reads (same source and
56
+ * msg_type filter), with no blob read, decompression or sanitising: what segmentation needs.
57
+ * Rows the sanitizer would drop are kept, so a stamp may have no text behind it.
58
+ */
59
+ export declare function loadRowStamps(dbPath: string): {
60
+ id: number;
61
+ timestamp: string;
62
+ }[];
52
63
  /**
53
64
  * Read conversation rows with id > afterRowId, in id order, sanitized.
54
65
  * Throws if the DB can't be opened (caller logs + exits).
@@ -37,24 +37,26 @@ const MAX_RECORD_VIEW_CHARS = 20_000;
37
37
  * the cwd slug, then a scan of every project's osb dir (same layout as
38
38
  * session-store.ts getStorePath / recall-cli listStores).
39
39
  */
40
+ /** <projectDir>/osb/<sessionId>/session.db when it exists and is not empty. */
41
+ function storeIn(projectDir, sessionId) {
42
+ const p = join(projectDir, 'osb', sessionId, 'session.db');
43
+ return existsSync(p) && statSync(p).size > 0 ? p : null;
44
+ }
40
45
  export function resolveSessionDb(sessionId, projectDir, cwd) {
41
46
  if (!sessionId || !SID_RE.test(sessionId))
42
47
  return null;
43
- const candidates = [];
44
- if (projectDir)
45
- candidates.push(join(projectDir, 'osb', sessionId, 'session.db'));
46
- if (cwd)
47
- candidates.push(join(slugDir(cwd), 'osb', sessionId, 'session.db'));
48
- for (const p of candidates)
49
- if (existsSync(p) && statSync(p).size > 0)
48
+ for (const pd of [projectDir, cwd ? slugDir(cwd) : null]) {
49
+ const p = pd ? storeIn(pd, sessionId) : null;
50
+ if (p)
50
51
  return p;
52
+ }
51
53
  const root = join(claudeDir(), 'projects');
52
54
  try {
53
55
  for (const ent of readdirSync(root, { withFileTypes: true })) {
54
56
  if (!ent.isDirectory())
55
57
  continue;
56
- const p = join(root, ent.name, 'osb', sessionId, 'session.db');
57
- if (existsSync(p) && statSync(p).size > 0)
58
+ const p = storeIn(join(root, ent.name), sessionId);
59
+ if (p)
58
60
  return p;
59
61
  }
60
62
  }
@@ -63,9 +65,55 @@ export function resolveSessionDb(sessionId, projectDir, cwd) {
63
65
  }
64
66
  return null;
65
67
  }
68
+ /** Every session store on this machine (the Library catch-up sweep). */
69
+ export function listSessionDbs() {
70
+ const out = [];
71
+ const root = join(claudeDir(), 'projects');
72
+ try {
73
+ for (const p of readdirSync(root, { withFileTypes: true })) {
74
+ if (!p.isDirectory())
75
+ continue;
76
+ const projectDir = join(root, p.name);
77
+ let ents = [];
78
+ try {
79
+ ents = readdirSync(join(projectDir, 'osb'), { withFileTypes: true });
80
+ }
81
+ catch {
82
+ continue;
83
+ }
84
+ for (const s of ents) {
85
+ const db = s.isDirectory() ? storeIn(projectDir, s.name) : null;
86
+ if (db)
87
+ out.push({ sessionId: s.name, db, projectDir });
88
+ }
89
+ }
90
+ }
91
+ catch {
92
+ /* no projects dir */
93
+ }
94
+ return out;
95
+ }
66
96
  export function includeSubagents() {
67
97
  return ['1', 'true', 'yes', 'on'].includes((process.env.OSBORN_LENS_INCLUDE_SUBAGENTS ?? '').trim().toLowerCase());
68
98
  }
99
+ /** The conversation-row filter both readers share: user/assistant rows, main thread unless subagents are included. */
100
+ const conversationRows = () => `msg_type IN ('user', 'assistant')${includeSubagents() ? '' : ` AND source = 'main'`}`;
101
+ /**
102
+ * Ids and timestamps of the same conversation rows loadConversationRows reads (same source and
103
+ * msg_type filter), with no blob read, decompression or sanitising: what segmentation needs.
104
+ * Rows the sanitizer would drop are kept, so a stamp may have no text behind it.
105
+ */
106
+ export function loadRowStamps(dbPath) {
107
+ const db = new Database(dbPath, { readonly: true, fileMustExist: true });
108
+ try {
109
+ db.pragma('busy_timeout = 5000');
110
+ const rows = db.prepare(`SELECT id, ts FROM content WHERE ${conversationRows()} ORDER BY id`).all();
111
+ return rows.map(r => ({ id: r.id, timestamp: r.ts ?? '' }));
112
+ }
113
+ finally {
114
+ db.close();
115
+ }
116
+ }
69
117
  /**
70
118
  * Read conversation rows with id > afterRowId, in id order, sanitized.
71
119
  * Throws if the DB can't be opened (caller logs + exits).
@@ -74,10 +122,9 @@ export function loadConversationRows(dbPath, afterRowId = 0, clientRedact, throu
74
122
  const db = new Database(dbPath, { readonly: true, fileMustExist: true });
75
123
  try {
76
124
  db.pragma('busy_timeout = 5000');
77
- const where = includeSubagents() ? '' : `AND source = 'main'`;
78
125
  const upper = Number.isFinite(throughRowId) ? `AND id <= ${Math.floor(throughRowId)}` : '';
79
126
  const stmt = db.prepare(`SELECT id, ts, msg_type, blob FROM content
80
- WHERE id > ? ${upper} AND msg_type IN ('user', 'assistant') ${where}
127
+ WHERE id > ? ${upper} AND ${conversationRows()}
81
128
  ORDER BY id`);
82
129
  const out = { dbPath, records: [], maxRowId: afterRowId, stats: { rowsRead: 0, dropped: 0, unwrapped: 0, chars: 0, stripped: {} } };
83
130
  for (const row of stmt.iterate(afterRowId)) {
@@ -59,6 +59,7 @@ export type IngestConfig = {
59
59
  };
60
60
  export declare function resolveIngestConfig(): IngestConfig;
61
61
  export declare function contentHashFor(p: Pick<IngestPage, 'sessionId' | 'startRowId' | 'markdown'>): string;
62
+ export declare const clip: (s: string, n: number) => string;
62
63
  /** Map a page to the content_ingest payload. Never includes status/published_at/owner. */
63
64
  export declare function buildIngestPayload(p: IngestPage, scrub?: (s: string) => string): Record<string, unknown>;
64
65
  /** POST one page to content_ingest. Never throws; returns the state to record in the manifest. */
@@ -63,7 +63,7 @@ export function resolveIngestConfig() {
63
63
  export function contentHashFor(p) {
64
64
  return createHash('sha256').update(`${p.sessionId}\n${p.startRowId}\n${p.markdown}`).digest('hex');
65
65
  }
66
- const clip = (s, n) => (s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s);
66
+ export const clip = (s, n) => (s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s);
67
67
  const SESSION_ID_RE = /^[a-zA-Z0-9._-]{1,128}$/;
68
68
  /** Map a page to the content_ingest payload. Never includes status/published_at/owner. */
69
69
  export function buildIngestPayload(p, scrub = s => s) {
@@ -12,9 +12,18 @@ export interface LensLaunchPayload {
12
12
  cwd?: string;
13
13
  /** Session-end runs: Library + content steps only, not the profile lens (step 1). */
14
14
  skipLens?: boolean;
15
+ /** Run the machine-wide catch-up sweep after the steps (session end), skipping these live sessions. */
16
+ sweep?: SweepRequest;
17
+ }
18
+ export interface SweepRequest {
19
+ /** Session ids that are live right now: never swept. */
20
+ exclude: string[];
21
+ trigger: string;
15
22
  }
16
23
  export type LensLaunchResult = {
17
24
  status: 'disabled';
25
+ } | {
26
+ status: 'cooldown';
18
27
  } | {
19
28
  status: 'no-key';
20
29
  } | {
@@ -51,7 +60,39 @@ type LastRun = {
51
60
  session: string;
52
61
  reason: string;
53
62
  status: LensLaunchResult['status'];
63
+ attempt?: number;
54
64
  };
55
65
  export declare const lastLibraryRun: () => LastRun;
56
- export declare function launchLibraryOnSessionEnd(sessionId: string | null | undefined, cwd: string | undefined, reason: string): LastRun | null;
66
+ /** Also keeps <osb-library>/live-sessions.json current (every 30s, written only on change), so a running sweep sees sessions that go live. */
67
+ export declare function setLibraryLiveSessions(fn: () => string[]): void;
68
+ /** A session end that found its project locked is retried after the lock can have expired (#268). */
69
+ export declare const sessionEndRetry: {
70
+ delayMs: number;
71
+ max: number;
72
+ };
73
+ /**
74
+ * `live` = sessions still running on this machine (never swept). The worker writes this
75
+ * session's page, then runs the catch-up sweep. When another worker holds this project's
76
+ * lock, a standalone sweep is launched for the other sessions, and this launch is retried
77
+ * (up to sessionEndRetry.max times) unless the session is live again by then.
78
+ */
79
+ export declare function launchLibraryOnSessionEnd(sessionId: string | null | undefined, cwd: string | undefined, reason: string, live?: string[], attempt?: number): LastRun | null;
80
+ /**
81
+ * The PostCompact launch, with the same bounded retry as a session end: a compaction that finds
82
+ * its project locked (a sweep page or a session-end worker is running there) is launched again
83
+ * once the lock can have gone, instead of being dropped.
84
+ */
85
+ export declare function launchCompactionLensWithRetry(payload: LensLaunchPayload, attempt?: number): LensLaunchResult;
86
+ /**
87
+ * Catch-up sweep (lens-library-sweep.ts) in a detached worker: every unwritten period and
88
+ * past-day digest on this machine, newest first, capped per run. The machine-wide sweep lock
89
+ * is taken here, so two sweeps never run at once; the worker inherits and releases it.
90
+ */
91
+ export declare function launchLibrarySweep(live: string[], trigger: string): LensLaunchResult;
92
+ /**
93
+ * The /health view of the Library: the last launches, and the sweep status file (survives
94
+ * restarts). Counts, timestamps and status / error codes only: no ids, days, costs, messages
95
+ * or paths (/health is public).
96
+ */
97
+ export declare function librarySweepHealth(): Record<string, unknown>;
57
98
  export {};