@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.
Files changed (246) hide show
  1. package/.env.example +21 -0
  2. package/README.md +70 -2
  3. package/dist/src/adapters/agent/claude/errors.d.ts +13 -0
  4. package/dist/src/adapters/agent/claude/errors.js +16 -0
  5. package/dist/src/adapters/agent/claude/normalize.d.ts +11 -0
  6. package/dist/src/adapters/agent/claude/normalize.js +83 -0
  7. package/dist/src/adapters/agent/errors.d.ts +13 -0
  8. package/dist/src/adapters/agent/errors.js +19 -0
  9. package/dist/src/adapters/agent/fixtures/claude-transcript.d.ts +70 -0
  10. package/dist/src/adapters/agent/fixtures/claude-transcript.js +15 -0
  11. package/dist/src/adapters/agent/fixtures/omp-transcript.d.ts +60 -0
  12. package/dist/src/adapters/agent/fixtures/omp-transcript.js +14 -0
  13. package/dist/src/adapters/agent/normalize.d.ts +18 -0
  14. package/dist/src/adapters/agent/normalize.js +77 -0
  15. package/dist/src/adapters/agent/transport.d.ts +35 -0
  16. package/dist/src/adapters/agent/transport.js +39 -0
  17. package/dist/src/adapters/agent/worker-service.d.ts +49 -0
  18. package/dist/src/adapters/agent/worker-service.js +77 -0
  19. package/dist/src/adapters/fake/fake-advisor.d.ts +15 -0
  20. package/dist/src/adapters/fake/fake-advisor.js +29 -0
  21. package/dist/src/adapters/fake/fake-agent.d.ts +12 -0
  22. package/dist/src/adapters/fake/fake-agent.js +21 -0
  23. package/dist/src/adapters/fake/fake-store.d.ts +13 -0
  24. package/dist/src/adapters/fake/fake-store.js +23 -0
  25. package/dist/src/adapters/fake/fake-web.d.ts +12 -0
  26. package/dist/src/adapters/fake/fake-web.js +21 -0
  27. package/dist/src/adapters/fake/fault-injector.d.ts +18 -0
  28. package/dist/src/adapters/fake/fault-injector.js +64 -0
  29. package/dist/src/adapters/fake/virtual-clock.d.ts +12 -0
  30. package/dist/src/adapters/fake/virtual-clock.js +35 -0
  31. package/dist/src/adapters/launch/discover.d.ts +18 -0
  32. package/dist/src/adapters/launch/discover.js +55 -0
  33. package/dist/src/adapters/launch/executor.d.ts +117 -0
  34. package/dist/src/adapters/launch/executor.js +383 -0
  35. package/dist/src/adapters/launch/profile.d.ts +35 -0
  36. package/dist/src/adapters/launch/profile.js +73 -0
  37. package/dist/src/adapters/launch/spawn.d.ts +29 -0
  38. package/dist/src/adapters/launch/spawn.js +18 -0
  39. package/dist/src/adapters/openai/openai-advisor.d.ts +56 -0
  40. package/dist/src/adapters/openai/openai-advisor.js +146 -0
  41. package/dist/src/cli/ckit.d.ts +5 -0
  42. package/dist/src/cli/ckit.js +384 -0
  43. package/dist/src/cli/demo.d.ts +1 -0
  44. package/dist/src/cli/demo.js +30 -0
  45. package/dist/src/cli/lifecycle.d.ts +19 -0
  46. package/dist/src/cli/lifecycle.js +90 -0
  47. package/dist/src/cli/sessions.d.ts +10 -0
  48. package/dist/src/cli/sessions.js +381 -0
  49. package/dist/src/cli/setup.d.ts +11 -0
  50. package/dist/src/cli/setup.js +115 -0
  51. package/dist/src/committee/decision.d.ts +84 -0
  52. package/dist/src/committee/decision.js +167 -0
  53. package/dist/src/committee/handover.d.ts +115 -0
  54. package/dist/src/committee/handover.js +191 -0
  55. package/dist/src/committee/no-progress.d.ts +44 -0
  56. package/dist/src/committee/no-progress.js +64 -0
  57. package/dist/src/committee/primary-registry.d.ts +15 -0
  58. package/dist/src/committee/primary-registry.js +60 -0
  59. package/dist/src/committee/reply-parser.d.ts +28 -0
  60. package/dist/src/committee/reply-parser.js +53 -0
  61. package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
  62. package/dist/src/committee/reviewer-scheduler.js +163 -0
  63. package/dist/src/committee/role-epoch.d.ts +91 -0
  64. package/dist/src/committee/role-epoch.js +154 -0
  65. package/dist/src/core/control.d.ts +18 -0
  66. package/dist/src/core/control.js +29 -0
  67. package/dist/src/core/entities.d.ts +166 -0
  68. package/dist/src/core/entities.js +119 -0
  69. package/dist/src/core/errors.d.ts +9 -0
  70. package/dist/src/core/errors.js +17 -0
  71. package/dist/src/core/events.d.ts +72 -0
  72. package/dist/src/core/events.js +125 -0
  73. package/dist/src/core/ids.d.ts +47 -0
  74. package/dist/src/core/ids.js +32 -0
  75. package/dist/src/core/machine.d.ts +55 -0
  76. package/dist/src/core/machine.js +110 -0
  77. package/dist/src/core/policy.d.ts +34 -0
  78. package/dist/src/core/policy.js +59 -0
  79. package/dist/src/core/provenance.d.ts +20 -0
  80. package/dist/src/core/provenance.js +21 -0
  81. package/dist/src/core/record.d.ts +35 -0
  82. package/dist/src/core/record.js +67 -0
  83. package/dist/src/core/replay.d.ts +10 -0
  84. package/dist/src/core/replay.js +36 -0
  85. package/dist/src/core/run-task.d.ts +20 -0
  86. package/dist/src/core/run-task.js +48 -0
  87. package/dist/src/diagnostics/doctor.d.ts +78 -0
  88. package/dist/src/diagnostics/doctor.js +365 -0
  89. package/dist/src/diagnostics/journal-lock.d.ts +38 -0
  90. package/dist/src/diagnostics/journal-lock.js +181 -0
  91. package/dist/src/evidence/linker.d.ts +44 -0
  92. package/dist/src/evidence/linker.js +75 -0
  93. package/dist/src/evidence/report-parser.d.ts +27 -0
  94. package/dist/src/evidence/report-parser.js +17 -0
  95. package/dist/src/evidence/store.d.ts +36 -0
  96. package/dist/src/evidence/store.js +57 -0
  97. package/dist/src/gui/server.d.ts +27 -0
  98. package/dist/src/gui/server.js +497 -0
  99. package/dist/src/host/checkpoint.d.ts +22 -0
  100. package/dist/src/host/checkpoint.js +74 -0
  101. package/dist/src/host/export.d.ts +52 -0
  102. package/dist/src/host/export.js +45 -0
  103. package/dist/src/host/ipc.d.ts +57 -0
  104. package/dist/src/host/ipc.js +124 -0
  105. package/dist/src/host/leases.d.ts +27 -0
  106. package/dist/src/host/leases.js +40 -0
  107. package/dist/src/host/retention.d.ts +47 -0
  108. package/dist/src/host/retention.js +130 -0
  109. package/dist/src/host/supervisor.d.ts +59 -0
  110. package/dist/src/host/supervisor.js +64 -0
  111. package/dist/src/intake/owner-intake.d.ts +31 -0
  112. package/dist/src/intake/owner-intake.js +97 -0
  113. package/dist/src/intake/types.d.ts +46 -0
  114. package/dist/src/intake/types.js +2 -0
  115. package/dist/src/intent/context-packet.d.ts +68 -0
  116. package/dist/src/intent/context-packet.js +76 -0
  117. package/dist/src/intent/idea-ledger.d.ts +50 -0
  118. package/dist/src/intent/idea-ledger.js +136 -0
  119. package/dist/src/intent/ledger.d.ts +35 -0
  120. package/dist/src/intent/ledger.js +40 -0
  121. package/dist/src/intent/registry.d.ts +51 -0
  122. package/dist/src/intent/registry.js +44 -0
  123. package/dist/src/intent/revision.d.ts +37 -0
  124. package/dist/src/intent/revision.js +48 -0
  125. package/dist/src/orchestration/dispatcher.d.ts +32 -0
  126. package/dist/src/orchestration/dispatcher.js +136 -0
  127. package/dist/src/orchestration/milestone-loop.d.ts +149 -0
  128. package/dist/src/orchestration/milestone-loop.js +132 -0
  129. package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
  130. package/dist/src/orchestration/recovery-coordinator.js +180 -0
  131. package/dist/src/orchestration/work-order-contract.d.ts +44 -0
  132. package/dist/src/orchestration/work-order-contract.js +85 -0
  133. package/dist/src/orchestration/work-queue.d.ts +56 -0
  134. package/dist/src/orchestration/work-queue.js +95 -0
  135. package/dist/src/ports/advisor.d.ts +33 -0
  136. package/dist/src/ports/advisor.js +2 -0
  137. package/dist/src/ports/agent.d.ts +31 -0
  138. package/dist/src/ports/agent.js +2 -0
  139. package/dist/src/ports/capabilities.d.ts +3 -0
  140. package/dist/src/ports/capabilities.js +5 -0
  141. package/dist/src/ports/clock.d.ts +5 -0
  142. package/dist/src/ports/clock.js +5 -0
  143. package/dist/src/ports/store.d.ts +13 -0
  144. package/dist/src/ports/store.js +2 -0
  145. package/dist/src/ports/web.d.ts +29 -0
  146. package/dist/src/ports/web.js +2 -0
  147. package/dist/src/run/api-run.d.ts +49 -0
  148. package/dist/src/run/api-run.js +173 -0
  149. package/dist/src/run/plan-run.d.ts +22 -0
  150. package/dist/src/run/plan-run.js +233 -0
  151. package/dist/src/run/plan.d.ts +36 -0
  152. package/dist/src/run/plan.js +119 -0
  153. package/dist/src/run/verify.d.ts +25 -0
  154. package/dist/src/run/verify.js +81 -0
  155. package/dist/src/security/redact.d.ts +7 -0
  156. package/dist/src/security/redact.js +21 -0
  157. package/dist/src/settings/env-config.d.ts +64 -0
  158. package/dist/src/settings/env-config.js +232 -0
  159. package/dist/src/storage/artifacts.d.ts +30 -0
  160. package/dist/src/storage/artifacts.js +105 -0
  161. package/dist/src/storage/audit.d.ts +6 -0
  162. package/dist/src/storage/audit.js +6 -0
  163. package/dist/src/storage/db.d.ts +9 -0
  164. package/dist/src/storage/db.js +43 -0
  165. package/dist/src/storage/events.d.ts +20 -0
  166. package/dist/src/storage/events.js +69 -0
  167. package/dist/src/storage/migrations.d.ts +8 -0
  168. package/dist/src/storage/migrations.js +48 -0
  169. package/dist/src/storage/outbox.d.ts +25 -0
  170. package/dist/src/storage/outbox.js +40 -0
  171. package/dist/src/storage/projections.d.ts +18 -0
  172. package/dist/src/storage/projections.js +40 -0
  173. package/dist/src/storage/reconcile.d.ts +14 -0
  174. package/dist/src/storage/reconcile.js +93 -0
  175. package/dist/src/storage/reservations.d.ts +12 -0
  176. package/dist/src/storage/reservations.js +80 -0
  177. package/dist/src/storage/store.d.ts +34 -0
  178. package/dist/src/storage/store.js +105 -0
  179. package/dist/src/team/attachments.d.ts +22 -0
  180. package/dist/src/team/attachments.js +211 -0
  181. package/dist/src/team/cli-models.d.ts +24 -0
  182. package/dist/src/team/cli-models.js +72 -0
  183. package/dist/src/team/config.d.ts +20 -0
  184. package/dist/src/team/config.js +113 -0
  185. package/dist/src/team/engine.d.ts +28 -0
  186. package/dist/src/team/engine.js +443 -0
  187. package/dist/src/team/journal.d.ts +30 -0
  188. package/dist/src/team/journal.js +70 -0
  189. package/dist/src/team/runners.d.ts +79 -0
  190. package/dist/src/team/runners.js +436 -0
  191. package/dist/src/team/secrets.d.ts +10 -0
  192. package/dist/src/team/secrets.js +68 -0
  193. package/dist/src/team/types.d.ts +157 -0
  194. package/dist/src/team/types.js +5 -0
  195. package/dist/src/tui/app.d.ts +29 -0
  196. package/dist/src/tui/app.js +96 -0
  197. package/dist/src/tui/control-model.d.ts +101 -0
  198. package/dist/src/tui/control-model.js +109 -0
  199. package/dist/src/tui/control-screens.d.ts +27 -0
  200. package/dist/src/tui/control-screens.js +85 -0
  201. package/dist/src/tui/graph-model.d.ts +34 -0
  202. package/dist/src/tui/graph-model.js +29 -0
  203. package/dist/src/tui/graph-screens.d.ts +13 -0
  204. package/dist/src/tui/graph-screens.js +4 -0
  205. package/dist/src/tui/inspector-model.d.ts +150 -0
  206. package/dist/src/tui/inspector-model.js +15 -0
  207. package/dist/src/tui/inspector-screens.d.ts +14 -0
  208. package/dist/src/tui/inspector-screens.js +61 -0
  209. package/dist/src/tui/live.d.ts +16 -0
  210. package/dist/src/tui/live.js +39 -0
  211. package/dist/src/tui/mission-action-screens.d.ts +15 -0
  212. package/dist/src/tui/mission-action-screens.js +105 -0
  213. package/dist/src/tui/mission-actions.d.ts +46 -0
  214. package/dist/src/tui/mission-actions.js +53 -0
  215. package/dist/src/tui/mission-model.d.ts +120 -0
  216. package/dist/src/tui/mission-model.js +164 -0
  217. package/dist/src/tui/mission-nav.d.ts +82 -0
  218. package/dist/src/tui/mission-nav.js +131 -0
  219. package/dist/src/tui/mission-plan-screens.d.ts +11 -0
  220. package/dist/src/tui/mission-plan-screens.js +40 -0
  221. package/dist/src/tui/mission-plan.d.ts +45 -0
  222. package/dist/src/tui/mission-plan.js +166 -0
  223. package/dist/src/tui/mission-screens.d.ts +7 -0
  224. package/dist/src/tui/mission-screens.js +263 -0
  225. package/dist/src/tui/provenance-label.d.ts +11 -0
  226. package/dist/src/tui/provenance-label.js +16 -0
  227. package/dist/src/tui/screens.d.ts +10 -0
  228. package/dist/src/tui/screens.js +34 -0
  229. package/dist/src/tui/session-outcome.d.ts +14 -0
  230. package/dist/src/tui/session-outcome.js +57 -0
  231. package/dist/src/tui/setup-model.d.ts +159 -0
  232. package/dist/src/tui/setup-model.js +234 -0
  233. package/dist/src/tui/setup-screens.d.ts +66 -0
  234. package/dist/src/tui/setup-screens.js +72 -0
  235. package/dist/src/tui/team/app.d.ts +24 -0
  236. package/dist/src/tui/team/app.js +228 -0
  237. package/dist/src/tui/team/demo-handle.d.ts +22 -0
  238. package/dist/src/tui/team/demo-handle.js +42 -0
  239. package/dist/src/tui/team/model.d.ts +81 -0
  240. package/dist/src/tui/team/model.js +133 -0
  241. package/gui/app.css +177 -0
  242. package/gui/app.js +677 -0
  243. package/gui/index.html +51 -0
  244. package/gui/network.js +413 -0
  245. package/package.json +44 -4
  246. package/src/storage/schema.sql +42 -0
@@ -0,0 +1,25 @@
1
+ import { type SpawnImpl } from '../adapters/launch/executor.js';
2
+ import type { CkitConfig } from '../settings/env-config.js';
3
+ import { type Acceptance } from './plan.js';
4
+ export interface CheckResult {
5
+ readonly taskId: string;
6
+ readonly checkId: string;
7
+ readonly required: boolean;
8
+ readonly status: 'pass' | 'fail' | 'manual-pending' | 'error';
9
+ readonly detail: string;
10
+ }
11
+ export interface VerifyOptions {
12
+ readonly projectRoot: string;
13
+ readonly config: Pick<CkitConfig, 'verifyAllow' | 'verifyTimeoutMs' | 'apiKey'>;
14
+ readonly env?: Readonly<Record<string, string | undefined>>;
15
+ readonly signal?: AbortSignal;
16
+ readonly spawnImpl?: SpawnImpl;
17
+ }
18
+ export declare function checkFileExists(projectRoot: string, path: string): {
19
+ status: 'pass' | 'fail' | 'error';
20
+ detail: string;
21
+ };
22
+ /** Runs every acceptance entry of one task; every result is attributed to that task id only. */
23
+ export declare function verifyTask(taskId: string, checks: readonly Acceptance[], options: VerifyOptions): Promise<CheckResult[]>;
24
+ /** A task is verified only when it has a required check and every required check passed. */
25
+ export declare function requiredAllPassed(results: readonly CheckResult[]): boolean;
@@ -0,0 +1,81 @@
1
+ // Acceptance verification for one plan task: file-exists is pure fs inside the project root; commands go through the executor module.
2
+ import { realpathSync, statSync } from 'node:fs';
3
+ import { isAbsolute, relative, resolve } from 'node:path';
4
+ import { executorEnvironment, runAcceptanceCommand, splitCommand } from '../adapters/launch/executor.js';
5
+ import { commandAllowed, SHELL_META } from './plan.js';
6
+ export function checkFileExists(projectRoot, path) {
7
+ if (isAbsolute(path) || path.split(/[\\/]/).includes('..'))
8
+ return { status: 'error', detail: 'path is absolute or escapes the project root' };
9
+ let root, real;
10
+ try {
11
+ root = realpathSync(projectRoot);
12
+ }
13
+ catch {
14
+ return { status: 'error', detail: 'project root is not accessible' };
15
+ }
16
+ try {
17
+ real = realpathSync(resolve(root, path));
18
+ }
19
+ catch {
20
+ return { status: 'fail', detail: `${path} does not exist` };
21
+ }
22
+ const rel = relative(root, real);
23
+ if (rel.startsWith('..') || isAbsolute(rel))
24
+ return { status: 'error', detail: `${path} resolves outside the project root` };
25
+ try {
26
+ statSync(real);
27
+ }
28
+ catch {
29
+ return { status: 'fail', detail: `${path} is not accessible` };
30
+ }
31
+ return { status: 'pass', detail: `${path} exists` };
32
+ }
33
+ /** Runs every acceptance entry of one task; every result is attributed to that task id only. */
34
+ export async function verifyTask(taskId, checks, options) {
35
+ const results = [];
36
+ for (const c of checks) {
37
+ const mk = (status, detail) => { results.push({ taskId, checkId: c.id, required: c.required, status, detail }); };
38
+ if (c.kind === 'manual') {
39
+ mk('manual-pending', 'needs owner acceptance');
40
+ continue;
41
+ }
42
+ if (c.kind === 'file-exists') {
43
+ const r = checkFileExists(options.projectRoot, c.path ?? '');
44
+ mk(r.status, r.detail);
45
+ continue;
46
+ }
47
+ const command = c.command ?? '';
48
+ // Re-validated at run time: the allow-list may differ from parse time only by caller error, never silently widened.
49
+ if (SHELL_META.test(command) || !commandAllowed(command, options.config.verifyAllow)) {
50
+ mk('error', 'command is not allowed');
51
+ continue;
52
+ }
53
+ let argv;
54
+ try {
55
+ argv = splitCommand(command);
56
+ }
57
+ catch (error) {
58
+ mk('error', error instanceof Error ? error.message : 'unparseable command');
59
+ continue;
60
+ }
61
+ const r = await runAcceptanceCommand(argv, { cwd: options.projectRoot, timeoutMs: options.config.verifyTimeoutMs, env: executorEnvironment(options.env ?? process.env, options.config.apiKey), ...(options.signal ? { signal: options.signal } : {}), ...(options.spawnImpl ? { spawnImpl: options.spawnImpl } : {}) });
62
+ const tail = r.output.trim().slice(-400);
63
+ if (r.spawnError !== null)
64
+ mk('error', `could not start: ${r.spawnError}`);
65
+ else if (r.timedOut)
66
+ mk('error', 'timed out and was killed');
67
+ else if (r.cancelled)
68
+ mk('error', 'cancelled');
69
+ else if (r.exitCode === 0)
70
+ mk('pass', `exit 0${tail ? `: ${tail}` : ''}`);
71
+ else
72
+ mk('fail', `exit ${r.exitCode ?? r.signal ?? 'unknown'}${tail ? `: ${tail}` : ''}`);
73
+ }
74
+ return results;
75
+ }
76
+ /** A task is verified only when it has a required check and every required check passed. */
77
+ export function requiredAllPassed(results) {
78
+ const req = results.filter(r => r.required);
79
+ return req.length > 0 && req.every(r => r.status === 'pass');
80
+ }
81
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1,7 @@
1
+ /** Single source of truth for secret-shaped text and credential-like key names. */
2
+ /** Key names whose values are credentials (superset of profile.secretKeyPattern). */
3
+ export declare const credentialKeyPattern: RegExp;
4
+ /** True when free text contains a secret-shaped assignment or bearer credential. */
5
+ export declare function containsSecretText(value: string): boolean;
6
+ /** Replace every secret-shaped value with '[REDACTED]' (keeps the key/keyword), plus every literal in knownSecretValues. Idempotent. */
7
+ export declare function redactSecretText(value: string, knownSecretValues?: readonly string[]): string;
@@ -0,0 +1,21 @@
1
+ /** Single source of truth for secret-shaped text and credential-like key names. */
2
+ /** Key names whose values are credentials (superset of profile.secretKeyPattern). */
3
+ export const credentialKeyPattern = /(?:token|secret|pass|key|pat|cookie|credential|auth|[_-]pwd$)/i;
4
+ const REDACTED = '[REDACTED]';
5
+ // Keyword must not follow a letter/digit, and a suffix is allowed only when it ends in a credential word (`SECRET_KEY`, `tokenValue`), so `tokenizer:`/`Secrets:`/`password_policy:` stay prose. JSON-quoted keys (`"password":"x"`) match too.
6
+ // Extra keywords: separator-joined `<word>[_-](pass|pwd|pat)` (DB_PASS, MYSQL_PWD, GH_PAT) and `pgpassword`; bare pwd/pass/pat stay prose. The value is a quoted run (`"…"`, escapes allowed, fail-closed when unterminated) or a `\S+` run; an already-redacted value is never re-matched (idempotent).
7
+ const ASSIGNMENT = /((?<![a-z0-9])(?:pgpassword|[a-z][a-z0-9]*[_-](?:pass|pwd|pat)|(?:api[_ -]?key|private[_ -]?key|token|password|passwd|secret|cookie|credentials?|authorization|passphrase)(?:[\w.-]*?(?:key|token|secret|password|passwd|pass|cookie|value|hash))?)"?\s*[:=]\s*)("(?!\[REDACTED\]")(?:(?:[^"\\]|\\.)*"|\S*)|(?!"|\[REDACTED\])(?:bearer\s+)?(?!\[REDACTED\])\S+)/gi;
8
+ const BEARER = /\bbearer\s+(?!\[REDACTED\])[\w.~+/-]+=*/gi;
9
+ /** True when free text contains a secret-shaped assignment or bearer credential. */
10
+ export function containsSecretText(value) {
11
+ return redactSecretText(value) !== value;
12
+ }
13
+ /** Replace every secret-shaped value with '[REDACTED]' (keeps the key/keyword), plus every literal in knownSecretValues. Idempotent. */
14
+ export function redactSecretText(value, knownSecretValues = []) {
15
+ let safe = value.replace(ASSIGNMENT, (_match, prefix, secret) => `${prefix}${secret.startsWith('"') ? `"${REDACTED}"` : REDACTED}`).replace(BEARER, `Bearer ${REDACTED}`);
16
+ for (const secret of knownSecretValues)
17
+ if (secret)
18
+ safe = safe.split(secret).join(REDACTED);
19
+ return safe;
20
+ }
21
+ //# sourceMappingURL=redact.js.map
@@ -0,0 +1,64 @@
1
+ export interface DotenvResult {
2
+ readonly values: Readonly<Record<string, string>>;
3
+ readonly issues: readonly string[];
4
+ }
5
+ /** Parses KEY=VALUE lines. No interpolation. A malformed line yields an issue naming only its line number. */
6
+ export declare function parseDotenv(text: string): DotenvResult;
7
+ /** Explicit path wins; else nearest ancestor of realpath(cwd) with .ckit/project.json, then nearest with .git, else cwd. */
8
+ export declare function resolveProjectRoot(cwd: string, explicit?: string): string;
9
+ export type ConfigSource = 'cli' | 'env' | 'file' | 'user' | 'default';
10
+ /** Per-user settings dir (XDG_CONFIG_HOME, else ~/.config) + /ckit; holds the fallback .env written by `ckit setup`. */
11
+ export declare function userConfigDir(env?: Readonly<Record<string, string | undefined>>): string;
12
+ export declare const EXECUTOR_PERMISSION_MODES: readonly ['acceptEdits', 'dontAsk'];
13
+ export type ExecutorPermissionMode = typeof EXECUTOR_PERMISSION_MODES[number];
14
+ export interface CkitConfig {
15
+ readonly provider: 'openai-compatible';
16
+ readonly baseUrl: string;
17
+ readonly auth: 'bearer' | 'none';
18
+ readonly apiKey: string;
19
+ readonly model: string;
20
+ readonly primaryModel: string;
21
+ readonly reviewerModel: string;
22
+ readonly reviewers: number;
23
+ readonly timeoutMs: number;
24
+ readonly maxTokens: number | null;
25
+ readonly executor: 'claude-code' | 'omp';
26
+ readonly executorPath: string | null;
27
+ readonly executorModel: string | null;
28
+ readonly executorTimeoutMs: number;
29
+ /** Opt-in claude-code `--permission-mode`; null = flag omitted (today's behaviour). bypassPermissions is never accepted. */
30
+ readonly executorPermissionMode: ExecutorPermissionMode | null;
31
+ /** Allow-listed command prefixes for plan acceptance checks (whole-token match). */
32
+ readonly verifyAllow: readonly string[];
33
+ readonly verifyTimeoutMs: number;
34
+ readonly maxTasks: number;
35
+ }
36
+ export interface ConfigIssue {
37
+ readonly variable: string;
38
+ readonly problem: string;
39
+ readonly fix: string;
40
+ }
41
+ export type ConfigResult = {
42
+ readonly ok: true;
43
+ readonly config: CkitConfig;
44
+ readonly sources: Readonly<Record<string, ConfigSource>>;
45
+ readonly projectRoot: string;
46
+ readonly configFile: string | null;
47
+ } | {
48
+ readonly ok: false;
49
+ readonly issues: readonly ConfigIssue[];
50
+ };
51
+ /** Every variable CKit reads; .env.example lists exactly these. */
52
+ export declare const CONFIG_VARIABLES: readonly ['CKIT_ADVISOR_PROVIDER', 'CKIT_OPENAI_BASE_URL', 'CKIT_OPENAI_AUTH', 'CKIT_OPENAI_API_KEY', 'CKIT_OPENAI_MODEL', 'CKIT_PRIMARY_MODEL', 'CKIT_REVIEWER_MODEL', 'CKIT_REVIEWERS', 'CKIT_OPENAI_TIMEOUT_MS', 'CKIT_OPENAI_MAX_TOKENS', 'CKIT_EXECUTOR', 'CKIT_EXECUTOR_PATH', 'CKIT_EXECUTOR_MODEL', 'CKIT_EXECUTOR_TIMEOUT_MS', 'CKIT_EXECUTOR_PERMISSION_MODE', 'CKIT_VERIFY_ALLOW', 'CKIT_VERIFY_TIMEOUT_MS', 'CKIT_MAX_TASKS'];
53
+ export declare const DEFAULT_VERIFY_ALLOW: readonly string[];
54
+ export declare function readDotenvFile(projectRoot: string): DotenvResult;
55
+ export declare function loadCkitConfig(input: {
56
+ readonly projectRoot: string;
57
+ readonly env?: Readonly<Record<string, string | undefined>>;
58
+ readonly overrides?: Readonly<Record<string, string | undefined>>;
59
+ readonly userDir?: string | null;
60
+ }): ConfigResult;
61
+ /** Display-safe summary: never contains the key, only whether one is set. */
62
+ export declare function maskedConfigSummary(config: CkitConfig): string;
63
+ /** True when any CKit variable is present at all (separates the unconfigured state from an invalid one). */
64
+ export declare function hasAnyAdvisorConfig(projectRoot: string, env?: Readonly<Record<string, string | undefined>>, userDir?: string | null): boolean;
@@ -0,0 +1,232 @@
1
+ // Dotenv-based CKit settings (ADR-017). Pure: never mutates process.env, never prints values.
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ /** Parses KEY=VALUE lines. No interpolation. A malformed line yields an issue naming only its line number. */
6
+ export function parseDotenv(text) {
7
+ const values = {}, issues = [];
8
+ const lines = text.replace(/^/, '').split(/\r?\n/);
9
+ lines.forEach((raw, index) => {
10
+ const line = raw.trim();
11
+ if (line === '' || line.startsWith('#'))
12
+ return;
13
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
14
+ if (!match) {
15
+ issues.push(`line ${index + 1} is not KEY=VALUE`);
16
+ return;
17
+ }
18
+ const key = match[1], rest = match[2].trim();
19
+ if (rest.startsWith('"')) {
20
+ let out = '', i = 1, closed = false;
21
+ for (; i < rest.length; i++) {
22
+ const ch = rest[i];
23
+ if (ch === '\\' && i + 1 < rest.length) {
24
+ const next = rest[i + 1];
25
+ out += next === 'n' ? '\n' : next === '"' ? '"' : next === '\\' ? '\\' : `\\${next}`;
26
+ i++;
27
+ }
28
+ else if (ch === '"') {
29
+ closed = true;
30
+ break;
31
+ }
32
+ else
33
+ out += ch;
34
+ }
35
+ const tail = rest.slice(i + 1).trim();
36
+ if (!closed || (tail !== '' && !tail.startsWith('#'))) {
37
+ issues.push(`line ${index + 1} has an unterminated or malformed quoted value`);
38
+ return;
39
+ }
40
+ values[key] = out;
41
+ }
42
+ else if (rest.startsWith("'")) {
43
+ const end = rest.indexOf("'", 1);
44
+ const tail = end < 0 ? '' : rest.slice(end + 1).trim();
45
+ if (end < 0 || (tail !== '' && !tail.startsWith('#'))) {
46
+ issues.push(`line ${index + 1} has an unterminated or malformed quoted value`);
47
+ return;
48
+ }
49
+ values[key] = rest.slice(1, end);
50
+ }
51
+ else
52
+ values[key] = rest.replace(/\s+#.*$/, '').trim();
53
+ });
54
+ return { values, issues };
55
+ }
56
+ /** Explicit path wins; else nearest ancestor of realpath(cwd) with .ckit/project.json, then nearest with .git, else cwd. */
57
+ export function resolveProjectRoot(cwd, explicit) {
58
+ const real = (path) => { try {
59
+ return realpathSync(resolve(path));
60
+ }
61
+ catch {
62
+ return resolve(path);
63
+ } };
64
+ if (explicit !== undefined)
65
+ return real(explicit);
66
+ const start = real(cwd);
67
+ for (const marker of [join('.ckit', 'project.json'), '.git']) {
68
+ let dir = start;
69
+ for (;;) {
70
+ if (existsSync(join(dir, marker)))
71
+ return dir;
72
+ const parent = dirname(dir);
73
+ if (parent === dir)
74
+ break;
75
+ dir = parent;
76
+ }
77
+ }
78
+ return start;
79
+ }
80
+ /** Per-user settings dir (XDG_CONFIG_HOME, else ~/.config) + /ckit; holds the fallback .env written by `ckit setup`. */
81
+ export function userConfigDir(env = process.env) { return join(env['XDG_CONFIG_HOME'] || join(homedir(), '.config'), 'ckit'); }
82
+ /** User dir derived only from the given env (XDG_CONFIG_HOME, then HOME); null when neither is set, so a caller-supplied env never picks up the real home. */
83
+ const userDirFromEnv = (env) => env['XDG_CONFIG_HOME'] ? join(env['XDG_CONFIG_HOME'], 'ckit') : env['HOME'] ? join(env['HOME'], '.config', 'ckit') : null;
84
+ export const EXECUTOR_PERMISSION_MODES = ['acceptEdits', 'dontAsk'];
85
+ /** Every variable CKit reads; .env.example lists exactly these. */
86
+ export const CONFIG_VARIABLES = ['CKIT_ADVISOR_PROVIDER', 'CKIT_OPENAI_BASE_URL', 'CKIT_OPENAI_AUTH', 'CKIT_OPENAI_API_KEY', 'CKIT_OPENAI_MODEL', 'CKIT_PRIMARY_MODEL', 'CKIT_REVIEWER_MODEL', 'CKIT_REVIEWERS', 'CKIT_OPENAI_TIMEOUT_MS', 'CKIT_OPENAI_MAX_TOKENS', 'CKIT_EXECUTOR', 'CKIT_EXECUTOR_PATH', 'CKIT_EXECUTOR_MODEL', 'CKIT_EXECUTOR_TIMEOUT_MS', 'CKIT_EXECUTOR_PERMISSION_MODE', 'CKIT_VERIFY_ALLOW', 'CKIT_VERIFY_TIMEOUT_MS', 'CKIT_MAX_TASKS'];
87
+ export const DEFAULT_VERIFY_ALLOW = ['npm test', 'npm run build', 'npm run lint', 'npm run typecheck', 'npx tsc --noEmit', 'node --test', 'pytest', 'go test', 'cargo test', 'make test'];
88
+ export function readDotenvFile(projectRoot) {
89
+ try {
90
+ return parseDotenv(readFileSync(join(projectRoot, '.env'), 'utf8'));
91
+ }
92
+ catch (error) {
93
+ if (error.code === 'ENOENT')
94
+ return { values: {}, issues: [] };
95
+ return { values: {}, issues: ['the dotenv file is unreadable'] };
96
+ }
97
+ }
98
+ export function loadCkitConfig(input) {
99
+ const env = input.env ?? process.env, overrides = input.overrides ?? {};
100
+ const file = readDotenvFile(input.projectRoot);
101
+ const userDir = input.userDir === undefined ? userDirFromEnv(env) : input.userDir;
102
+ const userFile = userDir === null ? { values: {}, issues: [] } : readDotenvFile(userDir);
103
+ const projectPath = join(input.projectRoot, '.env'), userPath = userDir === null ? null : join(userDir, '.env');
104
+ const configFile = existsSync(projectPath) ? projectPath : userPath !== null && existsSync(userPath) ? userPath : null;
105
+ const issues = [];
106
+ const sources = {};
107
+ const where = configFile ?? userPath ?? projectPath, hint = configFile === null && userPath !== null ? ' (or run `ckit setup`)' : '';
108
+ for (const problem of file.issues)
109
+ issues.push({ variable: '(dotenv file)', problem, fix: `fix the syntax in ${projectPath} (KEY=VALUE per line)` });
110
+ for (const problem of userFile.issues)
111
+ issues.push({ variable: '(dotenv file)', problem, fix: `fix the syntax in ${userPath} (KEY=VALUE per line)` });
112
+ const get = (name) => {
113
+ for (const [source, bag] of [['cli', overrides], ['env', env], ['file', file.values], ['user', userFile.values]]) {
114
+ const v = bag[name];
115
+ if (v !== undefined && v !== '') {
116
+ sources[name] = source;
117
+ return v;
118
+ }
119
+ }
120
+ sources[name] = 'default';
121
+ return undefined;
122
+ };
123
+ const bad = (variable, problem, fix) => { issues.push({ variable, problem, fix: fix ?? `set ${variable} in ${where}${hint} (copy .env.example)` }); };
124
+ const integer = (name, lo, hi, dflt) => {
125
+ const v = get(name);
126
+ if (v === undefined)
127
+ return dflt;
128
+ if (!/^\d+$/.test(v) || Number(v) < lo || Number(v) > hi) {
129
+ bad(name, `must be an integer between ${lo} and ${hi}`, `set ${name} to an integer in ${lo}..${hi}`);
130
+ return dflt;
131
+ }
132
+ return Number(v);
133
+ };
134
+ const provider = get('CKIT_ADVISOR_PROVIDER');
135
+ if (provider !== undefined && provider !== 'openai-compatible')
136
+ bad('CKIT_ADVISOR_PROVIDER', 'only "openai-compatible" is supported', 'remove it or set CKIT_ADVISOR_PROVIDER=openai-compatible');
137
+ let baseUrl = '';
138
+ const rawUrl = get('CKIT_OPENAI_BASE_URL');
139
+ if (rawUrl === undefined)
140
+ bad('CKIT_OPENAI_BASE_URL', 'is required');
141
+ else {
142
+ try {
143
+ const url = new URL(rawUrl);
144
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
145
+ bad('CKIT_OPENAI_BASE_URL', 'must be an http(s) URL', 'use an http:// or https:// URL including the version segment, e.g. https://<host>/v1');
146
+ else if (url.username !== '' || url.password !== '')
147
+ bad('CKIT_OPENAI_BASE_URL', 'must not contain credentials', 'remove user:password@ from the URL and use CKIT_OPENAI_API_KEY');
148
+ else if (url.search !== '' || url.hash !== '' || /[?#]/.test(rawUrl))
149
+ bad('CKIT_OPENAI_BASE_URL', 'must not contain a query or fragment', 'remove ?query and #fragment from the URL');
150
+ else {
151
+ baseUrl = `${url.origin}${url.pathname}`.replace(/\/+$/, '');
152
+ if (/\/chat\/completions$/i.test(baseUrl)) {
153
+ bad('CKIT_OPENAI_BASE_URL', 'must not end in /chat/completions', 'use the base URL only (e.g. https://<host>/v1); CKit appends /chat/completions');
154
+ baseUrl = '';
155
+ }
156
+ }
157
+ }
158
+ catch {
159
+ bad('CKIT_OPENAI_BASE_URL', 'is not a valid URL', 'use a full URL including the version segment, e.g. https://<host>/v1');
160
+ }
161
+ }
162
+ const authRaw = get('CKIT_OPENAI_AUTH');
163
+ let auth = 'bearer';
164
+ if (authRaw !== undefined) {
165
+ if (authRaw === 'bearer' || authRaw === 'none')
166
+ auth = authRaw;
167
+ else
168
+ bad('CKIT_OPENAI_AUTH', 'must be "bearer" or "none"', 'set CKIT_OPENAI_AUTH=bearer (default) or none');
169
+ }
170
+ const apiKey = get('CKIT_OPENAI_API_KEY') ?? '';
171
+ if (auth === 'bearer' && apiKey === '')
172
+ bad('CKIT_OPENAI_API_KEY', 'is required when CKIT_OPENAI_AUTH=bearer', `set CKIT_OPENAI_API_KEY in ${where}, or set CKIT_OPENAI_AUTH=none for a keyless endpoint`);
173
+ if (auth === 'none' && apiKey !== '')
174
+ bad('CKIT_OPENAI_API_KEY', 'must be empty when CKIT_OPENAI_AUTH=none', 'clear CKIT_OPENAI_API_KEY or set CKIT_OPENAI_AUTH=bearer');
175
+ const model = get('CKIT_OPENAI_MODEL') ?? '';
176
+ if (model === '')
177
+ bad('CKIT_OPENAI_MODEL', 'is required');
178
+ const primaryModel = get('CKIT_PRIMARY_MODEL') ?? model, reviewerModel = get('CKIT_REVIEWER_MODEL') ?? model;
179
+ const reviewers = integer('CKIT_REVIEWERS', 0, 3, 1) ?? 1;
180
+ const timeoutMs = integer('CKIT_OPENAI_TIMEOUT_MS', 1000, 600000, 120000) ?? 120000;
181
+ const maxTokens = integer('CKIT_OPENAI_MAX_TOKENS', 1, 1_000_000_000, null);
182
+ const exeRaw = get('CKIT_EXECUTOR');
183
+ let executor = 'claude-code';
184
+ if (exeRaw !== undefined) {
185
+ if (exeRaw === 'claude-code' || exeRaw === 'omp')
186
+ executor = exeRaw;
187
+ else
188
+ bad('CKIT_EXECUTOR', 'must be "claude-code" or "omp"', 'set CKIT_EXECUTOR=claude-code or CKIT_EXECUTOR=omp');
189
+ }
190
+ const executorPath = get('CKIT_EXECUTOR_PATH') ?? null;
191
+ if (executorPath !== null && !isAbsolute(executorPath))
192
+ bad('CKIT_EXECUTOR_PATH', 'must be an absolute path', 'use an absolute path or remove it to resolve the executor on PATH');
193
+ const executorModel = get('CKIT_EXECUTOR_MODEL') ?? null;
194
+ const executorTimeoutMs = integer('CKIT_EXECUTOR_TIMEOUT_MS', 10000, 7200000, 1800000) ?? 1800000;
195
+ // Opt-in worker permission mode (choices from `claude --help` --permission-mode). Never silently falls back; bypass is never accepted.
196
+ const permRaw = get('CKIT_EXECUTOR_PERMISSION_MODE');
197
+ let executorPermissionMode = null;
198
+ if (permRaw !== undefined && permRaw !== 'default') {
199
+ if (/bypass|dangerously/i.test(permRaw))
200
+ bad('CKIT_EXECUTOR_PERMISSION_MODE', 'bypassPermissions and dangerously-skip-permissions are never accepted (they would let the worker act without any permission check)', 'use default, acceptEdits or dontAsk, or remove the variable');
201
+ else if (EXECUTOR_PERMISSION_MODES.includes(permRaw))
202
+ executorPermissionMode = permRaw;
203
+ else
204
+ bad('CKIT_EXECUTOR_PERMISSION_MODE', 'must be "default", "acceptEdits" or "dontAsk"', 'set CKIT_EXECUTOR_PERMISSION_MODE to default (no flag), acceptEdits or dontAsk, or remove it');
205
+ }
206
+ const allowRaw = get('CKIT_VERIFY_ALLOW');
207
+ let verifyAllow = DEFAULT_VERIFY_ALLOW;
208
+ if (allowRaw !== undefined) {
209
+ const parsed = allowRaw.split(',').map(x => x.trim().replace(/\s+/g, ' ')).filter(Boolean);
210
+ if (parsed.length === 0 || parsed.some(x => /[;&|`$<>(){}\\"']/.test(x)))
211
+ bad('CKIT_VERIFY_ALLOW', 'must be a comma-separated list of plain command prefixes without shell metacharacters', 'set CKIT_VERIFY_ALLOW to e.g. "npm test,node --test" or remove it for the default list');
212
+ else
213
+ verifyAllow = parsed;
214
+ }
215
+ const verifyTimeoutMs = integer('CKIT_VERIFY_TIMEOUT_MS', 1000, 3600000, 600000) ?? 600000;
216
+ const maxTasks = integer('CKIT_MAX_TASKS', 1, 12, 6) ?? 6;
217
+ if (issues.length > 0)
218
+ return { ok: false, issues };
219
+ return { ok: true, projectRoot: input.projectRoot, configFile, sources, config: { provider: 'openai-compatible', baseUrl, auth, apiKey, model, primaryModel, reviewerModel, reviewers, timeoutMs, maxTokens, executor, executorPath, executorModel, executorTimeoutMs, executorPermissionMode, verifyAllow, verifyTimeoutMs, maxTasks } };
220
+ }
221
+ /** Display-safe summary: never contains the key, only whether one is set. */
222
+ export function maskedConfigSummary(config) {
223
+ const models = config.primaryModel === config.model && config.reviewerModel === config.model ? `model ${config.model}` : `model ${config.model} (primary ${config.primaryModel}, reviewer ${config.reviewerModel})`;
224
+ const key = config.auth === 'none' ? 'key: none (CKIT_OPENAI_AUTH=none)' : 'key: set';
225
+ return `provider ${config.provider} · ${config.baseUrl} · ${models} · executor ${config.executor}${config.executorModel ? ` (${config.executorModel})` : ''} · worker permission ${config.executor === 'omp' && config.executorPermissionMode ? `${config.executorPermissionMode} (ignored for omp)` : config.executorPermissionMode ?? 'default'} · reviewers ${config.reviewers} · ${key}`;
226
+ }
227
+ /** True when any CKit variable is present at all (separates the unconfigured state from an invalid one). */
228
+ export function hasAnyAdvisorConfig(projectRoot, env = process.env, userDir = userDirFromEnv(env)) {
229
+ const file = readDotenvFile(projectRoot).values, user = userDir === null ? {} : readDotenvFile(userDir).values;
230
+ return CONFIG_VARIABLES.some(name => (env[name] ?? '') !== '' || (file[name] ?? '') !== '' || (user[name] ?? '') !== '');
231
+ }
232
+ //# sourceMappingURL=env-config.js.map
@@ -0,0 +1,30 @@
1
+ import type { StorageDatabase } from './db.js';
2
+ import { type ArtifactRef } from '../core/ids.js';
3
+ export interface StagedArtifact {
4
+ readonly ref: ArtifactRef;
5
+ readonly hash: string;
6
+ readonly sizeBytes: number;
7
+ }
8
+ export interface SweepOptions {
9
+ readonly activeTaskEvidenceRefs?: readonly string[];
10
+ }
11
+ export declare class ArtifactStore {
12
+ private readonly db;
13
+ readonly root: string;
14
+ constructor(db: StorageDatabase, root: string);
15
+ pathFor(rawRef: string): string;
16
+ stage(data: string | Uint8Array, options?: {
17
+ beforeRename?: () => void | Promise<void>;
18
+ }): Promise<StagedArtifact>;
19
+ commit(staged: StagedArtifact): Promise<void>;
20
+ put(data: string | Uint8Array, options?: {
21
+ beforeRename?: () => void | Promise<void>;
22
+ }): Promise<StagedArtifact>;
23
+ read(rawRef: string): Promise<Buffer>;
24
+ verify(rawRef: string): Promise<void>;
25
+ protectForActiveTask(rawRef: string, taskId: string): void;
26
+ protectEvidenceForTask(rawRef: string, taskId: string): void;
27
+ cleanupTemporaryFiles(): Promise<readonly string[]>;
28
+ findOrphans(): Promise<readonly string[]>;
29
+ sweep(options?: SweepOptions): Promise<readonly string[]>;
30
+ }
@@ -0,0 +1,105 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, open, readFile, readdir, rename, rm, stat } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { artifactRef } from '../core/ids.js';
5
+ export class ArtifactStore {
6
+ db;
7
+ root;
8
+ constructor(db, root) {
9
+ this.db = db;
10
+ this.root = root;
11
+ }
12
+ pathFor(rawRef) { const ref = artifactRef(rawRef); return join(this.root, ref); }
13
+ async stage(data, options = {}) {
14
+ await mkdir(this.root, { recursive: true });
15
+ const ref = artifactRef(`artifact-${randomUUID().replaceAll('-', '')}`), bytes = typeof data === 'string' ? Buffer.from(data) : Buffer.from(data);
16
+ const temporary = join(this.root, `.${ref}.${randomUUID()}.tmp`), handle = await open(temporary, 'wx', 0o600);
17
+ try {
18
+ await handle.writeFile(bytes);
19
+ await handle.sync();
20
+ await handle.close();
21
+ await options.beforeRename?.();
22
+ await rename(temporary, this.pathFor(ref));
23
+ const directory = await open(this.root, 'r');
24
+ try {
25
+ await directory.sync();
26
+ }
27
+ finally {
28
+ await directory.close();
29
+ }
30
+ }
31
+ catch (error) {
32
+ try {
33
+ await handle.close();
34
+ }
35
+ catch { }
36
+ throw error;
37
+ }
38
+ return Object.freeze({ ref, hash: createHash('sha256').update(bytes).digest('hex'), sizeBytes: bytes.byteLength });
39
+ }
40
+ async commit(staged) {
41
+ const path = this.pathFor(staged.ref), info = await stat(path), bytes = await readFile(path);
42
+ const hash = createHash('sha256').update(bytes).digest('hex');
43
+ if (hash !== staged.hash || bytes.byteLength !== staged.sizeBytes || info.size !== staged.sizeBytes)
44
+ throw new Error(`staged artifact integrity mismatch: ${staged.ref}`);
45
+ this.db.transaction(() => this.db.raw.prepare('INSERT INTO artifact_refs(artifact_ref,hash,size_bytes,committed_at) VALUES(?,?,?,?)').run(staged.ref, hash, bytes.byteLength, new Date().toISOString()));
46
+ }
47
+ async put(data, options = {}) { const staged = await this.stage(data, options); await this.commit(staged); return staged; }
48
+ async read(rawRef) { const ref = artifactRef(rawRef), bytes = await readFile(this.pathFor(ref)); await this.verify(ref); return bytes; }
49
+ async verify(rawRef) {
50
+ const ref = artifactRef(rawRef), row = this.db.raw.prepare('SELECT hash,size_bytes FROM artifact_refs WHERE artifact_ref=?').get(ref);
51
+ if (!row)
52
+ throw new Error(`artifact reference missing: ${ref}`);
53
+ let bytes;
54
+ try {
55
+ bytes = await readFile(this.pathFor(ref));
56
+ }
57
+ catch (error) {
58
+ throw new Error(`artifact file missing: ${ref}`, { cause: error });
59
+ }
60
+ if (bytes.byteLength !== Number(row['size_bytes']) || createHash('sha256').update(bytes).digest('hex') !== String(row['hash']))
61
+ throw new Error(`artifact hash mismatch: ${ref}`);
62
+ }
63
+ protectForActiveTask(rawRef, taskId) { this.db.raw.prepare('INSERT OR IGNORE INTO artifact_task_protection(artifact_ref,task_id) VALUES(?,?)').run(artifactRef(rawRef), taskId); }
64
+ protectEvidenceForTask(rawRef, taskId) { if (!taskId)
65
+ throw new TypeError('task ID required'); this.db.raw.prepare('INSERT OR IGNORE INTO artifact_task_protection(artifact_ref,task_id) VALUES(?,?)').run(artifactRef(rawRef), taskId); }
66
+ async cleanupTemporaryFiles() { let names; try {
67
+ names = await readdir(this.root);
68
+ }
69
+ catch (error) {
70
+ if (error.code === 'ENOENT')
71
+ return Object.freeze([]);
72
+ throw error;
73
+ } const removed = []; for (const name of names.filter(n => n.startsWith('.') && n.endsWith('.tmp'))) {
74
+ await rm(join(this.root, name), { force: true });
75
+ removed.push(name);
76
+ } return Object.freeze(removed); }
77
+ async findOrphans() {
78
+ let names;
79
+ try {
80
+ names = await readdir(this.root);
81
+ }
82
+ catch (error) {
83
+ if (error.code === 'ENOENT')
84
+ return Object.freeze([]);
85
+ throw error;
86
+ }
87
+ const rows = this.db.raw.prepare('SELECT artifact_ref FROM artifact_refs').all(), known = new Set(rows.map(row => String(row['artifact_ref'])));
88
+ return Object.freeze(names.filter(name => !name.startsWith('.') && !known.has(name)).sort());
89
+ }
90
+ async sweep(options = {}) {
91
+ const active = new Set(options.activeTaskEvidenceRefs ?? []);
92
+ const protectedRows = this.db.raw.prepare('SELECT artifact_ref FROM artifact_task_protection').all();
93
+ for (const row of protectedRows)
94
+ active.add(String(row['artifact_ref']));
95
+ const orphans = await this.findOrphans(), removed = [];
96
+ for (const ref of orphans) {
97
+ if (active.has(ref))
98
+ continue;
99
+ await rm(this.pathFor(ref), { force: false });
100
+ removed.push(ref);
101
+ }
102
+ return Object.freeze(removed);
103
+ }
104
+ }
105
+ //# sourceMappingURL=artifacts.js.map
@@ -0,0 +1,6 @@
1
+ import type { StorageDatabase } from './db.js';
2
+ import { type DeliveryBoundary } from './events.js';
3
+ export interface AuditReader {
4
+ read(sessionId: string, requestId: string): readonly DeliveryBoundary[];
5
+ }
6
+ export declare function createAuditReader(db: StorageDatabase): AuditReader;
@@ -0,0 +1,6 @@
1
+ import { EventJournal } from './events.js';
2
+ export function createAuditReader(db) {
3
+ const journal = new EventJournal(db);
4
+ return Object.freeze({ read: (sessionId, requestId) => journal.audit(sessionId, requestId) });
5
+ }
6
+ //# sourceMappingURL=audit.js.map
@@ -0,0 +1,9 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { type Migration } from './migrations.js';
3
+ export interface StorageDatabase {
4
+ readonly raw: DatabaseSync;
5
+ transaction<T>(work: () => T): T;
6
+ migrate(plan?: readonly Migration[]): number;
7
+ close(): void;
8
+ }
9
+ export declare function openDatabase(path: string): StorageDatabase;
@@ -0,0 +1,43 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { applyMigrations, migrations } from './migrations.js';
3
+ export function openDatabase(path) {
4
+ const raw = new DatabaseSync(path, { enableForeignKeyConstraints: true, enableDoubleQuotedStringLiterals: false });
5
+ raw.exec('PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
6
+ let closed = false;
7
+ const transaction = (work) => {
8
+ if (closed)
9
+ throw new Error('database is closed');
10
+ raw.exec('BEGIN IMMEDIATE');
11
+ try {
12
+ const result = work();
13
+ raw.exec('COMMIT');
14
+ return result;
15
+ }
16
+ catch (error) {
17
+ try {
18
+ raw.exec('ROLLBACK');
19
+ }
20
+ catch { /* preserve original failure */ }
21
+ throw error;
22
+ }
23
+ };
24
+ const applyMigration = (version, sql) => transaction(() => {
25
+ raw.exec(sql);
26
+ if (raw.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_version'").get() !== undefined)
27
+ raw.prepare('UPDATE schema_version SET version=?').run(version);
28
+ });
29
+ return {
30
+ raw,
31
+ transaction,
32
+ migrate: (plan = migrations) => {
33
+ if (closed)
34
+ throw new Error('database is closed');
35
+ return applyMigrations(raw, applyMigration, plan);
36
+ },
37
+ close: () => { if (!closed) {
38
+ raw.close();
39
+ closed = true;
40
+ } },
41
+ };
42
+ }
43
+ //# sourceMappingURL=db.js.map