spequi 0.1.7 → 0.1.9

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 (45) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +27 -12
  3. package/bin/spequi.mjs +5 -3
  4. package/docs/agent-workflow.md +28 -4
  5. package/package.json +1 -1
  6. package/public/app.css +52 -2
  7. package/public/app.js +133 -64
  8. package/public/diff.css +62 -39
  9. package/public/index.html +230 -189
  10. package/public/requests.js +54 -27
  11. package/public/review.css +21 -4
  12. package/public/review.js +85 -50
  13. package/public/session.js +34 -20
  14. package/public/studio.css +191 -33
  15. package/public/studio.js +1 -1
  16. package/public/workflow.js +92 -6
  17. package/skills/spequi/SKILL.md +29 -10
  18. package/src/analytics.mjs +50 -16
  19. package/src/branches.mjs +52 -0
  20. package/src/commands.mjs +4 -41
  21. package/src/comment-controls.mjs +1 -1
  22. package/src/comment-view.mjs +6 -5
  23. package/src/creation-view.mjs +10 -3
  24. package/src/diff-view.mjs +3 -3
  25. package/src/document-view.mjs +9 -2
  26. package/src/drafts.mjs +19 -4
  27. package/src/feedback.mjs +2 -0
  28. package/src/jobs.mjs +71 -18
  29. package/src/lifecycle.mjs +12 -9
  30. package/src/plan-git.mjs +129 -0
  31. package/src/preview-view.mjs +14 -9
  32. package/src/previews.mjs +4 -1
  33. package/src/project.mjs +3 -2
  34. package/src/requests.mjs +1 -1
  35. package/src/review-images.mjs +51 -0
  36. package/src/review-store.mjs +16 -16
  37. package/src/review-view.mjs +3 -2
  38. package/src/server.mjs +54 -20
  39. package/src/source-preview-view.mjs +4 -4
  40. package/src/spec-context-view.mjs +3 -3
  41. package/src/spec-context.mjs +11 -8
  42. package/src/studio-view.mjs +64 -27
  43. package/src/updates.mjs +82 -0
  44. package/src/verification.mjs +6 -0
  45. package/src/views.mjs +53 -15
@@ -0,0 +1,51 @@
1
+ import fs from 'node:fs/promises';
2
+ import { randomUUID, createHash } from 'node:crypto';
3
+ import { within, safeID, readJSON, writeJSON, withLock } from './files.mjs';
4
+
5
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
6
+ const imageID = id => /^[a-f0-9-]{36}\.[a-z0-9]{1,12}$/.test(id || '');
7
+ const imagePath = (scope, id) => `.spequi/reviews/${safeID(scope)}/images/${id}`;
8
+
9
+ export async function readReviewImage(root, scope, id) {
10
+ if (!imageID(id)) throw new Error('Invalid attachment reference');
11
+ const file = imagePath(scope, id);
12
+ const metadata = await readJSON(await within(root, file + '.json'));
13
+ if (!metadata) throw new Error('Attachment not found');
14
+ const bytes = await fs.readFile(await within(root, file));
15
+ if (digest(bytes) !== metadata.hash) throw new Error('Attachment changed since upload');
16
+ return { ...metadata, type: { png: 'image/png', jpg: 'image/jpeg', webp: 'image/webp' }[id.split('.').at(-1)] || 'application/octet-stream', id, file, url: `/api/reviews/${scope}/images/${id}`, bytes };
17
+ }
18
+
19
+ export async function saveReviewImage(root, scope, { name, data }) {
20
+ safeID(scope);
21
+ if (typeof data !== 'string' || data.length > 7 * 1024 * 1024 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw new Error('Choose a file up to 5 MiB');
22
+ const bytes = Buffer.from(data, 'base64');
23
+ if (bytes.length > 5 * 1024 * 1024) throw new Error('Choose a file up to 5 MiB');
24
+ const png = bytes.length >= 24 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) && bytes.toString('ascii', 12, 16) === 'IHDR';
25
+ const jpg = bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
26
+ const webp = bytes.length >= 16 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP';
27
+ name = String(name || 'Attachment').replace(/[\x00-\x1f\x7f]/g, '').split(/[\\/]/).at(-1).slice(0, 160) || 'Attachment';
28
+ let extension = name.split('.').length > 1 ? name.split('.').at(-1).toLowerCase() : 'bin';
29
+ if (!/^[a-z0-9]{1,12}$/.test(extension) || ['png', 'jpg', 'jpeg', 'webp'].includes(extension)) extension = 'bin';
30
+ const format = png ? ['image/png', 'png'] : jpg ? ['image/jpeg', 'jpg'] : webp ? ['image/webp', 'webp'] : ['application/octet-stream', extension];
31
+ if (png && (!bytes.readUInt32BE(16) || !bytes.readUInt32BE(20) || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 40000000)) throw new Error('Choose an image smaller than 40 megapixels');
32
+ return withLock(await within(root, `.spequi/reviews/${scope}/images.lock`), async () => {
33
+ const directory = await within(root, `.spequi/reviews/${scope}/images`);
34
+ await fs.mkdir(directory, { recursive: true });
35
+ let size = 0;
36
+ for (const file of await fs.readdir(directory)) if (imageID(file)) size += (await fs.stat(await within(root, imagePath(scope, file)))).size;
37
+ if (size + bytes.length > 100 * 1024 * 1024) throw new Error('This review has reached its 100 MiB attachment limit');
38
+ const id = `${randomUUID()}.${format[1]}`, file = imagePath(scope, id);
39
+ const metadata = { name, type: format[0], size: bytes.length, hash: digest(bytes) };
40
+ await fs.writeFile(await within(root, file), bytes, { flag: 'wx', mode: 0o600 });
41
+ await writeJSON(await within(root, file + '.json'), metadata);
42
+ return { ...metadata, id, file, url: `/api/reviews/${scope}/images/${id}` };
43
+ });
44
+ }
45
+
46
+ export async function commentImages(root, scope, value = []) {
47
+ let ids;
48
+ try { ids = typeof value === 'string' ? JSON.parse(value) : value; } catch { throw new Error('Invalid attachment references'); }
49
+ if (!Array.isArray(ids) || ids.length > 4 || new Set(ids).size !== ids.length) throw new Error('Attach up to four files');
50
+ return Promise.all(ids.map(async id => { const { bytes, ...image } = await readReviewImage(root, scope, id); return image; }));
51
+ }
@@ -1,3 +1,4 @@
1
+ import { commentImages, readReviewImage } from './review-images.mjs';
1
2
  import * as fs from 'node:fs/promises';
2
3
  import { randomUUID, createHash } from 'node:crypto';
3
4
  import { readJSON, writeJSON, within, safeID, withLock } from './files.mjs';
@@ -7,7 +8,7 @@ import { feedbackMarkdown, planningEvidence } from './feedback.mjs';
7
8
  export { feedbackMarkdown } from './feedback.mjs';
8
9
  export const artifactReviewID = change => `change-${createHash('sha256').update(change).digest('hex')}`;
9
10
  export const documentHash = source => createHash('sha256').update(source).digest('hex');
10
- export const isCommentableArtifact = (change, file) => Boolean(change && !change.archived && change.files.includes(file) && /\/(proposal|design)\.md$/.test(file) && !file.includes('/specs/'));
11
+ export const isCommentableArtifact = (change, file) => Boolean(change && !change.archived && change.files.includes(file) && file.endsWith('.md'));
11
12
 
12
13
  export async function reviewScope(root, preview) {
13
14
  safeID(preview);
@@ -43,10 +44,11 @@ export async function reviewComments(root, preview) {
43
44
  return [...comments, ...await listComments(root, artifactReviewID(scope.job.change))];
44
45
  }
45
46
 
46
- async function addArtifactComment(root, preview, { file, body, side = 'file', start = '', end = '', sourceHash }, scope) {
47
+ async function addArtifactComment(root, preview, { file, body, side = 'file', start = '', end = '', sourceHash, attachments }, scope) {
47
48
  const change = (await inventory(root)).changes.find(change => change.id === scope.job.change);
48
- if (!isCommentableArtifact(change, file)) throw new Error('Select Proposal or Design in this active change');
49
- if (typeof body !== 'string' || !body.trim() || body.length > 6000) throw new Error('Write a comment of 1–6,000 characters');
49
+ if (!isCommentableArtifact(change, file)) throw new Error('Select a planning document in this active change');
50
+ const images = await commentImages(root, preview, attachments);
51
+ if (typeof body !== 'string' || body.length > 6000 || !body.trim() && !images.length) throw new Error('Write a comment or attach a file (up to 6,000 characters)');
50
52
  if (!['file', 'document'].includes(side)) throw new Error('Invalid document comment side');
51
53
  const source = await readArtifact(root, file), hash = documentHash(source);
52
54
  if (sourceHash !== hash) throw new Error('This document changed. Reload it before commenting; your draft is still available.');
@@ -59,7 +61,7 @@ async function addArtifactComment(root, preview, { file, body, side = 'file', st
59
61
  if (snippet.length > 20000) throw new Error('Selected source is too large; comment on the entire document instead');
60
62
  }
61
63
  const sourcePath = `.spequi/reviews/${preview}/documents/${hash}.md`;
62
- const record = { id: randomUUID(), kind: 'artifact', preview, change: change.id, file, side, start: first, end: last, snippet, sourceHash: hash, sourcePath, body: body.trim(), createdAt: new Date().toISOString() };
64
+ const record = { id: randomUUID(), kind: 'artifact', preview, change: change.id, file, side, start: first, end: last, snippet, sourceHash: hash, sourcePath, images, body: body.trim(), createdAt: new Date().toISOString() };
63
65
  await location(root, preview);
64
66
  return withLock(await location(root, preview, 'review.lock'), async () => {
65
67
  const comments = await listComments(root, preview);
@@ -76,11 +78,12 @@ async function addArtifactComment(root, preview, { file, body, side = 'file', st
76
78
  export async function addComment(root, preview, payload) {
77
79
  const scope = await reviewScope(root, preview);
78
80
  if (scope.kind === 'artifacts') return addArtifactComment(root, preview, payload, scope);
79
- const { file, body, side = 'file', start = '', end = '' } = payload;
81
+ const { file, body, side = 'file', start = '', end = '', attachments } = payload;
80
82
  const { job, result } = scope;
81
83
  const change = result.changes.find(change => change.file === file);
82
84
  if (!change) throw new Error('Comment file is not part of this preview');
83
- if (typeof body !== 'string' || !body.trim() || body.length > 6000) throw new Error('Write a comment of 1–6,000 characters');
85
+ const images = await commentImages(root, preview, attachments);
86
+ if (typeof body !== 'string' || body.length > 6000 || !body.trim() && !images.length) throw new Error('Write a comment or attach a file (up to 6,000 characters)');
84
87
  if (!['file', 'current', 'proposed'].includes(side)) throw new Error('Invalid comment side');
85
88
  let first = null, last = null, snippet = '';
86
89
  if (side !== 'file') {
@@ -92,7 +95,7 @@ export async function addComment(root, preview, payload) {
92
95
  snippet = lines.slice(first - 1, last).join('\n');
93
96
  if (snippet.length > 20000) throw new Error('Selected source is too large; comment on the entire file instead');
94
97
  }
95
- const record = { id: randomUUID(), preview, change: job.change, file, side, start: first, end: last, snippet, beforeHash: change.beforeHash, afterHash: change.afterHash, body: body.trim(), createdAt: new Date().toISOString() };
98
+ const record = { id: randomUUID(), preview, change: job.change, file, side, start: first, end: last, snippet, beforeHash: change.beforeHash, afterHash: change.afterHash, images, body: body.trim(), createdAt: new Date().toISOString() };
96
99
  const store = await location(root, preview);
97
100
  return withLock(await location(root, preview, 'review.lock'), async () => {
98
101
  const comments = await readJSON(store, []);
@@ -112,6 +115,7 @@ export async function deleteComment(root, preview, id) {
112
115
  });
113
116
  }
114
117
 
118
+ // Retained snapshots feed agent updates and existing queued requests.
115
119
  export async function exportFeedback(root, preview) {
116
120
  const scope = await reviewScope(root, preview);
117
121
  return withLock(await location(root, preview, 'review.lock'), async () => {
@@ -121,12 +125,14 @@ export async function exportFeedback(root, preview) {
121
125
  const expected = `.spequi/reviews/${artifactReviewID(scope.job.change)}/documents/${comment.sourceHash}.md`;
122
126
  if (!/^[a-f0-9]{64}$/.test(comment.sourceHash) || comment.change !== scope.job.change || comment.sourcePath !== expected || documentHash(await fs.readFile(await within(root, expected), 'utf8')) !== comment.sourceHash) throw new Error('Retained document changed; restore it before exporting feedback');
123
127
  }
128
+ const images = [...new Map(comments.flatMap(comment => (comment.images || []).map(image => [image.file, { scope: comment.preview, id: image.id, hash: image.hash }]))).values()];
129
+ for (const image of images) if ((await readReviewImage(root, image.scope, image.id)).hash !== image.hash) throw new Error('An attachment changed; review it before exporting');
124
130
  const id = randomUUID(), exportedAt = new Date().toISOString();
125
131
  const relative = `.spequi/reviews/${preview}/feedback-${id}.md`;
126
132
  const planning = await planningEvidence(root, scope.job.change);
127
133
  const document = feedbackMarkdown({ ...scope, planning, exportId: id, exportFile: relative }, comments, exportedAt);
128
134
  await fs.writeFile(await within(root, relative), document, { flag: 'wx', mode: 0o600 });
129
- const record = { id, preview, change: scope.job.change, file: relative, exportedAt, count: comments.length, hash: createHash('sha256').update(document).digest('hex') };
135
+ const record = { id, preview, change: scope.job.change, file: relative, exportedAt, count: comments.length, images, hash: createHash('sha256').update(document).digest('hex') };
130
136
  await writeJSON(await location(root, preview, `export-${id}.json`), record);
131
137
  return record;
132
138
  });
@@ -139,12 +145,6 @@ export async function feedbackExport(root, preview, id) {
139
145
  const file = `.spequi/reviews/${preview}/feedback-${id}.md`;
140
146
  const document = await fs.readFile(await within(root, file), 'utf8');
141
147
  if (record.hash !== createHash('sha256').update(document).digest('hex')) throw new Error('Feedback document changed after export; create a new export');
148
+ for (const image of record.images || []) if ((await readReviewImage(root, image.scope, image.id)).hash !== image.hash) throw new Error('An exported attachment changed; create a new feedback snapshot');
142
149
  return { ...record, file, document };
143
150
  }
144
-
145
- export async function listFeedbackExports(root, preview) {
146
- const directory = await within(root, `.spequi/reviews/${safeID(preview)}`);
147
- const files = await fs.readdir(directory).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
148
- const records = await Promise.all(files.filter(file => /^export-[a-zA-Z0-9_-]+\.json$/.test(file)).map(async file => readJSON(await within(root, `.spequi/reviews/${preview}/${file}`))));
149
- return records.filter(Boolean).sort((a, b) => b.exportedAt.localeCompare(a.exportedAt)).slice(0, 3);
150
- }
@@ -13,11 +13,12 @@ export async function renderReviewContext({ root, params, selected, context, job
13
13
  for (const doc of selected.files.filter(file => isCommentableArtifact(selected, file))) {
14
14
  try { fileHashes[doc] = documentHash(await readArtifact(root, doc)); } catch {}
15
15
  }
16
- const base = { change: selected?.id, view: 'preview', job: job.id, mode: params.mode, wrap: params.wrap };
16
+ const base = { change: selected?.id, view: params.view === 'studio' ? 'studio' : 'preview', stage: 'shape', job: job.id, mode: params.mode, wrap: params.wrap };
17
17
  const feedback = renderComments({ comments, job, file, selected, jobs, base, fileHashes }, { icon, link });
18
18
  if (!showImpact || !file || !result) return feedback;
19
19
  let evidence;
20
20
  try { evidence = await dependencyImpact(root, job.id, file.file); }
21
21
  catch (error) { evidence = { error: error.message }; }
22
- return renderImpactPanel({ file, evidence, result, jobs, preview: job.id, base }, { icon, link }) + feedback;
22
+ const linkWarning = result.specContext?.invalidReport || result.specContext?.invalidFiles?.includes(file.file) ? '<p class="inspector-section">Some recorded spec links were invalid and are not shown. Only verified references appear beside code.</p>' : '';
23
+ return linkWarning + renderImpactPanel({ file, evidence, result, jobs, preview: job.id, base }, { icon, link }) + feedback;
23
24
  }
package/src/server.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { publishPlan, requestCommitMessage } from './plan-git.mjs';
2
+ import { saveReviewImage, readReviewImage } from './review-images.mjs';
1
3
  import http from 'node:http';
2
4
  import * as fs from 'node:fs/promises';
3
5
  import path from 'node:path';
@@ -11,8 +13,8 @@ import { exists, readJSON, writeJSON, runtime, isPreviewSnapshotPath, acquireLoc
11
13
  import { inventory, readArtifact, escape, jobMatchesChange } from './specs.mjs';
12
14
  import { listJobs, enqueue, updateJob, agentStatus, getJob, pendingStatuses, createJobReader, claimNext, heartbeat, stopPolling, queueStatus } from './jobs.mjs';
13
15
  import { applyPreview, previewResult } from './previews.mjs';
14
- import { workspace, shell } from './views.mjs';
15
- import { addComment, deleteComment, exportFeedback, feedbackExport } from './review-store.mjs';
16
+ import { workspace, shell, icon } from './views.mjs';
17
+ import { addComment, deleteComment, exportFeedback, reviewScope } from './review-store.mjs';
16
18
  import { analyzeChange } from './spec-impact.mjs';
17
19
  import { directPreview } from './direct-preview.mjs';
18
20
  import { requestLifecycle, previewPlanChanged } from './lifecycle.mjs';
@@ -22,9 +24,11 @@ import { reportSession } from './agent-session.mjs';
22
24
  import { createWorkspaceState } from './workspace-state.mjs';
23
25
  import { listDrafts, saveDraft, deleteDraft, resumeDraft } from './drafts.mjs';
24
26
  import { requestPage, deleteRequest, retryRequest, dismissRequest, inboxState } from './requests.mjs';
27
+ import { checkForUpdate } from './updates.mjs';
25
28
  import { viewerVersion } from './project.mjs';
26
29
  import { conversation } from './studio-view.mjs';
27
- import { initializeAnalytics, trackEvent } from './analytics.mjs';
30
+ import { initializeAnalytics, trackEvent, analyticsConsent, saveAnalyticsConsent } from './analytics.mjs';
31
+ import { validateBranch, confirmChangeBranch, saveChangeBranch } from './branches.mjs';
28
32
 
29
33
  const require = createRequire(import.meta.url);
30
34
  const publicDir = fileURLToPath(new URL('../public/', import.meta.url));
@@ -49,6 +53,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
49
53
  let broadcast = () => {}, closed = false;
50
54
  const state = createWorkspaceState(root, { check: readinessCheck, changed: change => broadcast('readiness', { change }) });
51
55
  let origin;
56
+ const versionCheck = checkForUpdate(root);
52
57
  const send = (response, status, content, type = 'text/html; charset=utf-8', headers = {}) => {
53
58
  response.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin', ...headers }); response.end(content);
54
59
  };
@@ -127,6 +132,8 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
127
132
  const expose = ({ claimToken, instructions, workflow, workingDirectory, ...job }) => job;
128
133
  return send(response, 200, JSON.stringify({ ...result, items: result.items.map(expose), recent: result.recent?.map(expose) }), 'application/json');
129
134
  }
135
+ if (url.pathname === '/api/update-status') return send(response, 200, JSON.stringify(await versionCheck), 'application/json');
136
+ if (url.pathname === '/api/privacy') return send(response, 200, JSON.stringify(await analyticsConsent(root)), 'application/json');
130
137
  if (url.pathname === '/api/activity') {
131
138
  const [jobs, drafts] = await Promise.all([jobReader.read(), listDrafts(root)]);
132
139
  const change = url.searchParams.get('change');
@@ -135,12 +142,13 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
135
142
  const relevant = jobs.filter(job => !job.hiddenAt && (selected && jobMatchesChange(job, selected) || job.id === url.searchParams.get('creation')));
136
143
  const draftStates = await Promise.all(drafts.map(async draft => ({ id: draft.id, change: draft.change, creationId: draft.creationId, status: jobs.find(job => job.id === draft.creationId)?.status, hasPlan: Boolean(draft.creationId && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(draft.change) && await exists(path.join(root, 'openspec', 'changes', draft.change))) })));
137
144
  const inbox = requestPage(jobs, {}, { agent, dismissed: await inboxState(root) });
138
- return send(response, 200, JSON.stringify({ agent, attention: inbox.attention, inboxCount: inbox.total, revision: JSON.stringify(relevant.map(job => [job.id, job.status])), thread: conversation(relevant, agent), drafts: draftStates, active: jobs.filter(job => pendingStatuses.includes(job.status)).map(job => ({ id: job.id, change: job.change, status: job.status })) }), 'application/json');
145
+ return send(response, 200, JSON.stringify({ notifications: jobs.filter(job => !job.hiddenAt).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 100).map(({ id, action, change, status, updatedAt }) => ({ id, action, change, status, updatedAt })), agent, attention: inbox.attention, inboxCount: inbox.total, revision: JSON.stringify(relevant.map(job => [job.id, job.status])), thread: conversation(relevant, agent, icon), drafts: draftStates, active: jobs.filter(job => pendingStatuses.includes(job.status)).map(job => ({ id: job.id, change: job.change, status: job.status })) }), 'application/json');
139
146
  }
140
- const feedbackMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/feedback\/([a-zA-Z0-9_-]+)$/);
141
- if (feedbackMatch) {
142
- const exported = await feedbackExport(root, feedbackMatch[1], feedbackMatch[2]);
143
- return send(response, 200, exported.document, 'text/markdown; charset=utf-8', { 'Content-Disposition': 'attachment; filename="openspec-review-feedback.md"' });
147
+ const imageMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/(?:images|attachments)\/([a-f0-9-]{36}\.[a-z0-9]{1,12})$/);
148
+ if (imageMatch) {
149
+ await reviewScope(root, imageMatch[1]);
150
+ const image = await readReviewImage(root, imageMatch[1], imageMatch[2]);
151
+ return send(response, 200, image.bytes, image.type, image.type === 'application/octet-stream' ? { 'Content-Disposition': `attachment; filename="${image.id}"; filename*=UTF-8''${encodeURIComponent(image.name)}` } : {});
144
152
  }
145
153
  const patchMatch = url.pathname.match(/^\/api\/previews\/([a-zA-Z0-9_-]+)\/patch$/);
146
154
  if (patchMatch) {
@@ -152,13 +160,28 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
152
160
  const [data, jobs, drafts] = await Promise.all([state.data(), jobReader.read(), listDrafts(root)]);
153
161
  const agent = await agentStatus(root, { jobs });
154
162
  const content = await workspace({ root, data, params: Object.fromEntries(url.searchParams), jobs, drafts, agent, getReadiness: (_root, change) => state.readiness(change) });
155
- return send(response, 200, request.headers['hx-request'] ? content : shell(content, data, csrf, Object.fromEntries(url.searchParams)), 'text/html; charset=utf-8', {
163
+ return send(response, 200, request.headers['hx-request'] ? content : shell(content, data, csrf, Object.fromEntries(url.searchParams), await analyticsConsent(root)), 'text/html; charset=utf-8', {
156
164
  'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"
157
165
  });
158
166
  }
159
167
  if (request.method !== 'POST') return send(response, 405, 'Method not allowed');
160
- if (![origin, `http://localhost:${server.address().port}`].includes(request.headers.origin) || !tokenMatches(request.headers['x-csrf-token'], csrf)) return send(response, 403, '<p class="error-message">Local session verification failed. Reload the viewer and retry.</p>');
161
- const payload = await body(request, url.pathname.startsWith('/api/source-preview/') ? 2 * 1024 * 1024 : 100000);
168
+ if (![origin, `http://localhost:${server.address().port}`].includes(request.headers.origin) || !tokenMatches(request.headers['x-csrf-token'], csrf)) {
169
+ const error = 'Your workspace session expired. Reload the page and retry.';
170
+ return request.headers.accept?.includes('application/json') ? send(response, 403, JSON.stringify({ error }), 'application/json') : send(response, 403, `<p class="error-message">${error}</p>`);
171
+ }
172
+ const imageUpload = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/(?:images|attachments)$/);
173
+ const payload = await body(request, imageUpload ? 7 * 1024 * 1024 : url.pathname.startsWith('/api/source-preview/') ? 2 * 1024 * 1024 : 100000);
174
+ if (imageUpload) {
175
+ await reviewScope(root, imageUpload[1]);
176
+ return send(response, 201, JSON.stringify({ image: await saveReviewImage(root, imageUpload[1], payload) }), 'application/json');
177
+ }
178
+ if (url.pathname === '/api/plan-git/message') return send(response, 201, JSON.stringify(await requestCommitMessage(root, payload)), 'application/json');
179
+ if (url.pathname === '/api/plan-git') return send(response, 200, JSON.stringify(await publishPlan(root, payload)), 'application/json');
180
+ if (url.pathname === '/api/privacy') {
181
+ const consent = await saveAnalyticsConsent(root, payload.choice);
182
+ if (consent.choice !== 'off') await trackEvent(root, 'project_used');
183
+ return send(response, 200, JSON.stringify(consent), 'application/json');
184
+ }
162
185
  if (url.pathname === '/api/analytics') {
163
186
  if (payload.event === 'project_used') await trackEvent(root, 'project_used');
164
187
  else if (payload.event === 'file_diff_viewed' && /^[a-zA-Z0-9_-]{1,100}$/.test(payload.preview_id || '') && Number.isInteger(payload.changed_file_count) && payload.changed_file_count > 0 && ['unified', 'split'].includes(payload.layout)) {
@@ -167,6 +190,13 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
167
190
  return send(response, 204, '');
168
191
  }
169
192
  if (url.pathname === '/api/drafts') return send(response, 200, JSON.stringify({ draft: await saveDraft(root, payload) }), 'application/json');
193
+ if (url.pathname === '/api/change-branch') {
194
+ if ((await listJobs(root)).some(job => job.change === payload.change && pendingStatuses.includes(job.status))) throw new Error('Wait for this change’s active request to finish before changing its branch.');
195
+ const branch = await validateBranch(root, payload.branch);
196
+ const confirmed = await confirmChangeBranch(root, payload.change, branch, payload.confirmBranch);
197
+ await saveChangeBranch(root, payload.change, branch, confirmed);
198
+ return send(response, 200, JSON.stringify({ summary: branch ? `Branch saved. The agent will switch to ${branch} before starting its next request.` : 'Branch preference cleared. Requests will use the current branch.' }), 'application/json');
199
+ }
170
200
  const draftResume = url.pathname.match(/^\/api\/drafts\/([a-zA-Z0-9_-]+)\/resume$/);
171
201
  if (draftResume) return send(response, 200, JSON.stringify(await resumeDraft(root, draftResume[1])), 'application/json');
172
202
  const draftDelete = url.pathname.match(/^\/api\/drafts\/([a-zA-Z0-9_-]+)\/delete$/);
@@ -178,7 +208,8 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
178
208
  if (requestAction) {
179
209
  const result = requestAction[2] === 'dismiss' ? await dismissRequest(root, requestAction[1], payload) : requestAction[2] === 'delete' ? await deleteRequest(root, requestAction[1], payload) : { job: await retryRequest(root, requestAction[1]) };
180
210
  jobReader.invalidate(requestAction[1]);
181
- broadcast('requests');
211
+ await jobReader.read();
212
+ broadcast('requests'); broadcast('agent');
182
213
  return send(response, 200, JSON.stringify(result), 'application/json');
183
214
  }
184
215
  if (['/api/lifecycle/actions', '/api/lifecycle/command'].includes(url.pathname)) {
@@ -199,7 +230,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
199
230
  const query = new URLSearchParams({ change: job.change, view: 'preview', job: job.id });
200
231
  return send(response, 201, JSON.stringify({ job: { id: job.id, change: job.change, origin: job.origin, status: job.status }, url: `/?${query}` }), 'application/json', { 'HX-Trigger': 'workspace-updated' });
201
232
  }
202
- const reviewMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/(comments|export|update-specs|impact)$/);
233
+ const reviewMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/(comments|update-specs|impact)$/);
203
234
  if (reviewMatch) {
204
235
  const [, preview, action] = reviewMatch;
205
236
  if (action === 'comments') {
@@ -211,12 +242,10 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
211
242
  await enqueue(root, { action: 'impact', reviewPreview: preview, reviewFile: payload.file });
212
243
  return send(response, 201, '', undefined, { 'HX-Trigger': JSON.stringify({ 'spequi-toast': { message: 'Impact analysis queued for your attached agent.' }, 'workspace-updated': true }) });
213
244
  }
214
- const exported = await exportFeedback(root, preview);
215
- const update = action === 'update-specs' ? await enqueue(root, { action: 'update-specs', reviewPreview: preview, feedbackId: exported.id }) : null;
216
- const downloadUrl = `/api/reviews/${preview}/feedback/${exported.id}`;
217
- if (request.headers.accept?.includes('application/json')) return send(response, 201, JSON.stringify({ exported: { ...exported, downloadUrl }, ...(update ? { update: { id: update.id, change: update.change, status: update.status, reviewPreview: update.reviewPreview, feedbackId: update.feedbackId } } : {}) }), 'application/json');
218
- if (update) return send(response, 201, '', undefined, { 'HX-Trigger': JSON.stringify({ 'spequi-toast': { message: 'OpenSpec planning update queued using this feedback document.', downloadUrl }, 'workspace-updated': true }) });
219
- return send(response, 201, `<p class="success-message">${action === 'update-specs' ? 'OpenSpec planning update queued using this feedback document.' : 'Feedback document saved.'} <a href="${downloadUrl}" download="openspec-review-feedback.md">Download Markdown</a></p>`, undefined, { 'HX-Trigger': 'workspace-updated' });
245
+ const snapshot = await exportFeedback(root, preview);
246
+ const update = await enqueue(root, { action: 'update-specs', reviewPreview: preview, feedbackId: snapshot.id });
247
+ if (request.headers.accept?.includes('application/json')) return send(response, 201, JSON.stringify({ feedback: { id: snapshot.id, preview, count: snapshot.count }, update: { id: update.id, change: update.change, status: update.status, reviewPreview: update.reviewPreview, feedbackId: update.feedbackId } }), 'application/json');
248
+ return send(response, 201, '', undefined, { 'HX-Trigger': JSON.stringify({ 'spequi-toast': { message: 'Spec update queued for your attached agent.' }, 'workspace-updated': true }) });
220
249
  }
221
250
  const deleteMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/comments\/([a-zA-Z0-9_-]+)\/delete$/);
222
251
  if (deleteMatch) {
@@ -226,11 +255,15 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
226
255
  }
227
256
  if (url.pathname === '/api/jobs') {
228
257
  const job = await enqueue(root, payload);
258
+ if (request.headers.accept?.includes('application/json')) return send(response, 201, JSON.stringify({ job: { id: job.id, action: job.action, change: job.change, status: job.status } }), 'application/json');
229
259
  return send(response, 201, '', undefined, { 'HX-Trigger': JSON.stringify({ 'spequi-toast': { message: `${job.action === 'preview' ? 'Preview' : 'Workflow'} queued. Your agent will pick it up.` }, 'workspace-updated': true }) });
230
260
  }
231
261
  const cancelMatch = url.pathname.match(/^\/api\/jobs\/([a-zA-Z0-9_-]+)\/cancel$/);
232
262
  if (cancelMatch) {
233
263
  await updateJob(root, cancelMatch[1], null, 'cancel', 'Cancelled in viewer');
264
+ jobReader.invalidate(cancelMatch[1]);
265
+ await jobReader.read();
266
+ broadcast('requests'); broadcast('agent');
234
267
  return send(response, 200, request.headers.accept?.includes('application/json') ? JSON.stringify({ cancelled: true }) : '<p>Request cancelled.</p>', request.headers.accept?.includes('application/json') ? 'application/json' : undefined, { 'HX-Trigger': 'workspace-updated' });
235
268
  }
236
269
  const applyMatch = url.pathname.match(/^\/api\/previews\/([a-zA-Z0-9_-]+)\/apply$/);
@@ -266,7 +299,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
266
299
  });
267
300
  broadcast = (type, detail = {}) => { for (const client of wss.clients) if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify({ type, ...detail })); };
268
301
  let timer, requestTimer, changeScope, globalChange = false;
269
- const watcher = chokidar.watch([path.join(root, 'openspec'), runtime(root, 'jobs'), runtime(root, 'drafts'), runtime(root, 'agent.json'), runtime(root, 'agent-session.json'), runtime(root, 'previews'), runtime(root, 'reviews'), runtime(root, 'analyses'), runtime(root, 'validation'), runtime(root, 'studio')], { ignoreInitial: true, ignored: file => isPreviewSnapshotPath(file) || file.endsWith('.tmp') || file.endsWith('.lock') || file.endsWith('.recovery'), depth: 12, awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 50 } });
302
+ const watcher = chokidar.watch([path.join(root, 'openspec'), runtime(root, 'jobs'), runtime(root, 'drafts'), runtime(root, 'agent.json'), runtime(root, 'agent-session.json'), runtime(root, 'previews'), runtime(root, 'reviews'), runtime(root, 'analyses'), runtime(root, 'validation'), runtime(root, 'studio')], { usePolling: process.platform === 'win32', interval: 500, ignoreInitial: true, ignored: file => isPreviewSnapshotPath(file) || file.endsWith('.tmp') || file.endsWith('.lock') || file.endsWith('.recovery'), depth: 12, awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 50 } });
270
303
  watcher.on('all', (_event, watched) => {
271
304
  if ([runtime(root, 'agent.json'), runtime(root, 'agent-session.json')].includes(watched)) { broadcast('agent'); return; }
272
305
  if (watched.startsWith(runtime(root, 'jobs') + path.sep)) {
@@ -290,6 +323,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
290
323
  const interval = setInterval(() => broadcast('heartbeat'), 15000);
291
324
  interval.unref();
292
325
  if (!quiet) process.stdout.write(`\n spequi\n ${origin}\n Project: ${root}\n\n Attach the spequi skill in your agent to handle workflows.\n Press Ctrl+C to stop.\n\n`);
326
+ void versionCheck.then(info => { if (info.available && !quiet) process.stdout.write(` Spequi ${info.latest} is available (running ${info.current}). Run /spequi update in your agent when idle.\n`); });
293
327
  const close = async () => {
294
328
  if (closed) return;
295
329
  closed = true; state.close(); jobReader.close(); clearInterval(interval); clearTimeout(timer); clearTimeout(requestTimer);
@@ -7,8 +7,8 @@ export async function renderSourcePreviewTools(root, selected, hasPreview, pendi
7
7
  const [analysis, model] = await Promise.all([savedAnalysis(root, selected.id), modelInfo(root)]);
8
8
  const disabled = pending ? 'disabled' : '';
9
9
  const hidden = `<input type="hidden" name="change" value="${e(selected.id)}">`;
10
- const action = (kind, label) => `<button type="submit" class="button ${kind === 'analyze' ? 'primary' : ''}" ${disabled}>${icon(kind === 'analyze' ? 'search' : 'git')}${label}</button>`;
11
- const candidates = analysis ? `<p class="source-analysis-note">${analysis.candidates.length} likely affected ${analysis.candidates.length === 1 ? 'file' : 'files'} · ${analysis.coverage.scanned} scanned. ${analysis.stale ? '<strong>Inputs changed. Analyze again before generating.</strong>' : 'These suggestions contain no proposed edits.'}</p><div class="source-candidates">${analysis.candidates.map((candidate, index) => `<div class="source-candidate"><label class="source-context-choice"><input type="checkbox" name="files" value="${e(candidate.file)}" form="model-preview-form" ${analysis.stale || !model.configured || pending ? 'disabled' : ''}><span>Select ${e(candidate.file)} as model context</span></label><details id="source-candidate-${index}"><summary><code>${e(candidate.file)}</code><span class="badge">${e(candidate.strength)}</span></summary><ul>${candidate.evidence.map(item => `<li><strong>${e(item.kind)}</strong> ${e(item.text)}${item.artifact ? `<small>${e(item.artifact)}:${item.line}</small>` : ''}</li>`).join('')}</ul><pre aria-label="Source context for ${e(candidate.file)}">${candidate.excerpt.map(item => `${item.line} ${e(item.text)}`).join('\n')}</pre></details></div>`).join('') || '<p>No source matches found. Try naming files or symbols in the change, or use an explicit patch.</p>'}</div><details class="source-coverage" id="source-analysis-coverage"><summary>Analysis coverage</summary><p>${e(analysis.coverage.scope)}</p><p>${analysis.coverage.skipped.length} skipped files · ${analysis.coverage.unresolved.length} unresolved references · ${analysis.coverage.omitted} additional candidates omitted.</p>${analysis.coverage.skipped.length ? `<ul>${analysis.coverage.skipped.slice(0, 20).map(item => `<li><code>${e(item.file)}</code> — ${e(item.reason)}</li>`).join('')}</ul>` : ''}${analysis.coverage.unresolved.length ? `<ul>${analysis.coverage.unresolved.slice(0, 20).map(item => `<li><code>${e(item.reference)}</code> in ${e(item.file)}</li>`).join('')}</ul>` : ''}</details>` : '<p>Find source paths, named symbols, and related dependencies using this change’s planning documents. Analysis runs locally without an agent or model.</p>';
12
- const modelForm = model.configured ? `<form id="model-preview-form" data-source-action="model" action="/api/source-preview/model" method="post">${hidden}<input type="hidden" name="analysisId" value="${e(analysis?.id || '')}"><p>Generate with <strong>${e(model.model)}</strong> at <code>${e(model.destination)}</code>. This sends the planning documents and only the source files you select (up to 12). Review and test the returned edits before applying.</p><button type="submit" class="button" ${pending || !analysis || analysis.stale || !analysis.candidates.length ? 'disabled' : ''}>${icon('spark')}Generate with model</button></form>` : `<p class="source-model-help">${model.error ? e(model.error) : 'Model generation is optional. Configure previewModel in .spequi/config.json to use a local or hosted endpoint. Offline analysis and patch import work without it.'}</p>`;
13
- return `<details class="source-preview-tools" id="source-preview-tools" ${hasPreview ? '' : 'open'}><summary>${icon('code')}<strong>Plan file changes</strong><span>Analyze offline, generate, or import a patch</span>${icon('chevron')}</summary><div class="source-preview-body" data-analysis-id="${e(analysis?.id || '')}"><form data-source-action="analyze" action="/api/source-preview/analyze" method="post">${hidden}${action('analyze', analysis ? 'Refresh affected files' : 'Analyze affected files')}</form>${candidates}${modelForm}<details id="source-patch-import"><summary>Import patch</summary><form data-source-action="patch" action="/api/source-preview/patch" method="post">${hidden}<label for="source-preview-patch">Unified patch</label><p>Stage an existing patch in a temporary copy. Your project changes only when you apply the reviewed preview.</p><textarea id="source-preview-patch" name="patch" rows="6" required maxlength="1048576" spellcheck="false" placeholder="--- a/path/to/file&#10;+++ b/path/to/file&#10;@@ …"></textarea>${action('patch', 'Preview patch')}</form></details><div id="source-preview-feedback" role="status" aria-live="polite"></div></div></details>`;
10
+ const action = (kind, label) => `<button type="submit" class="button" ${disabled}>${icon(kind === 'analyze' ? 'search' : 'git')}${label}</button>`;
11
+ const candidates = analysis ? `<p class="source-analysis-note">${analysis.candidates.length} likely affected ${analysis.candidates.length === 1 ? 'file' : 'files'} · ${analysis.coverage.scanned} scanned. ${analysis.stale ? '<strong>Inputs changed. Analyze again before generating.</strong>' : 'These suggestions contain no proposed edits.'}</p><div class="source-candidates">${analysis.candidates.map((candidate, index) => `<div class="source-candidate">${model.configured ? `<label class="source-context-choice"><input type="checkbox" name="files" value="${e(candidate.file)}" form="model-preview-form" ${analysis.stale || !model.configured || pending ? 'disabled' : ''}><span>Select ${e(candidate.file)} as model context</span></label>` : ''}<details id="source-candidate-${index}"><summary><code>${e(candidate.file)}</code><span class="badge">${e(candidate.strength)}</span></summary><ul>${candidate.evidence.map(item => `<li><strong>${e(item.kind)}</strong> ${e(item.text)}${item.artifact ? `<small>${e(item.artifact)}:${item.line}</small>` : ''}</li>`).join('')}</ul><pre aria-label="Source context for ${e(candidate.file)}">${candidate.excerpt.map(item => `${item.line} ${e(item.text)}`).join('\n')}</pre></details></div>`).join('') || '<p>No matching files yet. Add filenames or symbols to the plan, then scan again.</p>'}</div><details class="source-coverage" id="source-analysis-coverage"><summary>Analysis coverage</summary><p>${e(analysis.coverage.scope)}</p><p>${analysis.coverage.skipped.length} skipped files · ${analysis.coverage.unresolved.length} unresolved references · ${analysis.coverage.omitted} additional candidates omitted.</p>${analysis.coverage.skipped.length ? `<ul>${analysis.coverage.skipped.slice(0, 20).map(item => `<li><code>${e(item.file)}</code> — ${e(item.reason)}</li>`).join('')}</ul>` : ''}${analysis.coverage.unresolved.length ? `<ul>${analysis.coverage.unresolved.slice(0, 20).map(item => `<li><code>${e(item.reference)}</code> in ${e(item.file)}</li>`).join('')}</ul>` : ''}</details>` : '';
12
+ const modelForm = model.configured ? `<form id="model-preview-form" data-source-action="model" action="/api/source-preview/model" method="post">${hidden}<input type="hidden" name="analysisId" value="${e(analysis?.id || '')}"><p>Generate with <strong>${e(model.model)}</strong> at <code>${e(model.destination)}</code>. This sends the planning documents and only the source files you select (up to 12). Review the proposed edits before applying.</p><button type="submit" class="button" ${pending || !analysis || analysis.stale || !analysis.candidates.length ? 'disabled' : ''}>${icon('spark')}Generate with model</button></form>` : '';
13
+ return `<details class="source-preview-tools" id="source-preview-tools"><summary>${icon('search')}<strong>Affected files</strong><span class="source-analysis-state">${analysis ? `${analysis.candidates.length} matches${analysis.stale ? ' · Outdated' : ''}` : 'Not scanned'}</span>${icon('chevron')}</summary><div class="source-preview-body" data-analysis-id="${e(analysis?.id || '')}"><div class="source-analysis-toolbar"><p>Find files referenced by this plan. Nothing is changed.</p><form data-source-action="analyze" action="/api/source-preview/analyze" method="post">${hidden}${action('analyze', analysis ? 'Scan again' : 'Scan files')}</form></div>${candidates}${modelForm}<div id="source-preview-feedback" role="status" aria-live="polite"></div></div></details>`;
14
14
  }
@@ -27,11 +27,11 @@ export function specContextRows(context, rows, scope, mode, icon) {
27
27
  if (emitted.has(reference.key)) return `<a class="spec-context-repeat" href="#${id}">${icon('file')}Same requirement: ${e(reference.title)}</a>`;
28
28
  emitted.add(reference.key);
29
29
  const text = reference.quote.replace(/^#{1,6}\s+[^\n]+\n+/, '');
30
- return `<details class="spec-context-quote" id="${id}" open><summary><span>${e(reference.title)}</span>${icon('chevron')}</summary><blockquote>${markdown(text)}</blockquote><p class="spec-context-source">${icon('file')}<span>${e(reference.spec)}<br>Lines ${reference.specStart}–${reference.specEnd} · Preview snapshot${reference.reason ? ` · ${e(reference.reason)}` : ''}</span></p></details>`;
30
+ return `<details class="spec-context-quote" id="${id}"><summary>${icon('book')}<span class="spec-context-label">Spec context</span><strong>${e(reference.title)}</strong><span class="spec-context-provenance ${suggested ? 'suggested' : ''}">${suggested ? 'Suggested' : 'Recorded'}</span>${icon('chevron')}</summary>${suggested ? '<p class="spec-context-caveat">Suggested from the saved plan; confirm relevance to this edit.</p>' : ''}<blockquote>${markdown(text)}</blockquote><p class="spec-context-source">${icon('file')}<span>${e(reference.spec)}<br>Lines ${reference.specStart}–${reference.specEnd} · Preview snapshot${reference.reason ? ` · ${e(reference.reason)}` : ''}</span></p></details>`;
31
31
  }).join('');
32
- return `<tr class="spec-context-row"><td colspan="${mode === 'split' ? 6 : 4}"><section class="spec-context-inline" aria-label="${suggested ? 'Suggested spec context for this file' : 'Spec context for this change block'}"><div class="spec-context-heading">${icon('file')}<strong>Spec context</strong><span class="spec-context-provenance ${suggested ? 'suggested' : ''}">${suggested ? 'Suggested · file-level' : 'Agent linked'}</span></div>${suggested ? '<p class="spec-context-caveat">Matched from the saved spec. Confirm relevance; this is not a recorded explanation for this block.</p>' : ''}${entries}</section></td></tr>`;
32
+ return `<tr class="spec-context-row"><td colspan="${mode === 'split' ? 6 : 4}"><section class="spec-context-inline" aria-label="${suggested ? 'Suggested spec context for this file' : 'Spec context for this change block'}">${entries}</section></td></tr>`;
33
33
  };
34
34
  const empty = !context.links.length && !context.suggestions.length;
35
35
  const notice = context.notice || (empty ? 'No spec links recorded for this file.' : '');
36
- return { render, leadingRows: first ? '' : render(rows[0]), notice: notice ? `<p class="spec-context-notice">${e(notice)}</p>` : '' };
36
+ return { render, leadingRows: first ? '' : render(rows[0]), overview: '', notice: '' };
37
37
  }
@@ -69,7 +69,7 @@ export async function captureSpecLinks(root, id, changes) {
69
69
  if (!stat) return empty;
70
70
  if (!stat.isFile() || stat.size > 65536) return { ...empty, invalidReport: true };
71
71
  const report = JSON.parse(await fs.readFile(reportFile, 'utf8'));
72
- if (report?.version !== 1 || !Array.isArray(report.links) || report.links.length > 100) return { ...empty, invalidReport: true };
72
+ if (report?.version !== 1 || !Array.isArray(report.links) || report.links.length > 800) return { ...empty, invalidReport: true };
73
73
  const saved = await snapshot(root, id), fileRows = new Map(), seen = new Set();
74
74
  for (const reference of report.links) {
75
75
  const file = changes.find(item => item.file === reference?.file);
@@ -109,28 +109,28 @@ async function suggestions(saved, file, rows) {
109
109
  for (let index = 0; index < sections.length; index++) {
110
110
  const section = sections[index];
111
111
  // A requirement owns its scenarios; avoid repeating the same quote for its child headings.
112
- if (section.depth > 3) continue;
113
- const nextSection = sections.slice(index + 1).find(next => next.depth <= 3);
112
+ if (section.depth > 4) continue;
113
+ const nextSection = sections.slice(index + 1).find(next => next.depth <= section.depth);
114
114
  const end = Math.min(nextSection ? nextSection.start - 1 : source.lines.length, section.start + 79);
115
115
  const text = source.lines.slice(section.start - 1, end).join('\n');
116
116
  const symbols = [...text.matchAll(/`([A-Za-z_$][\w$]{3,})`/g)].map(match => match[1]).filter(value => identifiers.has(value) && !['true', 'false', 'null', 'const', 'return', 'function', 'string', 'number', 'boolean'].includes(value));
117
117
  const paths = [...text.matchAll(/(?:`|\b)([A-Za-z0-9_./-]+\.[A-Za-z0-9]+)(?:`|\b)/g)].map(match => match[1]);
118
118
  const explicit = paths.includes(file.file), filename = uniqueName && paths.includes(basename);
119
- if (!explicit && !filename && !symbols.length) continue;
120
- const reference = quote(source, { spec: name, specStart: section.start, specEnd: end, specHash: source.hash, reason: explicit ? 'File path mentioned' : filename ? 'Unique filename mentioned' : `Changed symbol: ${symbols[0]}` }, 'suggested');
121
- if (reference) candidates.push({ ...reference, score: explicit ? 3 : filename ? 2 : 1 });
119
+ const symbolMatches = [...new Set(symbols)];
120
+ if (!explicit && !filename && !symbolMatches.length) continue;
121
+ const reference = quote(source, { spec: name, specStart: section.start, specEnd: end, specHash: source.hash, reason: explicit ? 'File path mentioned' : filename ? 'Unique filename mentioned' : `Changed symbol: ${symbolMatches.slice(0, 3).join(', ')}` }, 'suggested');
122
+ if (reference) candidates.push({ ...reference, score: (explicit ? 12 : filename ? 8 : 0) + Math.min(symbolMatches.length, 4) + (/\/specs\//.test(name) ? 2 : 0) });
122
123
  }
123
124
  }
124
125
  return candidates.sort((a, b) => b.score - a.score || a.spec.localeCompare(b.spec) || a.specStart - b.specStart).slice(0, 2);
125
126
  }
126
127
 
127
- export async function specContextForFile(root, job, file, result, before, after) {
128
+ export async function specContextForFile(root, job, file, result, before, after, rows = buildDiffRows(before, after).split) {
128
129
  const context = { links: [], suggestions: [], notice: '' };
129
130
  try {
130
131
  const saved = await snapshot(root, job.id);
131
132
  const verified = (hash, text) => hash ? hash === digest(text) : text === '';
132
133
  if (!verified(file.beforeHash, before) || !verified(file.afterHash, after)) return { ...context, notice: 'The saved code changed; spec context cannot be verified.' };
133
- const rows = buildDiffRows(before, after).split;
134
134
  const records = result.specContext?.version === 1 ? result.specContext.links || [] : [];
135
135
  for (const reference of records.filter(item => item.file === file.file).slice(0, 8)) {
136
136
  const source = await saved.source(reference.spec);
@@ -141,6 +141,9 @@ export async function specContextForFile(root, job, file, result, before, after)
141
141
  else context.notice = 'Some spec links could not be verified against this preview.';
142
142
  }
143
143
  if (result.specContext?.invalidReport || result.specContext?.invalidFiles?.includes(file.file)) context.notice = 'Some recorded spec links were invalid and are not shown.';
144
+ const changedLines = rows.flatMap(row => [row.before?.type === 'deletion' ? { side: 'current', number: row.before.number } : null, row.after?.type === 'addition' ? { side: 'proposed', number: row.after.number } : null].filter(Boolean));
145
+ const linked = changedLines.filter(line => context.links.some(reference => reference.side === line.side && line.number >= reference.start && line.number <= reference.end)).length;
146
+ context.coverage = { linked, total: changedLines.length, requirements: new Set(context.links.map(specLinkKey)).size };
144
147
  if (!context.links.length) context.suggestions = await suggestions(saved, file, rows);
145
148
  return context;
146
149
  } catch { return { ...context, notice: 'The retained spec snapshot is unavailable for this preview.' }; }