@bonesofspring/ai-rules 0.2.52 → 0.2.53

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 (134) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +27 -3
  3. package/bin/cli.js +551 -60
  4. package/bin/lib/engine-scripts.js +10 -0
  5. package/bin/lib/mcp/clients.js +168 -0
  6. package/bin/lib/mcp/credentials.js +298 -0
  7. package/bin/lib/mcp/doctor.js +394 -0
  8. package/bin/lib/mcp/prompt.js +115 -0
  9. package/bin/lib/mcp/registry.js +170 -0
  10. package/bin/lib/mcp/run.js +123 -0
  11. package/bin/lib/merged-config.js +45 -0
  12. package/bin/lib/seed-ai-local-team.js +5 -0
  13. package/bin/lib/tool-installs.js +27 -0
  14. package/docs/MCP-SETUP.md +62 -0
  15. package/docs/PRESET-CONTRIBUTION.md +3 -1
  16. package/docs/TEAM-DB.md +173 -0
  17. package/docs/openapi/team-db.v1.json +5085 -0
  18. package/mcp/gitlab.mjs +123 -0
  19. package/mcp/lib/envfile.mjs +126 -0
  20. package/mcp/lib/yandex.mjs +384 -0
  21. package/mcp/yandex-mcp-proxy.mjs +155 -0
  22. package/mcp/yandex-token-refresh.mjs +65 -0
  23. package/package.json +14 -1
  24. package/presets/_shared/ai-local/scripts/manifest.mjs +99 -0
  25. package/presets/_shared/ai-local/scripts/team-db-api.mjs +1275 -0
  26. package/presets/_shared/ai-local/scripts/team-db-dashboard.mjs +1067 -0
  27. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +1301 -0
  28. package/presets/_shared/ai-local/scripts/team-db-project.mjs +1506 -0
  29. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +831 -0
  30. package/presets/_shared/ai-local/scripts/team-db.mjs +251 -0
  31. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +109 -0
  32. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +109 -0
  33. package/presets/claude/android-kotlin/team/README.md +10 -0
  34. package/presets/claude/go/hooks/chain-team-phases.sh +109 -0
  35. package/presets/claude/go/team/README.md +10 -0
  36. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +109 -0
  37. package/presets/claude/ios-swift/team/README.md +10 -0
  38. package/presets/claude/java/hooks/chain-team-phases.sh +109 -0
  39. package/presets/claude/java/team/README.md +10 -0
  40. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +109 -0
  41. package/presets/claude/mcp-ts/team/README.md +10 -0
  42. package/presets/claude/next/hooks/chain-team-phases.sh +109 -0
  43. package/presets/claude/next/team/README.md +10 -0
  44. package/presets/claude/nuxt/hooks/chain-team-phases.sh +109 -0
  45. package/presets/claude/nuxt/team/README.md +10 -0
  46. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  47. package/presets/claude/php-hexagonal/team/README.md +10 -0
  48. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +109 -0
  49. package/presets/claude/php-laravel/team/README.md +10 -0
  50. package/presets/claude/svelte/hooks/chain-team-phases.sh +109 -0
  51. package/presets/claude/svelte/team/README.md +10 -0
  52. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +109 -0
  53. package/presets/cursor/android-kotlin/team/README.md +10 -0
  54. package/presets/cursor/go/hooks/chain-team-phases.sh +109 -0
  55. package/presets/cursor/go/team/README.md +10 -0
  56. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +109 -0
  57. package/presets/cursor/ios-swift/team/README.md +10 -0
  58. package/presets/cursor/java/hooks/chain-team-phases.sh +109 -0
  59. package/presets/cursor/java/team/README.md +10 -0
  60. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +109 -0
  61. package/presets/cursor/mcp-ts/team/README.md +10 -0
  62. package/presets/cursor/next/MCP.md +7 -0
  63. package/presets/cursor/next/hooks/chain-team-phases.sh +109 -0
  64. package/presets/cursor/next/team/README.md +10 -0
  65. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +109 -0
  66. package/presets/cursor/nuxt/team/README.md +10 -0
  67. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  68. package/presets/cursor/php-hexagonal/team/README.md +10 -0
  69. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +109 -0
  70. package/presets/cursor/php-laravel/team/README.md +10 -0
  71. package/presets/cursor/svelte/hooks/chain-team-phases.sh +109 -0
  72. package/presets/cursor/svelte/team/README.md +10 -0
  73. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  74. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +109 -0
  75. package/presets/mavis/android-kotlin/team/README.md +10 -0
  76. package/presets/mavis/go/adapter-map.json +1 -1
  77. package/presets/mavis/go/hooks/chain-team-phases.sh +109 -0
  78. package/presets/mavis/go/team/README.md +10 -0
  79. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  80. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +109 -0
  81. package/presets/mavis/ios-swift/team/README.md +10 -0
  82. package/presets/mavis/java/adapter-map.json +1 -1
  83. package/presets/mavis/java/hooks/chain-team-phases.sh +109 -0
  84. package/presets/mavis/java/team/README.md +10 -0
  85. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  86. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +109 -0
  87. package/presets/mavis/mcp-ts/team/README.md +10 -0
  88. package/presets/mavis/next/MCP.md +7 -0
  89. package/presets/mavis/next/adapter-map.json +1 -1
  90. package/presets/mavis/next/hooks/chain-team-phases.sh +109 -0
  91. package/presets/mavis/next/team/README.md +10 -0
  92. package/presets/mavis/nuxt/adapter-map.json +1 -1
  93. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +109 -0
  94. package/presets/mavis/nuxt/team/README.md +10 -0
  95. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  96. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  97. package/presets/mavis/php-hexagonal/team/README.md +10 -0
  98. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  99. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +109 -0
  100. package/presets/mavis/php-laravel/team/README.md +10 -0
  101. package/presets/mavis/svelte/adapter-map.json +1 -1
  102. package/presets/mavis/svelte/hooks/chain-team-phases.sh +109 -0
  103. package/presets/mavis/svelte/team/README.md +10 -0
  104. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  105. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +109 -0
  106. package/presets/opencode/android-kotlin/team/README.md +10 -0
  107. package/presets/opencode/go/adapter-map.json +1 -1
  108. package/presets/opencode/go/hooks/chain-team-phases.sh +109 -0
  109. package/presets/opencode/go/team/README.md +10 -0
  110. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  111. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +109 -0
  112. package/presets/opencode/ios-swift/team/README.md +10 -0
  113. package/presets/opencode/java/adapter-map.json +1 -1
  114. package/presets/opencode/java/hooks/chain-team-phases.sh +109 -0
  115. package/presets/opencode/java/team/README.md +10 -0
  116. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  117. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +109 -0
  118. package/presets/opencode/mcp-ts/team/README.md +10 -0
  119. package/presets/opencode/next/MCP.md +7 -0
  120. package/presets/opencode/next/adapter-map.json +1 -1
  121. package/presets/opencode/next/hooks/chain-team-phases.sh +109 -0
  122. package/presets/opencode/next/team/README.md +10 -0
  123. package/presets/opencode/nuxt/adapter-map.json +1 -1
  124. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +109 -0
  125. package/presets/opencode/nuxt/team/README.md +10 -0
  126. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  127. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  128. package/presets/opencode/php-hexagonal/team/README.md +10 -0
  129. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  130. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +109 -0
  131. package/presets/opencode/php-laravel/team/README.md +10 -0
  132. package/presets/opencode/svelte/adapter-map.json +1 -1
  133. package/presets/opencode/svelte/hooks/chain-team-phases.sh +109 -0
  134. package/presets/opencode/svelte/team/README.md +10 -0
@@ -0,0 +1,1506 @@
1
+ /**
2
+ * Parsers and projector for the `.ai.local/team` SQLite projection.
3
+ *
4
+ * Files are authoritative. One task directory is one transaction: parse the
5
+ * known artifacts, upsert every normalized row by its natural key, store every
6
+ * regular file as a raw document, and rebuild the task's search rows. A
7
+ * malformed input is recorded and the rest of the tree still projects; a
8
+ * database-level failure aborts the run.
9
+ *
10
+ * Nothing here writes a lifecycle file. `status.json` and `metrics.json` are
11
+ * read-only inputs.
12
+ */
13
+
14
+ import crypto from 'node:crypto';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ import {
19
+ SEARCH_MODE_FTS5,
20
+ TeamDbError,
21
+ chmodDatabaseFiles,
22
+ integrityCheck,
23
+ isBusyError,
24
+ isCorruptError,
25
+ openTeamDb,
26
+ readSearchMode,
27
+ teamDbFail,
28
+ } from './team-db-schema.mjs';
29
+
30
+ export const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
31
+ export const MAX_RAW_BYTES = 32 * 1024 * 1024;
32
+ export const RETENTION_DAYS = 90;
33
+ export const SYNC_RUN_RETENTION = 200;
34
+ export const DEFAULT_SLUG_DEADLINE_MS = 4500;
35
+
36
+ const HASH_CHUNK = 64 * 1024;
37
+ const MAX_KNOWN_BYTES = 8 * 1024 * 1024;
38
+ const SKIP_FILE = /(?:^|\/)(?:\.manifest\.lock|[^/]*\.lock|[^/]*\.tmp)$/;
39
+ const SKIP_DIR = new Set(['node_modules', '.git']);
40
+
41
+ const KNOWN_FILES = {
42
+ status: 'status.json',
43
+ pipeline: 'pipeline.json',
44
+ metrics: 'metrics.json',
45
+ manifest: 'artifact-manifest.json',
46
+ prompt: 'prompt.md',
47
+ promptLog: 'prompt-log.md',
48
+ goal: 'goal.md',
49
+ brief: 'brief.md',
50
+ outcome: 'outcome.md',
51
+ reviewLedger: 'review-ledger.md',
52
+ memlog: '.memlog.md',
53
+ };
54
+
55
+ export const EVENT_TYPES = new Set([
56
+ 'task_started',
57
+ 'attempt_started',
58
+ 'attempt_finished',
59
+ 'retry_scheduled',
60
+ 'attempt_skipped',
61
+ 'human_gate_started',
62
+ 'human_gate_ended',
63
+ 'pipeline_parse_error',
64
+ 'task_completed',
65
+ 'parallel_wave_started',
66
+ 'step_joined',
67
+ 'parallel_attribution_repair',
68
+ 'parallel_conflict_deferred',
69
+ ]);
70
+
71
+ const TEXT_EXTENSIONS = new Set([
72
+ '.md',
73
+ '.mdc',
74
+ '.json',
75
+ '.jsonl',
76
+ '.txt',
77
+ '.text',
78
+ '.yml',
79
+ '.yaml',
80
+ '.toml',
81
+ '.mjs',
82
+ '.cjs',
83
+ '.js',
84
+ '.ts',
85
+ '.tsx',
86
+ '.jsx',
87
+ '.css',
88
+ '.html',
89
+ '.htm',
90
+ '.xml',
91
+ '.csv',
92
+ '.log',
93
+ '.sh',
94
+ '.sql',
95
+ '.patch',
96
+ '.diff',
97
+ '',
98
+ ]);
99
+
100
+ const MEDIA_TYPES = {
101
+ '.md': 'text/markdown',
102
+ '.mdc': 'text/markdown',
103
+ '.json': 'application/json',
104
+ '.jsonl': 'application/x-ndjson',
105
+ '.txt': 'text/plain',
106
+ '.text': 'text/plain',
107
+ '.yml': 'text/yaml',
108
+ '.yaml': 'text/yaml',
109
+ '.toml': 'text/plain',
110
+ '.mjs': 'text/javascript',
111
+ '.cjs': 'text/javascript',
112
+ '.js': 'text/javascript',
113
+ '.ts': 'text/plain',
114
+ '.tsx': 'text/plain',
115
+ '.jsx': 'text/plain',
116
+ '.css': 'text/css',
117
+ '.html': 'text/html',
118
+ '.htm': 'text/html',
119
+ '.xml': 'application/xml',
120
+ '.csv': 'text/csv',
121
+ '.log': 'text/plain',
122
+ '.sh': 'text/x-shellscript',
123
+ '.sql': 'text/plain',
124
+ '.patch': 'text/plain',
125
+ '.diff': 'text/plain',
126
+ };
127
+
128
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
129
+
130
+ const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
131
+
132
+ /**
133
+ * Canonical JSON: sorted keys at every depth, arrays preserved, `undefined`
134
+ * dropped, non-finite numbers rejected. Re-projection of equal input is
135
+ * byte-identical even when the source key order differs.
136
+ */
137
+ export function canonicalJson(value) {
138
+ const walk = (node) => {
139
+ if (node === null || typeof node !== 'object') {
140
+ if (typeof node === 'number' && !Number.isFinite(node)) {
141
+ throw new Error('canonical JSON cannot represent a non-finite number');
142
+ }
143
+ return node;
144
+ }
145
+ if (Array.isArray(node)) return node.map(walk);
146
+ const sorted = {};
147
+ for (const key of Object.keys(node).sort()) {
148
+ if (node[key] === undefined) continue;
149
+ sorted[key] = walk(node[key]);
150
+ }
151
+ return sorted;
152
+ };
153
+ const serialized = JSON.stringify(walk(value));
154
+ return serialized === undefined ? 'null' : serialized;
155
+ }
156
+
157
+ const isoTimestamp = (value) => {
158
+ if (typeof value !== 'string' || value.trim() === '') return null;
159
+ return Number.isNaN(Date.parse(value)) ? null : value;
160
+ };
161
+
162
+ const integerOrNull = (value) => {
163
+ if (value === null || value === undefined || value === '') return null;
164
+ const number = typeof value === 'number' ? value : Number(value);
165
+ return Number.isFinite(number) ? Math.trunc(number) : null;
166
+ };
167
+
168
+ const positiveDurationOrNull = (value) => {
169
+ const number = integerOrNull(value);
170
+ return number === null || number < 0 ? null : number;
171
+ };
172
+
173
+ const booleanFlag = (value) => (value === true || value === 1 || value === 'true' ? 1 : 0);
174
+
175
+ const firstHeading = (text) => {
176
+ if (typeof text !== 'string') return null;
177
+ const match = /^#\s+(.+)$/m.exec(text);
178
+ return match ? match[1].trim() : null;
179
+ };
180
+
181
+ const readTextFile = (filePath) => {
182
+ const stats = fs.statSync(filePath);
183
+ if (stats.size > MAX_KNOWN_BYTES) {
184
+ throw new Error(`file is ${stats.size} bytes, above the ${MAX_KNOWN_BYTES}-byte parse bound`);
185
+ }
186
+ return fs.readFileSync(filePath, 'utf8');
187
+ };
188
+
189
+ /* --------------------------------- parsers -------------------------------- */
190
+
191
+ export function parseStatusJson(text) {
192
+ const value = JSON.parse(text);
193
+ if (!isRecord(value)) throw new Error('top level must be an object');
194
+ return value;
195
+ }
196
+
197
+ export function parsePipelineJson(text) {
198
+ const value = JSON.parse(text);
199
+ if (!isRecord(value)) throw new Error('top level must be an object');
200
+ if (value.steps !== undefined && !Array.isArray(value.steps)) throw new Error('"steps" must be an array');
201
+ return value;
202
+ }
203
+
204
+ export function parseMetricsJson(text) {
205
+ const value = JSON.parse(text);
206
+ if (!isRecord(value)) throw new Error('top level must be an object');
207
+ if (!Array.isArray(value.events)) throw new Error('"events" must be an array');
208
+ return value;
209
+ }
210
+
211
+ export function parseArtifactManifestJson(text) {
212
+ const value = JSON.parse(text);
213
+ if (!isRecord(value)) throw new Error('top level must be an object');
214
+ if (!Array.isArray(value.artifacts)) throw new Error('"artifacts" must be an array');
215
+ return value;
216
+ }
217
+
218
+ const FENCE_RE = /```(?:text|markdown|md)?\r?\n([\s\S]*?)\r?\n```/;
219
+
220
+ const parsePromptMeta = (text) => {
221
+ const meta = {};
222
+ for (const line of text.split('\n')) {
223
+ const match = /^(?:-\s*)?([A-Za-z][\w-]*):\s*(.*)$/.exec(line.trim());
224
+ if (!match) continue;
225
+ if (!(match[1] in meta)) meta[match[1]] = match[2].trim();
226
+ }
227
+ return meta;
228
+ };
229
+
230
+ const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
231
+ const PROMPT_HEADING_RE = /^#\s+(?:Original prompt|Prompt)\s*\r?\n+/i;
232
+
233
+ /**
234
+ * Canonical `prompt.md` carries one fenced block. Files written before that
235
+ * shape (24 of this repository's 66) are a frontmatter block and/or a heading
236
+ * followed by plain text; those are valid legacy prompts, not parse failures.
237
+ * An opened fence without a closing fence is still an error.
238
+ */
239
+ export function parsePromptMarkdown(text) {
240
+ const match = FENCE_RE.exec(text);
241
+ const meta = parsePromptMeta(text);
242
+ if (match) return { content: match[1], meta, error: null };
243
+ if (/^```/m.test(text)) {
244
+ return { content: text, meta, error: 'unterminated prompt code fence; stored the whole file' };
245
+ }
246
+ let body = text;
247
+ const frontmatter = FRONTMATTER_RE.exec(body);
248
+ if (frontmatter) {
249
+ Object.assign(meta, parsePromptMeta(frontmatter[1]));
250
+ body = body.slice(frontmatter[0].length);
251
+ }
252
+ const heading = PROMPT_HEADING_RE.exec(body);
253
+ if (heading) body = body.slice(heading[0].length);
254
+ return { content: body.trim(), meta, error: null };
255
+ }
256
+
257
+ export function parsePromptLogMarkdown(text) {
258
+ // `## <n>` is a section only outside a fenced block: a prompt may itself
259
+ // contain a Markdown heading.
260
+ const sections = [];
261
+ let inFence = false;
262
+ let current = null;
263
+ for (const line of text.split('\n')) {
264
+ if (/^\s*```/.test(line)) inFence = !inFence;
265
+ const heading = !inFence ? /^##\s+(\d+)\s*$/.exec(line) : null;
266
+ if (heading) {
267
+ current = { label: Number(heading[1]), lines: [line] };
268
+ sections.push(current);
269
+ continue;
270
+ }
271
+ if (current) current.lines.push(line);
272
+ }
273
+ const entries = [];
274
+ const errors = [];
275
+ const seen = new Set();
276
+ sections.forEach((section) => {
277
+ const body = section.lines.join('\n');
278
+ const fence = FENCE_RE.exec(body);
279
+ if (!fence) {
280
+ errors.push(`entry ${section.label} has no fenced text block`);
281
+ return;
282
+ }
283
+ const meta = parsePromptMeta(body.slice(0, fence.index));
284
+ const seq = integerOrNull(meta.seq) ?? section.label;
285
+ if (seen.has(seq)) {
286
+ errors.push(`entry ${section.label} duplicates seq ${seq}`);
287
+ return;
288
+ }
289
+ seen.add(seq);
290
+ entries.push({
291
+ seq,
292
+ source: meta.source ?? null,
293
+ command: meta.command ?? null,
294
+ capturedAt: isoTimestamp(meta.capturedAt),
295
+ language: meta.language ?? null,
296
+ content: fence[1],
297
+ });
298
+ });
299
+ return { entries, errors };
300
+ }
301
+
302
+ export function parseOutcomeMarkdown(text) {
303
+ const goalAchieved = /^\*\*goalAchieved:\*\*\s*(.+)$/m.exec(text);
304
+ const value = /^\*\*value:\*\*\s*(.+)$/m.exec(text);
305
+ const counts = {};
306
+ const countsSection = /^##\s+Review counts\s*$/m.exec(text);
307
+ if (countsSection) {
308
+ const tail = text.slice(countsSection.index + countsSection[0].length);
309
+ for (const line of tail.split('\n')) {
310
+ const item = /^-\s*([A-Za-z]+):\s*(\d+)\s*$/.exec(line.trim());
311
+ if (item) counts[item[1]] = Number(item[2]);
312
+ if (/^##\s+/.test(line)) break;
313
+ }
314
+ }
315
+ return {
316
+ goalAchieved: goalAchieved ? goalAchieved[1].trim() : null,
317
+ value: value ? value[1].trim() : null,
318
+ reviewTotal: counts.total ?? null,
319
+ reviewFair: counts.fair ?? null,
320
+ reviewRejected: counts.rejected ?? null,
321
+ reviewOpen: counts.open ?? null,
322
+ reviewRework: counts.rework ?? null,
323
+ };
324
+ }
325
+
326
+ const splitTableRow = (line) => {
327
+ const trimmed = line.trim().replace(/^\|/, '').replace(/\|$/, '');
328
+ const cells = [];
329
+ let current = '';
330
+ for (let index = 0; index < trimmed.length; index += 1) {
331
+ const char = trimmed[index];
332
+ if (char === '\\' && trimmed[index + 1] === '|') {
333
+ current += '|';
334
+ index += 1;
335
+ continue;
336
+ }
337
+ if (char === '|') {
338
+ cells.push(current.trim());
339
+ current = '';
340
+ continue;
341
+ }
342
+ current += char;
343
+ }
344
+ cells.push(current.trim());
345
+ return cells;
346
+ };
347
+
348
+ /**
349
+ * The ledger is a fixed eight-column table. A summary cell may contain an
350
+ * unescaped pipe; overflow cells are folded back into the summary because the
351
+ * last four columns are structural.
352
+ */
353
+ export function parseReviewLedgerMarkdown(text) {
354
+ const lines = text.split('\n');
355
+ const headerIndex = lines.findIndex((line) => /^\|\s*id\s*\|/.test(line.trim()));
356
+ if (headerIndex === -1) return { rows: [], error: 'no ledger table header' };
357
+ const header = splitTableRow(lines[headerIndex]);
358
+ const rows = [];
359
+ const errors = [];
360
+ for (let index = headerIndex + 1; index < lines.length; index += 1) {
361
+ const line = lines[index].trim();
362
+ if (line === '' || !line.startsWith('|')) break;
363
+ if (/^\|[\s:|-]+\|$/.test(line)) continue;
364
+ const cells = splitTableRow(line);
365
+ if (cells.length < header.length) {
366
+ errors.push(`row ${index + 1} has ${cells.length} cells, expected ${header.length}`);
367
+ continue;
368
+ }
369
+ const compact =
370
+ cells.length > header.length
371
+ ? [
372
+ ...cells.slice(0, 3),
373
+ cells.slice(3, cells.length - (header.length - 4)).join(' | '),
374
+ ...cells.slice(cells.length - (header.length - 4)),
375
+ ]
376
+ : cells;
377
+ const [id, at, source, summary, fair, disposition, evidence, signature] = compact;
378
+ if (!id) {
379
+ errors.push(`row ${index + 1} has no id`);
380
+ continue;
381
+ }
382
+ rows.push({ id, at: isoTimestamp(at), source, summary, fair, disposition, evidence, signature });
383
+ }
384
+ return { rows, error: null, errors };
385
+ }
386
+
387
+ /* ------------------------------- projection ------------------------------- */
388
+
389
+ export function listTaskDirectories(teamRoot) {
390
+ const tasksDir = path.join(teamRoot, 'tasks');
391
+ if (!fs.existsSync(tasksDir)) return [];
392
+ return fs
393
+ .readdirSync(tasksDir, { withFileTypes: true })
394
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.') && SLUG_RE.test(entry.name))
395
+ .map((entry) => entry.name)
396
+ .sort();
397
+ }
398
+
399
+ const hashFile = (absolute) => {
400
+ const hash = crypto.createHash('sha256');
401
+ const fd = fs.openSync(absolute, 'r');
402
+ const buffer = Buffer.allocUnsafe(HASH_CHUNK);
403
+ try {
404
+ let read = 0;
405
+ while ((read = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) {
406
+ hash.update(buffer.subarray(0, read));
407
+ }
408
+ } finally {
409
+ fs.closeSync(fd);
410
+ }
411
+ return hash.digest('hex');
412
+ };
413
+
414
+ /**
415
+ * Walk one task directory, hashing every regular file. Symlinks, lock files,
416
+ * temp files, and `node_modules` are skipped. Returns per-task metadata only,
417
+ * never the whole tree.
418
+ */
419
+ export function walkTaskDirectory(taskDir, deadlineAt = Infinity) {
420
+ const files = [];
421
+ const walk = (directory, prefix) => {
422
+ const entries = fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
423
+ for (const entry of entries) {
424
+ if (Date.now() > deadlineAt) teamDbFail('E_DEADLINE', 'projection deadline expired', 4);
425
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
426
+ if (entry.isSymbolicLink()) continue;
427
+ if (entry.isDirectory()) {
428
+ if (SKIP_DIR.has(entry.name)) continue;
429
+ walk(path.join(directory, entry.name), relative);
430
+ continue;
431
+ }
432
+ if (!entry.isFile()) continue;
433
+ if (SKIP_FILE.test(relative)) continue;
434
+ const absolute = path.join(directory, entry.name);
435
+ try {
436
+ const stats = fs.statSync(absolute);
437
+ files.push({ path: relative, absolute, bytes: stats.size, sha256: hashFile(absolute), readError: null });
438
+ } catch (error) {
439
+ files.push({ path: relative, absolute, bytes: null, sha256: null, readError: error.message });
440
+ }
441
+ }
442
+ };
443
+ walk(taskDir, '');
444
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
445
+ return files;
446
+ }
447
+
448
+ const taskContentHash = (files) =>
449
+ sha256(files.map((file) => `${file.path}\0${file.sha256 ?? ''}\n`).join(''));
450
+
451
+ const mediaTypeFor = (relative) => MEDIA_TYPES[path.extname(relative).toLowerCase()] ?? 'application/octet-stream';
452
+
453
+ const isTextCandidate = (relative, buffer) => {
454
+ if (!TEXT_EXTENSIONS.has(path.extname(relative).toLowerCase())) return false;
455
+ const probe = buffer.subarray(0, Math.min(buffer.length, 8192));
456
+ return !probe.includes(0);
457
+ };
458
+
459
+ const readDocument = (file) => {
460
+ if (file.readError) {
461
+ return {
462
+ content: null,
463
+ contentOmitted: null,
464
+ isText: 0,
465
+ mediaType: mediaTypeFor(file.path),
466
+ parseError: `E_TASK_READ: ${file.readError}`,
467
+ };
468
+ }
469
+ const mediaType = mediaTypeFor(file.path);
470
+ if (file.bytes > MAX_RAW_BYTES) {
471
+ return { content: null, contentOmitted: 'size', isText: 0, mediaType, parseError: null };
472
+ }
473
+ const buffer = fs.readFileSync(file.absolute);
474
+ if (!isTextCandidate(file.path, buffer)) {
475
+ return { content: null, contentOmitted: 'binary', isText: 0, mediaType, parseError: null };
476
+ }
477
+ return { content: buffer.toString('utf8'), contentOmitted: null, isText: 1, mediaType, parseError: null };
478
+ };
479
+
480
+ const readKnown = (taskDir, name) => {
481
+ const absolute = path.join(taskDir, name);
482
+ if (!fs.existsSync(absolute)) return { exists: false, text: null, error: null };
483
+ try {
484
+ return { exists: true, text: readTextFile(absolute), error: null };
485
+ } catch (error) {
486
+ return { exists: true, text: null, error: error.message };
487
+ }
488
+ };
489
+
490
+ const parseKnown = (taskDir, slug) => {
491
+ const result = {
492
+ status: null,
493
+ pipeline: null,
494
+ metrics: null,
495
+ manifest: null,
496
+ prompt: null,
497
+ promptLog: null,
498
+ goal: null,
499
+ brief: null,
500
+ outcome: null,
501
+ reviewLedger: null,
502
+ memlog: null,
503
+ errors: [],
504
+ };
505
+ const record = (key, parse) => {
506
+ const known = readKnown(taskDir, KNOWN_FILES[key]);
507
+ result[`${key}Exists`] = known.exists;
508
+ if (!known.exists) return;
509
+ if (known.error) {
510
+ result.errors.push({ path: `${slug}/${KNOWN_FILES[key]}`, reason: known.error });
511
+ return;
512
+ }
513
+ try {
514
+ result[key] = parse(known.text);
515
+ } catch (error) {
516
+ result.errors.push({ path: `${slug}/${KNOWN_FILES[key]}`, reason: error.message });
517
+ }
518
+ };
519
+ record('status', parseStatusJson);
520
+ record('pipeline', parsePipelineJson);
521
+ record('metrics', parseMetricsJson);
522
+ record('manifest', parseArtifactManifestJson);
523
+ record('goal', (text) => ({ text, title: firstHeading(text) }));
524
+ record('brief', (text) => ({ text, title: firstHeading(text) }));
525
+ record('memlog', (text) => ({ text }));
526
+
527
+ // Prompts carry their own soft errors: a missing fence does not discard the text.
528
+ const promptKnown = readKnown(taskDir, KNOWN_FILES.prompt);
529
+ result.promptExists = promptKnown.exists;
530
+ if (promptKnown.exists) {
531
+ if (promptKnown.error) result.errors.push({ path: `${slug}/${KNOWN_FILES.prompt}`, reason: promptKnown.error });
532
+ else {
533
+ result.prompt = parsePromptMarkdown(promptKnown.text);
534
+ if (result.prompt.error) result.errors.push({ path: `${slug}/${KNOWN_FILES.prompt}`, reason: result.prompt.error });
535
+ }
536
+ }
537
+ const logKnown = readKnown(taskDir, KNOWN_FILES.promptLog);
538
+ result.promptLogExists = logKnown.exists;
539
+ if (logKnown.exists) {
540
+ if (logKnown.error) result.errors.push({ path: `${slug}/${KNOWN_FILES.promptLog}`, reason: logKnown.error });
541
+ else {
542
+ result.promptLog = parsePromptLogMarkdown(logKnown.text);
543
+ for (const message of result.promptLog.errors) {
544
+ result.errors.push({ path: `${slug}/${KNOWN_FILES.promptLog}`, reason: message });
545
+ }
546
+ }
547
+ }
548
+ const outcomeKnown = readKnown(taskDir, KNOWN_FILES.outcome);
549
+ result.outcomeExists = outcomeKnown.exists;
550
+ if (outcomeKnown.exists) {
551
+ if (outcomeKnown.error) result.errors.push({ path: `${slug}/${KNOWN_FILES.outcome}`, reason: outcomeKnown.error });
552
+ else {
553
+ try {
554
+ result.outcome = { ...parseOutcomeMarkdown(outcomeKnown.text), body: outcomeKnown.text };
555
+ } catch (error) {
556
+ result.errors.push({ path: `${slug}/${KNOWN_FILES.outcome}`, reason: error.message });
557
+ }
558
+ }
559
+ }
560
+ const ledgerKnown = readKnown(taskDir, KNOWN_FILES.reviewLedger);
561
+ result.reviewLedgerExists = ledgerKnown.exists;
562
+ if (ledgerKnown.exists) {
563
+ if (ledgerKnown.error) result.errors.push({ path: `${slug}/${KNOWN_FILES.reviewLedger}`, reason: ledgerKnown.error });
564
+ else {
565
+ const ledger = parseReviewLedgerMarkdown(ledgerKnown.text);
566
+ if (ledger.error) result.errors.push({ path: `${slug}/${KNOWN_FILES.reviewLedger}`, reason: ledger.error });
567
+ for (const message of ledger.errors ?? []) {
568
+ result.errors.push({ path: `${slug}/${KNOWN_FILES.reviewLedger}`, reason: message });
569
+ }
570
+ result.reviewLedger = ledger;
571
+ }
572
+ }
573
+ return result;
574
+ };
575
+
576
+ const normalizeEvent = (event, index, slug) => {
577
+ if (!isRecord(event)) {
578
+ return {
579
+ eventId: `${slug}:event:${index}`,
580
+ seq: index,
581
+ type: 'unknown',
582
+ at: null,
583
+ payloadJson: canonicalJson(event ?? null),
584
+ malformed: 'event is not an object',
585
+ };
586
+ }
587
+ const type = typeof event.type === 'string' && event.type !== '' ? event.type : 'unknown';
588
+ return {
589
+ eventId: typeof event.eventId === 'string' && event.eventId !== '' ? event.eventId : `${slug}:event:${index}`,
590
+ seq: index,
591
+ type,
592
+ at: isoTimestamp(event.at),
593
+ attemptId: typeof event.attemptId === 'string' ? event.attemptId : null,
594
+ stepIndex: integerOrNull(event.stepIndex),
595
+ stepLabel: typeof event.stepLabel === 'string' ? event.stepLabel : null,
596
+ agent: typeof event.agent === 'string' ? event.agent : null,
597
+ role: typeof event.role === 'string' ? event.role : null,
598
+ attemptNo: integerOrNull(event.attempt),
599
+ outcome: typeof event.outcome === 'string' ? event.outcome : null,
600
+ gateStartedEventId: typeof event.gateStartedEventId === 'string' ? event.gateStartedEventId : null,
601
+ waveId: typeof event.waveId === 'string' ? event.waveId : null,
602
+ parallelGroupId: typeof event.parallelGroupId === 'string' ? event.parallelGroupId : null,
603
+ durationMs: positiveDurationOrNull(event.durationMs),
604
+ source: typeof event.source === 'string' ? event.source : null,
605
+ attributionConfidence:
606
+ typeof event.attributionConfidence === 'string' ? event.attributionConfidence : null,
607
+ payloadJson: canonicalJson(event),
608
+ known: EVENT_TYPES.has(type),
609
+ malformed: null,
610
+ };
611
+ };
612
+
613
+ const attemptSuffix = (attemptId) => {
614
+ const match = /:attempt-(\d+)$/.exec(attemptId || '');
615
+ return match ? Number(match[1]) : null;
616
+ };
617
+
618
+ export function deriveAttempts(events, status) {
619
+ const attempts = new Map();
620
+ const ensure = (attemptId) => {
621
+ if (!attempts.has(attemptId)) {
622
+ attempts.set(attemptId, {
623
+ attemptId,
624
+ stepIndex: null,
625
+ stepLabel: null,
626
+ agent: null,
627
+ role: null,
628
+ attemptNo: attemptSuffix(attemptId),
629
+ waveId: null,
630
+ parallelGroupId: null,
631
+ startedAt: null,
632
+ finishedAt: null,
633
+ durationMs: null,
634
+ outcome: null,
635
+ source: 'metrics',
636
+ attributionConfidence: null,
637
+ isCurrent: 0,
638
+ });
639
+ }
640
+ return attempts.get(attemptId);
641
+ };
642
+ for (const event of events) {
643
+ if (!event.attemptId) continue;
644
+ const row = ensure(event.attemptId);
645
+ row.stepIndex = event.stepIndex ?? row.stepIndex;
646
+ row.stepLabel = event.stepLabel ?? row.stepLabel;
647
+ row.agent = event.agent ?? row.agent;
648
+ row.role = event.role ?? row.role;
649
+ row.attemptNo = event.attemptNo ?? row.attemptNo;
650
+ row.waveId = event.waveId ?? row.waveId;
651
+ row.parallelGroupId = event.parallelGroupId ?? row.parallelGroupId;
652
+ row.source = event.source ?? row.source;
653
+ row.attributionConfidence = event.attributionConfidence ?? row.attributionConfidence;
654
+ if (event.type === 'attempt_started') {
655
+ row.startedAt = event.at ?? row.startedAt;
656
+ } else if (event.type === 'attempt_finished') {
657
+ row.finishedAt = event.at ?? row.finishedAt;
658
+ row.durationMs = event.durationMs ?? row.durationMs;
659
+ row.outcome = event.outcome ?? row.outcome;
660
+ } else if (event.type === 'attempt_skipped') {
661
+ row.outcome = 'skipped';
662
+ }
663
+ }
664
+ const active = isRecord(status?.activeAttempts) ? status.activeAttempts : {};
665
+ for (const [attemptId, value] of Object.entries(active)) {
666
+ const row = ensure(attemptId);
667
+ row.isCurrent = 1;
668
+ if (!isRecord(value)) continue;
669
+ row.stepIndex = integerOrNull(value.stepIndex) ?? row.stepIndex;
670
+ row.agent = typeof value.agent === 'string' ? value.agent : row.agent;
671
+ row.attemptNo = integerOrNull(value.attempt) ?? row.attemptNo;
672
+ row.waveId = typeof value.waveId === 'string' ? value.waveId : row.waveId;
673
+ row.parallelGroupId = typeof value.parallelGroupId === 'string' ? value.parallelGroupId : row.parallelGroupId;
674
+ row.startedAt = isoTimestamp(value.startedAt) ?? row.startedAt;
675
+ row.source = row.startedAt && !row.finishedAt ? 'status' : row.source;
676
+ }
677
+ return [...attempts.values()];
678
+ }
679
+
680
+ export function deriveGates(events) {
681
+ const gates = new Map();
682
+ for (const event of events) {
683
+ if (event.type === 'human_gate_started') {
684
+ gates.set(event.eventId, {
685
+ startEventId: event.eventId,
686
+ startedAt: event.at,
687
+ endEventId: null,
688
+ endedAt: null,
689
+ durationMs: null,
690
+ });
691
+ }
692
+ }
693
+ for (const event of events) {
694
+ if (event.type !== 'human_gate_ended') continue;
695
+ const gate = event.gateStartedEventId ? gates.get(event.gateStartedEventId) : null;
696
+ if (!gate) continue;
697
+ gate.endEventId = event.eventId;
698
+ gate.endedAt = event.at;
699
+ if (gate.startedAt && gate.endedAt) {
700
+ const duration = Date.parse(gate.endedAt) - Date.parse(gate.startedAt);
701
+ gate.durationMs = Number.isFinite(duration) && duration >= 0 ? duration : null;
702
+ }
703
+ }
704
+ return [...gates.values()];
705
+ }
706
+
707
+ const deriveTaskTimes = (events) => {
708
+ let startAt = null;
709
+ let endAt = null;
710
+ for (const event of events) {
711
+ if (event.type === 'task_started' && event.at && !startAt) startAt = event.at;
712
+ if (event.type === 'task_completed' && event.at) endAt = event.at;
713
+ }
714
+ return { startAt, endAt };
715
+ };
716
+
717
+ const pipelineAgents = (step) => {
718
+ if (Array.isArray(step.agent)) return step.agent.filter((agent) => typeof agent === 'string' && agent !== '');
719
+ return typeof step.agent === 'string' && step.agent !== '' ? [step.agent] : [];
720
+ };
721
+
722
+ const normalizePipeline = (pipeline) => {
723
+ const steps = Array.isArray(pipeline.steps) ? pipeline.steps : [];
724
+ return {
725
+ values: {
726
+ intent: typeof pipeline.intent === 'string' ? pipeline.intent : null,
727
+ profile: typeof pipeline.profile === 'string' ? pipeline.profile : null,
728
+ specMode: typeof pipeline.specMode === 'string' ? pipeline.specMode : null,
729
+ complexity:
730
+ typeof pipeline.routingDecision?.complexity === 'string' ? pipeline.routingDecision.complexity : null,
731
+ routingSummary: typeof pipeline.summary === 'string' ? pipeline.summary : null,
732
+ routingJson: isRecord(pipeline.routingDecision) ? canonicalJson(pipeline.routingDecision) : null,
733
+ contextBudget: typeof pipeline.contextBudget === 'string' ? pipeline.contextBudget : null,
734
+ planRevision:
735
+ pipeline.planRevision === undefined || pipeline.planRevision === null
736
+ ? null
737
+ : String(pipeline.planRevision),
738
+ stepCount: steps.length,
739
+ },
740
+ steps: steps.map((rawStep, index) => {
741
+ const step = isRecord(rawStep) ? rawStep : {};
742
+ return {
743
+ stepIndex: index,
744
+ label: typeof step.label === 'string' ? step.label : null,
745
+ scope: typeof step.scope === 'string' ? step.scope : null,
746
+ model: typeof step.model === 'string' ? step.model : null,
747
+ skipIf: typeof step.skipIf === 'string' ? step.skipIf : typeof step.skip_if === 'string' ? step.skip_if : null,
748
+ parallel: booleanFlag(step.parallel),
749
+ dependsOnJson: step.dependsOn === undefined ? null : canonicalJson(step.dependsOn),
750
+ taskIdsJson: step.taskIds === undefined ? null : canonicalJson(step.taskIds),
751
+ writeScopesJson: step.writeScopes === undefined ? null : canonicalJson(step.writeScopes),
752
+ agents: pipelineAgents(step),
753
+ };
754
+ }),
755
+ };
756
+ };
757
+
758
+ const normalizeArtifacts = (manifest) => {
759
+ const artifacts = [];
760
+ const skipped = [];
761
+ const seen = new Set();
762
+ for (const [index, entry] of (manifest.artifacts ?? []).entries()) {
763
+ if (!isRecord(entry) || typeof entry.id !== 'string' || entry.id === '') {
764
+ skipped.push(`artifacts[${index}] has no id`);
765
+ continue;
766
+ }
767
+ if (seen.has(entry.id)) {
768
+ skipped.push(`artifacts[${index}] duplicates id "${entry.id}"`);
769
+ continue;
770
+ }
771
+ seen.add(entry.id);
772
+ const receipt = isRecord(entry.receipt) ? entry.receipt : {};
773
+ const timestamps = isRecord(entry.timestamps) ? entry.timestamps : {};
774
+ artifacts.push({
775
+ artifactId: entry.id,
776
+ producer: typeof entry.producer === 'string' ? entry.producer : null,
777
+ status: typeof entry.status === 'string' ? entry.status : null,
778
+ outcome: typeof receipt.outcome === 'string' ? receipt.outcome : null,
779
+ summary: typeof receipt.summary === 'string' ? receipt.summary : typeof entry.summary === 'string' ? entry.summary : null,
780
+ receiptAttemptId:
781
+ typeof receipt.attemptId === 'string'
782
+ ? receipt.attemptId
783
+ : typeof entry.attemptId === 'string'
784
+ ? entry.attemptId
785
+ : null,
786
+ createdAt: isoTimestamp(timestamps.createdAt),
787
+ updatedAt: isoTimestamp(timestamps.updatedAt),
788
+ completedAt: isoTimestamp(timestamps.completedAt),
789
+ acIdsJson: canonicalJson(Array.isArray(entry.acceptanceCriteriaIds) ? entry.acceptanceCriteriaIds : []),
790
+ taskIdsJson: canonicalJson(Array.isArray(entry.taskIds) ? entry.taskIds : []),
791
+ authoritative: (Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths : []).filter(
792
+ (value) => typeof value === 'string' && value !== '',
793
+ ),
794
+ evidence: (Array.isArray(receipt.evidencePaths) ? receipt.evidencePaths : []).filter(
795
+ (value) => typeof value === 'string' && value !== '',
796
+ ),
797
+ });
798
+ }
799
+ return { artifacts, skipped };
800
+ };
801
+
802
+ const taskTitle = (parsed, slug) =>
803
+ parsed.goal?.title || parsed.brief?.title || parsed.status?.slug || slug;
804
+
805
+ const eventRows = (metrics, slug) =>
806
+ (metrics.events ?? []).map((event, index) => normalizeEvent(event, index, slug));
807
+
808
+ const UPSERT_TASK_SQL = `
809
+ INSERT INTO tasks (
810
+ slug, title, intent, profile, spec_mode, complexity, phase, state, pipeline_index,
811
+ current_agent, awaiting_human_gate, metrics_run_id, routing_summary, routing_json,
812
+ context_budget, plan_revision, step_count, start_at, end_at, updated_at,
813
+ projected_at, last_seen_at, content_hash, file_count, document_bytes,
814
+ parse_error_count, first_seen_at, absent_at
815
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
816
+ ON CONFLICT(slug) DO UPDATE SET
817
+ title = COALESCE(excluded.title, tasks.title),
818
+ intent = COALESCE(excluded.intent, tasks.intent),
819
+ profile = COALESCE(excluded.profile, tasks.profile),
820
+ spec_mode = COALESCE(excluded.spec_mode, tasks.spec_mode),
821
+ complexity = COALESCE(excluded.complexity, tasks.complexity),
822
+ phase = COALESCE(excluded.phase, tasks.phase),
823
+ state = COALESCE(excluded.state, tasks.state),
824
+ pipeline_index = COALESCE(excluded.pipeline_index, tasks.pipeline_index),
825
+ current_agent = COALESCE(excluded.current_agent, tasks.current_agent),
826
+ awaiting_human_gate = CASE WHEN ? THEN excluded.awaiting_human_gate ELSE tasks.awaiting_human_gate END,
827
+ metrics_run_id = COALESCE(excluded.metrics_run_id, tasks.metrics_run_id),
828
+ routing_summary = COALESCE(excluded.routing_summary, tasks.routing_summary),
829
+ routing_json = COALESCE(excluded.routing_json, tasks.routing_json),
830
+ context_budget = COALESCE(excluded.context_budget, tasks.context_budget),
831
+ plan_revision = COALESCE(excluded.plan_revision, tasks.plan_revision),
832
+ step_count = COALESCE(excluded.step_count, tasks.step_count),
833
+ start_at = COALESCE(excluded.start_at, tasks.start_at),
834
+ end_at = COALESCE(excluded.end_at, tasks.end_at),
835
+ updated_at = COALESCE(excluded.updated_at, tasks.updated_at),
836
+ projected_at = excluded.projected_at,
837
+ last_seen_at = excluded.last_seen_at,
838
+ content_hash = excluded.content_hash,
839
+ file_count = excluded.file_count,
840
+ document_bytes = excluded.document_bytes,
841
+ parse_error_count = excluded.parse_error_count,
842
+ absent_at = NULL
843
+ `;
844
+
845
+ const upsertTask = (db, row) => {
846
+ db.prepare(UPSERT_TASK_SQL).run(
847
+ row.slug,
848
+ row.title,
849
+ row.intent,
850
+ row.profile,
851
+ row.specMode,
852
+ row.complexity,
853
+ row.phase,
854
+ row.state,
855
+ row.pipelineIndex,
856
+ row.currentAgent,
857
+ row.awaitingHumanGate,
858
+ row.metricsRunId,
859
+ row.routingSummary,
860
+ row.routingJson,
861
+ row.contextBudget,
862
+ row.planRevision,
863
+ row.stepCount,
864
+ row.startAt,
865
+ row.endAt,
866
+ row.updatedAt,
867
+ row.projectedAt,
868
+ row.lastSeenAt,
869
+ row.contentHash,
870
+ row.fileCount,
871
+ row.documentBytes,
872
+ row.parseErrorCount,
873
+ row.firstSeenAt,
874
+ row.statusParsed,
875
+ );
876
+ };
877
+
878
+ const replacePipeline = (db, slug, pipeline) => {
879
+ db.prepare('DELETE FROM pipeline_steps WHERE task_slug = ?').run(slug);
880
+ const stepStatement = db.prepare(
881
+ `INSERT INTO pipeline_steps(
882
+ task_slug, step_index, label, scope, model, skip_if, parallel,
883
+ depends_on_json, task_ids_json, write_scopes_json
884
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
885
+ );
886
+ const agentStatement = db.prepare(
887
+ 'INSERT INTO pipeline_step_agents(task_slug, step_index, ordinal, agent) VALUES (?, ?, ?, ?)',
888
+ );
889
+ for (const step of pipeline.steps) {
890
+ stepStatement.run(
891
+ slug,
892
+ step.stepIndex,
893
+ step.label,
894
+ step.scope,
895
+ step.model,
896
+ step.skipIf,
897
+ step.parallel,
898
+ step.dependsOnJson,
899
+ step.taskIdsJson,
900
+ step.writeScopesJson,
901
+ );
902
+ step.agents.forEach((agent, ordinal) => {
903
+ agentStatement.run(slug, step.stepIndex, ordinal, agent);
904
+ });
905
+ }
906
+ };
907
+
908
+ const replaceEvents = (db, slug, events) => {
909
+ db.prepare('DELETE FROM events WHERE task_slug = ?').run(slug);
910
+ const statement = db.prepare(
911
+ `INSERT OR IGNORE INTO events(
912
+ event_id, task_slug, seq, type, at, attempt_id, step_index, step_label, agent, role,
913
+ attempt_no, outcome, gate_started_event_id, wave_id, parallel_group_id, duration_ms,
914
+ source, attribution_confidence, payload_json
915
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
916
+ );
917
+ for (const event of events) {
918
+ statement.run(
919
+ event.eventId,
920
+ slug,
921
+ event.seq,
922
+ event.type,
923
+ event.at,
924
+ event.attemptId,
925
+ event.stepIndex,
926
+ event.stepLabel,
927
+ event.agent,
928
+ event.role,
929
+ event.attemptNo,
930
+ event.outcome,
931
+ event.gateStartedEventId,
932
+ event.waveId,
933
+ event.parallelGroupId,
934
+ event.durationMs,
935
+ event.source,
936
+ event.attributionConfidence,
937
+ event.payloadJson,
938
+ );
939
+ }
940
+ };
941
+
942
+ const replaceAttempts = (db, slug, attempts) => {
943
+ db.prepare('DELETE FROM attempts WHERE task_slug = ?').run(slug);
944
+ const statement = db.prepare(
945
+ `INSERT OR IGNORE INTO attempts(
946
+ attempt_id, task_slug, step_index, step_label, agent, role, attempt_no, wave_id,
947
+ parallel_group_id, started_at, finished_at, duration_ms, outcome, source,
948
+ attribution_confidence, is_current
949
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
950
+ );
951
+ for (const attempt of attempts) {
952
+ statement.run(
953
+ attempt.attemptId,
954
+ slug,
955
+ attempt.stepIndex,
956
+ attempt.stepLabel,
957
+ attempt.agent,
958
+ attempt.role,
959
+ attempt.attemptNo,
960
+ attempt.waveId,
961
+ attempt.parallelGroupId,
962
+ attempt.startedAt,
963
+ attempt.finishedAt,
964
+ attempt.durationMs,
965
+ attempt.outcome,
966
+ attempt.source,
967
+ attempt.attributionConfidence,
968
+ attempt.isCurrent,
969
+ );
970
+ }
971
+ };
972
+
973
+ const replaceGates = (db, slug, gates) => {
974
+ db.prepare('DELETE FROM gates WHERE task_slug = ?').run(slug);
975
+ const statement = db.prepare(
976
+ 'INSERT OR IGNORE INTO gates(start_event_id, task_slug, started_at, end_event_id, ended_at, duration_ms) VALUES (?, ?, ?, ?, ?, ?)',
977
+ );
978
+ for (const gate of gates) {
979
+ statement.run(gate.startEventId, slug, gate.startedAt, gate.endEventId, gate.endedAt, gate.durationMs);
980
+ }
981
+ };
982
+
983
+ const replaceArtifacts = (db, slug, artifacts) => {
984
+ db.prepare('DELETE FROM artifacts WHERE task_slug = ?').run(slug);
985
+ const artifactStatement = db.prepare(
986
+ `INSERT INTO artifacts(
987
+ task_slug, artifact_id, producer, status, outcome, summary, receipt_attempt_id,
988
+ created_at, updated_at, completed_at, ac_ids_json, task_ids_json
989
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
990
+ );
991
+ const pathStatement = db.prepare(
992
+ 'INSERT INTO artifact_paths(task_slug, artifact_id, kind, ordinal, path) VALUES (?, ?, ?, ?, ?)',
993
+ );
994
+ for (const artifact of artifacts) {
995
+ artifactStatement.run(
996
+ slug,
997
+ artifact.artifactId,
998
+ artifact.producer,
999
+ artifact.status,
1000
+ artifact.outcome,
1001
+ artifact.summary,
1002
+ artifact.receiptAttemptId,
1003
+ artifact.createdAt,
1004
+ artifact.updatedAt,
1005
+ artifact.completedAt,
1006
+ artifact.acIdsJson,
1007
+ artifact.taskIdsJson,
1008
+ );
1009
+ artifact.authoritative.forEach((value, ordinal) => {
1010
+ pathStatement.run(slug, artifact.artifactId, 'authoritative', ordinal, value);
1011
+ });
1012
+ artifact.evidence.forEach((value, ordinal) => {
1013
+ pathStatement.run(slug, artifact.artifactId, 'evidence', ordinal, value);
1014
+ });
1015
+ }
1016
+ };
1017
+
1018
+ const replacePrompts = (db, slug, parsed) => {
1019
+ db.prepare('DELETE FROM prompts WHERE task_slug = ?').run(slug);
1020
+ const statement = db.prepare(
1021
+ `INSERT INTO prompts(task_slug, seq, source, command, captured_at, language, content, sha256, bytes)
1022
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1023
+ );
1024
+ const insert = (seq, entry) => {
1025
+ statement.run(
1026
+ slug,
1027
+ seq,
1028
+ entry.source ?? null,
1029
+ entry.command ?? null,
1030
+ entry.capturedAt ?? null,
1031
+ entry.language ?? null,
1032
+ entry.content,
1033
+ sha256(entry.content),
1034
+ Buffer.byteLength(entry.content, 'utf8'),
1035
+ );
1036
+ };
1037
+ if (parsed.prompt) {
1038
+ insert(0, {
1039
+ source: parsed.prompt.meta.source ?? 'user',
1040
+ command: parsed.prompt.meta.command ?? null,
1041
+ capturedAt: isoTimestamp(parsed.prompt.meta.capturedAt),
1042
+ language: parsed.prompt.meta.language ?? null,
1043
+ content: parsed.prompt.content,
1044
+ });
1045
+ }
1046
+ for (const entry of parsed.promptLog?.entries ?? []) {
1047
+ if (entry.seq === 0) continue;
1048
+ insert(entry.seq, entry);
1049
+ }
1050
+ };
1051
+
1052
+ const replaceOutcome = (db, slug, outcome) => {
1053
+ if (!outcome) {
1054
+ db.prepare('DELETE FROM outcomes WHERE task_slug = ?').run(slug);
1055
+ return;
1056
+ }
1057
+ db.prepare(
1058
+ `INSERT INTO outcomes(
1059
+ task_slug, goal_achieved, value, review_total, review_fair, review_rejected,
1060
+ review_open, review_rework, body, sha256
1061
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1062
+ ON CONFLICT(task_slug) DO UPDATE SET
1063
+ goal_achieved = excluded.goal_achieved,
1064
+ value = excluded.value,
1065
+ review_total = excluded.review_total,
1066
+ review_fair = excluded.review_fair,
1067
+ review_rejected = excluded.review_rejected,
1068
+ review_open = excluded.review_open,
1069
+ review_rework = excluded.review_rework,
1070
+ body = excluded.body,
1071
+ sha256 = excluded.sha256`,
1072
+ ).run(
1073
+ slug,
1074
+ outcome.goalAchieved,
1075
+ outcome.value,
1076
+ outcome.reviewTotal,
1077
+ outcome.reviewFair,
1078
+ outcome.reviewRejected,
1079
+ outcome.reviewOpen,
1080
+ outcome.reviewRework,
1081
+ outcome.body,
1082
+ sha256(outcome.body),
1083
+ );
1084
+ };
1085
+
1086
+ const replaceReviewLedger = (db, slug, ledger) => {
1087
+ db.prepare('DELETE FROM review_ledger WHERE task_slug = ?').run(slug);
1088
+ if (!ledger) return;
1089
+ const statement = db.prepare(
1090
+ `INSERT INTO review_ledger(task_slug, row_id, at, source, summary, fair, disposition, evidence, signature)
1091
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1092
+ );
1093
+ for (const row of ledger.rows) {
1094
+ statement.run(slug, row.id, row.at, row.source, row.summary, row.fair, row.disposition, row.evidence, row.signature);
1095
+ }
1096
+ };
1097
+
1098
+ const upsertDocuments = (db, slug, files, projectedAt) => {
1099
+ const existing = new Set(
1100
+ db.prepare('SELECT path FROM documents WHERE task_slug = ?').all(slug).map((row) => row.path),
1101
+ );
1102
+ const statement = db.prepare(
1103
+ `INSERT INTO documents(
1104
+ task_slug, path, sha256, bytes, media_type, is_text, content, content_omitted,
1105
+ parse_error, projected_at
1106
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1107
+ ON CONFLICT(task_slug, path) DO UPDATE SET
1108
+ sha256 = excluded.sha256,
1109
+ bytes = excluded.bytes,
1110
+ media_type = excluded.media_type,
1111
+ is_text = excluded.is_text,
1112
+ content = CASE WHEN documents.sha256 = excluded.sha256 THEN documents.content ELSE excluded.content END,
1113
+ content_omitted = CASE
1114
+ WHEN documents.sha256 = excluded.sha256 AND documents.content_omitted = 'retention' THEN 'retention'
1115
+ ELSE excluded.content_omitted
1116
+ END,
1117
+ parse_error = excluded.parse_error,
1118
+ projected_at = excluded.projected_at`,
1119
+ );
1120
+ for (const file of files) {
1121
+ const document = readDocument(file);
1122
+ statement.run(
1123
+ slug,
1124
+ file.path,
1125
+ file.sha256,
1126
+ file.bytes,
1127
+ document.mediaType,
1128
+ document.isText,
1129
+ document.content,
1130
+ document.contentOmitted,
1131
+ document.parseError,
1132
+ projectedAt,
1133
+ );
1134
+ existing.delete(file.path);
1135
+ }
1136
+ for (const stale of existing) {
1137
+ db.prepare('DELETE FROM documents WHERE task_slug = ? AND path = ?').run(slug, stale);
1138
+ }
1139
+ };
1140
+
1141
+ const setDocumentError = (db, slug, filePath, reason) => {
1142
+ db.prepare('UPDATE documents SET parse_error = ? WHERE task_slug = ? AND path = ?').run(reason, slug, filePath);
1143
+ };
1144
+
1145
+ const rebuildSearch = (db, slug, parsed, files) => {
1146
+ db.prepare('DELETE FROM search_fts WHERE task_slug = ?').run(slug);
1147
+ const insert = db.prepare(
1148
+ 'INSERT INTO search_fts(task_slug, doc_path, kind, body) VALUES (?, ?, ?, ?)',
1149
+ );
1150
+ const titles = [parsed.goal?.title, parsed.brief?.title].filter(Boolean);
1151
+ const artifactText =
1152
+ parsed.manifest?.artifacts
1153
+ ?.map((entry) => `${entry.id ?? ''} ${entry.receipt?.summary ?? entry.summary ?? ''} ${(entry.acceptanceCriteriaIds ?? []).join(' ')}`)
1154
+ .join('\n') ?? '';
1155
+ insert.run(slug, '', 'task', [slug, ...titles, artifactText].join('\n'));
1156
+ for (const file of files) {
1157
+ const document = readDocument(file);
1158
+ if (!document.content) continue;
1159
+ insert.run(slug, file.path, 'document', document.content);
1160
+ }
1161
+ if (parsed.prompt) insert.run(slug, 'prompt.md', 'prompt', parsed.prompt.content);
1162
+ for (const entry of parsed.promptLog?.entries ?? []) {
1163
+ insert.run(slug, `prompt-log.md#${entry.seq}`, 'prompt', entry.content);
1164
+ }
1165
+ };
1166
+
1167
+ const projectTask = ({ db, teamRoot, slug, now, searchMode, deadlineAt }) => {
1168
+ const taskDir = path.join(teamRoot, 'tasks', slug);
1169
+ const files = walkTaskDirectory(taskDir, deadlineAt);
1170
+ const contentHash = taskContentHash(files);
1171
+ const existing = db.prepare('SELECT content_hash, absent_at FROM tasks WHERE slug = ?').get(slug);
1172
+ if (existing && existing.content_hash === contentHash && existing.absent_at === null) {
1173
+ db.prepare('UPDATE tasks SET last_seen_at = ? WHERE slug = ?').run(now, slug);
1174
+ return { status: 'unchanged', errors: [] };
1175
+ }
1176
+
1177
+ const parsed = parseKnown(taskDir, slug);
1178
+ const errors = [...parsed.errors];
1179
+ const metrics = parsed.metrics ? eventRows(parsed.metrics, slug) : null;
1180
+ const pipeline = parsed.pipeline ? normalizePipeline(parsed.pipeline) : null;
1181
+ const artifacts = parsed.manifest ? normalizeArtifacts(parsed.manifest) : null;
1182
+ for (const skipped of artifacts?.skipped ?? []) {
1183
+ errors.push({ path: `${slug}/${KNOWN_FILES.manifest}`, reason: skipped });
1184
+ }
1185
+ const attempts = metrics ? deriveAttempts(metrics, parsed.status) : null;
1186
+ const gates = metrics ? deriveGates(metrics) : null;
1187
+ const times = metrics ? deriveTaskTimes(metrics) : null;
1188
+ const documentBytes = files.reduce((sum, file) => sum + (file.bytes ?? 0), 0);
1189
+
1190
+ db.exec('BEGIN IMMEDIATE');
1191
+ try {
1192
+ upsertTask(db, {
1193
+ slug,
1194
+ title: taskTitle(parsed, slug),
1195
+ intent: pipeline?.values.intent ?? parsed.status?.intent ?? null,
1196
+ profile: pipeline?.values.profile ?? parsed.status?.profile ?? null,
1197
+ specMode: pipeline?.values.specMode ?? null,
1198
+ complexity: pipeline?.values.complexity ?? null,
1199
+ phase: parsed.status?.phase ?? null,
1200
+ state: parsed.status?.state ?? null,
1201
+ pipelineIndex: integerOrNull(parsed.status?.pipelineIndex),
1202
+ currentAgent: parsed.status?.currentAgent ?? null,
1203
+ awaitingHumanGate: booleanFlag(parsed.status?.awaitingHumanGate),
1204
+ metricsRunId: parsed.status?.metricsRunId ?? parsed.metrics?.task?.runId ?? null,
1205
+ routingSummary: pipeline?.values.routingSummary ?? null,
1206
+ routingJson: pipeline?.values.routingJson ?? null,
1207
+ contextBudget: pipeline?.values.contextBudget ?? null,
1208
+ planRevision: pipeline?.values.planRevision ?? null,
1209
+ stepCount: pipeline?.values.stepCount ?? null,
1210
+ startAt: times?.startAt ?? null,
1211
+ endAt: times?.endAt ?? null,
1212
+ updatedAt: isoTimestamp(parsed.status?.updatedAt),
1213
+ projectedAt: now,
1214
+ lastSeenAt: now,
1215
+ contentHash,
1216
+ fileCount: files.length,
1217
+ documentBytes,
1218
+ parseErrorCount: errors.length,
1219
+ firstSeenAt: now,
1220
+ statusParsed: parsed.status ? 1 : 0,
1221
+ });
1222
+ if (pipeline) replacePipeline(db, slug, pipeline);
1223
+ if (metrics) {
1224
+ replaceEvents(db, slug, metrics);
1225
+ replaceAttempts(db, slug, attempts);
1226
+ replaceGates(db, slug, gates);
1227
+ }
1228
+ if (artifacts) replaceArtifacts(db, slug, artifacts.artifacts);
1229
+ replacePrompts(db, slug, parsed);
1230
+ if (parsed.outcome || !parsed.outcomeExists) replaceOutcome(db, slug, parsed.outcome);
1231
+ if (parsed.reviewLedger || !parsed.reviewLedgerExists) replaceReviewLedger(db, slug, parsed.reviewLedger);
1232
+ upsertDocuments(db, slug, files, now);
1233
+ for (const error of errors) {
1234
+ const relative = error.path.startsWith(`${slug}/`) ? error.path.slice(slug.length + 1) : null;
1235
+ if (relative) setDocumentError(db, slug, relative, error.reason);
1236
+ }
1237
+ if (searchMode === SEARCH_MODE_FTS5) rebuildSearch(db, slug, parsed, files);
1238
+ db.exec('COMMIT');
1239
+ } catch (error) {
1240
+ try {
1241
+ db.exec('ROLLBACK');
1242
+ } catch {
1243
+ /* the transaction may already be gone; the original error is the finding */
1244
+ }
1245
+ throw error;
1246
+ }
1247
+ return { status: existing ? 'updated' : 'inserted', errors };
1248
+ };
1249
+
1250
+ /* --------------------------- search and lifecycle -------------------------- */
1251
+
1252
+ const escapeLike = (value) => value.replace(/[\\%_]/g, '\\$&');
1253
+
1254
+ // A punctuation-only token (`'`, `--`) becomes an empty FTS phrase and matched
1255
+ // every row. Keep only tokens with a letter or digit; if none remain the search
1256
+ // is empty, not "no filter".
1257
+ const ftsTokens = (query) => query.split(/\s+/).filter((token) => /[\p{L}\p{N}]/u.test(token));
1258
+
1259
+ const toFtsQuery = (tokens) =>
1260
+ tokens
1261
+ .map((token) => `"${token.replace(/"/g, '""')}"`)
1262
+ .join(' AND ');
1263
+
1264
+ /**
1265
+ * Minimal search used by the WP2 suite and reusable by the query layer: FTS5
1266
+ * `MATCH` when available, escaped `LIKE` otherwise. Never builds SQL from input.
1267
+ */
1268
+ export function searchProjection(db, query, options = {}) {
1269
+ if (typeof query !== 'string' || query.trim() === '') return [];
1270
+ const tokens = ftsTokens(query);
1271
+ if (tokens.length === 0) return [];
1272
+ const limit = Number.isFinite(options.limit) ? Math.max(1, Math.min(200, options.limit)) : 50;
1273
+ const mode = options.mode ?? readSearchMode(db);
1274
+ if (mode === SEARCH_MODE_FTS5) {
1275
+ try {
1276
+ const rows = db
1277
+ .prepare(
1278
+ `SELECT task_slug AS taskSlug, doc_path, kind,
1279
+ snippet(search_fts, 3, '', '', '…', 12) AS snippet
1280
+ FROM search_fts
1281
+ WHERE search_fts MATCH ?
1282
+ ORDER BY rank
1283
+ LIMIT ?`,
1284
+ )
1285
+ .all(toFtsQuery(tokens), limit)
1286
+ .map((row) => ({ ...row }));
1287
+ // An index created after the tree was already projected is empty until a
1288
+ // task changes; the LIKE path keeps search correct in that window.
1289
+ if (rows.length > 0) return rows;
1290
+ } catch {
1291
+ /* an FTS syntax edge falls through to LIKE instead of failing the query */
1292
+ }
1293
+ }
1294
+ const pattern = `%${escapeLike(query)}%`;
1295
+ return db
1296
+ .prepare(
1297
+ `SELECT task_slug AS taskSlug, path AS doc_path, 'document' AS kind, substr(content, 1, 200) AS snippet
1298
+ FROM documents
1299
+ WHERE content LIKE ? ESCAPE '\\'
1300
+ UNION ALL
1301
+ SELECT task_slug AS taskSlug, 'prompt.md' AS doc_path, 'prompt' AS kind, substr(content, 1, 200) AS snippet
1302
+ FROM prompts
1303
+ WHERE content LIKE ? ESCAPE '\\'
1304
+ LIMIT ?`,
1305
+ )
1306
+ .all(pattern, pattern, limit)
1307
+ .map((row) => ({ ...row }));
1308
+ }
1309
+
1310
+ const hasSearchTable = (db) =>
1311
+ Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'search_fts'").get());
1312
+
1313
+ const markAbsent = (db, slug, at) =>
1314
+ db.prepare('UPDATE tasks SET absent_at = ? WHERE slug = ? AND absent_at IS NULL').run(at, slug).changes;
1315
+
1316
+ const maintainDatabase = (db, now) => {
1317
+ const retentionCutoff = new Date(Date.now() - RETENTION_DAYS * 24 * 60 * 60 * 1000).toISOString();
1318
+ const staleCutoff = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
1319
+ const absent = db
1320
+ .prepare('SELECT slug FROM tasks WHERE absent_at IS NOT NULL AND absent_at < ?')
1321
+ .all(retentionCutoff);
1322
+ let retained = 0;
1323
+ for (const row of absent) {
1324
+ const changed = db
1325
+ .prepare(
1326
+ "UPDATE documents SET content = NULL, content_omitted = 'retention' WHERE task_slug = ? AND content IS NOT NULL",
1327
+ )
1328
+ .run(row.slug).changes;
1329
+ if (hasSearchTable(db)) db.prepare('DELETE FROM search_fts WHERE task_slug = ?').run(row.slug);
1330
+ if (changed > 0) retained += 1;
1331
+ }
1332
+ db.prepare(
1333
+ `DELETE FROM sync_runs WHERE run_id NOT IN (
1334
+ SELECT run_id FROM sync_runs ORDER BY run_id DESC LIMIT ?
1335
+ )`,
1336
+ ).run(SYNC_RUN_RETENTION);
1337
+ db.prepare('DELETE FROM sync_runs WHERE finished_at IS NULL AND started_at < ?').run(staleCutoff);
1338
+ return { retained, now };
1339
+ };
1340
+
1341
+ const updateRun = (db, runId, result) => {
1342
+ db.prepare(
1343
+ `UPDATE sync_runs SET finished_at = ?, inserted = ?, updated = ?, unchanged = ?, failed = ?,
1344
+ absent = ?, pruned = ?, rebuilt = ?, exit_code = ?, error = ? WHERE run_id = ?`,
1345
+ ).run(
1346
+ new Date().toISOString(),
1347
+ result.inserted,
1348
+ result.updated,
1349
+ result.unchanged,
1350
+ result.failed,
1351
+ result.absent,
1352
+ result.pruned,
1353
+ result.rebuilt,
1354
+ result.exitCode,
1355
+ result.error ?? null,
1356
+ runId,
1357
+ );
1358
+ };
1359
+
1360
+ const resolveDeadline = (deadlineMs, slug) => {
1361
+ if (deadlineMs === null || deadlineMs === undefined || deadlineMs === '') {
1362
+ return Number.isFinite(defaultDeadline(slug)) ? Date.now() + defaultDeadline(slug) : Infinity;
1363
+ }
1364
+ const parsed = Number(deadlineMs);
1365
+ if (!Number.isFinite(parsed) || parsed < 0) teamDbFail('E_USAGE', '--deadline-ms must be a non-negative number', 3);
1366
+ return parsed === 0 ? Infinity : Date.now() + parsed;
1367
+ };
1368
+
1369
+ const defaultDeadline = (slug) => (slug ? DEFAULT_SLUG_DEADLINE_MS : Infinity);
1370
+
1371
+ /**
1372
+ * Project a tree (or one slug) into the database.
1373
+ *
1374
+ * Returns the `SyncResult` shape; throws `TeamDbError` for database-level
1375
+ * failures, usage errors, and deadline expiry.
1376
+ */
1377
+ export function syncProjection(options = {}) {
1378
+ const slug = options.slug ?? null;
1379
+ const maintain = Boolean(options.maintain || options.vacuum);
1380
+ const prune = Boolean(options.prune);
1381
+ const vacuum = Boolean(options.vacuum);
1382
+ if (slug && (prune || vacuum || options.maintain)) {
1383
+ teamDbFail('E_USAGE', '--maintain, --prune and --vacuum cannot be combined with --slug', 3);
1384
+ }
1385
+ const deadlineAt = resolveDeadline(options.deadlineMs, slug);
1386
+ const startedAt = new Date().toISOString();
1387
+ const handle = openTeamDb({
1388
+ teamRoot: options.teamRoot,
1389
+ dbPath: options.dbPath,
1390
+ rebuild: options.rebuild,
1391
+ noRebuild: options.noRebuild,
1392
+ searchMode: options.searchMode,
1393
+ env: options.env,
1394
+ });
1395
+ const { db } = handle;
1396
+ const result = {
1397
+ mode: slug ? 'slug' : 'full',
1398
+ startedAt,
1399
+ inserted: 0,
1400
+ updated: 0,
1401
+ unchanged: 0,
1402
+ failed: 0,
1403
+ absent: 0,
1404
+ pruned: 0,
1405
+ retained: 0,
1406
+ rebuilt: handle.rebuilt ? 1 : 0,
1407
+ exitCode: 0,
1408
+ errors: [],
1409
+ error: null,
1410
+ };
1411
+ const run = (() => {
1412
+ try {
1413
+ return db
1414
+ .prepare('INSERT INTO sync_runs(mode, started_at, rebuilt) VALUES (?, ?, ?)')
1415
+ .run(result.mode, startedAt, result.rebuilt);
1416
+ } catch (error) {
1417
+ db.close();
1418
+ if (isBusyError(error)) teamDbFail('E_DB_BUSY', `${handle.dbPath}: ${error.message}`, 2);
1419
+ if (isCorruptError(error)) teamDbFail('E_DB_CORRUPT', `${handle.dbPath}: ${error.message}`, 2);
1420
+ throw error;
1421
+ }
1422
+ })();
1423
+ const runId = Number(run.lastInsertRowid);
1424
+
1425
+ try {
1426
+ const slugs = slug ? [slug] : listTaskDirectories(handle.teamRoot);
1427
+ for (const taskSlug of slugs) {
1428
+ if (Date.now() > deadlineAt) teamDbFail('E_DEADLINE', `projection deadline expired before ${taskSlug}`, 4);
1429
+ const taskDir = path.join(handle.teamRoot, 'tasks', taskSlug);
1430
+ const present = fs.existsSync(taskDir) && fs.lstatSync(taskDir).isDirectory();
1431
+ if (!present) {
1432
+ if (slug) result.absent += markAbsent(db, taskSlug, startedAt);
1433
+ continue;
1434
+ }
1435
+ try {
1436
+ const outcome = projectTask({
1437
+ db,
1438
+ teamRoot: handle.teamRoot,
1439
+ slug: taskSlug,
1440
+ now: new Date().toISOString(),
1441
+ searchMode: handle.searchMode,
1442
+ deadlineAt,
1443
+ });
1444
+ result[outcome.status] += 1;
1445
+ for (const error of outcome.errors) result.errors.push(error);
1446
+ if (outcome.errors.length > 0) result.failed += 1;
1447
+ } catch (error) {
1448
+ if (error instanceof TeamDbError) throw error;
1449
+ if (isBusyError(error)) teamDbFail('E_DB_BUSY', `${taskSlug}: ${error.message}`, 2);
1450
+ if (isCorruptError(error)) teamDbFail('E_DB_CORRUPT', `${taskSlug}: ${error.message}`, 2);
1451
+ result.failed += 1;
1452
+ result.errors.push({ path: `${taskSlug}`, reason: error.message });
1453
+ }
1454
+ }
1455
+
1456
+ if (!slug) {
1457
+ const placeholders = slugs.map(() => '?').join(', ');
1458
+ const statement = slugs.length
1459
+ ? db.prepare(`UPDATE tasks SET absent_at = ? WHERE absent_at IS NULL AND slug NOT IN (${placeholders})`)
1460
+ : db.prepare('UPDATE tasks SET absent_at = ? WHERE absent_at IS NULL');
1461
+ result.absent += slugs.length ? statement.run(startedAt, ...slugs).changes : statement.run(startedAt).changes;
1462
+ }
1463
+ if (prune) result.pruned += db.prepare('DELETE FROM tasks WHERE absent_at IS NOT NULL').run().changes;
1464
+ if (maintain) {
1465
+ result.retained += maintainDatabase(db, startedAt).retained;
1466
+ if (!integrityCheck(db)) teamDbFail('E_DB_CORRUPT', `${handle.dbPath} failed PRAGMA integrity_check`, 2);
1467
+ } else if (!slug) {
1468
+ const quick = db.prepare('PRAGMA quick_check').get();
1469
+ if (!quick || Object.values(quick)[0] !== 'ok') {
1470
+ teamDbFail('E_DB_CORRUPT', `${handle.dbPath} failed PRAGMA quick_check`, 2);
1471
+ }
1472
+ }
1473
+ if (vacuum) {
1474
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
1475
+ db.exec('VACUUM');
1476
+ }
1477
+ result.exitCode = result.failed > 0 ? 1 : 0;
1478
+ result.error = result.errors[0] ? `${result.errors[0].path}: ${result.errors[0].reason}` : null;
1479
+ updateRun(db, runId, result);
1480
+ chmodDatabaseFiles(handle.dbPath);
1481
+ return result;
1482
+ } catch (error) {
1483
+ result.exitCode = error instanceof TeamDbError ? error.exitCode : 2;
1484
+ result.error = error.message;
1485
+ try {
1486
+ updateRun(db, runId, result);
1487
+ } catch {
1488
+ /* the primary failure is the finding */
1489
+ }
1490
+ throw error;
1491
+ } finally {
1492
+ try {
1493
+ db.close();
1494
+ } catch {
1495
+ /* a close error after a successful commit is not a projection failure */
1496
+ }
1497
+ }
1498
+ }
1499
+
1500
+ /** Human summary for a `sync` run. */
1501
+ export function describeSyncResult(result) {
1502
+ return (
1503
+ `sync: inserted=${result.inserted} updated=${result.updated} unchanged=${result.unchanged} ` +
1504
+ `absent=${result.absent} failed=${result.failed} pruned=${result.pruned} rebuilt=${result.rebuilt}`
1505
+ );
1506
+ }