specbox 6.29.1 → 6.29.2
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 +5 -3
- package/bin/specbox.mjs +38 -2
- package/hooks/app-docs-sync-guard.mjs +326 -0
- package/hooks/branch-guard.mjs +79 -0
- package/hooks/checkpoint-freshness-guard.mjs +56 -0
- package/hooks/commit-spec-guard.mjs +61 -0
- package/hooks/context-budget-guard.mjs +130 -0
- package/hooks/design-gate.mjs +144 -0
- package/hooks/design-review-gate.mjs +102 -0
- package/hooks/design-system-gate.mjs +134 -0
- package/hooks/e2e-gate.mjs +86 -0
- package/hooks/file-ownership-guard.mjs +163 -0
- package/hooks/freeform-fragment.mjs +160 -0
- package/hooks/freeform-path-guard.mjs +172 -0
- package/hooks/healing-budget-guard.mjs +83 -0
- package/hooks/hooks-history.json +176 -0
- package/hooks/hooks-manifest.json +51 -0
- package/hooks/implement-checkpoint.mjs +46 -0
- package/hooks/implement-healing.mjs +38 -0
- package/hooks/lib/autopilot.mjs +240 -0
- package/hooks/lib/config.mjs +117 -0
- package/hooks/lib/decisiones.mjs +58 -0
- package/hooks/lib/design-gaps.mjs +272 -0
- package/hooks/lib/execution-context.mjs +69 -0
- package/hooks/lib/freeform-fragment.mjs +379 -0
- package/hooks/lib/freeform-path.mjs +115 -0
- package/hooks/lib/handoff-builder.mjs +388 -0
- package/hooks/lib/heartbeat-send.mjs +91 -0
- package/hooks/lib/heartbeat.mjs +110 -0
- package/hooks/lib/mcp-client-io.mjs +210 -0
- package/hooks/lib/mcp-client.mjs +91 -0
- package/hooks/lib/native-reservation-revalidate.mjs +80 -0
- package/hooks/lib/output.mjs +70 -0
- package/hooks/lib/ownership-map.mjs +162 -0
- package/hooks/lib/token-counter.mjs +81 -0
- package/hooks/lib/utils.mjs +235 -0
- package/hooks/no-bypass-guard.mjs +57 -0
- package/hooks/on-session-end.mjs +163 -0
- package/hooks/pipeline-phase-guard.mjs +140 -0
- package/hooks/post-implement-validate.mjs +61 -0
- package/hooks/pre-commit-lint.mjs +76 -0
- package/hooks/pre-prd-discovery-check.mjs +242 -0
- package/hooks/pre-read-budget-guard.mjs +83 -0
- package/hooks/quality-first-guard.mjs +85 -0
- package/hooks/read-tracker.mjs +33 -0
- package/hooks/session-heartbeat.mjs +113 -0
- package/hooks/session-start.mjs +159 -0
- package/hooks/settings-hooks.json +363 -0
- package/hooks/spec-guard.mjs +152 -0
- package/hooks/stripe-safety-guard.mjs +262 -0
- package/hooks/uc-lifecycle-guard.mjs +87 -0
- package/lib/hooks.mjs +156 -0
- package/lib/install.mjs +9 -0
- package/lib/internal.mjs +26 -3
- package/lib/mcp-headers.mjs +31 -3
- package/lib/messages.mjs +41 -0
- package/package.json +4 -2
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/handoff-builder.mjs — Builds .quality/handoff.md from local state.
|
|
3
|
+
*
|
|
4
|
+
* Used by:
|
|
5
|
+
* - .claude/skills/handoff/SKILL.md (skill flow)
|
|
6
|
+
* - .claude/hooks/on-session-end.mjs (auto fallback)
|
|
7
|
+
*
|
|
8
|
+
* Public API:
|
|
9
|
+
* buildHandoffData(opts) → object with all fields needed by the template
|
|
10
|
+
* renderHandoff(data, narrative) → final Markdown string
|
|
11
|
+
* writeHandoff(narrative, opts) → writes to .quality/handoff.md and returns { path, data }
|
|
12
|
+
*
|
|
13
|
+
* Design: all "mechanical" fields are auto-populated. The skill is responsible
|
|
14
|
+
* for asking the model to fill the narrative parts (what_this_session_did,
|
|
15
|
+
* decisions_taken, open_questions, next_concrete_step) and passing them in.
|
|
16
|
+
*
|
|
17
|
+
* Engram and heartbeat side-effects live in the skill, not here. This module
|
|
18
|
+
* is pure I/O on the local filesystem so it's testable in isolation.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'fs';
|
|
22
|
+
import { createHash } from 'crypto';
|
|
23
|
+
import { basename, join } from 'path';
|
|
24
|
+
import {
|
|
25
|
+
git,
|
|
26
|
+
readJsonFile,
|
|
27
|
+
findFiles,
|
|
28
|
+
fileExists,
|
|
29
|
+
mkdir,
|
|
30
|
+
now,
|
|
31
|
+
} from './utils.mjs';
|
|
32
|
+
|
|
33
|
+
const HANDOFF_PATH = '.quality/handoff.md';
|
|
34
|
+
const MAX_CHARS = 14000;
|
|
35
|
+
const MAX_HOT_FILES = 8;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Generate a deterministic 12-char session_id from cwd + date.
|
|
39
|
+
* Same cwd on the same day yields the same id (useful for de-dup).
|
|
40
|
+
*/
|
|
41
|
+
export function computeSessionId(cwd, date) {
|
|
42
|
+
const d = (date || new Date().toISOString()).slice(0, 10);
|
|
43
|
+
return createHash('sha256').update(`${cwd}:${d}`).digest('hex').slice(0, 12);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read the most recent checkpoint and return { feature, phase, phase_name }.
|
|
48
|
+
*/
|
|
49
|
+
function readLatestCheckpoint() {
|
|
50
|
+
const files = findFiles('.quality/evidence', /^checkpoint\.json$/);
|
|
51
|
+
if (files.length === 0) return null;
|
|
52
|
+
let latest = null;
|
|
53
|
+
let latestMtime = 0;
|
|
54
|
+
for (const f of files) {
|
|
55
|
+
try {
|
|
56
|
+
const m = statSync(f).mtimeMs;
|
|
57
|
+
if (m > latestMtime) {
|
|
58
|
+
latestMtime = m;
|
|
59
|
+
latest = f;
|
|
60
|
+
}
|
|
61
|
+
} catch { /* ignore */ }
|
|
62
|
+
}
|
|
63
|
+
if (!latest) return null;
|
|
64
|
+
const cp = readJsonFile(latest);
|
|
65
|
+
if (!cp) return null;
|
|
66
|
+
return {
|
|
67
|
+
path: latest,
|
|
68
|
+
feature: cp.feature || '',
|
|
69
|
+
phase: cp.phase || null,
|
|
70
|
+
phase_name: cp.phase_name || '',
|
|
71
|
+
branch: cp.branch || '',
|
|
72
|
+
timestamp: cp.timestamp || '',
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Read .quality/active_uc.json if present.
|
|
78
|
+
*/
|
|
79
|
+
function readActiveUC() {
|
|
80
|
+
const data = readJsonFile('.quality/active_uc.json');
|
|
81
|
+
if (!data) return null;
|
|
82
|
+
return {
|
|
83
|
+
uc_id: data.uc_id || data.feature || null,
|
|
84
|
+
started_at: data.started_at || null,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Detect the configured backend from .claude/settings.local.json or app_spec.md.
|
|
90
|
+
* Returns 'freeform' | 'trello' | 'plane' | 'unknown'.
|
|
91
|
+
*/
|
|
92
|
+
function detectBackend() {
|
|
93
|
+
const settings = readJsonFile('.claude/settings.local.json');
|
|
94
|
+
if (settings?.specbox?.backend_type) return settings.specbox.backend_type;
|
|
95
|
+
if (settings?.trello?.boardId) return 'trello';
|
|
96
|
+
if (settings?.plane?.projectId) return 'plane';
|
|
97
|
+
if (existsSync('doc/tracking/items.json')) return 'freeform';
|
|
98
|
+
return 'unknown';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Count healing events from latest healing.jsonl.
|
|
103
|
+
*/
|
|
104
|
+
function countHealingEvents() {
|
|
105
|
+
const files = findFiles('.quality/evidence', /^healing\.jsonl$/);
|
|
106
|
+
if (files.length === 0) return 0;
|
|
107
|
+
let total = 0;
|
|
108
|
+
for (const f of files) {
|
|
109
|
+
try {
|
|
110
|
+
total += readFileSync(f, 'utf-8').split('\n').filter(Boolean).length;
|
|
111
|
+
} catch { /* ignore */ }
|
|
112
|
+
}
|
|
113
|
+
return total;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Count blocking feedback (severity critical|major and status=open).
|
|
118
|
+
*/
|
|
119
|
+
function countBlockingFeedback() {
|
|
120
|
+
const files = findFiles('.quality/evidence', /^FB-.*\.json$/);
|
|
121
|
+
let blocking = 0;
|
|
122
|
+
for (const f of files) {
|
|
123
|
+
const fb = readJsonFile(f);
|
|
124
|
+
if (!fb) continue;
|
|
125
|
+
if ((fb.status || 'open') !== 'open') continue;
|
|
126
|
+
const sev = fb.severity || 'minor';
|
|
127
|
+
if (sev === 'critical' || sev === 'major') blocking++;
|
|
128
|
+
}
|
|
129
|
+
return blocking;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Estimate context tokens used in this session by summing chars of changed files.
|
|
134
|
+
* Same heuristic on-session-end.mjs uses (chars / 4).
|
|
135
|
+
*/
|
|
136
|
+
function estimateContextTokens() {
|
|
137
|
+
const changed = new Set();
|
|
138
|
+
const diff = git('diff --name-only HEAD');
|
|
139
|
+
const cached = git('diff --cached --name-only');
|
|
140
|
+
if (diff) diff.split('\n').filter(Boolean).forEach((f) => changed.add(f));
|
|
141
|
+
if (cached) cached.split('\n').filter(Boolean).forEach((f) => changed.add(f));
|
|
142
|
+
let chars = 0;
|
|
143
|
+
for (const f of changed) {
|
|
144
|
+
if (existsSync(f)) {
|
|
145
|
+
try {
|
|
146
|
+
chars += readFileSync(f, 'utf-8').length;
|
|
147
|
+
} catch { /* ignore */ }
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return Math.floor(chars / 4);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Top N changed files by patch size in current diff.
|
|
155
|
+
*/
|
|
156
|
+
function topHotFiles(limit = MAX_HOT_FILES) {
|
|
157
|
+
const stat = git(`diff --stat HEAD`);
|
|
158
|
+
if (!stat) return [];
|
|
159
|
+
const files = [];
|
|
160
|
+
for (const line of stat.split('\n')) {
|
|
161
|
+
const m = line.match(/^\s*([^|]+?)\s*\|\s*(\d+)/);
|
|
162
|
+
if (m) {
|
|
163
|
+
files.push({ path: m[1].trim(), changes: Number(m[2]) });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
files.sort((a, b) => b.changes - a.changes);
|
|
167
|
+
return files.slice(0, limit).map((f) => f.path);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The newest of `paths` whose text names `ucId` (UC-11006: a plan or PRD covers several UCs). */
|
|
171
|
+
function newestMentioning(paths, ucId) {
|
|
172
|
+
if (!/^UC-/i.test(ucId || '')) return null;
|
|
173
|
+
const named = new RegExp(`\\b${ucId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
|
|
174
|
+
const withTime = paths.flatMap((p) => {
|
|
175
|
+
try {
|
|
176
|
+
return [{ p, t: statSync(p).mtimeMs }];
|
|
177
|
+
} catch {
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
for (const { p } of withTime.sort((a, b) => b.t - a.t)) {
|
|
182
|
+
try {
|
|
183
|
+
if (named.test(readFileSync(p, 'utf-8').slice(0, 400_000))) return p;
|
|
184
|
+
} catch { /* unreadable: next */ }
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function listDir(dir) {
|
|
190
|
+
try {
|
|
191
|
+
return readdirSync(dir);
|
|
192
|
+
} catch {
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Resolve known pointer paths: plan, prd, checkpoint.
|
|
199
|
+
*
|
|
200
|
+
* UC-11006: /prd writes doc/prd/<feature>/prd.md and /plan doc/plans/<name>_plan.md, where
|
|
201
|
+
* <feature> and <name> are the feature slug of the checkpoint or a story id, not the active UC.
|
|
202
|
+
* Exact paths for the UC and the feature first (the old doc/prds/… and uc_… ones still count);
|
|
203
|
+
* then the newest plan or PRD that names the active UC. Nothing found → null, never a guess.
|
|
204
|
+
*/
|
|
205
|
+
function resolvePointers(active) {
|
|
206
|
+
const keys = [...new Set([active?.feature, active?.checkpointFeature].filter(Boolean))];
|
|
207
|
+
const out = { plan: null, prd: null, checkpoint: null };
|
|
208
|
+
if (keys.length === 0) return out;
|
|
209
|
+
|
|
210
|
+
const exact = (paths) => paths.find((p) => existsSync(p)) || null;
|
|
211
|
+
const slugs = keys.flatMap((k) => [k, k.toLowerCase().replace(/^uc-/, 'uc_')]);
|
|
212
|
+
|
|
213
|
+
out.plan = exact(slugs.map((k) => `doc/plans/${k}_plan.md`))
|
|
214
|
+
|| newestMentioning(listDir('doc/plans').filter((f) => f.endsWith('.md')).map((f) => join('doc/plans', f)), active?.feature);
|
|
215
|
+
|
|
216
|
+
out.prd = exact(keys.flatMap((k) => [`doc/prd/${k}/prd.md`]).concat(slugs.map((k) => `doc/prds/${k}_prd.md`)))
|
|
217
|
+
|| newestMentioning(listDir('doc/prd').map((d) => join('doc/prd', d, 'prd.md')).filter((p) => existsSync(p)), active?.feature);
|
|
218
|
+
|
|
219
|
+
out.checkpoint = exact(keys.map((k) => `.quality/evidence/${k}/checkpoint.json`));
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Build the mechanical part of the handoff (everything except narrative bullets).
|
|
225
|
+
*
|
|
226
|
+
* @param {object} opts
|
|
227
|
+
* @param {string} [opts.trigger='manual']
|
|
228
|
+
* @param {string} [opts.cwd=process.cwd()]
|
|
229
|
+
* @returns {object} data structure for the template
|
|
230
|
+
*/
|
|
231
|
+
export function buildHandoffData(opts = {}) {
|
|
232
|
+
const trigger = opts.trigger || 'manual';
|
|
233
|
+
const cwd = opts.cwd || process.cwd();
|
|
234
|
+
const project = basename(cwd).replace(/_/g, '-');
|
|
235
|
+
const generatedAt = now();
|
|
236
|
+
const sessionId = computeSessionId(cwd, generatedAt);
|
|
237
|
+
|
|
238
|
+
const branch = git('branch --show-current') || 'unknown';
|
|
239
|
+
const lastCommitSha = git('log -1 --pretty=format:%h') || 'unknown';
|
|
240
|
+
const lastCommitSubject = git('log -1 --pretty=format:%s') || '';
|
|
241
|
+
|
|
242
|
+
const activeUC = readActiveUC();
|
|
243
|
+
const checkpoint = readLatestCheckpoint();
|
|
244
|
+
|
|
245
|
+
let activeUCDisplay = 'none';
|
|
246
|
+
let activeUCId = null;
|
|
247
|
+
if (activeUC?.uc_id) {
|
|
248
|
+
activeUCId = activeUC.uc_id;
|
|
249
|
+
if (checkpoint?.feature === activeUC.uc_id && checkpoint.phase) {
|
|
250
|
+
activeUCDisplay = `${activeUC.uc_id} (Phase ${checkpoint.phase} — ${checkpoint.phase_name})`;
|
|
251
|
+
} else {
|
|
252
|
+
activeUCDisplay = activeUC.uc_id;
|
|
253
|
+
}
|
|
254
|
+
} else if (checkpoint?.feature) {
|
|
255
|
+
activeUCId = checkpoint.feature;
|
|
256
|
+
activeUCDisplay = checkpoint.phase
|
|
257
|
+
? `${checkpoint.feature} (Phase ${checkpoint.phase} — ${checkpoint.phase_name})`
|
|
258
|
+
: checkpoint.feature;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const hotFiles = topHotFiles();
|
|
262
|
+
const pointers = resolvePointers({ feature: activeUCId, checkpointFeature: checkpoint?.feature });
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
generated_at: generatedAt,
|
|
266
|
+
schema_version: 1,
|
|
267
|
+
project,
|
|
268
|
+
session_id: sessionId,
|
|
269
|
+
trigger,
|
|
270
|
+
ttl_minutes: 1440,
|
|
271
|
+
branch,
|
|
272
|
+
active_uc: activeUCId,
|
|
273
|
+
active_uc_display: activeUCDisplay,
|
|
274
|
+
backend: detectBackend(),
|
|
275
|
+
last_commit_sha: lastCommitSha,
|
|
276
|
+
last_commit_subject: lastCommitSubject,
|
|
277
|
+
healing_events: countHealingEvents(),
|
|
278
|
+
blocking_feedback: countBlockingFeedback(),
|
|
279
|
+
context_tokens_est: estimateContextTokens(),
|
|
280
|
+
hot_files: hotFiles,
|
|
281
|
+
pointers,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function renderBullets(items, fallback = '_(none)_') {
|
|
286
|
+
if (!items || items.length === 0) return fallback;
|
|
287
|
+
return items.map((s) => `- ${s}`).join('\n');
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function redactSecrets(text) {
|
|
291
|
+
if (!text) return text;
|
|
292
|
+
return text
|
|
293
|
+
.replace(/sk_live_[A-Za-z0-9_-]+/g, '<redacted-stripe-key>')
|
|
294
|
+
.replace(/sk_test_[A-Za-z0-9_-]+/g, '<redacted-stripe-test-key>')
|
|
295
|
+
.replace(/(?:^|[^A-Za-z0-9_])([A-Za-z0-9_-]{32,})(?=[^A-Za-z0-9_]|$)/g, (m, tok) => {
|
|
296
|
+
if (/^[a-f0-9]{40,}$/i.test(tok)) return m;
|
|
297
|
+
return m.replace(tok, '<redacted-token>');
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Render the full Markdown using the data + narrative bullets supplied by the skill.
|
|
303
|
+
*
|
|
304
|
+
* @param {object} data — output of buildHandoffData
|
|
305
|
+
* @param {object} narrative
|
|
306
|
+
* @param {string[]} [narrative.what_this_session_did]
|
|
307
|
+
* @param {string[]} [narrative.decisions_taken]
|
|
308
|
+
* @param {string[]} [narrative.open_questions]
|
|
309
|
+
* @param {string} [narrative.next_concrete_step]
|
|
310
|
+
* @returns {string} the rendered Markdown
|
|
311
|
+
*/
|
|
312
|
+
export function renderHandoff(data, narrative = {}) {
|
|
313
|
+
const what = renderBullets(narrative.what_this_session_did);
|
|
314
|
+
const decisions = renderBullets(narrative.decisions_taken);
|
|
315
|
+
const questions = renderBullets(narrative.open_questions);
|
|
316
|
+
const nextStep = redactSecrets(narrative.next_concrete_step) || '_(none)_';
|
|
317
|
+
|
|
318
|
+
const hotFilesBlock = renderBullets(data.hot_files);
|
|
319
|
+
|
|
320
|
+
const pointerLines = [];
|
|
321
|
+
if (data.pointers.plan) pointerLines.push(`Plan: ${data.pointers.plan}`);
|
|
322
|
+
if (data.pointers.prd) pointerLines.push(`PRD: ${data.pointers.prd}`);
|
|
323
|
+
if (data.pointers.checkpoint) pointerLines.push(`Checkpoint: ${data.pointers.checkpoint}`);
|
|
324
|
+
if (narrative.engram_obs_id) pointerLines.push(`Engram observation_id: ${narrative.engram_obs_id}`);
|
|
325
|
+
const pointers = renderBullets(pointerLines);
|
|
326
|
+
|
|
327
|
+
const md = `---
|
|
328
|
+
generated_at: ${data.generated_at}
|
|
329
|
+
generator: specbox-handoff-v1
|
|
330
|
+
schema_version: ${data.schema_version}
|
|
331
|
+
project: ${data.project}
|
|
332
|
+
session_id: ${data.session_id}
|
|
333
|
+
trigger: ${data.trigger}
|
|
334
|
+
ttl_minutes: ${data.ttl_minutes}
|
|
335
|
+
branch: ${data.branch}
|
|
336
|
+
active_uc: ${data.active_uc === null ? 'null' : data.active_uc}
|
|
337
|
+
---
|
|
338
|
+
|
|
339
|
+
# SpecBox Handoff — ${data.project}
|
|
340
|
+
|
|
341
|
+
## State snapshot
|
|
342
|
+
- **Branch**: ${data.branch}
|
|
343
|
+
- **Active UC**: ${data.active_uc_display}
|
|
344
|
+
- **Backend**: ${data.backend}
|
|
345
|
+
- **Last commit**: ${data.last_commit_sha} "${data.last_commit_subject}"
|
|
346
|
+
- **Healing events this session**: ${data.healing_events}
|
|
347
|
+
- **Open feedback (blocking)**: ${data.blocking_feedback}
|
|
348
|
+
- **Context tokens estimated this session**: ${data.context_tokens_est}
|
|
349
|
+
|
|
350
|
+
## What this session did
|
|
351
|
+
${redactSecrets(what)}
|
|
352
|
+
|
|
353
|
+
## Decisions taken (with key)
|
|
354
|
+
${redactSecrets(decisions)}
|
|
355
|
+
|
|
356
|
+
## Open questions
|
|
357
|
+
${redactSecrets(questions)}
|
|
358
|
+
|
|
359
|
+
## Hot files (top N by edits this session)
|
|
360
|
+
${hotFilesBlock}
|
|
361
|
+
|
|
362
|
+
## Next concrete step
|
|
363
|
+
${nextStep}
|
|
364
|
+
|
|
365
|
+
## Pointers para la próxima sesión
|
|
366
|
+
${pointers}
|
|
367
|
+
`;
|
|
368
|
+
|
|
369
|
+
if (md.length > MAX_CHARS) {
|
|
370
|
+
return md.slice(0, MAX_CHARS - 100) + '\n\n_(truncated to fit max size)_\n';
|
|
371
|
+
}
|
|
372
|
+
return md;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Write handoff to .quality/handoff.md.
|
|
377
|
+
*
|
|
378
|
+
* @param {object} narrative — narrative bullets (see renderHandoff)
|
|
379
|
+
* @param {object} [opts]
|
|
380
|
+
* @returns {{ path: string, data: object }}
|
|
381
|
+
*/
|
|
382
|
+
export function writeHandoff(narrative = {}, opts = {}) {
|
|
383
|
+
mkdir('.quality');
|
|
384
|
+
const data = buildHandoffData(opts);
|
|
385
|
+
const md = renderHandoff(data, narrative);
|
|
386
|
+
writeFileSync(HANDOFF_PATH, md, 'utf-8');
|
|
387
|
+
return { path: HANDOFF_PATH, data };
|
|
388
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* lib/heartbeat-send.mjs — envía un latido al board, en su propio proceso (US-99 · UC-9901).
|
|
4
|
+
*
|
|
5
|
+
* Lo lanza session-heartbeat.mjs sin esperarlo: la sesión nunca espera al board. Usa la misma
|
|
6
|
+
* credencial que Claude Code para el MCP de SpecBox (~/.specbox/bin/mcp-headers.mjs) y un tope de
|
|
7
|
+
* 3 s. Si el board no responde, lo anota en .quality/logs/heartbeat.log, como mucho una vez por
|
|
8
|
+
* minuto, y termina (AC-03). Nunca escribe la credencial ni el latido en el registro.
|
|
9
|
+
*
|
|
10
|
+
* Uso: node heartbeat-send.mjs <raíz del repo> '<latido en JSON>'
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync, realpathSync } from 'node:fs';
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { pathToFileURL } from 'node:url';
|
|
17
|
+
import { llamarTool } from './mcp-client.mjs';
|
|
18
|
+
|
|
19
|
+
export const URL_POR_DEFECTO = 'https://mcp.specbox.build/mcp';
|
|
20
|
+
export const REGISTRO = '.quality/logs/heartbeat.log';
|
|
21
|
+
const MARCA = '.quality/heartbeat_error.json';
|
|
22
|
+
|
|
23
|
+
/** Anota un fallo si no se anotó otro en el último minuto. Devuelve si lo anotó. */
|
|
24
|
+
export function anotarFallo(raiz, motivo, ahora = Date.now()) {
|
|
25
|
+
const marca = join(raiz, MARCA);
|
|
26
|
+
let ultimo = 0;
|
|
27
|
+
try {
|
|
28
|
+
ultimo = JSON.parse(readFileSync(marca, 'utf8')).at || 0;
|
|
29
|
+
} catch {
|
|
30
|
+
ultimo = 0;
|
|
31
|
+
}
|
|
32
|
+
if (ahora - ultimo < 60_000) return false;
|
|
33
|
+
try {
|
|
34
|
+
mkdirSync(join(raiz, '.quality/logs'), { recursive: true });
|
|
35
|
+
appendFileSync(join(raiz, REGISTRO), `${new Date(ahora).toISOString()} latido no enviado: ${motivo}\n`);
|
|
36
|
+
writeFileSync(marca, JSON.stringify({ at: ahora }));
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** La cabecera Authorization del dispositivo, o {} si este equipo no tiene credencial. */
|
|
44
|
+
export async function cabecerasDelDispositivo(env = process.env) {
|
|
45
|
+
const ayudante = join(env.SPECBOX_HOME || join(homedir(), '.specbox'), 'bin', 'mcp-headers.mjs');
|
|
46
|
+
try {
|
|
47
|
+
const modulo = await import(pathToFileURL(ayudante).href);
|
|
48
|
+
return (await modulo.headersFor({ env })) || {};
|
|
49
|
+
} catch {
|
|
50
|
+
return {};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Manda el latido. Nunca lanza: devuelve true si el board lo aceptó. */
|
|
55
|
+
export async function enviarLatido({ raiz, latido, env = process.env, fetchImpl = fetch, cabeceras, ahora = Date.now }) {
|
|
56
|
+
const url = env.SPECBOX_MCP_URL || URL_POR_DEFECTO;
|
|
57
|
+
const h = cabeceras ?? (await cabecerasDelDispositivo({ ...env, CLAUDE_CODE_MCP_SERVER_URL: url }));
|
|
58
|
+
if (!h.Authorization) {
|
|
59
|
+
anotarFallo(raiz, 'este equipo no tiene credencial de SpecBox (specbox login)', ahora());
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const r = await llamarTool({ url, cabeceras: h, nombre: 'report_session_heartbeat', args: latido, fetchImpl });
|
|
64
|
+
if (r?.success === false) {
|
|
65
|
+
anotarFallo(raiz, `el board lo rechazó (${r.code || 'sin código'})`, ahora());
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
} catch (err) {
|
|
70
|
+
anotarFallo(raiz, err?.message || 'fallo', ahora());
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const directo = (() => {
|
|
76
|
+
try {
|
|
77
|
+
return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
|
|
78
|
+
} catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
})();
|
|
82
|
+
if (directo) {
|
|
83
|
+
let latido = null;
|
|
84
|
+
try {
|
|
85
|
+
latido = JSON.parse(process.argv[3] || 'null');
|
|
86
|
+
} catch {
|
|
87
|
+
latido = null;
|
|
88
|
+
}
|
|
89
|
+
const raiz = process.argv[2] || process.cwd();
|
|
90
|
+
(latido ? enviarLatido({ raiz, latido }) : Promise.resolve(false)).finally(() => process.exit(0));
|
|
91
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/heartbeat.mjs — el latido de la sesión (US-99 · UC-9901), sin efectos.
|
|
3
|
+
*
|
|
4
|
+
* Calcula qué decir al board (UC, fase, si espera) a partir del evento del hook y de lo que hay
|
|
5
|
+
* en el repo, y decide si toca enviarlo: al empezar y al cerrar siempre; si cambió la UC, la fase
|
|
6
|
+
* o la espera, en el acto; si no, como mucho cada dos minutos (AC-01). Solo campos enumerados o de
|
|
7
|
+
* forma fija: nunca texto de la conversación ni de las specs.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Cada cuánto, como mucho, se repite un latido sin cambios. */
|
|
11
|
+
export const INTERVALO_MS = 2 * 60 * 1000;
|
|
12
|
+
|
|
13
|
+
/** Las fases que acepta el board (CHECK de la migración 0031). */
|
|
14
|
+
export const FASES = ['idle', 'discovery', 'prd', 'plan', 'design', 'implement', 'tests', 'review', 'release'];
|
|
15
|
+
|
|
16
|
+
const UC = /^UC-[0-9]{1,6}[a-z]?$/;
|
|
17
|
+
const SESION = /^[A-Za-z0-9-]{8,64}$/;
|
|
18
|
+
|
|
19
|
+
/** La UC activa: la del marcador si es reciente, si no la de la rama `feature/UC-1234-…`. */
|
|
20
|
+
export function ucActiva({ marcador, rama } = {}) {
|
|
21
|
+
const delMarcador = (marcador?.uc_id || '').trim();
|
|
22
|
+
if (UC.test(delMarcador)) return delMarcador;
|
|
23
|
+
const m = /(?:^|\/)uc-([0-9]{1,6}[a-z]?)(?:[-_/]|$)/i.exec(rama || '');
|
|
24
|
+
return m ? `UC-${m[1].replace(/[a-z]$/i, (letra) => letra.toLowerCase())}` : null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Ids de fase de pipeline_state.json (/implement) → fase del board. */
|
|
28
|
+
const DE_PIPELINE = {
|
|
29
|
+
init: 'plan',
|
|
30
|
+
db_infra: 'implement',
|
|
31
|
+
stitch_designs: 'design',
|
|
32
|
+
design_to_code: 'design',
|
|
33
|
+
feature_code: 'implement',
|
|
34
|
+
appscript: 'implement',
|
|
35
|
+
n8n: 'implement',
|
|
36
|
+
integration: 'implement',
|
|
37
|
+
tests: 'tests',
|
|
38
|
+
qa: 'tests',
|
|
39
|
+
acceptance: 'tests',
|
|
40
|
+
pr: 'review',
|
|
41
|
+
merge: 'review',
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** Palabras del nombre de un checkpoint → fase (el primero que encaje). */
|
|
45
|
+
const PALABRAS = [
|
|
46
|
+
[/discovery/i, 'discovery'],
|
|
47
|
+
[/\bprd\b/i, 'prd'],
|
|
48
|
+
[/\bplan\b/i, 'plan'],
|
|
49
|
+
[/dise[ñn]o|design|lienzo|canvas/i, 'design'],
|
|
50
|
+
[/\bpruebas?\b|\btests?\b|\bqa\b|acceptance|aceptaci/i, 'tests'],
|
|
51
|
+
[/revisi[oó]n|review|\bpr\b|merge|fusi/i, 'review'],
|
|
52
|
+
[/release|publica/i, 'release'],
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* La fase: la de pipeline_state.json si la hay; si no, la del último checkpoint reciente (menos de
|
|
57
|
+
* dos horas); si no, `implement` con UC activa e `idle` sin ella.
|
|
58
|
+
*/
|
|
59
|
+
export function faseActual({ pipeline, checkpoint, checkpointEdadS, uc } = {}) {
|
|
60
|
+
const deP = DE_PIPELINE[pipeline?.current_phase];
|
|
61
|
+
if (deP) return deP;
|
|
62
|
+
if (checkpoint && (checkpointEdadS ?? Infinity) < 2 * 3600) {
|
|
63
|
+
const nombre = String(checkpoint.phase_name || '');
|
|
64
|
+
for (const [re, fase] of PALABRAS) if (re.test(nombre)) return fase;
|
|
65
|
+
return 'implement';
|
|
66
|
+
}
|
|
67
|
+
return uc ? 'implement' : 'idle';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Qué espera la sesión según el evento: una notificación de permiso → `permission`; la de
|
|
72
|
+
* inactividad («esperando tu respuesta») → `decision`; la persona escribe o una tool termina →
|
|
73
|
+
* `none`; el resto conserva lo que había.
|
|
74
|
+
*/
|
|
75
|
+
export function esperaTras(evento, entrada = {}, anterior = 'none') {
|
|
76
|
+
if (evento === 'Notification') {
|
|
77
|
+
const tipo = String(entrada.notification_type || '');
|
|
78
|
+
const texto = String(entrada.message || '');
|
|
79
|
+
if (tipo === 'permission_prompt' || /permission|permiso/i.test(texto)) return 'permission';
|
|
80
|
+
if (tipo === 'idle_prompt' || /waiting for your input|esperando/i.test(texto)) return 'decision';
|
|
81
|
+
return anterior;
|
|
82
|
+
}
|
|
83
|
+
if (evento === 'UserPromptSubmit' || evento === 'PostToolUse') return 'none';
|
|
84
|
+
if (evento === 'SessionStart' || evento === 'SessionEnd') return 'none';
|
|
85
|
+
return anterior;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** El latido que se enviaría, o null si no hay sesión o proyecto native que decir. */
|
|
89
|
+
export function latido({ evento, entrada = {}, proyecto, marcador, rama, pipeline, checkpoint, checkpointEdadS, anterior }) {
|
|
90
|
+
const sesion = String(entrada.session_id || '');
|
|
91
|
+
if (!SESION.test(sesion) || !proyecto) return null;
|
|
92
|
+
const uc = ucActiva({ marcador, rama });
|
|
93
|
+
return {
|
|
94
|
+
project_id: proyecto,
|
|
95
|
+
session_id: sesion,
|
|
96
|
+
uc_id: uc,
|
|
97
|
+
phase: faseActual({ pipeline, checkpoint, checkpointEdadS, uc }),
|
|
98
|
+
waiting: esperaTras(evento, entrada, anterior?.session_id === sesion ? anterior.waiting : 'none'),
|
|
99
|
+
ended: evento === 'SessionEnd',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** ¿Toca enviarlo? Al empezar y al cerrar, siempre; si cambió algo, ya; si no, cada dos minutos. */
|
|
104
|
+
export function tocaEnviar(nuevo, anterior, ahora) {
|
|
105
|
+
if (!nuevo) return false;
|
|
106
|
+
if (nuevo.ended) return true;
|
|
107
|
+
if (!anterior || anterior.session_id !== nuevo.session_id) return true;
|
|
108
|
+
for (const k of ['uc_id', 'phase', 'waiting']) if (anterior[k] !== nuevo[k]) return true;
|
|
109
|
+
return ahora - (anterior.sent_at || 0) >= INTERVALO_MS;
|
|
110
|
+
}
|