@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,90 @@
|
|
|
1
|
+
// `ckit install` (prepare the current folder) and `ckit update` (upgrade the globally installed package from npm).
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { appendFileSync, existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { teamConfigPath, writeDefaultTeamConfig } from '../team/config.js';
|
|
7
|
+
export const PACKAGE_NAME = '@ngockhoale/ckit';
|
|
8
|
+
const IGNORE_LINE = '.ckit/team/';
|
|
9
|
+
export function installedVersion() {
|
|
10
|
+
// dist/src/cli/lifecycle.js -> package root is three levels up.
|
|
11
|
+
const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'package.json'), 'utf8'));
|
|
12
|
+
return typeof pkg.version === 'string' ? pkg.version : 'unknown';
|
|
13
|
+
}
|
|
14
|
+
/** Prepares `cwd` (exactly that folder, never a parent) for CKit: writes the default .ckit/team.json when missing; keeps an existing one untouched. */
|
|
15
|
+
export function installProject(cwd) {
|
|
16
|
+
let root;
|
|
17
|
+
try {
|
|
18
|
+
root = realpathSync(resolve(cwd));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
root = resolve(cwd);
|
|
22
|
+
}
|
|
23
|
+
const configFile = teamConfigPath(root), created = !existsSync(configFile);
|
|
24
|
+
if (created)
|
|
25
|
+
writeDefaultTeamConfig(root);
|
|
26
|
+
// Run journals and uploads are local working data: keep them out of git when the folder already has a .gitignore.
|
|
27
|
+
let gitignoreUpdated = false;
|
|
28
|
+
const gi = join(root, '.gitignore');
|
|
29
|
+
if (existsSync(gi)) {
|
|
30
|
+
const text = readFileSync(gi, 'utf8');
|
|
31
|
+
if (!text.split(/\r?\n/).some(l => l.trim() === IGNORE_LINE || l.trim() === '.ckit/' || l.trim() === '.ckit')) {
|
|
32
|
+
appendFileSync(gi, `${text === '' || text.endsWith('\n') ? '' : '\n'}${IGNORE_LINE}\n`);
|
|
33
|
+
gitignoreUpdated = true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return { root, configFile, created, gitignoreUpdated };
|
|
37
|
+
}
|
|
38
|
+
export async function runInstallCommand(args) {
|
|
39
|
+
if (args.length !== 0)
|
|
40
|
+
throw new TypeError('usage: ckit install');
|
|
41
|
+
const r = installProject(process.cwd());
|
|
42
|
+
console.log(`CKit ${installedVersion()} is ready in ${r.root}`);
|
|
43
|
+
console.log(r.created ? `created ${r.configFile} (default team; change CLI and model per agent in the GUI: Config)` : `kept your existing ${r.configFile}`);
|
|
44
|
+
if (r.gitignoreUpdated)
|
|
45
|
+
console.log(`added ${IGNORE_LINE} to .gitignore (run journals and uploads stay local)`);
|
|
46
|
+
console.log('next: run "ckit" in this folder to open the GUI.');
|
|
47
|
+
return 0;
|
|
48
|
+
}
|
|
49
|
+
const realNpm = (args, inherit) => {
|
|
50
|
+
const r = spawnSync('npm', [...args], { encoding: 'utf8', stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32' });
|
|
51
|
+
return { status: r.error ? 1 : r.status ?? 1, stdout: typeof r.stdout === 'string' ? r.stdout : '' };
|
|
52
|
+
};
|
|
53
|
+
/** true when version a is newer than b (numeric major.minor.patch; with equal numbers a release beats a pre-release). */
|
|
54
|
+
export function isNewer(a, b) {
|
|
55
|
+
const parse = (v) => { const [core = '', ...rest] = v.split('-'); return { n: core.split('.').map(x => Number(x) || 0), pre: rest.length > 0 }; };
|
|
56
|
+
const x = parse(a), y = parse(b);
|
|
57
|
+
for (let i = 0; i < 3; i++) {
|
|
58
|
+
const d = (x.n[i] ?? 0) - (y.n[i] ?? 0);
|
|
59
|
+
if (d !== 0)
|
|
60
|
+
return d > 0;
|
|
61
|
+
}
|
|
62
|
+
return !x.pre && y.pre;
|
|
63
|
+
}
|
|
64
|
+
export async function runUpdateCommand(args, npm = realNpm, current = installedVersion(), log = console.log) {
|
|
65
|
+
const checkOnly = args.length === 1 && args[0] === '--check';
|
|
66
|
+
if (args.length !== 0 && !checkOnly)
|
|
67
|
+
throw new TypeError('usage: ckit update [--check]');
|
|
68
|
+
const view = npm(['view', `${PACKAGE_NAME}@latest`, 'version'], false), latest = view.stdout.trim();
|
|
69
|
+
if (view.status !== 0 || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?$/.test(latest)) {
|
|
70
|
+
log(`could not read the latest version of ${PACKAGE_NAME} from npm (check the network and "npm whoami"/registry settings). Installed: ${current}`);
|
|
71
|
+
return 1;
|
|
72
|
+
}
|
|
73
|
+
if (!isNewer(latest, current)) {
|
|
74
|
+
log(latest === current ? `CKit is up to date (${current}).` : `CKit ${current} is newer than the published ${latest}; nothing to update.`);
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
if (checkOnly) {
|
|
78
|
+
log(`update available: ${current} -> ${latest}. Run "ckit update" to install it.`);
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
log(`updating CKit ${current} -> ${latest} (npm install -g ${PACKAGE_NAME}@${latest})`);
|
|
82
|
+
const r = npm(['install', '-g', `${PACKAGE_NAME}@${latest}`], true);
|
|
83
|
+
if (r.status !== 0) {
|
|
84
|
+
log(`npm could not install the update (exit ${r.status}). Run it yourself to see why: npm install -g ${PACKAGE_NAME}@latest`);
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
log(`CKit ${latest} installed. Restart any running "ckit gui" to use it; your projects' .ckit/team.json files are unchanged.`);
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=lifecycle.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const SESSIONS_USAGE = "usage: ckit sessions [--project=<path>]";
|
|
2
|
+
export declare const OPEN_USAGE = "usage: ckit open <sessionId> [--project=<path>]";
|
|
3
|
+
export declare const REPLAY_USAGE = "usage: ckit replay <sessionId> [--project=<path>]";
|
|
4
|
+
export declare const BACKUP_USAGE = "usage: ckit backup <dest-dir> [--project=<path>]";
|
|
5
|
+
export declare const RESTORE_USAGE = "usage: ckit restore <backup-dir> [--project=<path>] [--allow-other-project]";
|
|
6
|
+
export declare function showSessions(args: readonly string[]): Promise<number>;
|
|
7
|
+
export declare function showOpen(args: readonly string[]): Promise<number>;
|
|
8
|
+
export declare function showReplay(args: readonly string[]): Promise<number>;
|
|
9
|
+
export declare function runBackup(args: readonly string[]): Promise<number>;
|
|
10
|
+
export declare function runRestore(args: readonly string[]): Promise<number>;
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
// TASK-T08-08: read-only session views (sessions/open/replay) and backup/restore of <project>/.ckit.
|
|
2
|
+
// Inert by construction: no advisor, executor or network client is constructed here; the DB is opened read-only.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
5
|
+
import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
7
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
8
|
+
import { validateEnvelope } from '../core/events.js';
|
|
9
|
+
import { inspectJournalLock, withJournalLock } from '../diagnostics/journal-lock.js';
|
|
10
|
+
import { redactSecretText } from '../security/redact.js';
|
|
11
|
+
import { resolveProjectRoot } from '../settings/env-config.js';
|
|
12
|
+
import { provenanceLabel } from '../tui/provenance-label.js';
|
|
13
|
+
import { outcomeLines, summarizeSessionOutcome } from '../tui/session-outcome.js';
|
|
14
|
+
const STATE_DIR = '.ckit', EVENTS_FILE = 'events.json', MANIFEST = 'manifest.json';
|
|
15
|
+
export const SESSIONS_USAGE = 'usage: ckit sessions [--project=<path>]';
|
|
16
|
+
export const OPEN_USAGE = 'usage: ckit open <sessionId> [--project=<path>]';
|
|
17
|
+
export const REPLAY_USAGE = 'usage: ckit replay <sessionId> [--project=<path>]';
|
|
18
|
+
export const BACKUP_USAGE = 'usage: ckit backup <dest-dir> [--project=<path>]';
|
|
19
|
+
export const RESTORE_USAGE = 'usage: ckit restore <backup-dir> [--project=<path>] [--allow-other-project]';
|
|
20
|
+
function parseArgs(args, usage, positionals, flags = []) {
|
|
21
|
+
const positional = [], seen = new Set();
|
|
22
|
+
let project;
|
|
23
|
+
for (const arg of args) {
|
|
24
|
+
if (arg.startsWith('--project=') && arg.length > 10 && project === undefined)
|
|
25
|
+
project = arg.slice(10);
|
|
26
|
+
else if (flags.includes(arg) && !seen.has(arg))
|
|
27
|
+
seen.add(arg);
|
|
28
|
+
else if (!arg.startsWith('-') && positional.length < positionals)
|
|
29
|
+
positional.push(arg);
|
|
30
|
+
else
|
|
31
|
+
throw new TypeError(usage);
|
|
32
|
+
}
|
|
33
|
+
if (positional.length !== positionals)
|
|
34
|
+
throw new TypeError(usage);
|
|
35
|
+
return { positional, project, flags: seen };
|
|
36
|
+
}
|
|
37
|
+
const stateDirOf = (project) => { const root = resolveProjectRoot(process.cwd(), project); return { root, stateDir: join(root, STATE_DIR) }; };
|
|
38
|
+
const safe = (text) => redactSecretText(text);
|
|
39
|
+
function readJournal(stateDir) {
|
|
40
|
+
let raw;
|
|
41
|
+
try {
|
|
42
|
+
raw = readFileSync(join(stateDir, EVENTS_FILE), 'utf8');
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error.code === 'ENOENT')
|
|
46
|
+
return [];
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
const parsed = JSON.parse(raw);
|
|
50
|
+
if (!Array.isArray(parsed))
|
|
51
|
+
throw new TypeError('event journal must be an array');
|
|
52
|
+
return parsed.map(validateEnvelope);
|
|
53
|
+
}
|
|
54
|
+
/** Tolerant grouping: never throws on cross-session references (unlike the strict projection). */
|
|
55
|
+
function groupSessions(events) {
|
|
56
|
+
const groups = new Map(), seen = new Set();
|
|
57
|
+
for (const event of events) {
|
|
58
|
+
if (seen.has(event.eventId))
|
|
59
|
+
continue;
|
|
60
|
+
seen.add(event.eventId);
|
|
61
|
+
const g = groups.get(event.sessionId) ?? [];
|
|
62
|
+
g.push(event);
|
|
63
|
+
groups.set(event.sessionId, g);
|
|
64
|
+
}
|
|
65
|
+
for (const g of groups.values())
|
|
66
|
+
g.sort((a, b) => a.sessionSequence - b.sessionSequence);
|
|
67
|
+
return groups;
|
|
68
|
+
}
|
|
69
|
+
const goalOf = (events) => { const t = events.find(e => e.payload.type === 'TaskCreated'); return t?.payload.type === 'TaskCreated' ? safe(t.payload.title) : '(no task recorded)'; };
|
|
70
|
+
const truncate = (text, n) => { const chars = [...text.replace(/\s+/g, ' ')]; return chars.length > n ? `${chars.slice(0, n - 1).join('')}…` : chars.join(''); };
|
|
71
|
+
export async function showSessions(args) {
|
|
72
|
+
const { project } = parseArgs(args, SESSIONS_USAGE, 0);
|
|
73
|
+
const { stateDir } = stateDirOf(project);
|
|
74
|
+
const groups = groupSessions(readJournal(stateDir));
|
|
75
|
+
if (groups.size === 0) {
|
|
76
|
+
console.log('No recorded sessions.');
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
|
79
|
+
const rows = [...groups.entries()].map(([id, events]) => ({ id, events, at: events[0].at }));
|
|
80
|
+
rows.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : a.id < b.id ? 1 : -1));
|
|
81
|
+
for (const { id, events, at } of rows) {
|
|
82
|
+
const done = events.find(e => e.payload.type === 'TaskCompleted');
|
|
83
|
+
const outcome = done?.payload.type === 'TaskCompleted' ? done.payload.outcome : 'open';
|
|
84
|
+
const unknown = events.filter(e => e.payload.type === 'AdvisorUnknownOutcome').length;
|
|
85
|
+
console.log(`[${provenanceLabel(events[0].provenance)}] ${id} ${outcome} tasks=${new Set(events.map(e => e.taskId)).size} unknown=${unknown} created=${at} — ${truncate(goalOf(events), 60)}`);
|
|
86
|
+
}
|
|
87
|
+
return 0;
|
|
88
|
+
}
|
|
89
|
+
function artifactHashes(stateDir, refs) {
|
|
90
|
+
const out = new Map(), db = join(stateDir, 'state.sqlite');
|
|
91
|
+
if (refs.length === 0 || !existsSync(db))
|
|
92
|
+
return out;
|
|
93
|
+
let handle;
|
|
94
|
+
try {
|
|
95
|
+
handle = new DatabaseSync(db, { readOnly: true });
|
|
96
|
+
const stmt = handle.prepare('SELECT hash FROM artifact_refs WHERE artifact_ref=?');
|
|
97
|
+
for (const ref of refs) {
|
|
98
|
+
const row = stmt.get(ref);
|
|
99
|
+
if (row)
|
|
100
|
+
out.set(ref, String(row['hash']));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch { /* hashes are best effort for a read-only view */ }
|
|
104
|
+
finally {
|
|
105
|
+
handle?.close();
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
function sessionOrNull(stateDir, id) { return groupSessions(readJournal(stateDir)).get(id) ?? null; }
|
|
110
|
+
function unknownSession(id) { console.error(`ckit: unknown session ${safe(id)}`); return 2; }
|
|
111
|
+
export async function showOpen(args) {
|
|
112
|
+
const { positional, project } = parseArgs(args, OPEN_USAGE, 1);
|
|
113
|
+
const id = positional[0], { stateDir } = stateDirOf(project);
|
|
114
|
+
const events = sessionOrNull(stateDir, id);
|
|
115
|
+
if (events === null)
|
|
116
|
+
return unknownSession(id);
|
|
117
|
+
const ids = new Set(events.map(e => e.eventId));
|
|
118
|
+
console.log(`[${provenanceLabel(events[0].provenance)}] session ${id} (read-only view)`);
|
|
119
|
+
console.log(`goal: ${truncate(goalOf(events), 200)}`);
|
|
120
|
+
const tasks = [...new Set(events.map(e => e.taskId))];
|
|
121
|
+
console.log(`tasks: ${tasks.length}`);
|
|
122
|
+
for (const t of tasks)
|
|
123
|
+
console.log(` task ${t}: ${events.filter(e => e.taskId === t).length} event(s)`);
|
|
124
|
+
const attempts = [...new Set(events.map(e => e.attemptId).filter((a) => a !== null))];
|
|
125
|
+
console.log(`attempts: ${attempts.length === 0 ? 'none recorded' : attempts.join(', ')}`);
|
|
126
|
+
const missing = events.filter(e => (e.parentEventId !== null && !ids.has(e.parentEventId)) || (e.causationId !== null && !ids.has(e.causationId)));
|
|
127
|
+
for (const e of missing)
|
|
128
|
+
console.log(`WARNING: event #${e.sessionSequence} references a parent event outside this session (cross-session parent; shown as recorded, not resolved)`);
|
|
129
|
+
const summary = summarizeSessionOutcome(events);
|
|
130
|
+
console.log(summary === null ? 'outcome: not closed' : outcomeLines(summary).join('\n'));
|
|
131
|
+
if (summary !== null) {
|
|
132
|
+
console.log(`worker done: ${summary.worker === 'completed' ? 'yes' : summary.worker === 'not run' ? 'not run' : 'no'}`);
|
|
133
|
+
console.log(`verify passed: ${summary.acceptance === 'verified' ? 'yes' : summary.acceptance === 'not reached' ? 'not reached' : 'no'}`);
|
|
134
|
+
}
|
|
135
|
+
console.log('delivery boundaries:');
|
|
136
|
+
const byAdapter = new Map();
|
|
137
|
+
for (const e of events) {
|
|
138
|
+
const p = e.payload;
|
|
139
|
+
if (p.type === 'AdvisorDispatched')
|
|
140
|
+
byAdapter.set(p.adapter, 'sent');
|
|
141
|
+
else if (p.type === 'AdvisorAcked')
|
|
142
|
+
byAdapter.set(p.adapter, 'acked');
|
|
143
|
+
else if (p.type === 'AdvisorCompleted' && e.adapter !== null)
|
|
144
|
+
byAdapter.set(e.adapter, 'completed');
|
|
145
|
+
else if (p.type === 'AdvisorUnknownOutcome' && e.adapter !== null)
|
|
146
|
+
byAdapter.set(e.adapter, 'UNKNOWN_DELIVERY');
|
|
147
|
+
}
|
|
148
|
+
if (byAdapter.size === 0)
|
|
149
|
+
console.log(' none');
|
|
150
|
+
else
|
|
151
|
+
for (const [adapter, state] of byAdapter)
|
|
152
|
+
console.log(` ${safe(adapter)}: ${state}`);
|
|
153
|
+
const refs = [...new Set(events.flatMap(e => [...e.artifactRefs, ...(e.payload.type === 'AdvisorDispatched' ? [e.payload.promptRef] : []), ...(e.payload.type === 'AdvisorCompleted' ? [e.payload.resultRef] : [])]))].filter(r => /^artifact-/.test(r));
|
|
154
|
+
const hashes = artifactHashes(stateDir, refs);
|
|
155
|
+
console.log('artifacts:');
|
|
156
|
+
if (refs.length === 0)
|
|
157
|
+
console.log(' none');
|
|
158
|
+
else
|
|
159
|
+
for (const ref of refs)
|
|
160
|
+
console.log(` ${ref} sha256=${hashes.get(ref) ?? 'unavailable'}`);
|
|
161
|
+
return 0;
|
|
162
|
+
}
|
|
163
|
+
function detail(e) {
|
|
164
|
+
const p = e.payload;
|
|
165
|
+
switch (p.type) {
|
|
166
|
+
case 'TaskCreated': return `TaskCreated ${truncate(safe(p.title), 80)}`;
|
|
167
|
+
case 'AdvisorDispatched': return `AdvisorDispatched ${safe(p.adapter)} ${safe(p.promptRef)}`;
|
|
168
|
+
case 'AdvisorAcked': return `AdvisorAcked ${safe(p.adapter)}`;
|
|
169
|
+
case 'AdvisorCompleted': return `AdvisorCompleted ${safe(p.resultRef)}`;
|
|
170
|
+
case 'AdvisorUnknownOutcome': return `AdvisorUnknownOutcome ${p.reason} ${truncate(safe(p.note), 120)}`;
|
|
171
|
+
case 'TaskCompleted': return `TaskCompleted ${p.outcome}${e.reasonCode !== null ? ` ${e.reasonCode}` : ''}`;
|
|
172
|
+
case 'ReviewerSelected': return `ReviewerSelected ${safe(p.reviewerId)}`;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
export async function showReplay(args) {
|
|
176
|
+
const { positional, project } = parseArgs(args, REPLAY_USAGE, 1);
|
|
177
|
+
const id = positional[0], { stateDir } = stateDirOf(project);
|
|
178
|
+
const events = sessionOrNull(stateDir, id);
|
|
179
|
+
if (events === null)
|
|
180
|
+
return unknownSession(id);
|
|
181
|
+
console.log(`replay ${id} (inert: nothing is dispatched or resent)`);
|
|
182
|
+
for (const e of events)
|
|
183
|
+
console.log(`#${e.sessionSequence} ${e.at} [${provenanceLabel(e.provenance)}] ${e.actor.role} ${detail(e)}`);
|
|
184
|
+
return 0;
|
|
185
|
+
}
|
|
186
|
+
const sha256 = async (path) => { const b = await readFile(path); return { sha256: createHash('sha256').update(b).digest('hex'), size: b.byteLength }; };
|
|
187
|
+
async function walk(dir, base = dir) {
|
|
188
|
+
const out = [];
|
|
189
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
190
|
+
const p = join(dir, entry.name);
|
|
191
|
+
if (entry.isDirectory())
|
|
192
|
+
out.push(...await walk(p, base));
|
|
193
|
+
else if (entry.isFile() && !entry.name.endsWith('.tmp') && !entry.name.startsWith('.'))
|
|
194
|
+
out.push(relative(base, p).split(sep).join('/'));
|
|
195
|
+
}
|
|
196
|
+
return out.sort();
|
|
197
|
+
}
|
|
198
|
+
const stamp = () => new Date().toISOString().replace(/[:.]/g, '-');
|
|
199
|
+
/** realpath of the deepest existing ancestor plus the not-yet-existing tail (so a symlinked destination is seen before anything is written). */
|
|
200
|
+
function realResolve(p) {
|
|
201
|
+
let cur = resolve(p);
|
|
202
|
+
const tail = [];
|
|
203
|
+
for (;;) {
|
|
204
|
+
try {
|
|
205
|
+
return join(realpathSync(cur), ...tail.reverse());
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
const up = dirname(cur);
|
|
209
|
+
if (up === cur)
|
|
210
|
+
return resolve(p);
|
|
211
|
+
tail.push(cur.slice(up.length + 1));
|
|
212
|
+
cur = up;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** Copies regular files and directories only: no symlinks, dot-files or *.tmp. */
|
|
217
|
+
async function copyRegular(from, to) {
|
|
218
|
+
await mkdir(to, { recursive: true });
|
|
219
|
+
for (const entry of await readdir(from, { withFileTypes: true })) {
|
|
220
|
+
if (entry.name.startsWith('.') || entry.name.endsWith('.tmp'))
|
|
221
|
+
continue;
|
|
222
|
+
const src = join(from, entry.name), info = await lstat(src);
|
|
223
|
+
if (info.isDirectory())
|
|
224
|
+
await copyRegular(src, join(to, entry.name));
|
|
225
|
+
else if (info.isFile())
|
|
226
|
+
await writeFile(join(to, entry.name), await readFile(src), { mode: 0o600 });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
export async function runBackup(args) {
|
|
230
|
+
const { positional, project } = parseArgs(args, BACKUP_USAGE, 1);
|
|
231
|
+
const { stateDir } = stateDirOf(project);
|
|
232
|
+
if (!existsSync(stateDir)) {
|
|
233
|
+
console.error('ckit: no .ckit state found for this project; nothing to back up');
|
|
234
|
+
return 2;
|
|
235
|
+
}
|
|
236
|
+
const stateReal = realResolve(stateDir), destParent = realResolve(positional[0]);
|
|
237
|
+
const r = relative(stateReal, destParent);
|
|
238
|
+
if (r === '' || (!r.startsWith('..') && !isAbsolute(r))) {
|
|
239
|
+
console.error('ckit: backup destination must not be inside .ckit/');
|
|
240
|
+
return 2;
|
|
241
|
+
}
|
|
242
|
+
await mkdir(destParent, { recursive: true });
|
|
243
|
+
const dest = join(destParent, `ckit-backup-${stamp()}`);
|
|
244
|
+
await mkdir(dest, { mode: 0o700 });
|
|
245
|
+
await withJournalLock(stateDir, async () => {
|
|
246
|
+
for (const name of ['events.json', 'project.json', 'sessions.json']) {
|
|
247
|
+
const src = join(stateDir, name);
|
|
248
|
+
try {
|
|
249
|
+
if ((await lstat(src)).isFile())
|
|
250
|
+
await writeFile(join(dest, name), await readFile(src), { mode: 0o600 });
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
if (error.code !== 'ENOENT')
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (existsSync(join(stateDir, 'artifacts')))
|
|
258
|
+
await copyRegular(join(stateDir, 'artifacts'), join(dest, 'artifacts'));
|
|
259
|
+
const db = join(stateDir, 'state.sqlite');
|
|
260
|
+
if (existsSync(db)) {
|
|
261
|
+
const h = new DatabaseSync(db, { readOnly: true });
|
|
262
|
+
try {
|
|
263
|
+
h.exec(`VACUUM INTO '${join(dest, 'state.sqlite').replaceAll("'", "''")}'`);
|
|
264
|
+
}
|
|
265
|
+
finally {
|
|
266
|
+
h.close();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
const files = [];
|
|
271
|
+
for (const path of await walk(dest))
|
|
272
|
+
files.push({ path, ...await sha256(join(dest, path)) });
|
|
273
|
+
await writeFile(join(dest, MANIFEST), `${JSON.stringify({ version: 1, createdAt: new Date().toISOString(), files }, null, 2)}\n`, { mode: 0o600 });
|
|
274
|
+
console.log(`backup written: ${dest}`);
|
|
275
|
+
console.log(`files: ${files.length} (sha256 manifest: ${MANIFEST}); only .ckit/ state is copied, never settings files or anything outside it`);
|
|
276
|
+
return 0;
|
|
277
|
+
}
|
|
278
|
+
/** True when every component of rel under base is a real directory and the leaf a regular file (no symlinks), and the real path stays inside base. */
|
|
279
|
+
async function isPlainFile(base, rel) {
|
|
280
|
+
let cur = base;
|
|
281
|
+
const parts = rel.split('/');
|
|
282
|
+
for (const [i, part] of parts.entries()) {
|
|
283
|
+
cur = join(cur, part);
|
|
284
|
+
let info;
|
|
285
|
+
try {
|
|
286
|
+
info = await lstat(cur);
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
if (info.isSymbolicLink() || (i < parts.length - 1 ? !info.isDirectory() : !info.isFile()))
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
const rb = realpathSync(base), rr = realpathSync(cur);
|
|
295
|
+
return rr.startsWith(`${rb}${sep}`);
|
|
296
|
+
}
|
|
297
|
+
export async function runRestore(args) {
|
|
298
|
+
const { positional, project, flags } = parseArgs(args, RESTORE_USAGE, 1, ['--allow-other-project']);
|
|
299
|
+
const { root, stateDir } = stateDirOf(project), backup = resolve(positional[0]);
|
|
300
|
+
let manifest;
|
|
301
|
+
try {
|
|
302
|
+
manifest = JSON.parse(await readFile(join(backup, MANIFEST), 'utf8'));
|
|
303
|
+
if (manifest.version !== 1 || !Array.isArray(manifest.files))
|
|
304
|
+
throw new Error('bad');
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
console.error('ckit: backup manifest missing or invalid; nothing was changed');
|
|
308
|
+
return 2;
|
|
309
|
+
}
|
|
310
|
+
for (const f of manifest.files) {
|
|
311
|
+
if (typeof f.path !== 'string' || f.path === '' || isAbsolute(f.path) || f.path.includes('\\') || f.path.split('/').some((part) => part === '..' || part === '' || part === '.')) {
|
|
312
|
+
console.error(`ckit: manifest path escapes the backup: ${safe(String(f.path))}; nothing was changed`);
|
|
313
|
+
return 2;
|
|
314
|
+
}
|
|
315
|
+
if (!await isPlainFile(backup, f.path)) {
|
|
316
|
+
console.error(`ckit: backup entry is a symlink, escapes the backup or is not a regular file: ${safe(f.path)}; nothing was changed`);
|
|
317
|
+
return 2;
|
|
318
|
+
}
|
|
319
|
+
const got = await sha256(join(backup, f.path));
|
|
320
|
+
if (got.sha256 !== f.sha256 || got.size !== f.size) {
|
|
321
|
+
console.error(`ckit: hash mismatch for ${safe(f.path)}; nothing was changed`);
|
|
322
|
+
return 2;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
let boundFrom;
|
|
326
|
+
if (manifest.files.some(f => f.path === 'project.json')) {
|
|
327
|
+
try {
|
|
328
|
+
boundFrom = JSON.parse(await readFile(join(backup, 'project.json'), 'utf8')).canonicalCwd;
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
boundFrom = undefined;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const other = boundFrom !== undefined && boundFrom !== root;
|
|
335
|
+
if (other && !flags.has('--allow-other-project')) {
|
|
336
|
+
console.error(`ckit: this backup came from another project (${safe(boundFrom)}); pass --allow-other-project to restore it here. Nothing was changed.`);
|
|
337
|
+
return 2;
|
|
338
|
+
}
|
|
339
|
+
const held = async () => existsSync(stateDir) && (await inspectJournalLock(stateDir)).state === 'held';
|
|
340
|
+
if (await held()) {
|
|
341
|
+
console.error('ckit: a live journal lock is held (a run is active); refusing to restore. Nothing was changed.');
|
|
342
|
+
return 2;
|
|
343
|
+
}
|
|
344
|
+
let aside = null;
|
|
345
|
+
if (existsSync(stateDir)) {
|
|
346
|
+
if (await held()) {
|
|
347
|
+
console.error('ckit: a live journal lock is held (a run is active); refusing to restore. Nothing was changed.');
|
|
348
|
+
return 2;
|
|
349
|
+
}
|
|
350
|
+
aside = join(root, `${STATE_DIR}.pre-restore-${stamp()}`);
|
|
351
|
+
await rename(stateDir, aside);
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
355
|
+
for (const f of manifest.files) {
|
|
356
|
+
const bytes = await readFile(join(backup, f.path));
|
|
357
|
+
if (createHash('sha256').update(bytes).digest('hex') !== f.sha256)
|
|
358
|
+
throw new Error(`hash mismatch for ${f.path} during copy`);
|
|
359
|
+
const to = join(stateDir, f.path);
|
|
360
|
+
await mkdir(dirname(to), { recursive: true });
|
|
361
|
+
await writeFile(to, bytes, { mode: 0o600 });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
await rm(stateDir, { recursive: true, force: true });
|
|
366
|
+
if (aside !== null)
|
|
367
|
+
await rename(aside, stateDir);
|
|
368
|
+
console.error(`ckit: restore failed and was rolled back: ${safe(error instanceof Error ? error.message : String(error))}`);
|
|
369
|
+
return 2;
|
|
370
|
+
}
|
|
371
|
+
console.log(`restored ${manifest.files.length} file(s) into ${stateDir}`);
|
|
372
|
+
if (aside !== null)
|
|
373
|
+
console.log(`previous state kept at ${aside} (never deleted)`);
|
|
374
|
+
console.log('delivery boundaries are restored as recorded: sent / UNKNOWN_DELIVERY stay unknown and must be reconciled; nothing is resent');
|
|
375
|
+
if (other) {
|
|
376
|
+
await rm(join(stateDir, 'project.json'), { force: true });
|
|
377
|
+
console.log(`note: backup came from ${boundFrom}; its project binding was not carried over. sessions/open/replay work here, but ckit status will fail for these sessions here (it needs the original project).`);
|
|
378
|
+
}
|
|
379
|
+
return 0;
|
|
380
|
+
}
|
|
381
|
+
//# sourceMappingURL=sessions.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface SetupIo {
|
|
2
|
+
readonly input: NodeJS.ReadableStream;
|
|
3
|
+
readonly output: NodeJS.WritableStream;
|
|
4
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
5
|
+
readonly dir: string;
|
|
6
|
+
readonly isTTY: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Replaces only the given keys (undefined removes), keeps every other line verbatim, appends new keys. */
|
|
9
|
+
export declare function mergeDotenv(existing: string, updates: Readonly<Record<string, string | undefined>>): string;
|
|
10
|
+
export declare function setupWith(args: readonly string[], io: SetupIo): Promise<number>;
|
|
11
|
+
export declare function runSetup(args: readonly string[]): Promise<number>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// `ckit setup`: guided writer for the per-user dotenv fallback. I/O is injectable so it is testable without a TTY. Never echoes or prints the API key.
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline/promises';
|
|
6
|
+
import { Writable } from 'node:stream';
|
|
7
|
+
import { loadCkitConfig, maskedConfigSummary, parseDotenv, userConfigDir } from '../settings/env-config.js';
|
|
8
|
+
const VARS = ['CKIT_OPENAI_BASE_URL', 'CKIT_OPENAI_API_KEY', 'CKIT_OPENAI_MODEL', 'CKIT_PRIMARY_MODEL', 'CKIT_REVIEWER_MODEL', 'CKIT_EXECUTOR', 'CKIT_EXECUTOR_PERMISSION_MODE', 'CKIT_REVIEWERS'];
|
|
9
|
+
const SETUP_USAGE = 'usage: ckit setup [--path]';
|
|
10
|
+
function quote(value) { return /^[^\s"'#\\]+$/.test(value) ? value : `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`; }
|
|
11
|
+
/** Replaces only the given keys (undefined removes), keeps every other line verbatim, appends new keys. */
|
|
12
|
+
export function mergeDotenv(existing, updates) {
|
|
13
|
+
const lines = existing === '' ? [] : existing.replace(/\r?\n$/, '').split(/\r?\n/), done = new Set(), out = [];
|
|
14
|
+
for (const line of lines) {
|
|
15
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line), key = m?.[1];
|
|
16
|
+
if (key === undefined || !(key in updates)) {
|
|
17
|
+
out.push(line);
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (done.has(key))
|
|
21
|
+
continue;
|
|
22
|
+
done.add(key);
|
|
23
|
+
const v = updates[key];
|
|
24
|
+
if (v !== undefined)
|
|
25
|
+
out.push(`${key}=${quote(v)}`);
|
|
26
|
+
}
|
|
27
|
+
for (const [key, v] of Object.entries(updates))
|
|
28
|
+
if (!done.has(key) && v !== undefined)
|
|
29
|
+
out.push(`${key}=${quote(v)}`);
|
|
30
|
+
return `${out.join('\n')}\n`;
|
|
31
|
+
}
|
|
32
|
+
export async function setupWith(args, io) {
|
|
33
|
+
const file = join(io.dir, '.env'), say = (text) => { io.output.write(`${text}\n`); };
|
|
34
|
+
if (args.length === 1 && args[0] === '--path') {
|
|
35
|
+
say(file);
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
if (args.length !== 0)
|
|
39
|
+
throw new TypeError(SETUP_USAGE);
|
|
40
|
+
if (!io.isTTY) {
|
|
41
|
+
say(`ckit setup needs an interactive terminal. Create ${file} (directory mode 0700, file mode 0600) with these variables:`);
|
|
42
|
+
say(` ${VARS.join('\n ')}`);
|
|
43
|
+
say('Required: CKIT_OPENAI_BASE_URL, CKIT_OPENAI_API_KEY, CKIT_OPENAI_MODEL. Then run: ckit doctor --check-connection');
|
|
44
|
+
return 2;
|
|
45
|
+
}
|
|
46
|
+
let existingText = '';
|
|
47
|
+
try {
|
|
48
|
+
existingText = readFileSync(file, 'utf8');
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error.code !== 'ENOENT') {
|
|
52
|
+
say(`ckit: cannot read ${file}`);
|
|
53
|
+
return 2;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const current = parseDotenv(existingText).values;
|
|
57
|
+
let muted = false;
|
|
58
|
+
const echo = new Writable({ write(chunk, _enc, cb) { if (!muted)
|
|
59
|
+
io.output.write(chunk); cb(); } });
|
|
60
|
+
const rl = createInterface({ input: io.input, output: echo, terminal: io.input.isTTY === true });
|
|
61
|
+
const lines = rl[Symbol.asyncIterator]();
|
|
62
|
+
const ask = async (label, dflt, hidden = false) => {
|
|
63
|
+
io.output.write(`${label}${dflt !== undefined && dflt !== '' ? ` [${dflt}]` : ''}: `);
|
|
64
|
+
muted = hidden;
|
|
65
|
+
try {
|
|
66
|
+
const next = await lines.next();
|
|
67
|
+
return next.done ? '' : next.value.trim();
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
muted = false;
|
|
71
|
+
if (hidden)
|
|
72
|
+
io.output.write('\n');
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
try {
|
|
76
|
+
say(`CKit setup. Writes ${file}. Press Enter to keep the value in [brackets].`);
|
|
77
|
+
const baseUrl = (await ask('API base URL, including the version segment, e.g. https://<host>/v1', current['CKIT_OPENAI_BASE_URL'])) || current['CKIT_OPENAI_BASE_URL'];
|
|
78
|
+
const hasKey = (current['CKIT_OPENAI_API_KEY'] ?? '') !== '';
|
|
79
|
+
const keyIn = await ask('API key (input hidden)', hasKey ? 'keep existing' : undefined, true);
|
|
80
|
+
const apiKey = keyIn || current['CKIT_OPENAI_API_KEY'];
|
|
81
|
+
const model = (await ask('Model', current['CKIT_OPENAI_MODEL'])) || current['CKIT_OPENAI_MODEL'];
|
|
82
|
+
const primary = (await ask('Primary model (optional)', current['CKIT_PRIMARY_MODEL'])) || current['CKIT_PRIMARY_MODEL'];
|
|
83
|
+
const reviewer = (await ask('Reviewer model (optional)', current['CKIT_REVIEWER_MODEL'])) || current['CKIT_REVIEWER_MODEL'];
|
|
84
|
+
const executor = (await ask('Worker executor (claude-code|omp)', current['CKIT_EXECUTOR'] || 'claude-code')) || current['CKIT_EXECUTOR'] || 'claude-code';
|
|
85
|
+
say('Worker permission: without a permission mode the worker cannot edit files. acceptEdits lets it edit files; dontAsk never prompts (denies anything not pre-allowed); none sets no mode. Bypass is never offered.');
|
|
86
|
+
const permIn = (await ask('Worker permission mode (acceptEdits|dontAsk|none)', current['CKIT_EXECUTOR_PERMISSION_MODE'] || 'acceptEdits')) || current['CKIT_EXECUTOR_PERMISSION_MODE'] || 'acceptEdits';
|
|
87
|
+
const reviewers = (await ask('Reviewers (0-3)', current['CKIT_REVIEWERS'] || '1')) || current['CKIT_REVIEWERS'] || '1';
|
|
88
|
+
const updates = { CKIT_OPENAI_BASE_URL: baseUrl, CKIT_OPENAI_API_KEY: apiKey, CKIT_OPENAI_MODEL: model, CKIT_PRIMARY_MODEL: primary, CKIT_REVIEWER_MODEL: reviewer, CKIT_EXECUTOR: executor, CKIT_EXECUTOR_PERMISSION_MODE: permIn === 'none' ? undefined : permIn, CKIT_REVIEWERS: reviewers };
|
|
89
|
+
const merged = mergeDotenv(existingText, updates);
|
|
90
|
+
const check = loadCkitConfig({ projectRoot: io.dir, env: {}, userDir: null, overrides: Object.fromEntries(Object.entries(parseDotenv(merged).values)) });
|
|
91
|
+
if (!check.ok) {
|
|
92
|
+
say('ckit: the answers are not valid; nothing was written:');
|
|
93
|
+
for (const issue of check.issues)
|
|
94
|
+
say(` ${issue.variable}: ${issue.problem}. ${issue.fix}`);
|
|
95
|
+
return 2;
|
|
96
|
+
}
|
|
97
|
+
mkdirSync(io.dir, { recursive: true, mode: 0o700 });
|
|
98
|
+
chmodSync(io.dir, 0o700);
|
|
99
|
+
const temp = join(io.dir, `.env.${randomBytes(6).toString('hex')}.tmp`);
|
|
100
|
+
writeFileSync(temp, merged, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
101
|
+
chmodSync(temp, 0o600);
|
|
102
|
+
renameSync(temp, file);
|
|
103
|
+
say(`Saved ${file}`);
|
|
104
|
+
say(maskedConfigSummary(check.config));
|
|
105
|
+
say('Next: ckit doctor --check-connection, then run ckit (GUI) or ckit team "<goal>" inside your project folder');
|
|
106
|
+
return 0;
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
rl.close();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
export async function runSetup(args) {
|
|
113
|
+
return setupWith(args, { input: process.stdin, output: process.stdout, env: process.env, dir: userConfigDir(process.env), isTTY: process.stdin.isTTY === true && process.stdout.isTTY === true });
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=setup.js.map
|