@oaksecurity/aitm 0.0.0-stage → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.env.example +11 -0
  2. package/CHANGELOG.md +100 -0
  3. package/LICENSE +21 -0
  4. package/README.md +229 -2
  5. package/SECURITY.md +49 -0
  6. package/SPEC.md +304 -0
  7. package/docs/api.md +332 -0
  8. package/docs/inputs-and-limits.md +78 -0
  9. package/docs/usage.md +351 -0
  10. package/examples/custody-architecture.md +27 -0
  11. package/package.json +67 -4
  12. package/src/api/server.js +591 -0
  13. package/src/api/web.js +38 -0
  14. package/src/application.js +32 -0
  15. package/src/assessments.js +37 -0
  16. package/src/assets/BDOGrotesk-Bold.ttf +0 -0
  17. package/src/assets/BDOGrotesk-Regular.ttf +0 -0
  18. package/src/assets/OFL.txt +93 -0
  19. package/src/assets/README.md +10 -0
  20. package/src/cli.js +224 -0
  21. package/src/client.js +88 -0
  22. package/src/config.js +105 -0
  23. package/src/doctor.js +128 -0
  24. package/src/engine/credentials.js +31 -0
  25. package/src/engine/download.js +135 -0
  26. package/src/engine/engine.js +783 -0
  27. package/src/engine/errors.js +23 -0
  28. package/src/engine/generation.js +121 -0
  29. package/src/engine/ingest.js +444 -0
  30. package/src/engine/pdf-layout.js +204 -0
  31. package/src/engine/pdf-report.js +573 -0
  32. package/src/engine/prompts.js +82 -0
  33. package/src/engine/providers.js +476 -0
  34. package/src/engine/references.js +112 -0
  35. package/src/engine/report.js +200 -0
  36. package/src/engine/schema.js +267 -0
  37. package/src/engine/store.js +115 -0
  38. package/src/engine/validate.js +397 -0
  39. package/src/engine/zip.js +70 -0
  40. package/src/index.js +5 -0
  41. package/src/source-input.js +32 -0
  42. package/src/token.js +59 -0
  43. package/src/tui/app.js +694 -0
  44. package/src/tui/editor.js +34 -0
  45. package/src/tui/file-picker.js +111 -0
  46. package/src/tui/logo.js +8 -0
  47. package/src/tui/progress.js +90 -0
  48. package/src/tui/report-reader.js +105 -0
  49. package/src/tui/select.js +63 -0
  50. package/src/tui/workbench.js +377 -0
  51. package/src/version.js +5 -0
  52. package/src/web/app.js +729 -0
  53. package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
  54. package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
  55. package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
  56. package/src/web/assets/README.md +5 -0
  57. package/src/web/assets/aitm-mark.svg +12 -0
  58. package/src/web/assets/oak-white.svg +166 -0
  59. package/src/web/html.js +32 -0
  60. package/src/web/index.html +26 -0
  61. package/src/web/markdown.js +48 -0
  62. package/src/web/styles.css +1450 -0
  63. package/src/web/views.js +254 -0
@@ -0,0 +1,254 @@
1
+ import { esc, human, button, pill, empty, list, field, select, pretty } from './html.js';
2
+ import { markdown } from './markdown.js';
3
+
4
+ export const activeRun = (p) =>
5
+ p?.runs.findLast((run) => ['queued', 'running'].includes(run.status));
6
+ export const title = (eyebrow, name, description = '') =>
7
+ `<div class="view-heading"><div class="eyebrow">${esc(eyebrow)}</div><h1>${esc(name)}</h1>${description ? `<p class="lede">${esc(description)}</p>` : ''}</div>`;
8
+ const data = (p, phase) => p.artifacts[phase]?.data;
9
+ const rank = (p) =>
10
+ [...(data(p, 'stride')?.threats || [])].sort(
11
+ (a, b) => b.likelihood * b.impact - a.likelihood * a.impact || a.id.localeCompare(b.id),
12
+ );
13
+ const phaseStatus = (p, id) => p.artifacts[id]?.status || 'pending';
14
+ const runButtons = (p) =>
15
+ activeRun(p)
16
+ ? button('cancel-run', 'Cancel run', '', 'danger')
17
+ : button('run-review', 'Run with review gates', p.sources.length ? '' : 'disabled');
18
+ export function sidebar(s) {
19
+ const p = s.project;
20
+ return `<div class="brand"><img src="/ui/assets/aitm-mark.svg" alt="AiTM node graph"><div>AiTM<span>AI Threat Modeller</span></div><span class="version">v2</span></div>
21
+ <div class="project-picker"><label for="project-picker">PROJECT</label><select id="project-picker" aria-label="Assessment"><option value="">Choose a project</option>${s.projects.map((item) => `<option value="${item.id}" ${p?.id === item.id ? 'selected' : ''}>${esc(item.name)}</option>`).join('')}</select><div class="row">${button('new-project', '+ New project', '', 'side')}${button('open-project', 'Open project', '', 'side')}</div></div>
22
+ <nav aria-label="TRACE phases">${
23
+ p
24
+ ? `<a href="#/projects/${p.id}/overview" ${s.view === 'overview' ? 'aria-current="page"' : ''}><span class="nav-number">◇</span>Overview</a>${s.phases
25
+ .filter((ph) => ph.id !== 'ingest')
26
+ .map(
27
+ (ph) =>
28
+ `<a href="#/projects/${p.id}/${ph.id}" ${s.view === ph.id ? 'aria-current="page"' : ''}><span class="nav-number">${ph.id === 'scope' ? '0·1' : s.meta.phases.findIndex((item) => item.id === ph.id)}</span><span>${esc({ scope: 'Sources & Scope', model: 'TRACE Model', stride: 'STRIDE', trees: 'Attack Trees', coordination: 'Coordination', report: 'Report' }[ph.id])}</span><span class="phase-dot ${phaseStatus(p, ph.id)}" title="${phaseStatus(p, ph.id)}" aria-label="${phaseStatus(p, ph.id)}"></span></a>`,
29
+ )
30
+ .join('')}`
31
+ : '<p class="side-hint">Create a project, then add its sources.</p>'
32
+ }</nav>
33
+ <div class="sidebar-bottom">${button('import', 'Import project JSON', '', 'side')}${p ? `<a href="#/projects/${p.id}/log" ${s.view === 'log' ? 'aria-current="page"' : ''}>↳ Run history</a>` : ''}<a href="${p ? `#/projects/${p.id}/settings` : '#/settings'}" ${s.view === 'settings' ? 'aria-current="page"' : ''}>⚙ Settings & models</a><div class="key-status"><span class="phase-dot ${s.providers[p?.config.provider || 'openai']?.configured ? 'approved' : ''}"></span>${esc(p?.config.provider || 'openai')} · ${s.providers[p?.config.provider || 'openai']?.configured ? 'key configured' : 'key needed'}</div><div class="byline">by <img src="/ui/assets/oak-white.svg" alt="Oak Security"></div></div>`;
34
+ }
35
+ export function topbar(s) {
36
+ return `${button('menu', '☰', 'aria-label="Toggle navigation" aria-expanded="false"', 'mobile-menu')}<div class="breadcrumb">Workspace <span>/</span> ${esc(s.project?.name || 'New assessment')}</div><div class="row">${s.project ? pill(activeRun(s.project) ? 'Running' : s.project.artifacts.report ? 'Report ready' : 'Draft', activeRun(s.project) ? 'gold' : '') + button('run-full', 'Run full pipeline', `${activeRun(s.project) || !s.project.sources.length ? 'disabled' : ''} title="Autorun every TRACE step, including the top three attack trees, without review pauses"`, 'primary') + button('export-project', 'Export project') : pill('Local workbench')}</div>`;
37
+ }
38
+ export function progress(s) {
39
+ const p = s.project,
40
+ run = activeRun(p) || p?.runs.at(-1),
41
+ event = s.event || run?.events.at(-1);
42
+ if (s.busy)
43
+ return `<span class="spinner"></span><strong>${esc(s.busy)}</strong><span class="muted">Keep this server running.</span>`;
44
+ if (!run)
45
+ return `<span class="status-dot"></span><strong>Ready</strong><span class="muted">Sequential TRACE · source → model → threats → report</span>`;
46
+ const running = ['queued', 'running'].includes(run.status);
47
+ const completed = s.phases.filter((ph) => p.artifacts[ph.id]).length;
48
+ const request = event?.batch
49
+ ? event
50
+ : s.request || run.events.findLast((e) => e.type === 'request' && e.phase === run.phase);
51
+ const lastRequest = run.events.findLast((e) => e.type === 'request' && e.phase === run.phase);
52
+ const batch = running && request?.batches ? `Batch ${request.batch}/${request.batches} · ` : '';
53
+ const provider = request?.model
54
+ ? `${request.provider}/${request.model}`
55
+ : lastRequest?.model
56
+ ? `${lastRequest.provider}/${lastRequest.model}`
57
+ : '';
58
+ const quietSeconds = event?.at
59
+ ? Math.max(0, Math.floor((Date.now() - Date.parse(event.at)) / 1000))
60
+ : 0;
61
+ const activity = running
62
+ ? `${batch}${event?.message || 'Starting TRACE…'}${quietSeconds >= 15 ? ` · waiting ${quietSeconds}s since last update` : ''}`
63
+ : run.error
64
+ ? `Paused at ${run.phase === 'ingest' ? 'source classification' : human(run.phase)}. Open Details, then Run full pipeline to retry.`
65
+ : `${completed}/${s.phases.length} phases available`;
66
+ const since = run.startedAt
67
+ ? Math.max(
68
+ 0,
69
+ Math.floor(
70
+ ((running ? Date.now() : Date.parse(run.finishedAt || run.startedAt)) -
71
+ Date.parse(run.startedAt)) /
72
+ 1000,
73
+ ),
74
+ )
75
+ : 0;
76
+ return `${running ? '<span class="spinner"></span>' : '<span class="status-dot"></span>'}<strong>${esc(running ? (run.phase === 'ingest' ? `Classifying${request?.batches ? ` · ${request.batch}/${request.batches}` : ' sources'}` : human(event?.phase || run.phase || 'Starting')) : human(run.status))}</strong><span class="activity-message" title="${esc(activity)}">${esc(activity)}</span><span class="activity-metrics" title="${esc(provider)}">${since}s · ${event?.characters ? `${event.characters.toLocaleString()} chars` : `${(run.usage.inputTokens + run.usage.outputTokens).toLocaleString()} tokens`}${running && provider ? ` · ${esc(provider)}` : ''}</span>${running ? button('cancel-run', 'Cancel', '', 'small') : ''}${p ? `<a href="#/projects/${p.id}/log">Details</a>` : ''}`;
77
+ }
78
+ export function welcome(s) {
79
+ return `${title('TRACE / YOUR WORKSPACE', 'Projects', 'Keep each assessment and its sources together. Create a project or reopen a saved one. Nothing is imported automatically.')}<div class="card pipeline-card"><div><h2>Start a new assessment</h2><p>Add public URLs, architecture documents, specifications and zipped repositories to the same project.</p></div><div class="stack">${button('new-project', 'New project', '', 'primary')}${button('open-project', 'Open project')}${button('import', 'Import project JSON')}</div></div><h2>Saved projects <span class="count">${s.projects.length}</span></h2>${s.projects.length ? `<div class="card flush"><ol class="phase-list">${s.projects.map((p) => `<li><a href="#/projects/${p.id}/overview"><strong>${esc(p.name)}</strong>${pill(`${p.sources} sources`)}<span class="hint">${esc(p.lastRun || 'Not run')}</span><span>→</span></a></li>`).join('')}</ol></div>` : empty('No saved projects yet', 'Create a named project, then import its sources.')}<div class="notice">Source content is sent to your selected AI provider only when you run an assessment. Results remain drafts until reviewed.</div>`;
80
+ }
81
+ export function sourceForm(replacing = false) {
82
+ return `<p class="muted">${replacing ? 'Choose one replacement for this source. Other sources stay in the project.' : 'Import several documents or ZIP repositories, or paste one public URL or local path per line.'} Changes invalidate dependent analysis.</p><label class="check"><input type="checkbox" id="run-after-import"> Run full pipeline after import</label><div class="card"><h3>Documents & repository ZIPs</h3><p class="hint">PDF, DOCX, source/text files and ZIP archives. ZIP contents follow the same source filters as local repositories.</p><label class="btn primary file-button">Choose documents or ZIPs<input type="file" ${replacing ? '' : 'multiple'} data-upload="sources" aria-label="Choose source files"></label></div><form data-form="sources">${field('locations', 'Public URLs or local paths', '', { area: true, required: true })}<p class="hint">${replacing ? 'One explicit source.' : 'One source per line.'} Empty input never imports the current folder.</p><div class="row"><button class="btn primary">${replacing ? 'Replace source' : 'Import sources'}</button>${button('close-dialog', 'Cancel')}</div></form>`;
83
+ }
84
+ export function overview(s) {
85
+ const p = s.project,
86
+ model = data(p, 'model'),
87
+ ingest = data(p, 'ingest');
88
+ return `${title('ASSESSMENT / OVERVIEW', p.name, 'From source evidence to a model, ranked threats and a practical roadmap.')}<div class="card pipeline-card"><div><span class="eyebrow">ONE SEQUENTIAL FLOW</span><h2>Run the full TRACE pipeline</h2><p>Classify the source, model the system, rank STRIDE threats, build attack trees for the top three threats, and assemble the report.</p><p class="hint">Use Run full pipeline above to autorun every step without approval pauses. Outputs remain drafts. Completed steps are reused.</p></div><div class="stack">${!p.sources.length ? `<a class="btn primary" href="#/projects/${p.id}/scope">Add sources →</a>` : ''}${runButtons(p)}${p.artifacts.report ? `<a class="btn secondary" href="#/projects/${p.id}/report">Read report →</a>` : ''}</div></div>
89
+ <div class="stats">${[
90
+ ['Sources', p.sources.length, 'scope'],
91
+ ['Protected assets', model?.protectedAssets.length || 0, 'model'],
92
+ ['STRIDE threats', data(p, 'stride')?.threats.length || 0, 'stride'],
93
+ ['Attack trees', data(p, 'trees')?.trees.length || 0, 'trees'],
94
+ ]
95
+ .map(
96
+ ([label, value, view]) =>
97
+ `<a href="#/projects/${p.id}/${view}" class="stat"><span>${esc(label)}</span><strong>${value.toString().padStart(2, '0')}</strong><span class="stat-arrow">↗</span></a>`,
98
+ )
99
+ .join('')}</div>
100
+ <div class="grid-2"><section class="card"><h2>System profile</h2>${ingest ? `<div class="row">${pill(ingest.profile, 'gold')}${ingest.pillars.map((v) => pill(v)).join('')}</div><p>${esc(ingest.summary)}</p><p class="muted">${esc(ingest.rationale)}</p>` : '<p class="muted">The first analysis step will classify your source and identify its actors and boundaries.</p>'}</section><section class="card"><h2>Scope</h2><p class="preserve">${esc(p.scope) || 'No scope provided.'}</p><a href="#/projects/${p.id}/scope">Edit scope →</a></section></div>
101
+ <h2>Assessment progress</h2><div class="card flush"><ol class="phase-list">${s.phases.map((ph) => `<li><a href="#/projects/${p.id}/${ph.id === 'ingest' ? 'scope' : ph.id}"><span class="phase-index">${s.meta.phases.findIndex((v) => v.id === ph.id)}</span><strong>${esc(ph.title)}</strong>${pill(phaseStatus(p, ph.id), phaseStatus(p, ph.id) === 'approved' ? 'approved' : '')}<span>→</span></a></li>`).join('')}</ol></div><details class="maintenance"><summary>Assessment actions</summary><div class="row">${button('restart', 'Restart full pipeline', '', 'danger')}${button('delete', 'Delete assessment', '', 'danger')}</div></details>`;
102
+ }
103
+ export function gate(s, phase) {
104
+ const p = s.project,
105
+ artifact = p.artifacts[phase],
106
+ enabled = s.phases.some((p) => p.id === phase),
107
+ busy = activeRun(p),
108
+ requiresReview = s.meta.phases.find((p) => p.id === phase)?.gate;
109
+ if (!enabled)
110
+ return '<div class="notice">This optional phase is disabled. Enable it in Settings & models.</div>';
111
+ return `<div class="card review-bar"><div><strong>${artifact ? human(artifact.status) : 'Pending'}</strong><p class="hint">${artifact?.review ? `${artifact.review.reviewer ? `Reviewed by ${esc(artifact.review.reviewer)}` : 'Review approved'}${artifact.review.notes ? ` · ${esc(artifact.review.notes)}` : ''}` : requiresReview ? 'Review is explicit. Approving this step unlocks the next review gate.' : 'This step needs no review.'}</p></div><div class="row">${artifact && phase !== 'scope' ? button('edit-artifact', 'Edit draft', `data-phase="${phase}" ${busy ? 'disabled' : ''}`) : ''}${artifact && requiresReview ? button('approve', artifact.status === 'approved' ? 'Record review' : 'Approve review', `data-phase="${phase}" ${busy ? 'disabled' : ''}`) : ''}${phase !== 'scope' ? button('generate', artifact ? 'Regenerate' : 'Generate step', `data-phase="${phase}" ${busy ? 'disabled' : ''}`, 'primary') : ''}</div></div>${artifact?.reviewNotes?.length ? `<details class="notice warn"><summary>${artifact.reviewNotes.length} evidence review note(s)</summary>${list(artifact.reviewNotes.map((note) => `${note.claim}: ${note.note}`))}</details>` : ''}`;
112
+ }
113
+ export function sources(s) {
114
+ const p = s.project,
115
+ ingest = data(p, 'ingest');
116
+ return `${title('TRACE / PHASES 0–1', 'Sources & Scope', 'Set the boundaries and inspect the complete source snapshot used by the engine.')}<form class="card" data-form="scope" data-revision="${p.revision}">${field('name', 'Assessment name', p.name, { required: true })}${field('scope', 'Scope and boundaries', p.scope, { area: true })}<button class="btn primary" ${activeRun(p) ? 'disabled' : ''}>Save scope</button><span class="hint">Changing scope invalidates dependent analysis.</span></form>
117
+ <div class="spread"><h2>Source inventory</h2>${button('add-sources', '+ Add sources', activeRun(p) ? 'disabled' : '')}</div>${p.sources.map((source) => `<section class="card"><div class="spread"><div><h3>${esc(source.label)}</h3><p class="hint">${esc(source.kind)} · ${source.files.length} file(s) · ${source.files.reduce((sum, f) => sum + f.text.length, 0).toLocaleString()} characters</p></div><div class="row">${button('replace-source', 'Replace source', `data-source="${source.id}" ${activeRun(p) ? 'disabled' : ''}`)}${['local', 'url', 'git'].includes(source.kind) ? button('sync', 'Refresh snapshot', `data-source="${source.id}" ${activeRun(p) ? 'disabled' : ''}`) : ''}${button('remove-source', 'Remove', `data-source="${source.id}" ${activeRun(p) ? 'disabled' : ''}`, 'danger')}</div></div><p class="hint code">${esc(source.locator || source.label)}</p>${source.warnings?.length ? `<details class="notice warn"><summary>Source notes (${source.warnings.length})</summary>${list(source.warnings)}</details>` : ''}<details><summary>Browse ${source.files.length} evidence file(s)</summary><div class="file-list">${source.files.map((file) => button('evidence', `${esc(file.path)} <span>${file.text.split('\n').length} lines</span>`, `data-file="${esc(file.id)}"`, 'file-row')).join('')}</div></details></section>`).join('')}${!p.sources.length ? empty('Add your sources', 'Import public URLs, documents and ZIP repositories. Each source has its own saved snapshot.') : ''}<h2>Ingest & classify</h2>${ingest ? `<div class="card"><div class="row">${pill(ingest.profile, 'gold')}${ingest.pillars.map((v) => pill(v)).join('')}</div><p>${esc(ingest.summary)}</p><p>${esc(ingest.rationale)}</p><h3>Candidate objects</h3>${ingest.candidates.map((c) => `<p><strong>${esc(c.name)}</strong> · ${esc(c.description)}</p>${evidence(c)}`).join('')}<h3>Questions for source review</h3>${list(ingest.missingEvidence)}</div>` : empty('Ready to classify', 'Run the full pipeline or generate this step after reviewing the source inventory.')}${gate(s, 'ingest')}`;
118
+ }
119
+ export function evidence(item) {
120
+ return `<div class="evidence">${(item.evidence || []).map((e) => button('evidence', `↗ ${esc(e.fileId)}:${e.startLine}–${e.endLine}`, `data-file="${esc(e.fileId)}" data-line="${e.startLine}" data-end="${e.endLine}"`, 'citation')).join('')}${item.assumption ? `<p class="assumption"><strong>Assumption:</strong> ${esc(item.assumption)}</p>` : ''}</div>`;
121
+ }
122
+ const itemEdit = (phase, key, index) =>
123
+ button(
124
+ 'edit-item',
125
+ 'Edit details',
126
+ `data-phase="${phase}" data-key="${key}" data-index="${index}"`,
127
+ 'small',
128
+ );
129
+ export function model(s) {
130
+ const p = s.project,
131
+ model = data(p, 'model');
132
+ return `${title('TRACE / PHASE 2', 'Construct TRACE Model', 'Threat actors, roles, protected assets, critical invariants and the edges between them.')}${gate(s, 'model')}${model ? `<p class="lede">${esc(model.overview)}</p>${['threatActors', 'roles', 'protectedAssets', 'invariants', 'components', 'edges'].map((key) => `<section><h2>${key === 'invariants' ? 'Critical invariants' : human(key)} <span class="count">${model[key].length}</span></h2><div class="object-grid">${model[key].map((item, index) => `<article class="card object-card"><div class="spread">${pill(item.id)}${itemEdit('model', key, index)}</div><h3>${esc(item.name)}</h3><p>${esc(item.description)}</p>${key === 'edges' ? `<div class="edge">${esc(item.from)} <span>→</span> ${esc(item.to)}</div><p class="hint">${esc(item.kind)} · ${esc(item.boundary)}</p>` : ''}${evidence(item)}</article>`).join('') || '<p class="muted">None identified.</p>'}</div></section>`).join('')}<section class="card"><h2>Open questions</h2>${list(model.openQuestions)}</section>` : empty('Build the model', 'Classify your source first, then generate the TRACE model or run the full pipeline.')}`;
133
+ }
134
+ export function stride(s) {
135
+ const p = s.project,
136
+ d = data(p, 'stride'),
137
+ threats = rank(p);
138
+ return `${title('TRACE / PHASE 3', 'STRIDE Identification & Ranking', 'Explore threats in risk order. Every scenario connects back to model objects and source evidence.')}${gate(s, 'stride')}${
139
+ d
140
+ ? `<div class="card filter-row">${field('threat-search', 'Find a threat')}${select('threat-category', 'STRIDE category', ['All categories', ...new Set(threats.map((t) => t.category))], 'All categories')}</div><p class="hint">Ranked by likelihood × impact (1–25). Attack trees in a full run cover the top three threats.</p><div id="threats">${threats
141
+ .map(
142
+ (threat, index) =>
143
+ `<article class="card threat-card" data-threat="${esc(`${threat.id} ${threat.title} ${threat.scenario}`.toLowerCase())}" data-category="${esc(threat.category)}"><div class="spread"><div class="row">${pill(`#${index + 1}`)}${pill(threat.category)}${pill(`${threat.likelihood * threat.impact} / 25`, threat.likelihood * threat.impact >= 15 ? 'risk-high' : 'gold')}</div>${itemEdit(
144
+ 'stride',
145
+ 'threats',
146
+ d.threats.findIndex((t) => t.id === threat.id),
147
+ )}</div><h2>${esc(threat.title)}</h2><p>${esc(threat.scenario)}</p><p class="hint">${esc(threat.id)} · Likelihood ${threat.likelihood} × Impact ${threat.impact} · ${esc(threat.confidence)} confidence</p><p>${esc(threat.rationale)}</p><details><summary>Controls, mitigations & evidence</summary><div class="grid-2"><div><h3>Existing controls</h3>${list(threat.existingControls)}</div><div><h3>Mitigations</h3>${list(threat.mitigations)}</div></div><dl>${['feasibility', 'incentives', 'blastRadius', 'timeSensitivity', 'targetIds', 'actorIds', 'assetIds', 'invariantIds'].map((key) => `<dt>${human(key)}</dt><dd>${esc(Array.isArray(threat[key]) ? threat[key].join(', ') : threat[key])}</dd>`).join('')}</dl>${evidence(threat)}</details></article>`,
148
+ )
149
+ .join(
150
+ '',
151
+ )}</div><div id="no-threats" class="notice" hidden>No threats match these filters.</div><details class="card"><summary>Model coverage & open questions</summary>${d.coverage.map((row) => `<p><strong>${esc(row.objectId)}</strong> → ${esc(row.threatIds.join(', '))}<br>${esc(row.explanation)}</p>`).join('')}${list(d.openQuestions)}</details>`
152
+ : empty('Rank the threats', 'Generate STRIDE after constructing the TRACE model.')
153
+ }`;
154
+ }
155
+ export function trees(s) {
156
+ const p = s.project,
157
+ d = data(p, 'trees');
158
+ const branch = (nodes, parent = null, seen = new Set()) =>
159
+ `<ul>${nodes
160
+ .filter((n) => n.parentId === parent && !seen.has(n.id))
161
+ .map((node) => {
162
+ const visited = new Set([...seen, node.id]);
163
+ return `<li><div class="tree-node"><div class="row">${pill(node.operator, node.operator === 'AND' ? 'gold' : '')}<strong>${esc(node.label)}</strong>${node.speculative ? pill('Assumption') : ''}</div><details><summary>Prerequisites & mitigations</summary>${list(node.prerequisites)}<h4>Mitigations</h4>${list(node.mitigations)}${evidence(node)}</details></div>${branch(nodes, node.id, visited)}</li>`;
164
+ })
165
+ .join('')}</ul>`;
166
+ return `${title('TRACE / PHASE 4', 'Build Attack Trees', 'Understand the steps and conditions needed to realize the highest ranked threats.')}${gate(s, 'trees')}${d ? `${d.trees.map((tree) => `<section class="card"><div class="row">${pill(tree.threatId, 'gold')}<span class="hint">${esc(data(p, 'stride')?.threats.find((t) => t.id === tree.threatId)?.title)}</span></div><h2>${esc(tree.goal)}</h2><div class="tree">${branch(tree.nodes)}</div></section>`).join('')}<p class="hint">AND requires all child paths. OR requires one child path. LEAF is an individual action.</p>${d.omitted.length ? `<div class="card"><h3>Omitted threats</h3>${list(d.omitted.map((v) => (typeof v === 'string' ? v : pretty(v))))}</div>` : ''}` : empty('Trace the attack paths', 'A full pipeline builds trees for the top three STRIDE threats, or all threats when fewer than three exist.')}`;
167
+ }
168
+ export function coordination(s) {
169
+ const d = data(s.project, 'coordination');
170
+ return `${title('TRACE / PHASE 5', 'Collusion & Coordination', 'Examine shared dependencies, incentives and the coalitions that could cause harm.')}${gate(s, 'coordination')}${d ? `${d.scenarios.map((item, index) => `<article class="card"><div class="spread">${pill(item.id, 'gold')}${itemEdit('coordination', 'scenarios', index)}</div><h2>${esc(item.title)}</h2><dl>${['actorIds', 'assetIds', 'threshold', 'incentive', 'consequence'].map((key) => `<dt>${human(key)}</dt><dd>${esc(Array.isArray(item[key]) ? item[key].join(', ') : item[key])}</dd>`).join('')}</dl><div class="grid-2"><div><h3>Shared dependencies</h3>${list(item.sharedDependencies)}</div><div><h3>Mitigations</h3>${list(item.mitigations)}</div></div>${evidence(item)}</article>`).join('') || empty('No scenarios identified', 'Review the source and assumptions before concluding that coordination is irrelevant.')}<div class="card"><h3>Assumptions</h3>${list(d.assumptions)}<h3>Open questions</h3>${list(d.openQuestions)}</div>` : empty('Inspect coordination', 'This phase runs automatically when classification identifies coordinating actors. You can override this in Settings.')}`;
171
+ }
172
+ export function report(s) {
173
+ const p = s.project;
174
+ return `${title('TRACE / PHASE 6', 'Roadmap & Report', 'Read the complete Markdown report, review it, or choose an export.')}${gate(s, 'report')}${p.artifacts.report ? `<div class="report-tools card"><div class="row">${button('report-preview', 'Read report', `aria-pressed="${!s.rawReport}"`)}${button('report-raw', 'Markdown source', `aria-pressed="${Boolean(s.rawReport)}"`)}</div><div class="row"><a class="btn secondary" href="/v1/projects/${p.id}/report" download>Download Markdown</a><a class="btn secondary" href="/v1/projects/${p.id}/report?format=pdf" download>Download PDF</a></div></div>${s.report == null ? '<p class="loading">Loading the complete report…</p>' : s.rawReport ? `<pre class="card raw-report">${esc(s.report)}</pre>` : renderReport(s.report)}<p class="hint">Assessment stored in <code>${esc(s.health.dataDir)}/${p.id}.json</code>. Exports are saved to your browser's download location.</p>` : empty('Your report will appear here', 'Run the full pipeline to assemble the roadmap and report from the preceding TRACE phases.')}`;
175
+ }
176
+ function renderReport(text) {
177
+ const rendered = markdown(text);
178
+ return `<div class="report-layout"><details class="report-contents" open><summary>IN THIS REPORT</summary><nav aria-label="Report sections">${rendered.headings
179
+ .filter((h) => h.level === 2)
180
+ .map((h) => `<a href="#${h.id}" data-section="${h.id}">${esc(h.title)}</a>`)
181
+ .join(
182
+ '',
183
+ )}</nav></details><article class="report-paper markdown">${rendered.html}</article></div>`;
184
+ }
185
+ export function settings(s) {
186
+ const p = s.project,
187
+ selected = s.settingsProvider || p?.config.provider || 'openai',
188
+ status = s.providers[selected];
189
+ const config = p?.config || {
190
+ ...status,
191
+ provider: selected,
192
+ effort: 'medium',
193
+ trees: true,
194
+ treeLimit: 3,
195
+ coordination: 'auto',
196
+ };
197
+ const catalog = s.catalogs[selected];
198
+ const models = catalog?.models || [{ id: status.fastModel }, { id: status.deepModel }];
199
+ const modelOptions = (current) =>
200
+ models.some((m) => m.id === current) ? models : [{ id: current }, ...models];
201
+ const sameProvider = selected === config.provider;
202
+ const fast = sameProvider ? config.fastModel : status.fastModel,
203
+ deep = sameProvider ? config.deepModel : status.deepModel;
204
+ const providerName = (id) => (id === 'openai' ? 'OpenAI' : 'Anthropic');
205
+ const noProject =
206
+ '<div class="card"><h2>Models</h2><p class="hint">Models are set for each assessment. A new assessment uses the provider that has a key (OpenAI first). Open an assessment to select other models.</p></div>';
207
+ const modelsForm = () =>
208
+ `<form data-form="models" data-provider="${selected}" data-revision="${p.revision}" class="card"><div class="spread"><h2>Models</h2>${button('refresh-models', 'Refresh list', `data-provider="${selected}"`)}</div>${sameProvider ? '' : `<p class="notice warn">Not saved. This assessment uses ${providerName(config.provider)} until you select <strong>Save assessment settings</strong>.</p>`}<p id="catalog-notice" class="hint">${esc(catalog?.notice || (catalog ? 'Compatible account models.' : 'Loading account models… Defaults are available.'))}</p><div class="grid-2">${select('fastModel', 'Fast model', modelOptions(fast), fast)}${select('deepModel', 'Deep model', modelOptions(deep), deep)}</div><p class="hint">Fast: classification, TRACE model, trees and report. Deep: STRIDE and coordination.</p>${select('effort', 'Reasoning effort', ['low', 'medium', 'high'], config.effort)}<h2>Optional phases</h2><div class="grid-2">${select(
209
+ 'trees',
210
+ 'Attack trees',
211
+ [
212
+ { id: 'true', name: 'Enabled' },
213
+ { id: 'false', name: 'Disabled' },
214
+ ],
215
+ String(config.trees),
216
+ )}${select(
217
+ 'treeLimit',
218
+ 'Number of trees (review runs)',
219
+ Array.from({ length: 10 }, (_, i) => String(i + 1)),
220
+ String(config.treeLimit),
221
+ )}${select(
222
+ 'coordination',
223
+ 'Coordination',
224
+ [
225
+ { id: 'auto', name: 'Automatic from classification' },
226
+ { id: 'on', name: 'Always run' },
227
+ { id: 'off', name: 'Disabled' },
228
+ ],
229
+ config.coordination,
230
+ )}</div><p class="hint">A full pipeline always includes attack trees for the top three threats. Saving changed model settings invalidates generated analysis; API key changes alone do not.</p><button class="btn primary" ${activeRun(p) ? 'disabled' : ''}>Save assessment settings</button></form>`;
231
+ return `${title('CONFIGURATION', 'Settings & Models', 'Manage provider credentials and choose the models for this assessment.')}<div class="card">${select(
232
+ 'settings-provider',
233
+ 'AI provider',
234
+ [
235
+ { id: 'openai', name: 'OpenAI' },
236
+ { id: 'anthropic', name: 'Anthropic' },
237
+ ],
238
+ selected,
239
+ )}</div>
240
+ <form data-form="credentials" data-provider="${selected}" class="card"><div class="spread"><h2>${selected === 'openai' ? 'OpenAI' : 'Anthropic'} API key</h2>${pill(status.configured ? 'Key configured' : 'Key needed', status.configured ? 'gold' : '')}</div><p class="hint" data-key-source>Current source: ${esc(status.keySource)}. A saved replacement takes precedence over environment settings.</p>${field('apiKey', 'New API key', '', { type: 'password' })}${selected === 'anthropic' ? field('workspaceId', 'Workspace ID (optional; blank keeps current)') : ''}<div class="row"><button class="btn primary">Save key</button>${button('test-provider', 'Test connection', `data-provider="${selected}"`)}</div><p class="hint">${s.health.keyFile ? `Keys are stored privately in <code>${esc(s.health.keyFile)}</code> (mode 600).` : 'Keys are kept in this server session; persistent credential storage was not configured by its host.'} Existing keys are never shown.</p></form>
241
+ ${p ? modelsForm() : noProject}<div class="notice">AI analysis sends the accepted source text to the selected provider. Results remain drafts until you record a review.</div>`;
242
+ }
243
+ export function log(s) {
244
+ const runs = [...s.project.runs].reverse();
245
+ return `${title('ASSESSMENT', 'Run History', 'Durable progress, provider usage and errors. Closing a browser tab leaves the engine running.')}${runs.map((run, index) => `<details class="card" ${index === 0 ? 'open' : ''}><summary>${pill(human(run.status), run.status === 'failed' ? 'risk-high' : '')} ${esc(run.startedAt || run.createdAt)} · ${esc(run.mode)}</summary>${run.error ? `<p class="notice warn">${esc(run.error)}</p>` : ''}<p class="hint code">${esc(run.id)} · ${run.usage.inputTokens} input / ${run.usage.outputTokens} output tokens</p><div class="event-log">${run.events.map((event) => `<div><time>${esc(event.at.slice(11, 19))}</time><span>${esc(event.phase || '')}</span><strong>${esc(human(event.type))}</strong><span>${esc(event.message)}</span></div>`).join('')}</div></details>`).join('') || empty('No runs yet', 'Start from Overview to run the full pipeline or walk through the review gates.')}`;
246
+ }
247
+ export const view = (s) => {
248
+ if (!s.project) return s.view === 'settings' ? settings(s) : welcome(s);
249
+ return (
250
+ { overview, scope: sources, model, stride, trees, coordination, report, settings, log }[
251
+ s.view
252
+ ] || overview
253
+ )(s);
254
+ };