@chemx/starter-kit 26.9.24-393 → 26.9.25-1337

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 (107) hide show
  1. package/README.md +70 -10
  2. package/blueprints/atoms/a-button.svelte +30 -0
  3. package/blueprints/atoms/a-button.tsx +36 -0
  4. package/blueprints/molecule-capsule/m-chemx-badge/m-chemx-badge.svelte +35 -0
  5. package/blueprints/molecule-capsule/m-sample-card.spec.ts +10 -4
  6. package/blueprints/molecule-capsule/m-sample-card.svelte +58 -0
  7. package/blueprints/molecule-capsule/m-sample-card.tsx +3 -3
  8. package/blueprints/molecule-capsule/m-sample-card.vue +60 -0
  9. package/blueprints/view-template.svelte +18 -0
  10. package/blueprints/view-template.vue +18 -0
  11. package/blueprints/workflows/chemx-audit.yml +36 -0
  12. package/cli/audit/ast-visitors.js +25 -13
  13. package/cli/audit/csharp-analyzer.js +80 -0
  14. package/cli/audit/extended-text-patterns.js +11 -2
  15. package/cli/audit/pattern-detector.js +5 -3
  16. package/cli/audit/pattern-detector.spec.js +17 -0
  17. package/cli/audit/reporter-grades.js +1 -0
  18. package/cli/audit/reporter-markdown.js +2 -0
  19. package/cli/audit/reporter-sections.js +3 -0
  20. package/cli/audit/rules-registry.js +27 -0
  21. package/cli/audit/rules.js +14 -3
  22. package/cli/audit/rules.spec.js +27 -0
  23. package/cli/audit/structural-weight-evaluator.js +121 -0
  24. package/cli/audit/structural-weight.js +92 -0
  25. package/cli/audit/structural-weight.spec.js +116 -0
  26. package/cli/audit-preflight-scope.js +4 -1
  27. package/cli/audit.js +9 -10
  28. package/cli/commands/cmd-audit.js +1 -1
  29. package/cli/commands/cmd-router.js +17 -2
  30. package/cli/commands-schema.js +36 -0
  31. package/cli/config/config.spec.js +51 -0
  32. package/cli/config/index.js +37 -0
  33. package/cli/config/loader.js +83 -0
  34. package/cli/config/profiles.js +56 -0
  35. package/cli/config.spec.js +1 -0
  36. package/cli/create.js +21 -8
  37. package/cli/create.spec.js +91 -0
  38. package/cli/generator-help.js +48 -0
  39. package/cli/generator-indexer.js +41 -0
  40. package/cli/generator.js +8 -43
  41. package/cli/generator.spec.js +29 -0
  42. package/cli/help.d.ts +2 -0
  43. package/cli/help.js +64 -0
  44. package/cli/help.spec.js +54 -1
  45. package/cli/installer-templates.js +8 -3
  46. package/cli/languages.js +122 -0
  47. package/cli/languages.spec.js +44 -0
  48. package/cli/mcp/tools-patch.js +7 -5
  49. package/cli/mcp/tools-team-tasks.js +56 -10
  50. package/cli/polyglot.spec.js +111 -0
  51. package/cli/reader-shorthand.spec.js +2 -2
  52. package/cli/scaffold-frameworks.js +133 -0
  53. package/cli/scaffold.js +102 -41
  54. package/cli/search-ast.js +41 -9
  55. package/cli/search-db.js +2 -8
  56. package/cli/search-queries-semantic.js +28 -9
  57. package/cli/search-tokenizer.js +52 -0
  58. package/cli/search.js +2 -5
  59. package/cli/search.spec.js +51 -3
  60. package/cli/team/team-adversarial-locks.spec.js +71 -0
  61. package/cli/team/team-commands-lock.js +64 -0
  62. package/cli/team/team-commands-vds.js +70 -0
  63. package/cli/team/team-commands.js +86 -24
  64. package/cli/team/team-db-lock-promotion.js +29 -18
  65. package/cli/team/team-db-locks.js +54 -43
  66. package/cli/team/team-db-task-helpers.js +18 -0
  67. package/cli/team/team-db-tasks.js +45 -51
  68. package/cli/team/team-db-transaction.js +52 -0
  69. package/cli/team/team-flags.js +4 -1
  70. package/cli/team/team-format.js +148 -0
  71. package/cli/team/team-memory.js +99 -13
  72. package/cli/team/team-memory.spec.js +49 -0
  73. package/cli/team/team-multiprocess-concurrency.spec.js +193 -0
  74. package/cli/team/team-release-train.js +65 -0
  75. package/cli/team/team-release-train.spec.js +91 -0
  76. package/cli/team/team-schema-vds.js +39 -0
  77. package/cli/team/team-schema.js +21 -23
  78. package/cli/team/team-tasks-asana.spec.js +60 -0
  79. package/cli/team/team-triage.js +12 -0
  80. package/cli/team/team-vds.js +88 -0
  81. package/cli/team/team-vds.spec.js +125 -0
  82. package/cli/team/team-verification-gate.spec.js +27 -0
  83. package/cli/theme.js +1 -0
  84. package/cli/ui-actions-vds.js +48 -0
  85. package/cli/ui-actions.js +1 -0
  86. package/cli/ui-client-api.js +8 -0
  87. package/cli/ui-client-script.js +33 -29
  88. package/cli/ui-dev-watcher.js +61 -0
  89. package/cli/ui-direct-routes.spec.js +55 -0
  90. package/cli/ui-handlers.js +6 -7
  91. package/cli/ui-index.html +416 -26
  92. package/cli/ui-kanban.spec.js +11 -0
  93. package/cli/ui-server-routes.js +14 -6
  94. package/cli/ui-server.js +17 -21
  95. package/cli/ui-sse.js +23 -10
  96. package/cli/ui-sse.spec.js +26 -0
  97. package/cli/ui-styles.js +20 -4
  98. package/cli/ui-template-kanban.js +23 -27
  99. package/cli/ui-template-task-sheet.js +87 -0
  100. package/cli/ui-template-vds-badges.js +34 -0
  101. package/cli/ui-template.js +13 -10
  102. package/cli/verify-helpers.js +192 -0
  103. package/cli/verify.js +132 -176
  104. package/cli/verify.spec.js +96 -0
  105. package/package.json +8 -4
  106. package/scripts/pre-commit.sh +12 -3
  107. package/docs/CHANGELOG.md +0 -332
@@ -1,21 +1,17 @@
1
1
  /**
2
2
  * Chemical X Protocol: Swarm Task DAG Management
3
- * Handles task lifecycle, claims, dependency verification, and status in SQLite
3
+ * Handles task lifecycle, claims, dependency verification, and VDS status in SQLite
4
4
  */
5
5
 
6
6
  import {
7
- normalizeAgentId,
8
- parseTaskRow,
9
- checkDependenciesMet,
10
- evaluateClaim,
11
- executeStatusUpdate,
12
- buildTaskListQuery
7
+ normalizeAgentId, parseTaskRow, checkDependenciesMet,
8
+ evaluateClaim, executeStatusUpdate, buildTaskListQuery
13
9
  } from './team-db-task-helpers.js';
10
+ import { withImmediateTransaction } from './team-db-transaction.js';
11
+ import { generateTaskPermalink } from './team-vds.js';
14
12
 
15
13
  export const getTask = (db, taskId) => {
16
- const hasDb = Boolean(db);
17
- const hasTaskId = Boolean(taskId);
18
- const canGet = hasDb && hasTaskId;
14
+ const canGet = Boolean(db) && Boolean(taskId);
19
15
  if (!canGet) return null;
20
16
  const row = db.prepare('SELECT * FROM agent_tasks WHERE id = ?').get(Number(taskId));
21
17
  return parseTaskRow(row);
@@ -24,18 +20,15 @@ export const getTask = (db, taskId) => {
24
20
  export const areTaskDependenciesMet = (db, taskId) => checkDependenciesMet(db, taskId, getTask);
25
21
 
26
22
  export const createTask = (db, taskData) => {
27
- const hasDb = Boolean(db);
28
- const hasTitle = Boolean(taskData?.title);
29
- const canCreate = hasDb && hasTitle;
23
+ const canCreate = Boolean(db) && Boolean(taskData?.title);
30
24
  if (!canCreate) return null;
31
25
 
32
26
  const now = Date.now();
33
27
  const sql = `INSERT INTO agent_tasks (
34
- title, description, tier, target_path, target_symbol,
35
- status, priority, assigned_agent_id, blocked_reason,
36
- parent_id, dependencies, created_at, updated_at, result_payload,
37
- origin_type, rule_id, violation_snapshot, diff_receipt
38
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
28
+ title, description, tier, target_path, target_symbol, status, priority, assigned_agent_id,
29
+ blocked_reason, parent_id, dependencies, created_at, updated_at, result_payload, origin_type,
30
+ rule_id, violation_snapshot, diff_receipt, moscow, vds_priority, vds_phase, vds_status, task_url, sprint_tag
31
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
39
32
  const info = db.prepare(sql).run(
40
33
  taskData.title, taskData.description || '', taskData.tier || '',
41
34
  taskData.target_path || null, taskData.target_symbol || '', taskData.status || 'queued',
@@ -44,55 +37,56 @@ export const createTask = (db, taskData) => {
44
37
  JSON.stringify(taskData.dependencies || []), now, now,
45
38
  JSON.stringify(taskData.result_payload || {}),
46
39
  taskData.origin_type || (taskData.target_path ? 'audit' : 'manual'),
47
- taskData.rule_id || '',
48
- JSON.stringify(taskData.violation_snapshot || {}),
49
- JSON.stringify(taskData.diff_receipt || {})
40
+ taskData.rule_id || '', JSON.stringify(taskData.violation_snapshot || {}),
41
+ JSON.stringify(taskData.diff_receipt || {}),
42
+ taskData.moscow || 'must', taskData.vds_priority || 'medium',
43
+ taskData.vds_phase || 'planning', taskData.vds_status || 'ready',
44
+ taskData.task_url || '', taskData.sprint_tag || ''
50
45
  );
51
- return getTask(db, info.lastInsertRowid);
46
+ const createdId = info.lastInsertRowid;
47
+ if (!taskData.task_url) {
48
+ db.prepare('UPDATE agent_tasks SET task_url = ? WHERE id = ?').run(generateTaskPermalink(createdId), createdId);
49
+ }
50
+ return getTask(db, createdId);
52
51
  };
53
52
 
54
53
  export const claimTask = (db, taskId, agentId) => {
55
- const hasDb = Boolean(db);
56
- const hasTaskId = Boolean(taskId);
57
- const hasAgentId = Boolean(agentId);
58
- const canClaim = hasDb && hasTaskId && hasAgentId;
54
+ const canClaim = Boolean(db) && Boolean(taskId) && Boolean(agentId);
59
55
  if (!canClaim) return { success: false, reason: 'missing_args' };
60
56
 
61
57
  const cleanId = normalizeAgentId(agentId);
62
- const task = getTask(db, taskId);
63
- const depsMet = areTaskDependenciesMet(db, taskId);
64
- const claimCheck = evaluateClaim(task, cleanId, depsMet);
65
- if (!claimCheck.allowed) {
66
- const { allowed, ...failDetails } = claimCheck;
67
- return { success: false, ...failDetails };
68
- }
58
+ return withImmediateTransaction(db, () => {
59
+ const task = getTask(db, taskId);
60
+ const depsMet = areTaskDependenciesMet(db, taskId);
61
+ const claimCheck = evaluateClaim(task, cleanId, depsMet);
62
+ if (!claimCheck.allowed) {
63
+ const { allowed, ...failDetails } = claimCheck;
64
+ return { success: false, ...failDetails };
65
+ }
69
66
 
70
- const now = Date.now();
71
- const sql = "UPDATE agent_tasks SET assigned_agent_id = ?, status = 'in_progress', updated_at = ? WHERE id = ? AND status = 'queued' AND (assigned_agent_id IS NULL OR assigned_agent_id = ?);";
72
- const info = db.prepare(sql).run(cleanId, now, Number(taskId), cleanId);
73
- if (info.changes !== 1) return { success: false, reason: 'already_claimed' };
74
- db.prepare("UPDATE agents SET current_task_id = ?, status = 'busy' WHERE id = ?").run(Number(taskId), cleanId);
75
- return { success: true, task: getTask(db, taskId) };
67
+ const now = Date.now();
68
+ const sql = "UPDATE agent_tasks SET assigned_agent_id = ?, status = 'in_progress', updated_at = ? WHERE id = ? AND status = 'queued' AND (assigned_agent_id IS NULL OR assigned_agent_id = ?);";
69
+ const info = db.prepare(sql).run(cleanId, now, Number(taskId), cleanId);
70
+ if (info.changes !== 1) return { success: false, reason: 'already_claimed' };
71
+ db.prepare("UPDATE agents SET current_task_id = ?, status = 'busy' WHERE id = ?").run(Number(taskId), cleanId);
72
+ return { success: true, task: getTask(db, taskId) };
73
+ });
76
74
  };
77
75
 
78
76
  export const updateTaskStatus = (db, taskId, status, options = {}) => {
79
- const hasDb = Boolean(db);
80
- const hasTaskId = Boolean(taskId);
81
- const hasStatus = Boolean(status);
82
- const canUpdate = hasDb && hasTaskId && hasStatus;
77
+ const canUpdate = Boolean(db) && Boolean(taskId) && Boolean(status);
83
78
  if (!canUpdate) return null;
84
79
 
85
- const task = getTask(db, taskId);
86
- const hasTask = Boolean(task);
87
- if (!hasTask) return null;
88
-
89
- executeStatusUpdate(db, taskId, status, options, task);
90
- return getTask(db, taskId);
80
+ return withImmediateTransaction(db, () => {
81
+ const task = getTask(db, taskId);
82
+ if (!task) return null;
83
+ executeStatusUpdate(db, taskId, status, options, task);
84
+ return getTask(db, taskId);
85
+ });
91
86
  };
92
87
 
93
88
  export const listTasks = (db, filter = {}) => {
94
- const hasDb = Boolean(db);
95
- if (!hasDb) return [];
89
+ if (!db) return [];
96
90
  const { query, params } = buildTaskListQuery(filter);
97
91
  return db.prepare(query).all(...params).map(parseTaskRow);
98
92
  };
@@ -0,0 +1,52 @@
1
+ export const isPidAlive = (pid) => {
2
+ const isValidPid = typeof pid === 'number' && pid > 0;
3
+ if (!isValidPid) return true;
4
+ try {
5
+ process.kill(pid, 0);
6
+ return true;
7
+ } catch (err) {
8
+ const isNoSuchProcess = err && err.code === 'ESRCH';
9
+ return !isNoSuchProcess;
10
+ }
11
+ };
12
+
13
+ export const withImmediateTransaction = (db, callback, maxRetries = 5) => {
14
+ const hasDb = Boolean(db);
15
+ const isFunction = typeof callback === 'function';
16
+ const canExecute = hasDb && isFunction;
17
+ if (!canExecute) throw new Error('Database connection and callback required.');
18
+
19
+ let attempts = 0;
20
+ while (attempts < maxRetries) {
21
+ attempts++;
22
+ let inTransaction = false;
23
+ try {
24
+ db.exec('BEGIN IMMEDIATE;');
25
+ inTransaction = true;
26
+ const result = callback();
27
+ db.exec('COMMIT;');
28
+ inTransaction = false;
29
+ return result;
30
+ } catch (err) {
31
+ if (inTransaction) {
32
+ try {
33
+ db.exec('ROLLBACK;');
34
+ } catch (rollbackErr) {
35
+ const rollbackNotice = rollbackErr?.message || String(rollbackErr);
36
+ process.stderr.write(`[SWARM] Transaction rollback failed: ${rollbackNotice}\n`);
37
+ }
38
+ }
39
+ const isSqliteBusy = err && (err.code === 'SQLITE_BUSY' || String(err.message).includes('busy'));
40
+ const hasRetriesLeft = attempts < maxRetries;
41
+ const canRetry = isSqliteBusy && hasRetriesLeft;
42
+
43
+ if (canRetry) {
44
+ const sleepMs = Math.floor(10 + Math.random() * 20);
45
+ const start = Date.now();
46
+ while (Date.now() - start < sleepMs) {}
47
+ continue;
48
+ }
49
+ throw err;
50
+ }
51
+ }
52
+ };
@@ -15,7 +15,8 @@ export const parseFlags = (args = []) => {
15
15
  isCompact: args.includes('--compact'),
16
16
  markRead: args.includes('--mark-read'),
17
17
  force: args.includes('--force') || args.includes('-f'),
18
- noTargetConfirm: args.includes('--no-target-confirm')
18
+ noTargetConfirm: args.includes('--no-target-confirm'),
19
+ help: args.includes('--help') || args.includes('-h')
19
20
  };
20
21
  for (let i = 0; i < args.length; i++) {
21
22
  const arg = args[i];
@@ -53,6 +54,8 @@ export const parseFlags = (args = []) => {
53
54
  if (arg.startsWith('--prio=') || arg.startsWith('--priority=')) flags.priority = parseInt(arg.split('=')[1], 10);
54
55
  if ((arg === '--prio' || arg === '--priority') && hasNext) flags.priority = parseInt(nextArg, 10);
55
56
  if (arg.startsWith('--purpose=')) flags.purpose = arg.split('=')[1];
57
+ if (arg.startsWith('--pid=')) flags.pid = parseInt(arg.split('=')[1], 10);
58
+ if (arg === '--pid' && hasNext) flags.pid = parseInt(nextArg, 10);
56
59
  if (arg.startsWith('--tokens=')) flags.tokens = parseInt(arg.split('=')[1], 10);
57
60
  if (arg.startsWith('--prompt-tokens=')) flags.promptTokens = parseInt(arg.split('=')[1], 10);
58
61
  if (arg.startsWith('--completion-tokens=')) flags.completionTokens = parseInt(arg.split('=')[1], 10);
@@ -119,3 +119,151 @@ export const formatMailboxCard = (mailbox) => {
119
119
  lines.push(`\x1b[90m${'-'.repeat(54)}\x1b[0m\n`);
120
120
  return lines.join('\n');
121
121
  };
122
+
123
+ export const formatTaskDetailCard = (task, events = []) => {
124
+ if (!task) return ' (Task not found)\n';
125
+ const lines = [''];
126
+ const statusColors = {
127
+ queued: '\x1b[33mqueued\x1b[0m',
128
+ in_progress: '\x1b[36min_progress\x1b[0m',
129
+ review: '\x1b[35mreview\x1b[0m',
130
+ done: '\x1b[32mdone\x1b[0m',
131
+ completed: '\x1b[32mcompleted\x1b[0m',
132
+ blocked: '\x1b[31mblocked\x1b[0m'
133
+ };
134
+ const statusStr = statusColors[task.status] || task.status;
135
+ const pStr = `P${task.priority || 2}`;
136
+ const tierStr = task.tier ? `[${task.tier}]` : '';
137
+
138
+ lines.push(`\x1b[1m\x1b[36m📋 [Chemical X Task #${task.id}]\x1b[0m \x1b[1m${task.title}\x1b[0m`);
139
+ lines.push(`\x1b[90m${'─'.repeat(58)}\x1b[0m`);
140
+ lines.push(` \x1b[1mStatus:\x1b[0m ${statusStr} │ \x1b[1mPriority:\x1b[0m ${pStr} │ \x1b[1mTier:\x1b[0m ${tierStr || 'utility'}`);
141
+ lines.push(` \x1b[1mAssignee:\x1b[0m ${task.assigned_agent_id || '(unassigned)'} │ \x1b[1mOrigin:\x1b[0m ${task.origin_type || 'manual'}`);
142
+
143
+ if (task.target_path) {
144
+ lines.push(` \x1b[1mTarget:\x1b[0m ${task.target_path}`);
145
+ }
146
+ if (task.blocked_reason) {
147
+ lines.push(` \x1b[1m\x1b[31mBlocker:\x1b[0m \x1b[33m${task.blocked_reason}\x1b[0m`);
148
+ }
149
+
150
+ const tok = task.total_tokens || ((task.prompt_tokens || 0) + (task.completion_tokens || 0));
151
+ if (tok > 0 || task.cost_usd > 0) {
152
+ lines.push(` \x1b[1mTelemetry:\x1b[0m ${tok.toLocaleString()} tokens │ \x1b[32m${Number(task.cost_usd || 0).toFixed(4)}\x1b[0m`);
153
+ }
154
+
155
+ if (task.diff_receipt?.verified || task.result_payload?.verified) {
156
+ const r = task.diff_receipt?.healthAfter ? task.diff_receipt : task.result_payload;
157
+ lines.push(` \x1b[32m🛡️ AST Verification:\x1b[0m Clean (Health: ${r.healthAfter ?? 100}/100)`);
158
+ }
159
+
160
+ lines.push('', ' \x1b[1mActivity & Status Stream (Asana Timeline):\x1b[0m');
161
+ if (events.length === 0) {
162
+ lines.push(' \x1b[90m(No updates recorded yet)\x1b[0m');
163
+ } else {
164
+ for (const ev of events) {
165
+ const timeStr = new Date(ev.timestamp).toLocaleTimeString();
166
+ let icon = '•';
167
+ let tag = ev.event_type;
168
+ if (ev.event_type === 'task_created') { icon = '⏳'; tag = 'created'; }
169
+ else if (ev.event_type === 'task_status_updated') { icon = '🔄'; tag = 'status_update'; }
170
+ else if (ev.event_type === 'task_reassigned') { icon = '👤'; tag = 'reassigned'; }
171
+ else if (ev.event_type === 'task_completed') { icon = '✅'; tag = 'completed'; }
172
+ else if (ev.event_type === 'comment' || ev.event_type === 'status_update') { icon = '💬'; tag = 'update'; }
173
+
174
+ lines.push(` \x1b[90m[${timeStr}]\x1b[0m ${icon} \x1b[36m${ev.author_id}\x1b[0m \x1b[90m(${tag})\x1b[0m`);
175
+ lines.push(` ${ev.message}`);
176
+ }
177
+ }
178
+
179
+ lines.push(`\x1b[90m${'─'.repeat(58)}\x1b[0m\n`);
180
+ return lines.join('\n');
181
+ };
182
+
183
+ export const formatTeamHelpCard = () => {
184
+ const lines = [
185
+ '',
186
+ '\x1b[1m\x1b[36m⚡ [Chemical X] Multi-Agent Swarm Orchestration (team)\x1b[0m',
187
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m`,
188
+ ' \x1b[1mUsage:\x1b[0m chemx team <command> [options]',
189
+ '',
190
+ ' \x1b[1mCommands:\x1b[0m',
191
+ ' \x1b[32mstatus\x1b[0m Display swarm agent, task, and lock status card',
192
+ ' \x1b[32mtask\x1b[0m [action] Manage agent tasks (list, show, add, claim, done, update)',
193
+ ' \x1b[32mlock\x1b[0m [acquire|release] Acquire or release a mutual exclusion file lock',
194
+ ' \x1b[32munlock\x1b[0m <file> Release a file lock held by an agent',
195
+ ' \x1b[32mfeed\x1b[0m View swarm feed event timeline',
196
+ ' \x1b[32mpost\x1b[0m <message> Post broadcast message to swarm feed',
197
+ ' \x1b[32minbox\x1b[0m [@agent] View agent mailbox and notifications',
198
+ ' \x1b[32mdm\x1b[0m <@agent> <msg> Send direct message to another agent',
199
+ ' \x1b[32mtokens\x1b[0m Inspect token consumption and telemetry breakdown',
200
+ ' \x1b[32mtriage\x1b[0m Generate tasks automatically from AST audit hazards',
201
+ ' \x1b[32mbenchmark\x1b[0m Run memory and token reduction ablation benchmark',
202
+ ' \x1b[32mtrain\x1b[0m Train/evaluate vector and pattern indices',
203
+ '',
204
+ ' \x1b[1mGlobal Options:\x1b[0m',
205
+ ' \x1b[33m--as\x1b[0m <@agent> Execute action as specified agent handle',
206
+ ' \x1b[33m--json\x1b[0m Output machine-readable JSON format',
207
+ ' \x1b[33m--help, -h\x1b[0m Show help for team or specific subcommands',
208
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m\n`
209
+ ];
210
+ return lines.join('\n');
211
+ };
212
+
213
+ export const formatTaskHelpCard = () => {
214
+ const lines = [
215
+ '',
216
+ '\x1b[1m\x1b[36m⚡ [Chemical X] Task Coordination Commands (team task)\x1b[0m',
217
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m`,
218
+ ' \x1b[1mUsage:\x1b[0m chemx team task <action> [arguments] [options]',
219
+ '',
220
+ ' \x1b[1mActions:\x1b[0m',
221
+ ' \x1b[32mlist\x1b[0m List swarm tasks (default action)',
222
+ ' \x1b[32mshow\x1b[0m <taskId> Display full details and activity stream for a task',
223
+ ' \x1b[32madd\x1b[0m "<title>" Create a new task in the queue',
224
+ ' \x1b[32mclaim\x1b[0m <taskId> Claim an unassigned task for an agent',
225
+ ' \x1b[32mdone\x1b[0m <taskId> Complete a task with automatic verification audit',
226
+ ' \x1b[32mupdate\x1b[0m <taskId> [status] Update task status (in_progress, blocked, done)',
227
+ ' \x1b[32mcomment\x1b[0m <taskId> <msg> Post a comment or status update to a task',
228
+ ' \x1b[32mtriage\x1b[0m Generate tasks from AST architectural hazards',
229
+ ' \x1b[32mreconcile\x1b[0m Auto-resolve tasks whose hazards have been fixed',
230
+ ' \x1b[32mset-target\x1b[0m <id> <path> Assign target file path to a task',
231
+ ' \x1b[32mvds-slot\x1b[0m <id> <moscow> <p> Set MoSCoW slot and priority on a task',
232
+ ' \x1b[32mtrace\x1b[0m <id> <url> Attach provenance trace URL to a task',
233
+ '',
234
+ ' \x1b[1mOptions:\x1b[0m',
235
+ ' \x1b[33m--as\x1b[0m <@agent> Agent handle (e.g. @agent-1)',
236
+ ' \x1b[33m--status\x1b[0m <status> Filter by status (todo, in_progress, blocked, done)',
237
+ ' \x1b[33m--agent\x1b[0m <@agent> Filter tasks assigned to agent',
238
+ ' \x1b[33m--prio\x1b[0m <1-5> Task priority filter or setting',
239
+ ' \x1b[33m--force, -f\x1b[0m Force complete task even with remaining hazards',
240
+ ' \x1b[33m--json\x1b[0m Output machine-readable JSON format',
241
+ ' \x1b[33m--help, -h\x1b[0m Show this help message',
242
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m\n`
243
+ ];
244
+ return lines.join('\n');
245
+ };
246
+
247
+ export const formatLockHelpCard = () => {
248
+ const lines = [
249
+ '',
250
+ '\x1b[1m\x1b[36m⚡ [Chemical X] Mutual Exclusion File Locking (team lock)\x1b[0m',
251
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m`,
252
+ ' \x1b[1mUsage:\x1b[0m chemx team lock [acquire|release] <filePath> [options]',
253
+ ' chemx team unlock <filePath> [options]',
254
+ '',
255
+ ' \x1b[1mActions:\x1b[0m',
256
+ ' \x1b[32macquire\x1b[0m <path> Acquire mutual exclusion lock (or enqueue in FIFO)',
257
+ ' \x1b[32mrelease\x1b[0m <path> Release lock and promote next FIFO waiter',
258
+ '',
259
+ ' \x1b[1mOptions:\x1b[0m',
260
+ ' \x1b[33m--as\x1b[0m <@agent> Agent handle acquiring/releasing lock (default: @agent)',
261
+ ' \x1b[33m--purpose\x1b[0m "<reason>" Reason or intent for acquiring lock',
262
+ ' \x1b[33m--priority\x1b[0m <1-5> Priority in FIFO wait queue (1 = highest, default: 2)',
263
+ ' \x1b[33m--pid\x1b[0m <pid> Optional process PID for crash-recovery lease reclamation',
264
+ ' \x1b[33m--json\x1b[0m Output machine-readable JSON format',
265
+ ' \x1b[33m--help, -h\x1b[0m Show this help message',
266
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m\n`
267
+ ];
268
+ return lines.join('\n');
269
+ };
@@ -17,7 +17,10 @@ export const recordMemoryInjection = (db, entry = {}) => {
17
17
  };
18
18
 
19
19
  export const recordMemoryUtilization = (db, { taskId, utilizedProvenance = [], causedRetry = false } = {}) => {
20
- if (!db || !taskId) return;
20
+ const hasDb = Boolean(db);
21
+ const hasTaskId = Boolean(taskId);
22
+ const canRecord = hasDb && hasTaskId;
23
+ if (!canRecord) return;
21
24
  if (causedRetry) db.prepare('UPDATE agent_memory_log SET caused_retry = 1 WHERE task_id = ?').run(taskId);
22
25
  for (const prov of utilizedProvenance) {
23
26
  db.prepare('UPDATE agent_memory_log SET was_utilized = 1 WHERE task_id = ? AND (provenance_path = ? OR provenance_path LIKE ?)').run(taskId, prov, `%${prov}%`);
@@ -51,14 +54,79 @@ export const calculateMemoryMetrics = (db) => {
51
54
 
52
55
  export const runAblationComparison = (db) => {
53
56
  const m = calculateMemoryMetrics(db);
54
- const turns = Math.max(10, m.totalCount || 10);
55
- const baseTokens = turns * 2500, memTokens = Math.max(turns * 70, m.totalInjectedTokens || 700);
56
- const tokensSaved = baseTokens - memTokens;
57
+ const row = db ? db.prepare(`
58
+ SELECT
59
+ COUNT(*) as totalTasks,
60
+ COALESCE(SUM(prompt_tokens), 0) as totalPromptTokens,
61
+ COALESCE(SUM(completion_tokens), 0) as totalCompletionTokens,
62
+ COALESCE(SUM(cached_tokens), 0) as totalCachedTokens,
63
+ COALESCE(SUM(cost_usd), 0) as totalCost
64
+ FROM agent_tasks
65
+ `).get() : null;
66
+
67
+ const taskStats = {
68
+ totalTasks: Number(row?.totalTasks || 0),
69
+ totalPromptTokens: Number(row?.totalPromptTokens || 0),
70
+ totalCompletionTokens: Number(row?.totalCompletionTokens || 0),
71
+ totalCachedTokens: Number(row?.totalCachedTokens || 0),
72
+ totalCost: Number(row?.totalCost || 0)
73
+ };
74
+
75
+ const hasTasks = taskStats.totalTasks > 0;
76
+ const hasMemories = m.totalCount > 0;
77
+ const hasRealData = Boolean(hasTasks || hasMemories);
78
+
79
+ if (!hasRealData) {
80
+ const turns = 10;
81
+ const baseTokens = turns * 2500;
82
+ const memTokens = 700;
83
+ const tokensSaved = baseTokens - memTokens;
84
+ const precisionGain = (100 / 12.0).toFixed(1) + 'x';
85
+ return {
86
+ hasRealData: false,
87
+ hasMeasuredTokens: false,
88
+ isSimulated: true,
89
+ workloadTurns: turns,
90
+ memoryEnabled: { mode: 'SQLite AST & Event Memory', tokensUsed: memTokens, staleRetryRatePct: 0.0, retrievalPrecisionPct: 100, astQualityScore: 100 },
91
+ memoryDisabled: { mode: 'Stateless Monolithic File Re-read', tokensUsed: baseTokens, staleRetryRatePct: 18.5, retrievalPrecisionPct: 12.0, astQualityScore: 84 },
92
+ delta: {
93
+ tokenReductionPct: Math.round((tokensSaved / baseTokens) * 100),
94
+ tokenReductionBasis: 'estimated_typical_usage',
95
+ isEstimated: true,
96
+ costAvoidedUsd: Number(((tokensSaved / 1000000) * 10.0).toFixed(4)),
97
+ retrievalPrecisionGainRatio: precisionGain,
98
+ staleRetriesEliminated: Math.round(turns * 0.185)
99
+ }
100
+ };
101
+ }
102
+
103
+ const turns = taskStats.totalTasks + m.totalCount;
104
+ const liveTokens = taskStats.totalPromptTokens + taskStats.totalCompletionTokens;
105
+ const hasMeasuredTokens = liveTokens > 0;
106
+ const memTokens = hasMeasuredTokens ? liveTokens : Math.max(turns * 70, m.totalInjectedTokens || 70);
107
+ const baseTokens = turns * 2500 + Math.round(memTokens * 0.5);
108
+ const tokensSaved = Math.max(0, baseTokens - memTokens);
109
+ const tokenReductionPct = baseTokens > 0 ? Math.round((tokensSaved / baseTokens) * 100) : 0;
110
+ const costAvoidedUsd = Number(((tokensSaved / 1000000) * 10.0).toFixed(4));
111
+ const precisionGainRatio = (m.precisionPct / 12.0).toFixed(1) + 'x';
112
+ const retryRatePct = m.totalCount > 0 ? Number(((m.staleRetries / m.totalCount) * 100).toFixed(1)) : 0.0;
113
+ const staleRetriesEliminated = Math.max(0, Math.round(turns * 0.185) - m.staleRetries);
114
+
57
115
  return {
116
+ hasRealData: true,
117
+ hasMeasuredTokens,
118
+ isSimulated: false,
58
119
  workloadTurns: turns,
59
- memoryEnabled: { mode: 'SQLite AST & Event Memory', tokensUsed: memTokens, staleRetryRatePct: 0.0, retrievalPrecisionPct: m.precisionPct, astQualityScore: 100 },
120
+ memoryEnabled: { mode: 'SQLite AST & Event Memory', tokensUsed: memTokens, staleRetryRatePct: retryRatePct, retrievalPrecisionPct: m.precisionPct, astQualityScore: 100 },
60
121
  memoryDisabled: { mode: 'Stateless Monolithic File Re-read', tokensUsed: baseTokens, staleRetryRatePct: 18.5, retrievalPrecisionPct: 12.0, astQualityScore: 84 },
61
- delta: { tokenReductionPct: Math.round((tokensSaved / baseTokens) * 100), costAvoidedUsd: Number(((tokensSaved / 1000000) * 10.0).toFixed(4)), retrievalPrecisionGainRatio: '7.8x', staleRetriesEliminated: Math.round(turns * 0.185) }
122
+ delta: {
123
+ tokenReductionPct,
124
+ tokenReductionBasis: hasMeasuredTokens ? 'measured' : 'estimated_typical_usage',
125
+ isEstimated: !hasMeasuredTokens,
126
+ costAvoidedUsd,
127
+ retrievalPrecisionGainRatio: precisionGainRatio,
128
+ staleRetriesEliminated
129
+ }
62
130
  };
63
131
  };
64
132
 
@@ -66,19 +134,37 @@ export const formatAblationCard = (a) => {
66
134
  const m = a.memoryEnabled;
67
135
  const d = a.memoryDisabled;
68
136
  const delta = a.delta;
137
+ const headerSuffix = a.hasRealData ? '[Live Project Telemetry]' : '[Reference Projection - Zero Local Tasks]';
69
138
  const lines = [
70
139
  '',
71
- '\x1b[1m\x1b[36m⚡ [Chemical X] Persistent Memory Ablation Benchmark\x1b[0m',
72
- `\x1b[90m${'─'.repeat(58)}\x1b[0m`,
140
+ `\x1b[1m\x1b[36m⚡ [Chemical X] Persistent Memory Ablation Benchmark ${headerSuffix}\x1b[0m`,
141
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m`
142
+ ];
143
+
144
+ if (!a.hasRealData) {
145
+ lines.push(
146
+ ' \x1b[33mℹ Notice: Zero local task history recorded. Displaying reference projection.\x1b[0m',
147
+ ' \x1b[33m Run team tasks and memory operations to generate live project benchmarks.\x1b[0m',
148
+ `\x1b[90m${'─'.repeat(58)}\x1b[0m`
149
+ );
150
+ }
151
+
152
+ const tokenReductionLabel = a.hasMeasuredTokens
153
+ ? `${delta.tokenReductionPct}% fewer tokens consumed (measured vs modeled baseline)`
154
+ : `${delta.tokenReductionPct}% fewer tokens consumed (estimated based on typical usage)`;
155
+ const costAvoidedSuffix = a.hasMeasuredTokens ? '' : ' (projected)';
156
+ const memoryTokensSuffix = a.hasMeasuredTokens ? '' : ' (est.)';
157
+
158
+ lines.push(
73
159
  ` \x1b[1mWorkload:\x1b[0m ${a.workloadTurns} agent turns / tasks`,
74
- ` \x1b[1mMemory Mode (SQLite):\x1b[0m ${m.tokensUsed.toLocaleString()} tokens │ Precision: ${m.retrievalPrecisionPct}% │ Retry: ${m.staleRetryRatePct}%`,
75
- ` \x1b[1mBaseline (Stateless):\x1b[0m ${d.tokensUsed.toLocaleString()} tokens │ Precision: ${d.retrievalPrecisionPct}% │ Retry: ${d.staleRetryRatePct}%`,
160
+ ` \x1b[1mMemory Mode (SQLite):\x1b[0m ${m.tokensUsed.toLocaleString()} tokens${memoryTokensSuffix} │ Precision: ${m.retrievalPrecisionPct}% │ Retry: ${m.staleRetryRatePct}%`,
161
+ ` \x1b[1mBaseline (Stateless):\x1b[0m ${d.tokensUsed.toLocaleString()} tokens (modeled) │ Precision: ${d.retrievalPrecisionPct}% │ Retry: ${d.staleRetryRatePct}%`,
76
162
  `\x1b[90m${'─'.repeat(58)}\x1b[0m`,
77
- ` \x1b[32m✔ Token Reduction:\x1b[0m ${delta.tokenReductionPct}% fewer tokens consumed`,
78
- ` \x1b[32m✔ Cost Avoided:\x1b[0m $${delta.costAvoidedUsd.toFixed(4)} USD`,
163
+ ` \x1b[32m✔ Token Reduction:\x1b[0m ${tokenReductionLabel}`,
164
+ ` \x1b[32m✔ Cost Avoided:\x1b[0m ${delta.costAvoidedUsd.toFixed(4)} USD${costAvoidedSuffix}`,
79
165
  ` \x1b[32m✔ Precision Gain:\x1b[0m ${delta.retrievalPrecisionGainRatio} higher retrieval precision per dollar`,
80
166
  ` \x1b[32m✔ Stale Retries:\x1b[0m ${delta.staleRetriesEliminated} retries eliminated`,
81
167
  `\x1b[90m${'─'.repeat(58)}\x1b[0m\n`
82
- ];
168
+ );
83
169
  return lines.join('\n');
84
170
  };
@@ -68,7 +68,56 @@ test("runAblationComparison and formatAblationCard generate metrics card without
68
68
  assert.strictEqual(ablation.memoryEnabled.astQualityScore, 100);
69
69
  assert.strictEqual(ablation.memoryDisabled.astQualityScore, 84);
70
70
  assert.ok(ablation.delta.tokenReductionPct >= 90);
71
+ assert.strictEqual(ablation.hasRealData, false);
72
+ assert.strictEqual(ablation.isSimulated, true);
71
73
  const card = formatAblationCard(ablation);
72
74
  assert.ok(card.includes("Persistent Memory Ablation Benchmark"));
75
+ assert.ok(card.includes("Reference Projection"));
73
76
  assert.strictEqual(card.includes("—"), false);
74
77
  }));
78
+
79
+ test("runAblationComparison computes dynamic metrics from live task and memory records", () => withTmpCwd((db) => {
80
+ db.prepare(`
81
+ INSERT INTO agent_tasks (title, status, prompt_tokens, completion_tokens, cost_usd, created_at, updated_at)
82
+ VALUES ('Refactor parser', 'done', 1500, 300, 0.05, 1000, 1000)
83
+ `).run();
84
+
85
+ recordMemoryInjection(db, { taskId: 1, provenance: "src/parser.ts", tokens: 200 });
86
+ recordMemoryUtilization(db, { taskId: 1, utilizedProvenance: ["src/parser.ts"], causedRetry: false });
87
+
88
+ const ablation = runAblationComparison(db);
89
+ assert.strictEqual(ablation.hasRealData, true);
90
+ assert.strictEqual(ablation.isSimulated, false);
91
+ assert.strictEqual(ablation.workloadTurns, 2);
92
+ assert.strictEqual(ablation.memoryEnabled.tokensUsed, 1800);
93
+ assert.ok(ablation.delta.tokenReductionPct > 0);
94
+ assert.ok(ablation.delta.retrievalPrecisionGainRatio.endsWith('x'));
95
+
96
+ const card = formatAblationCard(ablation);
97
+ assert.ok(card.includes("Live Project Telemetry"));
98
+ assert.ok(card.includes("measured vs modeled baseline"));
99
+ assert.strictEqual(ablation.hasMeasuredTokens, true);
100
+ assert.strictEqual(ablation.delta.isEstimated, false);
101
+ assert.strictEqual(ablation.delta.tokenReductionBasis, "measured");
102
+ assert.strictEqual(card.includes("—"), false);
103
+ }));
104
+
105
+ test("runAblationComparison marks token reduction as estimated when live tasks lack token counts", () => withTmpCwd((db) => {
106
+ db.prepare(`
107
+ INSERT INTO agent_tasks (title, status, created_at, updated_at)
108
+ VALUES ('Task without token telemetry', 'done', 1000, 1000)
109
+ `).run();
110
+
111
+ const ablation = runAblationComparison(db);
112
+ assert.strictEqual(ablation.hasRealData, true);
113
+ assert.strictEqual(ablation.hasMeasuredTokens, false);
114
+ assert.strictEqual(ablation.delta.isEstimated, true);
115
+ assert.strictEqual(ablation.delta.tokenReductionBasis, "estimated_typical_usage");
116
+ assert.strictEqual(ablation.delta.tokenReductionPct, 97);
117
+
118
+ const card = formatAblationCard(ablation);
119
+ assert.ok(card.includes("estimated based on typical usage"));
120
+ assert.ok(card.includes("(projected)"));
121
+ assert.strictEqual(card.includes("—"), false);
122
+ }));
123
+