@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,251 @@
1
+ /**
2
+ * CLI surface for the `.ai.local/team` SQLite projection.
3
+ *
4
+ * Commands:
5
+ * init [--root <team-dir>] [--rebuild] create or migrate the database
6
+ * check [--root <team-dir>] report schema, fingerprint, integrity
7
+ * sync [--root <team-dir>] [--slug <slug>] [--quiet] [--json]
8
+ * [--maintain] [--prune] [--vacuum] [--rebuild | --no-rebuild]
9
+ * [--deadline-ms <n>] project files into the database
10
+ * serve [--root <team-dir>] [--host <addr>] [--port <n>] [--allow-remote]
11
+ * [--open] read-only API + dashboard
12
+ *
13
+ * Exit codes: 0 ok, 1 at least one task failed or a migration checksum drifted,
14
+ * 2 database-level failure, 3 usage, 4 deadline or busy.
15
+ *
16
+ * A runtime without `node:sqlite` prints one line and stays file-only:
17
+ * `init`/`sync` exit 0 without creating a database, `check` exits 1.
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+
24
+ import { spawn } from 'node:child_process';
25
+
26
+ import {
27
+ DEFAULT_TEAM_ROOT,
28
+ INDEX_UNAVAILABLE_LINE,
29
+ TeamDbError,
30
+ checkTeamDb,
31
+ describeHandle,
32
+ integrityCheck,
33
+ isKillSwitchSet,
34
+ isSqliteAvailable,
35
+ openTeamDb,
36
+ teamDbFail,
37
+ } from './team-db-schema.mjs';
38
+ import { describeSyncResult, syncProjection } from './team-db-project.mjs';
39
+
40
+ const USAGE = `usage:
41
+ team-db.mjs init [--root <team-dir>] [--rebuild]
42
+ team-db.mjs check [--root <team-dir>]
43
+ team-db.mjs sync [--root <team-dir>] [--slug <slug>] [--quiet] [--json]
44
+ [--maintain] [--prune] [--vacuum] [--rebuild | --no-rebuild]
45
+ [--deadline-ms <n>]
46
+ team-db.mjs serve [--root <team-dir>] [--host <addr>] [--port <n>]
47
+ [--allow-remote] [--open]`;
48
+
49
+ const VALUE_FLAGS = new Set(['root', 'slug', 'deadline-ms', 'host', 'port']);
50
+ const BOOLEAN_FLAGS = new Set(['quiet', 'json', 'maintain', 'prune', 'vacuum', 'rebuild', 'no-rebuild', 'allow-remote', 'open']);
51
+ const COMMANDS = new Set(['init', 'check', 'sync', 'serve']);
52
+ const ALLOWED_FLAGS = {
53
+ init: new Set(['root', 'rebuild']),
54
+ check: new Set(['root']),
55
+ sync: new Set(['root', 'slug', 'quiet', 'json', 'maintain', 'prune', 'vacuum', 'rebuild', 'no-rebuild', 'deadline-ms']),
56
+ serve: new Set(['root', 'host', 'port', 'allow-remote', 'open']),
57
+ };
58
+
59
+ const parseArgs = (argv) => {
60
+ const [command, ...rest] = argv;
61
+ if (command === undefined || command === '--help' || command === 'help') return { command: 'help', flags: {} };
62
+ if (!COMMANDS.has(command)) teamDbFail('E_USAGE', `unknown command "${command}"\n${USAGE}`, 3);
63
+ const flags = {};
64
+ for (let index = 0; index < rest.length; index += 1) {
65
+ const token = rest[index];
66
+ if (!token.startsWith('--')) teamDbFail('E_USAGE', `unexpected argument "${token}"`, 3);
67
+ const [name, inline] = token.slice(2).split('=');
68
+ if (VALUE_FLAGS.has(name)) {
69
+ if (inline !== undefined) {
70
+ flags[name] = inline;
71
+ continue;
72
+ }
73
+ const next = rest[index + 1];
74
+ if (next === undefined || next.startsWith('--')) {
75
+ teamDbFail('E_USAGE', `flag --${name} needs a value`, 3);
76
+ }
77
+ flags[name] = next;
78
+ index += 1;
79
+ continue;
80
+ }
81
+ if (BOOLEAN_FLAGS.has(name)) {
82
+ if (inline !== undefined) teamDbFail('E_USAGE', `flag --${name} does not take a value`, 3);
83
+ flags[name] = true;
84
+ continue;
85
+ }
86
+ teamDbFail('E_USAGE', `unknown flag --${name}`, 3);
87
+ }
88
+ for (const name of Object.keys(flags)) {
89
+ if (!ALLOWED_FLAGS[command].has(name)) teamDbFail('E_USAGE', `flag --${name} does not apply to ${command}`, 3);
90
+ }
91
+ return { command, flags };
92
+ };
93
+
94
+ const teamRootFrom = (flags) => (flags.root ? path.resolve(flags.root) : DEFAULT_TEAM_ROOT);
95
+
96
+ const unavailableLine = () => process.stderr.write(`${INDEX_UNAVAILABLE_LINE}\n`);
97
+
98
+ const disabledLine = () => process.stderr.write('team-db: disabled by AI_RULES_TEAM_DB_DISABLE\n');
99
+
100
+ const cannotProject = (env) => {
101
+ if (isKillSwitchSet(env)) {
102
+ disabledLine();
103
+ return true;
104
+ }
105
+ if (!isSqliteAvailable(env)) {
106
+ unavailableLine();
107
+ return true;
108
+ }
109
+ return false;
110
+ };
111
+
112
+ const runInit = (flags) => {
113
+ if (cannotProject(process.env)) return 0;
114
+ const handle = openTeamDb({ teamRoot: teamRootFrom(flags), rebuild: Boolean(flags.rebuild) });
115
+ try {
116
+ if (!integrityCheck(handle.db)) {
117
+ teamDbFail('E_DB_CORRUPT', `${handle.dbPath} failed PRAGMA integrity_check`, 2);
118
+ }
119
+ process.stdout.write(`${describeHandle(handle)}\n`);
120
+ return 0;
121
+ } finally {
122
+ handle.db.close();
123
+ }
124
+ };
125
+
126
+ const runCheck = (flags) => {
127
+ if (isKillSwitchSet(process.env)) {
128
+ disabledLine();
129
+ return 1;
130
+ }
131
+ if (!isSqliteAvailable(process.env)) {
132
+ unavailableLine();
133
+ return 1;
134
+ }
135
+ const handle = checkTeamDb({ teamRoot: teamRootFrom(flags) });
136
+ process.stdout.write(`${describeHandle(handle)}\n`);
137
+ return 0;
138
+ };
139
+
140
+ const runSync = (flags) => {
141
+ if (cannotProject(process.env)) return 0;
142
+ if (flags.rebuild && flags['no-rebuild']) teamDbFail('E_USAGE', '--rebuild and --no-rebuild are exclusive', 3);
143
+ let result;
144
+ try {
145
+ result = syncProjection({
146
+ teamRoot: teamRootFrom(flags),
147
+ slug: flags.slug ?? null,
148
+ maintain: Boolean(flags.maintain),
149
+ prune: Boolean(flags.prune),
150
+ vacuum: Boolean(flags.vacuum),
151
+ rebuild: Boolean(flags.rebuild),
152
+ noRebuild: Boolean(flags['no-rebuild']),
153
+ deadlineMs: flags['deadline-ms'],
154
+ });
155
+ } catch (error) {
156
+ if (error instanceof TeamDbError && error.code === 'E_DB_BUSY' && flags.slug) error.exitCode = 4;
157
+ throw error;
158
+ }
159
+ // JSON output narrows stdout to one line; failures still print on stderr so
160
+ // AC-2.5 holds in every output mode.
161
+ for (const failure of result.errors) {
162
+ process.stderr.write(`${failure.path}: ${failure.reason}\n`);
163
+ }
164
+ if (flags.json) {
165
+ process.stdout.write(`${JSON.stringify(result)}\n`);
166
+ return result.exitCode;
167
+ }
168
+ if (!flags.quiet) process.stdout.write(`${describeSyncResult(result)}\n`);
169
+ return result.exitCode;
170
+ };
171
+
172
+ const openDashboard = (url) => {
173
+ try {
174
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
175
+ spawn(command, [url], { detached: true, stdio: 'ignore' }).unref();
176
+ } catch {
177
+ /* opening a browser is a convenience, never a failure */
178
+ }
179
+ };
180
+
181
+ const runServe = async (flags) => {
182
+ if (isKillSwitchSet(process.env)) {
183
+ disabledLine();
184
+ return 0;
185
+ }
186
+ if (!isSqliteAvailable(process.env)) {
187
+ unavailableLine();
188
+ return 0;
189
+ }
190
+ // Loaded here, not at module scope: `init`, `sync` and `check` must not pay
191
+ // for the server, the dashboard strings or the OpenAPI document.
192
+ const api = await import('./team-db-api.mjs');
193
+ const host = typeof flags.host === 'string' ? flags.host.trim() : api.DEFAULT_HOST;
194
+ const allowRemote = Boolean(flags['allow-remote']);
195
+ if (!host) teamDbFail('E_USAGE', '--host needs a value', 3);
196
+ if (!api.LOOPBACK_HOSTS.includes(host) && !allowRemote) {
197
+ teamDbFail('E_USAGE', `--host ${host} is not loopback; pass --allow-remote to bind it`, 3);
198
+ }
199
+ if (allowRemote && (host === '0.0.0.0' || host === '::' || host === '::0')) {
200
+ teamDbFail('E_USAGE', `--allow-remote refuses the wildcard address ${host}; name the exact interface`, 3);
201
+ }
202
+ const port = flags.port === undefined ? api.DEFAULT_PORT : Number(flags.port);
203
+ if (!Number.isInteger(port) || port < 0 || port > 65535) teamDbFail('E_USAGE', '--port must be an integer between 0 and 65535', 3);
204
+ const info = await api.startServer({ host, port, teamRoot: teamRootFrom(flags), allowRemote });
205
+ process.stdout.write(`${api.describeServer(info)}\n`);
206
+ if (!api.LOOPBACK_HOSTS.includes(info.host)) {
207
+ process.stderr.write(`WARNING: team-db is bound to ${info.host}:${info.port}, not loopback\n`);
208
+ }
209
+ if (flags.open) openDashboard(info.url);
210
+ const shutdown = () => {
211
+ info.close().then(() => process.exit(0));
212
+ };
213
+ process.once('SIGINT', shutdown);
214
+ process.once('SIGTERM', shutdown);
215
+ return new Promise(() => {});
216
+ };
217
+
218
+ export async function runCli(argv) {
219
+ const { command, flags } = parseArgs(argv);
220
+ if (command === 'help') {
221
+ process.stdout.write(`${USAGE}\n`);
222
+ return 0;
223
+ }
224
+ if (command === 'init') return runInit(flags);
225
+ if (command === 'check') return runCheck(flags);
226
+ if (command === 'serve') return runServe(flags);
227
+ return runSync(flags);
228
+ }
229
+
230
+ const invokedDirectly = (() => {
231
+ if (!process.argv[1]) return false;
232
+ try {
233
+ return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
234
+ } catch {
235
+ return false;
236
+ }
237
+ })();
238
+
239
+ if (invokedDirectly) {
240
+ try {
241
+ process.exitCode = await runCli(process.argv.slice(2));
242
+ } catch (error) {
243
+ if (error instanceof TeamDbError) {
244
+ process.stderr.write(`${error.message}\n`);
245
+ process.exitCode = error.exitCode;
246
+ } else {
247
+ process.stderr.write(`${error.message}\n`);
248
+ process.exitCode = 2;
249
+ }
250
+ }
251
+ }
@@ -2459,6 +2459,115 @@ if (!input || input.status !== 'completed') {
2459
2459
  process.exit(0);
2460
2460
  }
2461
2461
 
2462
+ // --- TEAM_DB_PROJECTION -------------------------------------------------------
2463
+ // The status, metrics, compaction and focus writes are already durable when this
2464
+ // postflight starts. The projection is a bounded child process: it must never
2465
+ // fail this stop, never change hook stdout/stderr beyond the capability line,
2466
+ // and never write a task file. A disabled switch, a missing script, or a
2467
+ // runtime without `node:sqlite` is a skip; a child failure is one log line.
2468
+ // This is a plain region marker, not a `hook-slot`: the block is identical in
2469
+ // all 40 rendered bodies and needs no per-stack fragment.
2470
+ // <<<team-db-projection>>>
2471
+ function teamDbTruthy(value) {
2472
+ if (typeof value !== 'string') return false;
2473
+ const normalized = value.trim().toLowerCase();
2474
+ return normalized === '1' || normalized === 'true' || normalized === 'yes';
2475
+ }
2476
+
2477
+ function teamDbLogPath(env) {
2478
+ const override = typeof env.AI_RULES_TEAM_DB_LOG === 'string' ? env.AI_RULES_TEAM_DB_LOG.trim() : '';
2479
+ if (override) return path.resolve(override);
2480
+ return path.join(process.cwd(), '.ai.local', 'team', 'team-db-errors.log');
2481
+ }
2482
+
2483
+ function teamDbLogPhase(env) {
2484
+ const value = typeof env.AI_RULES_TEAM_DB_SEAM === 'string' ? env.AI_RULES_TEAM_DB_SEAM.trim() : '';
2485
+ return value === 'hook' || value === 'receipt' || value === 'cli' || value === 'serve' ? value : 'hook';
2486
+ }
2487
+
2488
+ // One line per failure, newest 200 lines and at most 64 KiB. Never a prompt
2489
+ // body: only the code and the message this block owns.
2490
+ function teamDbLogFailure(env, code, message) {
2491
+ try {
2492
+ const target = teamDbLogPath(env);
2493
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2494
+ const line = new Date().toISOString() + ' ' + code + ' ' + teamDbLogPhase(env) + ' ' + message;
2495
+ fs.appendFileSync(target, line + '\n');
2496
+ let content = fs.readFileSync(target, 'utf8');
2497
+ let lines = content.split('\n').filter(function (entry) { return entry.length > 0; });
2498
+ if (lines.length > 200) lines = lines.slice(lines.length - 200);
2499
+ while (Buffer.byteLength(lines.join('\n') + '\n', 'utf8') > 65536 && lines.length > 1) lines.shift();
2500
+ content = lines.join('\n') + (lines.length > 0 ? '\n' : '');
2501
+ fs.writeFileSync(target, content);
2502
+ } catch (error) {
2503
+ /* a log failure is not a stop failure */
2504
+ }
2505
+ }
2506
+
2507
+ function teamDbSqliteAvailable(env) {
2508
+ if (teamDbTruthy(env.AI_RULES_TEAM_DB_FORCE_FALLBACK)) return false;
2509
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(process.versions.node || ''));
2510
+ if (!match) return false;
2511
+ const major = Number(match[1]);
2512
+ const minor = Number(match[2]);
2513
+ if (major < 22) return false;
2514
+ if (major === 22 && minor < 13) return false;
2515
+ try {
2516
+ const sqlite = require('node:sqlite');
2517
+ return typeof sqlite.DatabaseSync === 'function';
2518
+ } catch (error) {
2519
+ return false;
2520
+ }
2521
+ }
2522
+
2523
+ function teamDbProject() {
2524
+ try {
2525
+ const env = process.env;
2526
+ if (teamDbTruthy(env.AI_RULES_TEAM_DB_DISABLE)) return;
2527
+ // Same pattern as POSTFLIGHT_SLUG_RE above: the slug is re-derived from
2528
+ // `active-task.json` on this path too, so it cannot escape the tree.
2529
+ const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2530
+ let slug = '';
2531
+ try {
2532
+ const active = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'active-task.json'), 'utf8'));
2533
+ slug = typeof active.slug === 'string' ? active.slug : '';
2534
+ } catch (error) {
2535
+ return;
2536
+ }
2537
+ if (!slug || slug.length > 48 || !slugPattern.test(slug)) return;
2538
+ const taskDir = path.join(process.cwd(), '.ai.local', 'team', 'tasks', slug);
2539
+ if (!fs.existsSync(path.join(taskDir, 'status.json'))) return;
2540
+ const script = path.join(process.cwd(), '.ai.local', 'scripts', 'team-db.mjs');
2541
+ if (!fs.existsSync(script)) return;
2542
+ if (!teamDbSqliteAvailable(env)) {
2543
+ process.stderr.write('team-db: projection skipped (node:sqlite unavailable); file-only mode\n');
2544
+ return;
2545
+ }
2546
+ const result = spawnSync(
2547
+ process.execPath,
2548
+ ['.ai.local/scripts/team-db.mjs', 'sync', '--slug', slug, '--quiet', '--no-rebuild', '--deadline-ms', '4500'],
2549
+ { cwd: process.cwd(), env: env, encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'pipe'] },
2550
+ );
2551
+ if (result.error && result.error.code === 'ETIMEDOUT') {
2552
+ teamDbLogFailure(env, 'E_PROJECTION_TIMEOUT', 'projection exceeded 5000 ms and was killed');
2553
+ return;
2554
+ }
2555
+ if (result.error) {
2556
+ teamDbLogFailure(env, 'E_PROJECTION_FAILED', 'projection could not start: ' + String(result.error.code || 'unknown'));
2557
+ return;
2558
+ }
2559
+ if (typeof result.status === 'number' && result.status !== 0) {
2560
+ teamDbLogFailure(env, 'E_PROJECTION_FAILED', 'projection exited ' + result.status);
2561
+ }
2562
+ } catch (error) {
2563
+ /* the seam never fails the stop */
2564
+ }
2565
+ }
2566
+
2567
+ teamDbProject();
2568
+ // <<<team-db-projection-end>>>
2569
+ // --- end TEAM_DB_PROJECTION ---------------------------------------------------
2570
+
2462
2571
  // Ratchet: off for `light` pipelines and `spike` intents. A policy skip is
2463
2572
  // silent on purpose — a warning on every light receipt would make the
2464
2573
  // containment warnings below unreadable.
@@ -2618,6 +2618,115 @@ if (!input || input.status !== 'completed') {
2618
2618
  process.exit(0);
2619
2619
  }
2620
2620
 
2621
+ // --- TEAM_DB_PROJECTION -------------------------------------------------------
2622
+ // The status, metrics, compaction and focus writes are already durable when this
2623
+ // postflight starts. The projection is a bounded child process: it must never
2624
+ // fail this stop, never change hook stdout/stderr beyond the capability line,
2625
+ // and never write a task file. A disabled switch, a missing script, or a
2626
+ // runtime without `node:sqlite` is a skip; a child failure is one log line.
2627
+ // This is a plain region marker, not a `hook-slot`: the block is identical in
2628
+ // all 40 rendered bodies and needs no per-stack fragment.
2629
+ // <<<team-db-projection>>>
2630
+ function teamDbTruthy(value) {
2631
+ if (typeof value !== 'string') return false;
2632
+ const normalized = value.trim().toLowerCase();
2633
+ return normalized === '1' || normalized === 'true' || normalized === 'yes';
2634
+ }
2635
+
2636
+ function teamDbLogPath(env) {
2637
+ const override = typeof env.AI_RULES_TEAM_DB_LOG === 'string' ? env.AI_RULES_TEAM_DB_LOG.trim() : '';
2638
+ if (override) return path.resolve(override);
2639
+ return path.join(process.cwd(), '.ai.local', 'team', 'team-db-errors.log');
2640
+ }
2641
+
2642
+ function teamDbLogPhase(env) {
2643
+ const value = typeof env.AI_RULES_TEAM_DB_SEAM === 'string' ? env.AI_RULES_TEAM_DB_SEAM.trim() : '';
2644
+ return value === 'hook' || value === 'receipt' || value === 'cli' || value === 'serve' ? value : 'hook';
2645
+ }
2646
+
2647
+ // One line per failure, newest 200 lines and at most 64 KiB. Never a prompt
2648
+ // body: only the code and the message this block owns.
2649
+ function teamDbLogFailure(env, code, message) {
2650
+ try {
2651
+ const target = teamDbLogPath(env);
2652
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2653
+ const line = new Date().toISOString() + ' ' + code + ' ' + teamDbLogPhase(env) + ' ' + message;
2654
+ fs.appendFileSync(target, line + '\n');
2655
+ let content = fs.readFileSync(target, 'utf8');
2656
+ let lines = content.split('\n').filter(function (entry) { return entry.length > 0; });
2657
+ if (lines.length > 200) lines = lines.slice(lines.length - 200);
2658
+ while (Buffer.byteLength(lines.join('\n') + '\n', 'utf8') > 65536 && lines.length > 1) lines.shift();
2659
+ content = lines.join('\n') + (lines.length > 0 ? '\n' : '');
2660
+ fs.writeFileSync(target, content);
2661
+ } catch (error) {
2662
+ /* a log failure is not a stop failure */
2663
+ }
2664
+ }
2665
+
2666
+ function teamDbSqliteAvailable(env) {
2667
+ if (teamDbTruthy(env.AI_RULES_TEAM_DB_FORCE_FALLBACK)) return false;
2668
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(process.versions.node || ''));
2669
+ if (!match) return false;
2670
+ const major = Number(match[1]);
2671
+ const minor = Number(match[2]);
2672
+ if (major < 22) return false;
2673
+ if (major === 22 && minor < 13) return false;
2674
+ try {
2675
+ const sqlite = require('node:sqlite');
2676
+ return typeof sqlite.DatabaseSync === 'function';
2677
+ } catch (error) {
2678
+ return false;
2679
+ }
2680
+ }
2681
+
2682
+ function teamDbProject() {
2683
+ try {
2684
+ const env = process.env;
2685
+ if (teamDbTruthy(env.AI_RULES_TEAM_DB_DISABLE)) return;
2686
+ // Same pattern as POSTFLIGHT_SLUG_RE above: the slug is re-derived from
2687
+ // `active-task.json` on this path too, so it cannot escape the tree.
2688
+ const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2689
+ let slug = '';
2690
+ try {
2691
+ const active = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'active-task.json'), 'utf8'));
2692
+ slug = typeof active.slug === 'string' ? active.slug : '';
2693
+ } catch (error) {
2694
+ return;
2695
+ }
2696
+ if (!slug || slug.length > 48 || !slugPattern.test(slug)) return;
2697
+ const taskDir = path.join(process.cwd(), '.ai.local', 'team', 'tasks', slug);
2698
+ if (!fs.existsSync(path.join(taskDir, 'status.json'))) return;
2699
+ const script = path.join(process.cwd(), '.ai.local', 'scripts', 'team-db.mjs');
2700
+ if (!fs.existsSync(script)) return;
2701
+ if (!teamDbSqliteAvailable(env)) {
2702
+ process.stderr.write('team-db: projection skipped (node:sqlite unavailable); file-only mode\n');
2703
+ return;
2704
+ }
2705
+ const result = spawnSync(
2706
+ process.execPath,
2707
+ ['.ai.local/scripts/team-db.mjs', 'sync', '--slug', slug, '--quiet', '--no-rebuild', '--deadline-ms', '4500'],
2708
+ { cwd: process.cwd(), env: env, encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'pipe'] },
2709
+ );
2710
+ if (result.error && result.error.code === 'ETIMEDOUT') {
2711
+ teamDbLogFailure(env, 'E_PROJECTION_TIMEOUT', 'projection exceeded 5000 ms and was killed');
2712
+ return;
2713
+ }
2714
+ if (result.error) {
2715
+ teamDbLogFailure(env, 'E_PROJECTION_FAILED', 'projection could not start: ' + String(result.error.code || 'unknown'));
2716
+ return;
2717
+ }
2718
+ if (typeof result.status === 'number' && result.status !== 0) {
2719
+ teamDbLogFailure(env, 'E_PROJECTION_FAILED', 'projection exited ' + result.status);
2720
+ }
2721
+ } catch (error) {
2722
+ /* the seam never fails the stop */
2723
+ }
2724
+ }
2725
+
2726
+ teamDbProject();
2727
+ // <<<team-db-projection-end>>>
2728
+ // --- end TEAM_DB_PROJECTION ---------------------------------------------------
2729
+
2621
2730
  // Ratchet: off for `light` pipelines and `spike` intents. A policy skip is
2622
2731
  // silent on purpose — a warning on every light receipt would make the
2623
2732
  // containment warnings below unreadable.
@@ -90,6 +90,16 @@ printf '%s\n' '{"status":"completed","action":"end_human_gate","activateNext":tr
90
90
 
91
91
  Same JSON on Claude, Mavis, or OpenCode: `bash .<tool>/hooks/chain-team-phases.sh`.
92
92
 
93
+ ## Database projection
94
+
95
+ `team-db.mjs` projects this tree into `.ai.local/team/team.db` (SQLite, WAL). The files remain authoritative: the database is rebuildable and git-ignored (`team.db`, `team.db-wal`, `team.db-shm`, `team-db-errors.log`).
96
+
97
+ - Write points: the chain hook after its file writes, and `manifest.mjs` after a receipt. Both run one bounded 5 s child; a failure logs one line and never fails the file write.
98
+ - No agent writes lifecycle fields through the database. `status.json` / `metrics.json` stay hook-owned.
99
+ - `AI_RULES_TEAM_DB_DISABLE=1` stops every write point and `serve`; a runtime without `node:sqlite` stays file-only with exit 0.
100
+ - Inspect: `node .ai.local/scripts/team-db.mjs sync`, then `check`; `serve` opens the read-only dashboard at `http://127.0.0.1:4178`.
101
+ - Never commit the database. Delete `team.db*` and run `sync` to rebuild.
102
+
93
103
  ## Contracts
94
104
 
95
105
  - **Manifest field name:** receipts go in `artifacts[]`. Anything written under `entries` is ignored — the hook reads only `artifacts` and prints a dual-read warning naming the file. See `agent-team/agent-artifact-contracts.md` § Schema field name.
@@ -2613,6 +2613,115 @@ if (!input || input.status !== 'completed') {
2613
2613
  process.exit(0);
2614
2614
  }
2615
2615
 
2616
+ // --- TEAM_DB_PROJECTION -------------------------------------------------------
2617
+ // The status, metrics, compaction and focus writes are already durable when this
2618
+ // postflight starts. The projection is a bounded child process: it must never
2619
+ // fail this stop, never change hook stdout/stderr beyond the capability line,
2620
+ // and never write a task file. A disabled switch, a missing script, or a
2621
+ // runtime without `node:sqlite` is a skip; a child failure is one log line.
2622
+ // This is a plain region marker, not a `hook-slot`: the block is identical in
2623
+ // all 40 rendered bodies and needs no per-stack fragment.
2624
+ // <<<team-db-projection>>>
2625
+ function teamDbTruthy(value) {
2626
+ if (typeof value !== 'string') return false;
2627
+ const normalized = value.trim().toLowerCase();
2628
+ return normalized === '1' || normalized === 'true' || normalized === 'yes';
2629
+ }
2630
+
2631
+ function teamDbLogPath(env) {
2632
+ const override = typeof env.AI_RULES_TEAM_DB_LOG === 'string' ? env.AI_RULES_TEAM_DB_LOG.trim() : '';
2633
+ if (override) return path.resolve(override);
2634
+ return path.join(process.cwd(), '.ai.local', 'team', 'team-db-errors.log');
2635
+ }
2636
+
2637
+ function teamDbLogPhase(env) {
2638
+ const value = typeof env.AI_RULES_TEAM_DB_SEAM === 'string' ? env.AI_RULES_TEAM_DB_SEAM.trim() : '';
2639
+ return value === 'hook' || value === 'receipt' || value === 'cli' || value === 'serve' ? value : 'hook';
2640
+ }
2641
+
2642
+ // One line per failure, newest 200 lines and at most 64 KiB. Never a prompt
2643
+ // body: only the code and the message this block owns.
2644
+ function teamDbLogFailure(env, code, message) {
2645
+ try {
2646
+ const target = teamDbLogPath(env);
2647
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2648
+ const line = new Date().toISOString() + ' ' + code + ' ' + teamDbLogPhase(env) + ' ' + message;
2649
+ fs.appendFileSync(target, line + '\n');
2650
+ let content = fs.readFileSync(target, 'utf8');
2651
+ let lines = content.split('\n').filter(function (entry) { return entry.length > 0; });
2652
+ if (lines.length > 200) lines = lines.slice(lines.length - 200);
2653
+ while (Buffer.byteLength(lines.join('\n') + '\n', 'utf8') > 65536 && lines.length > 1) lines.shift();
2654
+ content = lines.join('\n') + (lines.length > 0 ? '\n' : '');
2655
+ fs.writeFileSync(target, content);
2656
+ } catch (error) {
2657
+ /* a log failure is not a stop failure */
2658
+ }
2659
+ }
2660
+
2661
+ function teamDbSqliteAvailable(env) {
2662
+ if (teamDbTruthy(env.AI_RULES_TEAM_DB_FORCE_FALLBACK)) return false;
2663
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(process.versions.node || ''));
2664
+ if (!match) return false;
2665
+ const major = Number(match[1]);
2666
+ const minor = Number(match[2]);
2667
+ if (major < 22) return false;
2668
+ if (major === 22 && minor < 13) return false;
2669
+ try {
2670
+ const sqlite = require('node:sqlite');
2671
+ return typeof sqlite.DatabaseSync === 'function';
2672
+ } catch (error) {
2673
+ return false;
2674
+ }
2675
+ }
2676
+
2677
+ function teamDbProject() {
2678
+ try {
2679
+ const env = process.env;
2680
+ if (teamDbTruthy(env.AI_RULES_TEAM_DB_DISABLE)) return;
2681
+ // Same pattern as POSTFLIGHT_SLUG_RE above: the slug is re-derived from
2682
+ // `active-task.json` on this path too, so it cannot escape the tree.
2683
+ const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2684
+ let slug = '';
2685
+ try {
2686
+ const active = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'active-task.json'), 'utf8'));
2687
+ slug = typeof active.slug === 'string' ? active.slug : '';
2688
+ } catch (error) {
2689
+ return;
2690
+ }
2691
+ if (!slug || slug.length > 48 || !slugPattern.test(slug)) return;
2692
+ const taskDir = path.join(process.cwd(), '.ai.local', 'team', 'tasks', slug);
2693
+ if (!fs.existsSync(path.join(taskDir, 'status.json'))) return;
2694
+ const script = path.join(process.cwd(), '.ai.local', 'scripts', 'team-db.mjs');
2695
+ if (!fs.existsSync(script)) return;
2696
+ if (!teamDbSqliteAvailable(env)) {
2697
+ process.stderr.write('team-db: projection skipped (node:sqlite unavailable); file-only mode\n');
2698
+ return;
2699
+ }
2700
+ const result = spawnSync(
2701
+ process.execPath,
2702
+ ['.ai.local/scripts/team-db.mjs', 'sync', '--slug', slug, '--quiet', '--no-rebuild', '--deadline-ms', '4500'],
2703
+ { cwd: process.cwd(), env: env, encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'pipe'] },
2704
+ );
2705
+ if (result.error && result.error.code === 'ETIMEDOUT') {
2706
+ teamDbLogFailure(env, 'E_PROJECTION_TIMEOUT', 'projection exceeded 5000 ms and was killed');
2707
+ return;
2708
+ }
2709
+ if (result.error) {
2710
+ teamDbLogFailure(env, 'E_PROJECTION_FAILED', 'projection could not start: ' + String(result.error.code || 'unknown'));
2711
+ return;
2712
+ }
2713
+ if (typeof result.status === 'number' && result.status !== 0) {
2714
+ teamDbLogFailure(env, 'E_PROJECTION_FAILED', 'projection exited ' + result.status);
2715
+ }
2716
+ } catch (error) {
2717
+ /* the seam never fails the stop */
2718
+ }
2719
+ }
2720
+
2721
+ teamDbProject();
2722
+ // <<<team-db-projection-end>>>
2723
+ // --- end TEAM_DB_PROJECTION ---------------------------------------------------
2724
+
2616
2725
  // Ratchet: off for `light` pipelines and `spike` intents. A policy skip is
2617
2726
  // silent on purpose — a warning on every light receipt would make the
2618
2727
  // containment warnings below unreadable.
@@ -90,6 +90,16 @@ printf '%s\n' '{"status":"completed","action":"end_human_gate","activateNext":tr
90
90
 
91
91
  Same JSON on Claude, Mavis, or OpenCode: `bash .<tool>/hooks/chain-team-phases.sh`.
92
92
 
93
+ ## Database projection
94
+
95
+ `team-db.mjs` projects this tree into `.ai.local/team/team.db` (SQLite, WAL). The files remain authoritative: the database is rebuildable and git-ignored (`team.db`, `team.db-wal`, `team.db-shm`, `team-db-errors.log`).
96
+
97
+ - Write points: the chain hook after its file writes, and `manifest.mjs` after a receipt. Both run one bounded 5 s child; a failure logs one line and never fails the file write.
98
+ - No agent writes lifecycle fields through the database. `status.json` / `metrics.json` stay hook-owned.
99
+ - `AI_RULES_TEAM_DB_DISABLE=1` stops every write point and `serve`; a runtime without `node:sqlite` stays file-only with exit 0.
100
+ - Inspect: `node .ai.local/scripts/team-db.mjs sync`, then `check`; `serve` opens the read-only dashboard at `http://127.0.0.1:4178`.
101
+ - Never commit the database. Delete `team.db*` and run `sync` to rebuild.
102
+
93
103
  ## Contracts
94
104
 
95
105
  - **Manifest field name:** receipts go in `artifacts[]`. Anything written under `entries` is ignored — the hook reads only `artifacts` and prints a dual-read warning naming the file. See `agent-team/agent-artifact-contracts.md` § Schema field name.