feat(ledger): Gate F, the ledger's T3 thread source (#1506)
packages/ledger/src/t3.mjs reads ~/.t3/userdata/state.sqlite read-only, in one transaction. It maps each thread to a seat by title and checks self-addressed headers. Unmatched threads go in a t3:unmapped row. A missing or locked database exits 1 and names --no-t3. Gate F is on by default (lead decision 12). The 6a uppercase-class fix rides here. Separate item: the Pi session reader splits lines only on \n, so a raw U+2028 or U+2029 in a string no longer splits a record. Node 26.8.1's readline split there, and the live ledger refused on HEAD. Darkwing built to brief R3 (f3c05c1b); manifest ba73a163. Filbert approved the build (e47ec6da) and the U+2028 fix as its own item; brief review be1aa414. On an index export: the eight suites 24/90/43/17/14/15/63/18, ledger 47/47. Four nonblocking notes go to a small follow-up. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, cpSync, symlinkSync } from 'node:fs';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, cpSync, symlinkSync, realpathSync } from 'node:fs';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -9,13 +10,50 @@ import { dateRange, messageKind, issueNumbers, totalsLine, summarize } from '../
|
||||
|
||||
const source = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../src');
|
||||
const range = dateRange('2026-09-06', '2026-09-12');
|
||||
// T3 fixture schema: the live tables, cut to the columns the reader uses plus
|
||||
// one it doesn't. `text` allows NULL so a non-text row can be tested.
|
||||
const T3_SCHEMA = `
|
||||
create table projection_projects (project_id text primary key, title text not null, workspace_root text not null, deleted_at text);
|
||||
create table projection_threads (thread_id text primary key, project_id text not null, title text not null, archived_at text, deleted_at text);
|
||||
create table projection_thread_messages (message_id text primary key, thread_id text not null, role text not null, text, created_at text not null);
|
||||
create table orchestration_events (sequence integer primary key autoincrement, stream_id text not null, event_type text not null, payload_json text not null, metadata_json text not null);`;
|
||||
// Writes a T3 database in WAL mode. Threads default to project p1, which is
|
||||
// the fixture root. Returns the open writer when keepOpen is set.
|
||||
function t3db(file, { root, projects, threads = [], messages = [], after = [], keepOpen = false }) {
|
||||
mkdirSync(path.dirname(file), { recursive: true });
|
||||
for (const old of [file, `${file}-wal`, `${file}-shm`]) rmSync(old, { force: true });
|
||||
const db = new DatabaseSync(file);
|
||||
db.exec('pragma journal_mode=wal'); db.exec(T3_SCHEMA);
|
||||
for (const [id, workspace, deleted = null] of projects ?? [['p1', root]]) {
|
||||
db.prepare('insert into projection_projects values (?, ?, ?, ?)').run(id, 'project', workspace, deleted);
|
||||
}
|
||||
for (const t of threads) {
|
||||
db.prepare('insert into projection_threads values (?, ?, ?, ?, ?)').run(t.id, t.project ?? 'p1', t.title, t.archived ?? null, t.deleted ?? null);
|
||||
}
|
||||
for (const m of messages) addMessage(db, m);
|
||||
for (const sql of after) db.exec(sql);
|
||||
if (keepOpen) return db;
|
||||
db.close();
|
||||
}
|
||||
let messageId = 0;
|
||||
function addMessage(db, { thread, text, role = 'user', at = '2026-09-08T12:00:00Z', origin = 'app' }) {
|
||||
const id = `m${++messageId}`;
|
||||
db.prepare('insert into projection_thread_messages values (?, ?, ?, ?, ?)').run(id, thread, role, text, at);
|
||||
if (origin !== 'none') db.prepare('insert into orchestration_events (stream_id, event_type, payload_json, metadata_json) values (?, ?, ?, ?)')
|
||||
.run(thread, 'thread.message-sent', JSON.stringify({ messageId: id, threadId: thread, role, text }), JSON.stringify({ origin: origin === 'app' ? { appVersion: '0.0.0' } : {} }));
|
||||
}
|
||||
const fixtureIssues = [
|
||||
{ number: 1, title: 'First issue', created_at: '2026-09-06T00:00:00Z', closed_at: '2026-09-07T12:00:00Z' },
|
||||
{ number: 2, title: 'Second issue', created_at: '2026-09-06T00:00:00Z', closed_at: null },
|
||||
];
|
||||
function fixture(t) {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'ledger-test-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
// No test opens the real ~/.t3: every CLI run gets this HOME, with an empty
|
||||
// T3 database at the default path. The CLI's root is a realpath.
|
||||
const home = mkdtempSync(path.join(os.tmpdir(), 'ledger-home-'));
|
||||
t.after(() => { rmSync(root, { recursive: true, force: true }); rmSync(home, { recursive: true, force: true }); });
|
||||
const defaultDb = path.join(home, '.t3/userdata/state.sqlite');
|
||||
t3db(defaultDb, { root: realpathSync(root) });
|
||||
const put = (name, data) => { const p = path.join(root, name); mkdirSync(path.dirname(p), { recursive: true }); writeFileSync(p, data); return p; };
|
||||
const git = (args, date = '2026-09-07T00:00:00Z') => execFileSync('git', args, { cwd: root, env: { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, stdio: 'pipe' });
|
||||
git(['init', '-b', 'refactor']); git(['config', 'user.email', '[email protected]']); git(['config', 'user.name', 'Fixture']);
|
||||
@@ -30,8 +68,8 @@ function fixture(t) {
|
||||
const entry = (text, timestamp = '2026-09-08T12:00:00Z') => ({ type: 'message', timestamp, message: { role: 'user', content: [{ type: 'text', text }] } });
|
||||
const logs = [entry('[host:control-board -> host:alice] do #1'), entry('[host:bob -> host:alice] review #2'), entry('build #2'), entry('old #1', '2026-09-05T23:59:59Z'), { type: 'message', timestamp: '2026-09-08T00:00:00Z', message: { role: 'assistant', content: 'not a user #1' } }];
|
||||
put('.pi/state/alice/sessions/one.jsonl', logs.map(x => JSON.stringify(x)).join('\n') + '\n');
|
||||
const run = (args = [], env = {}) => spawnSync(process.execPath, [path.join(root, 'packages/ledger/src/cli.mjs'), '--since', '2026-09-06', '--until', '2026-09-12', ...args], { cwd: root, encoding: 'utf8', env: { ...process.env, PATH: `${path.join(root, 'bin')}:${process.env.PATH}`, ISSUES: path.join(root, 'issues.json'), CALLS: path.join(root, 'calls.jsonl'), ...env } });
|
||||
return { root, put, commit, run, entry, logs };
|
||||
const run = (args = [], env = {}) => spawnSync(process.execPath, [path.join(root, 'packages/ledger/src/cli.mjs'), '--since', '2026-09-06', '--until', '2026-09-12', ...args], { cwd: root, encoding: 'utf8', env: { ...process.env, HOME: home, PATH: `${path.join(root, 'bin')}:${process.env.PATH}`, ISSUES: path.join(root, 'issues.json'), CALLS: path.join(root, 'calls.jsonl'), ...env } });
|
||||
return { root, real: realpathSync(root), home, defaultDb, put, commit, run, entry, logs };
|
||||
}
|
||||
test('fixture git subjects only, follow-ups and three session kinds', t => {
|
||||
const f = fixture(t), result = f.run(['--json']);
|
||||
@@ -63,7 +101,7 @@ test('missing credentials exit 2, no-issues never calls API and shows unknown',
|
||||
test('empty range gives no rows and zero totals', t => {
|
||||
const f = fixture(t);
|
||||
f.put('issues.json', '[]');
|
||||
const result = spawnSync(process.execPath, [path.join(f.root, 'packages/ledger/src/cli.mjs'), '--since', '2027-01-01', '--until', '2027-01-02', '--json'], { encoding: 'utf8', env: { ...process.env, PATH: `${f.root}/bin:${process.env.PATH}`, ISSUES: `${f.root}/issues.json`, CALLS: `${f.root}/calls.jsonl` } });
|
||||
const result = spawnSync(process.execPath, [path.join(f.root, 'packages/ledger/src/cli.mjs'), '--since', '2027-01-01', '--until', '2027-01-02', '--json'], { encoding: 'utf8', env: { ...process.env, HOME: f.home, PATH: `${f.root}/bin:${process.env.PATH}`, ISSUES: `${f.root}/issues.json`, CALLS: `${f.root}/calls.jsonl` } });
|
||||
assert.equal(result.status, 0, result.stderr); const r = JSON.parse(result.stdout);
|
||||
assert.deepEqual(r.issues, []); assert.deepEqual(r.seats, []); assert.ok(Object.values(r.totals).every(n => n === 0));
|
||||
});
|
||||
@@ -96,6 +134,13 @@ test('partial or malformed session log refuses with location, not content', t =>
|
||||
const f = fixture(t); f.put('.pi/state/alice/sessions/bad.jsonl', '{sensitive'); const r = f.run();
|
||||
assert.equal(r.status, 1); assert.match(r.stderr, /Malformed session JSON: alice\/bad.jsonl:1/); assert.doesNotMatch(r.stderr, /sensitive/);
|
||||
});
|
||||
test('a U+2028 inside a session string is one line, not a malformed record', t => {
|
||||
const f = fixture(t);
|
||||
f.put('.pi/state/bob/sessions/sep.jsonl', [f.entry('Jason: one\u2028two #2'), f.entry('[h:alice -> h:bob] ok')].map(x => JSON.stringify(x)).join('\r\n') + '\r\n');
|
||||
assert.ok(readFileSync(path.join(f.root, '.pi/state/bob/sessions/sep.jsonl'), 'utf8').includes('\u2028'));
|
||||
const r = f.run(['--json']); assert.equal(r.status, 0, r.stderr);
|
||||
assert.deepEqual(JSON.parse(r.stdout).seats[1], { seat: 'bob', board: 0, agent: 1, human: 1 });
|
||||
});
|
||||
test('no sessions is an empty table; symlink source refuses', t => {
|
||||
const f = fixture(t); rmSync(path.join(f.root, '.pi'), { recursive: true });
|
||||
assert.deepEqual(JSON.parse(f.run(['--json']).stdout).seats, []);
|
||||
@@ -140,7 +185,11 @@ test('T3 header: agent, or board from control-board; anything short of the full
|
||||
assert.equal(messageKind(`Jason here\n[from: ${sage} -> to: ${filbert}]\nquoted`), 'human');
|
||||
assert.equal(messageKind(` [from: ${sage} -> to: ${filbert}]`), 'human');
|
||||
assert.equal(messageKind(`[from: sage -> to: filbert]\nno thread ids`), 'human');
|
||||
assert.equal(messageKind(`[from: ${sage} -> to: ${filbert} class=Actionable]`), 'human');
|
||||
// Classes match in either case (Gate F). HEAD before the fix called these human.
|
||||
assert.equal(messageKind(`[from: ${sage} -> to: ${filbert} class=Actionable]`), 'agent');
|
||||
assert.equal(messageKind(`[from: ${sage} -> to: ${filbert} class=REVIEW-REQUEST]\nreview`), 'agent');
|
||||
assert.equal(messageKind('[h:sage -> h:bob class=DECISION] go'), 'agent');
|
||||
assert.equal(messageKind(`[from: ${sage} -> to: ${filbert} class=review_request]`), 'human');
|
||||
assert.equal(messageKind(`[from: ${sage} -> to: ${filbert}]trailing`), 'human');
|
||||
assert.equal(messageKind(`[From: ${sage} -> to: ${filbert}]`), 'human');
|
||||
});
|
||||
@@ -148,3 +197,218 @@ test('no closed issues with human messages means undefined ratio, not invented z
|
||||
const r = summarize(range, [], [], { rows: [{ seat: 'a', human: 1, board: 0, agent: 0 }], mentions: new Map() });
|
||||
assert.equal(r.totals.humanMessagesPerClosedIssue, 'unknown');
|
||||
});
|
||||
|
||||
// T3 thread source (Gate F, docs/plans/2026-09-26_ledger-t3-source.md).
|
||||
const T1 = 't-alice', T2 = 't-bob', T3 = 't-sagebrush', T4 = 't-researcher', T5 = 't-discord';
|
||||
const header = (from, to, toId, cls = '') => `[from: ${from} (x1) -> to: ${to} (${toId})${cls}]`;
|
||||
function t3Fixture(t) {
|
||||
const f = fixture(t);
|
||||
for (const seat of ['sage', 'researcher']) mkdirSync(path.join(f.root, 'agents', seat), { recursive: true });
|
||||
const db = path.join(f.home, 'fixture/t3.sqlite');
|
||||
const threads = [
|
||||
{ id: T1, title: 'Alice' }, { id: T2, title: 'Bob in Claude', archived: '2026-09-09T00:00:00Z' },
|
||||
{ id: T3, title: 'Sagebrush' }, { id: T4, title: 'Researcher' }, { id: T5, title: 'Discord Bot' },
|
||||
{ id: 'import:claudeAgent:1', title: 'alice' }, { id: 't-deleted', title: 'Alice', deleted: '2026-09-09T00:00:00Z' },
|
||||
{ id: 't-other', project: 'p2', title: 'Alice' },
|
||||
];
|
||||
const messages = [
|
||||
{ thread: T1, text: 'Jason: go #1' },
|
||||
{ thread: T1, text: `${header('sage', 'alice', T1, ' class=REVIEW-REQUEST')}\nreview #2`, origin: 'api' },
|
||||
{ thread: T1, text: '[h:sage -> h:alice class=DECISION] go', origin: 'api' },
|
||||
{ thread: T1, text: `${header('control-board', 'alice', T1)}\nbuzz`, origin: 'api' },
|
||||
{ thread: T1, text: 'outside', at: '2026-09-13T00:00:00Z' },
|
||||
{ thread: T1, text: 'an answer #9', role: 'assistant', origin: 'none' },
|
||||
{ thread: T2, text: 'archived still counts #2' },
|
||||
{ thread: T3, text: 'Sagebrush is not sage' },
|
||||
{ thread: T3, text: `${header('sage', 'discord', T3)}\nnot a seat role`, origin: 'api' },
|
||||
{ thread: T4, text: 'research this' },
|
||||
{ thread: T5, text: '[from: SetSpark coordinator (x1) -> to: Discord Bot (x2)]\nfree text', origin: 'api' },
|
||||
{ thread: 'import:claudeAgent:1', text: 'imported' },
|
||||
{ thread: 't-deleted', text: 'deleted' },
|
||||
{ thread: 't-other', text: 'other project' },
|
||||
];
|
||||
const write = (overrides = {}) => t3db(db, { root: f.real, projects: [['p1', f.real], ['p2', '/elsewhere']], threads, messages, ...overrides });
|
||||
return { ...f, db, threads, messages, write };
|
||||
}
|
||||
test('T3: seat, archived, unmapped and Researcher threads count; imported, deleted and other-project threads do not', t => {
|
||||
const f = t3Fixture(t); f.write();
|
||||
const result = f.run(['--json', '--t3-db', f.db]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
const r = JSON.parse(result.stdout);
|
||||
assert.deepEqual(r.seats, [
|
||||
{ seat: 'alice', board: 2, agent: 3, human: 2 }, { seat: 'bob', board: 0, agent: 0, human: 1 },
|
||||
{ seat: 'researcher', board: 0, agent: 0, human: 1 }, { seat: 't3:unmapped', board: 0, agent: 1, human: 2 },
|
||||
]);
|
||||
assert.deepEqual(r.pi, [{ seat: 'alice', board: 1, agent: 1, human: 1 }]);
|
||||
assert.deepEqual(r.t3.database, { path: f.db, default: false });
|
||||
assert.deepEqual(r.t3.seats, [
|
||||
{ seat: 'alice', board: 1, agent: 2, human: 1, threads: [{ id: T1, title: 'Alice', archived: false }] },
|
||||
{ seat: 'bob', board: 0, agent: 0, human: 1, threads: [{ id: T2, title: 'Bob in Claude', archived: true }] },
|
||||
{ seat: 'researcher', board: 0, agent: 0, human: 1, threads: [{ id: T4, title: 'Researcher', archived: false }] },
|
||||
]);
|
||||
assert.deepEqual(r.t3.unmapped, { board: 0, agent: 1, human: 2, threads: [
|
||||
{ id: T5, title: 'Discord Bot', archived: false }, { id: T3, title: 'Sagebrush', archived: false }] });
|
||||
assert.deepEqual(r.t3.excluded, { importedThreads: 1, deletedThreads: 1 });
|
||||
// The free-text header counts as human; only the diagnostic shows it was sent through the API.
|
||||
assert.deepEqual(r.t3.diagnostic, { humanSentThroughApi: 1, humanWithoutEvent: 0 });
|
||||
assert.equal(r.totals.humanMessagesPerClosedIssue, 6);
|
||||
assert.deepEqual(r.issues.map(x => [x.issue, x.seats]), [[1, ['alice']], [2, ['alice', 'bob']]]);
|
||||
const text = f.run(['--t3-db', f.db]);
|
||||
assert.equal(text.status, 0, text.stderr);
|
||||
assert.ok(text.stdout.includes(`T3: read from ${f.db}, not the default`));
|
||||
assert.match(text.stdout, /t3:unmapped \| 0 \| 1 \| 2/);
|
||||
});
|
||||
test('T3: the default path is read from HOME and prints no path line; --no-t3 says so', t => {
|
||||
const f = t3Fixture(t); f.write();
|
||||
rmSync(f.defaultDb); cpSync(f.db, f.defaultDb);
|
||||
const json = JSON.parse(f.run(['--json']).stdout);
|
||||
assert.deepEqual(json.t3.database, { path: f.defaultDb, default: true });
|
||||
assert.equal(json.seats.at(-1).seat, 't3:unmapped');
|
||||
const text = f.run(); assert.equal(text.status, 0, text.stderr); assert.doesNotMatch(text.stdout, /^T3:/m);
|
||||
rmSync(path.join(f.home, '.t3'), { recursive: true });
|
||||
const off = f.run(['--no-t3']); assert.equal(off.status, 0, off.stderr);
|
||||
assert.match(off.stdout, /^T3: not read \(--no-t3\)$/m);
|
||||
const offJson = JSON.parse(f.run(['--no-t3', '--json']).stdout);
|
||||
assert.deepEqual(offJson.t3, { read: false }); assert.deepEqual(offJson.seats, [{ seat: 'alice', board: 1, agent: 1, human: 1 }]);
|
||||
const both = f.run(['--no-t3', '--t3-db', f.db]); assert.equal(both.status, 1); assert.match(both.stderr, /cannot be combined/);
|
||||
assert.equal(f.run(['--t3-db']).status, 1);
|
||||
});
|
||||
test('T3: a HOME with no database exits 1 and names --no-t3', t => {
|
||||
const f = fixture(t); rmSync(path.join(f.home, '.t3'), { recursive: true });
|
||||
const r = f.run(); assert.equal(r.status, 1); assert.equal(r.stdout, '');
|
||||
assert.match(r.stderr, /T3 database unavailable: .*\.t3 is missing or unreadable; use --no-t3/);
|
||||
});
|
||||
test('T3: a file that is not a database exits 1 and names --no-t3', t => {
|
||||
const f = fixture(t); writeFileSync(f.defaultDb, 'not sqlite'.repeat(100));
|
||||
const r = f.run(); assert.equal(r.status, 1); assert.match(r.stderr, /T3 database cannot be read: .*\(SQLite \d+\); use --no-t3/);
|
||||
});
|
||||
test('T3: a seat thread renamed to another seat exits 1 naming thread, title and roles', t => {
|
||||
const f = t3Fixture(t);
|
||||
f.write({ messages: [...f.messages, { thread: T2, text: `${header('sage', 'alice', T2, ' class=INFO')}\nfor alice`, origin: 'api' }] });
|
||||
const r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1);
|
||||
assert.equal(r.stderr.trim(), `T3 header conflict: thread ${T2} "Bob in Claude" maps to bob, but a header addresses alice`);
|
||||
});
|
||||
test('T3: an unmapped thread addressed as a seat exits 1', t => {
|
||||
const f = t3Fixture(t);
|
||||
f.write({ messages: [...f.messages, { thread: T3, text: `${header('bob', 'Sage', T3)}\nhi`, origin: 'api' }] });
|
||||
const r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /thread t-sagebrush "Sagebrush" maps to no seat, but a header addresses Sage/);
|
||||
});
|
||||
test('T3: a header to another thread id is not cross-checked', t => {
|
||||
const f = t3Fixture(t);
|
||||
f.write({ messages: [...f.messages, { thread: T2, text: `${header('sage', 'alice', T1)}\ncopied`, origin: 'api' }] });
|
||||
const r = f.run(['--json', '--t3-db', f.db]); assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(JSON.parse(r.stdout).t3.seats[1].agent, 1);
|
||||
});
|
||||
test('T3: no project, or two, for this root exits 1', t => {
|
||||
const f = t3Fixture(t);
|
||||
f.write({ projects: [['p1', `${f.real}-link`], ['p2', '/elsewhere']] });
|
||||
let r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1); assert.match(r.stderr, /T3 has no project for .*symlink does not match/);
|
||||
f.write({ projects: [['p1', f.real], ['p2', f.real]] });
|
||||
r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1); assert.match(r.stderr, /T3 has more than one project for/);
|
||||
f.write({ projects: [['p1', f.real], ['p2', f.real, '2026-09-01T00:00:00Z']] });
|
||||
assert.equal(f.run(['--t3-db', f.db]).status, 0);
|
||||
});
|
||||
for (const [name, after, pattern] of [
|
||||
['a removed column', ['alter table projection_threads drop column title'], /T3 schema changed: missing projection_threads.title/],
|
||||
['a missing table', ['drop table projection_thread_messages'], /T3 schema changed: missing projection_thread_messages$/m],
|
||||
]) test(`T3: ${name} exits 1 and names it`, t => {
|
||||
const f = t3Fixture(t); f.write({ after, messages: [] });
|
||||
const r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1); assert.match(r.stderr, pattern);
|
||||
});
|
||||
for (const [name, message, pattern] of [
|
||||
['an unknown role', { role: 'system' }, /T3 message m\d+ in thread t-alice has an unknown role/],
|
||||
['non-text content', { text: null }, /has non-text content/],
|
||||
['an unparseable created_at', { at: 'yesterday' }, /has an invalid created_at/],
|
||||
]) test(`T3: a counted row with ${name} exits 1 without its text`, t => {
|
||||
const f = t3Fixture(t);
|
||||
f.write({ messages: [...f.messages, { thread: T1, text: 'secret words', ...message }] });
|
||||
const r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1); assert.match(r.stderr, pattern); assert.doesNotMatch(r.stderr, /secret/);
|
||||
});
|
||||
test('T3: a missing orchestration_events makes the diagnostic unknown and keeps the counts', t => {
|
||||
const f = t3Fixture(t); f.write();
|
||||
const before = JSON.parse(f.run(['--json', '--t3-db', f.db]).stdout);
|
||||
f.write({ after: ['drop table orchestration_events'] });
|
||||
const r = f.run(['--json', '--t3-db', f.db]); assert.equal(r.status, 0, r.stderr);
|
||||
const after = JSON.parse(r.stdout);
|
||||
assert.deepEqual(after.t3.diagnostic, { humanSentThroughApi: 'unknown', humanWithoutEvent: 'unknown' });
|
||||
assert.deepEqual(after.seats, before.seats); assert.deepEqual(after.totals, before.totals);
|
||||
});
|
||||
for (const link of ['.t3', '.t3/userdata', '.t3/userdata/state.sqlite']) test(`T3: a symlink at ~/${link} exits 1`, t => {
|
||||
const f = fixture(t), target = path.join(f.home, 'real', link);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
cpSync(path.join(f.home, link), target, { recursive: true });
|
||||
rmSync(path.join(f.home, link), { recursive: true }); symlinkSync(target, path.join(f.home, link));
|
||||
const r = f.run(); assert.equal(r.status, 1); assert.match(r.stderr, new RegExp(`${link.replaceAll('.', '\\.')} is a symlink; use --no-t3`));
|
||||
});
|
||||
test('T3: with --t3-db, a symlinked file or directory exits 1', t => {
|
||||
const f = t3Fixture(t); f.write();
|
||||
const file = path.join(f.home, 'file-link.sqlite'); symlinkSync(f.db, file);
|
||||
let r = f.run(['--t3-db', file]); assert.equal(r.status, 1); assert.match(r.stderr, /file-link.sqlite is a symlink/);
|
||||
const dir = path.join(f.home, 'dir-link'); symlinkSync(path.dirname(f.db), dir);
|
||||
r = f.run(['--t3-db', path.join(dir, 't3.sqlite')]); assert.equal(r.status, 1); assert.match(r.stderr, /dir-link is a symlink/);
|
||||
});
|
||||
|
||||
// WAL states. The CLI reads with mode=ro; it may create -wal and -shm but must
|
||||
// never change the main file.
|
||||
const sha = file => execFileSync('sha256sum', [file], { encoding: 'utf8' }).split(' ')[0];
|
||||
const humans = r => JSON.parse(r.stdout).t3.seats.find(s => s.seat === 'alice').human;
|
||||
const asRoot = process.getuid?.() === 0;
|
||||
function killedWriter(db) {
|
||||
// A writer that commits into the WAL and dies without a checkpoint.
|
||||
const code = `const { DatabaseSync } = require('node:sqlite'); const db = new DatabaseSync(${JSON.stringify(db)});
|
||||
db.exec('pragma wal_autocheckpoint=0');
|
||||
db.prepare("insert into projection_thread_messages values ('late', 't-alice', 'user', 'late human', '2026-09-08T13:00:00Z')").run();
|
||||
process.kill(process.pid, 'SIGKILL');`;
|
||||
const r = spawnSync(process.execPath, ['-e', code]);
|
||||
assert.equal(r.signal, 'SIGKILL');
|
||||
rmSync(`${db}-shm`);
|
||||
}
|
||||
function inReadOnlyDir(dir, check) {
|
||||
execFileSync('chmod', ['0555', dir]);
|
||||
try { check(); } finally { execFileSync('chmod', ['0755', dir]); }
|
||||
}
|
||||
test('T3 WAL: the newest message only in -wal, writer attached, is counted', t => {
|
||||
const f = t3Fixture(t), writer = f.write({ keepOpen: true });
|
||||
t.after(() => writer.close());
|
||||
writer.exec('pragma wal_autocheckpoint=0');
|
||||
addMessage(writer, { thread: T1, text: 'newest', at: '2026-09-08T13:00:00Z' });
|
||||
const main = sha(f.db);
|
||||
const r = f.run(['--json', '--t3-db', f.db]); assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(humans(r), 2); assert.equal(sha(f.db), main);
|
||||
});
|
||||
test('T3 WAL: stopped cleanly, counts are correct and the main file is unchanged', t => {
|
||||
const f = t3Fixture(t); f.write();
|
||||
assert.throws(() => readFileSync(`${f.db}-wal`));
|
||||
const main = sha(f.db);
|
||||
const r = f.run(['--json', '--t3-db', f.db]); assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(humans(r), 1); assert.equal(sha(f.db), main);
|
||||
});
|
||||
test('T3 WAL: -wal without -shm in a writable directory is read', t => {
|
||||
const f = t3Fixture(t); f.write(); killedWriter(f.db);
|
||||
const main = sha(f.db);
|
||||
const r = f.run(['--json', '--t3-db', f.db]); assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(humans(r), 2); assert.equal(sha(f.db), main);
|
||||
});
|
||||
test('T3 WAL: -wal without -shm in a read-only directory exits 1', { skip: asRoot && 'mode bits do not bind root' }, t => {
|
||||
const f = t3Fixture(t); f.write(); killedWriter(f.db);
|
||||
inReadOnlyDir(path.dirname(f.db), () => {
|
||||
const r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1); assert.match(r.stderr, /cannot be read: .*\(SQLite 14\); use --no-t3/);
|
||||
});
|
||||
});
|
||||
test('T3 WAL: stopped cleanly in a read-only directory exits 1', { skip: asRoot && 'mode bits do not bind root' }, t => {
|
||||
const f = t3Fixture(t); f.write();
|
||||
inReadOnlyDir(path.dirname(f.db), () => {
|
||||
const r = f.run(['--t3-db', f.db]); assert.equal(r.status, 1); assert.match(r.stderr, /cannot be read: .*\(SQLite 1544\); use --no-t3/);
|
||||
});
|
||||
});
|
||||
test('T3: a lock held past the 5 s busy timeout exits 1 and names --no-t3', t => {
|
||||
const f = t3Fixture(t), writer = f.write({ keepOpen: true });
|
||||
t.after(() => writer.close());
|
||||
writer.exec('pragma locking_mode=exclusive'); writer.exec('begin exclusive');
|
||||
addMessage(writer, { thread: T1, text: 'held' });
|
||||
const started = Date.now(), r = f.run(['--t3-db', f.db]);
|
||||
writer.exec('commit');
|
||||
assert.equal(r.status, 1); assert.match(r.stderr, /cannot be read: .*\(SQLite 5\); use --no-t3/);
|
||||
assert.ok(Date.now() - started >= 4500, 'the reader waited for the busy timeout');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user