oc-harness-setup 0.3.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/unwired-routing.md +16 -15
- package/AGENTS.md +105 -68
- package/CHANGELOG.md +91 -0
- package/GLOSSARY.md +46 -0
- package/LICENSE +1 -1
- package/README.md +48 -60
- package/agents/cleaner.md +86 -0
- package/agents/critic.md +79 -0
- package/agents/historian.md +92 -0
- package/agents/maintainer.md +106 -0
- package/agents/ops.md +69 -0
- package/agents/orchestrator.md +48 -18
- package/agents/researcher.md +72 -0
- package/agents/verifier.md +84 -0
- package/agents/worker.md +87 -0
- package/bin/cli.js +349 -133
- package/commands/close.md +11 -0
- package/commands/evolve.md +11 -0
- package/commands/fast.md +11 -0
- package/commands/goal.md +11 -0
- package/commands/search.md +11 -0
- package/commands/swarm.md +11 -0
- package/opencode.jsonc +39 -79
- package/package.json +13 -6
- package/reference/README.md +12 -14
- package/reference/canon.md +71 -0
- package/reference/context.md +35 -0
- package/reference/enforcement.md +6 -0
- package/reference/flow.md +19 -0
- package/reference/gates.md +23 -0
- package/reference/harness.md +15 -0
- package/reference/hygiene.md +13 -0
- package/reference/memory.md +13 -0
- package/reference/models.md +19 -24
- package/reference/phases.md +23 -0
- package/reference/repos.md +49 -0
- package/reference/tools.md +35 -0
- package/scripts/harness-doctor.ps1 +83 -0
- package/skills/close/SKILL.md +36 -0
- package/skills/evolve/SKILL.md +76 -0
- package/skills/fast/SKILL.md +36 -0
- package/skills/goal/SKILL.md +65 -0
- package/skills/search/SKILL.md +68 -0
- package/skills/swarm/SKILL.md +69 -0
- package/state-seed/lessons.md +22 -0
- package/state-seed/template.md +12 -0
- package/agents/build.md +0 -20
- package/agents/explore.md +0 -26
- package/agents/general.md +0 -19
- package/agents/plan.md +0 -29
- package/agents/reviewer.md +0 -22
- package/agents/vault.md +0 -73
- package/commands/build.md +0 -7
- package/commands/checkpoint.md +0 -7
- package/commands/code-simplify.md +0 -7
- package/commands/gauntlet.md +0 -7
- package/commands/handoff.md +0 -7
- package/commands/keeper.md +0 -7
- package/commands/kill.md +0 -11
- package/commands/plan.md +0 -7
- package/commands/retro.md +0 -15
- package/commands/review.md +0 -7
- package/commands/ship.md +0 -7
- package/commands/spec.md +0 -7
- package/commands/test.md +0 -7
- package/commands/webperf.md +0 -7
- package/reference/auto-mandate.md +0 -11
- package/reference/backup-convention.md +0 -9
- package/reference/clean-mandate.md +0 -13
- package/reference/editor-parity.md +0 -7
- package/reference/gc-scripts.md +0 -8
- package/reference/intent-routing.md +0 -14
- package/reference/lifecycle.md +0 -15
- package/reference/model-keeper.md +0 -46
- package/reference/model-test.md +0 -176
- package/reference/oc-source-map.md +0 -162
- package/reference/owner-pin.md +0 -31
- package/reference/roster.md +0 -15
- package/reference/session-scope.md +0 -9
- package/reference/session-state.md +0 -13
- package/reference/swarm.md +0 -32
- package/scripts/backup-config.ps1 +0 -42
- package/scripts/gc-branch.ps1 +0 -196
- package/scripts/gc-bump.ps1 +0 -198
- package/scripts/gc-clean.ps1 +0 -648
- package/scripts/gc-commit.ps1 +0 -143
- package/scripts/gc-merge.ps1 +0 -272
- package/scripts/gc-pr.ps1 +0 -190
- package/scripts/gc-push.ps1 +0 -111
- package/scripts/gc-read.ps1 +0 -150
- package/scripts/gc-rebase.ps1 +0 -162
- package/scripts/gc-release.ps1 +0 -225
- package/scripts/gc-stage.ps1 +0 -103
- package/scripts/gc-status.ps1 +0 -127
- package/scripts/gc-sync.ps1 +0 -65
- package/scripts/gc.core.ps1 +0 -715
- package/scripts/gc.smoke.ps1 +0 -779
- package/scripts/interrupt-session.ps1 +0 -65
- package/scripts/logbook/README.md +0 -108
- package/scripts/logbook/logbook.test.ts +0 -440
- package/scripts/logbook/logbook.ts +0 -797
- package/scripts/pirep/README.md +0 -147
- package/scripts/pirep/pirep.test.ts +0 -735
- package/scripts/pirep/pirep.ts +0 -836
- package/scripts/testflight/README.md +0 -112
- package/scripts/testflight/testflight.test.ts +0 -512
- package/scripts/testflight/testflight.ts +0 -806
- package/skills/_shared/SOURCES.md +0 -26
- package/skills/_shared/references/accessibility-checklist.md +0 -160
- package/skills/_shared/references/definition-of-done.md +0 -67
- package/skills/_shared/references/observability-checklist.md +0 -92
- package/skills/_shared/references/orchestration-patterns.md +0 -155
- package/skills/_shared/references/performance-checklist.md +0 -236
- package/skills/_shared/references/security-checklist.md +0 -245
- package/skills/_shared/references/testing-patterns.md +0 -235
- package/skills/api-and-interface-design/SKILL.md +0 -14
- package/skills/browser-testing-with-devtools/SKILL.md +0 -303
- package/skills/code-simplification/SKILL.md +0 -14
- package/skills/creative-writing/SKILL.md +0 -96
- package/skills/debugging-and-error-recovery/SKILL.md +0 -15
- package/skills/flight-deck/SKILL.md +0 -17
- package/skills/frontend-ui-engineering/SKILL.md +0 -16
- package/skills/gauntlet/SKILL.md +0 -21
- package/skills/git-ceremony/SKILL.md +0 -27
- package/skills/grilling/SKILL.md +0 -18
- package/skills/observability-and-instrumentation/SKILL.md +0 -18
- package/skills/performance-optimization/SKILL.md +0 -16
- package/skills/pilot-report/SKILL.md +0 -18
- package/skills/planning-and-task-breakdown/SKILL.md +0 -16
- package/skills/security-and-hardening/SKILL.md +0 -18
- package/skills/source-driven-development/SKILL.md +0 -16
- package/skills/spec-driven-development/SKILL.md +0 -26
- package/skills/test-driven-development/SKILL.md +0 -18
- package/skills/test-flight/SKILL.md +0 -14
- package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
- package/skills/writing-for-agents/SKILL.md +0 -89
|
@@ -1,797 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
/**
|
|
3
|
-
* logbook — the readable half of your OpenCode history.
|
|
4
|
-
*
|
|
5
|
-
* Every session you have ever run is still on disk, but it is write-only:
|
|
6
|
-
* nothing can search it, so problems get solved for the first time, every time.
|
|
7
|
-
* This makes it readable.
|
|
8
|
-
*
|
|
9
|
-
* Design rules, in order of importance:
|
|
10
|
-
*
|
|
11
|
-
* 1. The host database is opened READ-ONLY and never written. The index is a
|
|
12
|
-
* separate file this tool owns.
|
|
13
|
-
* 2. The index is derived data. If it is ever wrong or corrupt, deleting it and
|
|
14
|
-
* re-running is always safe — `--reindex` does exactly that.
|
|
15
|
-
* 3. Secret-shaped strings are scrubbed before they are indexed. Your messages
|
|
16
|
-
* contain pasted tokens; an index is a new place for them to leak from.
|
|
17
|
-
* 4. Degrade quietly: a missing index, an unreadable database, or an unexpected
|
|
18
|
-
* host schema prints a clear message and exits non-zero. It never throws a
|
|
19
|
-
* stack trace at you.
|
|
20
|
-
*
|
|
21
|
-
* Usage:
|
|
22
|
-
* logbook "lastexitcode" search
|
|
23
|
-
* logbook --precedent "<error>" find prior occurrences of a failure
|
|
24
|
-
* logbook --precedent ...reading the error from stdin
|
|
25
|
-
* logbook --stats what is in the index
|
|
26
|
-
* logbook --reindex rebuild from scratch
|
|
27
|
-
* logbook --json machine-readable output
|
|
28
|
-
*/
|
|
29
|
-
|
|
30
|
-
import { Database } from "bun:sqlite";
|
|
31
|
-
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
|
32
|
-
import { homedir } from "node:os";
|
|
33
|
-
import { join } from "node:path";
|
|
34
|
-
|
|
35
|
-
const HOME = homedir();
|
|
36
|
-
|
|
37
|
-
/** Overridable so the suite can run against fixtures instead of your history. */
|
|
38
|
-
const SOURCE_DB =
|
|
39
|
-
process.env["LOGBOOK_SOURCE"] ?? join(HOME, ".local", "share", "opencode", "opencode.db");
|
|
40
|
-
const INDEX_DB = process.env["LOGBOOK_INDEX"] ?? join(HOME, ".opencode", "logbook", "index.db");
|
|
41
|
-
|
|
42
|
-
// ---------------------------------------------------------------------------
|
|
43
|
-
// Redaction
|
|
44
|
-
// ---------------------------------------------------------------------------
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* A seatbelt, not a guarantee — same tradeoff as any secret scanner. The goal is
|
|
48
|
-
* that the index is not a *new* place for credentials to accumulate. Unknown
|
|
49
|
-
* formats will get through; that is stated rather than hidden.
|
|
50
|
-
*/
|
|
51
|
-
const SECRET_PATTERNS: readonly RegExp[] = [
|
|
52
|
-
/\b(?:npm|ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}\b/g,
|
|
53
|
-
/\bsk-[A-Za-z0-9_-]{16,}\b/g,
|
|
54
|
-
/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
|
|
55
|
-
/\bAKIA[0-9A-Z]{16}\b/g,
|
|
56
|
-
/\bAIza[0-9A-Za-z_-]{30,}\b/g,
|
|
57
|
-
/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, // JWT
|
|
58
|
-
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
|
|
59
|
-
];
|
|
60
|
-
|
|
61
|
-
/** `key=value` / `key: value` forms keep the key so the context survives. */
|
|
62
|
-
const KEYED_SECRET =
|
|
63
|
-
/\b((?:api[_-]?key|access[_-]?token|auth[_-]?token|_authToken|client[_-]?secret|password|secret)\s*[=:]\s*)(["']?)([^\s"',;]{8,})\2/gi;
|
|
64
|
-
|
|
65
|
-
export function redact(text: string): string {
|
|
66
|
-
let out = text;
|
|
67
|
-
for (const pattern of SECRET_PATTERNS) out = out.replace(pattern, "[redacted]");
|
|
68
|
-
out = out.replace(KEYED_SECRET, (_match, prefix: string) => `${prefix}[redacted]`);
|
|
69
|
-
return out;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// ---------------------------------------------------------------------------
|
|
73
|
-
// Index schema
|
|
74
|
-
// ---------------------------------------------------------------------------
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Plain FTS5 (not contentless) so rows can be deleted on re-sync — a message's
|
|
78
|
-
* tool output changes from "running" to "completed" and must replace its old
|
|
79
|
-
* row rather than duplicate it.
|
|
80
|
-
*/
|
|
81
|
-
const SCHEMA = `
|
|
82
|
-
create virtual table if not exists docs using fts5(
|
|
83
|
-
text,
|
|
84
|
-
doc_key unindexed,
|
|
85
|
-
session_id unindexed,
|
|
86
|
-
kind unindexed,
|
|
87
|
-
ts unindexed,
|
|
88
|
-
title unindexed,
|
|
89
|
-
dir unindexed
|
|
90
|
-
);
|
|
91
|
-
create table if not exists meta(key text primary key, value text);
|
|
92
|
-
`;
|
|
93
|
-
|
|
94
|
-
type Kind = "user" | "assistant" | "note" | "error";
|
|
95
|
-
|
|
96
|
-
interface Doc {
|
|
97
|
-
readonly key: string;
|
|
98
|
-
readonly sessionId: string;
|
|
99
|
-
readonly kind: Kind;
|
|
100
|
-
readonly ts: number;
|
|
101
|
-
readonly title: string;
|
|
102
|
-
readonly dir: string;
|
|
103
|
-
readonly text: string;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
interface SessionMeta {
|
|
107
|
-
readonly title: string;
|
|
108
|
-
readonly dir: string;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** One message, in the same shape whether it came from the host table or the API adapter. */
|
|
112
|
-
interface MessageRow {
|
|
113
|
-
readonly id: string;
|
|
114
|
-
readonly session_id: string;
|
|
115
|
-
readonly type: string;
|
|
116
|
-
readonly time_created: number;
|
|
117
|
-
readonly data: string;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export function openIndex(path: string = INDEX_DB): Database {
|
|
121
|
-
mkdirSync(join(path, ".."), { recursive: true });
|
|
122
|
-
const index = new Database(path);
|
|
123
|
-
// WAL lets a search run while a background sync writes, and busy_timeout makes
|
|
124
|
-
// a second invocation wait its turn instead of failing with SQLITE_BUSY.
|
|
125
|
-
index.exec("pragma journal_mode = wal");
|
|
126
|
-
index.exec("pragma busy_timeout = 15000");
|
|
127
|
-
index.exec("pragma synchronous = normal");
|
|
128
|
-
index.exec(SCHEMA);
|
|
129
|
-
return index;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function getMeta(index: Database, key: string): string | undefined {
|
|
133
|
-
const row = index.query<{ value: string }, [string]>("select value from meta where key = ?").get(key);
|
|
134
|
-
return row?.value;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function setMeta(index: Database, key: string, value: string): void {
|
|
138
|
-
index
|
|
139
|
-
.query("insert into meta(key, value) values(?, ?) on conflict(key) do update set value = excluded.value")
|
|
140
|
-
.run(key, value);
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// ---------------------------------------------------------------------------
|
|
144
|
-
// Extraction
|
|
145
|
-
// ---------------------------------------------------------------------------
|
|
146
|
-
|
|
147
|
-
/** Minimal shape checks — the host schema is not ours and must not be trusted. */
|
|
148
|
-
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
149
|
-
return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : undefined;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function asText(value: unknown): string | undefined {
|
|
153
|
-
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/** Tool results arrive as content blocks, exactly like assistant messages do. */
|
|
157
|
-
function blockText(content: unknown): string | undefined {
|
|
158
|
-
if (!Array.isArray(content)) return undefined;
|
|
159
|
-
const parts: string[] = [];
|
|
160
|
-
for (const block of content) {
|
|
161
|
-
const record = asRecord(block);
|
|
162
|
-
if (record?.["type"] === "text") {
|
|
163
|
-
const text = asText(record["text"]);
|
|
164
|
-
if (text !== undefined) parts.push(text);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
return parts.length === 0 ? undefined : parts.join("\n");
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
const MAX_DOC_CHARS = 8_000;
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Long documents are clamped head-and-tail rather than head-only: failures
|
|
174
|
-
* report at the *end* of output, so truncating from the tail would delete
|
|
175
|
-
* exactly what a precedent search came looking for.
|
|
176
|
-
*/
|
|
177
|
-
function clamp(text: string): string {
|
|
178
|
-
if (text.length <= MAX_DOC_CHARS) return text;
|
|
179
|
-
const head = text.slice(0, 4_800);
|
|
180
|
-
const tail = text.slice(-3_200);
|
|
181
|
-
return `${head}\n…\n${tail}`;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* One message becomes several documents, because the parts have different jobs:
|
|
186
|
-
* the model's prose explains *why*, while a failed tool result holds the *what*.
|
|
187
|
-
* Keeping them separate gives precise hits and readable snippets.
|
|
188
|
-
*/
|
|
189
|
-
export function docsFromMessage(row: MessageRow, meta: SessionMeta): Doc[] {
|
|
190
|
-
let parsed: unknown;
|
|
191
|
-
try {
|
|
192
|
-
parsed = JSON.parse(row.data);
|
|
193
|
-
} catch {
|
|
194
|
-
return [];
|
|
195
|
-
}
|
|
196
|
-
const message = asRecord(parsed);
|
|
197
|
-
if (message === undefined) return [];
|
|
198
|
-
|
|
199
|
-
const out: Doc[] = [];
|
|
200
|
-
let slot = 0;
|
|
201
|
-
const push = (kind: Kind, text: string | undefined): void => {
|
|
202
|
-
if (text === undefined) return;
|
|
203
|
-
const clean = clamp(redact(text)).trim();
|
|
204
|
-
// Short fragments are pure noise in a search index.
|
|
205
|
-
if (clean.length < 12) return;
|
|
206
|
-
out.push({
|
|
207
|
-
key: `${row.id}:${slot++}`,
|
|
208
|
-
sessionId: row.session_id,
|
|
209
|
-
kind,
|
|
210
|
-
ts: row.time_created,
|
|
211
|
-
title: meta.title,
|
|
212
|
-
dir: meta.dir,
|
|
213
|
-
text: clean,
|
|
214
|
-
});
|
|
215
|
-
};
|
|
216
|
-
|
|
217
|
-
if (row.type === "user" || row.type === "synthetic") {
|
|
218
|
-
push(row.type === "synthetic" ? "note" : "user", asText(message["text"]));
|
|
219
|
-
return out;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
const content = message["content"];
|
|
223
|
-
if (Array.isArray(content)) {
|
|
224
|
-
for (const block of content) {
|
|
225
|
-
const part = asRecord(block);
|
|
226
|
-
if (part === undefined) continue;
|
|
227
|
-
const type = part["type"];
|
|
228
|
-
if (type === "text") {
|
|
229
|
-
push("assistant", asText(part["text"]));
|
|
230
|
-
} else if (type === "tool") {
|
|
231
|
-
const state = asRecord(part["state"]);
|
|
232
|
-
// Only failures are indexed. Successful tool output is ~52k documents of
|
|
233
|
-
// file listings and command results — the bulk of the corpus and almost
|
|
234
|
-
// none of the retrieval value — and short `shell ...` fragments would
|
|
235
|
-
// outrank long explanations under bm25. Revisit if you ever want to
|
|
236
|
-
// search for a command you ran rather than a problem you solved.
|
|
237
|
-
if (asText(state?.["status"]) === "error") push("error", blockText(state?.["content"]));
|
|
238
|
-
}
|
|
239
|
-
// `reasoning` is deliberately skipped: high volume, low retrieval value.
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// Compaction summaries and similar carry their payload in plain `text`.
|
|
244
|
-
push(row.type === "compaction" ? "note" : "assistant", asText(message["text"]));
|
|
245
|
-
return out;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// ---------------------------------------------------------------------------
|
|
249
|
-
// Sync
|
|
250
|
-
// ---------------------------------------------------------------------------
|
|
251
|
-
|
|
252
|
-
function loadSessionMeta(source: Database): Map<string, SessionMeta> {
|
|
253
|
-
const meta = new Map<string, SessionMeta>();
|
|
254
|
-
// Two tables hold sessions across host versions; whichever is present wins.
|
|
255
|
-
for (const table of ["session_v2", "session"]) {
|
|
256
|
-
let rows: { id: string; title: string | null; directory: string | null }[];
|
|
257
|
-
try {
|
|
258
|
-
rows = source
|
|
259
|
-
.query<{ id: string; title: string | null; directory: string | null }, []>(
|
|
260
|
-
`select id, title, directory from ${table}`,
|
|
261
|
-
)
|
|
262
|
-
.all();
|
|
263
|
-
} catch {
|
|
264
|
-
continue; // table absent on this host version
|
|
265
|
-
}
|
|
266
|
-
for (const row of rows) {
|
|
267
|
-
if (meta.has(row.id)) continue;
|
|
268
|
-
meta.set(row.id, { title: row.title ?? "", dir: row.directory ?? "" });
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
return meta;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
interface SyncResult {
|
|
275
|
-
readonly indexed: number;
|
|
276
|
-
readonly scanned: number;
|
|
277
|
-
readonly skipped: number;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
export function sync(index: Database, source: Database, force: boolean): SyncResult {
|
|
281
|
-
const cursor = force ? "0" : (getMeta(index, "cursor") ?? "0");
|
|
282
|
-
const meta = loadSessionMeta(source);
|
|
283
|
-
|
|
284
|
-
const statement = source.query<
|
|
285
|
-
{ id: string; session_id: string; type: string; time_created: number; time_updated: number; data: string },
|
|
286
|
-
[string]
|
|
287
|
-
>(
|
|
288
|
-
`select id, session_id, type, time_created, time_updated, data
|
|
289
|
-
from session_message
|
|
290
|
-
where time_updated > ?
|
|
291
|
-
order by time_updated`,
|
|
292
|
-
);
|
|
293
|
-
|
|
294
|
-
const remove = index.query("delete from docs where doc_key = ?");
|
|
295
|
-
const insert = index.query(
|
|
296
|
-
"insert into docs(text, doc_key, session_id, kind, ts, title, dir) values(?, ?, ?, ?, ?, ?, ?)",
|
|
297
|
-
);
|
|
298
|
-
|
|
299
|
-
let indexed = 0;
|
|
300
|
-
let scanned = 0;
|
|
301
|
-
let skipped = 0;
|
|
302
|
-
let high = Number(cursor);
|
|
303
|
-
|
|
304
|
-
// ONE transaction for the whole batch, deliberately.
|
|
305
|
-
//
|
|
306
|
-
// Committing per message turned a 40k-document build into a 220-second fsync
|
|
307
|
-
// storm. It also meant an interrupted run could leave documents in the index
|
|
308
|
-
// while the cursor still pointed behind them. Now a run is applied whole or
|
|
309
|
-
// not at all, and an interrupted sync simply redoes its work next time.
|
|
310
|
-
const write = index.transaction(() => {
|
|
311
|
-
for (const row of statement.iterate(cursor)) {
|
|
312
|
-
scanned += 1;
|
|
313
|
-
try {
|
|
314
|
-
const sessionMeta = meta.get(row.session_id) ?? { title: "", dir: "" };
|
|
315
|
-
for (const doc of docsFromMessage(row, sessionMeta)) {
|
|
316
|
-
remove.run(doc.key);
|
|
317
|
-
insert.run(doc.text, doc.key, doc.sessionId, doc.kind, doc.ts, doc.title, doc.dir);
|
|
318
|
-
indexed += 1;
|
|
319
|
-
}
|
|
320
|
-
} catch {
|
|
321
|
-
// One unreadable message must not abandon the other forty thousand.
|
|
322
|
-
skipped += 1;
|
|
323
|
-
}
|
|
324
|
-
if (row.time_updated > high) high = row.time_updated;
|
|
325
|
-
}
|
|
326
|
-
setMeta(index, "cursor", String(high));
|
|
327
|
-
setMeta(index, "synced_at", String(Date.now()));
|
|
328
|
-
});
|
|
329
|
-
|
|
330
|
-
write();
|
|
331
|
-
return { indexed, scanned, skipped };
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
// ---------------------------------------------------------------------------
|
|
335
|
-
// V2 API source (primary)
|
|
336
|
-
// ---------------------------------------------------------------------------
|
|
337
|
-
|
|
338
|
-
/**
|
|
339
|
-
* The documented `opencode api` CLI, shelled directly — no token, port, or
|
|
340
|
-
* header scheme is invented here; the CLI owns the host's auth. The override
|
|
341
|
-
* exists so tests and the forced-fallback demonstration can point the API at a
|
|
342
|
-
* binary that does not exist; unset, it shells the `opencode` on PATH.
|
|
343
|
-
*/
|
|
344
|
-
function apiBin(): string {
|
|
345
|
-
return process.env["LOGBOOK_API_BIN"] ?? Bun.which("opencode") ?? "opencode";
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/** An API read that failed or returned something unusable. Triggers fallback. */
|
|
349
|
-
class ApiUnavailable extends Error {}
|
|
350
|
-
|
|
351
|
-
/** One `opencode api get <path>`. Never throws: the caller decides what a failure means. */
|
|
352
|
-
function apiGet(path: string): { ok: true; body: unknown } | { ok: false; reason: string } {
|
|
353
|
-
try {
|
|
354
|
-
const proc = Bun.spawnSync([apiBin(), "api", "get", path], { stdout: "pipe", stderr: "pipe" });
|
|
355
|
-
if (proc.exitCode !== 0) {
|
|
356
|
-
return { ok: false, reason: proc.stderr.toString().trim().slice(0, 200) || `exit ${proc.exitCode}` };
|
|
357
|
-
}
|
|
358
|
-
const text = proc.stdout.toString().trim();
|
|
359
|
-
if (text === "") return { ok: false, reason: "empty response" };
|
|
360
|
-
return { ok: true, body: JSON.parse(text) };
|
|
361
|
-
} catch (error) {
|
|
362
|
-
return { ok: false, reason: String(error).slice(0, 200) };
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
interface ApiPage {
|
|
367
|
-
readonly items: Record<string, unknown>[];
|
|
368
|
-
readonly next: string | undefined;
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/** Every list endpoint shares `{ data: [...], cursor: { next } }`. */
|
|
372
|
-
function readPage(body: unknown, what: string): ApiPage {
|
|
373
|
-
const record = asRecord(body);
|
|
374
|
-
const data = record?.["data"];
|
|
375
|
-
if (!Array.isArray(data)) throw new ApiUnavailable(`${what}: unexpected response shape`);
|
|
376
|
-
const cursor = asRecord(record?.["cursor"]);
|
|
377
|
-
return {
|
|
378
|
-
items: data.filter((item): item is Record<string, unknown> => asRecord(item) !== undefined),
|
|
379
|
-
next: asText(cursor?.["next"]),
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
/**
|
|
384
|
-
* Walks a list endpoint newest-first until `visit` returns false or the cursor
|
|
385
|
-
* is exhausted. Each call carries a single query parameter on purpose: on
|
|
386
|
-
* Windows `opencode` is a `.cmd` shim and Bun refuses to pass `&` to it, so
|
|
387
|
-
* `?limit=…&cursor=…` cannot be used. Newest-first is also the order ingest
|
|
388
|
-
* wants, so no `order` parameter is needed either.
|
|
389
|
-
*/
|
|
390
|
-
function apiWalk(
|
|
391
|
-
what: string,
|
|
392
|
-
firstPage: string,
|
|
393
|
-
cursorPage: (cursor: string) => string,
|
|
394
|
-
visit: (item: Record<string, unknown>) => boolean,
|
|
395
|
-
): void {
|
|
396
|
-
let path = firstPage;
|
|
397
|
-
for (let page = 0; page < 100_000; page += 1) {
|
|
398
|
-
const response = apiGet(path);
|
|
399
|
-
if (!response.ok) throw new ApiUnavailable(`${what}: ${response.reason}`);
|
|
400
|
-
const { items, next } = readPage(response.body, what);
|
|
401
|
-
let goOn = true;
|
|
402
|
-
for (const item of items) if (!visit(item)) goOn = false;
|
|
403
|
-
if (!goOn || next === undefined || items.length === 0) return;
|
|
404
|
-
path = cursorPage(next);
|
|
405
|
-
}
|
|
406
|
-
throw new ApiUnavailable(`${what}: pagination did not terminate`);
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/** The session fields the index needs, as the API exposes them. */
|
|
410
|
-
interface ApiSession {
|
|
411
|
-
readonly id: string;
|
|
412
|
-
readonly title: string;
|
|
413
|
-
readonly dir: string;
|
|
414
|
-
readonly created: number;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
/** The API reports native path separators; the host table stores forward slashes.
|
|
418
|
-
* Normalise so switching sources never changes an indexed value. */
|
|
419
|
-
export const normDir = (value: unknown): string => (asText(value) ?? "").replace(/\\/g, "/");
|
|
420
|
-
|
|
421
|
-
function sessionFromApi(raw: Record<string, unknown>): ApiSession {
|
|
422
|
-
const id = asText(raw["id"]);
|
|
423
|
-
const created = asRecord(raw["time"])?.["created"];
|
|
424
|
-
if (id === undefined || typeof created !== "number") throw new ApiUnavailable("session list: missing id or time");
|
|
425
|
-
const location = asRecord(raw["location"]);
|
|
426
|
-
return { id, title: asText(raw["title"]) ?? "", dir: normDir(location?.["directory"]), created };
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
/** Ids of the sessions the host currently reports as running. */
|
|
430
|
-
function apiActiveIds(): Set<string> {
|
|
431
|
-
const response = apiGet("/api/session/active");
|
|
432
|
-
if (!response.ok) throw new ApiUnavailable(`active sessions: ${response.reason}`);
|
|
433
|
-
const data = asRecord(asRecord(response.body)?.["data"]);
|
|
434
|
-
return new Set(data === undefined ? [] : Object.keys(data));
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
/**
|
|
438
|
-
* Adapts an API message to the row shape `docsFromMessage` already understands.
|
|
439
|
-
* The API flattens the payload to the top level and moves the timestamp into
|
|
440
|
-
* `time`; removing exactly those three keys reproduces the host's `data` blob,
|
|
441
|
-
* so both sources feed identical extraction.
|
|
442
|
-
*/
|
|
443
|
-
export function rowFromApiMessage(sessionId: string, raw: Record<string, unknown>): MessageRow | undefined {
|
|
444
|
-
const id = asText(raw["id"]);
|
|
445
|
-
const type = asText(raw["type"]);
|
|
446
|
-
const created = asRecord(raw["time"])?.["created"];
|
|
447
|
-
if (id === undefined || type === undefined || typeof created !== "number") return undefined;
|
|
448
|
-
const payload: Record<string, unknown> = { ...raw };
|
|
449
|
-
delete payload["id"];
|
|
450
|
-
delete payload["time"];
|
|
451
|
-
delete payload["type"];
|
|
452
|
-
return { id, session_id: sessionId, type, time_created: created, data: JSON.stringify(payload) };
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
const API_FLUSH_DOCS = 2_000;
|
|
456
|
-
|
|
457
|
-
/**
|
|
458
|
-
* Builds the index from the V2 API.
|
|
459
|
-
*
|
|
460
|
-
* Change detection is per session, because the API exposes no global
|
|
461
|
-
* "messages since" cursor and a session's `time.updated` does not move when it
|
|
462
|
-
* gains messages. Candidates are: sessions created since the last run, plus
|
|
463
|
-
* sessions the host reports as running. Messages are read newest-first and stop
|
|
464
|
-
* at a per-session high-water mark, so a re-run only pays for new messages.
|
|
465
|
-
* `--reindex` (force) walks every session.
|
|
466
|
-
*/
|
|
467
|
-
function syncFromApi(index: Database, force: boolean): SyncResult {
|
|
468
|
-
const active = apiActiveIds();
|
|
469
|
-
const storedCursor = force ? 0 : Number(getMeta(index, "api_session_cursor") ?? "0");
|
|
470
|
-
|
|
471
|
-
const sessions = new Map<string, ApiSession>();
|
|
472
|
-
const candidates = new Set<string>();
|
|
473
|
-
let highestCreated = 0;
|
|
474
|
-
let enumerated = 0;
|
|
475
|
-
|
|
476
|
-
apiWalk(
|
|
477
|
-
"session list",
|
|
478
|
-
"/api/session?limit=100",
|
|
479
|
-
(cursor) => `/api/session?cursor=${encodeURIComponent(cursor)}`,
|
|
480
|
-
(raw) => {
|
|
481
|
-
const session = sessionFromApi(raw);
|
|
482
|
-
enumerated += 1;
|
|
483
|
-
if (session.created > highestCreated) highestCreated = session.created;
|
|
484
|
-
sessions.set(session.id, session);
|
|
485
|
-
const isNew = session.created > storedCursor;
|
|
486
|
-
if (force || isNew || active.has(session.id)) candidates.add(session.id);
|
|
487
|
-
return force || isNew; // newest-first: past the cursor, nothing older is new
|
|
488
|
-
},
|
|
489
|
-
);
|
|
490
|
-
if (enumerated === 0) throw new ApiUnavailable("session list: empty");
|
|
491
|
-
|
|
492
|
-
// A session can be running long before the cursor was set; pick those up too.
|
|
493
|
-
for (const id of active) {
|
|
494
|
-
if (sessions.has(id)) continue;
|
|
495
|
-
candidates.add(id);
|
|
496
|
-
const response = apiGet(`/api/session/${encodeURIComponent(id)}`);
|
|
497
|
-
if (!response.ok) throw new ApiUnavailable(`session ${id}: ${response.reason}`);
|
|
498
|
-
const wrapped = asRecord(response.body);
|
|
499
|
-
const raw = asRecord(wrapped?.["data"]) ?? wrapped;
|
|
500
|
-
const location = asRecord(raw?.["location"]);
|
|
501
|
-
sessions.set(id, { id, title: asText(raw?.["title"]) ?? "", dir: normDir(location?.["directory"]), created: 0 });
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
const remove = index.query("delete from docs where doc_key = ?");
|
|
505
|
-
const insert = index.query(
|
|
506
|
-
"insert into docs(text, doc_key, session_id, kind, ts, title, dir) values(?, ?, ?, ?, ?, ?, ?)",
|
|
507
|
-
);
|
|
508
|
-
|
|
509
|
-
let buffered: Doc[] = [];
|
|
510
|
-
const marks = new Map<string, number>();
|
|
511
|
-
let indexed = 0;
|
|
512
|
-
let scanned = 0;
|
|
513
|
-
let skipped = 0;
|
|
514
|
-
|
|
515
|
-
// Batched so a full scan neither holds the corpus in memory nor fsyncs once
|
|
516
|
-
// per document. The session cursor advances only once the whole walk
|
|
517
|
-
// succeeded, so an interrupted run re-enumerates rather than skipping.
|
|
518
|
-
const flush = (advanceCursor: boolean): void => {
|
|
519
|
-
index.transaction(() => {
|
|
520
|
-
for (const doc of buffered) {
|
|
521
|
-
remove.run(doc.key);
|
|
522
|
-
insert.run(doc.text, doc.key, doc.sessionId, doc.kind, doc.ts, doc.title, doc.dir);
|
|
523
|
-
indexed += 1;
|
|
524
|
-
}
|
|
525
|
-
buffered = [];
|
|
526
|
-
for (const [id, mark] of marks) setMeta(index, `api_seen:${id}`, String(mark));
|
|
527
|
-
marks.clear();
|
|
528
|
-
if (advanceCursor) setMeta(index, "api_session_cursor", String(Math.max(storedCursor, highestCreated)));
|
|
529
|
-
setMeta(index, "synced_at", String(Date.now()));
|
|
530
|
-
})();
|
|
531
|
-
};
|
|
532
|
-
|
|
533
|
-
for (const id of candidates) {
|
|
534
|
-
const session = sessions.get(id);
|
|
535
|
-
const sessionMeta: SessionMeta =
|
|
536
|
-
session === undefined ? { title: "", dir: "" } : { title: session.title, dir: session.dir };
|
|
537
|
-
const mark = force ? 0 : Number(getMeta(index, `api_seen:${id}`) ?? "0");
|
|
538
|
-
let newest = mark;
|
|
539
|
-
apiWalk(
|
|
540
|
-
`messages for ${id}`,
|
|
541
|
-
`/api/session/${encodeURIComponent(id)}/message?limit=100`,
|
|
542
|
-
(cursor) => `/api/session/${encodeURIComponent(id)}/message?cursor=${encodeURIComponent(cursor)}`,
|
|
543
|
-
(raw) => {
|
|
544
|
-
const row = rowFromApiMessage(id, raw);
|
|
545
|
-
if (row === undefined) return true; // tolerate one odd message
|
|
546
|
-
if (row.time_created <= mark && !force) return false; // older pages are already indexed
|
|
547
|
-
if (row.time_created > newest) newest = row.time_created;
|
|
548
|
-
scanned += 1;
|
|
549
|
-
try {
|
|
550
|
-
buffered.push(...docsFromMessage(row, sessionMeta));
|
|
551
|
-
} catch {
|
|
552
|
-
skipped += 1;
|
|
553
|
-
}
|
|
554
|
-
return true;
|
|
555
|
-
},
|
|
556
|
-
);
|
|
557
|
-
marks.set(id, newest);
|
|
558
|
-
if (buffered.length >= API_FLUSH_DOCS) flush(false);
|
|
559
|
-
}
|
|
560
|
-
flush(true);
|
|
561
|
-
|
|
562
|
-
return { indexed, scanned, skipped };
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
export interface IngestResult extends SyncResult {
|
|
566
|
-
readonly source: "api" | "db";
|
|
567
|
-
readonly fallbackReason?: string;
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
/**
|
|
571
|
-
* Ingest from the V2 API, falling back to the read-only host database when the
|
|
572
|
-
* API is unavailable, errors, or returns nothing usable. The fallback is
|
|
573
|
-
* recorded in `meta` and returned to the caller; it is never silent.
|
|
574
|
-
*/
|
|
575
|
-
export function ingest(index: Database, source: Database | undefined, force: boolean): IngestResult {
|
|
576
|
-
try {
|
|
577
|
-
const result = syncFromApi(index, force);
|
|
578
|
-
setMeta(index, "last_source", "api");
|
|
579
|
-
return { ...result, source: "api" };
|
|
580
|
-
} catch (error) {
|
|
581
|
-
if (!(error instanceof ApiUnavailable) || source === undefined) throw error;
|
|
582
|
-
const result = sync(index, source, force);
|
|
583
|
-
const reason = error.message === "" ? "api unavailable" : error.message;
|
|
584
|
-
setMeta(index, "last_source", "db");
|
|
585
|
-
setMeta(index, "last_fallback_reason", reason);
|
|
586
|
-
return { ...result, source: "db", fallbackReason: reason };
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
// ---------------------------------------------------------------------------
|
|
591
|
-
// Search
|
|
592
|
-
// ---------------------------------------------------------------------------
|
|
593
|
-
|
|
594
|
-
/**
|
|
595
|
-
* FTS5 treats punctuation as syntax, and error messages are full of it. Every
|
|
596
|
-
* term is quoted, so an input like `bun test (fail)` is a search rather than a
|
|
597
|
-
* parse error.
|
|
598
|
-
*/
|
|
599
|
-
export function toMatchQuery(input: string, mode: "all" | "any"): string {
|
|
600
|
-
const tokens = input.toLowerCase().match(/[a-z0-9_]{3,}/g) ?? [];
|
|
601
|
-
const unique = [...new Set(tokens)].slice(0, 24);
|
|
602
|
-
if (unique.length === 0) return "";
|
|
603
|
-
const joiner = mode === "any" ? " OR " : " AND ";
|
|
604
|
-
return unique.map((token) => `"${token}"`).join(joiner);
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
export interface Hit {
|
|
608
|
-
readonly sessionId: string;
|
|
609
|
-
readonly kind: string;
|
|
610
|
-
readonly ts: number;
|
|
611
|
-
readonly title: string;
|
|
612
|
-
readonly dir: string;
|
|
613
|
-
readonly snippet: string;
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
export function search(index: Database, match: string, limit: number): Hit[] {
|
|
617
|
-
if (match === "") return [];
|
|
618
|
-
return index
|
|
619
|
-
.query<Hit, [string, number]>(
|
|
620
|
-
`select session_id as sessionId, kind, ts, title, dir,
|
|
621
|
-
snippet(docs, 0, '<<', '>>', ' … ', 16) as snippet
|
|
622
|
-
from docs
|
|
623
|
-
where docs match ?
|
|
624
|
-
order by bm25(docs), ts desc
|
|
625
|
-
limit ?`,
|
|
626
|
-
)
|
|
627
|
-
.all(match, limit);
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
// ---------------------------------------------------------------------------
|
|
631
|
-
// Output
|
|
632
|
-
// ---------------------------------------------------------------------------
|
|
633
|
-
|
|
634
|
-
const shortId = (id: string): string => id.slice(0, 8);
|
|
635
|
-
const day = (ts: number): string => new Date(ts).toISOString().slice(0, 10);
|
|
636
|
-
|
|
637
|
-
function printHits(hits: readonly Hit[]): void {
|
|
638
|
-
if (hits.length === 0) {
|
|
639
|
-
console.log("no matches.");
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
const sessions = new Set(hits.map((hit) => hit.sessionId)).size;
|
|
643
|
-
console.log(`${hits.length} hit(s) across ${sessions} session(s)\n`);
|
|
644
|
-
for (const hit of hits) {
|
|
645
|
-
const title = hit.title.trim() === "" ? "(untitled)" : hit.title.trim();
|
|
646
|
-
console.log(`${shortId(hit.sessionId)} ${day(hit.ts)} [${hit.kind}] ${title}`);
|
|
647
|
-
console.log(` ${hit.snippet.replace(/\s+/g, " ").trim()}\n`);
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
// ---------------------------------------------------------------------------
|
|
652
|
-
// CLI
|
|
653
|
-
// ---------------------------------------------------------------------------
|
|
654
|
-
|
|
655
|
-
interface Args {
|
|
656
|
-
readonly command: "search" | "precedent" | "stats" | "reindex" | "help";
|
|
657
|
-
readonly query: string;
|
|
658
|
-
readonly json: boolean;
|
|
659
|
-
readonly limit: number;
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
function parseArgs(argv: readonly string[]): Args {
|
|
663
|
-
const rest: string[] = [];
|
|
664
|
-
let command: Args["command"] = "search";
|
|
665
|
-
let json = false;
|
|
666
|
-
let limit = 0;
|
|
667
|
-
|
|
668
|
-
for (const arg of argv) {
|
|
669
|
-
if (arg === "--json") json = true;
|
|
670
|
-
else if (arg === "--stats") command = "stats";
|
|
671
|
-
else if (arg === "--reindex") command = "reindex";
|
|
672
|
-
else if (arg === "--help" || arg === "-h") command = "help";
|
|
673
|
-
else if (arg === "--precedent") command = command === "search" ? "precedent" : command;
|
|
674
|
-
else if (arg.startsWith("--limit=")) limit = Number(arg.slice(8)) || 0;
|
|
675
|
-
else rest.push(arg);
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
return { command, query: rest.join(" ").trim(), json, limit };
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
const USAGE = `logbook — search your OpenCode history
|
|
682
|
-
|
|
683
|
-
logbook "<query>" search every session you have run
|
|
684
|
-
logbook --precedent "<err>" find prior occurrences of a failure
|
|
685
|
-
logbook --precedent read the failure from stdin
|
|
686
|
-
logbook --stats what is indexed
|
|
687
|
-
logbook --reindex rebuild the index from scratch
|
|
688
|
-
logbook --json machine-readable output
|
|
689
|
-
logbook --limit=N cap the number of hits
|
|
690
|
-
|
|
691
|
-
Index: ${INDEX_DB}
|
|
692
|
-
Primary source: the running host's V2 session API (via \`opencode api\`)
|
|
693
|
-
Fallback source: ${SOURCE_DB} (read-only)`;
|
|
694
|
-
|
|
695
|
-
async function readStdin(): Promise<string> {
|
|
696
|
-
if (process.stdin.isTTY) return "";
|
|
697
|
-
const chunks: Buffer[] = [];
|
|
698
|
-
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
699
|
-
return Buffer.concat(chunks).toString("utf8");
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
async function main(): Promise<number> {
|
|
703
|
-
const args = parseArgs(process.argv.slice(2));
|
|
704
|
-
|
|
705
|
-
if (args.command === "help") {
|
|
706
|
-
console.log(USAGE);
|
|
707
|
-
return 0;
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
if (args.command === "reindex") {
|
|
711
|
-
if (existsSync(INDEX_DB)) rmSync(INDEX_DB, { force: true });
|
|
712
|
-
console.log("index cleared.");
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
const index = openIndex();
|
|
716
|
-
|
|
717
|
-
// The database is the fallback now, so its absence is not fatal on its own —
|
|
718
|
-
// the API may still serve history. Opened read-only, as always.
|
|
719
|
-
let source: Database | undefined;
|
|
720
|
-
if (existsSync(SOURCE_DB)) {
|
|
721
|
-
try {
|
|
722
|
-
// The one promise that matters: this is a reader, never a writer.
|
|
723
|
-
source = new Database(SOURCE_DB, { readonly: true });
|
|
724
|
-
} catch {
|
|
725
|
-
source = undefined;
|
|
726
|
-
}
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
let stats: IngestResult;
|
|
730
|
-
try {
|
|
731
|
-
stats = ingest(index, source, args.command === "reindex");
|
|
732
|
-
} catch (error) {
|
|
733
|
-
console.error(`logbook: no history found at ${SOURCE_DB} (${String(error)})`);
|
|
734
|
-
return 1;
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
if (stats.fallbackReason !== undefined) {
|
|
738
|
-
console.error(`logbook: V2 API unavailable (${stats.fallbackReason}); read from ${SOURCE_DB} instead.`);
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
if (args.command === "stats") {
|
|
742
|
-
const totals = index
|
|
743
|
-
.query<{ docs: number; sessions: number; first: number; last: number }, []>(
|
|
744
|
-
"select count(*) as docs, count(distinct session_id) as sessions, min(ts) as first, max(ts) as last from docs",
|
|
745
|
-
)
|
|
746
|
-
.get();
|
|
747
|
-
const payload = {
|
|
748
|
-
documents: totals?.docs ?? 0,
|
|
749
|
-
sessions: totals?.sessions ?? 0,
|
|
750
|
-
first: totals?.first ?? 0,
|
|
751
|
-
last: totals?.last ?? 0,
|
|
752
|
-
syncedNow: stats.indexed,
|
|
753
|
-
skipped: stats.skipped,
|
|
754
|
-
index: INDEX_DB,
|
|
755
|
-
source: SOURCE_DB,
|
|
756
|
-
ingest: stats.source,
|
|
757
|
-
fallback: stats.fallbackReason ?? null,
|
|
758
|
-
};
|
|
759
|
-
if (args.json) console.log(JSON.stringify(payload, null, 2));
|
|
760
|
-
else {
|
|
761
|
-
console.log(`documents ${payload.documents}`);
|
|
762
|
-
console.log(`sessions ${payload.sessions}`);
|
|
763
|
-
console.log(`range ${day(payload.first)} .. ${day(payload.last)}`);
|
|
764
|
-
console.log(`new now ${payload.syncedNow}`);
|
|
765
|
-
if (payload.skipped > 0) console.log(`skipped ${payload.skipped} (unreadable)`);
|
|
766
|
-
console.log(`ingest ${payload.ingest === "api" ? "v2 api" : "host database"}`);
|
|
767
|
-
if (payload.fallback !== null) console.log(`fallback ${payload.fallback}`);
|
|
768
|
-
console.log(`index ${payload.index}`);
|
|
769
|
-
}
|
|
770
|
-
return 0;
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
const isPrecedent = args.command === "precedent";
|
|
774
|
-
let query = args.query;
|
|
775
|
-
if (isPrecedent && query === "") query = (await readStdin()).trim();
|
|
776
|
-
|
|
777
|
-
if (query === "") {
|
|
778
|
-
console.log(USAGE);
|
|
779
|
-
return isPrecedent ? 1 : 0;
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
const match = toMatchQuery(query, isPrecedent ? "any" : "all");
|
|
783
|
-
const hits = search(index, match, args.limit > 0 ? args.limit : isPrecedent ? 6 : 14);
|
|
784
|
-
|
|
785
|
-
if (args.json) {
|
|
786
|
-
console.log(JSON.stringify({ query, mode: args.command, hits }, null, 2));
|
|
787
|
-
return 0;
|
|
788
|
-
}
|
|
789
|
-
if (isPrecedent) {
|
|
790
|
-
console.log(`precedent for: ${query.replace(/\s+/g, " ").slice(0, 120)}\n`);
|
|
791
|
-
}
|
|
792
|
-
printHits(hits);
|
|
793
|
-
return 0;
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
// Importing this module (from the test suite) must not run the CLI.
|
|
797
|
-
if (import.meta.main) process.exit(await main());
|