chapterhouse 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/server.js +14 -8
- package/dist/api/server.test.js +30 -0
- package/dist/copilot/orchestrator.js +4 -4
- package/dist/copilot/turn-event-log.js +35 -15
- package/dist/copilot/turn-event-log.test.js +31 -0
- package/dist/memory/eot.test.js +3 -3
- package/dist/memory/housekeeping.test.js +26 -26
- package/dist/store/db.js +336 -9
- package/dist/store/db.test.js +393 -7
- package/package.json +1 -1
- package/web/dist/assets/{index-DmYLALt0.js → index-B_cCSHan.js} +52 -52
- package/web/dist/assets/index-B_cCSHan.js.map +1 -0
- package/web/dist/index.html +1 -1
- package/web/dist/assets/index-DmYLALt0.js.map +0 -1
package/dist/store/db.js
CHANGED
|
@@ -1,11 +1,25 @@
|
|
|
1
1
|
import Database from "better-sqlite3";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
2
3
|
import { ensureChapterhouseHome, getDbPath } from "../paths.js";
|
|
3
4
|
let db;
|
|
4
5
|
let logInsertCount = 0;
|
|
5
6
|
let fts5Available = false;
|
|
7
|
+
let currentDaemonRunId;
|
|
8
|
+
let daemonRunRecorded = false;
|
|
6
9
|
function hasColumn(database, table, column) {
|
|
7
10
|
return database.prepare(`PRAGMA table_info(${table})`).all().some((entry) => entry.name === column);
|
|
8
11
|
}
|
|
12
|
+
export function getCurrentRunId() {
|
|
13
|
+
currentDaemonRunId ??= randomUUID();
|
|
14
|
+
return currentDaemonRunId;
|
|
15
|
+
}
|
|
16
|
+
function recordCurrentDaemonRun(database) {
|
|
17
|
+
if (daemonRunRecorded) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
database.prepare(`INSERT OR IGNORE INTO daemon_runs (run_id) VALUES (?)`).run(getCurrentRunId());
|
|
21
|
+
daemonRunRecorded = true;
|
|
22
|
+
}
|
|
9
23
|
function memoryTierCase(tableAlias = "") {
|
|
10
24
|
const prefix = tableAlias ? `${tableAlias}.` : "";
|
|
11
25
|
return `
|
|
@@ -209,6 +223,272 @@ const MEMORY_SCOPE_SEEDS = [
|
|
|
209
223
|
keywords: ["brian"],
|
|
210
224
|
},
|
|
211
225
|
];
|
|
226
|
+
const CHAPTERHOUSE_WIKI_INDEX_SOURCE = "wiki:pages/projects/chapterhouse/index.md";
|
|
227
|
+
const CHAPTERHOUSE_WIKI_HOT_TIER_REASON = "P6 PR1 wiki migration hot-tier candidate";
|
|
228
|
+
const CHAPTERHOUSE_WIKI_DECISION_HOT_TIER_REASON = "P6 PR2 wiki migration hot-tier candidate";
|
|
229
|
+
const CHAPTERHOUSE_PROJECT_ENTITY_SEED = {
|
|
230
|
+
name: "Chapterhouse",
|
|
231
|
+
kind: "project",
|
|
232
|
+
summary: "Always-on team-level AI assistant daemon that orchestrates specialist subagents and maintains a persistent knowledge wiki.",
|
|
233
|
+
};
|
|
234
|
+
const CHAPTERHOUSE_WIKI_OBSERVATION_SEEDS = [
|
|
235
|
+
{
|
|
236
|
+
content: "Chapterhouse architecture: Node.js daemon, web UI, per-conversation sessions, specialist agents, modular skills, MCP servers, local markdown wiki, project-rules prompt injection, and background workers with SSE event streaming.",
|
|
237
|
+
tier: "warm",
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
content: "Chapterhouse source lives at bketelsen/chapterhouse with local checkout ~/projects/chapterhouse; engineering plans are in docs/plans/ and product specs are in docs/prd/.",
|
|
241
|
+
tier: "warm",
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
content: "Background agent completions arrive as automatic system notifications; after spawning a background agent, end the turn and wait instead of polling read_agent, sleeping, or re-checking list_agents.",
|
|
245
|
+
tier: "hot",
|
|
246
|
+
},
|
|
247
|
+
{
|
|
248
|
+
content: "Use the default Chapterhouse chat for research and general questions; move code changes against a specific project into that project's chat session.",
|
|
249
|
+
tier: "warm",
|
|
250
|
+
},
|
|
251
|
+
{
|
|
252
|
+
content: "Squad manages Chapterhouse's own development workflow.",
|
|
253
|
+
tier: "warm",
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
content: "Chapterhouse uses frequent semver patch releases published to npm via the Publish to npm GitHub Actions workflow on tag push; never publish manually.",
|
|
257
|
+
tier: "hot",
|
|
258
|
+
},
|
|
259
|
+
{
|
|
260
|
+
content: "Agent-memory P1 shipped on 2026-05-13 as Chapterhouse v0.4.0 across 7 PRs: #215 through #225.",
|
|
261
|
+
tier: "warm",
|
|
262
|
+
},
|
|
263
|
+
{
|
|
264
|
+
content: "The v0.3.2 per-session orchestrator was confirmed under real concurrent load on 2026-05-08, enabling concurrent sessions without cross-blocking.",
|
|
265
|
+
tier: "hot",
|
|
266
|
+
},
|
|
267
|
+
];
|
|
268
|
+
const CHAPTERHOUSE_WIKI_DECISION_SEEDS = [
|
|
269
|
+
{
|
|
270
|
+
title: "Standardize API validation and JSON errors around `src/api/errors.ts`",
|
|
271
|
+
rationale: "Keep one 400/403/404/500 contract across routes instead of ad hoc parsing and responses; `src/api/errors.ts`, `src/api/server.ts`.",
|
|
272
|
+
decidedAt: "2026-05-06",
|
|
273
|
+
tier: "warm",
|
|
274
|
+
},
|
|
275
|
+
{
|
|
276
|
+
title: "Run in standalone mode when neither Entra nor an API token is configured",
|
|
277
|
+
rationale: "Disable auth checks and team sync together so local single-user startup still works; `src/config.ts`, `src/api/auth.ts`.",
|
|
278
|
+
decidedAt: "2026-05-06",
|
|
279
|
+
tier: "warm",
|
|
280
|
+
},
|
|
281
|
+
{
|
|
282
|
+
title: "Use bearer auth for SSE and serialize wiki writes",
|
|
283
|
+
rationale: "`/stream` no longer accepts query tokens, and wiki mutations go through `withWikiWrite()`; `web/src/stream.ts`, `src/wiki/lock.ts`.",
|
|
284
|
+
decidedAt: "2026-05-06",
|
|
285
|
+
tier: "warm",
|
|
286
|
+
},
|
|
287
|
+
{
|
|
288
|
+
title: "Default production to least privilege",
|
|
289
|
+
rationale: "Run as a non-root container, validate env early, and keep CORS and security headers tight in production; `Dockerfile`, `deploy/deploy.sh`, `src/config.ts`.",
|
|
290
|
+
decidedAt: "2026-05-06",
|
|
291
|
+
tier: "warm",
|
|
292
|
+
},
|
|
293
|
+
{
|
|
294
|
+
title: "Keep chat state session-scoped by `sessionKey`",
|
|
295
|
+
rationale: "Conversation history, SSE routing, and frontend buffers stay isolated per session instead of bleeding across chats; `src/store/db.ts`, `web/src/store.ts`.",
|
|
296
|
+
decidedAt: "2026-05-07",
|
|
297
|
+
tier: "warm",
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
title: "Preserve the 3-layer daemon timing contract",
|
|
301
|
+
rationale: "Orchestrator timeout must stay below daemon shutdown grace, which must stay below systemd `TimeoutStopSec`; `README.md`, `src/daemon.ts`, `src/daemon-install.ts`.",
|
|
302
|
+
decidedAt: "2026-05-08",
|
|
303
|
+
tier: "hot",
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
title: "Start WorkIQ MCP auto-install at daemon startup",
|
|
307
|
+
rationale: "Write the MCP entry before the SDK client starts so new sessions see it immediately; issue #33, PR #78.",
|
|
308
|
+
decidedAt: "2026-05-08",
|
|
309
|
+
tier: "warm",
|
|
310
|
+
},
|
|
311
|
+
{
|
|
312
|
+
title: "Use per-session orchestrators instead of a global queue",
|
|
313
|
+
rationale: "`SessionManager` and `SessionRegistry` keep independent queues so one chat cannot block another; issue #74, `src/copilot/session-manager.ts`.",
|
|
314
|
+
decidedAt: "2026-05-08",
|
|
315
|
+
tier: "hot",
|
|
316
|
+
},
|
|
317
|
+
{
|
|
318
|
+
title: "Make wiki path hierarchy the primary navigation model",
|
|
319
|
+
rationale: "`path` drives the tree and breadcrumbs, while `section` remains secondary metadata; `web/src/wiki/index.ts`, `web/src/routes/Wiki.tsx`.",
|
|
320
|
+
decidedAt: "2026-05-06",
|
|
321
|
+
tier: "warm",
|
|
322
|
+
},
|
|
323
|
+
{
|
|
324
|
+
title: "Route wiki breadcrumbs through `selected` state",
|
|
325
|
+
rationale: "Breadcrumb clicks use the same route-state flow as the sidebar so navigation stays predictable; `web/src/components/wiki/WikiBreadcrumbs.tsx`.",
|
|
326
|
+
decidedAt: "2026-05-06",
|
|
327
|
+
tier: "warm",
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
title: "Derive wiki page scope from configured team paths",
|
|
331
|
+
rationale: "The API returns `scope` and the UI shows personal/team indicators without adding new persisted metadata; `src/api/server.ts`, `web/src/components/wiki/WikiScopeIndicator.tsx`.",
|
|
332
|
+
decidedAt: "2026-05-06",
|
|
333
|
+
tier: "warm",
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
title: "Sort sidebar recents by actual project activity",
|
|
337
|
+
rationale: "`last_used_at` replaces registration time so recent projects reflect chat usage rather than signup order; issue #26, PR #30.",
|
|
338
|
+
decidedAt: "2026-05-08",
|
|
339
|
+
tier: "warm",
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
title: "Preload `CHAPTERHOUSE_DISABLE_DOTENV=1` for Node tests",
|
|
343
|
+
rationale: "Tests must not inherit developer-local env files before config singletons initialize; `src/test/setup-env.ts`, `src/config.ts`.",
|
|
344
|
+
decidedAt: "2026-05-06",
|
|
345
|
+
tier: "warm",
|
|
346
|
+
},
|
|
347
|
+
{
|
|
348
|
+
title: "Test API routes through a spawned server process",
|
|
349
|
+
rationale: "Real HTTP coverage catches auth, config preload, error middleware, and wiki I/O behavior that an unexported in-process app would miss; `src/api/server.test.ts`.",
|
|
350
|
+
decidedAt: "2026-05-06",
|
|
351
|
+
tier: "warm",
|
|
352
|
+
},
|
|
353
|
+
{
|
|
354
|
+
title: "Centralize frontend API Zod schemas in `web/src/api-schemas.ts`",
|
|
355
|
+
rationale: "Keep one audit surface for the browser-to-daemon contract and require validated JSON reads; issue #40, PR #63.",
|
|
356
|
+
decidedAt: "2026-05-08",
|
|
357
|
+
tier: "warm",
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
title: "Make frontend test isolation an infrastructure concern",
|
|
361
|
+
rationale: "Vitest globals, `test-setup.ts`, and MSW own cleanup so tests do not hand-roll it; issue #43, PR #62.",
|
|
362
|
+
decidedAt: "2026-05-08",
|
|
363
|
+
tier: "warm",
|
|
364
|
+
},
|
|
365
|
+
{
|
|
366
|
+
title: "Clean `dist/` before `npm test`",
|
|
367
|
+
rationale: "Remove stale compiled artifacts so deleted tests cannot linger in the Node test run; `package.json`.",
|
|
368
|
+
decidedAt: "2026-05-08",
|
|
369
|
+
tier: "warm",
|
|
370
|
+
},
|
|
371
|
+
{
|
|
372
|
+
title: "Adopt `pino` as the backend logger",
|
|
373
|
+
rationale: "Use `childLogger()` everywhere and keep chat content at `debug`, not `info`; issue #13, PR #28.",
|
|
374
|
+
decidedAt: "2026-05-08",
|
|
375
|
+
tier: "warm",
|
|
376
|
+
},
|
|
377
|
+
{
|
|
378
|
+
title: "Keep daemon control as a thin CLI over `src/daemon-install.ts`",
|
|
379
|
+
rationale: "Generate service artifacts in one module and support launchd and systemd user services without a separate control layer; issue #14, PR #24.",
|
|
380
|
+
decidedAt: "2026-05-08",
|
|
381
|
+
tier: "warm",
|
|
382
|
+
},
|
|
383
|
+
{
|
|
384
|
+
title: "Default publish workflows to Node 24+",
|
|
385
|
+
rationale: "npm Trusted Publishing depends on npm 11.5.1+, which Node 22 does not provide; `.github/workflows/npm-publish.yml`.",
|
|
386
|
+
decidedAt: "2026-05-08",
|
|
387
|
+
tier: "warm",
|
|
388
|
+
},
|
|
389
|
+
{
|
|
390
|
+
title: "Make `chapterhouse update` registry-aware",
|
|
391
|
+
rationale: "Registry installs update via npm, while legacy git installs keep the older pull-and-rebuild path; issue #31, PR #32.",
|
|
392
|
+
decidedAt: "2026-05-08",
|
|
393
|
+
tier: "warm",
|
|
394
|
+
},
|
|
395
|
+
{
|
|
396
|
+
title: "Keep markdownlint pragmatic rather than maximalist",
|
|
397
|
+
rationale: "Disable MD060, ignore `.github/agents/**`, and suppress MD041 only where template UX requires it; `.markdownlint-cli2.jsonc`.",
|
|
398
|
+
decidedAt: "2026-05-08",
|
|
399
|
+
tier: "warm",
|
|
400
|
+
},
|
|
401
|
+
{
|
|
402
|
+
title: "Enforce issue-closing references in feature and fix PRs",
|
|
403
|
+
rationale: "PR bodies must include `Closes #N`, `Fixes #N`, or `Resolves #N`, with a documented `no-issue` bypass; PR #60, `.github/workflows/lint-pr-closes.yml`.",
|
|
404
|
+
decidedAt: "2026-05-08",
|
|
405
|
+
tier: "warm",
|
|
406
|
+
},
|
|
407
|
+
{
|
|
408
|
+
title: "Use Conventional Commits for commits and PR titles",
|
|
409
|
+
rationale: "Keep repo history machine-readable and enforce it with commitlint, husky, and PR-title linting; `commitlint.config.js`, `.github/workflows/lint-pr-title.yml`.",
|
|
410
|
+
decidedAt: "2026-05-08",
|
|
411
|
+
tier: "warm",
|
|
412
|
+
},
|
|
413
|
+
];
|
|
414
|
+
function seedChapterhouseWikiIndexMemory(database) {
|
|
415
|
+
database.transaction(() => {
|
|
416
|
+
const chapterhouseScope = database.prepare(`
|
|
417
|
+
SELECT id
|
|
418
|
+
FROM mem_scopes
|
|
419
|
+
WHERE slug = 'chapterhouse'
|
|
420
|
+
`).get();
|
|
421
|
+
if (!chapterhouseScope) {
|
|
422
|
+
throw new Error("Cannot seed Chapterhouse wiki memory because scope 'chapterhouse' does not exist.");
|
|
423
|
+
}
|
|
424
|
+
database.prepare(`
|
|
425
|
+
INSERT INTO mem_entities (scope_id, kind, name, summary, tier, confidence, created_at, updated_at)
|
|
426
|
+
VALUES (?, ?, ?, ?, 'warm', 1.0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
|
427
|
+
ON CONFLICT(scope_id, kind, name) DO UPDATE SET
|
|
428
|
+
summary = excluded.summary,
|
|
429
|
+
updated_at = CURRENT_TIMESTAMP
|
|
430
|
+
`).run(chapterhouseScope.id, CHAPTERHOUSE_PROJECT_ENTITY_SEED.kind, CHAPTERHOUSE_PROJECT_ENTITY_SEED.name, CHAPTERHOUSE_PROJECT_ENTITY_SEED.summary);
|
|
431
|
+
const chapterhouseEntity = database.prepare(`
|
|
432
|
+
SELECT id
|
|
433
|
+
FROM mem_entities
|
|
434
|
+
WHERE scope_id = ? AND kind = ? AND name = ?
|
|
435
|
+
`).get(chapterhouseScope.id, CHAPTERHOUSE_PROJECT_ENTITY_SEED.kind, CHAPTERHOUSE_PROJECT_ENTITY_SEED.name);
|
|
436
|
+
if (!chapterhouseEntity) {
|
|
437
|
+
throw new Error("Cannot seed Chapterhouse wiki observations because the Chapterhouse entity was not created.");
|
|
438
|
+
}
|
|
439
|
+
const insertObservation = database.prepare(`
|
|
440
|
+
INSERT INTO mem_observations (
|
|
441
|
+
scope_id, entity_id, content, source, tier, confidence, tier_pinned_at, tier_reason, created_at
|
|
442
|
+
)
|
|
443
|
+
SELECT ?, ?, ?, ?, ?, 1.0,
|
|
444
|
+
CASE WHEN ? = 'hot' THEN CURRENT_TIMESTAMP ELSE NULL END,
|
|
445
|
+
CASE WHEN ? = 'hot' THEN ? ELSE NULL END,
|
|
446
|
+
CURRENT_TIMESTAMP
|
|
447
|
+
WHERE NOT EXISTS (
|
|
448
|
+
SELECT 1 FROM mem_observations WHERE scope_id = ? AND content = ?
|
|
449
|
+
)
|
|
450
|
+
`);
|
|
451
|
+
const updateObservation = database.prepare(`
|
|
452
|
+
UPDATE mem_observations
|
|
453
|
+
SET entity_id = ?,
|
|
454
|
+
source = ?,
|
|
455
|
+
tier = CASE WHEN ? = 'hot' THEN 'hot' ELSE tier END,
|
|
456
|
+
tier_pinned_at = CASE WHEN ? = 'hot' THEN COALESCE(tier_pinned_at, CURRENT_TIMESTAMP) ELSE tier_pinned_at END,
|
|
457
|
+
tier_reason = CASE WHEN ? = 'hot' THEN ? ELSE tier_reason END
|
|
458
|
+
WHERE scope_id = ? AND content = ?
|
|
459
|
+
`);
|
|
460
|
+
for (const observation of CHAPTERHOUSE_WIKI_OBSERVATION_SEEDS) {
|
|
461
|
+
insertObservation.run(chapterhouseScope.id, chapterhouseEntity.id, observation.content, CHAPTERHOUSE_WIKI_INDEX_SOURCE, observation.tier, observation.tier, observation.tier, CHAPTERHOUSE_WIKI_HOT_TIER_REASON, chapterhouseScope.id, observation.content);
|
|
462
|
+
updateObservation.run(chapterhouseEntity.id, CHAPTERHOUSE_WIKI_INDEX_SOURCE, observation.tier, observation.tier, observation.tier, CHAPTERHOUSE_WIKI_HOT_TIER_REASON, chapterhouseScope.id, observation.content);
|
|
463
|
+
}
|
|
464
|
+
const insertDecision = database.prepare(`
|
|
465
|
+
INSERT INTO mem_decisions (
|
|
466
|
+
scope_id, entity_id, title, rationale, decided_at, tier, tier_pinned_at, tier_reason, created_at
|
|
467
|
+
)
|
|
468
|
+
SELECT ?, ?, ?, ?, ?, ?,
|
|
469
|
+
CASE WHEN ? = 'hot' THEN CURRENT_TIMESTAMP ELSE NULL END,
|
|
470
|
+
CASE WHEN ? = 'hot' THEN ? ELSE NULL END,
|
|
471
|
+
CURRENT_TIMESTAMP
|
|
472
|
+
WHERE NOT EXISTS (
|
|
473
|
+
SELECT 1 FROM mem_decisions WHERE scope_id = ? AND title = ?
|
|
474
|
+
)
|
|
475
|
+
`);
|
|
476
|
+
const updateDecision = database.prepare(`
|
|
477
|
+
UPDATE mem_decisions
|
|
478
|
+
SET entity_id = ?,
|
|
479
|
+
rationale = ?,
|
|
480
|
+
decided_at = ?,
|
|
481
|
+
tier = ?,
|
|
482
|
+
tier_pinned_at = CASE WHEN ? = 'hot' THEN COALESCE(tier_pinned_at, CURRENT_TIMESTAMP) ELSE NULL END,
|
|
483
|
+
tier_reason = CASE WHEN ? = 'hot' THEN ? ELSE NULL END
|
|
484
|
+
WHERE scope_id = ? AND title = ?
|
|
485
|
+
`);
|
|
486
|
+
for (const decision of CHAPTERHOUSE_WIKI_DECISION_SEEDS) {
|
|
487
|
+
insertDecision.run(chapterhouseScope.id, chapterhouseEntity.id, decision.title, decision.rationale, decision.decidedAt, decision.tier, decision.tier, decision.tier, CHAPTERHOUSE_WIKI_DECISION_HOT_TIER_REASON, chapterhouseScope.id, decision.title);
|
|
488
|
+
updateDecision.run(chapterhouseEntity.id, decision.rationale, decision.decidedAt, decision.tier, decision.tier, decision.tier, CHAPTERHOUSE_WIKI_DECISION_HOT_TIER_REASON, chapterhouseScope.id, decision.title);
|
|
489
|
+
}
|
|
490
|
+
})();
|
|
491
|
+
}
|
|
212
492
|
export function getDb() {
|
|
213
493
|
if (!db) {
|
|
214
494
|
ensureChapterhouseHome();
|
|
@@ -267,11 +547,21 @@ export function getDb() {
|
|
|
267
547
|
)
|
|
268
548
|
`);
|
|
269
549
|
db.exec(`
|
|
550
|
+
CREATE TABLE IF NOT EXISTS daemon_runs (
|
|
551
|
+
run_id TEXT PRIMARY KEY,
|
|
552
|
+
started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
553
|
+
)
|
|
554
|
+
`);
|
|
555
|
+
recordCurrentDaemonRun(db);
|
|
556
|
+
db.exec(`
|
|
270
557
|
CREATE TABLE IF NOT EXISTS conversation_log (
|
|
271
558
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
272
559
|
role TEXT NOT NULL CHECK(role IN ('user', 'assistant', 'system', 'agent_completion')),
|
|
273
560
|
content TEXT NOT NULL,
|
|
274
561
|
source TEXT NOT NULL DEFAULT 'unknown',
|
|
562
|
+
session_key TEXT NOT NULL DEFAULT 'default',
|
|
563
|
+
turn_id TEXT,
|
|
564
|
+
run_id TEXT,
|
|
275
565
|
ts DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
276
566
|
)
|
|
277
567
|
`);
|
|
@@ -293,16 +583,27 @@ export function getDb() {
|
|
|
293
583
|
catch {
|
|
294
584
|
// CHECK constraint doesn't allow current synthetic roles — recreate table preserving data
|
|
295
585
|
db.exec(`ALTER TABLE conversation_log RENAME TO conversation_log_old`);
|
|
586
|
+
const oldConvCols = db.prepare(`PRAGMA table_info(conversation_log_old)`).all();
|
|
587
|
+
const oldConvColNames = new Set(oldConvCols.map((column) => column.name));
|
|
588
|
+
const sessionKeySelect = oldConvColNames.has("session_key") ? "session_key" : "'default'";
|
|
589
|
+
const turnIdSelect = oldConvColNames.has("turn_id") ? "turn_id" : "NULL";
|
|
590
|
+
const runIdSelect = oldConvColNames.has("run_id") ? "run_id" : "NULL";
|
|
296
591
|
db.exec(`
|
|
297
592
|
CREATE TABLE conversation_log (
|
|
298
593
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
299
594
|
role TEXT NOT NULL CHECK(role IN ('user', 'assistant', 'system', 'agent_completion')),
|
|
300
595
|
content TEXT NOT NULL,
|
|
301
596
|
source TEXT NOT NULL DEFAULT 'unknown',
|
|
597
|
+
session_key TEXT NOT NULL DEFAULT 'default',
|
|
598
|
+
turn_id TEXT,
|
|
599
|
+
run_id TEXT,
|
|
302
600
|
ts DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
303
601
|
)
|
|
304
602
|
`);
|
|
305
|
-
db.exec(`
|
|
603
|
+
db.exec(`
|
|
604
|
+
INSERT INTO conversation_log (role, content, source, session_key, turn_id, run_id, ts)
|
|
605
|
+
SELECT role, content, source, ${sessionKeySelect}, ${turnIdSelect}, ${runIdSelect}, ts FROM conversation_log_old
|
|
606
|
+
`);
|
|
306
607
|
db.exec(`DROP TABLE conversation_log_old`);
|
|
307
608
|
}
|
|
308
609
|
// New persistent session table — one row per chat session (default or project)
|
|
@@ -321,6 +622,13 @@ export function getDb() {
|
|
|
321
622
|
if (!convCols.some((c) => c.name === 'session_key')) {
|
|
322
623
|
db.exec(`ALTER TABLE conversation_log ADD COLUMN session_key TEXT NOT NULL DEFAULT 'default'`);
|
|
323
624
|
}
|
|
625
|
+
if (!convCols.some((c) => c.name === 'turn_id')) {
|
|
626
|
+
db.exec(`ALTER TABLE conversation_log ADD COLUMN turn_id TEXT`);
|
|
627
|
+
}
|
|
628
|
+
if (!convCols.some((c) => c.name === "run_id")) {
|
|
629
|
+
db.exec(`ALTER TABLE conversation_log ADD COLUMN run_id TEXT`);
|
|
630
|
+
}
|
|
631
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_conversation_log_session_run ON conversation_log(session_key, run_id, id)`);
|
|
324
632
|
// Migrate: add session_key column to agent_tasks if not present
|
|
325
633
|
const taskCols = db.prepare(`PRAGMA table_info(agent_tasks)`).all();
|
|
326
634
|
if (!taskCols.some((c) => c.name === 'session_key')) {
|
|
@@ -384,14 +692,20 @@ export function getDb() {
|
|
|
384
692
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
385
693
|
turn_id TEXT NOT NULL,
|
|
386
694
|
session_key TEXT NOT NULL DEFAULT 'default',
|
|
695
|
+
run_id TEXT,
|
|
387
696
|
seq INTEGER NOT NULL,
|
|
388
697
|
ts INTEGER NOT NULL,
|
|
389
698
|
event_type TEXT NOT NULL,
|
|
390
699
|
payload TEXT NOT NULL
|
|
391
700
|
)
|
|
392
701
|
`);
|
|
702
|
+
const turnEventCols = db.prepare(`PRAGMA table_info(turn_events)`).all();
|
|
703
|
+
if (!turnEventCols.some((c) => c.name === "run_id")) {
|
|
704
|
+
db.exec(`ALTER TABLE turn_events ADD COLUMN run_id TEXT`);
|
|
705
|
+
}
|
|
393
706
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_turn_events_turn_id ON turn_events(turn_id, seq)`);
|
|
394
707
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_turn_events_session_key ON turn_events(session_key, seq)`);
|
|
708
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_turn_events_session_run ON turn_events(session_key, run_id, seq)`);
|
|
395
709
|
db.exec(`
|
|
396
710
|
CREATE TABLE IF NOT EXISTS mem_scopes (
|
|
397
711
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -519,6 +833,7 @@ export function getDb() {
|
|
|
519
833
|
}
|
|
520
834
|
});
|
|
521
835
|
seedMemoryScopes();
|
|
836
|
+
seedChapterhouseWikiIndexMemory(db);
|
|
522
837
|
// Prune conversation log at startup — keep more history for better recovery
|
|
523
838
|
db.prepare(`DELETE FROM conversation_log WHERE id NOT IN (SELECT id FROM conversation_log ORDER BY id DESC LIMIT 1000)`).run();
|
|
524
839
|
// Set up FTS5 for memory search (graceful fallback if not available)
|
|
@@ -646,9 +961,10 @@ export function deleteState(key) {
|
|
|
646
961
|
db.prepare(`DELETE FROM max_state WHERE key = ?`).run(key);
|
|
647
962
|
}
|
|
648
963
|
/** Log a conversation turn (user, assistant, or system). */
|
|
649
|
-
export function logConversation(role, content, source, sessionKey = "default") {
|
|
964
|
+
export function logConversation(role, content, source, sessionKey = "default", turnId) {
|
|
650
965
|
const db = getDb();
|
|
651
|
-
db.prepare(`INSERT INTO conversation_log (role, content, source, session_key) VALUES (?, ?, ?, ?)`)
|
|
966
|
+
db.prepare(`INSERT INTO conversation_log (role, content, source, session_key, turn_id, run_id) VALUES (?, ?, ?, ?, ?, ?)`)
|
|
967
|
+
.run(role, content, source, sessionKey, turnId ?? null, getCurrentRunId());
|
|
652
968
|
// Keep last 1000 entries to support context recovery after session loss
|
|
653
969
|
logInsertCount++;
|
|
654
970
|
if (logInsertCount % 50 === 0) {
|
|
@@ -753,20 +1069,30 @@ export function normalizeSqliteTsToIso(ts) {
|
|
|
753
1069
|
* completion notices are included and mapped to assistant-style turns so reload
|
|
754
1070
|
* matches the live chat rendering path.
|
|
755
1071
|
*/
|
|
756
|
-
export function getSessionMessages(sessionKey, limit) {
|
|
1072
|
+
export function getSessionMessages(sessionKey, limit, options = {}) {
|
|
757
1073
|
const db = getDb();
|
|
758
1074
|
const effectiveLimit = Math.min(limit ?? DEFAULT_SESSION_MESSAGES_LIMIT, MAX_SESSION_MESSAGES_LIMIT);
|
|
759
|
-
const
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
1075
|
+
const includeHistorical = options.includeHistorical ?? false;
|
|
1076
|
+
const runId = options.runId ?? getCurrentRunId();
|
|
1077
|
+
const rows = includeHistorical
|
|
1078
|
+
? db
|
|
1079
|
+
.prepare(`SELECT id, role, content, ts, turn_id FROM conversation_log
|
|
1080
|
+
WHERE session_key = ? AND role IN ('user', 'assistant', 'agent_completion')
|
|
1081
|
+
ORDER BY id DESC LIMIT ?`)
|
|
1082
|
+
.all(sessionKey, effectiveLimit)
|
|
1083
|
+
: db
|
|
1084
|
+
.prepare(`SELECT id, role, content, ts, turn_id FROM conversation_log
|
|
1085
|
+
WHERE session_key = ? AND run_id = ? AND role IN ('user', 'assistant', 'agent_completion')
|
|
1086
|
+
ORDER BY id DESC LIMIT ?`)
|
|
1087
|
+
.all(sessionKey, runId, effectiveLimit);
|
|
764
1088
|
// Reverse so oldest is first (chronological order for the UI)
|
|
765
1089
|
rows.reverse();
|
|
766
1090
|
return rows.map((r) => ({
|
|
1091
|
+
id: r.id,
|
|
767
1092
|
role: r.role === "agent_completion" ? "assistant" : r.role,
|
|
768
1093
|
content: r.content,
|
|
769
1094
|
ts: normalizeSqliteTsToIso(r.ts),
|
|
1095
|
+
turn_id: r.turn_id,
|
|
770
1096
|
}));
|
|
771
1097
|
}
|
|
772
1098
|
/**
|
|
@@ -825,6 +1151,7 @@ export function closeDb() {
|
|
|
825
1151
|
if (db) {
|
|
826
1152
|
db.close();
|
|
827
1153
|
db = undefined;
|
|
1154
|
+
daemonRunRecorded = false;
|
|
828
1155
|
}
|
|
829
1156
|
}
|
|
830
1157
|
//# sourceMappingURL=db.js.map
|