@ngockhoale/ckit 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +70 -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 +384 -0
- package/dist/src/cli/demo.d.ts +1 -0
- package/dist/src/cli/demo.js +30 -0
- package/dist/src/cli/lifecycle.d.ts +19 -0
- package/dist/src/cli/lifecycle.js +90 -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 +113 -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 +157 -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 +677 -0
- package/gui/index.html +51 -0
- package/gui/network.js +413 -0
- package/package.json +44 -4
- package/src/storage/schema.sql +42 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { initialSession, reduce, validateEventReferences } from './machine.js';
|
|
2
|
+
/** Pure, read-only projection: groups by session identity and never emits effects. */
|
|
3
|
+
export function initialProjection(session) { return Object.freeze({ ...initialSession(session), projectId: null }); }
|
|
4
|
+
export function projectSession(session, events) {
|
|
5
|
+
let state = initialProjection(session);
|
|
6
|
+
for (const event of events) {
|
|
7
|
+
if (state.projectId !== null && state.projectId !== event.projectId)
|
|
8
|
+
throw new TypeError(`projectId mismatch in session ${session}`);
|
|
9
|
+
state = Object.freeze({ ...reduce(state, event), projectId: state.projectId ?? event.projectId });
|
|
10
|
+
}
|
|
11
|
+
return state;
|
|
12
|
+
}
|
|
13
|
+
export function projectEvents(events) {
|
|
14
|
+
const groups = new Map();
|
|
15
|
+
const canonical = new Map();
|
|
16
|
+
for (const event of events) {
|
|
17
|
+
const previous = canonical.get(event.eventId);
|
|
18
|
+
if (previous !== undefined) {
|
|
19
|
+
if (JSON.stringify(previous) !== JSON.stringify(event))
|
|
20
|
+
throw new TypeError(`conflicting duplicate eventId ${event.eventId}`);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
canonical.set(event.eventId, event);
|
|
24
|
+
const group = groups.get(event.sessionId) ?? [];
|
|
25
|
+
group.push(event);
|
|
26
|
+
groups.set(event.sessionId, group);
|
|
27
|
+
}
|
|
28
|
+
const projections = new Map();
|
|
29
|
+
for (const [session, group] of groups) {
|
|
30
|
+
group.sort((a, b) => a.sessionSequence - b.sessionSequence);
|
|
31
|
+
validateEventReferences(group);
|
|
32
|
+
projections.set(session, projectSession(session, group));
|
|
33
|
+
}
|
|
34
|
+
return projections;
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=replay.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Envelope } from './events.js';
|
|
2
|
+
import { type SessionState } from './machine.js';
|
|
3
|
+
import type { AdvisorPort } from '../ports/advisor.js';
|
|
4
|
+
export interface RunTaskInput {
|
|
5
|
+
readonly sessionId: string;
|
|
6
|
+
readonly taskId: string;
|
|
7
|
+
readonly title: string;
|
|
8
|
+
readonly promptRef: string;
|
|
9
|
+
readonly advisor: AdvisorPort;
|
|
10
|
+
readonly clock?: () => string;
|
|
11
|
+
}
|
|
12
|
+
export declare class RunTaskError extends Error {
|
|
13
|
+
readonly cause_: unknown;
|
|
14
|
+
constructor(message: string, cause_: unknown);
|
|
15
|
+
}
|
|
16
|
+
export interface RunTaskResult {
|
|
17
|
+
readonly state: SessionState;
|
|
18
|
+
readonly events: readonly Envelope[];
|
|
19
|
+
}
|
|
20
|
+
export declare function runTask(input: RunTaskInput): Promise<RunTaskResult>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { projectId, sessionId, taskId } from './ids.js';
|
|
2
|
+
import { recordEvent } from './record.js';
|
|
3
|
+
import { initialSession, replay, reduce } from './machine.js';
|
|
4
|
+
export class RunTaskError extends Error {
|
|
5
|
+
cause_;
|
|
6
|
+
constructor(message, cause_) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.cause_ = cause_;
|
|
9
|
+
this.name = 'RunTaskError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export async function runTask(input) {
|
|
13
|
+
if (!input.advisor.isSimulated) {
|
|
14
|
+
throw new RunTaskError(`offline runTask accepts simulated adapters only (got ${input.advisor.name}); live adapters require the authorized integration path (P03+ / ADR-015)`, input.advisor.name);
|
|
15
|
+
}
|
|
16
|
+
const sid = sessionId(input.sessionId), tid = taskId(input.taskId);
|
|
17
|
+
const now = input.clock ?? (() => new Date().toISOString());
|
|
18
|
+
const recording = { sessionId: sid, taskId: tid, projectId: projectId('project-offline001'), at: now, source: 'simulated', redactedConfigHash: 'offline-demo' };
|
|
19
|
+
const events = [];
|
|
20
|
+
let state = initialSession(sid);
|
|
21
|
+
const push = (step) => {
|
|
22
|
+
const env = recordEvent(recording, step, events.at(-1));
|
|
23
|
+
state = reduce(state, env);
|
|
24
|
+
events.push(env);
|
|
25
|
+
};
|
|
26
|
+
push({ actor: { role: 'owner' }, payload: { type: 'TaskCreated', title: input.title } });
|
|
27
|
+
push({ actor: { role: 'system', adapter: input.advisor.name }, payload: { type: 'AdvisorDispatched', promptRef: input.promptRef, adapter: input.advisor.name } });
|
|
28
|
+
for await (const msg of input.advisor.dispatch({ sessionId: sid, taskId: tid, promptRef: input.promptRef })) {
|
|
29
|
+
if (state.phase !== 'awaitingAdvisor')
|
|
30
|
+
throw new RunTaskError(`advisor streamed ${msg.kind} while session is ${state.phase}; refusing to advance`, msg);
|
|
31
|
+
if (msg.kind === 'ack')
|
|
32
|
+
push({ actor: { role: 'advisor', adapter: input.advisor.name }, payload: { type: 'AdvisorAcked', adapter: input.advisor.name } });
|
|
33
|
+
else if (msg.kind === 'completed') {
|
|
34
|
+
push({ actor: { role: 'advisor', adapter: input.advisor.name }, payload: { type: 'AdvisorCompleted', resultRef: msg.resultRef } });
|
|
35
|
+
push({ actor: { role: 'system' }, payload: { type: 'TaskCompleted', outcome: 'success' } });
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const reason = msg.kind === 'rejected' ? 'adapter-fault' : msg.reason, note = msg.kind === 'rejected' ? `rejected:${msg.reason}` : msg.note;
|
|
39
|
+
push({ actor: { role: 'advisor', adapter: input.advisor.name }, payload: { type: 'AdvisorUnknownOutcome', reason, note } });
|
|
40
|
+
push({ actor: { role: 'system' }, payload: { type: 'TaskCompleted', outcome: 'unknown' } });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const replayed = replay(sid, events);
|
|
44
|
+
if (replayed !== state && JSON.stringify(replayed) !== JSON.stringify(state))
|
|
45
|
+
throw new RunTaskError('replay mismatch: non-deterministic flow', { replayed });
|
|
46
|
+
return { state, events };
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=run-task.js.map
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { type ExecutableInspector, type VersionGate } from '../adapters/launch/profile.js';
|
|
2
|
+
import { type ExportBundle } from '../host/export.js';
|
|
3
|
+
import { type JournalLockOptions } from './journal-lock.js';
|
|
4
|
+
export type DoctorStatus = 'ok' | 'warn' | 'fail' | 'not_run';
|
|
5
|
+
export type DoctorCheckId = 'runtime' | 'executable' | 'state-permissions' | 'journal-lock' | 'storage-schema' | 'storage-disk' | 'binding' | 'capabilities' | 'profile-locks' | 'sessions' | 'advisor-config';
|
|
6
|
+
export interface DoctorCheck {
|
|
7
|
+
readonly id: DoctorCheckId;
|
|
8
|
+
readonly status: DoctorStatus;
|
|
9
|
+
readonly summary: string;
|
|
10
|
+
readonly action: string | null;
|
|
11
|
+
readonly tc: readonly string[];
|
|
12
|
+
}
|
|
13
|
+
export interface DoctorReport {
|
|
14
|
+
readonly schemaVersion: 1;
|
|
15
|
+
readonly label: 'OFFLINE';
|
|
16
|
+
readonly overall: 'ok' | 'warn' | 'fail';
|
|
17
|
+
readonly checks: readonly DoctorCheck[];
|
|
18
|
+
readonly connectionCheck?: true;
|
|
19
|
+
}
|
|
20
|
+
export interface DoctorOptions {
|
|
21
|
+
readonly cwd: string;
|
|
22
|
+
readonly now?: () => number;
|
|
23
|
+
readonly nodeVersion?: string;
|
|
24
|
+
readonly minimumNodeMajor?: number;
|
|
25
|
+
readonly executable?: {
|
|
26
|
+
readonly path: string;
|
|
27
|
+
readonly gate?: VersionGate;
|
|
28
|
+
readonly inspector?: ExecutableInspector;
|
|
29
|
+
};
|
|
30
|
+
readonly profileRoots?: readonly string[];
|
|
31
|
+
readonly minFreeBytes?: number;
|
|
32
|
+
readonly statfs?: (path: string) => Promise<{
|
|
33
|
+
readonly bavail: number;
|
|
34
|
+
readonly bsize: number;
|
|
35
|
+
}>;
|
|
36
|
+
readonly lock?: JournalLockOptions;
|
|
37
|
+
/** Pre-loaded advisor configuration state (doctor stays offline and never reads the dotenv file itself). Omitted: the advisor-config check is skipped. */
|
|
38
|
+
/** Executor resolved from CKIT_EXECUTOR / CKIT_EXECUTOR_PATH by the product resolver (ignored when `executable` is given). */
|
|
39
|
+
readonly configuredExecutor?: {
|
|
40
|
+
readonly state: 'resolved';
|
|
41
|
+
readonly kind: string;
|
|
42
|
+
readonly path: string;
|
|
43
|
+
} | {
|
|
44
|
+
readonly state: 'unresolved';
|
|
45
|
+
readonly kind: string;
|
|
46
|
+
readonly problem: string;
|
|
47
|
+
};
|
|
48
|
+
/** True when the caller will make the one bounded GET /models connection check; only changes the header wording. */
|
|
49
|
+
readonly connectionCheck?: boolean;
|
|
50
|
+
readonly advisor?: {
|
|
51
|
+
readonly state: 'unconfigured';
|
|
52
|
+
} | {
|
|
53
|
+
readonly state: 'invalid';
|
|
54
|
+
readonly variables: readonly string[];
|
|
55
|
+
readonly problems?: readonly {
|
|
56
|
+
readonly variable: string;
|
|
57
|
+
readonly problem: string;
|
|
58
|
+
}[];
|
|
59
|
+
} | {
|
|
60
|
+
readonly state: 'ok';
|
|
61
|
+
readonly summary: string;
|
|
62
|
+
readonly versionHint?: boolean;
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
export declare function projectKey(cwd: string): string;
|
|
66
|
+
/** Read-only diagnostics: never prompts, spawns, opens the network, migrates or repairs anything. */
|
|
67
|
+
export declare function runDoctor(options: DoctorOptions): Promise<DoctorReport>;
|
|
68
|
+
/** Connection row text: a 404 from /models means the endpoint was reached but does not list models. */
|
|
69
|
+
export declare function describeConnection(result: {
|
|
70
|
+
readonly status: string;
|
|
71
|
+
readonly http: number | null;
|
|
72
|
+
}): string;
|
|
73
|
+
export declare function formatDoctorReport(report: DoctorReport): string;
|
|
74
|
+
export declare function buildDiagnosticBundle(report: DoctorReport, input: {
|
|
75
|
+
readonly cwd: string;
|
|
76
|
+
readonly sessionId?: string;
|
|
77
|
+
readonly environment?: Readonly<Record<string, string>>;
|
|
78
|
+
}): ExportBundle;
|
|
@@ -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>;
|