@geraldmaron/construct 1.0.6 → 1.0.8

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 (218) hide show
  1. package/README.md +39 -34
  2. package/bin/construct +1403 -96
  3. package/commands/build/feature.md +1 -1
  4. package/commands/build/fix.md +1 -1
  5. package/commands/design/access.md +1 -1
  6. package/commands/design/flow.md +1 -1
  7. package/commands/design/ui.md +1 -1
  8. package/commands/measure/experiment.md +1 -1
  9. package/commands/measure/metrics.md +1 -1
  10. package/commands/measure/results.md +1 -1
  11. package/commands/plan/api.md +1 -1
  12. package/commands/plan/challenge.md +1 -1
  13. package/commands/plan/decide.md +1 -1
  14. package/commands/plan/feature.md +1 -1
  15. package/commands/plan/requirements.md +1 -1
  16. package/commands/remember/context.md +1 -1
  17. package/commands/remember/handoff.md +1 -1
  18. package/commands/remember/runbook.md +1 -1
  19. package/commands/review/code.md +1 -1
  20. package/commands/review/quality.md +1 -1
  21. package/commands/review/security.md +1 -1
  22. package/commands/ship/ready.md +1 -1
  23. package/commands/ship/release.md +1 -1
  24. package/commands/ship/status.md +1 -1
  25. package/commands/understand/docs.md +1 -1
  26. package/commands/understand/this.md +1 -1
  27. package/commands/understand/why.md +1 -1
  28. package/commands/work/clean.md +1 -1
  29. package/commands/work/drive.md +1 -1
  30. package/commands/work/optimize-prompts.md +2 -2
  31. package/commands/work/parallel-review.md +1 -1
  32. package/db/schema/007_tags.sql +30 -0
  33. package/db/schema/008_skill_usage.sql +24 -0
  34. package/db/schema/009_scheduler.sql +14 -0
  35. package/examples/internal/roles/architect/bad/clever-plan-without-contracts.md +1 -1
  36. package/examples/internal/roles/architect/golden/explicit-tradeoff-before-plan.md +1 -1
  37. package/examples/internal/roles/engineer/bad/speculative-abstraction.md +1 -1
  38. package/examples/internal/roles/engineer/golden/read-before-write.md +1 -1
  39. package/examples/internal/roles/qa/bad/coverage-theater.md +1 -1
  40. package/examples/internal/roles/qa/golden/regression-gate.md +1 -1
  41. package/examples/seed-observations/decisions.md +1 -1
  42. package/lib/audit-skills.mjs +3 -3
  43. package/lib/auto-docs.mjs +8 -8
  44. package/lib/boundary.mjs +126 -0
  45. package/lib/cache-strategy-google.js +26 -31
  46. package/lib/cli-commands.mjs +276 -122
  47. package/lib/comment-lint.mjs +139 -1
  48. package/lib/completions.mjs +1 -1
  49. package/lib/config/schema.mjs +15 -1
  50. package/lib/contracts/validate.mjs +371 -0
  51. package/lib/daemons/contract.mjs +210 -0
  52. package/lib/distill.mjs +22 -4
  53. package/lib/doc-stamp.mjs +48 -0
  54. package/lib/docs-verify.mjs +59 -6
  55. package/lib/doctor/cli.mjs +16 -1
  56. package/lib/doctor/index.mjs +3 -1
  57. package/lib/doctor/watchers/consistency.mjs +360 -0
  58. package/lib/doctor/watchers/mcp-protocol.mjs +232 -0
  59. package/lib/document-extract.mjs +420 -17
  60. package/lib/document-ingest.mjs +2 -0
  61. package/lib/embed/cli.mjs +124 -3
  62. package/lib/embed/daemon.mjs +43 -4
  63. package/lib/embed/docs-lifecycle.mjs +1 -1
  64. package/lib/embed/inbox.mjs +50 -3
  65. package/lib/embed/role-framing.mjs +3 -3
  66. package/lib/embed/scheduler.mjs +33 -5
  67. package/lib/env-config.mjs +9 -3
  68. package/lib/evaluator-optimizer.mjs +2 -3
  69. package/lib/extractors/calendar.mjs +173 -0
  70. package/lib/extractors/shared/drop-info.mjs +22 -0
  71. package/lib/extractors/transcript.mjs +0 -0
  72. package/lib/gates-audit.mjs +8 -2
  73. package/lib/git-hooks/prepare-commit-msg +1 -1
  74. package/lib/headhunt.mjs +2 -2
  75. package/lib/hooks/agent-tracker.mjs +6 -11
  76. package/lib/hooks/comment-lint.mjs +16 -0
  77. package/lib/hooks/guard-bash.mjs +35 -14
  78. package/lib/hooks/mcp-audit.mjs +14 -1
  79. package/lib/hooks/pre-compact.mjs +92 -5
  80. package/lib/hooks/pre-push-gate.mjs +41 -8
  81. package/lib/hooks/proactive-activation.mjs +0 -14
  82. package/lib/hooks/registry-sync.mjs +2 -2
  83. package/lib/hooks/rule-verifier.mjs +217 -0
  84. package/lib/hooks/session-optimize.mjs +2 -1
  85. package/lib/hooks/stop-notify.mjs +7 -6
  86. package/lib/host-capabilities.mjs +10 -1
  87. package/lib/hygiene/scan.mjs +141 -0
  88. package/lib/init-unified.mjs +73 -65
  89. package/lib/install/stage-project.mjs +4 -4
  90. package/lib/intake/classify.mjs +309 -58
  91. package/lib/intake/daemon.mjs +121 -0
  92. package/lib/intake/filesystem-queue.mjs +31 -6
  93. package/lib/intake/intake-config.mjs +2 -1
  94. package/lib/intake/postgres-queue.mjs +45 -3
  95. package/lib/intake/prepare.mjs +3 -1
  96. package/lib/intake/quarantine.mjs +205 -0
  97. package/lib/intake/session-prelude.mjs +7 -1
  98. package/lib/intake/traceability.mjs +90 -0
  99. package/lib/knowledge/postgres-search.mjs +132 -0
  100. package/lib/knowledge/research-store.mjs +2 -0
  101. package/lib/knowledge/search.mjs +14 -4
  102. package/lib/maintenance/cleanup.mjs +315 -0
  103. package/lib/mcp/memory-bridge.mjs +276 -0
  104. package/lib/mcp/server.mjs +11 -3
  105. package/lib/mcp/tools/skills.mjs +32 -11
  106. package/lib/mcp/tools/workflow.mjs +25 -0
  107. package/lib/mcp-catalog.json +12 -8
  108. package/lib/mcp-platform-config.mjs +16 -8
  109. package/lib/migrations/index.mjs +106 -0
  110. package/lib/migrations/v1-baseline.mjs +33 -0
  111. package/lib/model-registry.mjs +1 -1
  112. package/lib/observation-store.mjs +9 -4
  113. package/lib/opencode-runtime-plugin.mjs +1 -1
  114. package/lib/orchestration-policy.mjs +4 -4
  115. package/lib/outcomes/record.mjs +2 -0
  116. package/lib/overrides/resolver.mjs +3 -3
  117. package/lib/parity.mjs +4 -4
  118. package/lib/policy/engine.mjs +2 -2
  119. package/lib/profiles/lifecycle.mjs +1 -1
  120. package/lib/profiles/rebrand.mjs +46 -0
  121. package/lib/project-init-shared.mjs +12 -0
  122. package/lib/prompt-metadata.mjs +4 -4
  123. package/lib/provider-capabilities.js +20 -7
  124. package/lib/providers/auth-manager.mjs +58 -17
  125. package/lib/providers/circuit-breaker.mjs +14 -0
  126. package/lib/providers/contract.mjs +67 -3
  127. package/lib/providers/creds.mjs +219 -0
  128. package/lib/providers/scaffold.mjs +107 -0
  129. package/lib/reflect.mjs +49 -12
  130. package/lib/role-preload.mjs +5 -0
  131. package/lib/roles/catalog.mjs +1 -1
  132. package/lib/roles/manifest.mjs +2 -2
  133. package/lib/scheduler/index.mjs +112 -0
  134. package/lib/scheduler/solo.mjs +183 -0
  135. package/lib/server/index.mjs +29 -29
  136. package/lib/server/insights.mjs +14 -12
  137. package/lib/server/langfuse-login.mjs +58 -0
  138. package/lib/server/static/assets/index-ab25c707.js +1 -1
  139. package/lib/session-store.mjs +6 -4
  140. package/lib/setup.mjs +14 -3
  141. package/lib/{agent-contracts-enforce.mjs → specialist-contracts-enforce.mjs} +4 -4
  142. package/lib/{agent-contracts.mjs → specialist-contracts.mjs} +9 -8
  143. package/lib/{agents → specialists}/postconditions.mjs +3 -3
  144. package/lib/{agents → specialists}/schema.mjs +6 -6
  145. package/lib/status.mjs +13 -11
  146. package/lib/storage/backup.mjs +2 -2
  147. package/lib/tags/lifecycle.mjs +278 -0
  148. package/lib/tags/vocabulary.mjs +140 -0
  149. package/lib/telemetry/client.mjs +5 -1
  150. package/lib/telemetry/otel-tracer.mjs +184 -0
  151. package/lib/telemetry/skill-calls.mjs +73 -12
  152. package/lib/uninstall/uninstall.mjs +1 -1
  153. package/lib/update.mjs +1 -1
  154. package/lib/validator.mjs +57 -56
  155. package/lib/version.mjs +51 -0
  156. package/lib/worker/trace.mjs +5 -1
  157. package/lib/workflows/instantiate.mjs +320 -0
  158. package/package.json +16 -3
  159. package/personas/construct.md +5 -3
  160. package/platforms/claude/CLAUDE.md +1 -1
  161. package/rules/common/development-workflow.md +2 -1
  162. package/rules/common/no-fabrication.md +69 -0
  163. package/rules/common/review-before-change.md +58 -0
  164. package/scripts/{sync-agents.mjs → sync-specialists.mjs} +171 -68
  165. package/skills/ai/prompt-optimizer.md +3 -3
  166. package/skills/exploration/dependency-graph-reading.md +98 -0
  167. package/skills/exploration/tracer-bullet-method.md +71 -0
  168. package/skills/exploration/unknown-codebase-onboarding.md +91 -0
  169. package/skills/operating/change-management.md +91 -0
  170. package/skills/operating/incident-response.md +75 -0
  171. package/skills/operating/oncall-rotation.md +95 -0
  172. package/skills/operating/orchestration-reference.md +2 -2
  173. package/skills/strategy/competitive-landscape.md +75 -0
  174. package/skills/strategy/market-research-methods.md +87 -0
  175. package/skills/strategy/narrative-arc.md +77 -0
  176. package/skills/strategy/pricing-positioning.md +94 -0
  177. package/specialists/contracts.json +1002 -0
  178. package/specialists/contracts.schema.json +83 -0
  179. package/specialists/policy-inventory.json +160 -0
  180. package/{agents → specialists}/prompts/cx-accessibility.md +3 -1
  181. package/{agents → specialists}/prompts/cx-ai-engineer.md +3 -1
  182. package/{agents → specialists}/prompts/cx-architect.md +3 -1
  183. package/{agents → specialists}/prompts/cx-business-strategist.md +3 -1
  184. package/{agents → specialists}/prompts/cx-data-analyst.md +3 -1
  185. package/{agents → specialists}/prompts/cx-data-engineer.md +3 -1
  186. package/{agents → specialists}/prompts/cx-debugger.md +3 -1
  187. package/{agents → specialists}/prompts/cx-designer.md +3 -1
  188. package/{agents → specialists}/prompts/cx-devil-advocate.md +3 -1
  189. package/{agents → specialists}/prompts/cx-docs-keeper.md +4 -2
  190. package/{agents → specialists}/prompts/cx-engineer.md +4 -2
  191. package/{agents → specialists}/prompts/cx-evaluator.md +3 -1
  192. package/{agents → specialists}/prompts/cx-explorer.md +3 -1
  193. package/{agents → specialists}/prompts/cx-legal-compliance.md +3 -1
  194. package/{agents → specialists}/prompts/cx-operations.md +3 -1
  195. package/{agents → specialists}/prompts/cx-orchestrator.md +4 -2
  196. package/{agents → specialists}/prompts/cx-platform-engineer.md +3 -1
  197. package/{agents → specialists}/prompts/cx-product-manager.md +3 -1
  198. package/{agents → specialists}/prompts/cx-qa.md +3 -1
  199. package/{agents → specialists}/prompts/cx-rd-lead.md +3 -1
  200. package/{agents → specialists}/prompts/cx-release-manager.md +3 -1
  201. package/{agents → specialists}/prompts/cx-researcher.md +3 -1
  202. package/{agents → specialists}/prompts/cx-reviewer.md +4 -2
  203. package/{agents → specialists}/prompts/cx-security.md +3 -1
  204. package/{agents → specialists}/prompts/cx-sre.md +4 -2
  205. package/{agents → specialists}/prompts/cx-test-automation.md +3 -1
  206. package/{agents → specialists}/prompts/cx-trace-reviewer.md +5 -3
  207. package/{agents → specialists}/prompts/cx-ux-researcher.md +3 -1
  208. package/{agents → specialists}/registry.json +651 -418
  209. package/{agents → specialists}/role-manifests.json +8 -8
  210. package/templates/docs/construct_guide.md +6 -6
  211. package/templates/docs/skill-artifact.md +1 -1
  212. package/templates/provider-scaffold/health.test.mjs +30 -0
  213. package/templates/provider-scaffold/index.mjs +48 -0
  214. package/templates/workflows/cross-team-handoff.yml +85 -0
  215. package/templates/workflows/engineering-onboarding.yml +77 -0
  216. package/templates/workflows/new-feature.yml +53 -0
  217. package/agents/contracts.json +0 -387
  218. /package/{agents → specialists}/teams.json +0 -0
@@ -0,0 +1,210 @@
1
+ /**
2
+ * lib/daemons/contract.mjs — Shared safeguard contract for every long-running
3
+ * Construct process. No ambient process in Construct survives without these
4
+ * rails.
5
+ *
6
+ * Safeguards enforced for every daemon that uses DaemonRunner:
7
+ * - Bounded lifetime: max wall-clock runtime (default 24h) before self-restart
8
+ * with state checkpoint.
9
+ * - Idle shutdown: if no work for N consecutive ticks, stop and log;
10
+ * resume on next external trigger.
11
+ * - Heartbeat: every tick writes lastTickAt to a known path.
12
+ * - Single-writer lock: prevents duplicate daemon instances; auto-expires.
13
+ * - Killswitch: env var disables the daemon without code changes.
14
+ * - Resource caps: CPU/memory limits via process.resourceUsage thresholds.
15
+ *
16
+ * Per-item safeguards (TTL, retry budget, dead-letter) are owned by the work
17
+ * queue, not the runner; this module exposes a small queue helper for that.
18
+ */
19
+
20
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, statSync } from 'node:fs';
21
+ import { dirname } from 'node:path';
22
+ import { setTimeout as sleep } from 'node:timers/promises';
23
+
24
+ export const DEFAULT_MAX_RUNTIME_MS = 24 * 60 * 60 * 1000;
25
+ export const DEFAULT_IDLE_TICKS = 6;
26
+ export const DEFAULT_MEMORY_CAP_MB = 256;
27
+
28
+ /**
29
+ * Build a DaemonRunner. Spec fields:
30
+ * name — identifier; used in heartbeat path
31
+ * tick(ctx) — async; returns { didWork: boolean } each cycle
32
+ * intervalMs — sleep between ticks
33
+ * killswitchEnv — process.env key; when '=off' the daemon refuses to start
34
+ * heartbeatPath — file written each tick with { ts, name, ticks }
35
+ * lockPath — single-writer lockfile (defaults to heartbeatPath + .lock)
36
+ * maxRuntimeMs — bounded lifetime; default 24h
37
+ * maxIdleTicks — consecutive zero-work ticks before idle shutdown
38
+ * memoryCapMb — RSS cap; exceeding triggers self-stop + escalation
39
+ * onIdleShutdown — optional callback when the runner stops due to idle
40
+ * onMemoryExceeded — optional callback when the runner stops due to memory
41
+ */
42
+ export function createDaemon(spec) {
43
+ if (!spec?.name) throw new Error('daemon spec missing name');
44
+ if (typeof spec.tick !== 'function') throw new Error('daemon spec missing tick(ctx)');
45
+
46
+ const cfg = {
47
+ intervalMs: spec.intervalMs ?? 60_000,
48
+ killswitchEnv: spec.killswitchEnv,
49
+ heartbeatPath: spec.heartbeatPath,
50
+ lockPath: spec.lockPath || (spec.heartbeatPath ? `${spec.heartbeatPath}.lock` : null),
51
+ maxRuntimeMs: spec.maxRuntimeMs ?? DEFAULT_MAX_RUNTIME_MS,
52
+ maxIdleTicks: spec.maxIdleTicks ?? DEFAULT_IDLE_TICKS,
53
+ memoryCapMb: spec.memoryCapMb ?? DEFAULT_MEMORY_CAP_MB,
54
+ onIdleShutdown: spec.onIdleShutdown,
55
+ onMemoryExceeded: spec.onMemoryExceeded,
56
+ };
57
+
58
+ let running = false;
59
+ let stopRequested = false;
60
+ let startedAt = 0;
61
+ let ticks = 0;
62
+ let idleTicks = 0;
63
+
64
+ function killswitchEngaged() {
65
+ if (!cfg.killswitchEnv) return false;
66
+ return process.env[cfg.killswitchEnv] === 'off' || process.env[cfg.killswitchEnv] === '0';
67
+ }
68
+
69
+ function acquireLock() {
70
+ if (!cfg.lockPath) return true;
71
+ try { mkdirSync(dirname(cfg.lockPath), { recursive: true }); } catch { /* ignore */ }
72
+ try {
73
+ writeFileSync(cfg.lockPath, JSON.stringify({ pid: process.pid, startedAt: Date.now() }), { flag: 'wx' });
74
+ return true;
75
+ } catch (err) {
76
+ if (err.code !== 'EEXIST') throw err;
77
+ const holder = readLockHolder();
78
+ if (holder && processAlive(holder.pid)) return false;
79
+ // Stale lock — steal it
80
+ writeFileSync(cfg.lockPath, JSON.stringify({ pid: process.pid, startedAt: Date.now() }), { flag: 'w' });
81
+ return true;
82
+ }
83
+ }
84
+
85
+ function releaseLock() {
86
+ if (!cfg.lockPath) return;
87
+ try { unlinkSync(cfg.lockPath); } catch { /* ignore */ }
88
+ }
89
+
90
+ function readLockHolder() {
91
+ if (!cfg.lockPath || !existsSync(cfg.lockPath)) return null;
92
+ try { return JSON.parse(readFileSync(cfg.lockPath, 'utf8')); } catch { return null; }
93
+ }
94
+
95
+ function processAlive(pid) {
96
+ if (!pid) return false;
97
+ try { process.kill(pid, 0); return true; } catch { return false; }
98
+ }
99
+
100
+ function heartbeat() {
101
+ if (!cfg.heartbeatPath) return;
102
+ try { mkdirSync(dirname(cfg.heartbeatPath), { recursive: true }); } catch { /* ignore */ }
103
+ try {
104
+ writeFileSync(cfg.heartbeatPath, JSON.stringify({
105
+ name: spec.name, pid: process.pid, ts: Date.now(), ticks, idleTicks,
106
+ }));
107
+ } catch { /* heartbeat is best effort */ }
108
+ }
109
+
110
+ function memoryExceeded() {
111
+ const rssMb = process.memoryUsage().rss / (1024 * 1024);
112
+ return rssMb > cfg.memoryCapMb;
113
+ }
114
+
115
+ async function run() {
116
+ if (killswitchEngaged()) {
117
+ return { stopped: true, reason: 'killswitch' };
118
+ }
119
+ if (!acquireLock()) {
120
+ return { stopped: true, reason: 'lock-held' };
121
+ }
122
+
123
+ running = true;
124
+ stopRequested = false;
125
+ startedAt = Date.now();
126
+ ticks = 0;
127
+ idleTicks = 0;
128
+
129
+ try {
130
+ while (running && !stopRequested) {
131
+ if (Date.now() - startedAt >= cfg.maxRuntimeMs) {
132
+ return { stopped: true, reason: 'max-runtime', ticks };
133
+ }
134
+ if (memoryExceeded()) {
135
+ if (cfg.onMemoryExceeded) try { await cfg.onMemoryExceeded(); } catch { /* ignore */ }
136
+ return { stopped: true, reason: 'memory-cap', ticks };
137
+ }
138
+ if (killswitchEngaged()) {
139
+ return { stopped: true, reason: 'killswitch-mid-run', ticks };
140
+ }
141
+
142
+ ticks++;
143
+ let result;
144
+ try { result = await spec.tick({ ticks, idleTicks }); }
145
+ catch (err) { result = { didWork: false, error: err.message }; }
146
+
147
+ heartbeat();
148
+
149
+ if (result?.didWork) idleTicks = 0;
150
+ else idleTicks++;
151
+
152
+ if (idleTicks >= cfg.maxIdleTicks) {
153
+ if (cfg.onIdleShutdown) try { await cfg.onIdleShutdown(); } catch { /* ignore */ }
154
+ return { stopped: true, reason: 'idle', ticks };
155
+ }
156
+
157
+ await sleep(cfg.intervalMs);
158
+ }
159
+ return { stopped: true, reason: 'requested', ticks };
160
+ } finally {
161
+ running = false;
162
+ releaseLock();
163
+ }
164
+ }
165
+
166
+ function stop() { stopRequested = true; }
167
+
168
+ function status() {
169
+ return {
170
+ name: spec.name,
171
+ running,
172
+ ticks,
173
+ idleTicks,
174
+ uptimeMs: running ? Date.now() - startedAt : 0,
175
+ heartbeatPath: cfg.heartbeatPath,
176
+ lockPath: cfg.lockPath,
177
+ };
178
+ }
179
+
180
+ return { run, stop, status };
181
+ }
182
+
183
+ /**
184
+ * Inspect a heartbeat file written by a DaemonRunner. Returns the heartbeat
185
+ * if fresh (within staleMs), null if stale or missing.
186
+ */
187
+ export function readHeartbeat(heartbeatPath, { staleMs = 5 * 60 * 1000 } = {}) {
188
+ if (!heartbeatPath || !existsSync(heartbeatPath)) return null;
189
+ try {
190
+ const data = JSON.parse(readFileSync(heartbeatPath, 'utf8'));
191
+ const age = Date.now() - (data.ts || 0);
192
+ if (age > staleMs) return null;
193
+ return { ...data, ageMs: age };
194
+ } catch { return null; }
195
+ }
196
+
197
+ /**
198
+ * Helper for per-item TTL + retry + dead-letter routing inside a tick. Given
199
+ * a packet with `firstSeenAt` and optional `attempts`, returns a routing
200
+ * decision: 'process' (within budget), 'dead-letter' (TTL or retry budget
201
+ * exhausted), or 'escalate' (past TTL but not yet retried max).
202
+ */
203
+ export function classifyPacket(packet, { maxAgeMs = 14 * 24 * 60 * 60 * 1000, maxAttempts = 3 } = {}) {
204
+ const firstSeenAt = packet?.firstSeenAt || packet?.createdAt || Date.now();
205
+ const attempts = packet?.attempts || 0;
206
+ const age = Date.now() - new Date(firstSeenAt).getTime();
207
+ if (age > maxAgeMs) return { route: 'dead-letter', reason: 'ttl-exceeded' };
208
+ if (attempts >= maxAttempts) return { route: 'dead-letter', reason: 'retry-budget-exhausted' };
209
+ return { route: 'process', attempts };
210
+ }
package/lib/distill.mjs CHANGED
@@ -11,6 +11,7 @@ import { join, extname, relative, dirname, basename } from 'path';
11
11
  import { execSync, spawnSync } from 'child_process';
12
12
  import { homedir } from 'os';
13
13
  import { getActiveOverlays } from './headhunt.mjs';
14
+ import { withGenAiSpan, GenAiAttrs } from './telemetry/otel-tracer.mjs';
14
15
  import {
15
16
  EXTRACTABLE_DOCUMENT_EXTS,
16
17
  UTF8_TEXT_EXTS,
@@ -355,10 +356,27 @@ export async function distill(dir, { format = 'summary', query = '', mode = 'aut
355
356
  }
356
357
 
357
358
  process.stderr.write(' Invoking claude --print …\n\n');
358
- const result = spawnSync('claude', ['--print', prompt], {
359
- encoding: 'utf8',
360
- maxBuffer: 10 * 1024 * 1024,
361
- timeout: 120_000,
359
+ const result = await withGenAiSpan('chat', {
360
+ [GenAiAttrs.SYSTEM]: 'anthropic',
361
+ [GenAiAttrs.OPERATION_NAME]: 'chat',
362
+ [GenAiAttrs.REQUEST_MODEL]: process.env.CONSTRUCT_MODEL || 'claude-3-5-sonnet',
363
+ 'construct.operation': 'distill',
364
+ 'construct.prompt_chars': prompt.length,
365
+ }, async (span) => {
366
+ const r = spawnSync('claude', ['--print', prompt], {
367
+ encoding: 'utf8',
368
+ maxBuffer: 10 * 1024 * 1024,
369
+ timeout: 120_000,
370
+ });
371
+ if (r.error) throw r.error;
372
+ if (r.status !== 0) {
373
+ const errOut = r.stderr || '';
374
+ if (errOut) process.stderr.write(`${errOut}\n`);
375
+ throw new Error(`claude exited with status ${r.status}`);
376
+ }
377
+ const out = r.stdout || '';
378
+ span.setAttribute(GenAiAttrs.USAGE_OUTPUT_TOKENS, Math.ceil(out.length / 4));
379
+ return r;
362
380
  });
363
381
 
364
382
  if (result.error) throw result.error;
package/lib/doc-stamp.mjs CHANGED
@@ -7,6 +7,7 @@
7
7
  * stampFrontmatter — inject/update audit block at top of a markdown string
8
8
  * verifyStamp — verify body_hash against current content
9
9
  * parseStamp — extract stamp fields from a document string
10
+ * validateTags — validate frontmatter tags against a loaded vocabulary
10
11
  *
11
12
  * Design:
12
13
  * - Zero npm dependencies (Node built-ins only)
@@ -16,9 +17,12 @@
16
17
  * trimmed, so whitespace-only edits do not break verification.
17
18
  * - generator field is intentionally short (no version pinning) so the
18
19
  * stamp survives construct upgrades without false-positive hash mismatches.
20
+ * - validateTags does NOT throw: it returns { errors, warnings } for callers
21
+ * to decide how to handle violations.
19
22
  */
20
23
 
21
24
  import { createHash, randomBytes } from 'node:crypto';
25
+ import { validateTags as vocabValidateTags, isTagDeprecated, isTagArchived } from './tags/vocabulary.mjs';
22
26
 
23
27
  // ---------------------------------------------------------------------------
24
28
  // UUIDv7 — RFC 9562 §5.7
@@ -147,6 +151,50 @@ export function parseStamp(content) {
147
151
  return fields;
148
152
  }
149
153
 
154
+ // ---------------------------------------------------------------------------
155
+ // Tag validation — uses vocabulary module, returns errors/warnings for callers
156
+ // ---------------------------------------------------------------------------
157
+
158
+ /**
159
+ * Validates frontmatter tags against a loaded vocabulary object.
160
+ * Returns { errors: string[], warnings: string[] }.
161
+ *
162
+ * Errors (hard violations):
163
+ * - Two or more tags from the same exclusive facet (duplicateFacets)
164
+ * - Writing a tag with status 'archived'
165
+ *
166
+ * Warnings (soft violations):
167
+ * - Tag ID not found in vocabulary (unknown)
168
+ * - Writing a tag with status 'deprecated'
169
+ */
170
+ export function validateTags(frontmatter, vocab) {
171
+ const tags = Array.isArray(frontmatter.tags) ? frontmatter.tags : [];
172
+ const errors = [];
173
+ const warnings = [];
174
+
175
+ if (tags.length === 0) return { errors, warnings };
176
+
177
+ const { unknown, duplicateFacets } = vocabValidateTags(tags, vocab);
178
+
179
+ for (const id of duplicateFacets) {
180
+ errors.push(`exclusive-facet violation: tag "${id}" shares a facet with an earlier tag`);
181
+ }
182
+
183
+ for (const id of unknown) {
184
+ warnings.push(`unknown tag: "${id}" is not in the controlled vocabulary`);
185
+ }
186
+
187
+ for (const id of tags) {
188
+ if (isTagArchived(id, vocab)) {
189
+ errors.push(`archived-tag write: tag "${id}" has status archived and must not be applied`);
190
+ } else if (isTagDeprecated(id, vocab)) {
191
+ warnings.push(`deprecated-tag write: tag "${id}" has status deprecated`);
192
+ }
193
+ }
194
+
195
+ return { errors, warnings };
196
+ }
197
+
150
198
  /**
151
199
  * Verify that the stored body_hash matches the current body.
152
200
  * Returns { valid: true } or { valid: false, reason, stored, computed }.
@@ -4,9 +4,11 @@
4
4
  *
5
5
  * Checks:
6
6
  * 1. README.md exists and has basic sections
7
- * 2. AGENTS.md exists and has required sections
7
+ * 2. AGENTS.md exists and has required sections
8
8
  * 3. plan.md exists and is current (< 7 days)
9
- * 4. .cx/context.md exists and is current (< 7 days)
9
+ * 4. .cx/context.md is current (< 7 days, critical when .cx/ exists). Verifier
10
+ * reconstitutes the file from the init template when .cx/ exists but the
11
+ * file does not — invariant enforcement is centralized here.
10
12
  * 5. docs/README.md exists (if docs system initialized)
11
13
  * 6. Required documentation lanes exist (if specified in init)
12
14
  *
@@ -18,6 +20,8 @@
18
20
  import fs from "node:fs";
19
21
  import path from "node:path";
20
22
  import { statSync, readFileSync, existsSync } from "node:fs";
23
+ import { hasIntakeReference } from "./intake/traceability.mjs";
24
+ import { ensureCxDir } from "./project-init-shared.mjs";
21
25
 
22
26
  const args = process.argv.slice(2);
23
27
  const quickMode = args.includes("--quick");
@@ -196,6 +200,37 @@ function checkContextHasProgress(contextPath) {
196
200
  }
197
201
  }
198
202
 
203
+ // Surfaces drift: artifacts under intake-fed locations that lack an
204
+ // intake_id / intake: none frontmatter reference. Advisory (warning) because
205
+ // not every artifact necessarily comes from an intake packet — but the absence
206
+ // is a flag for the operator to either stamp the provenance or declare it
207
+ // intake-independent.
208
+ function checkIntakeTraceability(cwd) {
209
+ const intakeFedDirs = [
210
+ path.join(cwd, 'docs', 'prd'),
211
+ path.join(cwd, 'docs', 'research'),
212
+ path.join(cwd, '.cx', 'knowledge', 'internal'),
213
+ ];
214
+ let inspected = 0;
215
+ for (const dir of intakeFedDirs) {
216
+ if (!fs.existsSync(dir)) continue;
217
+ let entries;
218
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
219
+ for (const entry of entries) {
220
+ if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
221
+ if (entry.name.startsWith('_') || entry.name.toLowerCase() === 'readme.md') continue;
222
+ const filePath = path.join(dir, entry.name);
223
+ inspected += 1;
224
+ if (!hasIntakeReference(filePath)) {
225
+ warnings.push(
226
+ `Intake traceability: ${path.relative(cwd, filePath)} lacks intake_id or "intake: none" in frontmatter — stamp via \`construct intake done <id> --output\` or declare intake-independent.`,
227
+ );
228
+ }
229
+ }
230
+ }
231
+ return inspected;
232
+ }
233
+
199
234
  function checkDocsSystem(docsPath) {
200
235
  if (!fs.existsSync(docsPath)) {
201
236
  // docs/ directory doesn't exist, which is fine if project doesn't use docs system
@@ -331,7 +366,25 @@ function main() {
331
366
  // Critical checks (fail CI)
332
367
  checkExists(path.join(cwd, "README.md"), "README.md", true);
333
368
  checkExists(path.join(cwd, "AGENTS.md"), "AGENTS.md", true);
334
- checkExists(path.join(cwd, ".cx", "context.md"), ".cx/context.md", true);
369
+
370
+ // .cx/context.md invariant. The verifier is the canonical enforcer: if .cx/
371
+ // exists but context.md does not, the file is reconstituted from the init
372
+ // template here. This is consistent with construct init (which creates both
373
+ // together) and absorbs the case where a subsystem creates a .cx/ subdirectory
374
+ // for operational reasons without going through ensureCxDir. CI starts with
375
+ // no .cx/ at all (gitignored) so the block is skipped entirely. Staleness
376
+ // remains critical — a context.md older than 7 days indicates sessions that
377
+ // are running without keeping the handoff state current, which is the real
378
+ // bug the gate exists to catch.
379
+ const cxDir = path.join(cwd, ".cx");
380
+ const contextMdPath = path.join(cxDir, "context.md");
381
+ const cxExists = fs.existsSync(cxDir);
382
+ if (cxExists) {
383
+ if (!fs.existsSync(contextMdPath)) {
384
+ ensureCxDir(cwd);
385
+ }
386
+ checkFileAge(contextMdPath, 7, ".cx/context.md", true);
387
+ }
335
388
 
336
389
  // plan.md is a local working document — gitignored, not committed.
337
390
  // Verify it's healthy when present, but don't fail when it's absent.
@@ -339,16 +392,16 @@ function main() {
339
392
 
340
393
  // Age checks (fail CI if stale)
341
394
  if (planExists) checkFileAge(path.join(cwd, "plan.md"), 7, "plan.md", true);
342
- checkFileAge(path.join(cwd, ".cx", "context.md"), 7, ".cx/context.md", true);
343
395
 
344
396
  if (!quickMode) {
345
397
  // Detailed checks (warnings only)
346
398
  checkReadmeBasicSections(path.join(cwd, "README.md"));
347
399
  checkAgentsRequiredSections(path.join(cwd, "AGENTS.md"));
348
400
  if (planExists) checkPlanLinkedToIssues(path.join(cwd, "plan.md"));
349
- checkContextHasProgress(path.join(cwd, ".cx", "context.md"));
401
+ if (cxExists && fs.existsSync(contextMdPath)) checkContextHasProgress(contextMdPath);
350
402
  checkDocsSystem(path.join(cwd, "docs"));
351
-
403
+ checkIntakeTraceability(cwd);
404
+
352
405
  // Age warning for README.md (30 days)
353
406
  checkFileAge(path.join(cwd, "README.md"), 30, "README.md", false);
354
407
  }
@@ -85,6 +85,7 @@ export async function runCli(args) {
85
85
  import('./watchers/process-pressure.mjs'),
86
86
  import('./watchers/service-health.mjs'),
87
87
  import('./watchers/bd-watch.mjs'),
88
+ import('./watchers/consistency.mjs'),
88
89
  ]);
89
90
  for (const w of watchers) {
90
91
  const r = await w.tick();
@@ -93,7 +94,21 @@ export async function runCli(args) {
93
94
  return 0;
94
95
  }
95
96
 
97
+ if (sub === 'consistency') {
98
+ const { runAllChecks } = await import('./watchers/consistency.mjs');
99
+ const result = await runAllChecks();
100
+ const blocking = result.findings.filter((f) => f.severity === 'blocking');
101
+ const warnings = result.findings.filter((f) => f.severity === 'warning');
102
+
103
+ for (const p of result.passed) console.log(` ✓ ${p.category.padEnd(18)} ${p.summary}`);
104
+ for (const w of warnings) console.log(` ⚠ ${w.category.padEnd(18)} ${w.summary}`);
105
+ for (const b of blocking) console.log(` ✗ ${b.category.padEnd(18)} ${b.summary}`);
106
+
107
+ console.log(`\n${result.passed.length} category(s) clean, ${warnings.length} warning(s), ${blocking.length} blocking finding(s)`);
108
+ return blocking.length > 0 ? 1 : 0;
109
+ }
110
+
96
111
  console.error(`Unknown doctor subcommand: ${sub}`);
97
- console.error('Usage: construct doctor [status|watch|stop|logs|tick]');
112
+ console.error('Usage: construct doctor [status|watch|stop|logs|tick|consistency]');
98
113
  return 2;
99
114
  }
@@ -22,9 +22,11 @@ import * as processPressure from './watchers/process-pressure.mjs';
22
22
  import * as serviceHealth from './watchers/service-health.mjs';
23
23
  import * as bdWatch from './watchers/bd-watch.mjs';
24
24
  import * as handoffs from './watchers/handoffs.mjs';
25
+ import * as consistency from './watchers/consistency.mjs';
26
+ import * as mcpProtocol from './watchers/mcp-protocol.mjs';
25
27
 
26
28
  const STATE_PATH = join(homedir(), '.construct', 'doctor.json');
27
- const WATCHERS = [disk, cost, processPressure, serviceHealth, bdWatch, handoffs];
29
+ const WATCHERS = [disk, cost, processPressure, serviceHealth, bdWatch, handoffs, consistency, mcpProtocol];
28
30
 
29
31
  let running = false;
30
32
  let timers = [];