spequi 0.1.8 → 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.
@@ -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,10 @@ 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';
28
31
  import { validateBranch, confirmChangeBranch, saveChangeBranch } from './branches.mjs';
29
32
 
30
33
  const require = createRequire(import.meta.url);
@@ -50,6 +53,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
50
53
  let broadcast = () => {}, closed = false;
51
54
  const state = createWorkspaceState(root, { check: readinessCheck, changed: change => broadcast('readiness', { change }) });
52
55
  let origin;
56
+ const versionCheck = checkForUpdate(root);
53
57
  const send = (response, status, content, type = 'text/html; charset=utf-8', headers = {}) => {
54
58
  response.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin', ...headers }); response.end(content);
55
59
  };
@@ -128,6 +132,8 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
128
132
  const expose = ({ claimToken, instructions, workflow, workingDirectory, ...job }) => job;
129
133
  return send(response, 200, JSON.stringify({ ...result, items: result.items.map(expose), recent: result.recent?.map(expose) }), 'application/json');
130
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');
131
137
  if (url.pathname === '/api/activity') {
132
138
  const [jobs, drafts] = await Promise.all([jobReader.read(), listDrafts(root)]);
133
139
  const change = url.searchParams.get('change');
@@ -136,12 +142,13 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
136
142
  const relevant = jobs.filter(job => !job.hiddenAt && (selected && jobMatchesChange(job, selected) || job.id === url.searchParams.get('creation')));
137
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))) })));
138
144
  const inbox = requestPage(jobs, {}, { agent, dismissed: await inboxState(root) });
139
- 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), 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');
140
146
  }
141
- const feedbackMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/feedback\/([a-zA-Z0-9_-]+)$/);
142
- if (feedbackMatch) {
143
- const exported = await feedbackExport(root, feedbackMatch[1], feedbackMatch[2]);
144
- 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)}` } : {});
145
152
  }
146
153
  const patchMatch = url.pathname.match(/^\/api\/previews\/([a-zA-Z0-9_-]+)\/patch$/);
147
154
  if (patchMatch) {
@@ -153,13 +160,28 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
153
160
  const [data, jobs, drafts] = await Promise.all([state.data(), jobReader.read(), listDrafts(root)]);
154
161
  const agent = await agentStatus(root, { jobs });
155
162
  const content = await workspace({ root, data, params: Object.fromEntries(url.searchParams), jobs, drafts, agent, getReadiness: (_root, change) => state.readiness(change) });
156
- 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', {
157
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'"
158
165
  });
159
166
  }
160
167
  if (request.method !== 'POST') return send(response, 405, 'Method not allowed');
161
- 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>');
162
- 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
+ }
163
185
  if (url.pathname === '/api/analytics') {
164
186
  if (payload.event === 'project_used') await trackEvent(root, 'project_used');
165
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)) {
@@ -186,7 +208,8 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
186
208
  if (requestAction) {
187
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]) };
188
210
  jobReader.invalidate(requestAction[1]);
189
- broadcast('requests');
211
+ await jobReader.read();
212
+ broadcast('requests'); broadcast('agent');
190
213
  return send(response, 200, JSON.stringify(result), 'application/json');
191
214
  }
192
215
  if (['/api/lifecycle/actions', '/api/lifecycle/command'].includes(url.pathname)) {
@@ -207,7 +230,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
207
230
  const query = new URLSearchParams({ change: job.change, view: 'preview', job: job.id });
208
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' });
209
232
  }
210
- 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)$/);
211
234
  if (reviewMatch) {
212
235
  const [, preview, action] = reviewMatch;
213
236
  if (action === 'comments') {
@@ -219,12 +242,10 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
219
242
  await enqueue(root, { action: 'impact', reviewPreview: preview, reviewFile: payload.file });
220
243
  return send(response, 201, '', undefined, { 'HX-Trigger': JSON.stringify({ 'spequi-toast': { message: 'Impact analysis queued for your attached agent.' }, 'workspace-updated': true }) });
221
244
  }
222
- const exported = await exportFeedback(root, preview);
223
- const update = action === 'update-specs' ? await enqueue(root, { action: 'update-specs', reviewPreview: preview, feedbackId: exported.id }) : null;
224
- const downloadUrl = `/api/reviews/${preview}/feedback/${exported.id}`;
225
- 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');
226
- 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 }) });
227
- 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 }) });
228
249
  }
229
250
  const deleteMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/comments\/([a-zA-Z0-9_-]+)\/delete$/);
230
251
  if (deleteMatch) {
@@ -240,6 +261,9 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
240
261
  const cancelMatch = url.pathname.match(/^\/api\/jobs\/([a-zA-Z0-9_-]+)\/cancel$/);
241
262
  if (cancelMatch) {
242
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');
243
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' });
244
268
  }
245
269
  const applyMatch = url.pathname.match(/^\/api\/previews\/([a-zA-Z0-9_-]+)\/apply$/);
@@ -275,7 +299,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
275
299
  });
276
300
  broadcast = (type, detail = {}) => { for (const client of wss.clients) if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify({ type, ...detail })); };
277
301
  let timer, requestTimer, changeScope, globalChange = false;
278
- 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 } });
279
303
  watcher.on('all', (_event, watched) => {
280
304
  if ([runtime(root, 'agent.json'), runtime(root, 'agent-session.json')].includes(watched)) { broadcast('agent'); return; }
281
305
  if (watched.startsWith(runtime(root, 'jobs') + path.sep)) {
@@ -299,6 +323,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
299
323
  const interval = setInterval(() => broadcast('heartbeat'), 15000);
300
324
  interval.unref();
301
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`); });
302
327
  const close = async () => {
303
328
  if (closed) return;
304
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 ${''}" ${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,.</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>';
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
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>Explore affected files</strong><span>Optional · local analysis</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}<div id="source-preview-feedback" role="status" aria-live="polite"></div></div></details>`;
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,13 +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
- const coverage = context.coverage;
37
- const overview = coverage?.total ? `<div class="spec-context-overview"><span>${icon('book')}<strong>${coverage.requirements ? `${coverage.requirements} linked ${coverage.requirements === 1 ? 'spec section' : 'spec sections'}` : context.suggestions.length ? 'Suggested spec context' : 'Spec references'}</strong><span>${coverage.linked} of ${coverage.total} changed lines linked</span></span>${context.links.length || context.suggestions.length ? '<button type="button" class="text-button" data-spec-context-toggle aria-expanded="true">Collapse quotes</button>' : ''}</div>` : '';
38
- return { render, leadingRows: first ? '' : render(rows[0]), overview, notice: notice ? `<p class="spec-context-notice">${e(notice)}</p>` : '' };
36
+ return { render, leadingRows: first ? '' : render(rows[0]), overview: '', notice: '' };
39
37
  }
@@ -1,13 +1,17 @@
1
+ import { renderPlanGit } from './plan-git.mjs';
1
2
  import { escape as e, markdown } from './specs.mjs';
2
3
  import { lifecycleState } from './lifecycle.mjs';
3
4
  import { planVersions, planChanges } from './studio-plans.mjs';
4
5
  import { renderPlanMarkdown } from './studio-documents.mjs';
5
- import { renderCommandPicker } from './commands.mjs';
6
+ import { renderReviewMarkdown, renderDocumentDiscussion } from './document-view.mjs';
7
+ import { documentHash, artifactReviewID, listComments, isCommentableArtifact } from './review-store.mjs';
8
+ import { renderReviewContext } from './review-view.mjs';
9
+ import { hasVerificationReport } from './verification.mjs';
6
10
  import { renderCreation } from './creation-view.mjs';
7
11
  import { changeBranch } from './branches.mjs';
8
12
 
9
13
  const stages = [['shape', 'Plan'], ['finish', 'Workflow']];
10
- const labels = { explore: 'Question', 'revise-plan': 'Spec revision', 'update-specs': 'Review feedback', 'plan-next': 'Next artifact', propose: 'Full plan', preview: 'Implementation preview', verify: 'Implementation verification', archive: 'Archive', 'sync-specs': 'Sync specifications', 'create-change': 'New change', 'start-plan': 'New spec', impact: 'File impact' };
14
+ const labels = { 'commit-message': 'Commit message', explore: 'Question', 'revise-plan': 'Spec revision', 'update-specs': 'Review feedback', 'plan-next': 'Next artifact', propose: 'Full plan', preview: 'Implementation preview', verify: 'Implementation verification', archive: 'Archive', 'sync-specs': 'Sync specifications', 'create-change': 'New change', 'start-plan': 'New spec', impact: 'File impact' };
11
15
  const statusLabel = value => ({ queued: 'Waiting for agent', running: 'Working', 'awaiting-input': 'Your answer is needed', completed: 'Completed', failed: 'Failed', cancelled: 'Cancelled' }[value] || value);
12
16
  const feedback = '<div data-lifecycle-feedback role="status" aria-live="polite"></div>';
13
17
  const fields = (action, change) => `<input type="hidden" name="action" value="${e(action)}"><input type="hidden" name="change" value="${e(change)}">`;
@@ -26,13 +30,13 @@ function question(job, item) {
26
30
 
27
31
  export function jobQuestions(job) { return (job.questions || []).map(item => question(job, item)).join(''); }
28
32
 
29
- export function conversation(jobs, agent = {}) {
33
+ export function conversation(jobs, agent = {}, icon = () => '') {
30
34
  const visible = jobs.filter(job => !job.hiddenAt);
31
35
  const active = visible.find(job => ['running', 'awaiting-input'].includes(job.status)) || visible.find(job => job.status === 'queued');
32
36
  jobs = visible.slice(0, 20);
33
37
  if (active && !jobs.includes(active)) jobs = [...jobs.slice(0, 19), active];
34
38
  const historyLink = visible.length > jobs.length ? '<p class="studio-conversation-empty">Showing recent requests. <button type="button" class="button" data-requests-toggle>View all requests</button></p>' : '';
35
- if (!jobs.length) return '<p class="studio-conversation-empty">Describe what you want to change in the spec, or ask a question about the plan.</p>';
39
+ if (!jobs.length) return `<div class="studio-thread-placeholder">${icon('comment')}<strong>No conversation yet</strong><p>Questions, replies and updates for this change will appear here.</p></div>`;
36
40
  return historyLink + [...jobs].reverse().map((job, index) => {
37
41
  const pending = ['queued', 'running', 'awaiting-input'].includes(job.status);
38
42
  const active = ['queued', 'running'].includes(job.status);
@@ -40,14 +44,14 @@ export function conversation(jobs, agent = {}) {
40
44
  const title = job.status === 'queued' ? agent.queue?.status === 'blocked' ? 'Queue needs attention' : agent.queue?.active ? 'Waiting for the current request' : 'Waiting for your agent' : ownerConnected ? job.preparing ? 'Preparing the isolated workspace' : 'Agent is working' : 'Your request is in progress';
41
45
  const latest = !ownerConnected && job.status === 'running' ? 'This can take a few minutes. The result will appear here when ready. Your CLI may be waiting for a permission or another action.' : job.logs.at(-1)?.message || 'Progress will appear here as the agent works.';
42
46
  const progress = active ? `<div class="studio-progress" role="status"><span class="studio-progress-indicator" ${ownerConnected && job.status === 'running' ? 'data-working' : ''} aria-hidden="true"></span><div><strong>${e(title)}</strong><p>${e(latest)}</p><p class="studio-cli-hint">${ownerConnected && job.status === 'running' ? 'If progress pauses, check your CLI for permissions or other actions waiting for you.' : ''}</p><time datetime="${e(job.updatedAt)}">Updated ${e(new Date(job.updatedAt).toLocaleTimeString())}</time></div></div>` : '';
43
- const body = `${job.message ? `<div class="studio-message studio-user"><strong>You</strong><p>${e(job.message)}</p></div>` : ''}<div class="studio-message studio-agent"><div class="studio-message-heading"><strong>${e(labels[job.action] || job.action)}</strong><span class="${job.status === 'failed' ? 'studio-error' : ''}">${e(statusLabel(job.status))}</span></div>${jobQuestions(job)}${progress}${job.result ? `<div class="studio-result ${job.status === 'failed' ? 'studio-error' : ''}">${markdown(job.result)}</div>` : ''}<details id="studio-log-${job.id}"><summary>Activity · ${e(new Date(job.updatedAt).toLocaleString())}</summary><ol>${job.logs.slice(-30).map(log => `<li>${e(log.message)}</li>`).join('')}</ol></details>${pending && !(job.status === 'running' && job.origin) ? `<form data-lifecycle-form id="studio-cancel-${job.id}" action="/api/jobs/${job.id}/cancel" method="post" ${job.status === 'running' ? `data-studio-stalled-action data-request-owner="${e(job.id)}" ${ownerConnected || job.origin ? 'hidden' : ''}` : ''}><button type="submit" class="button">${job.status === 'running' ? 'End request' : 'Cancel request'}</button>${job.status === 'running' ? '<p class="studio-blocker">Stop the old agent in your coding tool first. Ending this request does not stop that process or undo its edits.</p>' : ''}${feedback}</form>` : ''}</div>`;
47
+ const body = `${job.message || job.attachments?.length ? `<div class="studio-message studio-user"><strong>You</strong><p>${e(job.message)}</p>${(job.attachments || []).map(file => `<a class="comment-image" href="${e(file.url)}" target="_blank" rel="noopener noreferrer">${/^image\/(png|jpeg|webp)$/.test(file.type) ? `<img src="${e(file.url)}" alt="${e(file.name)}">` : ''}<span>${e(file.name)}</span></a>`).join('')}</div>` : ''}<div class="studio-message studio-agent"><div class="studio-message-heading"><strong>${e(labels[job.action] || job.action)}</strong><span class="${job.status === 'failed' ? 'studio-error' : ''}">${e(statusLabel(job.status))}</span></div>${jobQuestions(job)}${progress}${job.result ? `<div class="studio-result ${job.status === 'failed' ? 'studio-error' : ''}">${markdown(job.result)}</div>` : ''}${pending && !(job.status === 'running' && job.origin) ? `<form data-lifecycle-form id="studio-cancel-${job.id}" action="/api/jobs/${job.id}/cancel" method="post" ${job.status === 'running' ? `data-studio-stalled-action data-request-owner="${e(job.id)}" ${ownerConnected || job.origin ? 'hidden' : ''}` : ''}><button type="submit" class="button">${job.status === 'running' ? 'End request' : 'Cancel request'}</button>${job.status === 'running' ? '<p class="studio-blocker">Stop the old agent in your coding tool first. Ending this request does not stop that process or undo its edits.</p>' : ''}${feedback}</form>` : ''}</div>`;
44
48
  return `<section class="studio-exchange" id="studio-job-${job.id}">${!pending && index < jobs.length - 1 ? `<details class="studio-history" id="studio-history-${job.id}"><summary><strong>${e(labels[job.action] || job.action)}</strong><span>${e(statusLabel(job.status))} · ${e(new Date(job.updatedAt).toLocaleTimeString())}</span></summary>${body}</details>` : body}</section>`;
45
49
  }).join('');
46
50
  }
47
51
 
48
52
  export async function renderStudio({ root, selected, jobs, agent, params = {}, changes = [], draft, getReadiness }, helpers) {
49
53
  const { icon, link, badge } = helpers;
50
- if (!selected) return renderCreation({jobs,params,agent,changes,draft},{...helpers,conversation: items => conversation(items, agent)});
54
+ if (!selected) return renderCreation({jobs,params,agent,changes,draft},{...helpers,conversation: items => conversation(items, agent, helpers.icon)});
51
55
  const state = await lifecycleState(root, selected.id, { jobs, selected, getReadiness });
52
56
  const stage = stages.some(([id]) => id === params.stage) ? params.stage : 'shape';
53
57
  const base = { change: selected.id, view: 'studio', stage, q: params.q, created: params.created, pane: params.pane === 'conversation' ? 'conversation' : 'document' };
@@ -56,14 +60,14 @@ export async function renderStudio({ root, selected, jobs, agent, params = {}, c
56
60
  const option = state.actions[name];
57
61
  return `<div class="studio-action"><form data-lifecycle-form id="studio-action-${e(id)}" action="/api/lifecycle/actions" method="post">${fields(name, selected.id)}<button type="submit" class="button ${primary ? 'primary' : ''}" ${option?.enabled ? '' : 'disabled'}>${e(label || option?.label || name)}</button>${feedback}</form>${option?.reason ? `<p class="studio-blocker">${e(option.reason)}</p>` : ''}</div>`;
58
62
  };
59
- let canvas = '', toolbar = '', footer = '', selectedPlan = '', followComplete = false;
63
+ let canvas = '', toolbar = '', footer = '', selectedPlan = '', followComplete = false, planningReview = '';
60
64
  if (stage === 'shape') {
61
65
  const versions = await planVersions(root, selected, jobs);
62
66
  const current = versions.current?.documents || {}, previous = versions.previous?.documents || {};
63
67
  const documents = [...new Set([...Object.keys(current), ...Object.keys(previous)])];
64
- const following = state.jobs.find(job => job.id === params.follow && job.action === 'plan-next' && job.status === 'completed');
68
+ const following = state.jobs.find(job => job.id === params.follow && ['plan-next', 'propose'].includes(job.action) && job.status === 'completed');
65
69
  const followedFile = following && versions.current?.hash === following.planAfter?.hash ? documents.find(name => !(name in previous)) || documents.find(name => current[name] !== previous[name]) : '';
66
- followComplete = Boolean(following);
70
+ followComplete = Boolean(following && state.readiness);
67
71
  const file = followedFile || (documents.includes(params.plan) ? params.plan : params.created === '1' ? documents.find(name => name === 'proposal.md') || documents[0] : documents.find(name => name.startsWith('specs/')) || documents[0]);
68
72
  selectedPlan = file || '';
69
73
  const changes = versions.previous ? planChanges(previous, current) : [];
@@ -80,31 +84,51 @@ export async function renderStudio({ root, selected, jobs, agent, params = {}, c
80
84
  toolbar = filePicker ? `<div class="studio-artifact-navigation">${filePicker}</div>` : '';
81
85
  const summary = changes.length ? `<details class="studio-change-summary" id="studio-change-summary"><summary>${changes.length} ${changes.length === 1 ? 'document changed' : 'documents changed'} in this revision</summary><ul>${changes.map(item => `<li>${stageLink(e(item.file), { stage: 'shape', plan: item.file, compare: params.compare })}<span>${e(item.type)} · +${item.additions} −${item.deletions}</span></li>`).join('')}</ul><p>Highlights mark changed sections.</p><button type="button" class="text-button" data-studio-change-jump>Show first changed section</button></details>` : '';
82
86
  const notice = versions.pending ? '<p class="studio-notice">The agent is updating the plan. The last retained version remains visible until the request finishes.</p>' : versions.failed ? '<p class="studio-notice studio-error">The last planning request failed. Current files may include unfinished edits; review them before continuing.</p>' : '';
83
- const document = file in current ? `<article class="prose studio-document">${renderPlanMarkdown(current[file], versions.previous ? previous[file] || '' : undefined)}</article>` : '<p class="studio-empty">This document was removed from the current revision.</p>';
87
+ const artifactPath = selected.files.find(name => name.endsWith('/' + file));
88
+ const artifact = file in current && isCommentableArtifact(selected, artifactPath) ? { file: artifactPath, kind: 'artifact', sourceHash: documentHash(current[file]) } : null;
89
+ const allNotes = artifact ? await listComments(root, artifactReviewID(selected.id)) : [];
90
+ const notes = allNotes.filter(note => note.file === artifactPath);
91
+ const document = file in current ? artifact ? `<div data-document-content data-source-hash="${artifact.sourceHash}"><article class="prose studio-document document-prose">${renderReviewMarkdown(current[file], { sourceHash: artifact.sourceHash, comments: notes, icon, previous: versions.previous ? previous[file] || '' : undefined })}</article></div>${renderDocumentDiscussion({ artifact, change: selected, comments: notes }, { icon })}` : `<article class="prose studio-document">${renderPlanMarkdown(current[file], versions.previous ? previous[file] || '' : undefined)}</article>` : '<p class="studio-empty">This document was removed from the current revision.</p>';
92
+ if (artifact && allNotes.length) planningReview = await renderReviewContext({ root, params: { ...params, view: 'studio' }, selected, context: { result: null }, jobs, agent, artifact, showImpact: false }, helpers);
84
93
  canvas = documents.length ? `${notice}${summary}${compare ? `<div class="studio-comparison"><section><h2>Previous · v${versions.previous.version}</h2><article class="prose studio-document">${file in previous ? markdown(previous[file]) : '<p>This document did not exist in this version.</p>'}</article></section><section><h2>Current · v${versions.current.version}</h2>${document}</section></div>` : document}` : `${notice}<div class="studio-empty"><h1>Plan this change</h1><p>Create the next artifact or generate the full plan, then revise it in the conversation.</p></div>`;
85
94
  footer = state.error ? action('refresh', 'Retry readiness', true) : !state.readiness?.planningComplete ? action('plan-next', state.readiness?.nextArtifact ? `Create ${state.readiness.nextArtifact}` : 'Create next artifact', true) : action('finish-planning', 'Finish planning', true);
86
95
  canvas += `<details class="studio-more" id="studio-planning-tools"><summary>Planning actions</summary><div class="studio-actions">${action('plan-next')}${action('propose')}${action('refresh', 'Refresh readiness')}</div></details>`;
96
+ const showPush = state.readiness?.planningComplete && (!params.plan || params.plan === 'publish' || params.created === '1' || following);
97
+ if (showPush) {
98
+ selectedPlan = 'publish'; toolbar = ''; planningReview = '';
99
+ canvas = `<section class="studio-plan-ready" aria-labelledby="studio-plan-ready-title"><h1 id="studio-plan-ready-title">Push spec files</h1><p>Your generated documents are ready. Review them, choose a commit message, and push them to your Git repository.</p>${await renderPlanGit(root, selected, Boolean(state.pending), icon, true)}</section>`;
100
+ footer = action('finish-planning', 'Finish planning');
101
+ }
102
+
87
103
 
88
104
  } else {
89
105
  const validation = state.validation;
90
106
  const report = state.jobs.find(job => job.action === 'verify' && job.status === 'completed');
107
+ const reportReady = Boolean(report && hasVerificationReport(report.result));
91
108
  const branch = await changeBranch(root, selected.id);
92
- const step = (number, title, description, status, body) => `<li class="workflow-step" data-step-state="${status === 'Complete' || status === 'Applied' || status === 'Archived' ? 'complete' : 'pending'}"><span class="workflow-step-number" aria-hidden="true">${number}</span><section><div class="workflow-step-heading"><h2>${title}</h2>${badge(status, ['Complete','Applied','Archived'].includes(status) ? 'success' : '')}</div><p>${description}</p>${body}</section></li>`;
109
+ const stepCommands = { 1: ['Agent skills', 'openspec-propose · openspec-update-change'], 2: ['Agent skill, then review in Spequi', 'openspec-apply-change'], 3: ['Local command', `openspec validate ${selected.id} --type change --strict --json --no-interactive`], 4: ['Agent skill or read-only comparison', 'openspec-verify-change'], 5: ['Agent skill', 'openspec-sync-specs'], 6: ['Agent skill', 'openspec-archive-change'] };
110
+ const step = (number, title, description, status, body) => {
111
+ if (state.building) status = number === 1 ? state.readiness?.planningComplete ? 'Ready to finish' : 'In progress' : 'Awaiting plan';
112
+ const tone = ['Complete', 'Applied', 'Archived', 'Ready to finish'].includes(status) ? 'success' : ['In progress', 'Generating', 'Ready to review', 'Next'].includes(status) ? 'blue' : ['Awaiting plan', 'Run again'].includes(status) ? 'workflow-status-waiting' : status === 'Report missing' ? 'workflow-status-error' : '';
113
+ return `<li class="workflow-step" data-step-state="${status === 'Complete' || status === 'Applied' || status === 'Archived' ? 'complete' : 'pending'}"><span class="workflow-step-number" aria-hidden="true">${number}</span><section><div class="workflow-step-heading"><div class="workflow-step-title"><h2>${title}</h2><code class="workflow-command-label" title="${e(stepCommands[number][1])}">${e({1:'/opsx-propose',2:'/opsx-apply',3:'openspec validate',4:'/opsx-verify',5:'/opsx-sync',6:'/opsx-archive'}[number])}</code></div>${badge(status, tone)}</div><p>${description}</p><div class="workflow-step-actions">${body}</div></section></li>`;
114
+ };
115
+ const publishPlan = state.readiness?.planningComplete ? await renderPlanGit(root, selected, Boolean(state.pending), icon) : '';
93
116
  const planStatus = selected.archived || state.readiness?.planningComplete ? 'Complete' : 'In progress';
94
- const planLink = link('Open planning documents', { change: selected.id, view: 'studio', stage: 'shape' }, 'button');
95
- const diffLink = link(state.result?.applied ? 'Review applied changes' : state.result ? 'Review file diff' : 'Open Files', { change: selected.id, view: 'preview' }, 'button');
117
+ const planLink = link('Open planning documents', { change: selected.id, view: 'rendered', doc: selected.files.find(file => file.endsWith('/proposal.md')) || selected.files[0] }, 'button');
118
+ const diffLink = state.building ? '<button type="button" class="button" disabled>Open Files</button><p class="studio-blocker">Finish planning before reviewing file changes.</p>' : link(state.result?.applied ? 'Review applied changes' : state.result ? 'Review file diff' : 'Open Files', { change: selected.id, view: 'preview' }, 'button');
96
119
  const validationBody = validation ? `<p>${badge(validation.stale ? 'Plan changed; run again' : validation.valid ? 'Specification valid' : 'Findings to review', validation.valid && !validation.stale ? 'success' : '')}</p><time>${e(new Date(validation.checkedAt).toLocaleString())}</time>${validation.issues.length ? `<ul>${validation.issues.map(item => `<li>${e(item.level || item.severity || 'Finding')}: ${e(item.message || '')}</li>`).join('')}</ul>` : ''}` : '';
97
- const reportStale = report && (state.previewStale || state.result?.appliedAt && report.updatedAt < state.result.appliedAt);
98
- const reportBody = report ? `<details class="workflow-report" id="workflow-verification"><summary>${reportStale ? 'Earlier report · run again after changes' : 'Read verification report'}</summary><div class="prose studio-document">${markdown(report.result || 'Report completed without a summary.')}</div></details>` : '';
120
+ const reportStale = report && (state.previewStale || state.result?.appliedAt && report.updatedAt < state.result.appliedAt || state.jobs.some(job => ['start-plan', 'propose', 'plan-next', 'revise-plan', 'update-specs', 'sync-specs'].includes(job.action) && job.status === 'completed' && job.updatedAt > report.updatedAt));
121
+ const reportBody = report && !reportReady ? '<p class="workflow-report-missing" role="status">The earlier run returned no report content. Run Check implementation again to get findings and inspected scope.</p>' : report ? `<details class="workflow-report" id="workflow-verification"><summary>${reportStale ? 'Earlier report · run again after changes' : 'Read verification report'}</summary><div class="prose studio-document">${markdown(report.result || 'Report completed without a summary.')}</div></details>` : '';
99
122
  const branchForm = selected.archived ? '' : `<details class="workflow-branch" id="workflow-branch"><summary>${icon('git')}<span>Branch: <strong>${e(branch || 'current branch')}</strong></span>${icon('chevron')}</summary><form id="change-branch-form" data-lifecycle-form action="/api/change-branch" method="post"><input type="hidden" name="change" value="${e(selected.id)}"><label for="change-branch">Git branch (optional)</label><div><input id="change-branch" name="branch" maxlength="200" value="${e(branch)}" placeholder="feature/change-name" ${state.pending ? 'disabled' : ''}><button type="submit" class="button" ${state.pending ? 'disabled' : ''}>Save branch</button></div><p>The agent creates or switches to this branch before starting any request, including planning. Existing branches require confirmation.</p>${feedback}</form></details>`;
100
- canvas = `<article class="studio-finish workflow-guide"><h1>${selected.archived ? 'Change archived' : 'From plan to finished change'}</h1><p>Follow the steps below. File generation only makes changes; run the optional checks when you choose.</p>${branchForm}<ol class="workflow-steps">${step(1, 'Prepare the plan', 'Define what should change in the proposal, specs, design and tasks. Planning stops before application code is changed.', planStatus, planLink)}${step(2, 'Generate, review and apply', 'Generate the spec’s file changes in an isolated copy. Review the diff and its spec references, then apply when ready.', state.result?.applied ? 'Applied' : state.result ? 'Ready to review' : state.pending?.action === 'preview' ? 'Generating' : 'Next', diffLink)}${step(3, 'Validate the specification', 'Optional. Check the planning documents for OpenSpec format and consistency. This does not test application behavior.', validation && !validation.stale && validation.valid ? 'Complete' : 'Optional', validationBody + action('validate', 'Validate specification'))}${step(4, 'Verify the implementation', 'Optional. Ask your agent to compare the implementation against the plan and report gaps. This runs only when you request it.', report && !reportStale ? 'Complete' : 'Optional', reportBody + action('verify', 'Check implementation'))}${step(5, 'Sync the specifications', 'Optional before archive. Merge this change’s requirements into the project’s main specs while keeping the change active.', state.jobs.some(job => job.action === 'sync-specs' && job.status === 'completed') ? 'Complete' : 'Optional', action('sync-specs'))}${step(6, 'Archive the change', 'Close the change when the work is complete. The archive workflow reviews task completion and spec conflicts before proceeding.', selected.archived ? 'Archived' : 'Finish', `<div class="studio-actions">${action('archive')}${state.actions['archive-override']?.enabled ? action('archive-override') : ''}</div>`)}</ol></article>`;
101
- footer = selected.archived ? '<p>Archived documents and conversation remain available.</p>' : '<p>Choose a step above. Checks run only when you request them.</p>';
123
+ canvas = `<article class="studio-finish workflow-guide"><h1>${selected.archived ? 'Change archived' : 'From plan to finished change'}</h1><p>Plan first, review the proposed code, then apply it. Validation and verification are optional. Each step shows the command or agent skill it uses.</p>${branchForm}<ol class="workflow-steps">${step(1, 'Prepare the plan', 'Define what should change in the proposal, specs, design and tasks. Planning stops before application code is changed.', planStatus, planLink + publishPlan)}${step(2, 'Generate, review and apply', 'Generate the spec’s file changes in an isolated copy. Review the diff and its spec references, then apply when ready.', state.result?.applied ? 'Applied' : state.result ? 'Ready to review' : state.pending?.action === 'preview' ? 'Generating' : 'Next', diffLink)}${step(3, 'Validate the specification', 'Optional. Check the planning documents for OpenSpec format and consistency. This does not test application behavior.', validation && !validation.stale && validation.valid ? 'Complete' : 'Optional', validationBody + action('validate', validation ? 'Run validation again' : 'Validate specification'))}${step(4, 'Verify the implementation', 'Optional. Ask your agent to compare the implementation against the plan and report gaps. This runs only when you request it.', reportReady && !reportStale ? 'Complete' : report && !reportReady ? 'Report missing' : reportStale ? 'Run again' : 'Optional', reportBody + action('verify', 'Check implementation'))}${step(5, 'Sync the specifications', 'Optional before archive. Merge this change’s requirements into the project’s main specs while keeping the change active.', state.jobs.some(job => job.action === 'sync-specs' && job.status === 'completed') ? 'Complete' : 'Optional', action('sync-specs'))}${step(6, 'Archive the change', 'Close the change when the work is complete. The archive workflow reviews task completion and spec conflicts before proceeding.', selected.archived ? 'Archived' : 'Finish', `${state.actions.archive?.enabled ? action('archive', 'Archive change') : state.actions['archive-override']?.enabled ? `${action('archive-override', 'Archive change')}<p class="studio-blocker">Some tasks are unfinished. Your agent will review them and ask before archiving.</p>` : action('archive', 'Archive change')}`)}</ol></article>`;
124
+ footer = state.building ? state.readiness?.planningComplete ? action('finish-planning', 'Finish planning', true) : '<p>Complete the planning documents to unlock the next steps.</p>' : selected.archived ? '<p>Archived documents and conversation remain available.</p>' : '<p>Choose a step above. Checks run only when you request them.</p>';
102
125
 
103
126
  }
104
127
  if (state.pending) footer = '<button type="button" class="button" data-studio-conversation-jump>View progress</button>';
105
128
  const latestQuestion = state.pending?.status === 'awaiting-input';
106
129
  const revisionAction = selected.files.length ? 'revise-plan' : 'plan-next';
107
- const composer = `<form ${state.pending || selected.archived ? 'hidden' : ''} class="studio-composer" data-lifecycle-form data-studio-composer id="studio-composer" action="/api/lifecycle/actions" method="post">${fields(revisionAction, selected.id)}<label for="studio-message">Describe a revision or ask about this change</label><div class="studio-message-box"><textarea name="message" id="studio-message" rows="2" maxlength="12000" required ${selected.archived || state.pending ? 'disabled' : ''} placeholder="Describe what should change, or type / for commands…"></textarea><div class="studio-composer-end"><fieldset ${selected.archived || state.pending ? 'disabled' : ''}><legend>Conversation intent</legend><label><input type="radio" name="intent" value="${revisionAction}" checked><span>${icon('file')}Revise spec</span></label><label><input type="radio" name="intent" value="explore"><span>${icon('comment')}Ask a question</span></label></fieldset><button type="submit" class="button primary" ${selected.archived || state.pending || state.error ? 'disabled' : ''}>Send ${icon('arrow')}</button></div></div>${state.error || selected.archived || state.pending ? `<p class="studio-blocker">${e(state.error || (selected.archived ? 'This change is archived and read-only.' : 'Answer or finish the current request before sending another message.'))}</p>` : ''}${feedback}</form>`;
108
- const header = `<div class="studio-flow-controls">${renderCommandPicker(state, { icon, planningOnly: stage === 'shape' })}${draft?.creationId ? `<button type="button" class="button danger" data-draft-delete="${e(draft.id)}" data-has-plan="true">Delete draft</button>` : ''}</div>`;
109
- return { header, plan: selectedPlan, followComplete, content: `<section class="studio" id="studio" data-studio data-readiness-pending="${!selected.archived && !state.readiness && !state.error}" data-awaiting-input="${latestQuestion}" data-stage="${stage}" data-pane="${base.pane}"><nav class="studio-mobile-panes" aria-label="Studio panes"><button type="button" data-studio-pane="document" aria-pressed="${base.pane === 'document'}">Document</button><button type="button" data-studio-pane="conversation" aria-pressed="${base.pane === 'conversation'}">Conversation${latestQuestion ? ' · Answer needed' : ''}</button></nav><div class="studio-body" id="studio-body"><section class="studio-canvas" aria-label="${e(stages.find(([id]) => id === stage)[1])} canvas">${toolbar ? `<div class="studio-canvas-toolbar">${toolbar}</div>` : ''}<div class="studio-canvas-body" id="studio-canvas-body">${canvas}</div></section><aside class="studio-conversation" aria-label="Change conversation"><header><div><h2>Conversation</h2><span data-lifecycle-agent-caption>${latestQuestion ? 'Your answer is needed' : agent.connected ? 'Same agent session' : 'Requests wait for your agent'}</span></div><button type="button" class="button studio-expand" data-studio-expand aria-expanded="false" aria-controls="studio-body">${icon('panel')}<span data-studio-expand-label>Expand conversation</span></button></header><div class="studio-thread" id="studio-thread">${conversation(state.jobs, agent)}</div>${composer}</aside></div><footer class="studio-footer"><div><strong>${latestQuestion ? 'Reply in the conversation to continue' : stage === 'shape' ? 'Finish planning to open Review' : selected.archived ? 'This change is archived' : 'Finish at your own pace'}</strong><span ${latestQuestion ? 'hidden' : ''}>${state.pending ? 'The current request and its progress stay in the conversation.' : stage === 'shape' ? 'Planning documents are ready when all required artifacts have been created.' : 'Validation and verification are optional, separate actions.'}</span></div>${latestQuestion ? '<button type="button" class="button primary" data-studio-question-jump>Answer question</button>' : footer}<div class="studio-footer-feedback" id="studio-action-feedback" role="status" aria-live="polite"></div></footer></section>` };
130
+ const composer = `<form ${state.pending || selected.archived ? 'hidden' : ''} class="studio-composer" data-attachment-scope="${artifactReviewID(selected.id)}" data-preview="${artifactReviewID(selected.id)}" data-file="conversation" data-attachment-blocked="${Boolean(state.pending || selected.archived || state.error)}" data-lifecycle-form data-studio-composer id="studio-composer" action="/api/lifecycle/actions" method="post">${fields(revisionAction, selected.id)}<label for="studio-message">Describe a revision or ask about this change</label><div class="studio-message-box"><textarea name="message" id="studio-message" rows="2" maxlength="12000" required ${selected.archived || state.pending ? 'disabled' : ''} placeholder="Describe what should change in the plan…" aria-describedby="studio-paste-hint"></textarea><p class="attachment-paste-hint" id="studio-paste-hint">Paste images here, or attach files.</p><div class="comment-image-drafts" data-comment-images></div><div data-composer-feedback role="status" aria-live="polite"></div><div class="studio-composer-end"><fieldset ${selected.archived || state.pending ? 'disabled' : ''}><legend>Conversation intent</legend><label><input type="radio" name="intent" value="${revisionAction}" checked><span>${icon('file')}Revise spec</span></label><label><input type="radio" name="intent" value="explore"><span>${icon('comment')}Ask a question</span></label></fieldset><div class="studio-send-actions"><button type="button" class="comment-image-add" data-comment-image-choose aria-label="Attach files" ${selected.archived || state.pending || state.error ? 'disabled' : ''} title="Attach files or paste text and images">${icon('attachment')}<span>Attach files</span></button><input type="file" data-comment-image-input multiple hidden><button type="submit" class="button primary" ${selected.archived || state.pending || state.error ? 'disabled' : ''}>Send ${icon('arrow')}</button></div></div></div>${state.error || selected.archived || state.pending ? `<p class="studio-blocker">${e(state.error || (selected.archived ? 'This change is archived and read-only.' : 'Answer or finish the current request before sending another message.'))}</p>` : ''}${feedback}</form>`;
131
+
132
+ const header = draft?.creationId ? `<div class="studio-flow-controls"><button type="button" class="button danger" data-draft-delete="${e(draft.id)}" data-has-plan="true">Delete draft</button></div>` : '';
133
+ return { header, plan: selectedPlan, followComplete, content: `<section class="studio" id="studio" data-studio data-readiness-pending="${!selected.archived && !state.readiness && !state.error}" data-awaiting-input="${latestQuestion}" data-stage="${stage}" data-pane="${base.pane}"><nav class="studio-mobile-panes" aria-label="Studio panes"><button type="button" data-studio-pane="document" aria-pressed="${base.pane === 'document'}">Document</button><button type="button" data-studio-pane="conversation" aria-pressed="${base.pane === 'conversation'}">Conversation${latestQuestion ? ' · Answer needed' : ''}</button></nav><div class="studio-body" id="studio-body"><section class="studio-canvas" aria-label="${e(stages.find(([id]) => id === stage)[1])} canvas">${toolbar ? `<div class="studio-canvas-toolbar">${toolbar}</div>` : ''}<div class="studio-canvas-body" id="studio-canvas-body">${canvas}</div></section><aside class="studio-conversation" aria-label="Change conversation"><header><div><h2>Conversation</h2><span data-lifecycle-agent-caption>${latestQuestion ? 'Your answer is needed' : agent.connected ? 'Same agent session' : 'Requests wait for your agent'}</span></div><button type="button" class="button studio-expand" data-studio-expand aria-expanded="false" aria-controls="studio-body">${icon('panel')}<span data-studio-expand-label>Expand conversation</span></button></header>${planningReview ? `<details class="studio-review" id="studio-review"><summary>${icon('comment')}Planning comments</summary>${planningReview}</details>` : ''}<div class="studio-thread" id="studio-thread">${conversation(state.jobs, agent, icon)}</div>${composer}</aside></div><footer class="studio-footer"><div><strong>${latestQuestion ? 'Reply in the conversation to continue' : stage === 'shape' || state.building ? 'Finish planning to open Review' : selected.archived ? 'This change is archived' : 'Finish at your own pace'}</strong><span ${latestQuestion ? 'hidden' : ''}>${state.pending ? 'The current request and its progress stay in the conversation.' : stage === 'shape' || state.building ? 'Planning documents are ready when all required artifacts have been created.' : 'Validation and verification are optional, separate actions.'}</span></div>${latestQuestion ? '<button type="button" class="button primary" data-studio-question-jump>Answer question</button>' : footer}<div class="studio-footer-feedback" id="studio-action-feedback" role="status" aria-live="polite"></div></footer></section>` };
110
134
  }