Status line for which .nendo files are open, and a band showing the planner's Now lane and the full gate's progress bar

<img src="docs/assets/brand/nendo.png" alt="Nendo" width="420">
Malleable software in a single file. One portable SQLite file starts empty and is shaped — by people and by coding agents — into a working application: schema, data, forms, boards, record pages and revision history. No generated project. No build step. No regeneration when you want a change.
Nendo (粘土) is Japanese for clay.
1.0, for one person's use. Nendo 1.0 promises that a file it opens keeps opening, with its data intact, in every later 1.x. It is still a research project built and used by one person: an unsigned per-user Windows x64 install built from source, with no download, no updates and no support. Read State before you rely on anything here.
thomasrohde.github.io/nendo — the concept, how it works, how to use it, the honest status, and guides written for people outside this repository. It does not render docs/.
The installed host always provides Nendo Studio, a high-quality database explorer and editor. Custom surfaces add focused experiences on top, but never become the only route to the data — if a surface breaks, the data is still there, and still editable.
Create empty file
→ add or import schema and data
→ work in the default Studio table
→ ask an agent to create or reshape a form, board or record page
→ review the semantic diff
→ accept, observe, and compensate where the operation supports it
Agents connect over a local MCP interface. They never get SQL, a database path or filesystem access — only typed semantic operations. Their changes are validated on a physical clone and previewed as a readable diff; accepting replays the exact validated operations against your file. Nothing an agent gets wrong can reach your data before you say yes.
The core loop works end to end, delivered as a local unsigned per-user Windows x64 install. Four reference applications falsify the hypothesis from different shapes — Idea Garden, Decision Log, the Axiom Register and Nendo Station — and the last two were built from an empty file through the MCP interface alone.
Version 1.0.0 promises one thing beyond that: a file Nendo 1.0 opens normally opens normally in every later 1.x, with its records, fields, screens and packages intact (ADR-0012). It is not a public release.
Public distribution, signing, ARM64, cloud sync and cross-platform support are not qualified, and the independent human evaluation has not been run. The roadmap states each gap plainly.
Windows x64 only. Nendo.Engine is net10.0 and builds anywhere, but the Desktop host is WinUI 3 with WebView2. The Engine is Nendo's own core, not a supported .NET library: its public types change with the app.
| Tool | Version | Install |
|---|---|---|
| .NET SDK | Pinned in global.json | winget install Microsoft.DotNet.SDK.10 |
| Node.js with npm | The engines range in src/Nendo.Workbench/package.json | winget install OpenJS.NodeJS.LTS |
| PowerShell 7 | pwsh; every script in tools/ assumes it | winget install Microsoft.PowerShell |
| Git | Any current version | winget install Git.Git |
| WebView2 Evergreen runtime | Already present on Windows 11 | winget install Microsoft.EdgeWebView2Runtime |
| NSIS | Only to build the installer; makensis on PATH | winget install NSIS.NSIS, or the NuGet route below |
Open a new shell after installing so PATH picks the tools up.
Where Group Policy disables winget, or only an internal package mirror is an approved source, NSIS is also published on NuGet as the portable package NSIS-Tool (a third-party repackaging; its makensis.exe is not Authenticode-signed, the package carries NuGet.org's repository signature). Restore it through your mirror and put it on PATH for the build session only; nothing is installed. The steps are in architecture.md. The Windows App SDK is bundled into the build output (self-contained), so it needs no separate runtime. global.json rolls forward to the latest feature band, so a newer 10.0 SDK that is already installed wins the pin.
cd src/Nendo.Workbench; npm ci; npm run build; cd ../..
dotnet build Nendo.slnx
./artifacts/bin/Nendo.Desktop/debug_win-x64/Nendo.Desktop.exe
Do not skip the Workbench step. The .NET build does not build the Workbench, and Nendo.LocalMcp embeds src/Nendo.Workbench/dist/_nendo/view-api.json, so dotnet build on a fresh clone stops with "Build the Workbench first" until npm run build has run. All build output goes under artifacts/, which is git-ignored.
Started with no argument, the app opens without a file; create one from there. Pass the path of a .nendo file to open it instead. The files in workspace/ are tracked demos: open a copy, not the original.
pwsh ./tools/Test-Repository.ps1 # fast invariant check
pwsh ./tools/Test-Production.ps1 # full gate; includes the above
Test-Production.ps1 does the whole build itself (npm ci, Workbench type check, tests and build, then .NET restore, build and tests), so on a fresh clone it is also the one-command build. It takes several minutes once packages are restored: the .NET suites alone run for about five, and the Desktop journeys open real windows. Some Desktop tests open real windows and use the clipboard, so run the gate in an unlocked, interactive desktop session. On a locked workstation the view journey reports its clipboard step as not run and the journey as Inconclusive, naming the lock; run it again unlocked to measure that step. A headless session fails the window tests without any product defect.
Packaging, the installer and the native review lanes outside the gate are documented in architecture.md.
While a file is open with Agent access on, Nendo listens on a loopback port that the file keeps on this computer. The first file you switch access on for keeps 41763, and each further file keeps the next free port. The address is the whole client configuration — there is no credential to find or paste:
claude mcp add --transport http nendo http://127.0.0.1:41763/mcp
codex mcp add nendo --url http://127.0.0.1:41763/mcp
Agent → Connect shows the address a file uses and copies either command.
The registrations checked into this repository (.mcp.json and .codex/config.toml) point at port 41787. That is the port the author's planner file keeps on their machine, not a default, so on a fresh machine they connect to nothing. To use them, set Port for this file to 41787 in Agent → Connect for the file you want an agent in this checkout to reach; otherwise register the address that panel shows.
Anything running on this computer can connect at the chosen access level, so leave access Off when no agent is working.
Codex reads AGENTS.md; CLAUDE.md imports that same file for Claude Code. Both use Nendo Development as the primary work planner through the repository's existing MCP registrations. Read the live work item and its acceptance criteria before implementation, and record outcomes and remaining work at handoff. Accepted ADRs retain architecture authority.
The planner file is the author's own data and is not in a clone. Without it there is no live work item to read: follow the planner-unavailable rule in AGENTS.md, work from the repository instructions and the task in hand, and do not create a replacement planner.
A curated, pinned set of first-party .NET agent skills is vendored under .agents/skills/ — use the matching skill rather than guessing current SDK, template, MSBuild or test behaviour.
| Path | What is in it |
|---|---|
src/Nendo.Engine | The typed core: storage, semantic operations, diff, behaviour. The only code that touches SQLite |
src/Nendo.Desktop | The WinUI 3 host: window, native shell integration, serving custom views from the open file |
src/Nendo.Workbench | The renderer — TypeScript and Vite, bundled into the Desktop output |
src/Nendo.LocalMcp | The loopback MCP server: tools, resources, leases and access modes |
tests/ | MSTest suites for the Engine, the Desktop host and the MCP adapter |
tools/ | Build, packaging, gate and review scripts (PowerShell and Node) |
extensions/ | Source for the eight example custom-view packages; a file carries a package's code once it is imported |
fixtures/ | Reference-application seed data |
workspace/ | Tracked .nendo demo files |
docs/ | Vision, architecture, ADRs and contracts |
site/ | The public website (ADR-0018) — Astro, outside the product boundary |
CONTRIBUTING.md has the loop, the gate to run and the house rules. SECURITY.md states the trust boundary and how to report a vulnerability.
MIT. Vendored third-party material retains its own notices and licences.
hooks/register.tsx 337 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import type { GateView, Planner, Snapshot, WorkItem } from '../types'
4import { bar, GATE_FILE, gateLine, gateShown, gateView, gateWords, parseGateFile } from './gate'
5
6const SNAPSHOT = { plugin: 'nendo-planner', key: 'snapshot' } as const
7const GATE = { plugin: 'nendo-planner', key: 'gate' } as const
8const GATE_EVERY_MS = 2_000
9// How often a run still marked running has its process looked for.
10const ALIVE_EVERY_MS = 15_000
11
12const PLANNER = 'Planner.nendo'
13const EVERY_MS = 60_000
14const SHOWN = 3
15const CLOSED = new Set(['Done', 'Dropped'])
16
17type $ = EngineInterface
18
19// One stateless JSON-RPC call on the 2026-07-28 discover path, as tools/Nendo-McpClient.mjs makes it.
20// Deliberately not an import of that client: a hook runs on the hook engine's $.http.fetch,
21// which returns a whole response, while the client is built on Node's fetch and AbortSignal; the
22// two cannot share a transport, and a listen stream is out of this engine's reach.
23async function rpc($: $, endpoint: string, method: string, params: Record<string, unknown>) {
24 const name = (params.name ?? params.uri) as string | undefined
25 const response = await $.http.fetch(endpoint, {
26 method: 'POST',
27 headers: {
28 Accept: 'application/json, text/event-stream',
29 'Content-Type': 'application/json',
30 'MCP-Protocol-Version': '2026-07-28',
31 'Mcp-Method': method,
32 ...(name ? { 'Mcp-Name': name } : {}),
33 },
34 body: JSON.stringify({
35 jsonrpc: '2.0',
36 id: 1,
37 method,
38 params: {
39 ...params,
40 _meta: {
41 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
42 'io.modelcontextprotocol/clientCapabilities': {},
43 'io.modelcontextprotocol/clientInfo': { name: 'nendo-planner-mod', version: '0.1.0' },
44 },
45 },
46 }),
47 })
48 if (!response.ok) throw Error(`${method}: HTTP ${response.status}`)
49 const messages = (response.headers['content-type'] ?? '').includes('text/event-stream')
50 ? response.text.split(/\r?\n/).filter(l => l.startsWith('data:')).map(l => JSON.parse(l.slice(5)))
51 : [JSON.parse(response.text)]
52 const reply = messages.find(m => m.id === 1)
53 if (!reply || reply.error) throw Error(`${method}: ${reply?.error?.message ?? 'no reply'}`)
54 return reply.result
55}
56
57async function openFiles($: $, workspace: string): Promise<string[]> {
58 const entries = await $.fs.list(workspace).catch(() => [])
59 return entries
60 .map(entry => entry.name)
61 .filter(name => name.endsWith('.nendo.write-owner'))
62 .map(name => name.slice(0, -'.write-owner'.length))
63 .sort((a, b) => (a === PLANNER ? -1 : b === PLANNER ? 1 : a.localeCompare(b)))
64}
65
66// The process that holds the workspace's Planner.nendo, as the write-owner sidecar beside it names
67// it. The sidecar goes when that process lets go of the file, so a process named here is alive and
68// holds this planner, not another file of the same name elsewhere (R2SP-14).
69async function plannerOwner($: $, workspace: string): Promise<number | null> {
70 const text = await $.fs.read(`${workspace}/${PLANNER}.write-owner`).catch(() => null)
71 if (typeof text !== 'string') return null
72 try {
73 const id = JSON.parse(text)?.processId
74 return Number.isInteger(id) && id > 0 ? id : null
75 } catch {
76 return null
77 }
78}
79
80// The discovery entry of that process. Picked by display name, the newest entry for any file named
81// Planner.nendo won, a crashed run's included, whose endpoint answers nothing (R2SP-14).
82async function plannerEndpoint($: $, owner: number): Promise<string | null> {
83 const local = await $.env.get('LOCALAPPDATA')
84 if (!local) return null
85 const folder = `${local}/Nendo/Mcp/active`
86 const entries = await $.fs.list(folder).catch(() => [])
87 let best: { endpoint: string; createdAt: string } | null = null
88 for (const entry of entries) {
89 if (!entry.name.endsWith('.json')) continue
90 const found = await $.fs.read(`${folder}/${entry.name}`).then(t => JSON.parse(t as string)).catch(() => null)
91 if (found?.processId !== owner || typeof found.endpoint !== 'string') continue
92 if (!best || found.createdAt > best.createdAt) best = found
93 }
94 return best?.endpoint ?? null
95}
96
97// A cursor holds the file's change sequence, so a commit between two page reads refuses the next
98// one: "Restart from the first page." The whole read starts again once (R2SP-14).
99async function readRecords($: $, endpoint: string): Promise<any[]> {
100 for (let attempt = 0; ; attempt++) {
101 const records: any[] = []
102 let cursor: string | null = null
103 try {
104 do {
105 const uri = 'nendo://application/entity/nd.work/records?'
106 + (cursor ? `cursor=${encodeURIComponent(cursor)}&` : '') + 'limit=100'
107 const result = await rpc($, endpoint, 'resources/read', { uri })
108 const page = JSON.parse(result.contents[0].text)
109 records.push(...page.items)
110 cursor = page.nextCursor ?? null
111 } while (cursor)
112 return records
113 } catch (error) {
114 if (attempt > 0 || !/first page/i.test(String((error as Error)?.message ?? error))) throw error
115 }
116 }
117}
118
119async function readPlanner($: $, endpoint: string): Promise<Planner> {
120 const lease = await rpc($, endpoint, 'tools/call', { name: 'nendo.lease.status', arguments: {} })
121 const holder = lease.structuredContent?.hasLease ? lease.structuredContent.clientDisplayName ?? 'someone' : null
122
123 const records = await readRecords($, endpoint)
124
125 const open = records.filter(r => !CLOSED.has(r.values['nd.work.status']))
126 const lane = (horizon: string): WorkItem[] => open
127 .filter(r => r.values['nd.work.horizon'] === horizon)
128 .sort((a, b) => (a.values['nd.work.order'] ?? 0) - (b.values['nd.work.order'] ?? 0))
129 .map(r => ({
130 ref: r.values['nd.work.ref'] ?? '?',
131 title: r.values['nd.work.title'] ?? '',
132 status: r.values['nd.work.status'] ?? '',
133 isBlocked: r.calculations?.find((c: any) => c.fieldId === 'nd.work.isBlocked')?.value === true,
134 }))
135
136 return {
137 now: lane('Now'),
138 next: lane('Next'),
139 inbox: open.filter(r => r.values['nd.work.status'] === 'Inbox').length,
140 leaseHolder: holder,
141 }
142}
143
144function statusLine(s: Snapshot): string {
145 if (s.open.length === 0) return 'Nendo: nothing open'
146 const names = s.open.map(n => n.replace(/\.nendo$/, '')).join(', ')
147 const lease = s.planner ? (s.planner.leaseHolder ? ` · lease: ${s.planner.leaseHolder}` : ' · lease free') : ''
148 return `Nendo: ${names} open${lease}`
149}
150
151let isRefreshing = false
152
153async function refresh($: $) {
154 if (isRefreshing) return
155 isRefreshing = true
156 try {
157 const root = await $.session.root()
158 const workspace = `${root}/workspace`
159 const open = await openFiles($, workspace)
160 let planner: Planner | null = null
161 let problem: string | null = null
162 if (open.includes(PLANNER)) {
163 const owner = await plannerOwner($, workspace)
164 const endpoint = owner === null ? null : await plannerEndpoint($, owner)
165 if (!endpoint) problem = 'Planner is open but has no MCP endpoint'
166 else planner = await readPlanner($, endpoint).catch(error => {
167 problem = `Planner did not answer (${String(error?.message ?? error).slice(0, 60)})`
168 return null
169 })
170 }
171 const next: Snapshot = { open, planner, problem, checkedAt: await $.clock.now() }
172 await $.state.set(SNAPSHOT, next)
173 $.ui.status(statusLine(next))
174 } finally {
175 isRefreshing = false
176 }
177}
178
179// The full gate's run, read from the file Test-Production.ps1 writes as it goes (GateProgress.psm1).
180let isPolling = false
181let aliveCheckedAt = 0
182let aliveFor: { processId: number; alive: boolean } | null = null
183
184async function processAlive($: $, processId: number, nowMs: number): Promise<boolean> {
185 if (aliveFor?.processId === processId && nowMs - aliveCheckedAt < ALIVE_EVERY_MS) return aliveFor.alive
186 aliveCheckedAt = nowMs
187 let alive = true
188 try {
189 const { stdout } = await $.process.run(['tasklist', '/FI', `PID eq ${processId}`, '/NH', '/FO', 'CSV'], { timeoutMs: 5_000 })
190 alive = stdout.includes(`"${processId}"`)
191 } catch {
192 // Not knowing is not the same as gone: the bar keeps going.
193 }
194 aliveFor = { processId, alive }
195 return alive
196}
197
198async function pollGate($: $) {
199 if (isPolling) return
200 isPolling = true
201 try {
202 const nowMs = await $.clock.now()
203 const root = await $.session.root()
204 const text = await $.fs.read(`${root}/${GATE_FILE}`).catch(() => null)
205 const file = typeof text === 'string' ? parseGateFile(text) : null
206 const view = file === null ? null
207 : gateView(file, nowMs, file.state !== 'running' || await processAlive($, file.processId, nowMs))
208 const before = (await $.state.get(GATE)).value ?? null
209 const shown = gateShown(view, nowMs) ? view : null
210 if (JSON.stringify(shown) === JSON.stringify(before)) return
211 await $.state.set(GATE, shown)
212 // Said once, when a run this session watched comes to an end.
213 if (before?.state === 'running' && shown !== null && shown.state !== 'running') $.ui.toast(gateLine(shown, 20))
214 } finally {
215 isPolling = false
216 }
217}
218
219function summary(s: Snapshot | null): string {
220 if (!s) return 'Not checked yet.'
221 if (!s.planner) return s.problem ?? 'Planner.nendo is not open.'
222 const line = (w: WorkItem) => `${w.ref} ${w.status}${w.isBlocked ? ' (blocked)' : ''}: ${w.title}`
223 const parts = [
224 `Now: ${s.planner.now.length ? '' : 'empty'}`, ...s.planner.now.map(line),
225 `Next: ${s.planner.next.length ? '' : 'empty'}`, ...s.planner.next.map(line),
226 `Inbox: ${s.planner.inbox}`,
227 `Lease: ${s.planner.leaseHolder ?? 'free'}`,
228 ]
229 return parts.join('\n')
230}
231
232export const register: Register = on => {
233 on('session.start', async ($, e, next) => {
234 await $.command.register({
235 name: 'planner',
236 description: 'Refresh and print the Nendo planner\'s Now and Next lanes',
237 })
238 await $.command.register({
239 name: 'gate',
240 description: 'Show how far the running Test-Production.ps1 has got',
241 })
242 void refresh($)
243 $.clock.every(EVERY_MS, () => void refresh($))
244 void pollGate($)
245 $.clock.every(GATE_EVERY_MS, () => void pollGate($))
246
247 return next(e)
248 })
249
250 on('command.run', { command: 'gate' }, async $ => {
251 await pollGate($)
252 const view = (await $.state.get(GATE)).value ?? null
253 return { text: view === null ? 'No run of Test-Production.ps1 in the last ten minutes.' : gateLine(view) }
254 })
255
256 on('command.run', { command: 'planner' }, async $ => {
257 await refresh($)
258
259 return { text: summary((await $.state.get(SNAPSHOT)).value ?? null) }
260 })
261
262 on('turn.complete', async ($, e, next) => {
263 void refresh($)
264
265 return next(e)
266 })
267
268 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
269 const s = (await $.state.get(SNAPSHOT)).value ?? null
270 const gate = (await $.state.get(GATE)).value ?? null
271 const hasPlanner = s !== null && (s.planner !== null || s.problem !== null)
272 if (e.props.hasSurvey || (!hasPlanner && gate === null)) return next(e)
273
274 const { Box, Button, Text } = $.ui.resolve(e)
275 const width = e.props.bodyColumns
276
277 // The gate's bar, above the planner's lanes, while a run goes and for a while after it ends.
278 const gateRow = (view: GateView) => {
279 const cells = Math.max(10, Math.min(40, Math.floor(width * 0.35)))
280 const { filled, empty } = bar(view.fraction, cells)
281 const tone = view.state === 'passed' ? 'green' : view.state === 'running' ? 'cyan' : 'red'
282 return (
283 <Box key="gate" width={width}>
284 <Text bold>Gate </Text>
285 <Text color={tone}>{filled}</Text>
286 <Text dimColor>{empty}</Text>
287 <Text wrap="truncate"> {gateWords(view)}</Text>
288 </Box>
289 )
290 }
291
292 if (!hasPlanner) return <Box flexDirection="column">{gateRow(gate!)}</Box>
293
294 if (!s!.planner) {
295 return (
296 <Box flexDirection="column">
297 {gate !== null ? gateRow(gate) : null}
298 <Text dimColor wrap="truncate">{s!.problem}</Text>
299 </Box>
300 )
301 }
302
303 const { now, next: upNext, inbox } = s!.planner
304 const item = (w: WorkItem, label: string) => (
305 <Box key={`${label}-${w.ref}`} width={width}>
306 <Text color="cyan">{label} </Text>
307 <Text bold>{w.ref} </Text>
308 <Text color={w.isBlocked || w.status === 'Blocked' ? 'red' : 'yellow'}>{w.status} </Text>
309 <Text wrap="truncate">{w.title}</Text>
310 </Box>
311 )
312
313 const rows = now.length > 0
314 ? now.slice(0, SHOWN).map(w => item(w, 'Now '))
315 : upNext.length > 0
316 ? [item(upNext[0]!, 'Next')]
317 : [<Text key="empty" dimColor>Now and Next are empty · {inbox} in the Later inbox</Text>]
318
319 const more = now.length > SHOWN ? now.length - SHOWN : now.length === 0 && upNext.length > 1 ? upNext.length - 1 : 0
320
321 return (
322 <Box flexDirection="column">
323 {gate !== null ? gateRow(gate) : null}
324 {rows}
325 <Box>
326 <Text dimColor>
327 {now.length === 0 && upNext.length > 0 ? 'Now is empty · ' : ''}
328 {more > 0 ? `+${more} more · ` : ''}
329 {inbox} in inbox · /planner for the list{' '}
330 </Text>
331 <Button key="refresh" label="Refresh" onPress={() => refresh($)} />
332 </Box>
333 </Box>
334 )
335 })
336}
337hooks/gate.ts 116 lines1import type { GateFile, GateStep, GateView } from '../types'
2
3// The full gate's progress, from the file Test-Production.ps1 writes as it runs
4// (tools/GateProgress.psm1). Pure: the hooks module reads the file and the clock.
5
6export const GATE_FILE = 'artifacts/gate-progress.json'
7
8// A finished run's line stays this long, then goes.
9export const SHOWN_AFTER_END_MS = 10 * 60_000
10
11// A step still running counts at most this share of its expected time, so the bar never
12// reaches the end of a step before the step does.
13const STEP_CAP = 0.95
14
15// A step no passing run has timed is weighed as the median of those that have, or this.
16const UNTIMED_SECONDS = 60
17
18function ms(iso: string | null): number | null {
19 if (iso === null) return null
20 const value = Date.parse(iso)
21 return Number.isNaN(value) ? null : value
22}
23
24function median(values: number[]): number | null {
25 if (values.length === 0) return null
26 const sorted = [...values].sort((a, b) => a - b)
27 const middle = Math.floor(sorted.length / 2)
28 return sorted.length % 2 === 1 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2
29}
30
31export function parseGateFile(text: string): GateFile | null {
32 try {
33 const file = JSON.parse(text)
34 if (file?.version !== 1 || !Array.isArray(file.steps) || typeof file.startedAt !== 'string') return null
35 if (!['running', 'passed', 'failed'].includes(file.state)) return null
36 return file as GateFile
37 } catch {
38 return null
39 }
40}
41
42/** What to draw for a run at `nowMs`. `alive` is false once the run's process is known to be gone. */
43export function gateView(file: GateFile, nowMs: number, alive = true): GateView {
44 const timed = file.steps.map(step => step.expectedSeconds).filter((value): value is number => typeof value === 'number' && value > 0)
45 const fallback = median(timed) ?? UNTIMED_SECONDS
46 const weight = (step: GateStep) => (typeof step.expectedSeconds === 'number' && step.expectedSeconds > 0 ? step.expectedSeconds : fallback)
47 const total = file.steps.reduce((sum, step) => sum + weight(step), 0)
48
49 let done = 0
50 for (const step of file.steps) {
51 const started = ms(step.startedAt)
52 const ended = ms(step.endedAt)
53 if (ended !== null) done += weight(step)
54 else if (started !== null) done += Math.min(Math.max(0, (nowMs - started) / 1000), weight(step) * STEP_CAP)
55 }
56
57 const state: GateView['state'] = file.state === 'running' && !alive ? 'interrupted' : file.state
58 const currentIndex = file.steps.findIndex(step => step.id === file.current)
59 const lastStarted = file.steps.reduce((last, step, index) => (step.startedAt !== null ? index : last), -1)
60 const stepIndex = currentIndex >= 0 ? currentIndex : lastStarted
61 const endedAtMs = state === 'running' ? null : ms(file.updatedAt) ?? nowMs
62 const startedAtMs = ms(file.startedAt) ?? nowMs
63 // An estimate only when most steps have an earlier time; otherwise the guess is mostly fallback.
64 const estimable = timed.length * 2 >= file.steps.length
65
66 return {
67 state,
68 fraction: state === 'passed' ? 1 : total > 0 ? Math.min(1, done / total) : 0,
69 stepNumber: stepIndex + 1,
70 stepCount: file.steps.length,
71 stepLabel: stepIndex >= 0 ? file.steps[stepIndex]!.label : null,
72 elapsedSeconds: Math.max(0, Math.round(((endedAtMs ?? nowMs) - startedAtMs) / 1000)),
73 remainingSeconds: state === 'running' && estimable ? Math.max(0, Math.round(total - done)) : null,
74 failure: file.failure,
75 endedAtMs,
76 }
77}
78
79/** Whether a run's line is still worth showing at `nowMs`. */
80export function gateShown(view: GateView | null, nowMs: number): view is GateView {
81 return view !== null && (view.endedAtMs === null || nowMs - view.endedAtMs < SHOWN_AFTER_END_MS)
82}
83
84export function clock(seconds: number): string {
85 const minutes = Math.floor(seconds / 60)
86 const rest = String(seconds % 60).padStart(2, '0')
87 return `${minutes}:${rest}`
88}
89
90/** The bar itself: `width` cells, filled to `fraction`. */
91export function bar(fraction: number, width: number): { filled: string; empty: string } {
92 const cells = Math.max(4, width)
93 const filled = Math.round(Math.min(1, Math.max(0, fraction)) * cells)
94 return { filled: '█'.repeat(filled), empty: '░'.repeat(cells - filled) }
95}
96
97/** The words beside the bar. */
98export function gateWords(view: GateView): string {
99 const percent = `${Math.floor(view.fraction * 100)}%`
100 switch (view.state) {
101 case 'passed': return `passed in ${clock(view.elapsedSeconds)}`
102 case 'failed': return `failed at ${view.stepLabel ?? 'the start'} after ${clock(view.elapsedSeconds)}`
103 case 'interrupted': return `stopped at ${view.stepLabel ?? 'the start'} (its process is gone)`
104 default: {
105 const left = view.remainingSeconds === null ? '' : ` · ~${Math.max(1, Math.round(view.remainingSeconds / 60))} min left`
106 return `${percent} · ${view.stepNumber}/${view.stepCount} ${view.stepLabel ?? ''} · ${clock(view.elapsedSeconds)}${left}`
107 }
108 }
109}
110
111/** One line of text, for /gate and the toast. */
112export function gateLine(view: GateView, width = 30): string {
113 const { filled, empty } = bar(view.fraction, width)
114 return `Gate ${filled}${empty} ${gateWords(view)}`
115}
116types/index.d.ts 67 lines1export type WorkItem = {
2 ref: string
3 title: string
4 status: string
5 isBlocked: boolean
6}
7
8export type Planner = {
9 now: WorkItem[]
10 next: WorkItem[]
11 inbox: number
12 leaseHolder: string | null
13}
14
15export type Snapshot = {
16 // .nendo files in workspace/ that Nendo holds open (a .write-owner sidecar beside them)
17 open: string[]
18 // null when the planner is closed or did not answer
19 planner: Planner | null
20 problem: string | null
21 checkedAt: number
22}
23
24// One step of a Test-Production.ps1 run, as tools/GateProgress.psm1 writes it.
25export type GateStep = {
26 id: string
27 label: string
28 // Seconds it took in the last run that passed; null when no run has timed it.
29 expectedSeconds: number | null
30 startedAt: string | null
31 endedAt: string | null
32}
33
34// artifacts/gate-progress.json
35export type GateFile = {
36 version: number
37 processId: number
38 startedAt: string
39 updatedAt: string | null
40 state: 'running' | 'passed' | 'failed'
41 current: string | null
42 failure: string | null
43 steps: GateStep[]
44}
45
46// What the band draws for a run: interrupted is a run still marked running whose process is gone.
47export type GateView = {
48 state: 'running' | 'passed' | 'failed' | 'interrupted'
49 // 0..1, weighted by each step's time in the last run that passed
50 fraction: number
51 stepNumber: number
52 stepCount: number
53 stepLabel: string | null
54 elapsedSeconds: number
55 // null when too few steps have an earlier time to say
56 remainingSeconds: number | null
57 failure: string | null
58 // When the run ended, for hiding a finished run's line after a while; null while it runs
59 endedAtMs: number | null
60}
61
62declare module 'claude-code' {
63 interface PluginState {
64 'nendo-planner': { snapshot: Snapshot | null; gate: GateView | null }
65 }
66}
67