@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.
- package/README.md +39 -34
- package/bin/construct +1403 -96
- package/commands/build/feature.md +1 -1
- package/commands/build/fix.md +1 -1
- package/commands/design/access.md +1 -1
- package/commands/design/flow.md +1 -1
- package/commands/design/ui.md +1 -1
- package/commands/measure/experiment.md +1 -1
- package/commands/measure/metrics.md +1 -1
- package/commands/measure/results.md +1 -1
- package/commands/plan/api.md +1 -1
- package/commands/plan/challenge.md +1 -1
- package/commands/plan/decide.md +1 -1
- package/commands/plan/feature.md +1 -1
- package/commands/plan/requirements.md +1 -1
- package/commands/remember/context.md +1 -1
- package/commands/remember/handoff.md +1 -1
- package/commands/remember/runbook.md +1 -1
- package/commands/review/code.md +1 -1
- package/commands/review/quality.md +1 -1
- package/commands/review/security.md +1 -1
- package/commands/ship/ready.md +1 -1
- package/commands/ship/release.md +1 -1
- package/commands/ship/status.md +1 -1
- package/commands/understand/docs.md +1 -1
- package/commands/understand/this.md +1 -1
- package/commands/understand/why.md +1 -1
- package/commands/work/clean.md +1 -1
- package/commands/work/drive.md +1 -1
- package/commands/work/optimize-prompts.md +2 -2
- package/commands/work/parallel-review.md +1 -1
- package/db/schema/007_tags.sql +30 -0
- package/db/schema/008_skill_usage.sql +24 -0
- package/db/schema/009_scheduler.sql +14 -0
- package/examples/internal/roles/architect/bad/clever-plan-without-contracts.md +1 -1
- package/examples/internal/roles/architect/golden/explicit-tradeoff-before-plan.md +1 -1
- package/examples/internal/roles/engineer/bad/speculative-abstraction.md +1 -1
- package/examples/internal/roles/engineer/golden/read-before-write.md +1 -1
- package/examples/internal/roles/qa/bad/coverage-theater.md +1 -1
- package/examples/internal/roles/qa/golden/regression-gate.md +1 -1
- package/examples/seed-observations/decisions.md +1 -1
- package/lib/audit-skills.mjs +3 -3
- package/lib/auto-docs.mjs +8 -8
- package/lib/boundary.mjs +126 -0
- package/lib/cache-strategy-google.js +26 -31
- package/lib/cli-commands.mjs +276 -122
- package/lib/comment-lint.mjs +139 -1
- package/lib/completions.mjs +1 -1
- package/lib/config/schema.mjs +15 -1
- package/lib/contracts/validate.mjs +371 -0
- package/lib/daemons/contract.mjs +210 -0
- package/lib/distill.mjs +22 -4
- package/lib/doc-stamp.mjs +48 -0
- package/lib/docs-verify.mjs +59 -6
- package/lib/doctor/cli.mjs +16 -1
- package/lib/doctor/index.mjs +3 -1
- package/lib/doctor/watchers/consistency.mjs +360 -0
- package/lib/doctor/watchers/mcp-protocol.mjs +232 -0
- package/lib/document-extract.mjs +420 -17
- package/lib/document-ingest.mjs +2 -0
- package/lib/embed/cli.mjs +124 -3
- package/lib/embed/daemon.mjs +43 -4
- package/lib/embed/docs-lifecycle.mjs +1 -1
- package/lib/embed/inbox.mjs +50 -3
- package/lib/embed/role-framing.mjs +3 -3
- package/lib/embed/scheduler.mjs +33 -5
- package/lib/env-config.mjs +9 -3
- package/lib/evaluator-optimizer.mjs +2 -3
- package/lib/extractors/calendar.mjs +173 -0
- package/lib/extractors/shared/drop-info.mjs +22 -0
- package/lib/extractors/transcript.mjs +0 -0
- package/lib/gates-audit.mjs +8 -2
- package/lib/git-hooks/prepare-commit-msg +1 -1
- package/lib/headhunt.mjs +2 -2
- package/lib/hooks/agent-tracker.mjs +6 -11
- package/lib/hooks/comment-lint.mjs +16 -0
- package/lib/hooks/guard-bash.mjs +35 -14
- package/lib/hooks/mcp-audit.mjs +14 -1
- package/lib/hooks/pre-compact.mjs +92 -5
- package/lib/hooks/pre-push-gate.mjs +41 -8
- package/lib/hooks/proactive-activation.mjs +0 -14
- package/lib/hooks/registry-sync.mjs +2 -2
- package/lib/hooks/rule-verifier.mjs +217 -0
- package/lib/hooks/session-optimize.mjs +2 -1
- package/lib/hooks/stop-notify.mjs +7 -6
- package/lib/host-capabilities.mjs +10 -1
- package/lib/hygiene/scan.mjs +141 -0
- package/lib/init-unified.mjs +73 -65
- package/lib/install/stage-project.mjs +4 -4
- package/lib/intake/classify.mjs +309 -58
- package/lib/intake/daemon.mjs +121 -0
- package/lib/intake/filesystem-queue.mjs +31 -6
- package/lib/intake/intake-config.mjs +2 -1
- package/lib/intake/postgres-queue.mjs +45 -3
- package/lib/intake/prepare.mjs +3 -1
- package/lib/intake/quarantine.mjs +205 -0
- package/lib/intake/session-prelude.mjs +7 -1
- package/lib/intake/traceability.mjs +90 -0
- package/lib/knowledge/postgres-search.mjs +132 -0
- package/lib/knowledge/research-store.mjs +2 -0
- package/lib/knowledge/search.mjs +14 -4
- package/lib/maintenance/cleanup.mjs +315 -0
- package/lib/mcp/memory-bridge.mjs +276 -0
- package/lib/mcp/server.mjs +11 -3
- package/lib/mcp/tools/skills.mjs +32 -11
- package/lib/mcp/tools/workflow.mjs +25 -0
- package/lib/mcp-catalog.json +12 -8
- package/lib/mcp-platform-config.mjs +16 -8
- package/lib/migrations/index.mjs +106 -0
- package/lib/migrations/v1-baseline.mjs +33 -0
- package/lib/model-registry.mjs +1 -1
- package/lib/observation-store.mjs +9 -4
- package/lib/opencode-runtime-plugin.mjs +1 -1
- package/lib/orchestration-policy.mjs +4 -4
- package/lib/outcomes/record.mjs +2 -0
- package/lib/overrides/resolver.mjs +3 -3
- package/lib/parity.mjs +4 -4
- package/lib/policy/engine.mjs +2 -2
- package/lib/profiles/lifecycle.mjs +1 -1
- package/lib/profiles/rebrand.mjs +46 -0
- package/lib/project-init-shared.mjs +12 -0
- package/lib/prompt-metadata.mjs +4 -4
- package/lib/provider-capabilities.js +20 -7
- package/lib/providers/auth-manager.mjs +58 -17
- package/lib/providers/circuit-breaker.mjs +14 -0
- package/lib/providers/contract.mjs +67 -3
- package/lib/providers/creds.mjs +219 -0
- package/lib/providers/scaffold.mjs +107 -0
- package/lib/reflect.mjs +49 -12
- package/lib/role-preload.mjs +5 -0
- package/lib/roles/catalog.mjs +1 -1
- package/lib/roles/manifest.mjs +2 -2
- package/lib/scheduler/index.mjs +112 -0
- package/lib/scheduler/solo.mjs +183 -0
- package/lib/server/index.mjs +29 -29
- package/lib/server/insights.mjs +14 -12
- package/lib/server/langfuse-login.mjs +58 -0
- package/lib/server/static/assets/index-ab25c707.js +1 -1
- package/lib/session-store.mjs +6 -4
- package/lib/setup.mjs +14 -3
- package/lib/{agent-contracts-enforce.mjs → specialist-contracts-enforce.mjs} +4 -4
- package/lib/{agent-contracts.mjs → specialist-contracts.mjs} +9 -8
- package/lib/{agents → specialists}/postconditions.mjs +3 -3
- package/lib/{agents → specialists}/schema.mjs +6 -6
- package/lib/status.mjs +13 -11
- package/lib/storage/backup.mjs +2 -2
- package/lib/tags/lifecycle.mjs +278 -0
- package/lib/tags/vocabulary.mjs +140 -0
- package/lib/telemetry/client.mjs +5 -1
- package/lib/telemetry/otel-tracer.mjs +184 -0
- package/lib/telemetry/skill-calls.mjs +73 -12
- package/lib/uninstall/uninstall.mjs +1 -1
- package/lib/update.mjs +1 -1
- package/lib/validator.mjs +57 -56
- package/lib/version.mjs +51 -0
- package/lib/worker/trace.mjs +5 -1
- package/lib/workflows/instantiate.mjs +320 -0
- package/package.json +16 -3
- package/personas/construct.md +5 -3
- package/platforms/claude/CLAUDE.md +1 -1
- package/rules/common/development-workflow.md +2 -1
- package/rules/common/no-fabrication.md +69 -0
- package/rules/common/review-before-change.md +58 -0
- package/scripts/{sync-agents.mjs → sync-specialists.mjs} +171 -68
- package/skills/ai/prompt-optimizer.md +3 -3
- package/skills/exploration/dependency-graph-reading.md +98 -0
- package/skills/exploration/tracer-bullet-method.md +71 -0
- package/skills/exploration/unknown-codebase-onboarding.md +91 -0
- package/skills/operating/change-management.md +91 -0
- package/skills/operating/incident-response.md +75 -0
- package/skills/operating/oncall-rotation.md +95 -0
- package/skills/operating/orchestration-reference.md +2 -2
- package/skills/strategy/competitive-landscape.md +75 -0
- package/skills/strategy/market-research-methods.md +87 -0
- package/skills/strategy/narrative-arc.md +77 -0
- package/skills/strategy/pricing-positioning.md +94 -0
- package/specialists/contracts.json +1002 -0
- package/specialists/contracts.schema.json +83 -0
- package/specialists/policy-inventory.json +160 -0
- package/{agents → specialists}/prompts/cx-accessibility.md +3 -1
- package/{agents → specialists}/prompts/cx-ai-engineer.md +3 -1
- package/{agents → specialists}/prompts/cx-architect.md +3 -1
- package/{agents → specialists}/prompts/cx-business-strategist.md +3 -1
- package/{agents → specialists}/prompts/cx-data-analyst.md +3 -1
- package/{agents → specialists}/prompts/cx-data-engineer.md +3 -1
- package/{agents → specialists}/prompts/cx-debugger.md +3 -1
- package/{agents → specialists}/prompts/cx-designer.md +3 -1
- package/{agents → specialists}/prompts/cx-devil-advocate.md +3 -1
- package/{agents → specialists}/prompts/cx-docs-keeper.md +4 -2
- package/{agents → specialists}/prompts/cx-engineer.md +4 -2
- package/{agents → specialists}/prompts/cx-evaluator.md +3 -1
- package/{agents → specialists}/prompts/cx-explorer.md +3 -1
- package/{agents → specialists}/prompts/cx-legal-compliance.md +3 -1
- package/{agents → specialists}/prompts/cx-operations.md +3 -1
- package/{agents → specialists}/prompts/cx-orchestrator.md +4 -2
- package/{agents → specialists}/prompts/cx-platform-engineer.md +3 -1
- package/{agents → specialists}/prompts/cx-product-manager.md +3 -1
- package/{agents → specialists}/prompts/cx-qa.md +3 -1
- package/{agents → specialists}/prompts/cx-rd-lead.md +3 -1
- package/{agents → specialists}/prompts/cx-release-manager.md +3 -1
- package/{agents → specialists}/prompts/cx-researcher.md +3 -1
- package/{agents → specialists}/prompts/cx-reviewer.md +4 -2
- package/{agents → specialists}/prompts/cx-security.md +3 -1
- package/{agents → specialists}/prompts/cx-sre.md +4 -2
- package/{agents → specialists}/prompts/cx-test-automation.md +3 -1
- package/{agents → specialists}/prompts/cx-trace-reviewer.md +5 -3
- package/{agents → specialists}/prompts/cx-ux-researcher.md +3 -1
- package/{agents → specialists}/registry.json +651 -418
- package/{agents → specialists}/role-manifests.json +8 -8
- package/templates/docs/construct_guide.md +6 -6
- package/templates/docs/skill-artifact.md +1 -1
- package/templates/provider-scaffold/health.test.mjs +30 -0
- package/templates/provider-scaffold/index.mjs +48 -0
- package/templates/workflows/cross-team-handoff.yml +85 -0
- package/templates/workflows/engineering-onboarding.yml +77 -0
- package/templates/workflows/new-feature.yml +53 -0
- package/agents/contracts.json +0 -387
- /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 =
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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 }.
|
package/lib/docs-verify.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/lib/doctor/cli.mjs
CHANGED
|
@@ -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
|
}
|
package/lib/doctor/index.mjs
CHANGED
|
@@ -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 = [];
|