spequi 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +27 -12
- package/bin/spequi.mjs +5 -3
- package/docs/agent-workflow.md +28 -4
- package/package.json +1 -1
- package/public/app.css +52 -2
- package/public/app.js +133 -64
- package/public/diff.css +62 -39
- package/public/index.html +230 -189
- package/public/requests.js +54 -27
- package/public/review.css +21 -4
- package/public/review.js +85 -50
- package/public/session.js +34 -20
- package/public/studio.css +191 -33
- package/public/studio.js +1 -1
- package/public/workflow.js +92 -6
- package/skills/spequi/SKILL.md +29 -10
- package/src/analytics.mjs +50 -16
- package/src/branches.mjs +52 -0
- package/src/commands.mjs +4 -41
- package/src/comment-controls.mjs +1 -1
- package/src/comment-view.mjs +6 -5
- package/src/creation-view.mjs +10 -3
- package/src/diff-view.mjs +3 -3
- package/src/document-view.mjs +9 -2
- package/src/drafts.mjs +19 -4
- package/src/feedback.mjs +2 -0
- package/src/jobs.mjs +71 -18
- package/src/lifecycle.mjs +12 -9
- package/src/plan-git.mjs +129 -0
- package/src/preview-view.mjs +14 -9
- package/src/previews.mjs +4 -1
- package/src/project.mjs +3 -2
- package/src/requests.mjs +1 -1
- package/src/review-images.mjs +51 -0
- package/src/review-store.mjs +16 -16
- package/src/review-view.mjs +3 -2
- package/src/server.mjs +54 -20
- package/src/source-preview-view.mjs +4 -4
- package/src/spec-context-view.mjs +3 -3
- package/src/spec-context.mjs +11 -8
- package/src/studio-view.mjs +64 -27
- package/src/updates.mjs +82 -0
- package/src/verification.mjs +6 -0
- package/src/views.mjs +53 -15
package/src/studio-view.mjs
CHANGED
|
@@ -1,12 +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 {
|
|
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';
|
|
11
|
+
import { changeBranch } from './branches.mjs';
|
|
7
12
|
|
|
8
|
-
const stages = [['shape', '
|
|
9
|
-
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
|
+
const stages = [['shape', 'Plan'], ['finish', 'Workflow']];
|
|
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' };
|
|
10
15
|
const statusLabel = value => ({ queued: 'Waiting for agent', running: 'Working', 'awaiting-input': 'Your answer is needed', completed: 'Completed', failed: 'Failed', cancelled: 'Cancelled' }[value] || value);
|
|
11
16
|
const feedback = '<div data-lifecycle-feedback role="status" aria-live="polite"></div>';
|
|
12
17
|
const fields = (action, change) => `<input type="hidden" name="action" value="${e(action)}"><input type="hidden" name="change" value="${e(change)}">`;
|
|
@@ -23,28 +28,30 @@ function question(job, item) {
|
|
|
23
28
|
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>`;
|
|
24
29
|
}
|
|
25
30
|
|
|
26
|
-
export function
|
|
31
|
+
export function jobQuestions(job) { return (job.questions || []).map(item => question(job, item)).join(''); }
|
|
32
|
+
|
|
33
|
+
export function conversation(jobs, agent = {}, icon = () => '') {
|
|
27
34
|
const visible = jobs.filter(job => !job.hiddenAt);
|
|
28
35
|
const active = visible.find(job => ['running', 'awaiting-input'].includes(job.status)) || visible.find(job => job.status === 'queued');
|
|
29
36
|
jobs = visible.slice(0, 20);
|
|
30
37
|
if (active && !jobs.includes(active)) jobs = [...jobs.slice(0, 19), active];
|
|
31
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>' : '';
|
|
32
|
-
if (!jobs.length) return
|
|
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>`;
|
|
33
40
|
return historyLink + [...jobs].reverse().map((job, index) => {
|
|
34
41
|
const pending = ['queued', 'running', 'awaiting-input'].includes(job.status);
|
|
35
42
|
const active = ['queued', 'running'].includes(job.status);
|
|
36
43
|
const ownerConnected = agent.queue?.active?.id === job.id ? agent.queue.active.ownerConnected : agent.connected;
|
|
37
|
-
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' : '
|
|
38
|
-
const latest = !ownerConnected && job.status === 'running' ? '
|
|
39
|
-
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>` : '';
|
|
40
|
-
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
|
|
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';
|
|
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.';
|
|
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>` : '';
|
|
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>`;
|
|
41
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>`;
|
|
42
49
|
}).join('');
|
|
43
50
|
}
|
|
44
51
|
|
|
45
52
|
export async function renderStudio({ root, selected, jobs, agent, params = {}, changes = [], draft, getReadiness }, helpers) {
|
|
46
53
|
const { icon, link, badge } = helpers;
|
|
47
|
-
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)});
|
|
48
55
|
const state = await lifecycleState(root, selected.id, { jobs, selected, getReadiness });
|
|
49
56
|
const stage = stages.some(([id]) => id === params.stage) ? params.stage : 'shape';
|
|
50
57
|
const base = { change: selected.id, view: 'studio', stage, q: params.q, created: params.created, pane: params.pane === 'conversation' ? 'conversation' : 'document' };
|
|
@@ -53,45 +60,75 @@ export async function renderStudio({ root, selected, jobs, agent, params = {}, c
|
|
|
53
60
|
const option = state.actions[name];
|
|
54
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>`;
|
|
55
62
|
};
|
|
56
|
-
let canvas = '', toolbar = '', footer = '';
|
|
63
|
+
let canvas = '', toolbar = '', footer = '', selectedPlan = '', followComplete = false, planningReview = '';
|
|
57
64
|
if (stage === 'shape') {
|
|
58
65
|
const versions = await planVersions(root, selected, jobs);
|
|
59
66
|
const current = versions.current?.documents || {}, previous = versions.previous?.documents || {};
|
|
60
67
|
const documents = [...new Set([...Object.keys(current), ...Object.keys(previous)])];
|
|
61
|
-
const
|
|
68
|
+
const following = state.jobs.find(job => job.id === params.follow && ['plan-next', 'propose'].includes(job.action) && job.status === 'completed');
|
|
69
|
+
const followedFile = following && versions.current?.hash === following.planAfter?.hash ? documents.find(name => !(name in previous)) || documents.find(name => current[name] !== previous[name]) : '';
|
|
70
|
+
followComplete = Boolean(following && state.readiness);
|
|
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]);
|
|
72
|
+
selectedPlan = file || '';
|
|
62
73
|
const changes = versions.previous ? planChanges(previous, current) : [];
|
|
63
74
|
const newSpec = params.created === '1';
|
|
64
75
|
const compare = !newSpec && params.compare === '1' && Boolean(versions.previous);
|
|
65
|
-
|
|
66
|
-
const artifactTabs = state.readiness?.artifacts.filter(item => item.status !== 'skipped').map(item => {
|
|
76
|
+
const files = state.readiness?.artifacts.filter(item => item.status !== 'skipped').map(item => {
|
|
67
77
|
const paths = state.readiness.artifactPaths[item.id]?.existingOutputPaths || [];
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
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>`;
|
|
71
|
-
}).join('') || '';
|
|
72
|
-
const files = artifactTabs ? artifactDocuments : documents;
|
|
78
|
+
return documents.filter(name => paths.some(output => output.replaceAll('\\', '/').endsWith('/' + name)));
|
|
79
|
+
}).find(files => files.includes(file)) || documents;
|
|
73
80
|
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.';
|
|
74
81
|
const fileLabel = name => name.replace(/^specs\//, '').replace(/\/spec\.md$/, '').replace(/\.md$/, '');
|
|
75
82
|
const displayLabel = name => fileLabel(name).replace(/[-_]/g, ' ').replace(/^./, letter => letter.toUpperCase());
|
|
76
83
|
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>` : '';
|
|
77
|
-
toolbar =
|
|
84
|
+
toolbar = filePicker ? `<div class="studio-artifact-navigation">${filePicker}</div>` : '';
|
|
78
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>` : '';
|
|
79
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>' : '';
|
|
80
|
-
const
|
|
81
|
-
|
|
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);
|
|
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>`;
|
|
82
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);
|
|
83
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
|
+
|
|
84
103
|
|
|
85
104
|
} else {
|
|
86
105
|
const validation = state.validation;
|
|
87
106
|
const report = state.jobs.find(job => job.action === 'verify' && job.status === 'completed');
|
|
88
|
-
|
|
89
|
-
|
|
107
|
+
const reportReady = Boolean(report && hasVerificationReport(report.result));
|
|
108
|
+
const branch = await changeBranch(root, selected.id);
|
|
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) : '';
|
|
116
|
+
const planStatus = selected.archived || state.readiness?.planningComplete ? 'Complete' : 'In progress';
|
|
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');
|
|
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>` : ''}` : '';
|
|
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>` : '';
|
|
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>`;
|
|
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>';
|
|
125
|
+
|
|
90
126
|
}
|
|
91
127
|
if (state.pending) footer = '<button type="button" class="button" data-studio-conversation-jump>View progress</button>';
|
|
92
128
|
const latestQuestion = state.pending?.status === 'awaiting-input';
|
|
93
129
|
const revisionAction = selected.files.length ? 'revise-plan' : 'plan-next';
|
|
94
|
-
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
|
|
95
|
-
|
|
96
|
-
|
|
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>` };
|
|
97
134
|
}
|
package/src/updates.mjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { execFile, spawn } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { readJSON, runtime, exists, withLock } from './files.mjs';
|
|
7
|
+
import { listJobs, pendingStatuses } from './jobs.mjs';
|
|
8
|
+
|
|
9
|
+
const exec = promisify(execFile);
|
|
10
|
+
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
|
|
11
|
+
const metadata = JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url), 'utf8'));
|
|
12
|
+
const release = value => /^\d+\.\d+\.\d+$/.test(value || '');
|
|
13
|
+
const newer = (a, b) => {
|
|
14
|
+
const left = a.split('.').map(Number), right = b.split('.').map(Number);
|
|
15
|
+
for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] > right[i];
|
|
16
|
+
return false;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
async function npmEntry() {
|
|
20
|
+
const candidates = [process.env.npm_execpath, path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js')];
|
|
21
|
+
for (const directory of (process.env.PATH || '').split(path.delimiter).filter(Boolean)) {
|
|
22
|
+
candidates.push(path.join(directory, 'node_modules/npm/bin/npm-cli.js'));
|
|
23
|
+
for (const name of ['npm', 'npm.cmd']) {
|
|
24
|
+
const resolved = await fs.realpath(path.join(directory, name)).catch(() => null);
|
|
25
|
+
if (resolved?.endsWith('npm-cli.js')) candidates.push(resolved);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
for (const file of candidates) if (file && await fs.stat(file).then(stat => stat.isFile(), () => false)) return file;
|
|
29
|
+
throw new Error('npm could not be found. Install Node.js with npm and retry.');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function checkForUpdate(root) {
|
|
33
|
+
const current = metadata.version;
|
|
34
|
+
try {
|
|
35
|
+
const { stdout } = await exec(process.execPath, [await npmEntry(), 'view', `${metadata.name}@latest`, 'version', '--json', '--fetch-retries=0', '--fetch-timeout=2500'], { cwd: root, timeout: 4000, maxBuffer: 4096, windowsHide: true });
|
|
36
|
+
const latest = JSON.parse(stdout);
|
|
37
|
+
if (!release(latest) || !release(current)) throw new Error('Invalid release version');
|
|
38
|
+
return { current, latest, available: newer(latest, current), development: await exists(path.join(packageRoot, '.git')) };
|
|
39
|
+
} catch { return { current, available: false, unavailable: true }; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function updateRuntime(root) {
|
|
43
|
+
if (await exists(path.join(packageRoot, '.git'))) throw new Error('This runtime is a local source checkout. Update the checkout yourself, then run node bin/spequi.mjs init; published updates will not replace local code.');
|
|
44
|
+
return withLock(runtime(root, 'update.lock'), async () => {
|
|
45
|
+
const connection = await readJSON(runtime(root, 'server.json'));
|
|
46
|
+
if (connection?.pid) {
|
|
47
|
+
let live = false;
|
|
48
|
+
try { process.kill(connection.pid, 0); live = true; } catch (error) { if (error.code === 'EPERM') live = true; }
|
|
49
|
+
if (live) throw new Error('Stop this project’s Spequi server before updating, then restart it and reload the Spequi skill. Requests and project state are retained.');
|
|
50
|
+
}
|
|
51
|
+
if ((await listJobs(root)).some(job => pendingStatuses.includes(job.status) && job.status !== 'queued')) throw new Error('Finish or resolve the active request before updating. Its saved state has been kept.');
|
|
52
|
+
for (const name of ['cli.mjs', 'server.mjs']) {
|
|
53
|
+
const content = await fs.readFile(runtime(root, name), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error; });
|
|
54
|
+
if (content && !content.startsWith('// Generated by spequi.')) throw new Error(`Custom .spequi/${name} was preserved. Reconcile it with the generated launcher before updating.`);
|
|
55
|
+
}
|
|
56
|
+
const shipped = await fs.readFile(new URL('../skills/spequi/SKILL.md', import.meta.url), 'utf8');
|
|
57
|
+
for (const relative of ['.agents/skills/spequi/SKILL.md', '.gigacode/skills/spequi/SKILL.md']) {
|
|
58
|
+
const content = await fs.readFile(path.join(root, relative), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error; });
|
|
59
|
+
if (content && content !== shipped) throw new Error(`Local changes in ${relative} were preserved. Use the project’s pinned runtime to update, or reconcile those changes first.`);
|
|
60
|
+
}
|
|
61
|
+
const wrappers = {
|
|
62
|
+
'.claude/commands/spequi.md': '---\nname: spequi\ndescription: Initialize and operate Spequi in the current agent session\n---\n\nRead and follow .agents/skills/spequi/SKILL.md. User arguments: $ARGUMENTS\n',
|
|
63
|
+
'.gigacode/commands/spequi.md': '---\ndescription: Initialize and operate Spequi in the current agent session\n---\n\nRead and follow .gigacode/skills/spequi/SKILL.md. User arguments: {{args}}\n'
|
|
64
|
+
};
|
|
65
|
+
for (const [relative, expected] of Object.entries(wrappers)) {
|
|
66
|
+
const content = await fs.readFile(path.join(root, relative), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error; });
|
|
67
|
+
if (content && content !== expected) throw new Error(`Custom ${relative} was preserved. Reconcile the command wrapper before updating.`);
|
|
68
|
+
}
|
|
69
|
+
const cli = await npmEntry();
|
|
70
|
+
const latest = await checkForUpdate(root);
|
|
71
|
+
if (latest.unavailable) throw new Error('Could not check the configured npm registry. Your current runtime is unchanged; retry when online or fix the project’s npm registry settings.');
|
|
72
|
+
if (!latest.available && newer(metadata.version, latest.latest)) throw new Error('The configured registry has an older release. Current runtime retained.');
|
|
73
|
+
await new Promise((resolve, reject) => {
|
|
74
|
+
const child = spawn(process.execPath, [cli, 'exec', '--yes', '--prefer-online', `--package=${metadata.name}@${latest.latest}`, '--', metadata.name, 'init', '--root', root], { cwd: root, stdio: 'inherit', shell: false });
|
|
75
|
+
child.once('error', reject);
|
|
76
|
+
child.once('exit', code => code === 0 ? resolve() : reject(new Error('Update failed. Project requests and data were retained; retry the update.')));
|
|
77
|
+
});
|
|
78
|
+
const config = await readJSON(runtime(root, 'config.json'));
|
|
79
|
+
if (config?.viewerVersion !== latest.latest) throw new Error('Could not confirm the new runtime. Re-run initialization with the intended package version.');
|
|
80
|
+
return { version: config.viewerVersion, next: 'Start node .spequi/server.mjs, reload the Spequi skill from disk, and reattach the agent. Existing requests are retained.' };
|
|
81
|
+
}, { waitMs: 0 });
|
|
82
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// A heading or generic completion message is not a verification report.
|
|
2
|
+
export function hasVerificationReport(value) {
|
|
3
|
+
if (typeof value !== 'string') return false;
|
|
4
|
+
const body = value.split(/\r?\n/).filter(line => !/^\s*(?:#{1,6}\s|[-=_]{3,}\s*$)/.test(line)).join('\n').trim();
|
|
5
|
+
return body.length >= 40 && !/^(?:verify|verification)(?:\s+report)?\s*:[^\n]*$|^(?:completed?|done|success)[.!]?$/i.test(body);
|
|
6
|
+
}
|
package/src/views.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isPlanningDraft } from './drafts.mjs';
|
|
2
|
+
import { exists, readJSON, runtime } from './files.mjs';
|
|
1
3
|
import path from 'node:path';
|
|
2
4
|
import { randomUUID } from 'node:crypto';
|
|
3
5
|
import { renderReviewMarkdown, renderReviewSource, renderDocumentDiscussion } from './document-view.mjs';
|
|
@@ -33,6 +35,11 @@ const paths = {
|
|
|
33
35
|
spark: '<path d="m12 3 2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5Z"/>',
|
|
34
36
|
plus: '<path d="M12 5v14M5 12h14"/>',
|
|
35
37
|
download: '<path d="M12 3v12m-4-4 4 4 4-4M4 16v5h16v-5"/>',
|
|
38
|
+
attachment: '<path d="m21 11-8 8a6 6 0 0 1-8.5-8.5l9-9a4 4 0 0 1 5.7 5.7l-9 9a2 2 0 0 1-2.9-2.9l8-8"/>',
|
|
39
|
+
image: '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m3 17 5-5 4 4 3-3 6 6"/>',
|
|
40
|
+
settings: '<path d="M12.00 4.20 13.35 4.32 15.42 2.60 17.00 3.34 17.01 6.02 17.98 6.99 18.75 8.10 19.33 9.33 21.85 10.26 22.00 12.00 19.68 13.35 19.33 14.67 18.75 15.90 17.98 17.01 18.43 19.66 17.00 20.66 14.67 19.33 13.35 19.68 12.00 19.80 10.65 19.68 8.58 21.40 7.00 20.66 6.99 17.98 6.02 17.01 5.25 15.90 4.67 14.67 2.15 13.74 2.00 12.00 4.32 10.65 4.67 9.33 5.25 8.10 6.02 6.99 5.57 4.34 7.00 3.34 9.33 4.67 10.65 4.32Z"/><circle cx="12" cy="12" r="3"/>',
|
|
41
|
+
privacy: '<path d="M12 3 3 7v5c0 5 9 9 9 9s9-4 9-9V7l-9-4Z"/><path d="m8 12 3 3 5-6"/>',
|
|
42
|
+
bell: '<path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9"/><path d="M10 21h4"/>',
|
|
36
43
|
book: '<path d="M12 5C9 2 4 3 2 4v16c3-2 7-2 10 0 3-2 7-2 10 0V4c-2-1-7-2-10 1Zm0 0v15"/>',
|
|
37
44
|
};
|
|
38
45
|
export const icon = name => `<svg aria-hidden="true" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">${paths[name] || paths.file}</svg>`;
|
|
@@ -40,8 +47,8 @@ function url(params) { const query = new URLSearchParams(Object.entries(params).
|
|
|
40
47
|
function link(label, params, className = '', extra = '') { return `<a href="${e(url(params))}" hx-get="${e(url(params))}" hx-target="#workspace" hx-swap="outerHTML" hx-push-url="true" class="${className}" ${extra}>${label}</a>`; }
|
|
41
48
|
function badge(label, type = '') { return `<span class="badge ${type}">${e(label)}</span>`; }
|
|
42
49
|
function progressBar(progress) { return `<span class="progress-track" aria-label="${progress.done} of ${progress.total} tasks complete"><span style="width:${progress.total ? Math.round(progress.done / progress.total * 100) : 0}%"></span></span>`; }
|
|
43
|
-
export function shell(content, data, csrf, params = {}) {
|
|
44
|
-
return `<!doctype html><html lang="en" data-theme="enterprise"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="csrf-token" content="${csrf}"><title>${e(data.name)} · Spequi</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><script src="/assets/app.js" defer></script><script src="/assets/review.js" defer></script><script src="/assets/workflow.js" defer></script><script src="/assets/studio.js" defer></script><script src="/assets/session.js" defer></script><script src="/assets/requests.js" defer></script><link rel="stylesheet" href="/assets/fonts.css"><link rel="stylesheet" href="/assets/app.css"><link rel="stylesheet" href="/assets/diff.css"><link rel="stylesheet" href="/assets/review.css"><link rel="stylesheet" href="/assets/studio.css"></head><body><a class="skip-link" href="#document">Skip to document</a><header class="topbar"><div class="topbar-start"><div class="brand">${icon('layers')}<span>Spequi</span><span class="local-pill">LOCAL</span></div></div><div class="topbar-end"><a class="tool-docs-link" href="/docs" target="_blank" rel="noopener noreferrer" aria-label="Spequi docs and landing page (opens in a new tab)" title="Docs and getting started">${icon('book')}<span>Docs</span></a><button type="button" class="button requests-toggle" data-requests-toggle aria-controls="requests-panel" aria-expanded="false"><span class="requests-icon" aria-hidden="true">${icon('clock')}<span class="requests-attention" data-request-count hidden></span></span>Requests</button><button type="button" id="agent-indicator" class="session-indicator" data-session-toggle aria-expanded="false" aria-controls="agent-connections"><span class="session-agent-icon" aria-hidden="true">${icon('agent')}<i></i></span><span data-session-label>Checking agent</span><span class="session-chevron" aria-hidden="true">${icon('chevron')}</span></button><button type="button" class="session-mcp-button" aria-label="MCP connections" data-session-toggle aria-expanded="false" aria-controls="mcp-connections">${icon('plug')}<span id="mcp-count">MCPs</span></button><button type="button" id="theme-toggle" class="theme-toggle" aria-label="Switch to dark mode" title="Switch to dark mode"><span class="theme-icon-dark">${icon('moon')}</span><span class="theme-icon-light">${icon('sun')}</span></button></div></header><aside id="agent-connections" class="session-panel agent-panel" aria-label="Agent connection" hidden><header><h2>Agent</h2><button type="button" class="icon-button" data-session-close aria-label="Close agent details">${icon('close')}</button></header><div class="agent-summary"><span class="agent-avatar" aria-hidden="true">${icon('agent')}</span><div class="agent-identity"><strong id="session-agent-name">Spequi Agent</strong><p id="session-agent-caption">Checking connection</p></div><span id="session-state" class="agent-state-badge">Checking</span></div><dl class="agent-facts"><div><dt>Last seen</dt><dd><time id="session-last-seen">Not yet</time></dd></div><div><dt>Queue</dt><dd id="session-queue-state">Checking</dd></div></dl><section class="agent-current" data-session-current aria-label="Current request" hidden><div><strong id="session-current-change"></strong><span id="session-current-state"></span></div><p id="session-current-hint"></p></section><section id="session-recovery" class="agent-guidance" aria-label="Next step" hidden><p id="session-recovery-message"></p><p id="session-recovery-detail" hidden></p></section><footer class="agent-panel-actions"><button type="button" class="button" data-session-refresh>Refresh status</button><button type="button" class="text-button" data-session-open-requests>View requests ${icon('arrow')}</button></footer><p data-session-check-result role="status" aria-live="polite" aria-atomic="true"></p></aside><aside id="mcp-connections" class="session-panel mcp-panel" aria-label="MCP connections" hidden><header><div><h2>MCP connections</h2><span id="mcp-panel-state" class="mcp-panel-state">Not reported</span></div><button type="button" class="icon-button" data-session-close aria-label="Close MCP connections">${icon('close')}</button></header><div class="mcp-panel-body"><p id="mcp-report-summary" hidden></p><div class="mcp-empty" data-mcp-empty><span class="mcp-empty-icon" aria-hidden="true">${icon('plug')}</span><div><h3 id="mcp-empty-title">Waiting for connection details</h3><p id="mcp-empty-description">Your agent hasn’t shared its MCP connections yet.</p></div></div><ul id="session-mcps"></ul></div><footer class="mcp-panel-footer"><button type="button" class="text-button" data-mcp-refresh>Refresh status</button><time id="mcp-report-date">Not reported yet</time></footer></aside><aside id="requests-panel" class="requests-panel" aria-label="Requests" hidden><header><h2>Requests</h2><div class="requests-tools"><select data-request-filter aria-label="Filter requests"><option value="inbox" selected>Inbox</option><option value="all">All history</option><option value="active">Active history</option><option value="completed">Completed</option><option value="failed">Failed</option><option value="cancelled">Cancelled</option></select><button type="button" class="icon-button" data-requests-close aria-label="Close requests">${icon('close')}</button></div></header><div data-requests-feedback role="status" aria-live="polite"></div><div data-request-list></div><footer hidden><span data-request-pagination></span><nav data-request-pages aria-label="Request pages" hidden><button class="icon-button" type="button" data-request-page="previous" aria-label="Previous page" title="Previous page">${icon('chevron')}</button><button class="icon-button" type="button" data-request-page="next" aria-label="Next page" title="Next page">${icon('chevron')}</button></nav></footer></aside><dialog id="request-delete-dialog" aria-labelledby="request-delete-title" aria-describedby="request-delete-description request-delete-retention"><form method="dialog"><h2 id="request-delete-title">Delete this request?</h2><p id="request-delete-description">Remove it from request history.</p><label><input type="checkbox" name="reviewData" checked> Also delete its saved preview and that preview’s comments and exports</label><p id="request-delete-retention">Project files, OpenSpec documents, and applied-file backups are kept.</p><div class="dialog-actions"><button value="cancel" class="button">Keep request</button><button value="confirm" class="button danger-solid">Delete request</button></div></form></dialog><dialog id="draft-delete-dialog" aria-labelledby="draft-delete-title" aria-describedby="draft-delete-description draft-delete-retention"><form method="dialog"><h2 id="draft-delete-title">Delete this draft?</h2><p id="draft-delete-description">The saved idea will be removed.</p><label data-delete-plan-choice><input type="checkbox" name="deletePlan"> Also delete the planning files generated from this draft</label><p id="draft-delete-retention">Cancel active requests before deleting. Application source files are kept.</p><div class="dialog-actions"><button value="cancel" class="button">Keep draft</button><button value="confirm" class="button danger-solid">Delete draft</button></div></form></dialog>${content}<div id="toast" role="status" aria-live="polite" aria-atomic="true"></div><dialog id="apply-dialog"><form method="dialog"><h2>Apply this preview?</h2><p>The reviewed files will be written to your project. If any affected file has changed since the preview, the whole operation will stop.</p><div class="dialog-actions"><button value="cancel">Keep reviewing</button><button value="confirm" class="button primary">Apply reviewed files</button></div></form></dialog></body></html>`;
|
|
50
|
+
export function shell(content, data, csrf, params = {}, consent = {}) {
|
|
51
|
+
return `<!doctype html><html lang="en" data-theme="enterprise"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="csrf-token" content="${csrf}"><title>${e(data.name)} · Spequi</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><script src="/assets/app.js" defer></script><script src="/assets/review.js" defer></script><script src="/assets/workflow.js" defer></script><script src="/assets/studio.js" defer></script><script src="/assets/session.js" defer></script><script src="/assets/requests.js" defer></script><link rel="stylesheet" href="/assets/fonts.css"><link rel="stylesheet" href="/assets/app.css"><link rel="stylesheet" href="/assets/diff.css"><link rel="stylesheet" href="/assets/review.css"><link rel="stylesheet" href="/assets/studio.css"></head><body><a class="skip-link" href="#document">Skip to document</a><header class="topbar"><div class="topbar-start"><div class="brand">${icon('layers')}<span>Spequi</span><span class="local-pill">LOCAL</span></div></div><div class="topbar-end"><button type="button" class="button requests-toggle" data-requests-toggle aria-controls="requests-panel" aria-expanded="false"><span class="requests-icon" aria-hidden="true">${icon('clock')}<span class="requests-attention" data-request-count hidden></span></span><span>Requests</span><span class="request-answer-marker" data-request-answer hidden></span></button><button type="button" id="agent-indicator" class="session-indicator" data-session-toggle aria-expanded="false" aria-controls="agent-connections"><span class="session-agent-icon" aria-hidden="true">${icon('agent')}<i></i></span><span data-session-label>Checking agent</span><span class="session-chevron" aria-hidden="true">${icon('chevron')}</span></button><button type="button" class="session-mcp-button" aria-label="MCP connections" data-session-toggle aria-expanded="false" aria-controls="mcp-connections">${icon('plug')}<span id="mcp-count">MCPs</span></button><button type="button" class="icon-button settings-toggle" data-privacy-toggle popovertarget="workspace-settings" aria-controls="workspace-settings" aria-expanded="false" aria-label="Settings" title="Settings">${icon('settings')}<span class="privacy-attention-dot" data-privacy-dot ${consent.choice ? 'hidden' : ''} aria-hidden="true"></span></button></div></header><aside id="agent-connections" class="session-panel agent-panel" aria-label="Agent connection" hidden><header><h2>Agent</h2><button type="button" class="icon-button" data-session-close aria-label="Close agent details">${icon('close')}</button></header><div class="agent-summary"><span class="agent-avatar" aria-hidden="true">${icon('agent')}</span><div class="agent-identity"><strong id="session-agent-name">Spequi Agent</strong><p id="session-agent-caption">Checking connection</p></div><span id="session-state" class="agent-state-badge">Checking</span></div><dl class="agent-facts"><div><dt>Last seen</dt><dd><time id="session-last-seen">Not yet</time></dd></div><div><dt>Queue</dt><dd id="session-queue-state">Checking</dd></div></dl><section class="agent-current" data-session-current aria-label="Current request" hidden><div><strong id="session-current-change"></strong><span id="session-current-state"></span></div><p id="session-current-hint"></p></section><section id="session-question" aria-label="Agent question" hidden></section><form id="session-cancel-request" data-lifecycle-form method="post" hidden><p>Cancelling frees the queue and keeps existing files.</p><button type="submit" class="button">Cancel request</button><div data-lifecycle-feedback role="status" aria-live="polite"></div></form><section id="session-recovery" class="agent-guidance" aria-label="Next step" hidden><p id="session-recovery-message"></p><p id="session-recovery-detail" hidden></p></section><footer class="agent-panel-actions"><button type="button" class="button" data-session-refresh>Refresh status</button><button type="button" class="text-button" data-session-open-requests>${icon('clock')} View requests</button></footer><p data-session-check-result role="status" aria-live="polite" aria-atomic="true"></p></aside><aside id="mcp-connections" class="session-panel mcp-panel" aria-label="MCP connections" hidden><header><div><h2>MCP connections</h2><span id="mcp-panel-state" class="mcp-panel-state">Not reported</span></div><button type="button" class="icon-button" data-session-close aria-label="Close MCP connections">${icon('close')}</button></header><div class="mcp-panel-body"><p id="mcp-report-summary" hidden></p><div class="mcp-empty" data-mcp-empty><span class="mcp-empty-icon" aria-hidden="true">${icon('plug')}</span><div><h3 id="mcp-empty-title">Waiting for connection details</h3><p id="mcp-empty-description">Your agent hasn’t shared its MCP connections yet.</p></div></div><ul id="session-mcps"></ul></div><footer class="mcp-panel-footer"><button type="button" class="text-button" data-mcp-refresh>Refresh status</button><time id="mcp-report-date">Not reported yet</time></footer></aside><aside id="workspace-settings" class="settings-panel" popover="auto" data-dropdown-panel data-dropdown-width="360" aria-labelledby="settings-title"><header><h2 id="settings-title">Settings</h2><button type="button" class="icon-button" popovertarget="workspace-settings" popovertargetaction="hide" aria-label="Close settings">${icon('close')}</button></header><a class="settings-link" data-dropdown-choice href="/docs" target="_blank" rel="noopener noreferrer" aria-label="Spequi docs and landing page (opens in a new tab)" title="Docs and getting started">${icon('book')}<span>Docs</span></a><button type="button" id="theme-toggle" class="theme-toggle settings-theme" aria-label="Switch to dark mode" title="Switch to dark mode"><span class="theme-icon-dark">${icon('moon')}</span><span class="theme-icon-light">${icon('sun')}</span><span data-theme-label>Dark mode</span></button><details id="settings-notifications" name="workspace-settings"><summary>${icon('bell')}Notifications${icon('chevron')}</summary><section id="notification-settings" class="notification-settings"><p>Get a desktop notification when your plan or file diff is ready, your agent needs an answer, or a request fails while you’re in another tab.</p><p class="notification-note">Keep this workspace open to receive alerts.</p><p data-notification-message role="status" aria-live="polite"></p><button type="button" class="button primary" data-enable-notifications hidden>Enable notifications</button></section></details><details id="settings-sharing" name="workspace-settings"><summary>${icon('privacy')}Usage sharing${icon('chevron')}</summary><section id="privacy-settings" class="privacy-settings" data-consent-pending="${!consent.choice}"><p>Choose what Spequi may send. Nothing is shared until you choose; your choice applies only to <strong>${e(data.name)}</strong>.</p><form data-consent-form><fieldset><legend>Usage data preference</legend>${[['off', 'Do not share', 'No usage or failure events leave this project.'], ['anonymous', 'Share usage without names', 'Includes action counts, CLI name and a random machine identifier.'], ['identity', 'Share usage with names', 'Also includes this project’s folder name and Git user.name.']].map(([value, label, description]) => `<label><input type="radio" name="choice" value="${value}" required ${consent.choice === value ? 'checked' : ''}><span><strong>${label}</strong><small>${description}</small></span></label>`).join('')}</fieldset><p class="privacy-note">Source code, prompts, comments and credentials are never included. Change this preference here at any time.</p><div data-consent-feedback role="status" aria-live="polite"></div><button type="submit" class="button primary">Save preference</button></form></section></details><p class="settings-update" data-update-note>Running Spequi. Update checks run on startup.</p></aside><aside id="requests-panel" class="requests-panel" aria-label="Requests" hidden><header><h2>Requests</h2><div class="requests-tools"><select data-request-filter aria-label="Filter requests"><option value="inbox" selected>Inbox</option><option value="all">All history</option><option value="active">Active history</option><option value="completed">Completed</option><option value="failed">Failed</option><option value="cancelled">Cancelled</option></select><button type="button" class="icon-button" data-requests-close aria-label="Close requests">${icon('close')}</button></div></header><div data-requests-feedback role="status" aria-live="polite"></div><div data-request-list></div><footer hidden><span data-request-pagination></span><nav data-request-pages aria-label="Request pages" hidden><button class="icon-button" type="button" data-request-page="previous" aria-label="Previous page" title="Previous page">${icon('chevron')}</button><button class="icon-button" type="button" data-request-page="next" aria-label="Next page" title="Next page">${icon('chevron')}</button></nav></footer></aside><dialog id="request-delete-dialog" aria-labelledby="request-delete-title" aria-describedby="request-delete-description request-delete-retention"><form method="dialog"><h2 id="request-delete-title">Delete this request?</h2><p id="request-delete-description">Remove it from request history.</p><label><input type="checkbox" name="reviewData" checked> Also delete its saved preview and that preview’s comments and exports</label><p id="request-delete-retention">Project files, OpenSpec documents, and applied-file backups are kept.</p><div class="dialog-actions"><button value="cancel" class="button">Keep request</button><button value="confirm" class="button danger-solid">Delete request</button></div></form></dialog><dialog id="draft-delete-dialog" aria-labelledby="draft-delete-title" aria-describedby="draft-delete-description draft-delete-retention"><form method="dialog"><h2 id="draft-delete-title">Delete this draft?</h2><p id="draft-delete-description">The saved idea will be removed.</p><label data-delete-plan-choice><input type="checkbox" name="deletePlan"> Also delete the planning files generated from this draft</label><p id="draft-delete-retention">Cancel active requests before deleting. Application source files are kept.</p><div class="dialog-actions"><button value="cancel" class="button">Keep draft</button><button value="confirm" class="button danger-solid">Delete draft</button></div></form></dialog>${content}<div id="toast" role="status" aria-live="polite" aria-atomic="true"></div><dialog id="plan-push-dialog" aria-labelledby="plan-push-title" aria-describedby="plan-push-note"><form method="dialog"><h2 id="plan-push-title">Push spec files?</h2><dl class="plan-push-facts"><div><dt>Branch</dt><dd data-push-branch></dd></div><div data-push-message-row><dt>Commit message</dt><dd data-push-message></dd></div></dl><details data-push-files-section><summary data-push-file-count></summary><ul data-push-files></ul></details><p id="plan-push-note">Earlier commits on this branch will be pushed too. Unrelated staged edits are kept.</p><div class="dialog-actions"><button value="cancel" class="button" autofocus>Keep editing</button><button value="confirm" class="button primary" data-push-confirm>Commit & push</button></div></form></dialog><dialog id="apply-dialog"><form method="dialog"><h2>Apply this preview?</h2><p>The reviewed files will be written to your project. If any affected file has changed since the preview, the whole operation will stop.</p><div class="dialog-actions"><button value="cancel">Keep reviewing</button><button value="confirm" class="button primary">Apply reviewed files</button></div></form></dialog></body></html>`;
|
|
45
52
|
}
|
|
46
53
|
export async function workspace({ root, data, params, jobs, agent, drafts = [], getReadiness, compact = true }) {
|
|
47
54
|
if (params.view === 'studio' && params.stage === 'implement') params = { ...params, view: 'preview', stage: undefined, pane: undefined };
|
|
@@ -61,9 +68,20 @@ export async function workspace({ root, data, params, jobs, agent, drafts = [],
|
|
|
61
68
|
const currentDraft = draft || { id: typeof params.draft === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(params.draft) ? params.draft : randomUUID() };
|
|
62
69
|
const draftChanges = new Set(drafts.filter(item => item.creationId).map(item => item.change));
|
|
63
70
|
const archivedTarget = params.change && data.changes.filter(change => change.archived && /^\d{4}-\d{2}-\d{2}-/.test(change.id) && change.id.slice(11) === params.change).sort((a, b) => b.id.localeCompare(a.id))[0];
|
|
64
|
-
const selected = params.view === 'studio' && params.new === '1' ? null : data.changes.find(change => change.id === params.change) || archivedTarget || (!params.doc ? data.changes.find(change => !change.archived) || data.changes[0] : null);
|
|
65
|
-
|
|
66
|
-
|
|
71
|
+
const selected = params.doc && data.specs.some(spec => spec.file === params.doc) ? null : params.view === 'studio' && params.new === '1' ? null : data.changes.find(change => change.id === params.change) || archivedTarget || (!params.doc ? data.changes.find(change => !change.archived) || data.changes[0] : null);
|
|
72
|
+
let doc = params.doc && data.files.includes(params.doc) ? params.doc : selected?.files[0] || data.specs[0]?.file;
|
|
73
|
+
let view = ['rendered', 'source', 'specs', 'preview', 'studio', 'workflow'].includes(params.view) ? params.view : 'rendered';
|
|
74
|
+
const building = await isPlanningDraft(root, selected, drafts);
|
|
75
|
+
if (building && !['studio', 'workflow'].includes(view)) {
|
|
76
|
+
view = 'studio';
|
|
77
|
+
params = { ...params, view, stage: 'shape', plan: selected.files.includes(doc) ? doc.split('/').slice(3).join('/') : params.plan };
|
|
78
|
+
}
|
|
79
|
+
if (selected && view === 'studio' && !building) {
|
|
80
|
+
const requested = `openspec/changes/${selected.id}/${params.plan || ''}`;
|
|
81
|
+
doc = selected.files.includes(requested) ? requested : doc;
|
|
82
|
+
view = 'rendered';
|
|
83
|
+
params = { ...params, view, stage: undefined, plan: undefined, created: undefined, creation: undefined, pane: undefined };
|
|
84
|
+
}
|
|
67
85
|
const studioLayout = ['studio', 'workflow'].includes(view);
|
|
68
86
|
const state = changeState(selected);
|
|
69
87
|
const preview = await getPreviewContext(root, params, jobs, selected);
|
|
@@ -90,14 +108,17 @@ export async function workspace({ root, data, params, jobs, agent, drafts = [],
|
|
|
90
108
|
}).join('');
|
|
91
109
|
const sidebar = `<aside class="sidebar" id="navigation"><button class="navigation-close" id="navigation-close" aria-controls="navigation" aria-label="Close project navigation">${icon('close')}</button><div class="project-select">${icon('folder')}<div><strong>${e(data.name)}</strong><small>OpenSpec workspace</small></div>${icon('chevron')}</div>${link(`${icon('plus')}New spec`, { view: 'studio', new: '1' }, 'button new-change-link')}<form class="search" action="/" hx-get="/" hx-target="#workspace" hx-swap="outerHTML" hx-push-url="true">${icon('search')}<input type="hidden" name="change" value="${e(selected?.id || '')}"><input type="hidden" name="view" value="${e(view)}"><input type="hidden" name="doc" value="${e(doc || '')}">${searchContext}<input id="search" hx-include="closest form" name="q" placeholder="Find a change…" aria-label="Find a change" value="${e(params.q || '')}" hx-trigger="input changed delay:300ms, search" hx-get="/" hx-target="#workspace" hx-swap="outerHTML" hx-push-url="true"><kbd>⌘ K</kbd></form><nav aria-label="Project navigation"><div data-project-changes><section data-drafts-navigation ${drafts.length ? '' : 'hidden'}><div class="nav-heading"><span>Drafts</span><span data-draft-count>${drafts.length}</span></div><div data-draft-links>${draftLinks}</div></section><div class="nav-heading"><span>Active changes</span><span>${active.length}</span></div>${active.map(navChange).join('') || '<p class="nav-empty">No matching active changes</p>'}</div>${previewNavigation}<div class="nav-heading separated"><span>Specifications</span><span>${data.specs.length}</span></div>${data.specs.filter(spec => !query || spec.id.toLowerCase().includes(query)).map(spec => link(`${icon('book')}<span>${e(spec.id)}</span>`, { doc: spec.file }, `spec-link ${doc === spec.file ? 'selected' : ''}`)).join('') || '<p class="nav-empty">Specs arrive when a change is synced or archived.</p>'}<div class="nav-heading separated"><span>Archive</span><span>${archived.length}</span></div>${archived.map(navChange).join('') || '<p class="nav-empty">Completed changes live here.</p>'}</nav><footer class="sidebar-community" aria-label="Community and credits"><a class="sidebar-community-invite" href="https://github.com/rahulnjs/spequi" target="_blank" rel="noopener noreferrer">${icon('code')}<span><strong>Make Spequi better</strong><small>Contribute on GitHub</small></span>${icon('arrow')}</a><div class="sidebar-community-credit"><a href="https://github.com/rahulnjs/spequi/issues/new" target="_blank" rel="noopener noreferrer">Share feedback</a><span>Built by <a href="https://github.com/rahulnjs" target="_blank" rel="noopener noreferrer">@rahulnjs</a></span></div></footer></aside>`;
|
|
92
110
|
const title = view === 'studio' && !selected ? 'New spec' : selected?.title || (doc ? doc.split('/').slice(2, -1).join(' / ') : 'Your specs, in focus.');
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
let content = '', artifact = null, studioHeader = '';
|
|
111
|
+
let navigation = '';
|
|
112
|
+
let content = '', artifact = null, studioHeader = '', followedArtifact = false;
|
|
96
113
|
if (studioLayout) {
|
|
97
114
|
const studio = await renderStudio({ root, selected, jobs, agent, params, changes: data.changes, draft: currentDraft, getReadiness }, { icon, link, badge });
|
|
98
|
-
content = studio.content; studioHeader = studio.header;
|
|
115
|
+
content = studio.content; studioHeader = studio.header; followedArtifact = studio.followComplete;
|
|
116
|
+
if (studio.plan) params = { ...params, plan: studio.plan, ...(studio.followComplete ? { follow: undefined, created: undefined } : {}) };
|
|
117
|
+
}
|
|
118
|
+
else if (view === 'preview') {
|
|
119
|
+
content = await renderPreview({ root, params, selected, agent, context: preview, compact: compact && Boolean(selected) }, { icon, link, badge, empty });
|
|
120
|
+
if (preview.followComplete) { params = { ...params, follow: undefined }; followedArtifact = true; }
|
|
99
121
|
}
|
|
100
|
-
else if (view === 'preview') content = await renderPreview({ root, params, selected, agent, context: preview, compact: compact && Boolean(selected) }, { icon, link, badge, empty });
|
|
101
122
|
else if (view === 'specs' && selected) {
|
|
102
123
|
const diffs = await requirementDiffs(root, selected);
|
|
103
124
|
content = `<div class="review-intro"><h2>Specification changes</h2><p>Current requirements alongside this change’s authored deltas. These describe behavior; code previews show the implementation.</p></div>${diffs.length ? diffs.map(diff => `<section class="spec-diff"><div class="diff-file-head">${icon('book')}<strong>${e(diff.capability)}</strong><span class="operation-badges">${diff.operations.map(op => badge(`${op.count} ${op.operation.toLowerCase()}`, op.operation === 'ADDED' ? 'success' : '')).join('')}</span></div><div class="comparison"><section><h3>Current specification</h3><div class="prose small">${diff.current ? markdown(diff.current) : '<p class="muted">New capability. No current specification.</p>'}</div></section><section><h3>Proposed delta</h3><div class="prose small">${markdown(diff.proposed)}</div></section></div></section>`).join('') : empty('No spec deltas yet', 'Propose a change with capability requirements to review its specification changes.', 'book')}`;
|
|
@@ -107,14 +128,31 @@ export async function workspace({ root, data, params, jobs, agent, drafts = [],
|
|
|
107
128
|
const notes = artifact ? (await listComments(root, artifactReviewID(selected.id))).filter(comment => comment.kind === 'artifact' && comment.file === doc) : [];
|
|
108
129
|
const documentBody = artifact ? `<div data-document-content data-source-hash="${artifact.sourceHash}">${view === 'source' ? renderReviewSource(source, { sourceHash: artifact.sourceHash, comments: notes, icon }) : `<article class="prose document-prose">${renderReviewMarkdown(source, { sourceHash: artifact.sourceHash, comments: notes, icon })}</article>`}</div>${renderDocumentDiscussion({ artifact, change: selected, comments: notes }, { icon })}` : view === 'source' ? `<pre class="source-view"><code>${e(source)}</code></pre>` : `<article class="prose">${markdown(source)}</article>`;
|
|
109
130
|
content = `<div class="file-toolbar"><span>${icon('file')}<span>${e(doc.replace('openspec/', ''))}</span></span><div class="segmented" aria-label="Document view">${link('Preview', { ...base, view: 'rendered' }, view === 'rendered' ? 'active' : '')}${link('Source', { ...base, view: 'source' }, view === 'source' ? 'active' : '')}<a href="/api/raw?file=${encodeURIComponent(doc)}" download="${e(path.basename(doc))}" title="Download Markdown" aria-label="Download Markdown">${icon('download')}</a></div></div>${documentBody}`;
|
|
110
|
-
} else
|
|
131
|
+
} else {
|
|
132
|
+
const configured = (await readJSON(runtime(root, 'config.json')))?.openspecDir || 'openspec';
|
|
133
|
+
const initialized = await exists(path.resolve(root, configured));
|
|
134
|
+
content = empty(initialized ? 'Create your first plan' : 'Set up your specification workspace', initialized ? 'OpenSpec is ready. Describe the change you want to make, then review its proposal, requirements, design and tasks before generating code.' : 'Initialize OpenSpec in this project, then create a plan with your coding agent. Your documents will appear here as you work.', 'layers', initialized ? link(`${icon('plus')}New spec`, { view: 'studio', new: '1' }, 'button primary') : '<p class="empty-setup-command"><code>openspec init</code></p><p class="muted">Run this in your project’s CLI, then refresh this page.</p>');
|
|
135
|
+
}
|
|
136
|
+
if (selected) {
|
|
137
|
+
const groups = ['proposal', 'specs', 'design', 'tasks'].map(name => ({ name, files: selected.files.filter(file => name === 'specs' ? file.includes('/specs/') : !file.includes('/specs/') && path.basename(file) === `${name}.md`) }));
|
|
138
|
+
const known = new Set(groups.flatMap(group => group.files));
|
|
139
|
+
for (const file of selected.files.filter(file => !known.has(file))) groups.push({ name: path.basename(file, '.md'), files: [file] });
|
|
140
|
+
const prefix = `openspec/changes/${selected.archived ? 'archive/' : ''}${selected.id}/`;
|
|
141
|
+
navigation = `<div class="document-tabs" role="navigation" aria-label="Change documents">${groups.map(group => {
|
|
142
|
+
const file = group.files[0], planning = building;
|
|
143
|
+
const active = planning ? view === 'studio' && group.files.some(file => file.slice(prefix.length) === params.plan) : group.files.includes(doc) && !['preview', 'specs', 'workflow'].includes(view) || group.name === 'specs' && view === 'specs';
|
|
144
|
+
const label = `${icon(group.name === 'tasks' ? 'check' : 'file')}<span>${e(group.name)}</span>${group.name === 'tasks' && file ? `<span class="tab-count">${selected.progress.done}/${selected.progress.total}</span>` : ''}`;
|
|
145
|
+
return file ? link(label, planning ? { change: selected.id, view: 'studio', stage: 'shape', plan: file.slice(prefix.length) } : { change: selected.id, doc: file, view: 'rendered' }, `document-tab ${active ? 'active' : ''}`, active ? 'aria-current="page"' : '') : `<span class="document-tab" aria-disabled="true" title="Create this planning artifact to open it">${label}</span>`;
|
|
146
|
+
}).join('')}${building ? `<span class="document-tab" aria-disabled="true" title="Finish planning before reviewing file changes">${icon('git')}<span>Files</span></span>` : link(`${icon('git')}<span>Files</span><span class="tab-count">${preview.result?.changes.length || 0}</span>`, { change: selected.id, view: 'preview', job: preview.job?.id }, `document-tab ${view === 'preview' ? 'active' : ''}`, 'data-files-tab hx-sync="#workspace:replace"')}${link('Workflow', { change: selected.id, view: 'workflow' }, `document-tab ${view === 'workflow' ? 'active' : ''}`, view === 'workflow' ? 'aria-current="page"' : '')}</div>`;
|
|
147
|
+
}
|
|
111
148
|
const lastPreview = preview.job;
|
|
112
149
|
const reviewContext = compact && selected && !studioLayout ? await renderReviewContext({ root, params, selected, context: preview, jobs, agent, artifact, showImpact: view === 'preview' }, { icon, link, badge }) : '';
|
|
113
|
-
const panel = studioLayout ? '' : `<aside class="inspector" id="review-details" aria-label="Review details">${reviewContext}<section class="inspector-section"><div class="section-title"><h2>Change details</h2>${icon('git')}</div><dl><div><dt>Status</dt><dd>${badge(state.label, state.type)}</dd></div><div><dt>Schema</dt><dd>spec-driven</dd></div><div><dt>Artifacts</dt><dd>${selected?.files.length || 0} files</dd></div></dl>${selected?.progress.total ? `<div class="task-progress"><span>Implementation<strong>${selected.progress.done}<span class="muted"> / ${selected.progress.total}</span></strong></span>${progressBar(selected.progress)}</div>` : ''}</section></aside>`;
|
|
150
|
+
const panel = studioLayout || !selected ? '' : `<aside class="inspector" id="review-details" aria-label="Review details">${reviewContext}<section class="inspector-section"><div class="section-title"><h2>Change details</h2>${icon('git')}</div><dl><div><dt>Status</dt><dd>${badge(state.label, state.type)}</dd></div><div><dt>Schema</dt><dd>spec-driven</dd></div><div><dt>Artifacts</dt><dd>${selected?.files.length || 0} files</dd></div></dl>${selected?.progress.total ? `<div class="task-progress"><span>Implementation<strong>${selected.progress.done}<span class="muted"> / ${selected.progress.total}</span></strong></span>${progressBar(selected.progress)}</div>` : ''}</section></aside>`;
|
|
114
151
|
|
|
115
|
-
const compactBreadcrumbs = `<div class="breadcrumbs"><button class="icon-button mobile-menu" id="navigation-toggle" aria-controls="navigation" aria-label="Toggle project navigation" aria-expanded="false">${icon('menu')}</button><span>${e(data.name)}</span>${icon('chevron')}<span>${selected?.archived ? 'Archive' : 'Changes'}</span>${icon('chevron')}<strong role="heading" aria-level="1" title="${e(title)}">${e(selected?.id || (view === 'studio' ? 'New spec' : ''))}</strong></div>`;
|
|
116
|
-
const compactHeader = `<header class="compact-change-header">${compactBreadcrumbs}${view === 'studio' ? studioHeader :
|
|
152
|
+
const compactBreadcrumbs = `<div class="breadcrumbs"><button class="icon-button mobile-menu" id="navigation-toggle" aria-controls="navigation" aria-label="Toggle project navigation" aria-expanded="false">${icon('menu')}</button><span>${e(data.name)}</span>${icon('chevron')}<span>${selected?.archived ? 'Archive' : 'Changes'}</span>${icon('chevron')}<strong role="heading" aria-level="1" title="${e(title)}">${e(selected?.id || creation?.change || (view === 'studio' ? 'New spec' : ''))}</strong></div>`;
|
|
153
|
+
const compactHeader = `<header class="compact-change-header">${compactBreadcrumbs}${navigation}${studioLayout || view === 'studio' ? studioHeader : ''}${studioLayout || !selected ? '' : `<button type="button" class="details-icon-toggle" id="toggle-review-details" data-review-details aria-controls="review-details" aria-expanded="true" aria-label="Hide review details" title="Hide review details">${icon('panel')}</button>`}</header>`;
|
|
154
|
+
const simpleHeader = `<div class="breadcrumbs"><button class="icon-button mobile-menu" id="navigation-toggle" aria-controls="navigation" aria-label="Toggle project navigation" aria-expanded="false">${icon('menu')}</button><span>${e(data.name)}</span>${icon('chevron')}<span>Specifications</span>${doc ? `${icon('chevron')}<strong>${e(data.specs.find(spec => spec.file === doc)?.id || path.basename(doc, '.md'))}</strong>` : ''}</div>`;
|
|
117
155
|
const refreshURL = url({ ...params, draft: view === 'studio' && !selected ? currentDraft.id : params.draft, change: selected?.id, view, doc: ['preview', 'studio', 'workflow'].includes(view) ? undefined : doc, job: view === 'preview' ? preview.job?.id : params.job, file: view === 'preview' ? preview.file?.file : params.file });
|
|
118
|
-
return `<div id="workspace" class="workspace ${studioLayout ? 'studio-workspace' : ''} ${view === 'preview' ? 'diff-workspace' : ''} ${compact && selected ? `compact-workspace${studioLayout ? '' : ' review-details-open'}` : ''}" data-creation-complete="${Boolean(created)}" data-request-state="${e(JSON.stringify(jobs.filter(job => !job.hiddenAt && (selected && jobMatchesChange(job, selected) || job.id === params.creation)).map(job => [job.id, job.status])))}" data-change="${e(selected?.id || '')}" data-workspace-mode="${
|
|
156
|
+
return `<div id="workspace" class="workspace ${studioLayout ? 'studio-workspace' : ''} ${view === 'preview' ? 'diff-workspace' : ''} ${compact && selected ? `compact-workspace${studioLayout ? '' : ' review-details-open'}` : !selected && !studioLayout ? 'specification-workspace' : ''}" data-creation-complete="${Boolean(created)}" data-artifact-follow-complete="${Boolean(followedArtifact)}" data-request-state="${e(JSON.stringify(jobs.filter(job => !job.hiddenAt && (selected && jobMatchesChange(job, selected) || job.id === params.creation)).map(job => [job.id, job.status])))}" data-change="${e(selected?.id || '')}" data-workspace-mode="${building ? 'build' : 'review'}" data-view="${e(view)}" ${compact ? `data-refresh-url="${e(refreshURL)}"` : ''}>${sidebar}<main class="main" id="document" tabindex="-1">${!selected && view !== 'studio' ? simpleHeader : (compact && selected) || view === 'studio' ? compactHeader : `<div class="breadcrumbs"><button class="icon-button mobile-menu" id="navigation-toggle" aria-controls="navigation" aria-label="Toggle project navigation" aria-expanded="false">${icon('menu')}</button><span>${e(data.name)}</span>${icon('chevron')}<span>${selected?.archived ? 'Archive' : selected ? 'Changes' : 'Specifications'}</span>${selected ? `${icon('chevron')}<strong>${e(selected.id)}</strong>` : ''}</div><div class="change-header"><div><div class="change-title-line"><h1>${e(title)}</h1>${badge(state.label, state.type)}</div><p>${selected ? e(selected.id) : 'A local workspace for intent, implementation, and review.'}</p></div><div class="header-actions">${view === 'preview' ? `<button type="button" class="button" id="toggle-review-details" data-review-details aria-expanded="false" aria-controls="review-details">${icon('layers')}Details</button>` : `${selected ? link(`${icon('git')} Spec changes`, { ...base, view: 'specs' }, `button ${view === 'specs' ? 'selected-button' : ''}`) : ''}${link(`${icon('git')} Files changed${lastPreview ? '<span class="new-dot"></span>' : ''}`, { ...base, view: 'preview', job: lastPreview?.id }, `button ${view === 'preview' ? 'selected-button' : ''}`)}`}</div></div>${navigation}`}<div class="reader ${view === 'preview' || view === 'specs' ? 'review-reader' : ''}">${content}</div><footer class="workspace-footer"><span>${icon('folder')} ${e(data.name)}<span class="footer-divider">/</span>openspec</span><span>${view === 'preview' ? 'Current files compared with an isolated implementation' : 'Markdown is the source of truth'}</span></footer></main>${panel}</div>`;
|
|
119
157
|
}
|
|
120
158
|
function empty(title, copy, symbol = 'code', extra = '') { return `<div class="empty-state">${icon(symbol)}<h2>${title}</h2><p>${copy}</p>${extra}</div>`; }
|