osborn 0.9.291 → 0.9.293
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/.claude/skills/browser-apply/SKILL.md +5 -4
- package/.claude/skills/browser-apply/candidate.example.env +4 -1
- package/.claude/skills/browser-apply/fill.mjs +13 -2
- package/.claude/skills/meetings/SKILL.md +26 -7
- package/.env.example +6 -0
- package/dist/agent-store.d.ts +6 -0
- package/dist/agent-store.js +36 -6
- package/dist/approval-policy.d.ts +99 -0
- package/dist/approval-policy.js +196 -0
- package/dist/claude-llm.d.ts +3 -2
- package/dist/claude-llm.js +49 -19
- package/dist/config.d.ts +12 -16
- package/dist/config.js +80 -22
- package/dist/content/compaction-lens-worker.d.ts +5 -0
- package/dist/content/compaction-lens-worker.js +78 -7
- package/dist/content/content-llm.d.ts +14 -3
- package/dist/content/content-llm.js +33 -142
- package/dist/content/lens-db.d.ts +16 -5
- package/dist/content/lens-db.js +58 -11
- package/dist/content/lens-ingest.d.ts +1 -0
- package/dist/content/lens-ingest.js +1 -1
- package/dist/content/lens-launch.d.ts +42 -1
- package/dist/content/lens-launch.js +202 -40
- package/dist/content/lens-library-digest.d.ts +85 -0
- package/dist/content/lens-library-digest.js +305 -0
- package/dist/content/lens-library-index.d.ts +14 -3
- package/dist/content/lens-library-index.js +35 -8
- package/dist/content/lens-library-select.d.ts +1 -1
- package/dist/content/lens-library-select.js +1 -1
- package/dist/content/lens-library-sweep.d.ts +36 -0
- package/dist/content/lens-library-sweep.js +331 -0
- package/dist/content/lens-library.d.ts +29 -0
- package/dist/content/lens-library.js +130 -20
- package/dist/content/lens-model.d.ts +4 -0
- package/dist/content/lens-model.js +5 -0
- package/dist/content/lens-paths.d.ts +72 -0
- package/dist/content/lens-paths.js +248 -5
- package/dist/content/period-run.js +2 -2
- package/dist/content/secret-rules.d.ts +51 -0
- package/dist/content/secret-rules.js +185 -0
- package/dist/content/transcript-sanitizer.d.ts +1 -41
- package/dist/content/transcript-sanitizer.js +4 -171
- package/dist/data-sender-auth.d.ts +43 -6
- package/dist/data-sender-auth.js +61 -45
- package/dist/env-keys.d.ts +10 -2
- package/dist/env-keys.js +26 -5
- package/dist/index.js +499 -106
- package/dist/phone-code.d.ts +76 -0
- package/dist/phone-code.js +124 -0
- package/dist/phone-voice-actions.d.ts +132 -0
- package/dist/phone-voice-actions.js +223 -0
- package/dist/pipeline-direct-llm.d.ts +7 -1
- package/dist/pipeline-direct-llm.js +12 -1
- package/dist/prompts/library-digest.md +11 -0
- package/dist/prompts.js +2 -2
- package/dist/pushover.d.ts +2 -1
- package/dist/pushover.js +7 -6
- package/dist/risk-tier.d.ts +14 -0
- package/dist/risk-tier.js +140 -0
- package/dist/session-store.d.ts +1 -0
- package/dist/session-store.js +3 -2
- package/dist/session-switch.d.ts +22 -7
- package/dist/session-switch.js +58 -24
- package/dist/steward-verdict.d.ts +16 -3
- package/dist/steward-verdict.js +37 -18
- package/dist/watch-gateway.js +3 -1
- package/package.json +1 -1
- package/dist/bridge-llm.d.ts +0 -22
- package/dist/bridge-llm.js +0 -39
- package/dist/codex-handler.d.ts +0 -38
- package/dist/codex-handler.js +0 -83
- package/dist/codex-llm.d.ts +0 -40
- package/dist/codex-llm.js +0 -144
- package/dist/fast-brain.d.ts +0 -176
- package/dist/fast-brain.js +0 -1887
- package/dist/index-3-2-26-legacy.d.ts +0 -1
- package/dist/index-3-2-26-legacy.js +0 -2233
- package/dist/leagcyprompts2.d.ts +0 -0
- package/dist/leagcyprompts2.js +0 -573
- package/dist/prompts-2-25-26.d.ts +0 -0
- package/dist/prompts-2-25-26.js +0 -518
- package/dist/prompts-3-2-26.d.ts +0 -78
- package/dist/prompts-3-2-26.js +0 -1319
- package/dist/summary-index.d.ts +0 -90
- package/dist/summary-index.js +0 -585
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lens-library-digest.ts — the DAILY DIGEST of short chats.
|
|
3
|
+
*
|
|
4
|
+
* A stretch of conversation that spans less than the period minimum (1h by default) never
|
|
5
|
+
* becomes a period page. The catch-up sweep (lens-library-sweep.ts) gathers those short chats
|
|
6
|
+
* from every session on the machine, groups them by LOCAL calendar day, and writes one page per
|
|
7
|
+
* day that is over (never today, while chats can still be added):
|
|
8
|
+
* <claudeDir>/osb-library/digests/<YYYY-MM-DD>-digest.md (+ INDEX.md, .digest-manifest.json)
|
|
9
|
+
* Each chat gets a title and a one-to-two line summary from ONE model call per day, through the
|
|
10
|
+
* period map's model path (lens-model: OpenRouter, reasoning off, hard $ cap per call). Input
|
|
11
|
+
* rows go through the same strip + secret redaction as the period map (loadConversationRows)
|
|
12
|
+
* plus each project's client redactor; the page is scrubbed again before it is written.
|
|
13
|
+
*
|
|
14
|
+
* Idempotent: .digest-manifest.json records which chats each day holds. A day is rewritten (in
|
|
15
|
+
* place, same file and same cloud row) only when a chat it does not hold turns up for it.
|
|
16
|
+
* Ingest goes through the shared content_ingest seam (postContentIngest) with a stable
|
|
17
|
+
* per-day content hash, so an update replaces the day's draft instead of adding a second one.
|
|
18
|
+
*/
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
20
|
+
import { mkdirSync, readFileSync, rmSync } from 'node:fs';
|
|
21
|
+
import { hostname } from 'node:os';
|
|
22
|
+
import { dirname, join } from 'node:path';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { loadConversationRows } from './lens-db.js';
|
|
25
|
+
import { Budget, chat, getModelInfo, isTransportError, modelCallFailed } from './lens-model.js';
|
|
26
|
+
import { loadClientRedactor } from './lens-redact.js';
|
|
27
|
+
import { redactSecrets } from './transcript-sanitizer.js';
|
|
28
|
+
import { parseJsonLoose } from './content-llm.js';
|
|
29
|
+
import { machineTimeZone, parseDigest, rebuildIndex } from './lens-library-index.js';
|
|
30
|
+
import { clip, needsIngest, postContentIngest, resolveIngestConfig } from './lens-ingest.js';
|
|
31
|
+
import { writeAtomic } from './content-manifest.js';
|
|
32
|
+
import { libraryHomeDir } from './lens-paths.js';
|
|
33
|
+
const DIGEST_MANIFEST_FILE = '.digest-manifest.json';
|
|
34
|
+
/** Hard cap for one day's call. */
|
|
35
|
+
export const DIGEST_CAP_USD = 0.25;
|
|
36
|
+
/** A day that failed this many times in a row is retried only when it gains a chat. */
|
|
37
|
+
const MAX_DIGEST_FAILURES = 3;
|
|
38
|
+
const MAX_CHATS_PER_DAY = 60;
|
|
39
|
+
const CHAT_HEAD = 2_500;
|
|
40
|
+
const CHAT_TAIL = 1_500;
|
|
41
|
+
const MAX_OUT = 6_000;
|
|
42
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
43
|
+
/** YYYY-MM-DD of `ts` in the machine's local time zone (TZ). */
|
|
44
|
+
export function localDay(ts) {
|
|
45
|
+
const d = new Date(ts);
|
|
46
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
47
|
+
}
|
|
48
|
+
const localTime = (ts) => {
|
|
49
|
+
const d = new Date(ts);
|
|
50
|
+
return Number.isFinite(d.getTime()) ? `${pad(d.getHours())}:${pad(d.getMinutes())}` : '?';
|
|
51
|
+
};
|
|
52
|
+
export const chatKey = (c) => `${c.sessionId}:${c.period.startRowId}-${c.period.endRowId}`;
|
|
53
|
+
export const digestDir = (home = libraryHomeDir()) => join(home, 'digests');
|
|
54
|
+
const digestFileName = (day) => `${day}-digest.md`;
|
|
55
|
+
export function readDigestManifest(dir) {
|
|
56
|
+
try {
|
|
57
|
+
const o = JSON.parse(readFileSync(join(dir, DIGEST_MANIFEST_FILE), 'utf-8'));
|
|
58
|
+
if (o && typeof o.days === 'object' && !Array.isArray(o.days))
|
|
59
|
+
return { version: 1, days: o.days };
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
/* missing / unreadable → empty */
|
|
63
|
+
}
|
|
64
|
+
return { version: 1, days: {} };
|
|
65
|
+
}
|
|
66
|
+
export function writeDigestManifest(dir, m) {
|
|
67
|
+
writeAtomic(join(dir, DIGEST_MANIFEST_FILE), JSON.stringify(m, null, 2) + '\n');
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Which past days need a (re)write: never digested, holding a chat the page does not, or holding
|
|
71
|
+
* a chat that is gone (`stale`: it grew into a written period page, or into a longer chat).
|
|
72
|
+
* Chats that touch today wait (they are returned as `today`). Each pending day comes with ALL
|
|
73
|
+
* its current chats, so an updated page is complete. `emptied` = digested days none of whose
|
|
74
|
+
* chats is left: their page should go. Pure.
|
|
75
|
+
*/
|
|
76
|
+
export function pendingDigestDays(chats, m, now = Date.now(), stale = new Set()) {
|
|
77
|
+
const today = localDay(now);
|
|
78
|
+
const byDay = new Map();
|
|
79
|
+
const waiting = [];
|
|
80
|
+
for (const c of chats) {
|
|
81
|
+
if (c.period.rows < 2)
|
|
82
|
+
continue; // a lone message with no reply is not a chat
|
|
83
|
+
const day = localDay(c.period.fromTs);
|
|
84
|
+
const end = localDay(c.period.toTs);
|
|
85
|
+
if (!/^\d{4}-/.test(day) || !/^\d{4}-/.test(end))
|
|
86
|
+
continue;
|
|
87
|
+
if (end >= today) {
|
|
88
|
+
waiting.push(c); // the day is not over yet
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
byDay.set(day, [...(byDay.get(day) ?? []), c]);
|
|
92
|
+
}
|
|
93
|
+
const emptied = Object.values(m.days)
|
|
94
|
+
.filter(e => e.status === 'ok' && !byDay.has(e.day) && e.chats.length > 0 && e.chats.every(k => stale.has(k)))
|
|
95
|
+
.map(e => e.day);
|
|
96
|
+
for (const [day, cs] of [...byDay]) {
|
|
97
|
+
const e = m.days[day];
|
|
98
|
+
if (!e)
|
|
99
|
+
continue;
|
|
100
|
+
const keys = cs.map(chatKey);
|
|
101
|
+
const fresh = keys.some(k => !e.chats.includes(k));
|
|
102
|
+
const gone = e.chats.some(k => stale.has(k));
|
|
103
|
+
// Keeps failing on the same chats: stop until another chat turns up for that day.
|
|
104
|
+
const stuck = (e.failures ?? 0) >= MAX_DIGEST_FAILURES && keys.every(k => e.chats.includes(k) || (e.tried ?? []).includes(k));
|
|
105
|
+
if (((e.status === 'ok' || e.status === 'empty') && !fresh && !gone) || stuck)
|
|
106
|
+
byDay.delete(day);
|
|
107
|
+
}
|
|
108
|
+
return { days: byDay, today: waiting, emptied };
|
|
109
|
+
}
|
|
110
|
+
const oneLine = (s) => s.replace(/\s+/g, ' ').trim();
|
|
111
|
+
/** prompts/library-digest.md (src/prompts in dev, dist/prompts when built). */
|
|
112
|
+
const DIGEST_PROMPT_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', 'prompts', 'library-digest.md');
|
|
113
|
+
function digestPrompt(day, items) {
|
|
114
|
+
return readFileSync(DIGEST_PROMPT_PATH, 'utf-8')
|
|
115
|
+
.trimEnd()
|
|
116
|
+
.replaceAll('{{count}}', String(items.length))
|
|
117
|
+
.replaceAll('{{day}}', day)
|
|
118
|
+
.replace('{{chats}}', () => items.map(i => `<chat n="${i.n}">\n${i.text}\n</chat>`).join('\n\n'));
|
|
119
|
+
}
|
|
120
|
+
function renderDigestMd(day, items, o) {
|
|
121
|
+
const L = [`<!-- osborn-digest: day=${day} chats=${o.total}${o.dry ? ' dry' : ''} -->`, `# Daily digest — ${day}`, ''];
|
|
122
|
+
L.push(`Short chats from this day; the day and the times are in ${machineTimeZone()}. Each is under the period minimum, so none has a period page of its own.`, '');
|
|
123
|
+
L.push(`- Chats: ${o.total}`);
|
|
124
|
+
if (o.total > items.length)
|
|
125
|
+
L.push(`- Listed: the first ${items.length}; ${o.total - items.length} more short chat(s) that day are not summarised`);
|
|
126
|
+
L.push(o.dry ? '- Calls: none (dry run)' : `- Calls: 1, $${o.costUsd.toFixed(4)} (cap $${DIGEST_CAP_USD.toFixed(2)})`, '', '## Chats', '');
|
|
127
|
+
for (const i of items) {
|
|
128
|
+
const p = i.chat.period;
|
|
129
|
+
L.push(`### ${oneLine(i.title || i.fallbackTitle)}`, `- Session ${i.chat.sessionId.slice(0, 8)} · rows #${p.startRowId}–#${p.endRowId} · ${localTime(p.fromTs)}–${localTime(p.toTs)}`);
|
|
130
|
+
L.push(i.summary ? oneLine(i.summary) : '(no summary)', '');
|
|
131
|
+
}
|
|
132
|
+
return L.join('\n');
|
|
133
|
+
}
|
|
134
|
+
/** Stable per machine + day, so a rewritten digest updates its draft in place. */
|
|
135
|
+
function digestContentHash(day) {
|
|
136
|
+
return createHash('sha256').update(`osborn-library-digest\n${hostname()}\n${day}`).digest('hex');
|
|
137
|
+
}
|
|
138
|
+
const bodyHash = (md) => createHash('sha256').update(md).digest('hex');
|
|
139
|
+
/** Send one digest page through the shared content_ingest seam. Never throws; updates `e`. */
|
|
140
|
+
async function ingestDigest(e, markdown, o) {
|
|
141
|
+
const scrub = o.scrub ?? ((s) => s);
|
|
142
|
+
const { titles } = parseDigest(e.file, markdown);
|
|
143
|
+
const payload = {
|
|
144
|
+
type: 'text_post',
|
|
145
|
+
title: clip(scrub(`Daily digest ${e.day}: ${e.chats.length} short chat${e.chats.length === 1 ? '' : 's'}`), 200),
|
|
146
|
+
hook: clip(scrub(titles.slice(0, 3).join(' · ')), 280) || null,
|
|
147
|
+
body: scrub(markdown),
|
|
148
|
+
source_session_id: null,
|
|
149
|
+
source_anchors: { digest_day: e.day, chats: e.chats.length, file: e.file },
|
|
150
|
+
source_kind: 'library_digest',
|
|
151
|
+
content_hash: digestContentHash(e.day),
|
|
152
|
+
};
|
|
153
|
+
// The cloud row is keyed on the stable day hash; the state records the body hash (needsIngest).
|
|
154
|
+
e.ingest = await postContentIngest(payload, bodyHash(markdown), `library: ingest digest ${e.day}`, o);
|
|
155
|
+
}
|
|
156
|
+
/** Retry pass for written digests whose ingest never landed (no model call). Returns true if the manifest changed. */
|
|
157
|
+
export async function ingestPendingDigests(dir, m, o = {}) {
|
|
158
|
+
if (!resolveIngestConfig().ok)
|
|
159
|
+
return false;
|
|
160
|
+
let changed = false;
|
|
161
|
+
for (const e of Object.values(m.days)) {
|
|
162
|
+
if (e.status !== 'ok')
|
|
163
|
+
continue;
|
|
164
|
+
try {
|
|
165
|
+
const md = readFileSync(join(dir, e.file), 'utf-8');
|
|
166
|
+
if (!needsIngest(e.ingest, bodyHash(md)))
|
|
167
|
+
continue;
|
|
168
|
+
await ingestDigest(e, md, o);
|
|
169
|
+
changed = true;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
/* fail-open: next run */
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return changed;
|
|
176
|
+
}
|
|
177
|
+
/** Write (or rewrite) one day's digest. One model call at most. Never throws. */
|
|
178
|
+
export async function runDigestDay(o) {
|
|
179
|
+
const log = o.log ?? (() => { });
|
|
180
|
+
const dir = o.dir ?? digestDir();
|
|
181
|
+
const res = { status: 'failed', page: null, costUsd: 0, errors: [] };
|
|
182
|
+
try {
|
|
183
|
+
mkdirSync(dir, { recursive: true });
|
|
184
|
+
const m = readDigestManifest(dir);
|
|
185
|
+
const prev = m.days[o.day];
|
|
186
|
+
const every = [...o.chats].sort((a, b) => a.period.fromTs.localeCompare(b.period.fromTs));
|
|
187
|
+
const reds = new Map();
|
|
188
|
+
const redFor = (pd) => reds.get(pd) ?? reds.set(pd, loadClientRedactor(pd)).get(pd);
|
|
189
|
+
// Segmentation counts raw rows; only the sanitised rows count here. A chat with fewer than two
|
|
190
|
+
// left (a replayed session tail, a lone message) is not a chat: it is left out before numbering.
|
|
191
|
+
const kept = every
|
|
192
|
+
.map(c => ({ c, recs: loadConversationRows(c.db, c.period.startRowId - 1, redFor(c.projectDir).redact, c.period.endRowId).records }))
|
|
193
|
+
.filter(x => x.recs.length >= 2);
|
|
194
|
+
const items = kept.slice(0, MAX_CHATS_PER_DAY).map(({ c, recs }, i) => {
|
|
195
|
+
const all = recs.map(r => `${r.speaker}: ${r.text}`).join('\n');
|
|
196
|
+
const text = all.length > CHAT_HEAD + CHAT_TAIL ? `${all.slice(0, CHAT_HEAD)}\n…\n${all.slice(-CHAT_TAIL)}` : all;
|
|
197
|
+
const first = recs.find(r => r.speaker === 'user')?.text ?? recs[0]?.text ?? '';
|
|
198
|
+
return { n: i + 1, chat: c, text, fallbackTitle: clip(oneLine(first), 80) || 'Untitled chat' };
|
|
199
|
+
});
|
|
200
|
+
const scrub = (s) => redactSecrets([...reds.values()].reduce((t, r) => r.redact(t), s), { assistant: true });
|
|
201
|
+
// Every chat of the day is recorded, listed, empty or not, so the day is not re-digested each run.
|
|
202
|
+
const keys = every.map(chatKey);
|
|
203
|
+
if (!items.length) {
|
|
204
|
+
// Nothing to summarise: no call, no page, no ingest. An earlier page of that day goes (removeDigestDay).
|
|
205
|
+
if (prev?.status === 'ok')
|
|
206
|
+
await removeDigestDay(dir, o.day, { scrub, log });
|
|
207
|
+
const m2 = readDigestManifest(dir);
|
|
208
|
+
// A cloud draft emptied in place stays 'ok'; any other entry (an earlier error) settles as 'empty'.
|
|
209
|
+
m2.days[o.day] = m2.days[o.day]?.status === 'ok'
|
|
210
|
+
? { ...m2.days[o.day], chats: keys }
|
|
211
|
+
: { day: o.day, file: digestFileName(o.day), chats: keys, status: 'empty', costUsd: 0, errors: [], updatedAt: new Date().toISOString() };
|
|
212
|
+
writeDigestManifest(dir, m2);
|
|
213
|
+
log(`digest ${o.day}: ${every.length} chat(s), none with anything to summarise — no page`);
|
|
214
|
+
return { ...res, status: 'empty' };
|
|
215
|
+
}
|
|
216
|
+
const fail = (status) => {
|
|
217
|
+
m.days[o.day] = {
|
|
218
|
+
...(prev ?? { day: o.day, file: digestFileName(o.day), chats: [] }),
|
|
219
|
+
status: prev?.status === 'ok' ? 'ok' : 'error', // a good page stays; only its retry count moves
|
|
220
|
+
failures: (prev?.failures ?? 0) + (isTransportError(res.errors) ? 0 : 1), tried: keys, costUsd: res.costUsd, errors: res.errors, updatedAt: new Date().toISOString(),
|
|
221
|
+
};
|
|
222
|
+
writeDigestManifest(dir, m);
|
|
223
|
+
log(`digest ${o.day}: ${status} ${res.errors.join('; ')}`);
|
|
224
|
+
return { ...res, status };
|
|
225
|
+
};
|
|
226
|
+
if (!o.dry) {
|
|
227
|
+
const key = (process.env.OPENROUTER_API_KEY || '').trim();
|
|
228
|
+
if (!key)
|
|
229
|
+
throw new Error('OPENROUTER_API_KEY not set');
|
|
230
|
+
const info = await getModelInfo(key);
|
|
231
|
+
if (!info)
|
|
232
|
+
throw new Error('model info unavailable (cannot enforce the cost cap)');
|
|
233
|
+
const prompt = digestPrompt(o.day, items);
|
|
234
|
+
const budget = new Budget(info, { maxCalls: 1, maxCostUsd: DIGEST_CAP_USD });
|
|
235
|
+
try {
|
|
236
|
+
const r = await chat(budget, prompt, key, MAX_OUT);
|
|
237
|
+
if (!r)
|
|
238
|
+
res.errors.push('refused by the cost cap');
|
|
239
|
+
else {
|
|
240
|
+
const parsed = parseJsonLoose(r.content);
|
|
241
|
+
for (const c of Array.isArray(parsed?.chats) ? parsed.chats : []) {
|
|
242
|
+
const it = items.find(i => i.n === Number(c?.n));
|
|
243
|
+
if (!it)
|
|
244
|
+
continue;
|
|
245
|
+
it.title = clip(oneLine(String(c?.title ?? '')), 120) || undefined;
|
|
246
|
+
it.summary = clip(oneLine(String(c?.summary ?? '')), 400) || undefined;
|
|
247
|
+
}
|
|
248
|
+
if (!items.some(i => i.summary))
|
|
249
|
+
res.errors.push('no parseable digest reply');
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch (e) {
|
|
253
|
+
res.errors.push(modelCallFailed(e));
|
|
254
|
+
}
|
|
255
|
+
res.costUsd = +budget.spentUsd.toFixed(4);
|
|
256
|
+
if (!items.some(i => i.summary))
|
|
257
|
+
return fail('model-error');
|
|
258
|
+
}
|
|
259
|
+
const markdown = scrub(renderDigestMd(o.day, items, { costUsd: res.costUsd, dry: o.dry, total: kept.length }));
|
|
260
|
+
const file = digestFileName(o.day);
|
|
261
|
+
res.page = join(dir, file);
|
|
262
|
+
writeAtomic(res.page, markdown);
|
|
263
|
+
rebuildIndex(dir, 'daily digests', scrub);
|
|
264
|
+
const entry = {
|
|
265
|
+
day: o.day, file, chats: keys, status: o.dry ? 'dry' : 'ok', costUsd: res.costUsd, errors: res.errors,
|
|
266
|
+
updatedAt: new Date().toISOString(), ingest: prev?.ingest,
|
|
267
|
+
};
|
|
268
|
+
if (!o.dry)
|
|
269
|
+
await ingestDigest(entry, markdown, { scrub, log });
|
|
270
|
+
m.days[o.day] = entry;
|
|
271
|
+
writeDigestManifest(dir, m);
|
|
272
|
+
res.status = o.dry ? 'dry' : 'written';
|
|
273
|
+
log(`digest ${o.day}: ${res.status} ${items.length} chat(s) $${res.costUsd.toFixed(4)}${prev?.status === 'ok' ? ' (updated)' : ''}`);
|
|
274
|
+
return res;
|
|
275
|
+
}
|
|
276
|
+
catch (e) {
|
|
277
|
+
res.errors.push(e?.message ?? String(e));
|
|
278
|
+
log(`digest ${o.day}: failed (fail-open): ${e?.message ?? e}`);
|
|
279
|
+
return { ...res, status: 'failed' };
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/** Remove a digested day none of whose chats is left (they grew into period pages). No model call. */
|
|
283
|
+
export async function removeDigestDay(dir, day, o = {}) {
|
|
284
|
+
const log = o.log ?? (() => { });
|
|
285
|
+
const m = readDigestManifest(dir);
|
|
286
|
+
const e = m.days[day];
|
|
287
|
+
if (!e)
|
|
288
|
+
return;
|
|
289
|
+
if (e.ingest?.status === 'ok') {
|
|
290
|
+
// Already a cloud draft: rewrite it in place (same day hash) rather than leave a stale copy there.
|
|
291
|
+
const md = [`<!-- osborn-digest: day=${day} chats=0 -->`, `# Daily digest — ${day}`, '',
|
|
292
|
+
'The short chats of this day have grown into period pages, so this digest no longer lists any.', '', '- Chats: 0', ''].join('\n');
|
|
293
|
+
writeAtomic(join(dir, e.file), md);
|
|
294
|
+
Object.assign(e, { chats: [], errors: [], updatedAt: new Date().toISOString() });
|
|
295
|
+
await ingestDigest(e, md, o);
|
|
296
|
+
log(`digest ${day}: emptied in place (its chats are now in period pages)`);
|
|
297
|
+
}
|
|
298
|
+
else {
|
|
299
|
+
rmSync(join(dir, e.file), { force: true });
|
|
300
|
+
delete m.days[day];
|
|
301
|
+
log(`digest ${day}: removed (its chats are now in period pages)`);
|
|
302
|
+
}
|
|
303
|
+
writeDigestManifest(dir, m);
|
|
304
|
+
rebuildIndex(dir, 'daily digests', o.scrub);
|
|
305
|
+
}
|
|
@@ -2,10 +2,21 @@
|
|
|
2
2
|
* lens-library-index.ts — rebuild a session library's INDEX.md from the period
|
|
3
3
|
* pages on disk. The pages are the source of truth (renderPeriodMd format), so
|
|
4
4
|
* pages written by the manual backfill are listed alongside auto-written ones,
|
|
5
|
-
* and a rebuild is idempotent: same pages in → same INDEX out.
|
|
5
|
+
* and a rebuild is idempotent: same pages in → same INDEX out. In the daily-digests dir
|
|
6
|
+
* (lens-library-digest.ts) the same rebuild lists the digest pages instead.
|
|
6
7
|
*/
|
|
7
8
|
export declare const INDEX_FILE = "INDEX.md";
|
|
8
9
|
export declare const PAGE_RE: RegExp;
|
|
10
|
+
/** The machine's time zone (TZ): what "day" means for a digest. Cloud machines run on UTC. */
|
|
11
|
+
export declare const machineTimeZone: () => string;
|
|
12
|
+
export interface DigestSummary {
|
|
13
|
+
file: string;
|
|
14
|
+
day: string;
|
|
15
|
+
chats: number;
|
|
16
|
+
titles: string[];
|
|
17
|
+
}
|
|
18
|
+
/** Parse one digest page (renderDigestMd output). Pure. */
|
|
19
|
+
export declare function parseDigest(file: string, md: string): DigestSummary;
|
|
9
20
|
export interface PageStory {
|
|
10
21
|
title: string;
|
|
11
22
|
rows: string;
|
|
@@ -25,6 +36,6 @@ export interface PageSummary {
|
|
|
25
36
|
/** Parse one period page (renderPeriodMd output). Pure. */
|
|
26
37
|
export declare function parsePage(file: string, md: string): PageSummary;
|
|
27
38
|
/** Render INDEX.md. Pure. */
|
|
28
|
-
export declare function renderIndex(sessionLabel: string, pages: PageSummary[]): string;
|
|
29
|
-
/** Rebuild <dir>/INDEX.md from every period page in <dir>. `scrub` = final redaction pass. Returns the path. */
|
|
39
|
+
export declare function renderIndex(sessionLabel: string, pages: PageSummary[], digests?: DigestSummary[]): string;
|
|
40
|
+
/** Rebuild <dir>/INDEX.md from every period page (or daily digest) in <dir>. `scrub` = final redaction pass. Returns the path. */
|
|
30
41
|
export declare function rebuildIndex(dir: string, sessionLabel: string, scrub?: (s: string) => string): string;
|
|
@@ -2,12 +2,23 @@
|
|
|
2
2
|
* lens-library-index.ts — rebuild a session library's INDEX.md from the period
|
|
3
3
|
* pages on disk. The pages are the source of truth (renderPeriodMd format), so
|
|
4
4
|
* pages written by the manual backfill are listed alongside auto-written ones,
|
|
5
|
-
* and a rebuild is idempotent: same pages in → same INDEX out.
|
|
5
|
+
* and a rebuild is idempotent: same pages in → same INDEX out. In the daily-digests dir
|
|
6
|
+
* (lens-library-digest.ts) the same rebuild lists the digest pages instead.
|
|
6
7
|
*/
|
|
7
8
|
import { readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
|
|
8
9
|
import { join } from 'node:path';
|
|
9
10
|
export const INDEX_FILE = 'INDEX.md';
|
|
10
11
|
export const PAGE_RE = /^(\d{4}-\d{2}-\d{2}|undated)-period-(\d+)\.md$/;
|
|
12
|
+
/** One daily digest of short chats (lens-library-digest.ts), named after its local day. */
|
|
13
|
+
const DIGEST_RE = /^(\d{4}-\d{2}-\d{2})-digest\.md$/;
|
|
14
|
+
/** The machine's time zone (TZ): what "day" means for a digest. Cloud machines run on UTC. */
|
|
15
|
+
export const machineTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
16
|
+
/** Parse one digest page (renderDigestMd output). Pure. */
|
|
17
|
+
export function parseDigest(file, md) {
|
|
18
|
+
const n = md.match(/^- Chats: (\d+)/m);
|
|
19
|
+
const titles = [...md.matchAll(/^### (.+)$/gm)].map(m => m[1].trim());
|
|
20
|
+
return { file, day: file.match(DIGEST_RE)?.[1] ?? '', chats: n ? Number(n[1]) : titles.length, titles };
|
|
21
|
+
}
|
|
11
22
|
function section(md, heading) {
|
|
12
23
|
const at = md.indexOf(`\n## ${heading}\n`);
|
|
13
24
|
if (at < 0)
|
|
@@ -41,11 +52,15 @@ export function parsePage(file, md) {
|
|
|
41
52
|
const cell = (s) => s.replace(/\|/g, '\\|').replace(/\n+/g, ' ');
|
|
42
53
|
const when = (iso) => (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(iso) ? iso.slice(0, 16).replace('T', ' ') : iso || '?');
|
|
43
54
|
/** Render INDEX.md. Pure. */
|
|
44
|
-
export function renderIndex(sessionLabel, pages) {
|
|
55
|
+
export function renderIndex(sessionLabel, pages, digests = []) {
|
|
45
56
|
const ps = [...pages].sort((a, b) => a.index - b.index || a.file.localeCompare(b.file));
|
|
57
|
+
if (!ps.length && digests.length)
|
|
58
|
+
return renderDigestIndex(digests);
|
|
46
59
|
const L = [`# Content library — session ${sessionLabel}`, ''];
|
|
47
60
|
L.push('Period pages from the period map (review mode). New pages are written automatically by the content-lens worker on each ' +
|
|
48
|
-
'compaction and when a session ends, one per period spanning at least an hour, keyed on the period\'s opening boundary row
|
|
61
|
+
'compaction and when a session ends, one per period spanning at least an hour, keyed on the period\'s opening boundary row; the catch-up sweep writes older ' +
|
|
62
|
+
'periods that were skipped (at most 10 pages a run, newest first). Chats shorter than a period go to the daily digests ' +
|
|
63
|
+
'(osb-library/digests). content-profile.md and the HWM are not touched.', '');
|
|
49
64
|
L.push('## Periods (chronological)', '', '| # | Date range (UTC) | Rows | Period goal | Top high-leverage item | File |', '|---|---|---|---|---|---|');
|
|
50
65
|
for (const p of ps) {
|
|
51
66
|
L.push(`| ${String(p.index).padStart(2, '0')} | ${when(p.from)} → ${when(p.to)} | ${p.rows} | ${cell(p.goal)} | ${cell(p.topItem ?? '(none verified)')} | [${p.file}](${p.file}) |`);
|
|
@@ -66,14 +81,26 @@ export function renderIndex(sessionLabel, pages) {
|
|
|
66
81
|
L.push('', '## Totals', '', `- Periods: ${ps.length}`, `- Stories: ${stories}`, `- Model spend across pages: $${cost.toFixed(4)}`);
|
|
67
82
|
return L.join('\n') + '\n';
|
|
68
83
|
}
|
|
69
|
-
/**
|
|
84
|
+
/** INDEX.md of the digests dir: one row per local day. Pure. */
|
|
85
|
+
function renderDigestIndex(digests) {
|
|
86
|
+
const ds = [...digests].sort((a, b) => b.day.localeCompare(a.day));
|
|
87
|
+
const L = ['# Content library — daily digests', ''];
|
|
88
|
+
L.push(`One page per calendar day (machine time zone: ${machineTimeZone()}) for chats too short to become a period page (under the period minimum, 1h by default): ` +
|
|
89
|
+
'each chat\'s title and a one-to-two line summary. Written by the catch-up sweep only for days that are over; a day is ' +
|
|
90
|
+
'rewritten in place when new short chats turn up for it.', '', '| Day | Chats | Titles | File |', '|---|---|---|---|');
|
|
91
|
+
for (const d of ds)
|
|
92
|
+
L.push(`| ${d.day} | ${d.chats} | ${cell(d.titles.slice(0, 5).join('; ') + (d.titles.length > 5 ? '; …' : ''))} | [${d.file}](${d.file}) |`);
|
|
93
|
+
L.push('', '## Totals', '', `- Days: ${ds.length}`, `- Chats: ${ds.reduce((n, d) => n + d.chats, 0)}`);
|
|
94
|
+
return L.join('\n') + '\n';
|
|
95
|
+
}
|
|
96
|
+
/** Rebuild <dir>/INDEX.md from every period page (or daily digest) in <dir>. `scrub` = final redaction pass. Returns the path. */
|
|
70
97
|
export function rebuildIndex(dir, sessionLabel, scrub = s => s) {
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
98
|
+
const files = readdirSync(dir);
|
|
99
|
+
const pages = files.filter(f => PAGE_RE.test(f)).map(f => parsePage(f, readFileSync(join(dir, f), 'utf-8')));
|
|
100
|
+
const digests = files.filter(f => DIGEST_RE.test(f)).map(f => parseDigest(f, readFileSync(join(dir, f), 'utf-8')));
|
|
74
101
|
const path = join(dir, INDEX_FILE);
|
|
75
102
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
76
|
-
writeFileSync(tmp, scrub(renderIndex(sessionLabel, pages)), 'utf-8');
|
|
103
|
+
writeFileSync(tmp, scrub(renderIndex(sessionLabel, pages, digests)), 'utf-8');
|
|
77
104
|
renameSync(tmp, path);
|
|
78
105
|
return path;
|
|
79
106
|
}
|
|
@@ -54,7 +54,7 @@ export type PickResult = {
|
|
|
54
54
|
/**
|
|
55
55
|
* The newest period not yet written, among (1) the tail when it is long enough
|
|
56
56
|
* and (2) the last seam-closed group. At most one per run; older gaps are left to
|
|
57
|
-
*
|
|
57
|
+
* the capped catch-up sweep (lens-library-sweep.ts) so a compaction never triggers surprise spend.
|
|
58
58
|
*/
|
|
59
59
|
export declare function pickLibraryPeriod(seg: Segmentation, isDone: (startRowId: number) => boolean, minSpanMs?: number): PickResult;
|
|
60
60
|
/** <YYYY-MM-DD of the period start>-period-<NN>.md — same scheme as the manual backfill. */
|
|
@@ -58,7 +58,7 @@ export function segmentPeriods(records, boundaries, minSpanMs = DEFAULT_MIN_SPAN
|
|
|
58
58
|
/**
|
|
59
59
|
* The newest period not yet written, among (1) the tail when it is long enough
|
|
60
60
|
* and (2) the last seam-closed group. At most one per run; older gaps are left to
|
|
61
|
-
*
|
|
61
|
+
* the capped catch-up sweep (lens-library-sweep.ts) so a compaction never triggers surprise spend.
|
|
62
62
|
*/
|
|
63
63
|
export function pickLibraryPeriod(seg, isDone, minSpanMs = DEFAULT_MIN_SPAN_MS) {
|
|
64
64
|
if (!seg.tail && !seg.closed.length)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lens-library-sweep.ts — the Library's CATCH-UP SWEEP (runs in the detached worker).
|
|
3
|
+
*
|
|
4
|
+
* The per-session step writes at most one page per run (the period that just ended). The sweep
|
|
5
|
+
* writes the rest of the backlog across every session on this machine except the live ones:
|
|
6
|
+
* - every unwritten period that spans >= the min span (libraryBacklog: older closed periods,
|
|
7
|
+
* gaps between written pages, tails of ended sessions), one page each via runLibraryStep;
|
|
8
|
+
* - one daily digest per past local day for the chats too short to become a period
|
|
9
|
+
* (lens-library-digest.ts).
|
|
10
|
+
* Newest work first, at most SWEEP_MAX_PAGES model-call pages a run (periods and digests
|
|
11
|
+
* together), so spend stays bounded and the backlog clears over several runs. Each period or
|
|
12
|
+
* day gets one attempt per run; repeat failures stop being retried (MAX_*_FAILURES).
|
|
13
|
+
* Idempotent through the manifests: a written period or digested day is never redone.
|
|
14
|
+
*
|
|
15
|
+
* Locking: the caller holds the machine-wide sweep lock (<claudeDir>/osb-library) and no project
|
|
16
|
+
* lock. Each period takes its project's lock for the length of its write (skipped when another
|
|
17
|
+
* worker has it), and periods in a project a live session uses wait for a later run, so the sweep
|
|
18
|
+
* never keeps a live session's compaction run out. A dry run writes only under <home>/dry. Result + backlog go to library-sweep-status.json there (read by /health), the log to
|
|
19
|
+
* content-lens.log there. Never throws.
|
|
20
|
+
*/
|
|
21
|
+
import { type SweepStatus } from './lens-paths.js';
|
|
22
|
+
export interface SweepOptions {
|
|
23
|
+
/** Live sessions: never swept. */
|
|
24
|
+
exclude?: string[];
|
|
25
|
+
trigger?: string;
|
|
26
|
+
maxPages?: number;
|
|
27
|
+
/** No model calls (pages/digests marked dry, never counted as written). */
|
|
28
|
+
dry?: boolean;
|
|
29
|
+
now?: number;
|
|
30
|
+
/** Skip the run when the last one finished this recently (default SWEEP_COOLDOWN_MS; the manual CLI passes 0). */
|
|
31
|
+
cooldownMs?: number;
|
|
32
|
+
}
|
|
33
|
+
/** An error as one redacted line of at most 200 chars: what the status file keeps (SweepError, workerError). */
|
|
34
|
+
export declare const errorLine: (e: unknown) => string;
|
|
35
|
+
/** Run one sweep. Never throws; returns the status it wrote. */
|
|
36
|
+
export declare function runLibrarySweep(o?: SweepOptions): Promise<SweepStatus>;
|