spequi 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.mjs CHANGED
@@ -20,11 +20,12 @@ import { requestCommand } from './commands.mjs';
20
20
  import { answerJob, askJob, jobInput } from './job-dialogue.mjs';
21
21
  import { reportSession } from './agent-session.mjs';
22
22
  import { createWorkspaceState } from './workspace-state.mjs';
23
- import { listDrafts, saveDraft, deleteDraft, resumeDraft, finishDrafts } from './drafts.mjs';
23
+ import { listDrafts, saveDraft, deleteDraft, resumeDraft } from './drafts.mjs';
24
24
  import { requestPage, deleteRequest, retryRequest, dismissRequest, inboxState } from './requests.mjs';
25
25
  import { viewerVersion } from './project.mjs';
26
26
  import { conversation } from './studio-view.mjs';
27
27
  import { initializeAnalytics, trackEvent } from './analytics.mjs';
28
+ import { validateBranch, confirmChangeBranch, saveChangeBranch } from './branches.mjs';
28
29
 
29
30
  const require = createRequire(import.meta.url);
30
31
  const publicDir = fileURLToPath(new URL('../public/', import.meta.url));
@@ -47,12 +48,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
47
48
  const csrf = randomBytes(32).toString('hex'), agentToken = randomBytes(32).toString('hex');
48
49
  const jobReader = createJobReader(root);
49
50
  let broadcast = () => {}, closed = false;
50
- const state = createWorkspaceState(root, { check: readinessCheck, changed: (change, readiness) => {
51
- broadcast('readiness', { change });
52
- if (readiness?.planningComplete) void jobReader.read().then(jobs => {
53
- if (!jobs.some(job => job.change === change && pendingStatuses.includes(job.status))) return finishDrafts(root, change);
54
- }).catch(error => { if (!quiet) process.stderr.write(`Draft readiness: ${error.message}\n`); });
55
- } });
51
+ const state = createWorkspaceState(root, { check: readinessCheck, changed: change => broadcast('readiness', { change }) });
56
52
  let origin;
57
53
  const send = (response, status, content, type = 'text/html; charset=utf-8', headers = {}) => {
58
54
  response.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin', ...headers }); response.end(content);
@@ -140,7 +136,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
140
136
  const relevant = jobs.filter(job => !job.hiddenAt && (selected && jobMatchesChange(job, selected) || job.id === url.searchParams.get('creation')));
141
137
  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))) })));
142
138
  const inbox = requestPage(jobs, {}, { agent, dismissed: await inboxState(root) });
143
- 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');
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');
144
140
  }
145
141
  const feedbackMatch = url.pathname.match(/^\/api\/reviews\/([a-zA-Z0-9_-]+)\/feedback\/([a-zA-Z0-9_-]+)$/);
146
142
  if (feedbackMatch) {
@@ -172,6 +168,13 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
172
168
  return send(response, 204, '');
173
169
  }
174
170
  if (url.pathname === '/api/drafts') return send(response, 200, JSON.stringify({ draft: await saveDraft(root, payload) }), 'application/json');
171
+ if (url.pathname === '/api/change-branch') {
172
+ 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.');
173
+ const branch = await validateBranch(root, payload.branch);
174
+ const confirmed = await confirmChangeBranch(root, payload.change, branch, payload.confirmBranch);
175
+ await saveChangeBranch(root, payload.change, branch, confirmed);
176
+ 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');
177
+ }
175
178
  const draftResume = url.pathname.match(/^\/api\/drafts\/([a-zA-Z0-9_-]+)\/resume$/);
176
179
  if (draftResume) return send(response, 200, JSON.stringify(await resumeDraft(root, draftResume[1])), 'application/json');
177
180
  const draftDelete = url.pathname.match(/^\/api\/drafts\/([a-zA-Z0-9_-]+)\/delete$/);
@@ -189,6 +192,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
189
192
  if (['/api/lifecycle/actions', '/api/lifecycle/command'].includes(url.pathname)) {
190
193
  const { job, ...result } = await (url.pathname.endsWith('/command') ? requestCommand(root,payload) : requestLifecycle(root, payload));
191
194
  if (result.refreshed) state.invalidate(payload.change);
195
+ if (result.finishedPlanning) { state.invalidate(payload.change); broadcast('changed', { change: payload.change }); }
192
196
  return send(response, job ? 201 : 200, JSON.stringify({ ...result, ...(job ? { job: { id: job.id, action: job.action, change: job.change, status: job.status } } : {}) }), 'application/json', { 'HX-Trigger': 'workspace-updated' });
193
197
  }
194
198
  const replyMatch = url.pathname.match(/^\/api\/lifecycle\/jobs\/([a-zA-Z0-9_-]+)\/reply$/);
@@ -230,6 +234,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
230
234
  }
231
235
  if (url.pathname === '/api/jobs') {
232
236
  const job = await enqueue(root, payload);
237
+ 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');
233
238
  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 }) });
234
239
  }
235
240
  const cancelMatch = url.pathname.match(/^\/api\/jobs\/([a-zA-Z0-9_-]+)\/cancel$/);
@@ -245,7 +250,7 @@ export async function startServer({ root = process.cwd(), port, quiet = false, r
245
250
  if ((await listJobs(root)).some(item => item.change === job.change && pendingStatuses.includes(item.status))) throw new Error('Wait for the current request to finish before applying.');
246
251
  if (await previewPlanChanged(root, selected, job, await previewResult(root, job.id))) throw new Error('The spec changed. Generate a fresh code preview before applying.');
247
252
  await applyPreview(root, applyMatch[1]);
248
- return send(response, 200, '<p class="success-message">Code changes applied to your project. <a href="/?change=' + encodeURIComponent(job.change) + '&amp;view=studio&amp;stage=finish">Continue in Build</a></p>', undefined, { 'HX-Trigger': 'workspace-updated' });
253
+ return send(response, 200, '<p class="success-message">Code changes applied to your project. <a href="/?change=' + encodeURIComponent(job.change) + '&amp;view=workflow">Continue to validation</a></p>', undefined, { 'HX-Trigger': 'workspace-updated' });
249
254
  }
250
255
  return send(response, 404, 'Action not found');
251
256
  } catch (error) {
@@ -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"><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>';
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>`;
14
14
  }
@@ -33,5 +33,7 @@ export function specContextRows(context, rows, scope, mode, icon) {
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
+ 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>` : '' };
37
39
  }
@@ -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.' }; }
@@ -1,14 +1,12 @@
1
1
  import { escape as e, markdown } from './specs.mjs';
2
- import { lifecycleState, previewPlanChanged } from './lifecycle.mjs';
2
+ import { lifecycleState } from './lifecycle.mjs';
3
3
  import { planVersions, planChanges } from './studio-plans.mjs';
4
4
  import { renderPlanMarkdown } from './studio-documents.mjs';
5
- import { renderFileDiff } from './diff-view.mjs';
6
- import { getPreviewContext } from './preview-view.mjs';
7
5
  import { renderCommandPicker } from './commands.mjs';
8
6
  import { renderCreation } from './creation-view.mjs';
9
- import { renderSourcePreviewTools } from './source-preview-view.mjs';
7
+ import { changeBranch } from './branches.mjs';
10
8
 
11
- const stages = [['shape', 'Shape spec'], ['implement', 'Implement'], ['finish', 'Validate & archive']];
9
+ const stages = [['shape', 'Plan'], ['finish', 'Workflow']];
12
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' };
13
11
  const statusLabel = value => ({ queued: 'Waiting for agent', running: 'Working', 'awaiting-input': 'Your answer is needed', completed: 'Completed', failed: 'Failed', cancelled: 'Cancelled' }[value] || value);
14
12
  const feedback = '<div data-lifecycle-feedback role="status" aria-live="polite"></div>';
@@ -26,6 +24,8 @@ function question(job, item) {
26
24
  return `<section class="studio-question" ${waiting ? `data-studio-question="${e(item.id)}" tabindex="-1" aria-labelledby="studio-question-${e(item.id)}"` : ''}><p class="studio-question-text" id="studio-question-${e(item.id)}">${e(item.message)}</p>${item.answeredAt ? `<div class="studio-answer"><strong>Your answer</strong><p>${e(item.answer)}</p></div>` : waiting ? `<form data-lifecycle-form id="studio-answer-${item.id}" action="/api/lifecycle/jobs/${job.id}/reply" method="post"><input type="hidden" name="questionId" value="${item.id}">${item.options.map(option => `<label class="studio-choice"><input type="radio" name="choice" value="${e(option)}"><span>${e(option)}</span></label>`).join('')}<label for="studio-reply-${item.id}">${item.options.length ? 'Additional context (optional)' : 'Your answer'}</label><textarea id="studio-reply-${item.id}" name="answer" rows="3" maxlength="6000" ${item.options.length ? '' : 'required'}></textarea><button class="button primary" type="submit">Reply & continue</button>${feedback}</form>` : '<p class="muted">This request is no longer waiting for a reply.</p>'}</section>`;
27
25
  }
28
26
 
27
+ export function jobQuestions(job) { return (job.questions || []).map(item => question(job, item)).join(''); }
28
+
29
29
  export function conversation(jobs, agent = {}) {
30
30
  const visible = jobs.filter(job => !job.hiddenAt);
31
31
  const active = visible.find(job => ['running', 'awaiting-input'].includes(job.status)) || visible.find(job => job.status === 'queued');
@@ -37,10 +37,10 @@ export function conversation(jobs, agent = {}) {
37
37
  const pending = ['queued', 'running', 'awaiting-input'].includes(job.status);
38
38
  const active = ['queued', 'running'].includes(job.status);
39
39
  const ownerConnected = agent.queue?.active?.id === job.id ? agent.queue.active.ownerConnected : agent.connected;
40
- 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' : 'Waiting for the agent to reconnect';
41
- const latest = job.logs.at(-1)?.message || 'Progress will appear here as the agent works.';
42
- 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><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>${(job.questions || []).map(item => question(job, item)).join('')}${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 stalled 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>`;
40
+ 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
+ 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
+ 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>`;
44
44
  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
45
  }).join('');
46
46
  }
@@ -56,84 +56,55 @@ export async function renderStudio({ root, selected, jobs, agent, params = {}, c
56
56
  const option = state.actions[name];
57
57
  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
58
  };
59
- let canvas = '', toolbar = '', footer = '';
59
+ let canvas = '', toolbar = '', footer = '', selectedPlan = '', followComplete = false;
60
60
  if (stage === 'shape') {
61
61
  const versions = await planVersions(root, selected, jobs);
62
62
  const current = versions.current?.documents || {}, previous = versions.previous?.documents || {};
63
63
  const documents = [...new Set([...Object.keys(current), ...Object.keys(previous)])];
64
- const file = 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];
64
+ const following = state.jobs.find(job => job.id === params.follow && job.action === 'plan-next' && job.status === 'completed');
65
+ 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);
67
+ 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
+ selectedPlan = file || '';
65
69
  const changes = versions.previous ? planChanges(previous, current) : [];
66
70
  const newSpec = params.created === '1';
67
71
  const compare = !newSpec && params.compare === '1' && Boolean(versions.previous);
68
- let artifactDocuments = [];
69
- const artifactTabs = state.readiness?.artifacts.filter(item => item.status !== 'skipped').map(item => {
72
+ const files = state.readiness?.artifacts.filter(item => item.status !== 'skipped').map(item => {
70
73
  const paths = state.readiness.artifactPaths[item.id]?.existingOutputPaths || [];
71
- const available = documents.filter(name => paths.some(output => output.replaceAll('\\', '/').endsWith('/' + name)));
72
- if (available.includes(file)) artifactDocuments = available;
73
- return available.length ? stageLink(e(item.id.replaceAll('-', ' ')), { plan: available.includes(file) ? file : available[0], created: params.created }, `studio-artifact-tab ${available.includes(file) ? 'selected' : ''}`, available.includes(file) ? 'aria-current="page"' : '') : `<span class="studio-artifact-tab" aria-disabled="true" title="${e(item.status === 'ready' ? 'Create this artifact next' : 'Complete its planning dependencies first')}">${e(item.id.replaceAll('-', ' '))}<small>Pending</small></span>`;
74
- }).join('') || '';
75
- const files = artifactTabs ? artifactDocuments : documents;
74
+ return documents.filter(name => paths.some(output => output.replaceAll('\\', '/').endsWith('/' + name)));
75
+ }).find(files => files.includes(file)) || documents;
76
76
  const fileHint = files.every(name => name.startsWith('specs/')) ? 'OpenSpec stores each capability in specs/<capability>/spec.md. Select one to review its requirement changes and scenarios.' : 'OpenSpec separates proposals, design, tasks, and capability specs. Select a document to review that part of the plan.';
77
77
  const fileLabel = name => name.replace(/^specs\//, '').replace(/\/spec\.md$/, '').replace(/\.md$/, '');
78
78
  const displayLabel = name => fileLabel(name).replace(/[-_]/g, ' ').replace(/^./, letter => letter.toUpperCase());
79
79
  const filePicker = files.length > 1 ? `<div class="studio-artifact-file-picker"><button type="button" id="studio-plan-file" popovertarget="studio-plan-files" aria-controls="studio-plan-files" aria-expanded="false" aria-label="Choose planning document" aria-describedby="studio-plan-files-help" title="${e(file)}">${icon('file')}<span>${e(displayLabel(file))}</span>${icon('down')}</button><nav id="studio-plan-files" class="studio-artifact-file-menu" popover="auto" data-dropdown-panel aria-label="Planning documents">${files.map(name => stageLink(`<span class="studio-artifact-option-copy"><strong class="studio-artifact-option-heading"><span class="studio-artifact-folder">${e(name.slice(0, name.lastIndexOf('/') + 1))}</span><span class="studio-artifact-filename">${e(name.split('/').at(-1))}</span></strong><small>${e(documentDescription(current[name] ?? previous[name]))}</small></span><span class="studio-artifact-choice-state">${name === file ? icon('check') : ''}</span>`, { plan: name, compare: params.compare }, name === file ? 'selected' : '', `aria-label="${e(name)}" data-dropdown-choice hx-sync="#workspace:replace"${name === file ? ' aria-current="page"' : ''}`)).join('')}<p class="studio-artifact-file-help" id="studio-plan-files-help">${e(fileHint)}</p></nav></div>` : '';
80
- toolbar = artifactTabs || filePicker ? `<div class="studio-artifact-navigation">${artifactTabs ? `<nav class="studio-artifact-tabs" aria-label="Planning artifacts">${artifactTabs}</nav>` : ''}${filePicker}</div>` : '';
80
+ toolbar = filePicker ? `<div class="studio-artifact-navigation">${filePicker}</div>` : '';
81
81
  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
82
  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
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>';
84
- 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>Shape this change</h1><p>Create the next artifact or generate the full plan, then revise it in the conversation.</p></div>`;
85
- 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) : state.preview && state.result && !state.previewStale ? stageLink('Review implementation preview', { stage: 'implement' }, 'button primary') : action('preview', 'Preview implementation', true);
84
+ 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
+ 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
86
  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>`;
87
- } else if (stage === 'implement') {
88
- const preview = await getPreviewContext(root, params, jobs, selected);
89
- const { job, result, file } = preview;
90
- const diffLink = (label, values, ...rest) => stageLink(label, { ...values, view: 'studio', stage: 'implement', pane: 'document' }, rest[0], `${rest[1] || ''} hx-sync="#workspace:replace"`);
91
- toolbar = job ? `<button type="button" class="button studio-files-button" id="studio-browse-files" data-studio-files aria-controls="navigation" aria-label="Browse changed files">${icon('folder')}Files <span class="tab-count">${result?.changes.length || 0}</span></button><form class="studio-picker" action="/" hx-get="/" hx-target="#workspace" hx-swap="outerHTML" hx-push-url="true" hx-trigger="change"><input type="hidden" name="change" value="${e(selected.id)}"><input type="hidden" name="view" value="studio"><input type="hidden" name="stage" value="implement"><input type="hidden" name="q" value="${e(params.q || '')}"><input type="hidden" name="pane" value="${base.pane}"><label for="studio-preview-picker">Preview</label><select name="job" id="studio-preview-picker" ${job ? '' : 'disabled'}>${preview.previews.map((item, index) => `<option value="${item.id}" ${item.id === job?.id ? 'selected' : ''}>${index === 0 ? 'Latest preview' : e(new Date(item.updatedAt).toLocaleString())}</option>`).join('')}</select>${file ? `<input type="hidden" name="file" value="${e(file.file)}">` : ''}<input type="hidden" name="mode" value="${params.mode === 'split' ? 'split' : 'unified'}"><input type="hidden" name="wrap" value="${params.wrap === '0' ? '0' : '1'}"></form>` : '';
92
- const stale = job && result ? await previewPlanChanged(root, selected, job, result) : false;
93
- let emptyTitle = 'Ready to implement', emptyDescription = 'Generate an implementation in an isolated copy, then review the file diff before applying it.';
94
- let emptyAction = action('preview', agent.connected ? 'Generate implementation' : 'Queue implementation', true, 'empty-preview');
95
- let emptyHint = !agent.connected ? 'Resume the Spequi skill in your coding session to process queued requests.' : '';
96
- const conversationAction = (label, question = false) => `<button type="button" class="button" ${question ? 'data-studio-question-jump' : 'data-studio-conversation-jump'} data-studio-request="${e(state.pending?.id || job?.id || preview.failure?.id || '')}">${label}${icon('arrow')}</button>`;
97
- if (selected.archived) {
98
- emptyTitle = result ? 'No file changes in this preview' : 'No preview saved for this archived change'; emptyDescription = 'The archived planning documents remain available to review.';
99
- emptyAction = stageLink('Review plan', { stage: 'shape' }, 'button'); emptyHint = '';
100
- } else if (state.pending) {
101
- const pending = state.pending, implementation = pending.action === 'preview';
102
- emptyTitle = pending.status === 'awaiting-input' ? 'Your answer is needed' : pending.status === 'queued' && !agent.connected ? 'Waiting for your agent' : implementation ? pending.status === 'queued' ? 'Implementation queued' : 'Preparing the implementation' : 'Finish the current request';
103
- emptyDescription = pending.status === 'awaiting-input' ? 'Reply to your agent in the conversation to continue.' : pending.status === 'queued' ? `${labels[pending.action] || 'Your request'} is queued. ${agent.connected ? 'Your agent will pick it up when ready.' : 'Resume the Spequi skill in your coding session to continue.'}${implementation ? ' Its file diff will appear here when ready.' : ' Generate the implementation after this request finishes.'}` : implementation ? 'Proposed changes are being prepared in an isolated copy. The file diff will appear here when ready.' : `${labels[pending.action] || 'The current request'} is in progress. Generate the implementation after it finishes.`;
104
- emptyAction = conversationAction(pending.status === 'awaiting-input' ? 'Answer question' : 'View request', pending.status === 'awaiting-input'); emptyHint = '';
105
- } else if (state.error || !state.readiness) {
106
- emptyTitle = state.error ? 'Could not check the plan' : 'Checking the plan'; emptyDescription = state.error || 'Checking whether the required planning documents are ready for implementation.';
107
- emptyAction = action('refresh', 'Refresh readiness', true, 'empty-readiness'); emptyHint = '';
108
- } else if (!state.readiness.planningComplete) {
109
- emptyTitle = 'Finish planning first'; emptyDescription = 'Complete the required planning documents before generating an implementation.';
110
- emptyAction = stageLink('Continue planning', { stage: 'shape' }, 'button primary'); emptyHint = '';
111
- } else if (result) {
112
- emptyTitle = 'No file changes in this preview'; emptyDescription = 'This preview completed without producing a reviewable file diff. Read the agent result in the conversation.';
113
- emptyAction = conversationAction('View agent result'); emptyHint = '';
114
- } else if (job) {
115
- emptyTitle = 'Preview files unavailable'; emptyDescription = 'The saved preview files are missing. Generate a fresh implementation preview to review its diff.';
116
- } else if (preview.failure) {
117
- emptyTitle = 'Implementation preview failed'; emptyDescription = preview.failure.result || 'The previous attempt could not produce a preview. Try again with your agent attached.';
118
- } else if (!state.actions.preview?.enabled) {
119
- emptyTitle = 'No implementation preview saved'; emptyDescription = state.actions.preview?.reason || 'Review the plan before requesting an implementation.';
120
- emptyAction = stageLink('Review plan', { stage: 'shape' }, 'button'); emptyHint = '';
121
- }
122
- const emptyPreview = `<div class="studio-empty studio-implementation-empty">${icon(state.pending ? 'clock' : 'code')}<h1>${e(emptyTitle)}</h1><p>${e(emptyDescription)}</p><div class="studio-empty-actions">${emptyAction}</div>${emptyHint ? `<p class="studio-empty-hint">${e(emptyHint)}</p>` : ''}</div>`;
123
- canvas = `${stale ? '<p class="studio-notice studio-error">The spec changed after this preview. Generate a fresh preview before applying.</p>' : ''}${file && preview.pending ? '<p class="studio-notice">An implementation preview is being prepared in a separate copy. Your project has not changed.</p>' : ''}${result?.unsupported.length ? `<p class="studio-notice studio-error">Unsupported files prevent application: ${e(result.unsupported.join(', '))}</p>` : ''}${file ? `<section class="diff-panel studio-diff-panel">${await renderFileDiff({ root, job, file, result, selected, params, compact: false, pathLabel: true }, { ...helpers, link: diffLink })}</section>` : emptyPreview}`;
124
- const canApply = result && !selected.archived && !state.pending && !stale && !result.applied && result.changes.length && !result.unsupported.length;
125
- footer = !file ? '' : result?.applied ? stageLink(`Continue to validation ${icon('arrow')}`, { stage: 'finish' }, 'button primary') : job && result && !stale ? `<div class="studio-action"><form data-apply-form hx-post="/api/previews/${job.id}/apply" hx-target="#studio-action-feedback"><button class="button primary" type="submit" ${canApply ? '' : 'disabled'}>Apply reviewed preview</button></form>${!canApply ? `<p class="studio-blocker">${e(selected.archived ? 'This change is archived.' : state.pending ? 'Finish the current request first.' : 'No supported file changes are available to apply.')}</p>` : ''}</div>` : action('preview', 'Generate preview', true);
126
- canvas += `<details class="studio-more" id="studio-offline-tools"><summary>Offline analysis and preview tools</summary>${await renderSourcePreviewTools(root, selected, Boolean(result), state.pending, icon)}</details>`;
87
+
127
88
  } else {
128
89
  const validation = state.validation;
129
90
  const report = state.jobs.find(job => job.action === 'verify' && job.status === 'completed');
130
- canvas = `<article class="studio-finish"><h1>${selected.archived ? 'Change archived' : 'Validate and finish'}</h1><p>Check the implementation against the spec, then finish this change.</p><section><h2>Specification validation</h2>${validation ? `<p>${badge(validation.stale ? 'Spec changed since validation' : validation.valid ? 'Specification valid' : 'Specification findings', validation.valid && !validation.stale ? 'success' : '')}</p><time>${e(new Date(validation.checkedAt).toLocaleString())}</time><ul>${validation.issues.map(item => `<li>${e(item.level || item.severity || 'Finding')}: ${e(item.message || '')}</li>`).join('')}</ul>` : '<p>No specification validation result saved yet.</p>'}<p class="muted">This checks planning artifacts, not application behavior.</p>${action('validate', 'Validate specification')}</section><section><h2>Implementation verification</h2>${report ? `<p class="muted">${e(new Date(report.updatedAt).toLocaleString())}${state.previewStale || state.result?.appliedAt && report.updatedAt < state.result.appliedAt ? ' · Earlier implementation; run verification again.' : ''}</p><div class="prose studio-document">${markdown(report.result || 'Report completed without a summary.')}</div>` : '<p>No implementation verification report saved yet.</p>'}${action('verify', 'Check implementation')}</section><section><h2>Finish this change</h2><p>Sync updates main specs and keeps the change active. Archive closes the change after the workflow checks its state.</p><div class="studio-actions">${action('sync-specs')}${action('archive')}${state.actions['archive-override']?.enabled ? action('archive-override') : ''}</div></section></article>`;
131
- footer = selected.archived ? '<p>Archived documents and conversation remain available.</p>' : !report || state.previewStale || state.result?.appliedAt && report.updatedAt < state.result.appliedAt ? action('verify', 'Check implementation', true, 'next-verify') : action('archive', 'Archive change', true, 'next-archive');
91
+ 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>`;
93
+ 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');
96
+ 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>` : '';
99
+ 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>';
102
+
132
103
  }
133
104
  if (state.pending) footer = '<button type="button" class="button" data-studio-conversation-jump>View progress</button>';
134
105
  const latestQuestion = state.pending?.status === 'awaiting-input';
135
106
  const revisionAction = selected.files.length ? 'revise-plan' : 'plan-next';
136
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>`;
137
- const header = `<nav class="studio-stages" aria-label="Build stages">${stages.map(([id, name], index) => stageLink(`<span class="studio-stage-number">${index + 1}</span>${e(name)}`, { stage: id }, `studio-stage ${stage === id ? 'selected' : ''}`, `id="studio-stage-${id}" data-studio-stage="${id}" ${stage === id ? 'aria-current="step"' : ''}`)).join('')}</nav><div class="studio-flow-controls">${renderCommandPicker(state, { icon })}${draft?.creationId ? `<button type="button" class="button danger" data-draft-delete="${e(draft.id)}" data-has-plan="true">Delete draft</button>` : ''}</div>`;
138
- return { header, 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' ? 'Review the plan, then preview code' : stage === 'implement' ? state.result?.changes.length ? 'Review the exact changes before applying' : 'Generate a preview to review the implementation' : selected.archived ? 'This change is archived' : 'Read the checks before archiving'}</strong><span ${latestQuestion ? 'hidden' : ''}>${state.pending ? 'The current request and its progress stay in the conversation.' : stage === 'shape' ? 'Spec revisions update documents; code generation is a separate step.' : stage === 'implement' ? state.result?.changes.length ? 'Application uses the reviewed files and checks for conflicts.' : 'Review the proposed file diff before applying changes.' : 'All finish actions use the existing workflow checks.'}</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>` };
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>` };
139
110
  }