@ngockhoale/ckit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/.env.example +42 -0
  2. package/README.md +116 -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 +472 -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/sessions.d.ts +10 -0
  46. package/dist/src/cli/sessions.js +381 -0
  47. package/dist/src/cli/setup.d.ts +11 -0
  48. package/dist/src/cli/setup.js +115 -0
  49. package/dist/src/committee/decision.d.ts +84 -0
  50. package/dist/src/committee/decision.js +167 -0
  51. package/dist/src/committee/handover.d.ts +115 -0
  52. package/dist/src/committee/handover.js +191 -0
  53. package/dist/src/committee/no-progress.d.ts +44 -0
  54. package/dist/src/committee/no-progress.js +64 -0
  55. package/dist/src/committee/primary-registry.d.ts +15 -0
  56. package/dist/src/committee/primary-registry.js +60 -0
  57. package/dist/src/committee/reply-parser.d.ts +28 -0
  58. package/dist/src/committee/reply-parser.js +53 -0
  59. package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
  60. package/dist/src/committee/reviewer-scheduler.js +163 -0
  61. package/dist/src/committee/role-epoch.d.ts +91 -0
  62. package/dist/src/committee/role-epoch.js +154 -0
  63. package/dist/src/core/control.d.ts +18 -0
  64. package/dist/src/core/control.js +29 -0
  65. package/dist/src/core/entities.d.ts +166 -0
  66. package/dist/src/core/entities.js +119 -0
  67. package/dist/src/core/errors.d.ts +9 -0
  68. package/dist/src/core/errors.js +17 -0
  69. package/dist/src/core/events.d.ts +72 -0
  70. package/dist/src/core/events.js +125 -0
  71. package/dist/src/core/ids.d.ts +47 -0
  72. package/dist/src/core/ids.js +32 -0
  73. package/dist/src/core/machine.d.ts +55 -0
  74. package/dist/src/core/machine.js +110 -0
  75. package/dist/src/core/policy.d.ts +34 -0
  76. package/dist/src/core/policy.js +59 -0
  77. package/dist/src/core/provenance.d.ts +20 -0
  78. package/dist/src/core/provenance.js +21 -0
  79. package/dist/src/core/record.d.ts +35 -0
  80. package/dist/src/core/record.js +67 -0
  81. package/dist/src/core/replay.d.ts +10 -0
  82. package/dist/src/core/replay.js +36 -0
  83. package/dist/src/core/run-task.d.ts +20 -0
  84. package/dist/src/core/run-task.js +48 -0
  85. package/dist/src/diagnostics/doctor.d.ts +78 -0
  86. package/dist/src/diagnostics/doctor.js +365 -0
  87. package/dist/src/diagnostics/journal-lock.d.ts +38 -0
  88. package/dist/src/diagnostics/journal-lock.js +181 -0
  89. package/dist/src/evidence/linker.d.ts +44 -0
  90. package/dist/src/evidence/linker.js +75 -0
  91. package/dist/src/evidence/report-parser.d.ts +27 -0
  92. package/dist/src/evidence/report-parser.js +17 -0
  93. package/dist/src/evidence/store.d.ts +36 -0
  94. package/dist/src/evidence/store.js +57 -0
  95. package/dist/src/gui/server.d.ts +27 -0
  96. package/dist/src/gui/server.js +497 -0
  97. package/dist/src/host/checkpoint.d.ts +22 -0
  98. package/dist/src/host/checkpoint.js +74 -0
  99. package/dist/src/host/export.d.ts +52 -0
  100. package/dist/src/host/export.js +45 -0
  101. package/dist/src/host/ipc.d.ts +57 -0
  102. package/dist/src/host/ipc.js +124 -0
  103. package/dist/src/host/leases.d.ts +27 -0
  104. package/dist/src/host/leases.js +40 -0
  105. package/dist/src/host/retention.d.ts +47 -0
  106. package/dist/src/host/retention.js +130 -0
  107. package/dist/src/host/supervisor.d.ts +59 -0
  108. package/dist/src/host/supervisor.js +64 -0
  109. package/dist/src/intake/owner-intake.d.ts +31 -0
  110. package/dist/src/intake/owner-intake.js +97 -0
  111. package/dist/src/intake/types.d.ts +46 -0
  112. package/dist/src/intake/types.js +2 -0
  113. package/dist/src/intent/context-packet.d.ts +68 -0
  114. package/dist/src/intent/context-packet.js +76 -0
  115. package/dist/src/intent/idea-ledger.d.ts +50 -0
  116. package/dist/src/intent/idea-ledger.js +136 -0
  117. package/dist/src/intent/ledger.d.ts +35 -0
  118. package/dist/src/intent/ledger.js +40 -0
  119. package/dist/src/intent/registry.d.ts +51 -0
  120. package/dist/src/intent/registry.js +44 -0
  121. package/dist/src/intent/revision.d.ts +37 -0
  122. package/dist/src/intent/revision.js +48 -0
  123. package/dist/src/orchestration/dispatcher.d.ts +32 -0
  124. package/dist/src/orchestration/dispatcher.js +136 -0
  125. package/dist/src/orchestration/milestone-loop.d.ts +149 -0
  126. package/dist/src/orchestration/milestone-loop.js +132 -0
  127. package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
  128. package/dist/src/orchestration/recovery-coordinator.js +180 -0
  129. package/dist/src/orchestration/work-order-contract.d.ts +44 -0
  130. package/dist/src/orchestration/work-order-contract.js +85 -0
  131. package/dist/src/orchestration/work-queue.d.ts +56 -0
  132. package/dist/src/orchestration/work-queue.js +95 -0
  133. package/dist/src/ports/advisor.d.ts +33 -0
  134. package/dist/src/ports/advisor.js +2 -0
  135. package/dist/src/ports/agent.d.ts +31 -0
  136. package/dist/src/ports/agent.js +2 -0
  137. package/dist/src/ports/capabilities.d.ts +3 -0
  138. package/dist/src/ports/capabilities.js +5 -0
  139. package/dist/src/ports/clock.d.ts +5 -0
  140. package/dist/src/ports/clock.js +5 -0
  141. package/dist/src/ports/store.d.ts +13 -0
  142. package/dist/src/ports/store.js +2 -0
  143. package/dist/src/ports/web.d.ts +29 -0
  144. package/dist/src/ports/web.js +2 -0
  145. package/dist/src/run/api-run.d.ts +49 -0
  146. package/dist/src/run/api-run.js +173 -0
  147. package/dist/src/run/plan-run.d.ts +22 -0
  148. package/dist/src/run/plan-run.js +233 -0
  149. package/dist/src/run/plan.d.ts +36 -0
  150. package/dist/src/run/plan.js +119 -0
  151. package/dist/src/run/verify.d.ts +25 -0
  152. package/dist/src/run/verify.js +81 -0
  153. package/dist/src/security/redact.d.ts +7 -0
  154. package/dist/src/security/redact.js +21 -0
  155. package/dist/src/settings/env-config.d.ts +64 -0
  156. package/dist/src/settings/env-config.js +232 -0
  157. package/dist/src/storage/artifacts.d.ts +30 -0
  158. package/dist/src/storage/artifacts.js +105 -0
  159. package/dist/src/storage/audit.d.ts +6 -0
  160. package/dist/src/storage/audit.js +6 -0
  161. package/dist/src/storage/db.d.ts +9 -0
  162. package/dist/src/storage/db.js +43 -0
  163. package/dist/src/storage/events.d.ts +20 -0
  164. package/dist/src/storage/events.js +69 -0
  165. package/dist/src/storage/migrations.d.ts +8 -0
  166. package/dist/src/storage/migrations.js +48 -0
  167. package/dist/src/storage/outbox.d.ts +25 -0
  168. package/dist/src/storage/outbox.js +40 -0
  169. package/dist/src/storage/projections.d.ts +18 -0
  170. package/dist/src/storage/projections.js +40 -0
  171. package/dist/src/storage/reconcile.d.ts +14 -0
  172. package/dist/src/storage/reconcile.js +93 -0
  173. package/dist/src/storage/reservations.d.ts +12 -0
  174. package/dist/src/storage/reservations.js +80 -0
  175. package/dist/src/storage/store.d.ts +34 -0
  176. package/dist/src/storage/store.js +105 -0
  177. package/dist/src/team/attachments.d.ts +22 -0
  178. package/dist/src/team/attachments.js +211 -0
  179. package/dist/src/team/cli-models.d.ts +24 -0
  180. package/dist/src/team/cli-models.js +72 -0
  181. package/dist/src/team/config.d.ts +20 -0
  182. package/dist/src/team/config.js +111 -0
  183. package/dist/src/team/engine.d.ts +28 -0
  184. package/dist/src/team/engine.js +443 -0
  185. package/dist/src/team/journal.d.ts +30 -0
  186. package/dist/src/team/journal.js +70 -0
  187. package/dist/src/team/runners.d.ts +79 -0
  188. package/dist/src/team/runners.js +436 -0
  189. package/dist/src/team/secrets.d.ts +10 -0
  190. package/dist/src/team/secrets.js +68 -0
  191. package/dist/src/team/types.d.ts +155 -0
  192. package/dist/src/team/types.js +5 -0
  193. package/dist/src/tui/app.d.ts +29 -0
  194. package/dist/src/tui/app.js +96 -0
  195. package/dist/src/tui/control-model.d.ts +101 -0
  196. package/dist/src/tui/control-model.js +109 -0
  197. package/dist/src/tui/control-screens.d.ts +27 -0
  198. package/dist/src/tui/control-screens.js +85 -0
  199. package/dist/src/tui/graph-model.d.ts +34 -0
  200. package/dist/src/tui/graph-model.js +29 -0
  201. package/dist/src/tui/graph-screens.d.ts +13 -0
  202. package/dist/src/tui/graph-screens.js +4 -0
  203. package/dist/src/tui/inspector-model.d.ts +150 -0
  204. package/dist/src/tui/inspector-model.js +15 -0
  205. package/dist/src/tui/inspector-screens.d.ts +14 -0
  206. package/dist/src/tui/inspector-screens.js +61 -0
  207. package/dist/src/tui/live.d.ts +16 -0
  208. package/dist/src/tui/live.js +39 -0
  209. package/dist/src/tui/mission-action-screens.d.ts +15 -0
  210. package/dist/src/tui/mission-action-screens.js +105 -0
  211. package/dist/src/tui/mission-actions.d.ts +46 -0
  212. package/dist/src/tui/mission-actions.js +53 -0
  213. package/dist/src/tui/mission-model.d.ts +120 -0
  214. package/dist/src/tui/mission-model.js +164 -0
  215. package/dist/src/tui/mission-nav.d.ts +82 -0
  216. package/dist/src/tui/mission-nav.js +131 -0
  217. package/dist/src/tui/mission-plan-screens.d.ts +11 -0
  218. package/dist/src/tui/mission-plan-screens.js +40 -0
  219. package/dist/src/tui/mission-plan.d.ts +45 -0
  220. package/dist/src/tui/mission-plan.js +166 -0
  221. package/dist/src/tui/mission-screens.d.ts +7 -0
  222. package/dist/src/tui/mission-screens.js +263 -0
  223. package/dist/src/tui/provenance-label.d.ts +11 -0
  224. package/dist/src/tui/provenance-label.js +16 -0
  225. package/dist/src/tui/screens.d.ts +10 -0
  226. package/dist/src/tui/screens.js +34 -0
  227. package/dist/src/tui/session-outcome.d.ts +14 -0
  228. package/dist/src/tui/session-outcome.js +57 -0
  229. package/dist/src/tui/setup-model.d.ts +159 -0
  230. package/dist/src/tui/setup-model.js +234 -0
  231. package/dist/src/tui/setup-screens.d.ts +66 -0
  232. package/dist/src/tui/setup-screens.js +72 -0
  233. package/dist/src/tui/team/app.d.ts +24 -0
  234. package/dist/src/tui/team/app.js +228 -0
  235. package/dist/src/tui/team/demo-handle.d.ts +22 -0
  236. package/dist/src/tui/team/demo-handle.js +42 -0
  237. package/dist/src/tui/team/model.d.ts +81 -0
  238. package/dist/src/tui/team/model.js +133 -0
  239. package/gui/app.css +177 -0
  240. package/gui/app.js +675 -0
  241. package/gui/index.html +51 -0
  242. package/gui/network.js +413 -0
  243. package/package.json +45 -4
  244. package/src/storage/schema.sql +42 -0
@@ -0,0 +1,49 @@
1
+ import type { Envelope } from '../core/events.js';
2
+ import { type FetchImpl } from '../adapters/openai/openai-advisor.js';
3
+ import { type ExecutorSpec, type SpawnImpl } from '../adapters/launch/executor.js';
4
+ import type { CkitConfig } from '../settings/env-config.js';
5
+ export type PrimarySettlement = 'sent' | 'refused' | 'unknown' | 'not_sent';
6
+ /** Engine-level settlement for a stopped Primary turn: only a provably never-sent request releases the slot; a refused 4xx was delivered and consumes it. */
7
+ export declare function settlementFor(stop: {
8
+ kind: 'rejected';
9
+ delivery: 'never-sent' | 'refused';
10
+ } | {
11
+ kind: 'unknown';
12
+ }): {
13
+ engine: 'sent' | 'unknown' | 'not_sent';
14
+ report: PrimarySettlement;
15
+ };
16
+ export interface RunJournal {
17
+ readonly projectId: string;
18
+ readonly stateDir: string;
19
+ read(): Promise<Envelope[]>;
20
+ write(events: readonly Envelope[]): Promise<void>;
21
+ lock<T>(operation: () => Promise<T>): Promise<T>;
22
+ }
23
+ export interface ApiRunInput {
24
+ readonly projectRoot: string;
25
+ readonly goal: string;
26
+ readonly config: CkitConfig;
27
+ readonly journal: RunJournal;
28
+ readonly executorSpec: ExecutorSpec;
29
+ readonly executorPath: string;
30
+ readonly fetchImpl?: FetchImpl;
31
+ readonly spawnImpl?: SpawnImpl;
32
+ readonly env?: Readonly<Record<string, string | undefined>>;
33
+ readonly log?: (line: string) => void;
34
+ readonly signal?: AbortSignal;
35
+ /** Second interrupt: escalate the executor kill to SIGKILL immediately. */
36
+ readonly hardKill?: AbortSignal;
37
+ }
38
+ export interface ApiRunResult {
39
+ readonly exitCode: 0 | 1;
40
+ readonly sessionId: string;
41
+ readonly outcome: 'success' | 'failed' | 'unknown';
42
+ readonly verdict: 'ACCEPT' | 'REJECT' | 'none';
43
+ readonly events: readonly Envelope[];
44
+ readonly primarySettlements: readonly PrimarySettlement[];
45
+ }
46
+ export declare const REVIEWER_SYSTEM = "You are an independent reviewer. Given a goal, an instruction and the executor result, give a short, critical opinion on whether the goal was met and what is risky or missing.";
47
+ export declare const VERDICT_ASK = "Now give your verdict. The first line must be exactly \"VERDICT: ACCEPT\" or \"VERDICT: REJECT\", followed by a short rationale.";
48
+ export declare function parseVerdict(text: string): 'ACCEPT' | 'REJECT' | 'none';
49
+ export declare function runApiTask(input: ApiRunInput): Promise<ApiRunResult>;
@@ -0,0 +1,173 @@
1
+ // `ckit run`: API advisor (Primary + reviewers) plans/reviews, the selected CLI executor executes (ADR-017).
2
+ // Every step goes through recordEvent + the strict machine; any unknown/rejected outcome stops the run (no resend, no retry).
3
+ import { randomBytes } from 'node:crypto';
4
+ import { join } from 'node:path';
5
+ import { DecisionEngine } from '../committee/decision.js';
6
+ import { projectId as toProjectId, sessionId as toSessionId, taskId as toTaskId } from '../core/ids.js';
7
+ import { initialSession, reduce } from '../core/machine.js';
8
+ import { recordEvent } from '../core/record.js';
9
+ import { containsSecretText, redactSecretText } from '../security/redact.js';
10
+ import { ArtifactStore } from '../storage/artifacts.js';
11
+ import { openDatabase } from '../storage/db.js';
12
+ import { OpenAiCompatibleAdvisor } from '../adapters/openai/openai-advisor.js';
13
+ import { describeWorkerEnv, describeWorkerPermission, executorEnvironmentReport, executorFailureDetail, runExecutor, subagentLogger } from '../adapters/launch/executor.js';
14
+ /** Engine-level settlement for a stopped Primary turn: only a provably never-sent request releases the slot; a refused 4xx was delivered and consumes it. */
15
+ export function settlementFor(stop) {
16
+ if (stop.kind === 'unknown')
17
+ return { engine: 'unknown', report: 'unknown' };
18
+ return stop.delivery === 'never-sent' ? { engine: 'not_sent', report: 'not_sent' } : { engine: 'sent', report: 'refused' };
19
+ }
20
+ const PRIMARY_SYSTEM = 'You are the Primary advisor for a coding agent that works in the project root on the owner\'s machine. Produce a concise, concrete execution instruction for that coding agent. Reply with the instruction only.';
21
+ export const REVIEWER_SYSTEM = 'You are an independent reviewer. Given a goal, an instruction and the executor result, give a short, critical opinion on whether the goal was met and what is risky or missing.';
22
+ export const VERDICT_ASK = 'Now give your verdict. The first line must be exactly "VERDICT: ACCEPT" or "VERDICT: REJECT", followed by a short rationale.';
23
+ export function parseVerdict(text) {
24
+ const first = text.split(/\r?\n/).find(line => line.trim() !== '') ?? '';
25
+ const m = /^\s*VERDICT:\s*(ACCEPT|REJECT)\b/i.exec(first);
26
+ return m ? m[1].toUpperCase() : 'none';
27
+ }
28
+ export async function runApiTask(input) {
29
+ const { config, journal } = input;
30
+ const key = config.apiKey;
31
+ const safe = (text) => redactSecretText(text, key ? [key] : []);
32
+ const log = (line) => (input.log ?? console.log)(safe(line));
33
+ if (!input.goal.trim())
34
+ throw new TypeError('goal must not be empty');
35
+ if (containsSecretText(input.goal))
36
+ throw new TypeError('goal appears to contain secret material; refusing to persist it');
37
+ const goal = input.goal;
38
+ return journal.lock(async () => {
39
+ const previous = await journal.read();
40
+ const rid = randomBytes(6).toString('hex');
41
+ const sid = toSessionId(`session-${rid}`), tid = toTaskId(`task-${rid}`);
42
+ const context = { sessionId: sid, taskId: tid, projectId: toProjectId(journal.projectId), source: { liveRef: `api-run:${sid}@${config.baseUrl}` }, at: () => new Date().toISOString(), redactedConfigHash: 'api-run' };
43
+ const mine = [];
44
+ let state = initialSession(sid);
45
+ const push = (step) => { const env = recordEvent(context, step, mine.at(-1)); state = reduce(state, env); mine.push(env); };
46
+ const flush = () => journal.write([...previous, ...mine]);
47
+ const db = openDatabase(join(journal.stateDir, 'state.sqlite'));
48
+ db.migrate();
49
+ const artifacts = new ArtifactStore(db, join(journal.stateDir, 'artifacts'));
50
+ const put = async (text) => (await artifacts.put(safe(text))).ref;
51
+ const advisor = new OpenAiCompatibleAdvisor(config, { saveReply: (_thread, text) => put(text) }, input.fetchImpl);
52
+ const engine = new DecisionEngine({ decisionId: `decision-${rid}`, primaryId: 'primary-advisor' });
53
+ let verdict = 'none';
54
+ let lastStop = null;
55
+ const settlements = [];
56
+ const settle = (id, result) => {
57
+ if (result === 'stopped') {
58
+ const m = settlementFor(lastStop ?? { kind: 'unknown' });
59
+ engine.settlePrimary(id, m.engine);
60
+ settlements.push(m.report);
61
+ return;
62
+ }
63
+ engine.settlePrimary(id, 'sent');
64
+ settlements.push('sent');
65
+ };
66
+ const finish = async (outcome) => {
67
+ push({ actor: { role: 'system' }, payload: { type: 'TaskCompleted', outcome } });
68
+ await flush();
69
+ log(`session ${sid}: outcome ${outcome}${verdict !== 'none' ? `, verdict ${verdict}` : ''}`);
70
+ return { exitCode: outcome === 'success' ? 0 : 1, sessionId: sid, outcome, verdict, events: [...mine], primarySettlements: [...settlements] };
71
+ };
72
+ /** Stops the run at the first non-completed advisor/executor message: definite rejection -> failed, otherwise unknown. */
73
+ const stop = async (who, adapter, msg) => {
74
+ lastStop = msg;
75
+ const reason = msg.kind === 'rejected' ? 'adapter-fault' : msg.reason;
76
+ const note = msg.kind === 'rejected' ? `rejected:${msg.reason}: ${msg.note}` : msg.note;
77
+ push({ actor: { role: who === 'executor' ? 'worker' : 'advisor', adapter }, adapter, payload: { type: 'AdvisorUnknownOutcome', reason, note: safe(note) } });
78
+ log(`${who} ${msg.kind === 'rejected' ? 'rejected the request' : 'outcome unknown'}: ${note}. Stopping; nothing was resent.`);
79
+ return finish(msg.kind === 'rejected' ? 'failed' : 'unknown');
80
+ };
81
+ try {
82
+ push({ actor: { role: 'owner' }, payload: { type: 'TaskCreated', title: goal } });
83
+ await flush();
84
+ log(`session ${sid} created in ${journal.stateDir.replace(/\/\.ckit$/, '')}`);
85
+ log(describeWorkerEnv(executorEnvironmentReport(input.env ?? process.env, key, input.executorSpec.kind))); // preflight: before any paid advisor call
86
+ log(describeWorkerPermission(input.executorSpec.kind, config.executorPermissionMode));
87
+ /** One advisor turn through the port: prompt text is redacted, stored as an artifact (promptRef) and dispatched. */
88
+ const advise = async (adapter, thread, text) => {
89
+ const promptText = safe(text);
90
+ const promptRef = await put(promptText);
91
+ advisor.registerPrompt(promptRef, thread, promptText);
92
+ push({ actor: { role: 'advisor', adapter }, adapter, payload: { type: 'AdvisorDispatched', promptRef, adapter } });
93
+ await flush();
94
+ log(`-> ${adapter} (model ${thread.model})`);
95
+ for await (const msg of advisor.dispatch({ sessionId: sid, taskId: tid, promptRef })) {
96
+ if (msg.kind === 'ack')
97
+ push({ actor: { role: 'advisor', adapter }, adapter, payload: { type: 'AdvisorAcked', adapter } });
98
+ else if (msg.kind === 'completed') {
99
+ push({ actor: { role: 'advisor', adapter }, adapter, payload: { type: 'AdvisorCompleted', resultRef: msg.resultRef }, artifactRefs: [msg.resultRef] });
100
+ await flush();
101
+ return { reply: String((await artifacts.read(msg.resultRef)).toString('utf8')) };
102
+ }
103
+ else
104
+ return stop(adapter, adapter, msg);
105
+ }
106
+ return stop(adapter, adapter, { kind: 'unknown', reason: 'adapter-fault', note: 'advisor stream ended without a result' });
107
+ };
108
+ const isStop = (v) => 'exitCode' in v;
109
+ // Primary round 1.
110
+ const primary = advisor.createAdvisorThread('primary', `primary-${rid}`, config.primaryModel, PRIMARY_SYSTEM);
111
+ const p1 = `${sid}-p1`;
112
+ engine.reservePrimary(p1, 'bootstrap');
113
+ const r1 = await advise('openai-compatible:primary', primary, `Goal:\n${goal}`);
114
+ if (isStop(r1)) {
115
+ settle(p1, 'stopped');
116
+ return { ...r1, primarySettlements: [...settlements] };
117
+ }
118
+ settle(p1, 'sent');
119
+ const instruction = r1.reply;
120
+ log(`primary instruction recorded (${instruction.length} chars)`);
121
+ // Executor.
122
+ const xAdapter = input.executorSpec.kind;
123
+ const instrRef = await put(instruction);
124
+ push({ actor: { role: 'worker', adapter: xAdapter }, adapter: xAdapter, payload: { type: 'AdvisorDispatched', promptRef: instrRef, adapter: xAdapter } });
125
+ await flush();
126
+ log(`-> executor ${xAdapter} in ${input.projectRoot}`);
127
+ const envr = executorEnvironmentReport(input.env ?? process.env, key, input.executorSpec.kind), watcher = subagentLogger(input.executorSpec.kind, log);
128
+ watcher.announce();
129
+ const xr = await runExecutor(input.executorSpec, input.executorPath, instruction, { cwd: input.projectRoot, timeoutMs: config.executorTimeoutMs, env: envr.env, secrets: key ? [key] : [], onEvent: watcher.onEvent, ...(input.spawnImpl ? { spawnImpl: input.spawnImpl } : {}), ...(input.signal ? { signal: input.signal } : {}), ...(input.hardKill ? { hardKill: input.hardKill } : {}), onSpawn: () => push({ actor: { role: 'worker', adapter: xAdapter }, adapter: xAdapter, payload: { type: 'AdvisorAcked', adapter: xAdapter } }) });
130
+ if (xr.status !== 'completed') {
131
+ const msg = xr.status === 'failed'
132
+ ? { kind: 'unknown', reason: 'adapter-fault', note: `executor exited with code ${xr.exitCode ?? 'unknown'}; external effects may have occurred${executorFailureDetail(xr, envr.withheld)}` }
133
+ : { kind: 'unknown', reason: xr.reason === 'timeout' ? 'timeout' : 'adapter-fault', note: `${xr.reason}: ${xr.note}${executorFailureDetail(xr, envr.withheld)}` };
134
+ return stop('executor', xAdapter, msg);
135
+ }
136
+ const execRef = await put(xr.text);
137
+ push({ actor: { role: 'worker', adapter: xAdapter }, adapter: xAdapter, payload: { type: 'AdvisorCompleted', resultRef: execRef }, artifactRefs: [execRef] });
138
+ await flush();
139
+ log(`executor completed (${xr.text.length} chars)`);
140
+ const execText = safe(xr.text);
141
+ // Reviewers (own threads).
142
+ const opinions = [];
143
+ for (let i = 1; i <= config.reviewers; i++) {
144
+ const adapter = `openai-compatible:reviewer-${i}`;
145
+ const thread = advisor.createAdvisorThread('reviewer', `reviewer-${i}-${rid}`, config.reviewerModel, REVIEWER_SYSTEM);
146
+ const rr = await advise(adapter, thread, `Goal:\n${goal}\n\nInstruction given to the executor:\n${instruction}\n\nExecutor result:\n${execText}`);
147
+ if (isStop(rr))
148
+ return rr;
149
+ opinions.push(`Reviewer ${i}:\n${rr.reply}`);
150
+ }
151
+ // Primary round 2 continues the Primary's own thread.
152
+ const p2 = `${sid}-p2`;
153
+ engine.reservePrimary(p2, 'continue');
154
+ const r2 = await advise('openai-compatible:primary', primary, `Executor result:\n${execText}\n\n${opinions.length ? `${opinions.join('\n\n')}\n\n` : ''}${VERDICT_ASK}`);
155
+ if (isStop(r2)) {
156
+ settle(p2, 'stopped');
157
+ return { ...r2, primarySettlements: [...settlements] };
158
+ }
159
+ settle(p2, 'sent');
160
+ verdict = parseVerdict(r2.reply);
161
+ return finish(verdict === 'ACCEPT' ? 'success' : 'failed');
162
+ }
163
+ catch (error) {
164
+ // Keep a valid prefix; the caller reports the error (message is redacted at the CLI boundary).
165
+ await flush().catch(() => undefined);
166
+ throw error;
167
+ }
168
+ finally {
169
+ db.close();
170
+ }
171
+ });
172
+ }
173
+ //# sourceMappingURL=api-run.js.map
@@ -0,0 +1,22 @@
1
+ import type { Envelope } from '../core/events.js';
2
+ import { type ApiRunInput, type PrimarySettlement } from './api-run.js';
3
+ export type TaskStatus = 'verified' | 'acceptance-failed' | 'worker-failed' | 'unknown' | 'dependency-blocked' | 'owner-acceptance-pending';
4
+ export interface PlannedRunInput extends ApiRunInput {
5
+ readonly now?: () => string;
6
+ }
7
+ export interface PlannedTaskResult {
8
+ readonly taskId: string;
9
+ readonly sessionId: string;
10
+ readonly status: TaskStatus;
11
+ }
12
+ export interface PlannedRunResult {
13
+ readonly exitCode: 0 | 1;
14
+ readonly runId: string;
15
+ readonly planSessionId: string;
16
+ readonly taskResults: readonly PlannedTaskResult[];
17
+ readonly verdict: 'ACCEPT' | 'REJECT' | 'none';
18
+ readonly goalMet: boolean;
19
+ readonly events: readonly Envelope[];
20
+ readonly primarySettlements: readonly PrimarySettlement[];
21
+ }
22
+ export declare function runPlannedTask(input: PlannedRunInput): Promise<PlannedRunResult>;
@@ -0,0 +1,233 @@
1
+ // `ckit run` (planned): the Primary plans tasks with acceptance checks, the executor runs each task, CKit verifies the checks itself.
2
+ // No event schema change: one planning session + one session per plan task, all sharing one runId (ADR-017 + T08-07).
3
+ // The planning session stays open until the final Primary verdict, because a closed session accepts no further events.
4
+ import { randomBytes } from 'node:crypto';
5
+ import { join } from 'node:path';
6
+ import { DecisionEngine } from '../committee/decision.js';
7
+ import { projectId as toProjectId, sessionId as toSessionId, taskId as toTaskId } from '../core/ids.js';
8
+ import { initialSession, reduce } from '../core/machine.js';
9
+ import { recordEvent } from '../core/record.js';
10
+ import { containsSecretText, redactSecretText } from '../security/redact.js';
11
+ import { ArtifactStore } from '../storage/artifacts.js';
12
+ import { openDatabase } from '../storage/db.js';
13
+ import { OpenAiCompatibleAdvisor } from '../adapters/openai/openai-advisor.js';
14
+ import { describeWorkerEnv, describeWorkerPermission, executorEnvironmentReport, executorFailureDetail, runExecutor, subagentLogger } from '../adapters/launch/executor.js';
15
+ import { parseVerdict, REVIEWER_SYSTEM, settlementFor, VERDICT_ASK } from './api-run.js';
16
+ import { parsePlan, planSystemPrompt, topoReady } from './plan.js';
17
+ import { requiredAllPassed, verifyTask } from './verify.js';
18
+ export async function runPlannedTask(input) {
19
+ const { config, journal } = input;
20
+ const key = config.apiKey;
21
+ const safe = (text) => redactSecretText(text, key ? [key] : []);
22
+ const log = (line) => (input.log ?? console.log)(safe(line));
23
+ if (!input.goal.trim())
24
+ throw new TypeError('goal must not be empty');
25
+ if (containsSecretText(input.goal))
26
+ throw new TypeError('goal appears to contain secret material; refusing to persist it');
27
+ const goal = input.goal;
28
+ const now = input.now ?? (() => new Date().toISOString());
29
+ return journal.lock(async () => {
30
+ const previous = await journal.read();
31
+ const rid = randomBytes(6).toString('hex');
32
+ const runId = `run-${rid}`;
33
+ const mine = [];
34
+ const open = () => {
35
+ const sr = randomBytes(6).toString('hex');
36
+ const sid = toSessionId(`session-${sr}`), tid = toTaskId(`task-${sr}`);
37
+ return { sid, tid, state: initialSession(sid), last: undefined, ctx: { sessionId: sid, taskId: tid, projectId: toProjectId(journal.projectId), source: { liveRef: `api-run:${sid}@${config.baseUrl}` }, at: now, redactedConfigHash: 'api-run' } };
38
+ };
39
+ const push = (s, step) => {
40
+ const env = recordEvent(s.ctx, { ...step, runId }, s.last);
41
+ s.state = reduce(s.state, env);
42
+ s.last = env;
43
+ mine.push(env);
44
+ };
45
+ const flush = () => journal.write([...previous, ...mine]);
46
+ const db = openDatabase(join(journal.stateDir, 'state.sqlite'));
47
+ db.migrate();
48
+ const artifacts = new ArtifactStore(db, join(journal.stateDir, 'artifacts'));
49
+ const put = async (text) => (await artifacts.put(safe(text))).ref;
50
+ const advisor = new OpenAiCompatibleAdvisor(config, { saveReply: (_thread, text) => put(text) }, input.fetchImpl);
51
+ const engine = new DecisionEngine({ decisionId: `decision-${rid}`, primaryId: 'primary-advisor' });
52
+ const settlements = [];
53
+ const settle = (id, result) => {
54
+ if (result === 'stopped') {
55
+ const m = settlementFor(lastStop ?? { kind: 'unknown' });
56
+ engine.settlePrimary(id, m.engine);
57
+ settlements.push(m.report);
58
+ return;
59
+ }
60
+ engine.settlePrimary(id, 'sent');
61
+ settlements.push('sent');
62
+ };
63
+ const taskResults = [];
64
+ let verdict = 'none';
65
+ let lastStop = null;
66
+ const plan = open();
67
+ const result = (goalMet) => ({ exitCode: goalMet ? 0 : 1, runId, planSessionId: plan.sid, taskResults: [...taskResults], verdict, goalMet, events: [...mine], primarySettlements: [...settlements] });
68
+ const closePlan = async (outcome, reasonCode, goalMet) => {
69
+ push(plan, { actor: { role: 'system' }, payload: { type: 'TaskCompleted', outcome }, status: outcome, reasonCode });
70
+ await flush();
71
+ log(`session goal met: ${goalMet ? 'yes' : 'no'} (${reasonCode}${verdict !== 'none' ? `, verdict ${verdict}` : ''})`);
72
+ return result(goalMet);
73
+ };
74
+ const stopPlan = async (who, adapter, msg) => {
75
+ lastStop = msg;
76
+ const note = msg.kind === 'rejected' ? `rejected:${msg.reason}: ${msg.note}` : msg.note;
77
+ push(plan, { actor: { role: 'advisor', adapter }, adapter, payload: { type: 'AdvisorUnknownOutcome', reason: msg.kind === 'rejected' ? 'adapter-fault' : msg.reason, note: safe(note) } });
78
+ log(`${who} ${msg.kind === 'rejected' ? 'rejected the request' : 'outcome unknown'}: ${note}. Stopping; nothing was resent.`);
79
+ return closePlan(msg.kind === 'rejected' ? 'failed' : 'unknown', msg.kind === 'rejected' ? 'advisor-rejected' : 'advisor-unknown', false);
80
+ };
81
+ try {
82
+ push(plan, { actor: { role: 'owner' }, payload: { type: 'TaskCreated', title: goal } });
83
+ await flush();
84
+ log(`run ${runId}: planning session ${plan.sid} in ${journal.stateDir.replace(/\/\.ckit$/, '')}`);
85
+ log(describeWorkerEnv(executorEnvironmentReport(input.env ?? process.env, key, input.executorSpec.kind))); // preflight: before any paid advisor call
86
+ log(describeWorkerPermission(input.executorSpec.kind, config.executorPermissionMode));
87
+ const advise = async (adapter, thread, text) => {
88
+ const promptText = safe(text);
89
+ const promptRef = await put(promptText);
90
+ advisor.registerPrompt(promptRef, thread, promptText);
91
+ push(plan, { actor: { role: 'advisor', adapter }, adapter, payload: { type: 'AdvisorDispatched', promptRef, adapter } });
92
+ await flush();
93
+ log(`-> ${adapter} (model ${thread.model})`);
94
+ for await (const msg of advisor.dispatch({ sessionId: plan.sid, taskId: plan.tid, promptRef })) {
95
+ if (msg.kind === 'ack')
96
+ push(plan, { actor: { role: 'advisor', adapter }, adapter, payload: { type: 'AdvisorAcked', adapter } });
97
+ else if (msg.kind === 'completed') {
98
+ push(plan, { actor: { role: 'advisor', adapter }, adapter, payload: { type: 'AdvisorCompleted', resultRef: msg.resultRef }, artifactRefs: [msg.resultRef] });
99
+ await flush();
100
+ return { reply: String((await artifacts.read(msg.resultRef)).toString('utf8')) };
101
+ }
102
+ else
103
+ return stopPlan(adapter, adapter, msg);
104
+ }
105
+ return stopPlan(adapter, adapter, { kind: 'unknown', reason: 'adapter-fault', note: 'advisor stream ended without a result' });
106
+ };
107
+ const isStop = (v) => 'exitCode' in v;
108
+ // Planning turn (Primary round 1).
109
+ const limits = { maxTasks: config.maxTasks, verifyAllow: config.verifyAllow };
110
+ const primary = advisor.createAdvisorThread('primary', `primary-${rid}`, config.primaryModel, planSystemPrompt(limits));
111
+ const p1 = `${plan.sid}-p1`;
112
+ engine.reservePrimary(p1, 'bootstrap');
113
+ const r1 = await advise('openai-compatible:primary', primary, `Goal:\n${goal}`);
114
+ if (isStop(r1)) {
115
+ settle(p1, 'stopped');
116
+ return { ...r1, primarySettlements: [...settlements] };
117
+ }
118
+ settle(p1, 'sent');
119
+ const parsed = parsePlan(r1.reply, limits);
120
+ if (!parsed.ok) {
121
+ log(`plan rejected: ${parsed.reason}. No task was run; the plan was not repaired or resent.`);
122
+ return closePlan('failed', 'plan-invalid', false);
123
+ }
124
+ const tasks = parsed.plan.tasks;
125
+ log(`plan accepted: ${tasks.length} task(s)`);
126
+ // Tasks, sequentially in topological order.
127
+ const statuses = new Map();
128
+ const reports = [];
129
+ const xAdapter = input.executorSpec.kind;
130
+ const runTask = async (task) => {
131
+ const s = open();
132
+ push(s, { actor: { role: 'owner' }, payload: { type: 'TaskCreated', title: safe(`${task.id}: ${task.title}`) } });
133
+ await flush();
134
+ const finishTask = async (status, outcome, reasonCode, checks, note, refs = []) => {
135
+ push(s, { actor: { role: 'system' }, payload: { type: 'TaskCompleted', outcome }, status: status === 'verified' ? 'verified' : outcome, reasonCode, artifactRefs: refs });
136
+ await flush();
137
+ statuses.set(task.id, status);
138
+ taskResults.push({ taskId: task.id, sessionId: s.sid, status });
139
+ reports.push({ task, status, checks, note });
140
+ log(`task ${task.id} (${s.sid}): ${status}${note ? ` - ${note}` : ''}`);
141
+ };
142
+ const blocked = task.dependsOn.filter(d => statuses.get(d) !== 'verified');
143
+ if (blocked.length > 0) {
144
+ await finishTask('dependency-blocked', 'failed', 'dependency-blocked', [], `not run; dependency not verified: ${blocked.join(', ')}`);
145
+ return 'next';
146
+ }
147
+ const criteria = task.acceptance.map(a => `- [${a.required ? 'required' : 'optional'}] ${a.kind}: ${a.command ?? a.path ?? a.id}`).join('\n');
148
+ const instruction = safe(`Overall goal: ${goal}\n\nYour task (${task.id}: ${task.title}):\n${task.instruction}\n\nAcceptance checks CKit will run afterwards:\n${criteria}`);
149
+ const instrRef = await put(instruction);
150
+ push(s, { actor: { role: 'worker', adapter: xAdapter }, adapter: xAdapter, payload: { type: 'AdvisorDispatched', promptRef: instrRef, adapter: xAdapter }, artifactRefs: [instrRef] });
151
+ await flush();
152
+ log(`-> executor ${xAdapter} for task ${task.id}`);
153
+ const envr = executorEnvironmentReport(input.env ?? process.env, key, input.executorSpec.kind), watcher = subagentLogger(input.executorSpec.kind, log);
154
+ watcher.announce();
155
+ const xr = await runExecutor(input.executorSpec, input.executorPath, instruction, { cwd: input.projectRoot, timeoutMs: config.executorTimeoutMs, env: envr.env, secrets: key ? [key] : [], onEvent: watcher.onEvent, ...(input.spawnImpl ? { spawnImpl: input.spawnImpl } : {}), ...(input.signal ? { signal: input.signal } : {}), ...(input.hardKill ? { hardKill: input.hardKill } : {}), onSpawn: () => push(s, { actor: { role: 'worker', adapter: xAdapter }, adapter: xAdapter, payload: { type: 'AdvisorAcked', adapter: xAdapter } }) });
156
+ if (xr.status !== 'completed') {
157
+ const unknownReason = xr.status === 'failed' ? 'adapter-fault' : xr.reason === 'timeout' ? 'timeout' : 'adapter-fault';
158
+ const note = xr.status === 'failed' ? `executor exited with code ${xr.exitCode ?? 'unknown'}; external effects may have occurred${executorFailureDetail(xr, envr.withheld)}` : `${xr.reason}: ${xr.note}${executorFailureDetail(xr, envr.withheld)}`;
159
+ push(s, { actor: { role: 'worker', adapter: xAdapter }, adapter: xAdapter, payload: { type: 'AdvisorUnknownOutcome', reason: unknownReason, note: safe(note) } });
160
+ if (xr.status === 'failed')
161
+ await finishTask('worker-failed', 'failed', 'worker-failed', [], note);
162
+ else
163
+ await finishTask('unknown', 'unknown', xr.reason === 'timeout' ? 'worker-timeout' : xr.reason, [], note);
164
+ return xr.status === 'unknown' && xr.reason === 'cancelled' ? 'stop' : 'next';
165
+ }
166
+ const execRef = await put(xr.text);
167
+ push(s, { actor: { role: 'worker', adapter: xAdapter }, adapter: xAdapter, payload: { type: 'AdvisorCompleted', resultRef: execRef }, artifactRefs: [execRef] });
168
+ await flush();
169
+ const checks = await verifyTask(task.id, task.acceptance, { projectRoot: input.projectRoot, config, ...(input.env ? { env: input.env } : {}), ...(input.signal ? { signal: input.signal } : {}) });
170
+ const reportRef = await put(checks.map(c => `${c.taskId}/${c.checkId} [${c.required ? 'required' : 'optional'}] ${c.status}: ${c.detail}`).join('\n') || 'no checks');
171
+ if (requiredAllPassed(checks))
172
+ await finishTask('verified', 'success', 'acceptance-verified', checks, 'worker exit 0, required checks passed', [reportRef]);
173
+ else if (checks.some(c => c.required && (c.status === 'fail' || c.status === 'error')))
174
+ await finishTask('acceptance-failed', 'failed', 'acceptance-failed', checks, 'worker exit 0 but a required check failed', [reportRef]);
175
+ else
176
+ await finishTask('owner-acceptance-pending', 'failed', 'owner-acceptance-pending', checks, 'a required check needs owner acceptance', [reportRef]);
177
+ return 'next';
178
+ };
179
+ for (;;) {
180
+ if (input.signal?.aborted)
181
+ break;
182
+ const pending = tasks.filter(t => !statuses.has(t.id));
183
+ if (pending.length === 0)
184
+ break;
185
+ const ready = topoReady({ tasks }, statuses);
186
+ // A task whose dependency is terminal-but-not-verified is run through the blocked path (own session, no spawn).
187
+ const next = ready[0] ?? pending.find(t => t.dependsOn.every(d => statuses.has(d)));
188
+ if (!next)
189
+ break;
190
+ if (await runTask(next) === 'stop')
191
+ break;
192
+ }
193
+ if (input.signal?.aborted) {
194
+ log('run cancelled: no reviewers and no verdict turn were requested.');
195
+ return closePlan('failed', 'cancelled', false);
196
+ }
197
+ // Reviewers (own threads) over the aggregate report.
198
+ const report = safe(reports.map(r => `Task ${r.task.id} (${r.task.title}): ${r.status}${r.note ? ` - ${r.note}` : ''}\n${r.checks.map(c => ` check ${c.checkId} [${c.required ? 'required' : 'optional'}] ${c.status}: ${c.detail}`).join('\n')}`).join('\n'));
199
+ const opinions = [];
200
+ for (let i = 1; i <= config.reviewers; i++) {
201
+ const thread = advisor.createAdvisorThread('reviewer', `reviewer-${i}-${rid}`, config.reviewerModel, REVIEWER_SYSTEM);
202
+ const rr = await advise(`openai-compatible:reviewer-${i}`, thread, `Goal:\n${goal}\n\nVerification report (checks were run by CKit, not by the executor):\n${report}`);
203
+ if (isStop(rr))
204
+ return rr;
205
+ opinions.push(`Reviewer ${i}:\n${rr.reply}`);
206
+ }
207
+ // Primary round 2 continues the Primary's thread.
208
+ const p2 = `${plan.sid}-p2`;
209
+ engine.reservePrimary(p2, 'continue');
210
+ const r2 = await advise('openai-compatible:primary', primary, `Verification report:\n${report}\n\n${opinions.length ? `${opinions.join('\n\n')}\n\n` : ''}${VERDICT_ASK}`);
211
+ if (isStop(r2)) {
212
+ settle(p2, 'stopped');
213
+ return { ...r2, primarySettlements: [...settlements] };
214
+ }
215
+ settle(p2, 'sent');
216
+ verdict = parseVerdict(r2.reply);
217
+ const allVerified = tasks.every(t => statuses.get(t.id) === 'verified');
218
+ const goalMet = allVerified && verdict === 'ACCEPT';
219
+ const verifiedCount = [...statuses.values()].filter(v => v === 'verified').length;
220
+ const blockedCount = taskResults.filter(t => t.status === 'dependency-blocked').length;
221
+ log(`summary: ${tasks.length} planned, ${taskResults.length - blockedCount} attempted (spawned), blocked ${blockedCount}; acceptance verified ${verifiedCount}/${tasks.length}; reviewer/primary opinion ${verdict}; (an opinion never overrides a failed required check)`);
222
+ return closePlan(goalMet ? 'success' : 'failed', goalMet ? 'goal-met' : allVerified ? 'verdict-not-accept' : 'acceptance-unmet', goalMet);
223
+ }
224
+ catch (error) {
225
+ await flush().catch(() => undefined);
226
+ throw error;
227
+ }
228
+ finally {
229
+ db.close();
230
+ }
231
+ });
232
+ }
233
+ //# sourceMappingURL=plan-run.js.map
@@ -0,0 +1,36 @@
1
+ export interface Acceptance {
2
+ readonly id: string;
3
+ readonly kind: 'command' | 'file-exists' | 'manual';
4
+ readonly command?: string;
5
+ readonly path?: string;
6
+ readonly required: boolean;
7
+ }
8
+ export interface PlanTask {
9
+ readonly id: string;
10
+ readonly title: string;
11
+ readonly instruction: string;
12
+ readonly dependsOn: readonly string[];
13
+ readonly acceptance: readonly Acceptance[];
14
+ }
15
+ export interface Plan {
16
+ readonly tasks: readonly PlanTask[];
17
+ }
18
+ export interface PlanLimits {
19
+ readonly maxTasks: number;
20
+ readonly verifyAllow: readonly string[];
21
+ }
22
+ export type PlanParse = {
23
+ readonly ok: true;
24
+ readonly plan: Plan;
25
+ } | {
26
+ readonly ok: false;
27
+ readonly reason: string;
28
+ };
29
+ export declare const SHELL_META: RegExp;
30
+ /** Whole-token prefix match: the command equals an allowed prefix or continues it after a space. */
31
+ export declare function commandAllowed(command: string, allow: readonly string[]): boolean;
32
+ export declare function planSystemPrompt(limits: PlanLimits): string;
33
+ export declare const PLAN_SYSTEM: string;
34
+ export declare function parsePlan(text: string, limits: PlanLimits): PlanParse;
35
+ /** Tasks that are still pending and whose dependencies are all verified, in plan order. */
36
+ export declare function topoReady(plan: Plan, statuses: ReadonlyMap<string, string>): PlanTask[];
@@ -0,0 +1,119 @@
1
+ export const SHELL_META = /[;&|`$<>(){}\n\\]/;
2
+ /** Whole-token prefix match: the command equals an allowed prefix or continues it after a space. */
3
+ export function commandAllowed(command, allow) {
4
+ const c = command.trim().replace(/\s+/g, ' ');
5
+ return allow.some(a => c === a || c.startsWith(`${a} `));
6
+ }
7
+ export function planSystemPrompt(limits) {
8
+ return `You are the Primary advisor planning work for a coding agent that works in the project root. Split the goal into at most ${limits.maxTasks} tasks and reply with ONE JSON object (optionally inside a \`\`\`json fence) and nothing else, in exactly this schema:
9
+ {"tasks":[{"id":"t1","title":"short title","instruction":"concrete instruction for the coding agent","dependsOn":[],"acceptance":[{"id":"a1","kind":"command|file-exists|manual","command":"only for kind command","path":"project-relative path, only for kind file-exists","required":true}]}]}
10
+ Rules: ids are unique; dependsOn lists ids of earlier tasks (no cycles); every task needs at least one acceptance check with required:true of kind command or file-exists (manual checks never count as automatic). Commands run without a shell, so they must not contain ; & | \` $ < > ( ) { } backslashes or newlines, and must start with one of these allowed prefixes: ${limits.verifyAllow.join(' | ')}. file-exists paths must be relative and must not contain "..".`;
11
+ }
12
+ export const PLAN_SYSTEM = planSystemPrompt({ maxTasks: 6, verifyAllow: ['npm test', 'npm run build', 'npm run lint', 'npm run typecheck', 'npx tsc --noEmit', 'node --test', 'pytest', 'go test', 'cargo test', 'make test'] });
13
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
14
+ const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
15
+ function extractJson(text) {
16
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(text);
17
+ const candidates = [];
18
+ if (fenced)
19
+ candidates.push(fenced[1]);
20
+ const start = text.indexOf('{'), end = text.lastIndexOf('}');
21
+ if (start >= 0 && end > start)
22
+ candidates.push(text.slice(start, end + 1));
23
+ for (const c of candidates) {
24
+ try {
25
+ return JSON.parse(c.trim());
26
+ }
27
+ catch { /* try next */ }
28
+ }
29
+ return undefined;
30
+ }
31
+ export function parsePlan(text, limits) {
32
+ const raw = extractJson(text);
33
+ if (raw === undefined)
34
+ return { ok: false, reason: 'no JSON object found in the Primary reply' };
35
+ if (!isObj(raw) || !Array.isArray(raw['tasks']) || raw['tasks'].length === 0)
36
+ return { ok: false, reason: 'invalid shape: expected {"tasks":[...]} with at least one task' };
37
+ const rawTasks = raw['tasks'];
38
+ if (rawTasks.length > limits.maxTasks)
39
+ return { ok: false, reason: `too many tasks: ${rawTasks.length} > ${limits.maxTasks}` };
40
+ const tasks = [];
41
+ const ids = new Set();
42
+ for (const [i, t] of rawTasks.entries()) {
43
+ const at = `task #${i + 1}`;
44
+ if (!isObj(t) || !nonEmpty(t['id']) || !nonEmpty(t['title']) || !nonEmpty(t['instruction']))
45
+ return { ok: false, reason: `invalid shape: ${at} needs non-empty id, title, instruction` };
46
+ const id = t['id'];
47
+ if (!/^[A-Za-z0-9_-]{1,40}$/.test(id))
48
+ return { ok: false, reason: `invalid shape: ${at} id must match [A-Za-z0-9_-]{1,40}` };
49
+ if (ids.has(id))
50
+ return { ok: false, reason: `duplicate task id "${id}"` };
51
+ ids.add(id);
52
+ const dep = t['dependsOn'] ?? [];
53
+ if (!Array.isArray(dep) || !dep.every(nonEmpty))
54
+ return { ok: false, reason: `invalid shape: ${at} dependsOn must be an array of ids` };
55
+ if (!Array.isArray(t['acceptance']))
56
+ return { ok: false, reason: `invalid shape: task "${id}" needs an acceptance array` };
57
+ const acceptance = [];
58
+ const aids = new Set();
59
+ for (const a of t['acceptance']) {
60
+ if (!isObj(a) || !nonEmpty(a['id']) || typeof a['required'] !== 'boolean' || (a['kind'] !== 'command' && a['kind'] !== 'file-exists' && a['kind'] !== 'manual'))
61
+ return { ok: false, reason: `invalid shape: task "${id}" has a malformed acceptance entry` };
62
+ const aid = a['id'];
63
+ if (aids.has(aid))
64
+ return { ok: false, reason: `duplicate acceptance id "${aid}" in task "${id}"` };
65
+ aids.add(aid);
66
+ const base = { id: aid, required: a['required'] };
67
+ if (a['kind'] === 'command') {
68
+ if (!nonEmpty(a['command']))
69
+ return { ok: false, reason: `invalid shape: acceptance "${aid}" of task "${id}" needs a command` };
70
+ const command = a['command'].trim();
71
+ if (SHELL_META.test(command))
72
+ return { ok: false, reason: `command of acceptance "${aid}" in task "${id}" contains shell metacharacters` };
73
+ if (!commandAllowed(command, limits.verifyAllow))
74
+ return { ok: false, reason: `command of acceptance "${aid}" in task "${id}" is not allowed (CKIT_VERIFY_ALLOW)` };
75
+ acceptance.push({ ...base, kind: 'command', command });
76
+ }
77
+ else if (a['kind'] === 'file-exists') {
78
+ if (!nonEmpty(a['path']))
79
+ return { ok: false, reason: `invalid shape: acceptance "${aid}" of task "${id}" needs a path` };
80
+ const path = a['path'].trim();
81
+ if (/^([A-Za-z]:|[\\/])/.test(path) || path.split(/[\\/]/).includes('..') || path.includes('\0'))
82
+ return { ok: false, reason: `path of acceptance "${aid}" in task "${id}" is absolute or escapes the project` };
83
+ acceptance.push({ ...base, kind: 'file-exists', path });
84
+ }
85
+ else
86
+ acceptance.push({ ...base, kind: 'manual' });
87
+ }
88
+ if (!acceptance.some(a => a.required && a.kind !== 'manual'))
89
+ return { ok: false, reason: `task "${id}" has no required automatic acceptance check (command or file-exists)` };
90
+ tasks.push({ id, title: t['title'], instruction: t['instruction'], dependsOn: dep, acceptance });
91
+ }
92
+ for (const t of tasks)
93
+ for (const d of t.dependsOn) {
94
+ if (!ids.has(d))
95
+ return { ok: false, reason: `task "${t.id}" depends on unknown task "${d}"` };
96
+ if (d === t.id)
97
+ return { ok: false, reason: `dependency cycle at task "${t.id}"` };
98
+ }
99
+ // Cycle detection (Kahn).
100
+ const left = new Map(tasks.map(t => [t.id, new Set(t.dependsOn)]));
101
+ for (;;) {
102
+ const free = [...left].filter(([, deps]) => deps.size === 0).map(([id]) => id);
103
+ if (free.length === 0)
104
+ break;
105
+ for (const id of free) {
106
+ left.delete(id);
107
+ for (const deps of left.values())
108
+ deps.delete(id);
109
+ }
110
+ }
111
+ if (left.size > 0)
112
+ return { ok: false, reason: `dependency cycle among tasks: ${[...left.keys()].join(', ')}` };
113
+ return { ok: true, plan: { tasks } };
114
+ }
115
+ /** Tasks that are still pending and whose dependencies are all verified, in plan order. */
116
+ export function topoReady(plan, statuses) {
117
+ return plan.tasks.filter(t => !statuses.has(t.id) && t.dependsOn.every(d => statuses.get(d) === 'verified'));
118
+ }
119
+ //# sourceMappingURL=plan.js.map