@chemx/starter-kit 26.10.29-360 → 26.11.15-614

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 (103) hide show
  1. package/README.md +106 -433
  2. package/cli/audit/ratchet.js +52 -7
  3. package/cli/commands/cmd-router.js +3 -1
  4. package/cli/commands-schema-commit.js +3 -2
  5. package/cli/commands-schema-search.js +1 -0
  6. package/cli/commands-schema-team.js +11 -4
  7. package/cli/commit/commit-args.js +5 -4
  8. package/cli/commit/commit-hunks.js +108 -0
  9. package/cli/commit/commit-run.js +33 -2
  10. package/cli/config/index.js +28 -0
  11. package/cli/docs-check/command-tree.js +1 -1
  12. package/cli/generator-indexer.js +3 -2
  13. package/cli/index-seed.js +1 -0
  14. package/cli/lang/detect.js +189 -0
  15. package/cli/lang/legacy-extensions.js +9 -0
  16. package/cli/lang/records/c.js +53 -0
  17. package/cli/lang/records/cpp.js +76 -0
  18. package/cli/lang/records/csharp.js +59 -0
  19. package/cli/lang/records/go.js +47 -0
  20. package/cli/lang/records/index.js +18 -0
  21. package/cli/lang/records/java.js +55 -0
  22. package/cli/lang/records/javascript.js +50 -0
  23. package/cli/lang/records/kotlin.js +48 -0
  24. package/cli/lang/records/php.js +54 -0
  25. package/cli/lang/records/python.js +50 -0
  26. package/cli/lang/records/rust.js +47 -0
  27. package/cli/lang/records/svelte.js +45 -0
  28. package/cli/lang/records/typescript.js +66 -0
  29. package/cli/lang/records/vue.js +45 -0
  30. package/cli/lang/registry.js +73 -0
  31. package/cli/lang/rollout.js +114 -0
  32. package/cli/lang/schema.js +288 -0
  33. package/cli/lang/static-table.js +71 -0
  34. package/cli/lang/types.d.ts +142 -0
  35. package/cli/lang/vocab.js +90 -0
  36. package/cli/languages.js +50 -88
  37. package/cli/search-args.js +1 -1
  38. package/cli/search-ast-module.js +26 -3
  39. package/cli/search-ast.js +4 -2
  40. package/cli/search-commands.js +44 -0
  41. package/cli/search-db.js +1 -0
  42. package/cli/search-index-meta.js +23 -7
  43. package/cli/search-index-write.js +5 -2
  44. package/cli/search-literal.js +24 -6
  45. package/cli/search-queries.js +19 -0
  46. package/cli/search-schema-ddl.js +11 -0
  47. package/cli/search-schema.js +6 -3
  48. package/cli/search-sync-paths.js +4 -3
  49. package/cli/search-sync-rows.js +2 -2
  50. package/cli/search-sync.js +2 -0
  51. package/cli/search.js +8 -3
  52. package/cli/team/check-delivery.js +115 -0
  53. package/cli/team/check-drainer.js +288 -0
  54. package/cli/team/check-executor.js +106 -0
  55. package/cli/team/check-fingerprint.js +105 -0
  56. package/cli/team/check-queue.js +114 -0
  57. package/cli/team/help/card-rows.js +2 -1
  58. package/cli/team/help/check.js +6 -0
  59. package/cli/team/team-commands-check.js +142 -0
  60. package/cli/team/team-commands.js +6 -4
  61. package/cli/team/team-db-feed.js +6 -0
  62. package/cli/team/team-db-task-helpers.js +9 -6
  63. package/cli/team/team-dispatch-prompts.js +10 -1
  64. package/cli/team/team-dispatch-select.js +1 -0
  65. package/cli/team/team-dispatch-v2.js +1 -0
  66. package/cli/team/team-dispatch.js +3 -1
  67. package/cli/team/team-help-golden.json +20 -5
  68. package/cli/team/team-schema-checks.js +46 -0
  69. package/cli/team/team-schema.js +2 -0
  70. package/cli/ui-api-index.js +39 -0
  71. package/cli/ui-handlers.js +17 -20
  72. package/cli/ui-html.js +17 -4
  73. package/cli/ui-index.html +298 -107
  74. package/cli/ui-page/components/00-core.css +10 -0
  75. package/cli/ui-page/components/00-core.js +78 -0
  76. package/cli/ui-page/components/xo-agent-profile.js +6 -0
  77. package/cli/ui-page/components/xo-avatar.js +17 -0
  78. package/cli/ui-page/components/xo-composer.js +5 -0
  79. package/cli/ui-page/components/xo-notification-bell.js +5 -0
  80. package/cli/ui-page/components/xo-post-card.js +20 -0
  81. package/cli/ui-page/components/xo-post-permalink.js +5 -0
  82. package/cli/ui-page/components/xo-post-thread.js +5 -0
  83. package/cli/ui-page/components/xo-timeline.js +52 -0
  84. package/cli/ui-page/components/xo-today-card.js +5 -0
  85. package/cli/ui-paging-agents.js +34 -0
  86. package/cli/ui-paging-feed.js +14 -0
  87. package/cli/ui-paging-task-where.js +63 -0
  88. package/cli/ui-paging-tasks.js +68 -0
  89. package/cli/ui-paging.js +35 -0
  90. package/cli/ui-server-routes.js +5 -4
  91. package/cli/ui-server.js +12 -0
  92. package/cli/ui-social-digest.js +12 -0
  93. package/cli/ui-social-feed.js +12 -0
  94. package/cli/ui-social-mentions.js +12 -0
  95. package/cli/ui-social-notify.js +12 -0
  96. package/cli/ui-social-posts.js +12 -0
  97. package/cli/ui-social-profile.js +12 -0
  98. package/cli/ui-social-routes.js +21 -0
  99. package/cli/ui-social-threads.js +12 -0
  100. package/package.json +2 -2
  101. package/scripts/package-json-guard.mjs +35 -0
  102. package/scripts/package-json-guard.spec.mjs +50 -0
  103. package/scripts/publish-both.mjs +25 -7
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Delivers a finished check: a DM to every requester (PASS is one line; FAIL is the fault count and up to
3
+ * 25 faults) and a board post only when it did not pass. A cancelled check is delivered as a one-line DM.
4
+ * The sender is @check_runner, so the result reaches a requester whose session is gone: the DM waits in the inbox.
5
+ *
6
+ * Delivery is at-least-once and exception-safe: each requester is notified in its own try/catch and marked
7
+ * notified (notified_at) only after the DM went out, the board post is recorded on the job so it happens once,
8
+ * and redeliverUnnotified() sweeps finished jobs that still have an un-notified requester (the worker does it on
9
+ * start), so a crash or a DM error between "result recorded" and "requesters told" loses nothing.
10
+ */
11
+
12
+ import { sendDirectMessage } from './team-db-mailbox.js';
13
+ import { postFeedEvent } from './team-db-feed.js';
14
+ import { isDerivedHandle } from './agent-identity.js';
15
+ import { rowToJob } from './check-queue.js';
16
+
17
+ export const CHECK_RUNNER = '@check_runner';
18
+ export const MAX_FAULTS = 25;
19
+
20
+ // The process-scoped fallback handle (@agent-<pid>-<hex>) nobody reads. Older rows may still carry one.
21
+ const PHANTOM_HANDLE = /^@agent-\d+-[0-9a-f]{6}$/;
22
+
23
+ export const isPhantomHandle = (handle) => PHANTOM_HANDLE.test(String(handle || '')) || isDerivedHandle(handle);
24
+
25
+ const seconds = (ms) => `${(Math.max(0, ms || 0) / 1000).toFixed(1)}s`;
26
+
27
+ const faultLine = (fault) => {
28
+ const where = fault.file ? `${fault.file}${fault.line ? `:${fault.line}` : ''}` : '';
29
+ const code = fault.code ? ` ${fault.code}` : '';
30
+ return ` ${where}${code} ${fault.message || ''}`.trimEnd();
31
+ };
32
+
33
+ export const formatPass = (job, result) => `check #${job.id} ${job.kind} PASS (${seconds(result.durationMs)})${result.stale ? ' [tree changed while it ran]' : ''}`;
34
+
35
+ export const formatCancelled = (job, result) => `check #${job.id} ${job.kind} CANCELLED${result.cancelledBy ? ` by ${result.cancelledBy}` : ''}; no result will come. Rerun: chemx team check ${job.kind}`;
36
+
37
+ export const formatFailure = (job, result) => {
38
+ const faults = result.faults || [];
39
+ const shown = faults.slice(0, MAX_FAULTS);
40
+ const total = Math.max(result.errorCount || 0, faults.length);
41
+ const hidden = total - shown.length;
42
+ const verdict = result.status === 'inconclusive' ? 'INCONCLUSIVE' : 'FAIL';
43
+ const head = `check #${job.id} ${job.kind} ${verdict}: ${total} fault(s)${result.summaryLine ? `. ${result.summaryLine}` : ''}${result.stale ? ' [tree changed while it ran]' : ''}`;
44
+ const more = hidden > 0 ? [` +${hidden} more (chemx team check show ${job.id})`] : [];
45
+ return [head, ...shown.map(faultLine), ...more, `Rerun: chemx team check ${job.kind}`].join('\n');
46
+ };
47
+
48
+ const FORMATTERS = { cancelled: formatCancelled, pass: formatPass };
49
+
50
+ const messageFor = (job, result) => (FORMATTERS[result.status] || formatFailure)(job, result);
51
+
52
+ const hasBoardPost = (db, jobId) => db.prepare("SELECT json_extract(result, '$.boardPostedAt') AS at FROM check_jobs WHERE id = ?").get(jobId)?.at != null;
53
+
54
+ const markPosted = (db, jobId, now) => db.prepare("UPDATE check_jobs SET result = json_set(result, '$.boardPostedAt', ?) WHERE id = ?").run(now, jobId);
55
+
56
+ const markNotified = (db, jobId, agentId, now) => db.prepare('UPDATE check_requesters SET notified_at = ? WHERE job_id = ? AND agent_id = ?').run(now, jobId, agentId);
57
+
58
+ /**
59
+ * Tells every requester not yet notified, and posts a non-passing result to the board once.
60
+ * Returns { dms, posted, skipped, errors }: `errors` lists what failed and will be retried by the next sweep.
61
+ */
62
+ export const deliverCheckResult = (db, job, result, { send = sendDirectMessage, post = postFeedEvent } = {}) => {
63
+ const isPass = result.status === 'pass';
64
+ const isCancelled = result.status === 'cancelled';
65
+ const message = messageFor(job, result);
66
+ const metadata = { checkId: job.id, kind: job.kind, status: result.status };
67
+ const requesters = db.prepare('SELECT agent_id, task_id FROM check_requesters WHERE job_id = ? AND notified_at IS NULL ORDER BY agent_id').all(job.id);
68
+ const now = Date.now();
69
+ const outcome = { dms: 0, posted: false, skipped: 0, errors: [] };
70
+ const shouldPost = !isPass && !isCancelled && !hasBoardPost(db, job.id);
71
+ if (shouldPost) {
72
+ try {
73
+ post(db, { author_id: CHECK_RUNNER, event_type: 'check_result', message, metadata });
74
+ markPosted(db, job.id, now);
75
+ outcome.posted = true;
76
+ } catch (error) {
77
+ outcome.errors.push(`board post: ${error?.message || error}`);
78
+ }
79
+ }
80
+ for (const requester of requesters) {
81
+ if (isPhantomHandle(requester.agent_id)) {
82
+ markNotified(db, job.id, requester.agent_id, now);
83
+ outcome.skipped += 1;
84
+ continue;
85
+ }
86
+ try {
87
+ send(db, { author_id: CHECK_RUNNER, recipient_id: requester.agent_id, task_id: requester.task_id, message, metadata });
88
+ markNotified(db, job.id, requester.agent_id, now);
89
+ outcome.dms += 1;
90
+ } catch (error) {
91
+ outcome.errors.push(`dm ${requester.agent_id}: ${error?.message || error}`);
92
+ }
93
+ }
94
+ return outcome;
95
+ };
96
+
97
+ /** Finished jobs that still have a requester nobody told: the work a crash or a DM error left behind. */
98
+ export const unnotifiedJobs = (db) => db.prepare("SELECT DISTINCT j.* FROM check_jobs j JOIN check_requesters r ON r.job_id = j.id WHERE j.status IN ('done', 'failed', 'cancelled') AND r.notified_at IS NULL ORDER BY j.id").all().map(rowToJob);
99
+
100
+ /**
101
+ * Delivers every unnotified finished job through `deliver`; one job's error never stops the rest and leaves that job
102
+ * un-notified for the next sweep. Returns { attempted, failures: [{ id, error }] }.
103
+ */
104
+ export const redeliverUnnotified = (db, deliver) => {
105
+ const jobs = unnotifiedJobs(db);
106
+ const failures = [];
107
+ for (const job of jobs) {
108
+ try {
109
+ deliver(db, job, job.result);
110
+ } catch (error) {
111
+ failures.push({ id: job.id, error: String(error?.message || error) });
112
+ }
113
+ }
114
+ return { attempted: jobs.length, failures };
115
+ };
@@ -0,0 +1,288 @@
1
+ /**
2
+ * The check queue's single drain worker. One row in check_drainer is the lease: it is taken in a
3
+ * BEGIN IMMEDIATE transaction, kept alive by a heartbeat, and taken over when the heartbeat is stale
4
+ * or the holder's pid is dead. The worker is detached and unref'd (no daemon): it runs due jobs one
5
+ * at a time through the injected executor, recovers jobs a dead worker left running, and exits
6
+ * after an idle period. Clock, executor, delivery and fingerprint are injected so specs never wait or spawn.
7
+ *
8
+ * Failure handling: while a job runs, a watcher heartbeats the lease and polls the row, and aborts the executor
9
+ * (which kills the check's process tree) when the job was cancelled or this worker lost the lease. A busy db never
10
+ * kills the worker. Delivery never throws into the loop: a result that could not be delivered stays un-notified,
11
+ * and the worker re-delivers every finished-but-unnotified job when it starts and again before it goes idle.
12
+ */
13
+
14
+ import { spawn } from 'node:child_process';
15
+ import { randomUUID } from 'node:crypto';
16
+ import { closeSync, openSync, statSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ import { setTimeout as delay } from 'node:timers/promises';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { isPidAlive, isSqliteBusyError, withImmediateTransaction } from './team-db-transaction.js';
22
+ import { rowToJob } from './check-queue.js';
23
+ import { treeFingerprint } from './check-fingerprint.js';
24
+ import { redeliverUnnotified } from './check-delivery.js';
25
+
26
+ export const LEASE_STALE_MS = 30_000;
27
+ export const HEARTBEAT_MS = 5_000;
28
+ export const IDLE_EXIT_MS = 60_000;
29
+ export const MAX_ATTEMPTS = 2;
30
+ const POLL_MS = 1_000;
31
+ const LEASE_LOST = 'lease-lost';
32
+ const CANCELLED = 'cancelled';
33
+ const CANCEL_POLL_MS = 1_000;
34
+ const MAX_LOG_BYTES = 1_000_000;
35
+ const CLI_ENTRY = fileURLToPath(new URL('../index.js', import.meta.url));
36
+
37
+ export const acquireLease = (db, { pid, token, now = Date.now(), isAlive = isPidAlive }) => withImmediateTransaction(db, () => {
38
+ const row = db.prepare('SELECT pid, token, heartbeat FROM check_drainer WHERE id = 1').get();
39
+ const isMine = Boolean(row) && row.token === token;
40
+ const isStale = Boolean(row) && (now - row.heartbeat >= LEASE_STALE_MS || !isAlive(row.pid));
41
+ const isFree = !row || isMine || isStale;
42
+ if (!isFree) return false;
43
+ db.prepare('INSERT OR REPLACE INTO check_drainer (id, pid, token, heartbeat, started_at) VALUES (1, ?, ?, ?, ?)').run(pid, token, now, now);
44
+ return true;
45
+ });
46
+
47
+ /** false when this worker no longer holds the lease (another took over). */
48
+ export const heartbeat = (db, token, now = Date.now()) => db.prepare('UPDATE check_drainer SET heartbeat = ? WHERE id = 1 AND token = ?').run(now, token).changes > 0;
49
+
50
+ export const releaseLease = (db, token) => {
51
+ db.prepare('DELETE FROM check_drainer WHERE id = 1 AND token = ?').run(token);
52
+ };
53
+
54
+ export const drainerStatus = (db, now = Date.now(), isAlive = isPidAlive) => {
55
+ const row = db.prepare('SELECT pid, heartbeat, started_at FROM check_drainer WHERE id = 1').get();
56
+ if (!row) return { running: false };
57
+ const ageMs = now - row.heartbeat;
58
+ return { running: ageMs < LEASE_STALE_MS && isAlive(row.pid), pid: row.pid, heartbeatAgeMs: ageMs, startedAt: row.started_at };
59
+ };
60
+
61
+ /** Where the detached worker's stdout and stderr go, so a crash at startup leaves a trace. */
62
+ export const drainLogPath = (env = process.env) => env.CHEMX_CHECK_DRAIN_LOG || join(tmpdir(), `chemx-check-drainer-${process.getuid?.() ?? 'user'}.log`);
63
+
64
+ const openDrainLog = (path) => {
65
+ try {
66
+ const isOversize = statSync(path, { throwIfNoEntry: false })?.size > MAX_LOG_BYTES;
67
+ return openSync(path, isOversize ? 'w' : 'a');
68
+ } catch {
69
+ // chemx-allow: best-effort an unwritable log only costs the trace, not the worker
70
+ return 'ignore';
71
+ }
72
+ };
73
+
74
+ /** Spawns the detached worker. A spawn that fails (now or on the next tick) is reported on stderr, never swallowed. */
75
+ const defaultSpawn = (cwd) => {
76
+ const logPath = drainLogPath();
77
+ const log = openDrainLog(logPath);
78
+ const child = spawn(process.execPath, [CLI_ENTRY, 'team', 'check', 'drain'], { cwd, detached: true, stdio: ['ignore', log, log], env: { ...process.env, CHEMX_DRAIN: '1' } });
79
+ child.on('error', (error) => process.stderr.write(`chemx: the check drain worker could not start (${error.message}). Run \`chemx team check drain\` yourself; worker log: ${logPath}\n`));
80
+ child.unref();
81
+ const isFileDescriptor = typeof log === 'number';
82
+ if (isFileDescriptor) closeSync(log);
83
+ };
84
+
85
+ /**
86
+ * Starts a detached worker unless a live one holds the lease. Returns { spawned, error }: `error` is why a spawn
87
+ * threw. Callers run it for every enqueue that is not answered from cache, so a dead or crashed worker is revived
88
+ * even when the new request coalesced into, or joined, a job nobody is working on.
89
+ */
90
+ export const ensureDrainer = (db, { cwd, now = Date.now(), isAlive = isPidAlive, spawnWorker = defaultSpawn } = {}) => {
91
+ if (drainerStatus(db, now, isAlive).running) return { spawned: false, error: null };
92
+ try {
93
+ spawnWorker(cwd);
94
+ return { spawned: true, error: null };
95
+ } catch (error) {
96
+ return { spawned: false, error: String(error?.message || error) };
97
+ }
98
+ };
99
+
100
+ /** Jobs left 'running' by a dead worker: requeue once, then fail as inconclusive. Returns the failed ones. */
101
+ export const recoverOrphans = (db, now = Date.now()) => withImmediateTransaction(db, () => {
102
+ const orphans = db.prepare("SELECT * FROM check_jobs WHERE status = 'running'").all();
103
+ const failed = [];
104
+ for (const row of orphans) {
105
+ const isExhausted = row.attempts >= MAX_ATTEMPTS;
106
+ if (!isExhausted) {
107
+ db.prepare("UPDATE check_jobs SET status = 'queued', worker_token = NULL, worker_pid = 0 WHERE id = ?").run(row.id);
108
+ continue;
109
+ }
110
+ const result = { status: 'inconclusive', reason: 'worker-crash', summaryLine: 'the drain worker died twice while running this check', faults: [], errorCount: 0 };
111
+ db.prepare("UPDATE check_jobs SET status = 'failed', finished_at = ?, result = ? WHERE id = ?").run(now, JSON.stringify(result), row.id);
112
+ failed.push(rowToJob({ ...row, status: 'failed', result: JSON.stringify(result) }));
113
+ }
114
+ return failed;
115
+ });
116
+
117
+ const claimNext = (db, { token, pid, now }) => withImmediateTransaction(db, () => {
118
+ const row = db.prepare("SELECT * FROM check_jobs WHERE status = 'queued' AND run_at <= ? ORDER BY priority, id LIMIT 1").get(now);
119
+ if (!row) return null;
120
+ db.prepare("UPDATE check_jobs SET status = 'running', started_at = ?, worker_token = ?, worker_pid = ?, attempts = attempts + 1 WHERE id = ?").run(now, token, pid, row.id);
121
+ return rowToJob(db.prepare('SELECT * FROM check_jobs WHERE id = ?').get(row.id));
122
+ });
123
+
124
+ /** Records the result unless the job was cancelled meanwhile; returns whether it was recorded. */
125
+ const finishJob = (db, job, result, now) => {
126
+ const status = result.status === 'pass' ? 'done' : 'failed';
127
+ const info = db.prepare("UPDATE check_jobs SET status = ?, finished_at = ?, result = ? WHERE id = ? AND status = 'running' AND worker_token = ?").run(status, now, JSON.stringify(result), job.id, job.worker_token);
128
+ return info.changes > 0;
129
+ };
130
+
131
+ const hasQueued = (db) => db.prepare("SELECT 1 AS found FROM check_jobs WHERE status = 'queued' LIMIT 1").get() !== undefined;
132
+
133
+ const isJobStillMine = (db, job) => db.prepare("SELECT 1 AS found FROM check_jobs WHERE id = ? AND status = 'running' AND worker_token = ?").get(job.id, job.worker_token) !== undefined;
134
+
135
+ /** A heartbeat that treats a busy db as "still alive, try again": only a lost lease (false) or a real error says otherwise. */
136
+ const beat = (db, token, now) => {
137
+ try {
138
+ return heartbeat(db, token, now);
139
+ } catch (error) {
140
+ if (isSqliteBusyError(error)) return true;
141
+ throw error;
142
+ }
143
+ };
144
+
145
+ const stillMine = (db, job) => {
146
+ try {
147
+ return isJobStillMine(db, job);
148
+ } catch (error) {
149
+ if (isSqliteBusyError(error)) return true;
150
+ throw error;
151
+ }
152
+ };
153
+
154
+ /**
155
+ * While a job runs: heartbeat the lease, and poll the row. A cancelled job (the row left 'running') or a lost lease
156
+ * aborts the controller, which stops the executor's process tree. Timer errors never escape (an uncaught one would
157
+ * kill the worker mid-job and leave its child running): they are kept in `failures` and the watcher keeps going.
158
+ */
159
+ const watchJob = (db, job, { token, clock, controller, heartbeatMs, cancelPollMs }) => {
160
+ const failures = [];
161
+ const guarded = (action) => () => {
162
+ try {
163
+ action();
164
+ } catch (error) {
165
+ failures.push(String(error?.message || error));
166
+ }
167
+ };
168
+ const checkLease = () => {
169
+ const hasLease = beat(db, token, clock());
170
+ if (!hasLease) controller.abort(LEASE_LOST);
171
+ };
172
+ const checkJob = () => {
173
+ const isMine = stillMine(db, job);
174
+ if (!isMine) controller.abort(CANCELLED);
175
+ };
176
+ const beatTimer = setInterval(guarded(checkLease), heartbeatMs);
177
+ const cancelTimer = setInterval(guarded(checkJob), cancelPollMs);
178
+ // Not unref'd: while a check runs, these timers are what keeps the worker alive and able to abort it. stop() clears them.
179
+ return { failures, stop: () => { clearInterval(beatTimer); clearInterval(cancelTimer); } };
180
+ };
181
+
182
+ const executeJob = async (executor, job, signal) => {
183
+ const started = Date.now();
184
+ try {
185
+ return await executor(job, { signal });
186
+ } catch (error) {
187
+ const wasAborted = signal.aborted;
188
+ const summaryLine = wasAborted ? 'the check was cancelled or its worker lost the lease' : String(error?.message || error);
189
+ return { status: 'inconclusive', reason: wasAborted ? 'aborted' : 'executor-error', summaryLine, faults: [], errorCount: 0, durationMs: Date.now() - started };
190
+ }
191
+ };
192
+
193
+ /** Delivery that never throws into the worker: whatever fails stays un-notified for the next sweep. */
194
+ const deliverSafely = (db, job, result, deliver) => {
195
+ try {
196
+ deliver(db, job, result);
197
+ return true;
198
+ } catch {
199
+ // chemx-allow: best-effort the requesters stay un-notified and the next sweep redelivers
200
+ return false;
201
+ }
202
+ };
203
+
204
+ const runOne = async (db, job, deps) => {
205
+ const { executor, deliver, clock, fingerprint, token, heartbeatMs, cancelPollMs } = deps;
206
+ const controller = new AbortController();
207
+ const watcher = watchJob(db, job, { token, clock, controller, heartbeatMs, cancelPollMs });
208
+ let startDeep = '';
209
+ let result;
210
+ try {
211
+ const startFp = fingerprint(job.cwd);
212
+ startDeep = fingerprint(job.cwd, { deep: true });
213
+ db.prepare('UPDATE check_jobs SET tree_fp = ?, tree_fp_deep = ? WHERE id = ?').run(startFp, startDeep, job.id);
214
+ const isCancelledAlready = !stillMine(db, job);
215
+ if (isCancelledAlready) controller.abort(CANCELLED);
216
+ result = controller.signal.aborted ? { status: 'inconclusive', reason: 'aborted', faults: [], errorCount: 0 } : await executeJob(executor, job, controller.signal);
217
+ } finally {
218
+ watcher.stop();
219
+ }
220
+ // A worker that lost the lease records nothing: the job is still 'running', so the new worker's recoverOrphans requeues it.
221
+ const hasLostLease = controller.signal.reason === LEASE_LOST;
222
+ if (hasLostLease) return;
223
+ const finishDeep = fingerprint(job.cwd, { deep: true });
224
+ const finished = { ...result, treeFpAtFinish: finishDeep, stale: finishDeep !== startDeep };
225
+ const isRecorded = finishJob(db, job, finished, clock());
226
+ if (isRecorded) deliverSafely(db, { ...job, tree_fp_deep: startDeep }, finished, deliver);
227
+ };
228
+
229
+ /**
230
+ * Runs the drain loop. Returns { exited: 'lease-held' | 'idle' | 'lease-lost' | 'once', ran }.
231
+ * Options: executor(job, { signal }) -> result, deliver(db, job, result), clock, sleep, fingerprint(cwd, { deep }), pid, token,
232
+ * isAlive, idleExitMs, once, heartbeatMs, cancelPollMs.
233
+ */
234
+ export const runDrainer = async (db, options = {}) => {
235
+ const { executor, deliver, clock = Date.now, sleep = delay, fingerprint = treeFingerprint, pid = process.pid, token = randomUUID(), isAlive = isPidAlive, idleExitMs = IDLE_EXIT_MS, once = false, heartbeatMs = HEARTBEAT_MS, cancelPollMs = CANCEL_POLL_MS } = options;
236
+ const deps = { executor, deliver, clock, fingerprint, token, heartbeatMs, cancelPollMs };
237
+ const hasLease = () => acquireLease(db, { pid, token, now: clock(), isAlive });
238
+ if (!hasLease()) return { exited: 'lease-held', ran: 0 };
239
+ try {
240
+ return await drainLoop(db, { deps, options: { sleep, idleExitMs, once, pid }, hasLease });
241
+ } finally {
242
+ // Whatever ended the loop (an error included), never leave a lease nobody works under.
243
+ releaseLeaseSafely(db, token);
244
+ }
245
+ };
246
+
247
+ const releaseLeaseSafely = (db, token) => {
248
+ try {
249
+ releaseLease(db, token);
250
+ } catch (error) {
251
+ // A busy db leaves the lease to go stale (LEASE_STALE_MS); anything else is a real fault.
252
+ if (!isSqliteBusyError(error)) throw error;
253
+ }
254
+ };
255
+
256
+ const drainLoop = async (db, { deps, options, hasLease }) => {
257
+ const { clock, token, deliver } = deps;
258
+ const { sleep, idleExitMs, once, pid } = options;
259
+ recoverOrphans(db, clock());
260
+ redeliverUnnotified(db, deliver);
261
+ let ran = 0;
262
+ let idleSince = clock();
263
+ for (;;) {
264
+ const job = claimNext(db, { token, pid, now: clock() });
265
+ if (job) {
266
+ await runOne(db, job, deps);
267
+ ran += 1;
268
+ idleSince = clock();
269
+ const isStillMine = beat(db, token, clock());
270
+ if (!isStillMine) return { exited: 'lease-lost', ran };
271
+ continue;
272
+ }
273
+ if (once) return { exited: 'once', ran };
274
+ const isIdleLongEnough = clock() - idleSince >= idleExitMs;
275
+ if (!isIdleLongEnough) {
276
+ const isLeaseKept = beat(db, token, clock());
277
+ if (!isLeaseKept) return { exited: 'lease-lost', ran };
278
+ await sleep(POLL_MS);
279
+ continue;
280
+ }
281
+ redeliverUnnotified(db, deliver);
282
+ // Close the enqueue race: an enqueuer that saw a live lease did not spawn, so look once more after releasing it.
283
+ releaseLease(db, token);
284
+ if (!hasQueued(db)) return { exited: 'idle', ran };
285
+ if (!hasLease()) return { exited: 'lease-held', ran };
286
+ idleSince = clock();
287
+ }
288
+ };
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The drain worker's default executor: runs a queued check through the existing audit for its kind
3
+ * (runTypecheckAudit, runTestAudit, runProjectVerify, runBuildAudit). Those go through runInLine, so the job line
4
+ * stays the one-heavy-at-a-time arbiter. Modules load lazily: enqueueing never pays for them.
5
+ *
6
+ * Cancellation: the worker hands the executor an AbortSignal. It is installed as the request signal
7
+ * (request-context.js), which executeBuild honours by killing the check's whole process group, and which the
8
+ * job line honours while the check waits for its turn. Aborting therefore stops the real typecheck, test or build.
9
+ */
10
+
11
+ import { runWithRequestContext } from '../request-context.js';
12
+
13
+ const MAX_COLLECTED = 200;
14
+ const MAX_DEPTH = 4;
15
+ const MAX_DETAIL_CHARS = 300;
16
+
17
+ const detailsOf = (item) => (Array.isArray(item?.details) ? item.details.map(String).join(' ').slice(0, MAX_DETAIL_CHARS) : '');
18
+
19
+ /** One fault as { file, line, code, message }. A failed test ({ name, details[] }) keeps its name as the location and its details as the message. */
20
+ const asFault = (item, prefix = '') => {
21
+ const rawFile = String(item?.file || item?.path || item?.name || '');
22
+ const isPrefixed = prefix !== '' && rawFile !== '' && item?.name !== rawFile;
23
+ return {
24
+ file: isPrefixed ? `${prefix}/${rawFile}` : rawFile,
25
+ line: Number(item?.line || 0),
26
+ code: String(item?.code || item?.rule || ''),
27
+ message: String(item?.message || item?.error || item?.title || detailsOf(item) || (typeof item === 'string' ? item : ''))
28
+ };
29
+ };
30
+
31
+ const FAULT_LISTS = ['errors', 'failures', 'failedTests'];
32
+ const SECTIONS = ['typecheck', 'tests', 'build', 'audit'];
33
+
34
+ const isErrorDiagnostic = (item) => item?.severity === undefined || item.severity === 'error';
35
+
36
+ const listOf = (report, key) => (Array.isArray(report[key]) ? report[key] : []);
37
+
38
+ const packagePrefix = (entry) => (entry?.dir && entry.dir !== '.' ? String(entry.dir) : '');
39
+
40
+ /**
41
+ * Every fault a report carries, flattened. Besides a report's own lists it descends into a verify summary's
42
+ * sections and into a workspace report's `packages` (each a full report; its faults get the package dir as a path prefix).
43
+ */
44
+ export const collectFaults = (report, depth = 0, prefix = '') => {
45
+ const faults = [];
46
+ const isObject = report !== null && typeof report === 'object';
47
+ const isSkipped = !isObject || depth > MAX_DEPTH;
48
+ if (isSkipped) return faults;
49
+ for (const key of FAULT_LISTS) faults.push(...listOf(report, key).map((item) => asFault(item, prefix)));
50
+ faults.push(...listOf(report, 'diagnostics').filter(isErrorDiagnostic).map((item) => asFault(item, prefix)));
51
+ for (const section of SECTIONS) faults.push(...collectFaults(report[section], depth + 1, prefix));
52
+ for (const entry of listOf(report, 'packages')) faults.push(...collectFaults(entry, depth + 1, packagePrefix(entry) || prefix));
53
+ return faults.slice(0, MAX_COLLECTED);
54
+ };
55
+
56
+ const numberOf = (report) => Number(report?.errorCount ?? report?.totalErrors ?? report?.failed);
57
+
58
+ /** The report's own fault count, summed over workspace packages and verify sections when it carries none itself. */
59
+ const countOf = (report, depth = 0) => {
60
+ const isObject = report !== null && typeof report === 'object';
61
+ const isSkipped = !isObject || depth > MAX_DEPTH;
62
+ const own = isSkipped ? 0 : numberOf(report);
63
+ const hasOwnCount = own > 0;
64
+ const children = isSkipped ? [] : [...listOf(report, 'packages'), ...SECTIONS.map((key) => report[key])];
65
+ return hasOwnCount ? own : children.reduce((sum, child) => sum + countOf(child, depth + 1), 0);
66
+ };
67
+
68
+ const messageOf = (report) => String(report?.executionError || report?.error || report?.detail || '');
69
+
70
+ /** The first reason any workspace package or verify section gives, since the top-level report of a workspace run has none. */
71
+ const summaryOf = (report) => {
72
+ const own = messageOf(report);
73
+ if (own) return own;
74
+ const children = [...listOf(report, 'packages'), ...SECTIONS.map((key) => report?.[key])];
75
+ const reason = children.map((child) => ({ child, text: messageOf(child) })).find((entry) => entry.text);
76
+ if (!reason) return '';
77
+ const name = reason.child.package || reason.child.dir || '';
78
+ return name ? `${name}: ${reason.text}` : reason.text;
79
+ };
80
+
81
+ export const toCheckResult = (report, startedAt) => {
82
+ const faults = collectFaults(report);
83
+ const status = ['pass', 'fail', 'inconclusive'].includes(report?.status) ? report.status : 'inconclusive';
84
+ const count = Math.max(countOf(report), faults.length);
85
+ return { status, exitCode: report?.exitCode ?? null, durationMs: Date.now() - startedAt, errorCount: count, faults: faults.slice(0, 25), more: Math.max(0, count - 25), summaryLine: summaryOf(report) };
86
+ };
87
+
88
+ const loadRunners = async () => {
89
+ const [{ runTypecheckAudit }, { runTestAudit }, { runProjectVerify }, { runBuildAudit }] = await Promise.all([
90
+ import('../typecheck-audit.js'), import('../test-audit.js'), import('../verify.js'), import('../build.js')
91
+ ]);
92
+ return { typecheck: runTypecheckAudit, test: runTestAudit, verify: runProjectVerify, build: runBuildAudit };
93
+ };
94
+
95
+ /**
96
+ * @param runners optional { kind: (args, isCli, options) => report } override (specs inject it).
97
+ * The returned executor is (job, { signal }) => result; aborting `signal` kills the check's process tree.
98
+ */
99
+ export const createCheckExecutor = (runners = null) => async (job, { signal = null } = {}) => {
100
+ const startedAt = Date.now();
101
+ const table = runners || await loadRunners();
102
+ const run = table[job.kind];
103
+ if (!run) return { status: 'inconclusive', summaryLine: `unknown check kind: ${job.kind}`, faults: [], errorCount: 0, durationMs: 0 };
104
+ const report = await runWithRequestContext({ signal }, () => run(['--json'], false, { cwd: job.cwd, print: false, json: true }));
105
+ return toCheckResult(report, startedAt);
106
+ };
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The working-tree fingerprint the check queue keys its cache, its join of a running job and its stale
3
+ * flag on. Two depths, because the cost differs by an order of magnitude in a monorepo of submodules
4
+ * (measured in the elysium root: shallow about 80 to 125 ms on a busy shared tree, deep about 1.5 s):
5
+ * - shallow (the enqueue path): HEAD plus every changed or untracked path of the repo that holds cwd, with
6
+ * its size and mtime, plus the commit each flagged submodule points at. Two cheap git calls.
7
+ * - deep (the drain worker, and the verification of a cache or join candidate): shallow plus the same
8
+ * state for every submodule's own working tree, recursively, so an edit inside a dirty submodule shows.
9
+ * Paths are resolved against the repo toplevel (git status prints them relative to it, whatever cwd is).
10
+ * '' means git could not say, and callers treat that as "never cache, never join".
11
+ */
12
+
13
+ import { execFileSync } from 'node:child_process';
14
+ import { createHash } from 'node:crypto';
15
+ import { existsSync, statSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+
18
+ const GITLINK_MODE = '160000';
19
+ const MAX_SUBMODULE_DEPTH = 4;
20
+ const STATUS_ARGS = ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=dirty'];
21
+
22
+ const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
23
+
24
+ const hasOrigin = (code) => /[RC]/.test(code);
25
+
26
+ /** Parses `git status --porcelain=v1 -z`: a rename or copy record is followed by its origin path as a record of its own. */
27
+ export const parseStatusZ = (text) => {
28
+ const records = text.split('\0');
29
+ const entries = [];
30
+ for (let index = 0; index < records.length; index += 1) {
31
+ const record = records[index];
32
+ const isEntry = record.length >= 4;
33
+ if (!isEntry) continue;
34
+ const code = record.slice(0, 2);
35
+ entries.push({ code, path: record.slice(3) });
36
+ if (!hasOrigin(code)) continue;
37
+ index += 1;
38
+ const origin = records[index];
39
+ if (origin) entries.push({ code: 'origin', path: origin });
40
+ }
41
+ return entries;
42
+ };
43
+
44
+ const headOf = (dir) => {
45
+ try {
46
+ return git(dir, ['rev-parse', 'HEAD']).trim();
47
+ } catch {
48
+ return 'no-head';
49
+ }
50
+ };
51
+
52
+ const stampOf = (top, { code, path }) => {
53
+ try {
54
+ const stats = statSync(join(top, path));
55
+ // A directory here is a submodule whose commit moved: its own HEAD says which commit.
56
+ if (stats.isDirectory()) return `${code}:${path}:dir:${headOf(join(top, path))}`;
57
+ return `${code}:${path}:${stats.size}:${Math.floor(stats.mtimeMs)}`;
58
+ } catch {
59
+ return `${code}:${path}:gone`;
60
+ }
61
+ };
62
+
63
+ const gitlinkPaths = (top) => git(top, ['ls-files', '--stage', '-z']).split('\0').filter((line) => line.startsWith(GITLINK_MODE)).map((line) => line.slice(line.indexOf('\t') + 1));
64
+
65
+ const changesOf = (top) => parseStatusZ(git(top, STATUS_ARGS)).sort((a, b) => a.path.localeCompare(b.path) || a.code.localeCompare(b.code)).map((entry) => stampOf(top, entry));
66
+
67
+ // One git call per submodule: its HEAD is already pinned by the parent (an unflagged submodule sits at the
68
+ // index's gitlink, a moved one is stamped by stampOf), so only its own changed and untracked files are read.
69
+ // A directory with no .git entry is an uninitialized submodule; git run there would report the parent repo.
70
+ const submodulesOf = (top, depth) => {
71
+ const parts = [];
72
+ const isNested = depth > 0;
73
+ const hasSubmodules = !isNested || existsSync(join(top, '.gitmodules'));
74
+ const isTooDeep = depth >= MAX_SUBMODULE_DEPTH;
75
+ const hasNothingToVisit = !hasSubmodules || isTooDeep;
76
+ if (hasNothingToVisit) return parts;
77
+ for (const path of gitlinkPaths(top).sort()) {
78
+ const dir = join(top, path);
79
+ const isInitialized = existsSync(join(dir, '.git'));
80
+ if (!isInitialized) {
81
+ parts.push(`sub:${path}:uninitialized`);
82
+ continue;
83
+ }
84
+ try {
85
+ parts.push(`sub:${path}`, ...changesOf(dir), ...submodulesOf(dir, depth + 1));
86
+ } catch {
87
+ parts.push(`sub:${path}:unreadable`);
88
+ }
89
+ }
90
+ return parts;
91
+ };
92
+
93
+ const stateOf = (cwd, isDeep) => {
94
+ const [top, head] = git(cwd, ['rev-parse', '--show-toplevel', 'HEAD']).trim().split('\n');
95
+ return [head, ...changesOf(top), ...(isDeep ? submodulesOf(top, 0) : [])];
96
+ };
97
+
98
+ /** A hash of the working tree's state; see the file header for what shallow and deep cover. '' when git cannot say. */
99
+ export const treeFingerprint = (cwd, { deep = false } = {}) => {
100
+ try {
101
+ return createHash('sha1').update(stateOf(cwd, deep).join('\n')).digest('hex').slice(0, 16);
102
+ } catch {
103
+ return '';
104
+ }
105
+ };