@ngockhoale/ckit 0.0.0-stage → 0.1.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/.env.example +42 -0
- package/README.md +116 -2
- package/dist/src/adapters/agent/claude/errors.d.ts +13 -0
- package/dist/src/adapters/agent/claude/errors.js +16 -0
- package/dist/src/adapters/agent/claude/normalize.d.ts +11 -0
- package/dist/src/adapters/agent/claude/normalize.js +83 -0
- package/dist/src/adapters/agent/errors.d.ts +13 -0
- package/dist/src/adapters/agent/errors.js +19 -0
- package/dist/src/adapters/agent/fixtures/claude-transcript.d.ts +70 -0
- package/dist/src/adapters/agent/fixtures/claude-transcript.js +15 -0
- package/dist/src/adapters/agent/fixtures/omp-transcript.d.ts +60 -0
- package/dist/src/adapters/agent/fixtures/omp-transcript.js +14 -0
- package/dist/src/adapters/agent/normalize.d.ts +18 -0
- package/dist/src/adapters/agent/normalize.js +77 -0
- package/dist/src/adapters/agent/transport.d.ts +35 -0
- package/dist/src/adapters/agent/transport.js +39 -0
- package/dist/src/adapters/agent/worker-service.d.ts +49 -0
- package/dist/src/adapters/agent/worker-service.js +77 -0
- package/dist/src/adapters/fake/fake-advisor.d.ts +15 -0
- package/dist/src/adapters/fake/fake-advisor.js +29 -0
- package/dist/src/adapters/fake/fake-agent.d.ts +12 -0
- package/dist/src/adapters/fake/fake-agent.js +21 -0
- package/dist/src/adapters/fake/fake-store.d.ts +13 -0
- package/dist/src/adapters/fake/fake-store.js +23 -0
- package/dist/src/adapters/fake/fake-web.d.ts +12 -0
- package/dist/src/adapters/fake/fake-web.js +21 -0
- package/dist/src/adapters/fake/fault-injector.d.ts +18 -0
- package/dist/src/adapters/fake/fault-injector.js +64 -0
- package/dist/src/adapters/fake/virtual-clock.d.ts +12 -0
- package/dist/src/adapters/fake/virtual-clock.js +35 -0
- package/dist/src/adapters/launch/discover.d.ts +18 -0
- package/dist/src/adapters/launch/discover.js +55 -0
- package/dist/src/adapters/launch/executor.d.ts +117 -0
- package/dist/src/adapters/launch/executor.js +383 -0
- package/dist/src/adapters/launch/profile.d.ts +35 -0
- package/dist/src/adapters/launch/profile.js +73 -0
- package/dist/src/adapters/launch/spawn.d.ts +29 -0
- package/dist/src/adapters/launch/spawn.js +18 -0
- package/dist/src/adapters/openai/openai-advisor.d.ts +56 -0
- package/dist/src/adapters/openai/openai-advisor.js +146 -0
- package/dist/src/cli/ckit.d.ts +5 -0
- package/dist/src/cli/ckit.js +472 -0
- package/dist/src/cli/demo.d.ts +1 -0
- package/dist/src/cli/demo.js +30 -0
- package/dist/src/cli/sessions.d.ts +10 -0
- package/dist/src/cli/sessions.js +381 -0
- package/dist/src/cli/setup.d.ts +11 -0
- package/dist/src/cli/setup.js +115 -0
- package/dist/src/committee/decision.d.ts +84 -0
- package/dist/src/committee/decision.js +167 -0
- package/dist/src/committee/handover.d.ts +115 -0
- package/dist/src/committee/handover.js +191 -0
- package/dist/src/committee/no-progress.d.ts +44 -0
- package/dist/src/committee/no-progress.js +64 -0
- package/dist/src/committee/primary-registry.d.ts +15 -0
- package/dist/src/committee/primary-registry.js +60 -0
- package/dist/src/committee/reply-parser.d.ts +28 -0
- package/dist/src/committee/reply-parser.js +53 -0
- package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
- package/dist/src/committee/reviewer-scheduler.js +163 -0
- package/dist/src/committee/role-epoch.d.ts +91 -0
- package/dist/src/committee/role-epoch.js +154 -0
- package/dist/src/core/control.d.ts +18 -0
- package/dist/src/core/control.js +29 -0
- package/dist/src/core/entities.d.ts +166 -0
- package/dist/src/core/entities.js +119 -0
- package/dist/src/core/errors.d.ts +9 -0
- package/dist/src/core/errors.js +17 -0
- package/dist/src/core/events.d.ts +72 -0
- package/dist/src/core/events.js +125 -0
- package/dist/src/core/ids.d.ts +47 -0
- package/dist/src/core/ids.js +32 -0
- package/dist/src/core/machine.d.ts +55 -0
- package/dist/src/core/machine.js +110 -0
- package/dist/src/core/policy.d.ts +34 -0
- package/dist/src/core/policy.js +59 -0
- package/dist/src/core/provenance.d.ts +20 -0
- package/dist/src/core/provenance.js +21 -0
- package/dist/src/core/record.d.ts +35 -0
- package/dist/src/core/record.js +67 -0
- package/dist/src/core/replay.d.ts +10 -0
- package/dist/src/core/replay.js +36 -0
- package/dist/src/core/run-task.d.ts +20 -0
- package/dist/src/core/run-task.js +48 -0
- package/dist/src/diagnostics/doctor.d.ts +78 -0
- package/dist/src/diagnostics/doctor.js +365 -0
- package/dist/src/diagnostics/journal-lock.d.ts +38 -0
- package/dist/src/diagnostics/journal-lock.js +181 -0
- package/dist/src/evidence/linker.d.ts +44 -0
- package/dist/src/evidence/linker.js +75 -0
- package/dist/src/evidence/report-parser.d.ts +27 -0
- package/dist/src/evidence/report-parser.js +17 -0
- package/dist/src/evidence/store.d.ts +36 -0
- package/dist/src/evidence/store.js +57 -0
- package/dist/src/gui/server.d.ts +27 -0
- package/dist/src/gui/server.js +497 -0
- package/dist/src/host/checkpoint.d.ts +22 -0
- package/dist/src/host/checkpoint.js +74 -0
- package/dist/src/host/export.d.ts +52 -0
- package/dist/src/host/export.js +45 -0
- package/dist/src/host/ipc.d.ts +57 -0
- package/dist/src/host/ipc.js +124 -0
- package/dist/src/host/leases.d.ts +27 -0
- package/dist/src/host/leases.js +40 -0
- package/dist/src/host/retention.d.ts +47 -0
- package/dist/src/host/retention.js +130 -0
- package/dist/src/host/supervisor.d.ts +59 -0
- package/dist/src/host/supervisor.js +64 -0
- package/dist/src/intake/owner-intake.d.ts +31 -0
- package/dist/src/intake/owner-intake.js +97 -0
- package/dist/src/intake/types.d.ts +46 -0
- package/dist/src/intake/types.js +2 -0
- package/dist/src/intent/context-packet.d.ts +68 -0
- package/dist/src/intent/context-packet.js +76 -0
- package/dist/src/intent/idea-ledger.d.ts +50 -0
- package/dist/src/intent/idea-ledger.js +136 -0
- package/dist/src/intent/ledger.d.ts +35 -0
- package/dist/src/intent/ledger.js +40 -0
- package/dist/src/intent/registry.d.ts +51 -0
- package/dist/src/intent/registry.js +44 -0
- package/dist/src/intent/revision.d.ts +37 -0
- package/dist/src/intent/revision.js +48 -0
- package/dist/src/orchestration/dispatcher.d.ts +32 -0
- package/dist/src/orchestration/dispatcher.js +136 -0
- package/dist/src/orchestration/milestone-loop.d.ts +149 -0
- package/dist/src/orchestration/milestone-loop.js +132 -0
- package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
- package/dist/src/orchestration/recovery-coordinator.js +180 -0
- package/dist/src/orchestration/work-order-contract.d.ts +44 -0
- package/dist/src/orchestration/work-order-contract.js +85 -0
- package/dist/src/orchestration/work-queue.d.ts +56 -0
- package/dist/src/orchestration/work-queue.js +95 -0
- package/dist/src/ports/advisor.d.ts +33 -0
- package/dist/src/ports/advisor.js +2 -0
- package/dist/src/ports/agent.d.ts +31 -0
- package/dist/src/ports/agent.js +2 -0
- package/dist/src/ports/capabilities.d.ts +3 -0
- package/dist/src/ports/capabilities.js +5 -0
- package/dist/src/ports/clock.d.ts +5 -0
- package/dist/src/ports/clock.js +5 -0
- package/dist/src/ports/store.d.ts +13 -0
- package/dist/src/ports/store.js +2 -0
- package/dist/src/ports/web.d.ts +29 -0
- package/dist/src/ports/web.js +2 -0
- package/dist/src/run/api-run.d.ts +49 -0
- package/dist/src/run/api-run.js +173 -0
- package/dist/src/run/plan-run.d.ts +22 -0
- package/dist/src/run/plan-run.js +233 -0
- package/dist/src/run/plan.d.ts +36 -0
- package/dist/src/run/plan.js +119 -0
- package/dist/src/run/verify.d.ts +25 -0
- package/dist/src/run/verify.js +81 -0
- package/dist/src/security/redact.d.ts +7 -0
- package/dist/src/security/redact.js +21 -0
- package/dist/src/settings/env-config.d.ts +64 -0
- package/dist/src/settings/env-config.js +232 -0
- package/dist/src/storage/artifacts.d.ts +30 -0
- package/dist/src/storage/artifacts.js +105 -0
- package/dist/src/storage/audit.d.ts +6 -0
- package/dist/src/storage/audit.js +6 -0
- package/dist/src/storage/db.d.ts +9 -0
- package/dist/src/storage/db.js +43 -0
- package/dist/src/storage/events.d.ts +20 -0
- package/dist/src/storage/events.js +69 -0
- package/dist/src/storage/migrations.d.ts +8 -0
- package/dist/src/storage/migrations.js +48 -0
- package/dist/src/storage/outbox.d.ts +25 -0
- package/dist/src/storage/outbox.js +40 -0
- package/dist/src/storage/projections.d.ts +18 -0
- package/dist/src/storage/projections.js +40 -0
- package/dist/src/storage/reconcile.d.ts +14 -0
- package/dist/src/storage/reconcile.js +93 -0
- package/dist/src/storage/reservations.d.ts +12 -0
- package/dist/src/storage/reservations.js +80 -0
- package/dist/src/storage/store.d.ts +34 -0
- package/dist/src/storage/store.js +105 -0
- package/dist/src/team/attachments.d.ts +22 -0
- package/dist/src/team/attachments.js +211 -0
- package/dist/src/team/cli-models.d.ts +24 -0
- package/dist/src/team/cli-models.js +72 -0
- package/dist/src/team/config.d.ts +20 -0
- package/dist/src/team/config.js +111 -0
- package/dist/src/team/engine.d.ts +28 -0
- package/dist/src/team/engine.js +443 -0
- package/dist/src/team/journal.d.ts +30 -0
- package/dist/src/team/journal.js +70 -0
- package/dist/src/team/runners.d.ts +79 -0
- package/dist/src/team/runners.js +436 -0
- package/dist/src/team/secrets.d.ts +10 -0
- package/dist/src/team/secrets.js +68 -0
- package/dist/src/team/types.d.ts +155 -0
- package/dist/src/team/types.js +5 -0
- package/dist/src/tui/app.d.ts +29 -0
- package/dist/src/tui/app.js +96 -0
- package/dist/src/tui/control-model.d.ts +101 -0
- package/dist/src/tui/control-model.js +109 -0
- package/dist/src/tui/control-screens.d.ts +27 -0
- package/dist/src/tui/control-screens.js +85 -0
- package/dist/src/tui/graph-model.d.ts +34 -0
- package/dist/src/tui/graph-model.js +29 -0
- package/dist/src/tui/graph-screens.d.ts +13 -0
- package/dist/src/tui/graph-screens.js +4 -0
- package/dist/src/tui/inspector-model.d.ts +150 -0
- package/dist/src/tui/inspector-model.js +15 -0
- package/dist/src/tui/inspector-screens.d.ts +14 -0
- package/dist/src/tui/inspector-screens.js +61 -0
- package/dist/src/tui/live.d.ts +16 -0
- package/dist/src/tui/live.js +39 -0
- package/dist/src/tui/mission-action-screens.d.ts +15 -0
- package/dist/src/tui/mission-action-screens.js +105 -0
- package/dist/src/tui/mission-actions.d.ts +46 -0
- package/dist/src/tui/mission-actions.js +53 -0
- package/dist/src/tui/mission-model.d.ts +120 -0
- package/dist/src/tui/mission-model.js +164 -0
- package/dist/src/tui/mission-nav.d.ts +82 -0
- package/dist/src/tui/mission-nav.js +131 -0
- package/dist/src/tui/mission-plan-screens.d.ts +11 -0
- package/dist/src/tui/mission-plan-screens.js +40 -0
- package/dist/src/tui/mission-plan.d.ts +45 -0
- package/dist/src/tui/mission-plan.js +166 -0
- package/dist/src/tui/mission-screens.d.ts +7 -0
- package/dist/src/tui/mission-screens.js +263 -0
- package/dist/src/tui/provenance-label.d.ts +11 -0
- package/dist/src/tui/provenance-label.js +16 -0
- package/dist/src/tui/screens.d.ts +10 -0
- package/dist/src/tui/screens.js +34 -0
- package/dist/src/tui/session-outcome.d.ts +14 -0
- package/dist/src/tui/session-outcome.js +57 -0
- package/dist/src/tui/setup-model.d.ts +159 -0
- package/dist/src/tui/setup-model.js +234 -0
- package/dist/src/tui/setup-screens.d.ts +66 -0
- package/dist/src/tui/setup-screens.js +72 -0
- package/dist/src/tui/team/app.d.ts +24 -0
- package/dist/src/tui/team/app.js +228 -0
- package/dist/src/tui/team/demo-handle.d.ts +22 -0
- package/dist/src/tui/team/demo-handle.js +42 -0
- package/dist/src/tui/team/model.d.ts +81 -0
- package/dist/src/tui/team/model.js +133 -0
- package/gui/app.css +177 -0
- package/gui/app.js +675 -0
- package/gui/index.html +51 -0
- package/gui/network.js +413 -0
- package/package.json +45 -4
- package/src/storage/schema.sql +42 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants, realpathSync } from 'node:fs';
|
|
3
|
+
import { access, lstat, stat, readFile, readlink, realpath, statfs as fsStatfs } from 'node:fs/promises';
|
|
4
|
+
import { homedir, hostname as osHostname } from 'node:os';
|
|
5
|
+
import { join, isAbsolute, resolve } from 'node:path';
|
|
6
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
7
|
+
import { validateExecutable } from '../adapters/launch/profile.js';
|
|
8
|
+
import { validateEnvelope } from '../core/events.js';
|
|
9
|
+
import { projectEvents } from '../core/replay.js';
|
|
10
|
+
import { ExportService } from '../host/export.js';
|
|
11
|
+
import { redactSecretText } from '../security/redact.js';
|
|
12
|
+
import { migrations } from '../storage/migrations.js';
|
|
13
|
+
import { DEFAULT_LOCK_STALE_AFTER_MS, inspectJournalLock, isProcessAlive } from './journal-lock.js';
|
|
14
|
+
const STATE_DIR = '.ckit';
|
|
15
|
+
export function projectKey(cwd) {
|
|
16
|
+
const slug = cwd.split('/').filter(Boolean).at(-1)?.toLowerCase().replace(/[^a-z0-9_-]/g, '-') || 'root';
|
|
17
|
+
const suffix = createHash('sha256').update(cwd).digest('hex').slice(0, 12);
|
|
18
|
+
return `project-${slug.slice(0, 20).padEnd(6, '0')}-${suffix}`;
|
|
19
|
+
}
|
|
20
|
+
const check = (id, status, summary, action = null, tc = []) => ({ id, status, summary, action, tc });
|
|
21
|
+
const errCode = (error) => error.code;
|
|
22
|
+
const errMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
23
|
+
const rank = { ok: 0, not_run: 0, warn: 1, fail: 2 };
|
|
24
|
+
function worst(items) { return items.reduce((acc, item) => rank[item.status] > rank[acc] ? item.status : acc, 'ok'); }
|
|
25
|
+
/** Opens read-only; never creates or migrates. Returns null when no database file exists. */
|
|
26
|
+
async function withReadOnlyDb(path, work) {
|
|
27
|
+
try {
|
|
28
|
+
await lstat(path);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (errCode(error) === 'ENOENT')
|
|
32
|
+
return null;
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
36
|
+
try {
|
|
37
|
+
return work(db);
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
db.close();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function runtimeCheck(options) {
|
|
44
|
+
const version = options.nodeVersion ?? process.versions.node, min = options.minimumNodeMajor ?? 22;
|
|
45
|
+
const major = Number.parseInt(version.split('.')[0] ?? '', 10);
|
|
46
|
+
if (!Number.isFinite(major) || major < min)
|
|
47
|
+
return check('runtime', 'fail', `Node.js ${version} is older than required ${min}`, `Install Node.js >= ${min} and re-run ckit`);
|
|
48
|
+
return check('runtime', 'ok', `Node.js ${version}`);
|
|
49
|
+
}
|
|
50
|
+
async function executableCheck(options) {
|
|
51
|
+
const tc = ['TC041', 'TC057'], exe = options.executable;
|
|
52
|
+
if (!exe && options.configuredExecutor) {
|
|
53
|
+
const c = options.configuredExecutor;
|
|
54
|
+
return c.state === 'resolved' ? check('executable', 'ok', `${c.kind} agent executable resolved at ${c.path}; version probe NOT_RUN (T00-04)`, null, tc)
|
|
55
|
+
: check('executable', 'fail', `agent executable (${c.kind}) not resolved: ${c.problem}`, 'set CKIT_EXECUTOR_PATH to an absolute path, or install the executor on PATH; no dispatch performed.', tc);
|
|
56
|
+
}
|
|
57
|
+
if (!exe)
|
|
58
|
+
return check('executable', 'not_run', 'no agent executable configured; NOT_RUN live probe (T00-04)', null, tc);
|
|
59
|
+
if (!isAbsolute(exe.path))
|
|
60
|
+
return check('executable', 'fail', 'agent executable path is not absolute', 'absolute path required; aliases and bare names are never resolved', tc);
|
|
61
|
+
try {
|
|
62
|
+
const info = await lstat(exe.path).then(async (s) => s.isSymbolicLink() ? stat(exe.path) : s);
|
|
63
|
+
if (!info.isFile())
|
|
64
|
+
throw Object.assign(new Error('not a regular file'), { code: 'ENOTFILE' });
|
|
65
|
+
await access(exe.path, constants.X_OK);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (errCode(error) === 'ENOENT')
|
|
69
|
+
return check('executable', 'fail', 'agent executable unavailable (ENOENT)', 'Install or configure an executable path; no dispatch performed.', tc);
|
|
70
|
+
return check('executable', 'fail', `agent executable is unrunnable (${errCode(error) ?? 'error'})`, 'Check the executable path and permissions.', tc);
|
|
71
|
+
}
|
|
72
|
+
if (exe.gate && exe.inspector) {
|
|
73
|
+
try {
|
|
74
|
+
return check('executable', 'ok', `agent executable ok (version ${await validateExecutable(exe.path, exe.gate, exe.inspector)})`, null, tc);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
return check('executable', 'fail', errMessage(error), 'fix the executable as described; doctor does not change configuration', tc);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return check('executable', 'ok', 'agent executable is present and executable; version probe NOT_RUN (T00-04)', null, tc);
|
|
81
|
+
}
|
|
82
|
+
async function permissionsCheck(stateDir) {
|
|
83
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : undefined;
|
|
84
|
+
let dir;
|
|
85
|
+
try {
|
|
86
|
+
dir = await lstat(stateDir);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (errCode(error) === 'ENOENT')
|
|
90
|
+
return check('state-permissions', 'warn', '.ckit not initialised', 'run: ckit new "<goal>"');
|
|
91
|
+
return check('state-permissions', 'fail', `.ckit is not readable (${errCode(error) ?? 'error'})`, 'Check the permissions of .ckit');
|
|
92
|
+
}
|
|
93
|
+
const problems = [], actions = [];
|
|
94
|
+
if (uid !== undefined && dir.uid !== uid) {
|
|
95
|
+
problems.push('.ckit is owned by another user');
|
|
96
|
+
actions.push('run ckit as the owner of .ckit');
|
|
97
|
+
}
|
|
98
|
+
if ((dir.mode & 0o077) !== 0) {
|
|
99
|
+
problems.push(`.ckit mode ${(dir.mode & 0o777).toString(8)} is too open`);
|
|
100
|
+
actions.push('run: chmod 700 .ckit');
|
|
101
|
+
}
|
|
102
|
+
for (const name of ['project.json', 'events.json', 'sessions.json', 'state.sqlite', 'events.lock']) {
|
|
103
|
+
let info;
|
|
104
|
+
try {
|
|
105
|
+
info = await lstat(join(stateDir, name));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (uid !== undefined && info.uid !== uid) {
|
|
111
|
+
problems.push(`.ckit/${name} is owned by another user`);
|
|
112
|
+
actions.push('run ckit as the owner of .ckit');
|
|
113
|
+
}
|
|
114
|
+
if ((info.mode & 0o077) !== 0) {
|
|
115
|
+
problems.push(`.ckit/${name} mode ${(info.mode & 0o777).toString(8)} is too open`);
|
|
116
|
+
actions.push(`run: chmod 600 .ckit/${name}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return problems.length ? check('state-permissions', 'fail', problems.join('; '), actions.join('; ')) : check('state-permissions', 'ok', '.ckit permissions are private');
|
|
120
|
+
}
|
|
121
|
+
async function lockCheck(stateDir, options) {
|
|
122
|
+
const tc = ['I-3'], lock = options.lock ?? {};
|
|
123
|
+
const inspection = await inspectJournalLock(stateDir, lock);
|
|
124
|
+
if (inspection.state === 'absent')
|
|
125
|
+
return check('journal-lock', 'ok', 'no journal lock held', null, tc);
|
|
126
|
+
if (inspection.state === 'stale')
|
|
127
|
+
return check('journal-lock', 'warn', `stale (${inspection.reason})`, 'the next "ckit new" recovers it automatically; doctor does not remove it', tc);
|
|
128
|
+
if (inspection.owner.token === '')
|
|
129
|
+
return check('journal-lock', 'warn', `journal lock unreadable, age ${Math.round(inspection.ageMs)}ms`, 'wait a few seconds; the next "ckit new" recovers it if it is stale', tc);
|
|
130
|
+
const { pid, hostname, createdAt } = inspection.owner;
|
|
131
|
+
if (inspection.sameHost && inspection.ageMs > (lock.staleAfterMs ?? DEFAULT_LOCK_STALE_AFTER_MS))
|
|
132
|
+
return check('journal-lock', 'warn', `journal lock held by pid ${pid} on ${hostname} since ${createdAt} (long-running)`, `confirm that pid ${pid} is a CKit process; doctor never steals a live lock`, tc);
|
|
133
|
+
return check('journal-lock', 'warn', `journal lock held by pid ${pid} on ${hostname} since ${createdAt}`, 'retry after that CKit command exits', tc);
|
|
134
|
+
}
|
|
135
|
+
async function schemaCheck(dbPath) {
|
|
136
|
+
try {
|
|
137
|
+
const result = await withReadOnlyDb(dbPath, db => {
|
|
138
|
+
const quick = db.prepare('PRAGMA quick_check').all().map(row => String(Object.values(row)[0]));
|
|
139
|
+
const row = db.prepare('SELECT version FROM schema_version').get();
|
|
140
|
+
return { quick, version: row?.version ?? 0 };
|
|
141
|
+
});
|
|
142
|
+
if (result === null)
|
|
143
|
+
return check('storage-schema', 'ok', 'no database yet');
|
|
144
|
+
if (result.quick.length !== 1 || result.quick[0] !== 'ok')
|
|
145
|
+
return check('storage-schema', 'fail', 'state.sqlite failed the integrity check', 'preserve the file and restore from backup; do not delete it');
|
|
146
|
+
const current = migrations.length;
|
|
147
|
+
if (result.version > current)
|
|
148
|
+
return check('storage-schema', 'fail', `database schema ${result.version} is newer than this ckit (${current})`, 'upgrade ckit or restore a compatible backup; no task will run');
|
|
149
|
+
if (result.version < current)
|
|
150
|
+
return check('storage-schema', 'warn', `database schema ${result.version} will migrate on next open (current ${current})`, 'back up .ckit/state.sqlite first');
|
|
151
|
+
return check('storage-schema', 'ok', `database schema ${result.version} is current`);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (/not a database/i.test(errMessage(error)))
|
|
155
|
+
return check('storage-schema', 'fail', 'state.sqlite is not a SQLite database', 'preserve the file and restore from backup; do not delete it');
|
|
156
|
+
return check('storage-schema', 'fail', `state.sqlite cannot be read (${errMessage(error)})`, 'preserve the file and restore from backup; do not delete it');
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async function diskCheck(stateDir, cwd, options) {
|
|
160
|
+
const min = options.minFreeBytes ?? 104_857_600, probe = options.statfs ?? ((path) => fsStatfs(path));
|
|
161
|
+
const target = await lstat(stateDir).then(() => stateDir, () => cwd);
|
|
162
|
+
try {
|
|
163
|
+
const stats = await probe(target), free = stats.bavail * stats.bsize;
|
|
164
|
+
return free < min ? check('storage-disk', 'fail', `only ${free} bytes free; ${min} required`, 'free disk space before running ckit') : check('storage-disk', 'ok', `${free} bytes free`);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
return check('storage-disk', 'warn', `free space unknown (${errCode(error) ?? 'error'})`, 'free disk space if writes fail');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async function bindingCheck(stateDir, cwd) {
|
|
171
|
+
let raw;
|
|
172
|
+
try {
|
|
173
|
+
raw = await readFile(join(stateDir, 'project.json'), 'utf8');
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
if (errCode(error) === 'ENOENT')
|
|
177
|
+
return check('binding', 'warn', 'project binding not initialised', 'run: ckit new "<goal>"');
|
|
178
|
+
return check('binding', 'fail', `project.json is unreadable (${errCode(error) ?? 'error'})`, 'preserve the file; restore it from backup');
|
|
179
|
+
}
|
|
180
|
+
let parsed;
|
|
181
|
+
try {
|
|
182
|
+
parsed = JSON.parse(raw);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
parsed = {};
|
|
186
|
+
}
|
|
187
|
+
if (parsed === null || typeof parsed !== 'object' || parsed.version !== 1 || typeof parsed.canonicalCwd !== 'string' || typeof parsed.projectId !== 'string')
|
|
188
|
+
return check('binding', 'fail', 'project.json is malformed', 'preserve the file; restore it from backup');
|
|
189
|
+
const real = await realpath(resolve(cwd));
|
|
190
|
+
if (parsed.canonicalCwd !== real || parsed.projectId !== projectKey(parsed.canonicalCwd))
|
|
191
|
+
return check('binding', 'fail', 'project binding does not match this directory', 'doctor does not rewrite project.json; run ckit from the original directory or restore the binding');
|
|
192
|
+
return check('binding', 'ok', `bound to ${parsed.projectId}`);
|
|
193
|
+
}
|
|
194
|
+
async function capabilitiesCheck(dbPath) {
|
|
195
|
+
const tc = ['T11-01'];
|
|
196
|
+
try {
|
|
197
|
+
const rows = await withReadOnlyDb(dbPath, db => ({
|
|
198
|
+
advisors: db.prepare('SELECT advisor_id, provider, capabilities FROM advisor_bindings').all(),
|
|
199
|
+
agents: db.prepare('SELECT agent_id, kind, version, capabilities FROM agent_bindings').all(),
|
|
200
|
+
}));
|
|
201
|
+
if (rows === null || rows.advisors.length + rows.agents.length === 0)
|
|
202
|
+
return check('capabilities', 'not_run', 'no bindings recorded', null, tc);
|
|
203
|
+
const weak = [];
|
|
204
|
+
const empty = (json) => { try {
|
|
205
|
+
const v = JSON.parse(json);
|
|
206
|
+
return !Array.isArray(v) || v.length === 0;
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return true;
|
|
210
|
+
} };
|
|
211
|
+
for (const a of rows.advisors)
|
|
212
|
+
if (empty(a.capabilities))
|
|
213
|
+
weak.push(`advisor ${a.advisor_id} (${a.provider})`);
|
|
214
|
+
for (const a of rows.agents)
|
|
215
|
+
if (empty(a.capabilities) || a.version === '')
|
|
216
|
+
weak.push(`agent ${a.agent_id} (${a.kind})`);
|
|
217
|
+
return weak.length ? check('capabilities', 'warn', `bindings with missing capabilities or version: ${weak.join(', ')}`, 're-probe the binding (live probe NOT_RUN: T00-03/T00-04)', tc) : check('capabilities', 'ok', `${rows.advisors.length + rows.agents.length} binding(s) with recorded capabilities`, null, tc);
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
return check('capabilities', 'not_run', 'bindings unreadable; see storage-schema', null, tc);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async function profileLocksCheck(options) {
|
|
224
|
+
const tc = ['TC035'], roots = options.profileRoots;
|
|
225
|
+
if (!roots || roots.length === 0)
|
|
226
|
+
return check('profile-locks', 'not_run', 'no browser profile configured; live check NOT_RUN (T00-03)', null, tc);
|
|
227
|
+
const host = options.lock?.hostname ?? osHostname(), alive = options.lock?.isAlive ?? isProcessAlive;
|
|
228
|
+
const results = [];
|
|
229
|
+
for (const [index, root] of roots.entries()) {
|
|
230
|
+
const label = `profile #${index + 1}`;
|
|
231
|
+
try {
|
|
232
|
+
if (!(await lstat(root)).isDirectory())
|
|
233
|
+
throw new Error('not a directory');
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
results.push(check('profile-locks', 'fail', `${label}: directory missing`, 'configure an existing browser profile directory', tc));
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const found = [];
|
|
240
|
+
let singleton = null;
|
|
241
|
+
try {
|
|
242
|
+
singleton = await readlink(join(root, 'SingletonLock'));
|
|
243
|
+
}
|
|
244
|
+
catch { /* absent or not a symlink */ }
|
|
245
|
+
if (singleton !== null) {
|
|
246
|
+
const match = /^(.*)-(\d+)$/.exec(singleton);
|
|
247
|
+
if (!match)
|
|
248
|
+
found.push(check('profile-locks', 'warn', `${label}: unrecognised SingletonLock`, 'doctor does not delete it; close browsers using this profile', tc));
|
|
249
|
+
else if (match[1] !== host)
|
|
250
|
+
found.push(check('profile-locks', 'warn', `${label}: held by another host`, 'use the profile from the host that locked it', tc));
|
|
251
|
+
else if (alive(Number(match[2])))
|
|
252
|
+
found.push(check('profile-locks', 'warn', `${label}: profile in use by pid ${match[2]}`, 'close the other browser using this profile; a second instance on the same profile is refused', tc));
|
|
253
|
+
else
|
|
254
|
+
found.push(check('profile-locks', 'warn', `${label}: stale browser profile lock`, 'doctor does not delete it; remove SingletonLock manually once no browser is running', tc));
|
|
255
|
+
}
|
|
256
|
+
for (const name of ['parent.lock', 'lock']) {
|
|
257
|
+
const info = await lstat(join(root, name)).catch(() => null);
|
|
258
|
+
if (info?.isFile())
|
|
259
|
+
found.push(check('profile-locks', 'warn', `${label}: profile lock file present (${name})`, 'doctor does not delete it; close browsers using this profile', tc));
|
|
260
|
+
}
|
|
261
|
+
results.push(...(found.length ? found : [check('profile-locks', 'ok', `${label}: no lock`, null, tc)]));
|
|
262
|
+
}
|
|
263
|
+
const status = worst(results);
|
|
264
|
+
const notable = results.filter(r => r.status !== 'ok');
|
|
265
|
+
return check('profile-locks', status, results.map(r => r.summary).join('; '), notable.map(r => r.action).filter(Boolean).join('; ') || null, tc);
|
|
266
|
+
}
|
|
267
|
+
async function sessionsCheck(stateDir, dbPath, now) {
|
|
268
|
+
const bad = (what) => check('sessions', 'fail', `${what} is malformed`, 'preserve the file; restore from backup');
|
|
269
|
+
let events = [];
|
|
270
|
+
try {
|
|
271
|
+
const raw = await readFile(join(stateDir, 'events.json'), 'utf8').catch(error => { if (errCode(error) === 'ENOENT')
|
|
272
|
+
return null; throw error; });
|
|
273
|
+
if (raw !== null) {
|
|
274
|
+
const parsed = JSON.parse(raw);
|
|
275
|
+
if (!Array.isArray(parsed))
|
|
276
|
+
throw new TypeError('not an array');
|
|
277
|
+
events = parsed.map(validateEnvelope);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return bad('events.json');
|
|
282
|
+
}
|
|
283
|
+
let active = 0;
|
|
284
|
+
try {
|
|
285
|
+
active = [...projectEvents(events).values()].filter(state => state.phase !== 'closed').length;
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return bad('events.json');
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
const raw = await readFile(join(stateDir, 'sessions.json'), 'utf8').catch(error => { if (errCode(error) === 'ENOENT')
|
|
292
|
+
return null; throw error; });
|
|
293
|
+
if (raw !== null && !Array.isArray(JSON.parse(raw)))
|
|
294
|
+
throw new TypeError('not an array');
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
return bad('sessions.json');
|
|
298
|
+
}
|
|
299
|
+
let leases = [];
|
|
300
|
+
try {
|
|
301
|
+
leases = (await withReadOnlyDb(dbPath, db => db.prepare('SELECT owner, resource FROM leases WHERE expires_at > ?').all(now))) ?? [];
|
|
302
|
+
}
|
|
303
|
+
catch { /* storage-schema reports it */ }
|
|
304
|
+
const detail = leases.length ? ` [${leases.map(l => `${l.owner} on ${l.resource}`).join(', ')}]` : '';
|
|
305
|
+
return check('sessions', 'ok', `${active} active session(s); ${leases.length} live lease(s)${detail}`);
|
|
306
|
+
}
|
|
307
|
+
function advisorConfigCheck(advisor) {
|
|
308
|
+
if (advisor.state === 'unconfigured')
|
|
309
|
+
return check('advisor-config', 'warn', 'API advisor is not configured', 'copy .env.example to .env and fill CKIT_OPENAI_BASE_URL, CKIT_OPENAI_API_KEY (or CKIT_OPENAI_AUTH=none), CKIT_OPENAI_MODEL');
|
|
310
|
+
if (advisor.state === 'invalid')
|
|
311
|
+
return check('advisor-config', 'fail', `API advisor configuration is invalid: ${advisor.problems?.length ? advisor.problems.map(i => `${i.variable} ${i.problem}`).join('; ') : advisor.variables.join(', ')}`, 'fix the listed variables in .env (see .env.example); values are never printed');
|
|
312
|
+
if (advisor.versionHint)
|
|
313
|
+
return check('advisor-config', 'warn', `${advisor.summary}; base URL path has no version segment (/v1)`, 'check CKIT_OPENAI_BASE_URL: most OpenAI-compatible endpoints need a version segment such as /v1 (not changed automatically)');
|
|
314
|
+
return check('advisor-config', 'ok', advisor.summary);
|
|
315
|
+
}
|
|
316
|
+
/** Read-only diagnostics: never prompts, spawns, opens the network, migrates or repairs anything. */
|
|
317
|
+
export async function runDoctor(options) {
|
|
318
|
+
const cwd = resolve(options.cwd), stateDir = join(cwd, STATE_DIR), dbPath = join(stateDir, 'state.sqlite');
|
|
319
|
+
const now = (options.now ?? Date.now)();
|
|
320
|
+
const checks = [
|
|
321
|
+
runtimeCheck(options),
|
|
322
|
+
await executableCheck(options),
|
|
323
|
+
await permissionsCheck(stateDir),
|
|
324
|
+
await lockCheck(stateDir, options),
|
|
325
|
+
await schemaCheck(dbPath),
|
|
326
|
+
await diskCheck(stateDir, cwd, options),
|
|
327
|
+
await bindingCheck(stateDir, cwd),
|
|
328
|
+
await capabilitiesCheck(dbPath),
|
|
329
|
+
await profileLocksCheck(options),
|
|
330
|
+
await sessionsCheck(stateDir, dbPath, now),
|
|
331
|
+
...(options.advisor ? [advisorConfigCheck(options.advisor)] : []),
|
|
332
|
+
];
|
|
333
|
+
const overall = worst(checks);
|
|
334
|
+
return { schemaVersion: 1, label: 'OFFLINE', overall, checks, ...(options.connectionCheck ? { connectionCheck: true } : {}) };
|
|
335
|
+
}
|
|
336
|
+
/** Connection row text: a 404 from /models means the endpoint was reached but does not list models. */
|
|
337
|
+
export function describeConnection(result) {
|
|
338
|
+
const http = result.http !== null ? ` (http ${result.http})` : '';
|
|
339
|
+
return result.status === 'not-found' ? 'endpoint reached; /models returned 404 (model listing not supported, or base URL path is wrong); chat not checked' : `${result.status}${http}`;
|
|
340
|
+
}
|
|
341
|
+
export function formatDoctorReport(report) {
|
|
342
|
+
const lines = [report.connectionCheck ? 'ckit doctor — no prompts, no changes; one bounded connection check (GET /models) is made' : 'ckit doctor — OFFLINE (no prompts, no network, no changes)'];
|
|
343
|
+
for (const item of report.checks) {
|
|
344
|
+
lines.push(`[${item.status.toUpperCase()}] ${item.id}: ${item.summary}`);
|
|
345
|
+
if (item.action)
|
|
346
|
+
lines.push(` action: ${item.action}`);
|
|
347
|
+
}
|
|
348
|
+
return redactSecretText(lines.join('\n'));
|
|
349
|
+
}
|
|
350
|
+
export function buildDiagnosticBundle(report, input) {
|
|
351
|
+
const replacements = [];
|
|
352
|
+
const add = (path, token) => { if (path.length > 1 && !replacements.some(([p]) => p === path))
|
|
353
|
+
replacements.push([path, token]); };
|
|
354
|
+
add(input.cwd, '<project>');
|
|
355
|
+
try {
|
|
356
|
+
add(realpathSync(input.cwd), '<project>');
|
|
357
|
+
}
|
|
358
|
+
catch { /* cwd may not exist */ }
|
|
359
|
+
add(homedir(), '<home>');
|
|
360
|
+
let text = JSON.stringify(report);
|
|
361
|
+
for (const [path, token] of replacements.sort((a, b) => b[0].length - a[0].length))
|
|
362
|
+
text = text.split(JSON.stringify(path).slice(1, -1)).join(token);
|
|
363
|
+
return new ExportService().export({ sessionId: input.sessionId ?? 'doctor', cwd: input.cwd, profile: 'doctor', pendingOrders: [], diagnostics: JSON.parse(text), environment: input.environment ?? {} });
|
|
364
|
+
}
|
|
365
|
+
//# sourceMappingURL=doctor.js.map
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export declare const JOURNAL_LOCK_FILE = "events.lock";
|
|
2
|
+
export declare const DEFAULT_LOCK_STALE_AFTER_MS = 600000;
|
|
3
|
+
export declare const UNREADABLE_LOCK_GRACE_MS = 5000;
|
|
4
|
+
export interface JournalLockOwner {
|
|
5
|
+
readonly version: 1;
|
|
6
|
+
readonly pid: number;
|
|
7
|
+
readonly hostname: string;
|
|
8
|
+
readonly createdAt: string;
|
|
9
|
+
readonly token: string;
|
|
10
|
+
}
|
|
11
|
+
export type JournalLockInspection = {
|
|
12
|
+
readonly state: 'absent';
|
|
13
|
+
} | {
|
|
14
|
+
readonly state: 'held';
|
|
15
|
+
readonly owner: JournalLockOwner;
|
|
16
|
+
readonly ageMs: number;
|
|
17
|
+
readonly sameHost: boolean;
|
|
18
|
+
} | {
|
|
19
|
+
readonly state: 'stale';
|
|
20
|
+
readonly reason: 'dead-pid' | 'expired' | 'unreadable';
|
|
21
|
+
readonly owner: JournalLockOwner | null;
|
|
22
|
+
readonly ageMs: number;
|
|
23
|
+
};
|
|
24
|
+
export interface JournalLockOptions {
|
|
25
|
+
readonly staleAfterMs?: number;
|
|
26
|
+
readonly now?: () => number;
|
|
27
|
+
readonly hostname?: string;
|
|
28
|
+
readonly pid?: number;
|
|
29
|
+
readonly isAlive?: (pid: number) => boolean;
|
|
30
|
+
/** Test seam: runs after a contender classified the lock stale and before it tries to take over. */
|
|
31
|
+
readonly beforeTakeover?: () => Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
/** Default liveness probe: signal 0; ESRCH means dead, EPERM means alive. */
|
|
34
|
+
export declare function isProcessAlive(pid: number): boolean;
|
|
35
|
+
/** Read-only classification of the journal lock. */
|
|
36
|
+
export declare function inspectJournalLock(stateDir: string, options?: JournalLockOptions): Promise<JournalLockInspection>;
|
|
37
|
+
/** Atomic, owner-recorded journal lock with race-safe stale recovery; a live lock is never stolen. */
|
|
38
|
+
export declare function withJournalLock<T>(stateDir: string, operation: () => Promise<T>, options?: JournalLockOptions): Promise<T>;
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { link, open, readFile, stat, unlink } from 'node:fs/promises';
|
|
3
|
+
import { hostname as osHostname } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
export const JOURNAL_LOCK_FILE = 'events.lock';
|
|
6
|
+
export const DEFAULT_LOCK_STALE_AFTER_MS = 600_000;
|
|
7
|
+
export const UNREADABLE_LOCK_GRACE_MS = 5_000;
|
|
8
|
+
const GUARD_SUFFIX = '.takeover';
|
|
9
|
+
/** Default liveness probe: signal 0; ESRCH means dead, EPERM means alive. */
|
|
10
|
+
export function isProcessAlive(pid) {
|
|
11
|
+
try {
|
|
12
|
+
process.kill(pid, 0);
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
return error.code !== 'ESRCH';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function validateStale(value) {
|
|
20
|
+
if (value === undefined)
|
|
21
|
+
return DEFAULT_LOCK_STALE_AFTER_MS;
|
|
22
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
23
|
+
throw new TypeError('staleAfterMs must be a positive safe integer');
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
function parseOwner(raw) {
|
|
27
|
+
try {
|
|
28
|
+
const value = JSON.parse(raw);
|
|
29
|
+
if (!value || typeof value !== 'object' || value.version !== 1 || typeof value.pid !== 'number' || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.hostname !== 'string' || typeof value.createdAt !== 'string' || typeof value.token !== 'string' || Number.isNaN(Date.parse(value.createdAt)))
|
|
30
|
+
return null;
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function snapshot(lockPath, options) {
|
|
38
|
+
const staleAfterMs = validateStale(options.staleAfterMs);
|
|
39
|
+
const now = (options.now ?? Date.now)();
|
|
40
|
+
const host = options.hostname ?? osHostname();
|
|
41
|
+
const isAlive = options.isAlive ?? isProcessAlive;
|
|
42
|
+
let info, raw;
|
|
43
|
+
try {
|
|
44
|
+
info = await stat(lockPath);
|
|
45
|
+
raw = await readFile(lockPath, 'utf8');
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error.code === 'ENOENT')
|
|
49
|
+
return null;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
const owner = parseOwner(raw);
|
|
53
|
+
if (!owner) {
|
|
54
|
+
const ageMs = Math.max(0, now - info.mtimeMs);
|
|
55
|
+
if (ageMs > UNREADABLE_LOCK_GRACE_MS)
|
|
56
|
+
return { inspection: { state: 'stale', reason: 'unreadable', owner: null, ageMs }, raw, ino: info.ino, unreadableBusy: false };
|
|
57
|
+
const synthetic = { version: 1, pid: 0, hostname: 'unknown', createdAt: new Date(info.mtimeMs).toISOString(), token: '' };
|
|
58
|
+
return { inspection: { state: 'held', owner: synthetic, ageMs, sameHost: false }, raw, ino: info.ino, unreadableBusy: true };
|
|
59
|
+
}
|
|
60
|
+
const ageMs = Math.max(0, now - Date.parse(owner.createdAt));
|
|
61
|
+
const sameHost = owner.hostname === host;
|
|
62
|
+
let inspection;
|
|
63
|
+
if (sameHost)
|
|
64
|
+
inspection = isAlive(owner.pid) ? { state: 'held', owner, ageMs, sameHost } : { state: 'stale', reason: 'dead-pid', owner, ageMs };
|
|
65
|
+
else
|
|
66
|
+
inspection = ageMs > staleAfterMs ? { state: 'stale', reason: 'expired', owner, ageMs } : { state: 'held', owner, ageMs, sameHost };
|
|
67
|
+
return { inspection, raw, ino: info.ino, unreadableBusy: false };
|
|
68
|
+
}
|
|
69
|
+
/** Read-only classification of the journal lock. */
|
|
70
|
+
export async function inspectJournalLock(stateDir, options = {}) {
|
|
71
|
+
validateStale(options.staleAfterMs);
|
|
72
|
+
return (await snapshot(join(stateDir, JOURNAL_LOCK_FILE), options))?.inspection ?? { state: 'absent' };
|
|
73
|
+
}
|
|
74
|
+
function busy(snap) {
|
|
75
|
+
const inspection = snap?.inspection;
|
|
76
|
+
if (inspection && inspection.state !== 'absent') {
|
|
77
|
+
if (snap.unreadableBusy || (inspection.state === 'stale' && inspection.owner === null))
|
|
78
|
+
return new Error(`event journal is busy (lock unreadable, age ${Math.round(inspection.ageMs)}ms); retry after that CKit command exits`);
|
|
79
|
+
if (inspection.owner)
|
|
80
|
+
return new Error(`event journal is busy (held by pid ${inspection.owner.pid} on ${inspection.owner.hostname} since ${inspection.owner.createdAt}); retry after that CKit command exits`);
|
|
81
|
+
}
|
|
82
|
+
return new Error('event journal is busy (another CKit command is recovering the lock); retry after that CKit command exits');
|
|
83
|
+
}
|
|
84
|
+
const code = (error) => error.code;
|
|
85
|
+
async function tryLink(stateDir, lockPath, ownerJson) {
|
|
86
|
+
const temp = join(stateDir, `events-lock-${randomBytes(6).toString('hex')}.tmp`);
|
|
87
|
+
const file = await open(temp, 'wx', 0o600);
|
|
88
|
+
try {
|
|
89
|
+
await file.writeFile(ownerJson, 'utf8');
|
|
90
|
+
await file.sync();
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
await file.close().catch(() => undefined);
|
|
94
|
+
await unlink(temp).catch(() => undefined);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
await file.close();
|
|
98
|
+
try {
|
|
99
|
+
await link(temp, lockPath);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (code(error) === 'EEXIST')
|
|
104
|
+
return false;
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
await unlink(temp).catch(() => undefined);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async function acquire(stateDir, lockPath, ownerJson, options) {
|
|
112
|
+
if (await tryLink(stateDir, lockPath, ownerJson))
|
|
113
|
+
return;
|
|
114
|
+
const snap = await snapshot(lockPath, options);
|
|
115
|
+
if (snap === null) {
|
|
116
|
+
if (await tryLink(stateDir, lockPath, ownerJson))
|
|
117
|
+
return;
|
|
118
|
+
throw busy(await snapshot(lockPath, options));
|
|
119
|
+
}
|
|
120
|
+
if (snap.inspection.state !== 'stale')
|
|
121
|
+
throw busy(snap);
|
|
122
|
+
await options.beforeTakeover?.();
|
|
123
|
+
const guardPath = `${lockPath}${GUARD_SUFFIX}`;
|
|
124
|
+
let guard;
|
|
125
|
+
try {
|
|
126
|
+
guard = await open(guardPath, 'wx', 0o600);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (code(error) !== 'EEXIST')
|
|
130
|
+
throw error;
|
|
131
|
+
// Remove an abandoned guard only if it is still the same file (ino + mtime) we judged stale.
|
|
132
|
+
const seen = await stat(guardPath).catch(() => null);
|
|
133
|
+
if (seen && (options.now ?? Date.now)() - seen.mtimeMs > UNREADABLE_LOCK_GRACE_MS) {
|
|
134
|
+
const recheck = await stat(guardPath).catch(() => null);
|
|
135
|
+
if (recheck && recheck.ino === seen.ino && recheck.mtimeMs === seen.mtimeMs)
|
|
136
|
+
await unlink(guardPath).catch(() => undefined);
|
|
137
|
+
}
|
|
138
|
+
throw busy(null);
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
const again = await snapshot(lockPath, options);
|
|
142
|
+
if (again === null) {
|
|
143
|
+
if (await tryLink(stateDir, lockPath, ownerJson))
|
|
144
|
+
return;
|
|
145
|
+
throw busy(await snapshot(lockPath, options));
|
|
146
|
+
}
|
|
147
|
+
if (again.inspection.state !== 'stale' || again.raw !== snap.raw || again.ino !== snap.ino)
|
|
148
|
+
throw busy(again);
|
|
149
|
+
try {
|
|
150
|
+
await unlink(lockPath);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (code(error) === 'ENOENT')
|
|
154
|
+
throw busy(null);
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
if (!(await tryLink(stateDir, lockPath, ownerJson)))
|
|
158
|
+
throw busy(await snapshot(lockPath, options));
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
await guard.close();
|
|
162
|
+
await unlink(guardPath).catch(() => undefined);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** Atomic, owner-recorded journal lock with race-safe stale recovery; a live lock is never stolen. */
|
|
166
|
+
export async function withJournalLock(stateDir, operation, options = {}) {
|
|
167
|
+
validateStale(options.staleAfterMs);
|
|
168
|
+
const lockPath = join(stateDir, JOURNAL_LOCK_FILE);
|
|
169
|
+
const token = randomBytes(12).toString('hex');
|
|
170
|
+
const owner = { version: 1, pid: options.pid ?? process.pid, hostname: options.hostname ?? osHostname(), createdAt: new Date((options.now ?? Date.now)()).toISOString(), token };
|
|
171
|
+
await acquire(stateDir, lockPath, JSON.stringify(owner), options);
|
|
172
|
+
try {
|
|
173
|
+
return await operation();
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
const current = await readFile(lockPath, 'utf8').then(parseOwner, () => null);
|
|
177
|
+
if (current?.token === token)
|
|
178
|
+
await unlink(lockPath).catch(() => undefined);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
//# sourceMappingURL=journal-lock.js.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { VerificationLevel } from './store.js';
|
|
2
|
+
import { EvidenceStore } from './store.js';
|
|
3
|
+
export interface AcceptanceCriterion {
|
|
4
|
+
readonly criterionId: string;
|
|
5
|
+
readonly requiredLevel: VerificationLevel;
|
|
6
|
+
readonly revision: string;
|
|
7
|
+
readonly cwd: string;
|
|
8
|
+
}
|
|
9
|
+
export interface EvidenceLink {
|
|
10
|
+
readonly criterionId: string;
|
|
11
|
+
readonly evidenceId: string;
|
|
12
|
+
readonly verification: VerificationLevel;
|
|
13
|
+
readonly revision: string;
|
|
14
|
+
readonly cwd: string;
|
|
15
|
+
}
|
|
16
|
+
export interface EvidenceJustification {
|
|
17
|
+
readonly criterionId: string;
|
|
18
|
+
readonly evidenceId: string;
|
|
19
|
+
readonly reason: string;
|
|
20
|
+
}
|
|
21
|
+
export interface EvaluationContext {
|
|
22
|
+
readonly revision: string;
|
|
23
|
+
readonly cwd: string;
|
|
24
|
+
}
|
|
25
|
+
export interface CriterionEvaluation {
|
|
26
|
+
readonly criterionId: string;
|
|
27
|
+
readonly satisfied: boolean;
|
|
28
|
+
readonly links: readonly EvidenceLink[];
|
|
29
|
+
readonly escalation: string | null;
|
|
30
|
+
}
|
|
31
|
+
export declare class EvidenceLinker {
|
|
32
|
+
private readonly evidence;
|
|
33
|
+
private readonly criteria;
|
|
34
|
+
private readonly links;
|
|
35
|
+
private readonly justifications;
|
|
36
|
+
private readonly escalations;
|
|
37
|
+
constructor(evidence: EvidenceStore);
|
|
38
|
+
attach(criterion: AcceptanceCriterion, evidenceId: string): EvidenceLink;
|
|
39
|
+
justify(input: EvidenceJustification): void;
|
|
40
|
+
evaluate(criterionId: string, context: EvaluationContext): CriterionEvaluation;
|
|
41
|
+
complete(criterionIds: readonly string[], context: EvaluationContext): boolean;
|
|
42
|
+
getEscalations(): readonly string[];
|
|
43
|
+
getJustifications(): readonly EvidenceJustification[];
|
|
44
|
+
}
|