Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: the trail, periods and progress charts, on the field classes (rebuilds #445) (#674)

nyblnetd521c5d203ac
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bf476a47..51414cb4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -281,6 +281,21 @@ jobs:
TZ=$tz node scripts/test-spaces-calc.ts
done
+ - name: Trail, periods and progress charts (several timezones)
+ # A trail row's key is a LOCAL day, so the whole bug class here is the
+ # one the journal rig exists for. Kiritimati (UTC+14) and Niue (UTC-11)
+ # bracket every hour where "which day is it" has two answers. The rest
+ # of the rig is behavioural: it writes rows, draws the charts, and
+ # asserts that a gap draws as a gap and never as a zero.
+ # (Bundled: it reaches store.ts, whose imports are extensionless.)
+ run: |
+ slides/node_modules/.bin/esbuild scripts/test-spaces-trail.ts --bundle --platform=node --format=esm \
+ --outfile="$RUNNER_TEMP/test-spaces-trail.mjs"
+ for tz in UTC Europe/Berlin Pacific/Kiritimati Pacific/Niue; do
+ echo "--- $tz"
+ TZ=$tz node "$RUNNER_TEMP/test-spaces-trail.mjs"
+ done
+
- name: Spaces Markdown round-trip rig
# The About dialog promises, in eight languages, that "a space is never
# a dead end … every page exports as Markdown". This is that sentence,
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index dc30a2dd..e1ccf35d 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -10001,6 +10001,89 @@ Pointers: spaces/src/history.ts, scripts/test-spaces-history.ts,
scripts/test-spaces-save-revisions.ts (the prepare rows and the main.ts pins),
scripts/test-spaces-copytiers.ts (real revisions per tier).
+## 2026-10-10 — spaces: the trail (doc.trail), periods, and the three progress charts, on the field classes
+
+Rebuilds the never-merged #445 on main's field classes and in-file history
+(#671). Three decisions from #445 carry over unchanged in substance and are
+recorded here because they never reached this log; two are new.
+
+**1. A record is not a derivation.** `calc.ts` stores no answer, `fields.ts
+viewRows` keeps no copy of the rows, `model.ts tableOf` normalises at read
+time. The rule underneath is narrower than "everything derives": *never store
+what the current document already implies; do store an observation it cannot
+reproduce.* No recomputation over today's pages answers "how many points were
+open on 3 September", so `doc.trail` — `YYYY-MM-DD` (or `<series>/YYYY-MM-DD`)
+→ counts per status option id — is a stored observation, in the same class as
+`page.created`, `Comment.at` and `doc.revisions`. The falsifiable half: the
+chart's TODAY point is derived from live state; only strictly earlier days are
+read from the trail, and only today's key is ever written (`backfill` refuses
+to overwrite). A missing day is drawn as a gap, never interpolated, carried
+forward or zeroed; thinning SELECTS a bucket's last row and stamps the span it
+stands for, never averages. A row holds counts and nothing else — no page ids,
+no assignee breakdown — a budget rule and a privacy rule at once. Rejected:
+deriving burndown from `doc.revisions` (pruned oldest-first, keyed to saves not
+days, and "Clear history" would silently empty every chart).
+
+**2. The host follows the data source.** Gantt and workload read pages live, so
+they are view layouts. Burndown, burnup and CFD read pre-aggregated counts, so a
+view's `filter` would look like it narrowed them and would not; they are a
+`chart` BLOCK, and their scope is frozen onto a `doc.periods` entry at commit.
+They draw their own SVG rather than `kernel/src/charts.ts`, measured: charts-lite
+maps an absent datum to zero, has no stacking, and has no per-segment dashing.
+
+**3. trail is HISTORY class; periods is CONTENT.** (New, replacing #445's hand
+`stripRecord` and its per-key sync of the trail.)
+- `trail` is classed `history` in `SPACES_FIELDS`, so the kernel's copy table
+ keeps it in the file, a duplicate and an invite and drops it from reader,
+ sealed reading, link, audience, template and Copy-JSON copies and the page
+ extract. No builder strips it by name; copytiers' sweep now fails on a
+ history field stripped by name outside its own engine module. It is never
+ synced: the kernel's `shape()` skips history fields, so each replica records
+ what it saw. #445 synced it per key; under the history class two files of one
+ room each hold their own truthful record, which is what file-local means.
+- `periods` is classed `content`. A period is something a person decided (a
+ window and a committed scope), a chart block names it by id, ⌘Z takes it back,
+ and collaborators share the sprint. As history it would be dropped from a
+ reader copy while the block naming it stayed — a dangling reference — and it
+ would not sync. It holds totals at one instant (`base`), never page ids or a
+ series, so carrying it to a reader discloses one aggregate count, not cadence.
+ It stays a per-key CRDT map (`DOC_MAPS` = `['periods']`, docmaps.ts) so two
+ people starting different periods both keep theirs; a dotted `periods.<id>`
+ written by an older peer is folded back at parse.
+- A chart in a copy that has the period but not the trail (not editable, no
+ `trail` key) says "This copy does not include the day-by-day record" instead
+ of drawing every day as *Not recorded*, which would claim nobody worked.
+
+**4. The trail records while editing, so it counts as unsaved work.** Today's
+row is written on the store's `doc` event, outside any commit and never on
+open; a read-only store (reader, reading copy, frozen file) never writes.
+Because rows land between saves, `trail` is NOT in `SPACES_NOT_EDIT`: a row
+recorded since the last save raises the recovery key, the kernel's default.
+(`revisions` is exempt only because spaces writes it inside a save's prepare.)
+The store keeps history-class fields live across undo, redo and `replaceDoc`,
+which is right for the trail: ⌘Z never erases a row, and Replace from JSON with
+Copy-JSON output never wipes it.
+
+**5. The trail has its own budget, beside history's.** `TRAIL_BUDGET` = 32 KB
+and `TRAIL_MAX` = 400 rows (trail.ts), beside `HISTORY_BUDGET` = 128 KB: at
+most 160 KB of record, the joint ceiling ruled acceptable. This supersedes
+#445's single proportional budget (`clamp(25% of content, 64–256 KB)`, trail
+yielding to history), which never merged. Past the budget the oldest rows thin
+to weekly, then monthly, then drop with `cut` on the oldest survivor; a live
+period's days are never thinned. A real fixture (500 days of edits and saves)
+asserts both budgets and the joint ceiling.
+
+**Interim chrome:** the block sits in Insert → View ▾ behind a rule, not as a
+Chart button of its own — a button tipped the bar out of slides' width at 1440,
+the same reason Embed sits in Image ▾.
+
+**Known gap, not fixed here:** a recovery restore goes through `replaceDoc`,
+which keeps the live trail, so rows that exist only in a crash-recovery
+snapshot (recorded on a day the file was never saved) are not brought back.
+Today's row is re-observed on the next edit; earlier unsaved days are lost.
+
+Pointers: spaces/src/trail.ts, observe.ts, periods.ts, charts.ts, docmaps.ts,
+docclass.ts; scripts/test-spaces-trail.ts, scripts/test-spaces-copytiers.ts.
## 2026-10-10 — a spaces invite discloses its history and can leave it out
**Decision.** The kernel's invite tier keeps the `history` class, and the
diff --git a/docs/spaces-agents.md b/docs/spaces-agents.md
index 7803658c..2e3a948d 100644
--- a/docs/spaces-agents.md
+++ b/docs/spaces-agents.md
@@ -136,6 +136,7 @@ unique ids the first time.
| `view` | `layout`, `groupBy`, `source`, `filter`, `sort`, `html` | a board, list, table, gallery, timeline or workload chart of this space's pages |
| `view` | `layout`, `span`, `groupBy`, `html` | a board, list, table, gallery or calendar of this space's pages |
| `view` | `layout`, `groupBy`, `sort`, `source`, `filter`, `html` | a board or list of this space's issues |
+| `chart` | `kind` (`burndown`/`burnup`/`cfd`), `period`, `html` | a progress chart over `doc.trail` — see **Progress charts** |
`type` is a **string**, not a closed set: an unknown type survives a round trip
and renders its `html` as a fallback. Properties are **flat on the block** —
@@ -563,6 +564,52 @@ same trade the format makes everywhere: never silently narrow.
**Not in this format, deliberately**: teams, per-user permissions,
notifications, automation. The file is the team boundary and the capability.
+### Progress charts
+
+A `chart` block draws **burndown**, **burnup** or **cumulative flow** from
+`doc.trail` — a record the file keeps of itself, one row per local day:
+
+```jsonc
+{
+ "trail": { // document-level, optional
+ "2026-09-08": {
+ "n": { "todo": 3, "doing": 2, "done": 1 }, // issues per STATUS OPTION id
+ "e": { "todo": 11, "doing": 8, "done": 4 }, // summed estimate, absent if nothing is estimated
+ "x": 2 // issues counted that carried no estimate
+ }
+ },
+ "periods": { // the windows charts are drawn over
+ "pd-1": { "label": "Sprint 12", "from": "2026-09-01", "to": "2026-09-20",
+ "base": { "at": "2026-09-01", "n": 6, "e": 23 } }
+ }
+}
+```
+
+Three things to know before you touch either of them.
+
+**Do not write past rows.** The app writes TODAY's key and only today's; a row,
+once written, is immutable for the rest of the file's life. Rewriting yesterday
+from today's numbers is the one thing the whole design exists to prevent.
+
+**A missing key is a GAP and is drawn as one** — a broken line and a hatched
+band labelled "not recorded". Do not fill gaps in, and never carry a value
+forward: a carried value looks exactly like data. A row carrying `s` stands for
+that many days ending on its own key and draws dashed, so a weekly sample is
+never mistaken for a daily reading.
+
+**A row holds counts and nothing else.** No page ids, no assignee breakdown, no
+per-issue anything — that is a budget rule and a privacy rule at once, and it
+is not an oversight to be helpfully corrected. What a trail discloses is the
+team's cadence, so `trail` is version history in the copy rules: the file, a
+duplicate and an invite keep it; a view-only copy, the reading copy, Copy
+document JSON, a template and a page extract carry none of it. It is never
+synced either — each copy records what it saw. `periods` is ordinary content:
+it syncs, and every copy keeps it.
+
+Both keys are absent until something is recorded, and a cleared space deletes
+the key rather than storing `{}`. A `chart` block whose `period` names nothing
+renders "this chart's period is gone" rather than an empty graph.
+
## What makes a space good rather than merely correct
| When the material is… | Reach for | Why |
diff --git a/scripts/test-spaces-chrome.ts b/scripts/test-spaces-chrome.ts
index ecb57fb4..304f13a0 100644
--- a/scripts/test-spaces-chrome.ts
+++ b/scripts/test-spaces-chrome.ts
@@ -193,10 +193,12 @@ ok(LISTED.length >= 15 && LISTED.includes('p') && !LISTED.includes('prop'), `the
// Embed sits in Image ▾ beside Link to page (interim, 2026-10-09: a bar
// button of its own tipped the bar out of slides' width at 1440), so it is in
// the Image family's members below, not here.
-// what the group should show on THIS build: Chart where that
-// block exists, and a Code menu once maths joins it
+// The chart of progress sits in View ▾ behind a rule for the same reason
+// (interim, 2026-10-10): a Chart button of its own tipped the bar out of
+// slides' width at 1440 — measured, it went compact. What the group should
+// show on THIS build: a Code menu once maths joins it.
const has = (t: string) => LISTED.includes(t)
-const WANT_GROUP = ['Text ▾', 'Image ▾', 'Table', ...(has('chart') ? ['Chart'] : []), 'View ▾', has('math') ? 'Code ▾' : 'Code', 'Comment']
+const WANT_GROUP = ['Text ▾', 'Image ▾', 'Table', 'View ▾', has('math') ? 'Code ▾' : 'Code', 'Comment']
// slides' numbers for its insert buttons and their group, read from its stylesheet
const SLIDES_INS = {
groupGap: decl(block('.ed-group'), 'gap'),
diff --git a/scripts/test-spaces-copytiers.ts b/scripts/test-spaces-copytiers.ts
index bd80ab4e..c5b76bf3 100644
--- a/scripts/test-spaces-copytiers.ts
+++ b/scripts/test-spaces-copytiers.ts
@@ -60,6 +60,9 @@ const { projectForCopy, collabForReader, COLLAB_READER_KEEP, COLLAB_INVITE_KEEP
const { mintCollab } = await import('../kernel/src/sync/online.ts')
const { recordRevision, revisionsOf, applyRevisions } = await import('../spaces/src/history.ts')
const { validateRevision } = await import('../kernel/src/docfields.ts')
+const { recordTrail } = await import('../spaces/src/observe.ts')
+const { startPeriod } = await import('../spaces/src/periods.ts')
+const { trailOf } = await import('../spaces/src/trail.ts')
import type { SpacesDoc } from '../spaces/src/model.ts'
import type { Tier } from '../kernel/src/docfields.ts'
@@ -98,7 +101,7 @@ const collab = {
const OWNER_PRIV = (collab as Obj).ownerPriv as string
/** Content fields of the fixture — everything the map classes 'content'. */
-const CONTENT = ['format', 'version', 'title', 'home', 'pages', 'theme', 'modified', 'assets', 'footnotes', 'design', 'journalTemplate']
+const CONTENT = ['format', 'version', 'title', 'home', 'pages', 'theme', 'modified', 'assets', 'footnotes', 'design', 'journalTemplate', 'periods']
function source(extra: Obj = {}): SpacesDoc {
return {
format: FORMAT, version: 1,
@@ -117,7 +120,8 @@ function source(extra: Obj = {}): SpacesDoc {
journalTemplate: 't1',
collab: clone(collab),
revisions: realRevisions(),
- trail: { '2026-10-09': { done: 3 } },
+ trail: realTrail(),
+ periods: realPeriods(),
futureField: 'FROM-A-NEWER-BUILD',
...extra,
} as unknown as SpacesDoc
@@ -153,6 +157,38 @@ function realRevisions(): unknown[] {
return clone(REAL_REVISIONS)
}
+/**
+ * A REAL trail and a REAL period, recorded by observe.ts and periods.ts exactly
+ * as editing records them: a tracker whose status options are named so their
+ * ids are unmistakable in a copy's text (`trailmark-*`). A row holds counts per
+ * option id and nothing else, so the option id IS the marker — if any of it
+ * reaches a copy, a full-text scan finds it.
+ */
+// eslint-disable-next-line no-var
+var REAL_TRACKER: { trail: unknown; periods: unknown } | undefined
+function tracked(): { trail: unknown; periods: unknown } {
+ if (REAL_TRACKER) return clone(REAL_TRACKER)
+ const issue = (id: string, status: string, est: number) => ({
+ id, title: `Issue ${id}`, blocks: [
+ { id: `${id}-s`, type: 'prop', key: 'status', value: status, html: `Status: ${status}` },
+ { id: `${id}-e`, type: 'prop', key: 'estimate', value: est, html: `Estimate: ${est}` },
+ ],
+ })
+ const d = {
+ format: FORMAT, version: 1, docId: 'doc-source', title: 'Tracker', home: 'i1',
+ pages: [issue('i1', 'trailmark-open', 3), issue('i2', 'trailmark-open', 5), issue('i3', 'trailmark-shut', 2)],
+ theme: { background: '#FFFFFF', color: '#1E2A3A', accent: '#F7A600', fontFamily: 'sans-serif', measure: 720 },
+ } as unknown as SpacesDoc
+ startPeriod(d, 'pd-rig', { label: 'Sprint 12', from: '2026-10-07', to: '2026-10-20', today: '2026-10-07' })
+ recordTrail(d, { today: '2026-10-08' })
+ ;(d.pages[0].blocks[0] as Obj).value = 'trailmark-shut'
+ recordTrail(d, { today: '2026-10-09' })
+ REAL_TRACKER = { trail: clone(d.trail), periods: clone(d.periods) }
+ return clone(REAL_TRACKER)
+}
+function realTrail(): unknown { return tracked().trail }
+function realPeriods(): unknown { return tracked().periods }
+
/** No capability secret anywhere in the serialized copy — a full-text scan. */
function noSecrets(o: object, label: string, allowFreshInvite = false) {
const text = JSON.stringify(o)
@@ -221,6 +257,46 @@ console.log('\nreal in-file history (history.ts), tier by tier')
}
}
+// ---------------------------------------------------------------------------
+// A REAL TRAIL, per tier, and the PERIODS beside it. The trail is history:
+// the owner's own copies and an invite keep it byte-for-byte; every copy handed
+// to a reader drops it whole, and no `trailmark-*` option id (the only thing a
+// row can name) survives anywhere in one. `periods` is content: every copy
+// keeps it, so a chart block in a kept page never names a period that is gone.
+console.log('\nreal trail (observe.ts) and periods (periods.ts), tier by tier')
+{
+ const src = source()
+ const wantTrail = JSON.stringify(src.trail)
+ const wantPeriods = JSON.stringify(src.periods)
+ ok(Object.keys(trailOf(src)).length === 3 && wantTrail.includes('trailmark-open'),
+ `the fixture's trail is 3 real recorded rows keyed by option id (${Object.keys(trailOf(src)).join(',')})`)
+ ok(wantPeriods.includes('Sprint 12') && !wantPeriods.includes('trailmark'),
+ "the fixture's period is real, and holds totals only — no option ids, no page ids")
+ const kept: Array<[string, SpacesDoc]> = [
+ ['invite', (await inviteCopy(source()))!],
+ ['duplicate', duplicateAsNew(source(), 'doc-fresh')],
+ ['file', projectForCopy(source(), SPACES_FIELDS, 'file')],
+ ]
+ for (const [label, o] of kept) {
+ ok(JSON.stringify((o as Obj).trail) === wantTrail, `${label}: KEEPS the trail byte-for-byte`)
+ ok(JSON.stringify((o as Obj).periods) === wantPeriods, `${label}: keeps the periods`)
+ }
+ const dropped: Array<[string, SpacesDoc]> = [
+ ['reader (view-only copy)', readerCopy(source())!],
+ ['Copy document JSON', docForExport(source())],
+ ['sealed reading copy (reading.ts, tier package)', readingCopy(source())],
+ ['link', projectForCopy(source(), SPACES_FIELDS, 'link')],
+ ['audience', projectForCopy(source(), SPACES_FIELDS, 'audience', { projectAudience: (c) => ({ ...collabForReader(c), role: 'audience' }) })],
+ ['template', projectForCopy(source(), SPACES_FIELDS, 'template')],
+ ['extract', extractSpace(source(), 'p1', { subtree: true, docId: 'doc-x' }).doc],
+ ]
+ for (const [label, o] of dropped) {
+ ok(!('trail' in (o as Obj)), `${label}: DROPS the trail`)
+ ok(!JSON.stringify(o).includes('trailmark'), `${label}: no recorded option id appears anywhere in it`)
+ ok(JSON.stringify((o as Obj).periods) === wantPeriods, `${label}: keeps the periods (content)`)
+ }
+}
+
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// THE INVITE'S HISTORY CHOICE (the maintainer's history ruling): an invite
@@ -261,6 +337,19 @@ async function checkInviteChoice(build: InviteBuilder, label: string): Promise<b
ok(hasHistory(source()) && !hasHistory({ ...source(), revisions: undefined, trail: undefined } as SpacesDoc),
'hasHistory: true with revisions or trail, false with neither (the notice shows only then)')
await checkInviteChoice(inviteCopy, 'invite')
+ // A TRAIL ALONE. A space that has never been saved with a version still has
+ // the day-by-day record the moment anyone edits an issue — so the notice must
+ // show for it, and "leave out" must take the trail (recorded for real by
+ // observe.ts) while keeping the periods a chart block names by id.
+ {
+ const trailOnly = { ...source(), revisions: undefined } as SpacesDoc
+ ok(!!(trailOnly as Obj).trail && hasHistory(trailOnly),
+ 'a space with a trail and NO revisions still has history — the invite notice shows')
+ const out = (await inviteCopy(trailOnly, { withHistory: false }))! as Obj
+ ok(!('trail' in out) && !('revisions' in out), '"leave out" on a trail-only space — no trail in the invite')
+ ok(JSON.stringify(out.periods) === JSON.stringify((trailOnly as Obj).periods),
+ '…and the periods (content) ride along, so its chart blocks still name a real period')
+ }
// NOT VACUOUS: a builder that ignores the option must fail these rows
const ignoring: InviteBuilder = (d) => inviteCopy(d)
const f0 = failures, c0 = checks
@@ -534,6 +623,18 @@ console.log('\nevery builder routes through projectForCopy (source)')
const s = rd(f)
if (/delete [\w.]+\.collab\b/.test(s)) handStrip.push(`${f}: delete .collab`)
if (/collabFor(Reader|Invite)\(/.test(s)) handStrip.push(`${f}: collabFor*`)
+ // and no HISTORY field is stripped by name: the class drops it, from the
+ // map, so a copy rule added later covers it without anyone remembering.
+ // (extractSpace's class-derived drop names no field, and passes.) The ONE
+ // exemption is each field's own engine, which owns "Clear history" /
+ // clearing the record: history.ts for revisions, trail.ts for trail.
+ const OWN: Record<string, string> = { revisions: 'history.ts', trail: 'trail.ts' }
+ for (const k of Object.keys(SPACES_FIELDS).filter((k) => (SPACES_FIELDS as Record<string, string>)[k] === 'history')) {
+ if (OWN[k] === f) continue
+ const lit = new RegExp(`delete [\\w.]+(\\.${k}\\b|\\[['"]${k}['"]\\])|\\b${k}: _\\w*\\s*[,}]`)
+ if (lit.test(s)) handStrip.push(`${f}: strips ${k} by name`)
+ }
+ if (/\bstripRecord\(/.test(s)) handStrip.push(`${f}: stripRecord`)
// editor.ts strips a bento/SLIDES deck (pageToDeck), not a space: the one
// withoutCaps allowed, and it is pinned by name
const caps = [...s.matchAll(/withoutCaps\(/g)].length
diff --git a/scripts/test-spaces-md-strict.ts b/scripts/test-spaces-md-strict.ts
index e8a91b28..319be683 100644
--- a/scripts/test-spaces-md-strict.ts
+++ b/scripts/test-spaces-md-strict.ts
@@ -104,12 +104,14 @@ const FIX: Record<string, () => Fixture> = {
return { blocks: [c, b('p', 'card one', { parent: c.id, x: 40, y: 60 }), b('p', 'card two', { parent: c.id, x: 300, y: 120 }),
three, b('bullet', 'its own child', { parent: three.id }), b('p', 'card four, placed by slot', { parent: c.id }), b('p', 'after the canvas')] }
},
+ chart: () => ({ blocks: [b('chart', 'Burndown — Sprint 12 (1–14 Sept)', { kind: 'burndown', period: 'pd-1' })] }),
}
// THE PINS — the types Markdown cannot yet carry, each with why. The reason is
// the design brief's own row, so a reader of a failure knows what closing it
// would take. Removing a pin is the deliberate edit this rig asks for.
const PINNED: Record<string, string> = {
+ chart: 'exports as the sentence the block carries (`**Burndown — Sprint 12**`) and comes back a paragraph: Markdown has no chart, and the record it draws (doc.trail, doc.periods) is document-level, not in the page',
prop: 'exports as `**Status:** In progress` and comes back a paragraph; the natural form is front matter (`status: doing`), and value id vs label needs the schema',
}
diff --git a/scripts/test-spaces-trail.ts b/scripts/test-spaces-trail.ts
new file mode 100644
index 00000000..e67a25b5
--- /dev/null
+++ b/scripts/test-spaces-trail.ts
@@ -0,0 +1,746 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The trail, the periods, and the three charts drawn from them.
+//
+// node scripts/test-spaces-trail.ts
+// TZ=Pacific/Kiritimati node scripts/test-spaces-trail.ts
+//
+// RUN UNDER SEVERAL TIMEZONES, alongside the journal and calc rigs, for the
+// reason those two are: a row key is a LOCAL day, and a date bug that only
+// appears east of UTC passes every assertion written in UTC. Kiritimati is
+// UTC+14 and Niue is UTC-11 — between them they bracket every hour of the day
+// where "which day is it" has two answers.
+//
+// EVERY ASSERTION HERE IS BEHAVIOURAL. This zone has measured, twice, that a
+// source-grep assertion passes straight through a live regression: the literal
+// stayed in the file while the dispatch changed underneath it, 826/826 green.
+// So these build a document, write rows into it, draw the chart, and assert on
+// the numbers and the geometry that come back.
+
+import {
+ isDay, dayIndex, addDays, daysBetween, weekKey, monthKey, dayRange,
+ trailKey, parseTrailKey, trailOf, trailIsForeign, seriesRows, slots,
+ writeRow, backfill, clearTrail,
+ pruneTrail, trailBytes,
+ wasCut, spanOf, countOf, TRAIL_BUDGET, TRAIL_MAX,
+ type Trail, type TrailRow,
+} from '../spaces/src/trail.ts'
+import { foldDottedMapKeys, DOC_MAPS } from '../spaces/src/docmaps.ts'
+import { SPACES_FIELDS, SPACES_NOT_EDIT } from '../spaces/src/docclass.ts'
+import { HISTORY_BUDGET, recordRevision, historyBytes } from '../spaces/src/history.ts'
+import { observe, recordTrail, estimateField } from '../spaces/src/observe.ts'
+import {
+ periodsOf, periodOf, startPeriod, closePeriod, removePeriod, isLive,
+ protectedDays, isPeriod,
+} from '../spaces/src/periods.ts'
+import { chartData, chartKind, CHART_KINDS } from '../spaces/src/charts.ts'
+import { parseDoc, docContentKey, docForExport, FORMAT, type SpacesDoc, type Page } from '../spaces/src/model.ts'
+import { extractSpace } from '../spaces/src/portable.ts'
+import { DEFAULT_FIELDS } from '../spaces/src/fields.ts'
+import { SPEC } from '../spaces/src/blocks.ts'
+import { SPACES_SHAPE, SyncState } from '../spaces/src/sync/crdt.ts'
+// BUNDLED (scripts/test-spaces.mjs): store.ts imports './model' without an
+// extension, which node's strip-only TypeScript loader will not follow.
+import { Store } from '../spaces/src/store.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const TZ = process.env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone
+console.log(`bento/spaces trail (TZ=${TZ})\n`)
+
+// ---------------------------------------------------------------------------
+// fixtures
+// ---------------------------------------------------------------------------
+
+let seq = 0
+const issue = (status: string, estimate?: number): Page => {
+ const id = `i${++seq}`
+ const blocks: Page['blocks'] = [
+ { id: `${id}-s`, type: 'prop', key: 'status', value: status, html: `Status: ${status}` } as never,
+ ]
+ if (estimate !== undefined) {
+ blocks.push({ id: `${id}-e`, type: 'prop', key: 'estimate', value: estimate, html: `Estimate: ${estimate}` } as never)
+ }
+ return { id, title: `Issue ${id}`, blocks }
+}
+
+function docOf(pages: Page[], extra: Partial<SpacesDoc> = {}): SpacesDoc {
+ return {
+ format: FORMAT,
+ version: 1,
+ docId: 'doc-rig',
+ title: 'Rig space',
+ pages,
+ theme: { background: '#fff', color: '#000', accent: '#F7A600', fontFamily: 'sans-serif' },
+ ...extra,
+ } as SpacesDoc
+}
+
+/** A tracker: three open, two done, all estimated. */
+const tracker = () => {
+ seq = 0
+ return docOf([
+ issue('todo', 3), issue('doing', 5), issue('todo', 2),
+ issue('done', 8), issue('cancelled', 1),
+ ])
+}
+
+// ---------------------------------------------------------------------------
+// 1. day arithmetic — the label is the thing, and it has no timezone
+// ---------------------------------------------------------------------------
+{
+ ok(isDay('2026-09-11'), 'a real day is a day')
+ ok(!isDay('2026-13-99'), 'a digit-shaped non-date is rejected, not rolled over')
+ ok(!isDay('2026-02-30'), 'the 30th of February is rejected')
+ ok(!isDay('2026-9-1') && !isDay('') && !isDay(undefined), 'loose shapes are rejected')
+
+ // THE BUG THIS EXISTS TO CATCH: at UTC+14 and at UTC-11, one label must be
+ // one number. `new Date('2026-01-01')` is UTC midnight, so anything that
+ // round-trips a label through a local Date drifts by a day in half the world.
+ ok(dayIndex('1970-01-01') === 0, 'the epoch label is day 0 whatever TZ this is')
+ ok(dayIndex('2026-01-01') === 20454, '2026-01-01 is the same ordinal in every timezone')
+ ok(addDays('2026-01-01', -1) === '2025-12-31', 'a day before new year is the year before')
+ ok(addDays('2026-02-28', 1) === '2026-03-01', '2026 is not a leap year')
+ ok(addDays('2024-02-28', 1) === '2024-02-29', '2024 is')
+ // DST boundaries: 86,400,000 ms is not a day in Berlin in March, and this
+ // must not care.
+ ok(addDays('2026-03-28', 1) === '2026-03-29', 'the European DST boundary steps by one')
+ ok(addDays('2026-11-01', 1) === '2026-11-02', 'the American one steps by one')
+ ok(daysBetween('2026-01-01', '2026-12-31') === 364, 'a non-leap year is 364 steps end to end')
+ ok(daysBetween('2026-09-11', '2026-09-10') === -1, 'backwards is negative, not an error')
+
+ ok(weekKey('2026-09-07') === weekKey('2026-09-13'), 'Monday and the Sunday after share an ISO week')
+ ok(weekKey('2026-09-13') !== weekKey('2026-09-14'), 'Monday starts a new one')
+ ok(monthKey('2026-09-30') === '2026-09' && monthKey('2026-10-01') === '2026-10', 'months split at the 1st')
+
+ ok(dayRange('2026-09-01', '2026-09-03').join(',') === '2026-09-01,2026-09-02,2026-09-03', 'a range is inclusive')
+ ok(dayRange('2026-09-03', '2026-09-01').length === 0, 'a backwards range is empty, and does not throw')
+ ok(dayRange('nonsense', '2026-09-01').length === 0, 'a malformed range is empty')
+}
+
+// ---------------------------------------------------------------------------
+// 2. keys
+// ---------------------------------------------------------------------------
+{
+ ok(trailKey('2026-09-11') === '2026-09-11', 'the default series is a bare date')
+ ok(trailKey('2026-09-11', 'apollo') === 'apollo/2026-09-11', 'a series prefixes the key')
+ const a = parseTrailKey('apollo/2026-09-11')
+ ok(a?.series === 'apollo' && a.day === '2026-09-11', 'a series key parses back')
+ const b = parseTrailKey('2026-09-11')
+ ok(b?.series === '' && b.day === '2026-09-11', 'a bare key is the default series')
+ ok(parseTrailKey('2026-13-99') === null, 'a key that is not a day is not a key')
+ ok(parseTrailKey('a/b/2026-09-11') === null, 'a shape from a newer build is left alone')
+}
+
+// ---------------------------------------------------------------------------
+// 3. observation — one counting rule, the board's
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ const obs = observe(doc)!
+ ok(!!obs, 'a space with a status field is observed')
+ ok(obs.n.todo === 2 && obs.n.doing === 1 && obs.n.done === 1 && obs.n.cancelled === 1,
+ 'counts are per status OPTION id, not per phase group')
+ ok(obs.e?.todo === 5 && obs.e?.done === 8, 'estimates are summed per option')
+ ok(obs.x === undefined, 'no unestimated issues, so no x')
+
+ // ARCHIVED PAGES ARE EXCLUDED — because viewRows excludes them, which is the
+ // whole point of using the board's own counter.
+ const arch = tracker()
+ arch.pages[0].archived = true
+ ok(observe(arch)!.n.todo === 1, 'an archived issue leaves the count')
+
+ // UNESTIMATED
+ const mixed = docOf([issue('todo', 3), issue('todo')])
+ const m = observe(mixed)!
+ ok(m.n.todo === 2 && m.e?.todo === 3 && m.x === 1, 'an unestimated issue is counted in n and in x')
+
+ // NOT A TRACKER. `fieldsOf` falls back to DEFAULT_FIELDS while `doc.fields`
+ // is absent, so the phase field is found — and the observation is EMPTY,
+ // because a notes space has no issues. That is what makes tracking implicit
+ // without turning itself on: no issues, no counts, no row (asserted below).
+ const notes = docOf([{ id: 'p1', title: 'Notes', blocks: [{ id: 'b1', type: 'p', html: 'hello' }] }])
+ ok(Object.keys(observe(notes)!.n).length === 0, 'a space with no issues observes nothing')
+ // a document that DECLARES a schema with no phased field has no notion of
+ // open at all, and is not observed
+ const unphased = docOf([issue('todo', 1)], { fields: [{ key: 'tag', label: 'Tag', vt: 'text' }] } as never)
+ ok(observe(unphased) === null, 'a schema that declares no phase field is not observed at all')
+
+ // an unknown status counts under its own literal
+ const future = docOf([issue('shipped')])
+ ok(observe(future)!.n.shipped === 1, "a status this build does not know is counted literally")
+
+ ok(estimateField(tracker())?.key === 'estimate', 'the estimate field is derived from the schema')
+ ok(DEFAULT_FIELDS.some((f) => f.key === 'status'), 'the default schema still declares status')
+}
+
+// ---------------------------------------------------------------------------
+// 4. writing — idempotent within a day, and never on open
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ ok(doc.trail === undefined, 'a fresh tracker carries no trail key at all')
+
+ recordTrail(doc, { today: '2026-09-11' })
+ recordTrail(doc, { today: '2026-09-11' })
+ recordTrail(doc, { today: '2026-09-11' })
+ ok(Object.keys(trailOf(doc)).length === 1, 'three writes on one day produce exactly one key')
+ ok(trailOf(doc)['2026-09-11'].n.todo === 2, 'and it holds the observation')
+
+ // the LAST observation of the day wins
+ ;(doc.pages[0].blocks[0] as { value: string }).value = 'done'
+ recordTrail(doc, { today: '2026-09-11' })
+ ok(trailOf(doc)['2026-09-11'].n.todo === 1, "a day's row is the LAST observation of that day")
+
+ // NOT A TRACKER, NO ROWS
+ const notes = docOf([{ id: 'p1', title: 'Notes', blocks: [{ id: 'b1', type: 'p', html: 'x' }] }])
+ recordTrail(notes, { today: '2026-09-11' })
+ ok(notes.trail === undefined, 'a notes space writes no rows and gains no key')
+
+ // A FOREIGN TRAIL IS NEVER WRITTEN OVER
+ const foreign = tracker()
+ ;(foreign as Record<string, unknown>).trail = 'something a newer build meant'
+ ok(trailIsForeign(foreign), 'a non-object trail is foreign')
+ recordTrail(foreign, { today: '2026-09-11' })
+ ok(foreign.trail === 'something a newer build meant', 'and it is left exactly as it was found')
+}
+
+// ---------------------------------------------------------------------------
+// 5. EDITING THE PAST DOES NOT REWRITE IT
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ recordTrail(doc, { today: '2026-09-09' })
+ recordTrail(doc, { today: '2026-09-10' })
+ const before = JSON.stringify(trailOf(doc)['2026-09-09'])
+ const before10 = JSON.stringify(trailOf(doc)['2026-09-10'])
+
+ // change an estimate, close an issue, add an issue — everything a day of work
+ // does — and then write today.
+ ;(doc.pages[0].blocks[1] as { value: number }).value = 99
+ ;(doc.pages[1].blocks[0] as { value: string }).value = 'done'
+ doc.pages.push(issue('todo', 13))
+ recordTrail(doc, { today: '2026-09-11' })
+
+ ok(JSON.stringify(trailOf(doc)['2026-09-09']) === before, "yesterday's row is byte-identical after today's edits")
+ ok(JSON.stringify(trailOf(doc)['2026-09-10']) === before10, 'and so is the day before that')
+ ok(trailOf(doc)['2026-09-11'].e!.todo === 114, "today's row moved, because today is what changed")
+
+ // BACKFILL REFUSES TO OVERWRITE
+ const row: TrailRow = { n: { todo: 1 } }
+ ok(backfill(doc, '2026-09-09', row) === false, 'backfill refuses a key that is already there')
+ ok(JSON.stringify(trailOf(doc)['2026-09-09']) === before, 'and changed nothing when it refused')
+ ok(backfill(doc, '2026-09-01', row) === true, 'backfill writes an absent past key')
+}
+
+// ---------------------------------------------------------------------------
+// 6. GAPS DRAW AS GAPS — the load-bearing assertion
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ const trail: Trail = {
+ '2026-09-01': { n: { todo: 4 } },
+ '2026-09-02': { n: { todo: 3 } },
+ // 03, 04, 05 NOT RECORDED — nobody opened the file
+ '2026-09-06': { n: { todo: 1 } },
+ }
+ doc.trail = trail
+
+ const s = slots(trail, '2026-09-01', '2026-09-06')
+ ok(s.length === 6, 'six days, six slots')
+ ok(s[2].kind === 'gap' && s[3].kind === 'gap' && s[4].kind === 'gap', 'the three unrecorded days are gaps')
+ ok(s[2].row === undefined, 'a gap carries no row — there is nothing to carry')
+ ok(s[0].kind === 'day' && s[0].anchor, 'an observed day is a day')
+
+ const period = { label: 'Sprint', from: '2026-09-01', to: '2026-09-06' }
+ // today is AFTER the window, so nothing is derived live and the whole chart
+ // comes from the record
+ const data = chartData(doc, period, 'burndown', '2026-09-20')
+ ok(data.runs.length === 2, 'a gap BREAKS the line: two runs, not one')
+ ok(data.runs[0].length === 2 && data.runs[1].length === 1, 'two points before the gap, one after')
+ ok(data.gaps.length === 1 && data.gaps[0][0] === '2026-09-03' && data.gaps[0][1] === '2026-09-05',
+ 'the gap is reported as its own range, for the hatched band')
+
+ // THE FAILURE THIS RIG EXISTS FOR: an absent day must never become a zero.
+ const values = data.runs.flat().map((p) => p.v[0])
+ ok(!values.includes(0), 'no zero point was invented for an unrecorded day')
+ ok(values.length === 3, 'exactly three points — one per recorded day, none per gap')
+ ok(data.runs.every((r) => r.every((p) => p.kind === 'day')),
+ 'nothing was carried forward: every point is a day someone observed')
+
+ // ABSENT IS NOT ZERO, and they must be distinguishable
+ const withZero = { ...trail, '2026-09-04': { n: {} } as TrailRow }
+ const zdata = chartData(docOf(doc.pages, { trail: withZero }), period, 'burndown', '2026-09-20')
+ ok(zdata.runs.flat().some((p) => p.v[0] === 0), 'a day with nothing open IS a point at zero')
+ ok(zdata.gaps.length === 2, 'and the days either side of it are still two separate gaps')
+}
+
+// ---------------------------------------------------------------------------
+// 7. THINNED ROWS ARE A THIRD STATE
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ const trail: Trail = {
+ '2026-09-01': { n: { todo: 9 } },
+ '2026-09-08': { n: { todo: 5 }, s: 8 }, // stands for 09-01..09-08
+ '2026-09-09': { n: { todo: 4 } },
+ }
+ doc.trail = trail
+ const s = slots(trail, '2026-09-01', '2026-09-09')
+ ok(s[1].kind === 'sample' && !s[1].anchor, 'a covered day is a sample, and not a point')
+ ok(s[7].kind === 'sample' && s[7].anchor, 'the sample row anchors on its own day')
+ ok(s.every((x) => x.kind !== 'gap'), 'a span covers its days: no gap inside it')
+ ok(s[0].anchor && s[0].kind === 'day', 'a span never buries a day that was observed in its own right')
+
+ const data = chartData(doc, { label: 's', from: '2026-09-01', to: '2026-09-09' }, 'burndown', '2026-09-30')
+ ok(data.runs.length === 1, 'a covered span does not break the line')
+ ok(data.runs[0].map((p) => p.kind).join(',') === 'day,sample,day',
+ 'the sample point is marked as one, so its segment can be drawn dashed')
+}
+
+// ---------------------------------------------------------------------------
+// 8. the budget — tiers, never fails, never averages
+// ---------------------------------------------------------------------------
+{
+ // THE TRAIL'S OWN CEILING, beside history's. 128 KB + 32 KB = the 160 KB
+ // joint ceiling that was ruled acceptable; each side tiers on its own.
+ ok(TRAIL_BUDGET === 32 * 1024, `TRAIL_BUDGET is 32 KB (${TRAIL_BUDGET} B)`)
+ ok(HISTORY_BUDGET + TRAIL_BUDGET <= 160 * 1024,
+ `history + trail ceilings sum to at most 160 KB (${(HISTORY_BUDGET + TRAIL_BUDGET) / 1024} KB)`)
+
+ // a year of daily rows, measured
+ //
+ // THE COUNTS VARY PER DAY, and that is not decoration. With a uniform
+ // fixture the "never averages" assertion below passes VACUOUSLY — the mean
+ // of two identical rows is that row — and this rig watched a deliberate
+ // averaging sabotage sail straight through it before the numbers were made
+ // to move. An assertion nobody has seen fail is not evidence.
+ const year: Trail = {}
+ for (let i = 0; i < 365; i++) {
+ year[addDays('2026-01-01', i)] = {
+ n: { backlog: 12 + (i % 7), todo: 9 + (i % 5), doing: 4 + (i % 3), review: 2, done: 31 + i, cancelled: 3 },
+ e: { backlog: 40 + i, todo: 27 + (i % 11), doing: 13, review: 5, done: 96 + i, cancelled: 8 },
+ x: 4,
+ }
+ }
+ const yearBytes = JSON.stringify(year).length
+ console.log(` · a year of full daily rows: ${yearBytes} bytes (${(yearBytes / 1024).toFixed(1)} KB), ` +
+ `${Math.round(yearBytes / 365)} bytes/row`)
+ const countOnly: Trail = {}
+ for (const k of Object.keys(year)) countOnly[k] = { n: year[k].n }
+ console.log(` · counts only: ${JSON.stringify(countOnly).length} bytes ` +
+ `(${(JSON.stringify(countOnly).length / 1024).toFixed(1)} KB)`)
+
+ // TIERING: over the allowance, resolution goes from the distant past first.
+ const pruned = pruneTrail(year, 20 * 1024)
+ ok(JSON.stringify(pruned).length <= 20 * 1024, 'pruning brings the trail under its allowance')
+ ok(Object.keys(pruned).length > 0, 'and it tiers rather than failing to nothing')
+ ok(Object.keys(pruned).length < 365, 'rows were dropped')
+
+ // NEVER AVERAGES: every surviving row's counts equal some original row's.
+ const originals = new Set(Object.values(year).map((r) => JSON.stringify(r.n)))
+ const invented = Object.values(pruned).filter((r) => !originals.has(JSON.stringify(r.n)))
+ ok(invented.length === 0, 'every surviving row is an observation somebody made, never an average')
+
+ // the dropped-from-the-front flag
+ ok(wasCut(pruned), 'the oldest survivor is stamped cut, so the chart says "recording starts here"')
+ const cutCount = Object.values(pruned).filter((r) => r.cut).length
+ ok(cutCount === 1, 'exactly one row carries it')
+
+ // spans are stamped and are truthful: a row never claims to cover a day
+ // before the earliest row it replaced
+ const kept = seriesRows(pruned)
+ let truthful = true
+ for (let i = 1; i < kept.length; i++) {
+ const back = spanOf(kept[i].row) - 1
+ if (daysBetween(kept[i - 1].day, kept[i].day) < back) truthful = false
+ }
+ ok(truthful, 'no span reaches back over another surviving row')
+
+ // MONOTONIC: a tighter allowance is never bigger
+ const sizes = [40 * 1024, 20 * 1024, 8 * 1024, 2 * 1024]
+ .map((b) => JSON.stringify(pruneTrail(year, b)).length)
+ ok(sizes.every((v, i) => i === 0 || v <= sizes[i - 1]), 'a tighter allowance never produces a bigger trail')
+
+ // THE ROW CAP
+ ok(Object.keys(pruneTrail(year, 10 * 1024 * 1024, 30)).length <= 30, 'the row cap holds however roomy the budget')
+ ok(TRAIL_MAX === 400, 'and the default cap is 400 rows')
+
+ // A LIVE PERIOD IS NOT THINNED UNDERNEATH ITSELF
+ const live = new Set(dayRange('2026-12-01', '2026-12-31'))
+ const guarded = pruneTrail(year, 4 * 1024, TRAIL_MAX, (d) => live.has(d))
+ const keptLive = Object.keys(guarded).filter((k) => live.has(k))
+ ok(keptLive.length === 31, "every day of a running period survives, at full resolution")
+ ok(keptLive.every((k) => guarded[k].s === undefined), 'and none of them was turned into a sample')
+}
+
+// ---------------------------------------------------------------------------
+// 9. periods
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ const id = startPeriod(doc, 'pd-1', {
+ label: 'Sprint 12', from: '2026-09-07', to: '2026-09-20', today: '2026-09-11',
+ })
+ ok(id === 'pd-1', 'a period is committed under the id it was given')
+ const p = periodOf(doc, 'pd-1')!
+ ok(p.base!.n === 5, 'the baseline is a TOTAL, not a list of page ids')
+ ok(p.base!.e === 19, 'and the summed estimate')
+ ok(p.base!.at === '2026-09-11', 'base.at records the day the baseline was ACTUALLY taken')
+ ok(JSON.stringify(p).indexOf('i1') < 0, 'no page id appears anywhere in a period')
+ ok(trailOf(doc)['2026-09-11'] !== undefined, "committing inside the window writes today's row")
+ ok(trailOf(doc)['2026-09-07'] === undefined, 'and fabricates no past key — the days before are gaps')
+
+ // malformed periods are not periods
+ ok(startPeriod(doc, 'pd-x', { label: 'x', from: '2026-09-20', to: '2026-09-07', today: '2026-09-11' }) === null,
+ 'a period whose `to` precedes its `from` is refused')
+ ok(!isPeriod({ label: 'x', from: '2026-13-99', to: '2026-09-07' }), 'and one with a non-date is not a period')
+ ok(!isPeriod(null) && !isPeriod('x') && !isPeriod([]), 'neither is anything that is not an object')
+ const junk = docOf([], { periods: { bad: { from: '2026-09-20', to: '2026-09-01', label: 'x' } } as never })
+ ok(Object.keys(periodsOf(junk)).length === 0, 'an unreadable period is simply not returned')
+ ok(junk.periods !== undefined, 'and is left in the file untouched')
+
+ ok(isLive(p, '2026-09-25'), 'a period is live while it runs')
+ ok(isLive(p, '2026-10-10'), 'and for thirty days after')
+ ok(!isLive(p, '2026-11-30'), 'and not forever')
+ closePeriod(doc, 'pd-1')
+ ok(!isLive(periodOf(doc, 'pd-1')!, '2026-09-08'), 'closing one ends it immediately')
+
+ const guard = protectedDays(doc, '2026-09-11')
+ ok(!guard('2026-09-08'), 'a closed period protects nothing')
+ startPeriod(doc, 'pd-2', { label: 'now', from: '2026-09-07', to: '2026-09-20', today: '2026-09-11' })
+ const guard2 = protectedDays(doc, '2026-09-11')
+ ok(guard2('2026-09-08') && !guard2('2026-08-08'), 'a live one protects its own window and nothing else')
+
+ removePeriod(doc, 'pd-1')
+ removePeriod(doc, 'pd-2')
+ ok(doc.periods === undefined, 'removing the last period deletes the key — never an empty object')
+}
+
+// ---------------------------------------------------------------------------
+// 10. the charts
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ const period = { label: 'S', from: '2026-09-01', to: '2026-09-10', base: { at: '2026-09-01', n: 5, e: 19 } }
+ doc.trail = {
+ '2026-09-01': { n: { todo: 3, done: 1 }, e: { todo: 10, done: 8 } },
+ '2026-09-02': { n: { todo: 2, done: 2 }, e: { todo: 6, done: 12 } },
+ }
+
+ const burn = chartData(doc, period, 'burndown', '2026-09-30')
+ ok(burn.units === 'points', 'rows carrying estimates are charted in points')
+ ok(burn.runs[0][0].v[0] === 10 && burn.runs[0][1].v[0] === 6, 'a burndown draws the OPEN work remaining')
+ ok(burn.ideal === 19, 'the ideal line starts at the committed baseline')
+ ok(burn.bands.length === 1, 'one line')
+
+ const up = chartData(doc, period, 'burnup', '2026-09-30')
+ ok(up.bands.length === 2, 'a burnup draws two lines')
+ ok(up.runs[0][0].v[0] === 8 && up.runs[0][0].v[1] === 18, 'completed, and total scope')
+ ok(up.committed?.v === 19 && up.committed.at === '2026-09-01', 'plus the committed scope, and when it was committed')
+
+ const cfd = chartData(doc, period, 'cfd', '2026-09-30')
+ ok(cfd.bands.length === 6, 'a CFD has a band per declared status option')
+ ok(cfd.bands.map((b) => b.id).join(',') === 'backlog,todo,doing,review,done,cancelled',
+ 'in the schema order the board declares')
+ ok(cfd.runs[0][0].v[cfd.bands.findIndex((b) => b.id === 'todo')] === 10, 'each band carries its own option')
+
+ // counts, when nothing is estimated
+ const plain = docOf(doc.pages, { trail: { '2026-09-01': { n: { todo: 3, done: 1 } } } })
+ ok(chartData(plain, period, 'burndown', '2026-09-30').units === 'issues',
+ 'rows with no estimates are charted as issue counts')
+
+ // AN OPTION THE SCHEMA NO LONGER DECLARES
+ const drifted = docOf(doc.pages, { trail: { '2026-09-01': { n: { blocked: 2 } } } })
+ const d = chartData(drifted, period, 'cfd', '2026-09-30')
+ ok(d.bands.some((b) => b.unknown && b.id === 'blocked'), 'a band whose option is gone is kept and marked unknown')
+
+ // TODAY IS DERIVED, NOT READ
+ const live = tracker()
+ live.trail = { '2026-09-11': { n: { todo: 999 }, e: { todo: 999 } } }
+ const before = chartData(live, { label: 'S', from: '2026-09-10', to: '2026-09-12' }, 'burndown', '2026-09-11')
+ const todayPoint = before.runs.flat().find((p) => p.day === '2026-09-11')!
+ ok(todayPoint.live === true, "today's point is marked derived")
+ ok(todayPoint.v[0] === 10, 'and it is counted from live state, not read from the stored 999')
+ ;(live.pages[0].blocks[1] as { value: number }).value = 100
+ const after = chartData(live, { label: 'S', from: '2026-09-10', to: '2026-09-12' }, 'burndown', '2026-09-11')
+ ok(after.runs.flat().find((p) => p.day === '2026-09-11')!.v[0] === 107,
+ 'change an estimate now and today moves immediately — the falsifiable half of the rule')
+
+ // the future is not drawn
+ ok(!after.runs.flat().some((p) => p.day > '2026-09-11'), 'a burndown does not draw the future')
+
+ // a period whose window holds nothing
+ const empty = chartData(tracker(), { label: 'S', from: '2026-01-01', to: '2026-01-10' }, 'burndown', '2026-09-11')
+ ok(empty.empty === true, 'a window with no observation says so instead of drawing an empty graph')
+
+ // MALFORMED ROWS MUST NOT THROW AND MUST NOT MISLEAD
+ const nasty = docOf(doc.pages, {
+ trail: {
+ '2026-09-01': { n: { todo: -5, doing: NaN as never, done: 'x' as never } },
+ '2026-09-02': { n: { todo: 2 }, s: -3 },
+ },
+ })
+ let threw = false
+ let nastyData: ReturnType<typeof chartData> | null = null
+ try { nastyData = chartData(nasty, period, 'cfd', '2026-09-30') } catch { threw = true }
+ ok(!threw, 'negative, NaN and non-numeric counts do not throw')
+ ok(nastyData!.runs.flat().every((p) => p.v.every((v) => Number.isFinite(v) && v >= 0)),
+ 'and none of them draws a misleading value')
+ ok(countOf({ n: { todo: -5 } }, 'todo') === 0, 'a negative count reads as zero')
+ ok(countOf({ n: {} }, 'toString') === 0, 'a prototype key is not a count')
+
+ ok(CHART_KINDS.length === 3 && chartKind('nonsense') === 'burndown', 'an unknown kind falls back rather than blanking')
+ ok(SPEC.get('chart')?.custom === true, 'the chart block is registered and renders custom')
+ ok(SPEC.get('chart')?.text !== true, "and carries no inline host — its html is the readable fallback")
+}
+
+// ---------------------------------------------------------------------------
+// 11. additivity — a round trip changes nothing
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ recordTrail(doc, { today: '2026-09-11' })
+ startPeriod(doc, 'pd-1', { label: 'S', from: '2026-09-01', to: '2026-09-20', today: '2026-09-11' })
+ // a field from a NEWER build, inside a row
+ ;(trailOf(doc)['2026-09-11'] as Record<string, unknown>).futureThing = { deep: [1, 2] }
+
+ const json = JSON.stringify(doc)
+ const res = parseDoc(json)
+ ok(res.ok, 'a trail-carrying document parses')
+ if (res.ok) {
+ ok(JSON.stringify(res.doc.trail) === JSON.stringify(doc.trail), 'the trail round-trips byte-identically')
+ ok(JSON.stringify(res.doc.periods) === JSON.stringify(doc.periods), 'and so do the periods')
+ ok(JSON.stringify((res.doc.trail as Trail)['2026-09-11']).includes('futureThing'),
+ 'including a row field this build has never heard of')
+ }
+
+ // THE DOTTED-KEY HAZARD, and its fold — for `periods`, the one doc-level
+ // map spaces declares. `trail` is not a map and never synced, so no peer can
+ // ever send `trail.<day>`; a literal key of that name is an unknown field
+ // like any other and is left exactly where it is.
+ const damaged = JSON.parse(json) as Record<string, unknown>
+ damaged['periods.pd-2'] = { label: 'from an older peer', from: '2026-09-01', to: '2026-09-02' }
+ damaged['trail.2026-09-10'] = { n: { todo: 7 } }
+ damaged['not.a.map'] = 'left alone'
+ const folded = parseDoc(JSON.stringify(damaged))
+ ok(folded.ok, 'a document damaged by an older peer still parses')
+ if (folded.ok) {
+ ok(periodOf(folded.doc, 'pd-2')?.label === 'from an older peer', 'the dotted periods key is folded back into the map')
+ ok(folded.doc['periods.pd-2'] === undefined, 'and the junk key is gone')
+ ok(folded.doc['trail.2026-09-10'] !== undefined && trailOf(folded.doc)['2026-09-10'] === undefined,
+ 'a dotted trail key is NOT folded — trail is not a synced map')
+ ok(folded.doc['not.a.map'] === 'left alone', 'a dotted key that is not a declared map is untouched')
+ }
+ // the fold never clobbers
+ const both = { periods: { 'pd-1': { label: 'placed' } }, 'periods.pd-1': { label: 'stray' } } as Record<string, unknown>
+ foldDottedMapKeys(both)
+ ok((both.periods as Record<string, { label: string }>)['pd-1'].label === 'placed',
+ 'a folded key never overwrites one already in place')
+ // nor overwrites a `periods` some newer build gave another shape
+ const foreign = { periods: 'a newer shape', 'periods.pd-1': { label: 'stray' } } as Record<string, unknown>
+ foldDottedMapKeys(foreign)
+ ok(foreign.periods === 'a newer shape' && foreign['periods.pd-1'] !== undefined,
+ 'a foreign periods value is never folded over')
+
+ // THE SHAPE: periods per key, trail not at all
+ ok(DOC_MAPS.length === 1 && DOC_MAPS[0] === 'periods', 'DOC_MAPS is exactly [periods]')
+ ok(SPACES_SHAPE.maps.has('periods') && !SPACES_SHAPE.maps.has('trail'),
+ 'the sync shape merges periods per key, and does not map trail')
+ ok(SPACES_SHAPE.skipDoc.has('trail') && SPACES_SHAPE.skipDoc.has('revisions'),
+ 'the sync shape skips trail (and revisions) outright')
+ ok(SPACES_SHAPE.maps.has('assets'), 'and still declares the maps it always did')
+}
+
+// ---------------------------------------------------------------------------
+// 12. clearing and stripping
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ recordTrail(doc, { today: '2026-09-11' })
+ clearTrail(doc)
+ ok(doc.trail === undefined, 'clearing deletes the key — never trail: {}')
+ ok(!('trail' in doc), 'a cleared space is byte-identical to one that never recorded')
+
+ // THE CLASSES. No builder strips the trail by hand: the kernel's copy table
+ // does, from the field map (scripts/test-spaces-copytiers.ts holds every
+ // tier and sweeps the builders for hand strips).
+ ok(SPACES_FIELDS.trail === 'history', 'trail is classed history')
+ ok(SPACES_FIELDS.periods === 'content', 'periods is classed content')
+ ok(!SPACES_NOT_EDIT.has('trail'), 'trail is NOT in SPACES_NOT_EDIT: it is written while editing')
+
+ const shared = tracker()
+ recordTrail(shared, { today: '2026-09-11' })
+ startPeriod(shared, 'pd-1', { label: 'S', from: '2026-09-01', to: '2026-09-20', today: '2026-09-11' })
+ const copy = docForExport(shared)
+ ok(copy.trail === undefined, 'Copy document JSON carries no trail')
+ ok(copy.periods !== undefined, 'but keeps the periods — content the chart blocks name')
+ ok(shared.trail !== undefined, 'and the original is untouched')
+
+ // the page extract drops the history class too
+ const ex = extractSpace(shared, shared.pages[0].id, { docId: 'doc-x', subtree: false, now: '2026-09-11T00:00:00Z' })
+ ok(ex.doc.trail === undefined, 'a page extract carries no trail')
+}
+
+// ---------------------------------------------------------------------------
+// 13. two replicas, one day
+// ---------------------------------------------------------------------------
+{
+ const base = tracker()
+ recordTrail(base, { today: '2026-09-09' })
+ const json = JSON.stringify(base)
+
+ const a = new SyncState('actor-a')
+ const b = new SyncState('actor-b')
+ const docA = JSON.parse(json) as SpacesDoc
+ const docB = JSON.parse(json) as SpacesDoc
+ a.adopt(docA as never)
+ b.adopt(docB as never)
+
+ // A TRAIL ROW MINTS NO OPS. Each replica keeps its own record of what it saw.
+ const beforeA = JSON.parse(JSON.stringify(docA)) as SpacesDoc
+ recordTrail(docA, { today: '2026-09-10' })
+ const opsA = a.diff(beforeA as never, docA as never)
+ ok(opsA.length === 0, `a trail-only change diffs to zero ops (${opsA.length})`)
+ b.apply(docB as never, opsA)
+ ok(trailOf(docB)['2026-09-10'] === undefined, "and B's file never receives A's row")
+
+ // a content edit beside a trail row: only the content travels
+ const before2A = JSON.parse(JSON.stringify(docA)) as SpacesDoc
+ ;(docA.pages[0].blocks[0] as { value: string }).value = 'done'
+ recordTrail(docA, { today: '2026-09-11' })
+ const ops2A = a.diff(before2A as never, docA as never)
+ ok(ops2A.length > 0 && ops2A.every((o) => !JSON.stringify(o).includes('2026-09-11')),
+ 'an edit syncs; the row recorded beside it does not')
+ b.apply(docB as never, ops2A)
+ ok((docB.pages[0].blocks[0] as { value: string }).value === 'done', 'B has the edit')
+ ok(trailOf(docB)['2026-09-11'] === undefined, 'and not the row')
+
+ // PERIODS ARE A PER-KEY MAP: two people starting different periods both keep theirs
+ const bpA = JSON.parse(JSON.stringify(docA)) as SpacesDoc
+ startPeriod(docA, 'pd-a', { label: 'A', from: '2026-09-11', to: '2026-09-24', today: '2026-09-11' })
+ const pA = a.diff(bpA as never, docA as never)
+ const bpB = JSON.parse(JSON.stringify(docB)) as SpacesDoc
+ startPeriod(docB, 'pd-b', { label: 'B', from: '2026-09-11', to: '2026-09-24', today: '2026-09-11' })
+ const pB = b.diff(bpB as never, docB as never)
+ a.apply(docA as never, pB)
+ b.apply(docB as never, pA)
+ ok(periodOf(docA, 'pd-a') !== undefined && periodOf(docA, 'pd-b') !== undefined, 'concurrent periods: both survive on A')
+ ok(periodOf(docB, 'pd-a') !== undefined && periodOf(docB, 'pd-b') !== undefined, 'and on B — per key, not one register')
+ ok(pA.every((o) => !JSON.stringify(o).includes('"trail')), "the period's backfilled row did not ride along")
+}
+
+// ---------------------------------------------------------------------------
+// 14. undo — a record is not an editing step, a period is
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ const store = new Store(doc)
+ store.checkpoint()
+
+ // a row written OUTSIDE a commit, the way the autosave debounce writes it
+ recordTrail(store.doc, { today: '2026-09-11' })
+ ok(trailOf(store.doc)['2026-09-11'] !== undefined, 'a row lands outside any commit')
+
+ store.commit(() => { store.doc.title = 'Renamed' })
+ recordTrail(store.doc, { today: '2026-09-12' })
+ store.undo()
+ ok(store.doc.title === 'Rig space', 'undo takes back the edit')
+ ok(trailOf(store.doc)['2026-09-11'] !== undefined && trailOf(store.doc)['2026-09-12'] !== undefined,
+ 'and takes back NEITHER row — a record is not an editing step')
+
+ // A PERIOD IS one. It is authored, inside a commit, and ⌘Z must reach it.
+ store.commit(() => {
+ startPeriod(store.doc, 'pd-undo', { label: 'S', from: '2026-09-11', to: '2026-09-24', today: '2026-09-11' })
+ })
+ ok(periodOf(store.doc, 'pd-undo') !== undefined, 'starting a period is a commit')
+ store.undo()
+ ok(periodOf(store.doc, 'pd-undo') === undefined, 'and ⌘Z takes it back, like any other edit')
+ ok(trailOf(store.doc)['2026-09-11'] !== undefined, 'while the rows it wrote stand')
+
+ // REDO keeps the live trail too
+ store.redo()
+ ok(periodOf(store.doc, 'pd-undo') !== undefined, 'redo brings the period back')
+ recordTrail(store.doc, { today: '2026-09-13' })
+ store.undo(); store.redo()
+ ok(trailOf(store.doc)['2026-09-13'] !== undefined, 'a row recorded after a redo survives another undo/redo')
+
+ // REPLACE FROM JSON with Copy document JSON's output (which drops trail by the
+ // copy table) must not wipe the trail
+ const rows = Object.keys(trailOf(store.doc)).sort().join(',')
+ const pasted = docForExport(store.doc)
+ ok(pasted.trail === undefined, 'Copy document JSON carries no trail')
+ store.replaceDoc(JSON.parse(JSON.stringify(pasted)) as SpacesDoc)
+ ok(Object.keys(trailOf(store.doc)).sort().join(',') === rows,
+ 'replaceDoc keeps the LIVE trail — Replace from JSON does not wipe it')
+ // and a pasted doc carrying a DIFFERENT trail cannot overwrite the live one
+ const forged = JSON.parse(JSON.stringify(store.doc)) as SpacesDoc
+ forged.trail = { '2020-01-01': { n: { todo: 999 } } }
+ store.replaceDoc(forged)
+ ok(trailOf(store.doc)['2020-01-01'] === undefined && Object.keys(trailOf(store.doc)).sort().join(',') === rows,
+ 'a restored or pasted trail never replaces the live record')
+}
+
+// ---------------------------------------------------------------------------
+// 14b. the recovery key — a row recorded while editing is unsaved work
+// ---------------------------------------------------------------------------
+{
+ const doc = tracker()
+ const before = docContentKey(doc)
+ recordTrail(doc, { today: '2026-09-11' })
+ ok(docContentKey(doc) !== before, 'an edit-time trail row raises the recovery key')
+ // a row change on its own — no content edit beside it — still moves the key
+ const k1 = docContentKey(doc)
+ writeRow(doc, '2026-09-11', { n: { todo: 1 } })
+ ok(docContentKey(doc) !== k1, 'a trail change alone moves the recovery key')
+ const same = JSON.parse(JSON.stringify(doc)) as SpacesDoc
+ ok(docContentKey(same) === docContentKey(doc), 'an identical document keys identically')
+}
+
+// ---------------------------------------------------------------------------
+// 15. the joint ceiling — history and trail, both at their budgets
+// ---------------------------------------------------------------------------
+{
+ // A REAL fixture, not arithmetic on the constants: a tracker saved many
+ // times with large paragraph rewrites (history.ts tiers it to HISTORY_BUDGET)
+ // and recorded every day for well over a year (trail.ts tiers it to
+ // TRAIL_BUDGET). The record the file carries about itself must stay inside
+ // the 160 KB that was ruled acceptable.
+ const doc = tracker()
+ doc.pages[0].blocks.push({ id: 'para', type: 'p', html: 'start' } as never)
+ const statuses = ['todo', 'doing', 'review', 'done']
+ for (let i = 0; i < 500; i++) {
+ const day = addDays('2025-06-01', i)
+ for (let j = 0; j < doc.pages.length; j++) {
+ ;(doc.pages[j].blocks[0] as { value: string }).value = statuses[(i + j) % statuses.length]
+ const est = doc.pages[j].blocks.find((b) => (b as { key?: string }).key === 'estimate')
+ if (est) (est as { value: number }).value = 1 + ((i * 7 + j) % 13)
+ }
+ ;(doc.pages[0].blocks.find((b) => b.id === 'para') as { html: string }).html =
+ `day ${i}: ` + Array.from({ length: 160 }, (_, w) => `word${(i * 31 + w) % 997}`).join(' ')
+ recordTrail(doc, { today: day })
+ recordRevision(doc)
+ }
+ const hb = historyBytes(doc)
+ const tb = trailBytes(doc)
+ console.log(` · after 500 days: history ${(hb / 1024).toFixed(1)} KB, trail ${(tb / 1024).toFixed(1)} KB, ` +
+ `${Object.keys(trailOf(doc)).length} rows`)
+ ok(hb <= HISTORY_BUDGET, `history stays within HISTORY_BUDGET (${hb} B)`)
+ ok(tb <= TRAIL_BUDGET, `the trail stays within TRAIL_BUDGET (${tb} B)`)
+ ok(hb + tb <= 160 * 1024, `history + trail stay within the 160 KB joint ceiling (${((hb + tb) / 1024).toFixed(1)} KB)`)
+ ok(hb > HISTORY_BUDGET * 0.5 && tb > TRAIL_BUDGET * 0.5,
+ 'and both actually used their budgets, so the ceiling was exercised')
+ ok(wasCut(trailOf(doc)) || Object.values(trailOf(doc)).some((r) => (r.s ?? 1) > 1),
+ 'the trail tiered (thinned or cut) to get there rather than failing')
+}
+
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjs
index 14b618d5..86bab225 100755
--- a/scripts/test-spaces.mjs
+++ b/scripts/test-spaces.mjs
@@ -45,6 +45,10 @@ const esbuild = join(root, 'slides/node_modules/.bin/esbuild')
// implementation from a broken one.
const TZS_JOURNAL = ['UTC', 'Europe/Berlin', 'America/Los_Angeles', 'Pacific/Kiritimati', 'Pacific/Niue', 'Australia/Lord_Howe']
const TZS_CALC = ['UTC', 'Europe/Berlin', 'America/Los_Angeles', 'Pacific/Kiritimati']
+// The trail's key is a LOCAL day. Kiritimati (UTC+14) and Niue (UTC-11) bracket
+// every hour where "which day is it" has two answers, which is the whole bug
+// class here.
+const TZS_TRAIL = ['UTC', 'Europe/Berlin', 'Pacific/Kiritimati', 'Pacific/Niue']
const RIGS = [
// The model rig carries the CALENDAR layout's arithmetic now — month grids,
@@ -62,6 +66,7 @@ const RIGS = [
// exactly what a one-timezone run cannot see.
{ name: 'gantt', file: 'scripts/test-spaces-gantt.ts', tzs: TZS_JOURNAL },
{ name: 'caret', file: 'scripts/test-spaces-caret.ts' },
+ { name: 'trail', file: 'scripts/test-spaces-trail.ts', tzs: TZS_TRAIL, bundle: true },
{ name: 'undo', file: 'scripts/test-spaces-undo.ts', bundle: true },
{ name: 'invite', file: 'scripts/test-spaces-invite.ts', bundle: true },
{ name: 'copytiers', file: 'scripts/test-spaces-copytiers.ts', bundle: true },
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index 1103dd2c..b62df520 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -1316,6 +1316,21 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
Pasting document JSON over the space no longer touches the history, and
neither does undo.
+- **Burndown, burnup and cumulative flow.** A tracker could always say what is
+ open today and never what was open last Tuesday. Now the space keeps a small
+ record of itself, one row of counts per day you work in it, and a new
+ **Chart of progress** block (Insert → View ▾) draws it over a period —
+ "New two-week period from today" starts one and records the scope as it
+ stands. A day nobody worked in the file is drawn as a gap, labelled *Not
+ recorded*, never filled in; a thinned older reading draws dashed. Today's
+ point always comes from the issues as they are now, and editing them never
+ rewrites an earlier day. The record holds counts only — no page names, no
+ people — and it is written while you edit, never when you merely open the
+ file. It is capped at 32 KB beside history's 128 KB; past that the oldest
+ days thin to weekly, then monthly. Like version history it stays with your
+ own copies and invites, and leaves reading copies, view-only copies, Copy
+ document JSON and exported pages; each collaborator's file keeps its own.
+ ⌘Z never erases it, and neither does pasting document JSON.
- **Invites say they carry the history, and can leave it out.** When a space
has version history, **Share → Invite to edit…** now asks first: "This copy
includes the space’s version history." Ticking **Leave version history out**
diff --git a/spaces/src/blocks.ts b/spaces/src/blocks.ts
index c3249eeb..58e1b02f 100644
--- a/spaces/src/blocks.ts
+++ b/spaces/src/blocks.ts
@@ -412,6 +412,29 @@ export const SPECS: BlockSpec[] = [
return [...out, '```']
},
},
+ {
+ // A CHART OF THE TRAIL — burndown, burnup, cumulative flow.
+ //
+ // NOT A `view` LAYOUT, and the distinction is the rule rather than a filing
+ // preference: THE HOST FOLLOWS THE DATA SOURCE. A view reads pages live, so
+ // `source`/`filter`/`sort` genuinely narrow it at read time. These read
+ // `doc.trail`, whose rows are counts written at aggregation time — the
+ // pages that made a stored 47 are deliberately not in the record, so a
+ // `filter` key here would look like it narrowed the chart and silently
+ // would not. What DOES narrow it is frozen onto the period at commit
+ // (src/charts.ts).
+ //
+ // `text: false` and a readable `html`: the block carries its own sentence
+ // — "Burndown — Sprint 12 (1–14 Sept)" — which is what an older build, a
+ // grep, a markdown export and the static preview see. Same degradation rule
+ // every `prop` block follows.
+ type: 'chart', label: 'Chart of progress', hint: 'Burndown, burnup or cumulative flow', icon: 'board',
+ tag: 'div', custom: true,
+ init: (b) => { if (b.kind === undefined) b.kind = 'burndown' },
+ // MARKDOWN HAS NO CHART, and the honest export is the sentence the block
+ // already carries rather than a picture-shaped thing that is not a picture.
+ toMd: (_b, text) => [`**${text || 'Chart'}**`],
+ },
{
// A SPATIAL SURFACE — a storyboard, a roadmap, a mind map. Its cards are
// the blocks whose `parent` is its id, exactly like a callout's body, and
diff --git a/spaces/src/charts.ts b/spaces/src/charts.ts
new file mode 100644
index 00000000..d21ce203
--- /dev/null
+++ b/spaces/src/charts.ts
@@ -0,0 +1,769 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// BURNDOWN, BURNUP AND CUMULATIVE FLOW — charts of the trail.
+//
+// WHY THESE ARE A `chart` BLOCK AND NOT A `view` LAYOUT. Gantt and workload are
+// view layouts and that is right: they read the pages LIVE, and `source`,
+// `filter`, `sort` and `groupBy` genuinely narrow them at read time. These
+// three are different in kind. They read `doc.trail`, whose rows are counts
+// written at aggregation time — you cannot retroactively filter "project =
+// Apollo" out of a stored count of 47, because the pages that made it are
+// deliberately not in the record. A view layout would therefore give them
+// `source` and `filter` keys that LOOK like they narrow the chart and silently
+// do not, which is the exact failure mode this codebase keeps hitting.
+//
+// THE HOST FOLLOWS THE DATA SOURCE.
+// Charts of pages are view layouts. Charts of the trail are chart blocks.
+//
+// The scope a trail chart IS narrowed by is frozen onto its PERIOD at commit
+// time, where it cannot be edited into a lie afterwards.
+//
+// WHY THIS DRAWS ITS OWN SVG RATHER THAN CALLING `kernel/src/charts.ts`. That
+// was the intended host and it was read first. Charts-lite interprets the
+// ECharts option SHAPE but implements a subset, and three things these charts
+// are ABOUT are outside it — measured against the source, not assumed:
+//
+// 1. A GAP WOULD DRAW AS ZERO. `renderCartesian` maps every datum through
+// `num(v, 0)`, so an absent day is a point at the origin. "Absent must
+// look different from zero" is the load-bearing requirement here, and the
+// one engine we have coerces one into the other.
+// 2. NO STACKING. There is no `stack` support anywhere in the file, and a
+// cumulative flow diagram is stacked bands by definition.
+// 3. NO PER-SEGMENT LINE STYLE. `stroke-dasharray` is set only to animate a
+// sweep, so a thinned weekly sample could not be drawn as a dashed
+// segment and would be indistinguishable from a daily reading.
+//
+// Kernel is a serialized zone and this is not a kernel change; the honest
+// answer was to draw these three in the app that needs them, exactly as
+// `graph.ts` already draws the graph view rather than shipping d3. The
+// arithmetic below is about a hundred lines, and the parts that matter — where
+// a gap is, what a sample covers — are pure functions with a rig on them.
+
+import type { SpacesDoc } from './model'
+import { t, locale } from './i18n.ts'
+import { phaseField, type FieldOption } from './fields.ts'
+import { observe } from './observe.ts'
+import { periodOf, periodList, scopeOf, startPeriod, type Period } from './periods.ts'
+import { row, type Menu } from './menus.ts'
+import {
+ slots, seriesRows, wasCut, countOf, estimateOf, hasEstimates,
+ isDay, daysBetween, addDays, type Trail, trailOf,
+} from './trail.ts'
+
+export const CHART_KINDS = ['burndown', 'burnup', 'cfd'] as const
+export type ChartKind = (typeof CHART_KINDS)[number]
+
+export const chartKind = (raw: unknown): ChartKind => {
+ const s = String(raw ?? 'burndown')
+ return (CHART_KINDS as readonly string[]).includes(s) ? (s as ChartKind) : 'burndown'
+}
+
+/** What each kind is called. A function with literal t() calls, never a map
+ * read back through t(MAP[k]) — the extractor sweeps LITERALS, and the packer
+ * would still report 100% while shipping English (fields.ts learned this). */
+export function chartKindLabel(kind: ChartKind): string {
+ switch (kind) {
+ case 'burnup': return t('Burnup')
+ case 'cfd': return t('Cumulative flow')
+ default: return t('Burndown')
+ }
+}
+
+// ---- the data --------------------------------------------------------------
+
+/** One stacked band or one line. */
+export interface Band {
+ id: string
+ label: string
+ color: string
+ /** an option id no schema in this document declares */
+ unknown?: boolean
+}
+
+/** One drawn point. `sample` means it stands for more than the day it sits on. */
+export interface Point {
+ day: string
+ kind: 'day' | 'sample'
+ /** one value per band, in band order */
+ v: number[]
+ /** derived from live state rather than read from the trail */
+ live?: boolean
+}
+
+export interface ChartData {
+ kind: ChartKind
+ from: string
+ to: string
+ bands: Band[]
+ /** contiguous runs of points; the space BETWEEN two runs is a gap */
+ runs: Point[][]
+ /** day ranges with no observation at all, inclusive, in order */
+ gaps: Array<[string, string]>
+ /** the burndown guide: full at `from`, zero at `to` */
+ ideal?: number
+ /** the burnup's committed scope, and the day it was committed */
+ committed?: { v: number; at: string }
+ /** older rows were dropped: the left edge is "recording starts here" */
+ cut: boolean
+ /** issues with no estimate on the most recent point */
+ unestimated: number
+ /** whether the numbers are summed estimates or issue counts */
+ units: 'points' | 'issues'
+ /** is there anything to draw at all? */
+ empty: boolean
+}
+
+const OPEN = (o: FieldOption | undefined): boolean =>
+ o?.group !== 'done' && o?.group !== 'cancelled'
+
+const UNKNOWN_COLOR = '#98A2B3'
+
+/**
+ * The status options in force, as bands.
+ *
+ * Option ids appearing in the trail that the schema no longer declares are kept
+ * and marked unknown — the rule `ViewFilter` states for a value this build does
+ * not know: carry it literally rather than match nothing. An option deleted
+ * next month must not silently delete a band out of last month's chart.
+ */
+function optionBands(doc: SpacesDoc, seen: Set<string>): Band[] {
+ const pf = phaseField(doc)
+ const declared = pf?.options ?? []
+ const bands: Band[] = []
+ const used = new Set<string>()
+ for (const o of declared) {
+ if (!o || typeof o.id !== 'string') continue
+ used.add(o.id)
+ bands.push({ id: o.id, label: String(o.label ?? o.id), color: String(o.color ?? UNKNOWN_COLOR) })
+ }
+ for (const id of [...seen].sort()) {
+ if (used.has(id)) continue
+ bands.push({
+ id,
+ label: id ? t('{id} (unknown)', { id }) : t('No status'),
+ color: UNKNOWN_COLOR,
+ unknown: true,
+ })
+ }
+ return bands
+}
+
+const optionById = (doc: SpacesDoc, id: string): FieldOption | undefined =>
+ phaseField(doc)?.options?.find((o) => o?.id === id)
+
+/**
+ * The points, the runs and the gaps for one period.
+ *
+ * TODAY IS DERIVED, EVERY OTHER DAY IS READ. The falsifiable half of the
+ * derivation rule: change an estimate now and today's point moves immediately,
+ * because it is counted from live state rather than read from a stored copy.
+ * Strictly-earlier days come from the trail, where there is nothing left to
+ * disagree with.
+ */
+export function chartData(doc: SpacesDoc, period: Period, kind: ChartKind, today: string): ChartData {
+ const series = typeof period.series === 'string' ? period.series : ''
+ const trail: Trail = trailOf(doc)
+
+ // the drawn window stops at today: a burndown does not draw the future.
+ const last = isDay(today) && daysBetween(today, period.to) > 0 ? today : period.to
+ const all = slots(trail, period.from, last, series)
+
+ // which option ids the window actually mentions
+ const seen = new Set<string>()
+ for (const s of all) if (s.row) for (const k of Object.keys(s.row.n ?? {})) seen.add(k)
+ const live = isDay(today) && daysBetween(period.from, today) >= 0 && daysBetween(today, period.to) >= 0
+ ? observe(doc, scopeOf(period))
+ : null
+ if (live) for (const k of Object.keys(live.n)) seen.add(k)
+
+ const options = optionBands(doc, seen)
+ const bands: Band[] =
+ kind === 'cfd' ? options
+ : kind === 'burnup'
+ ? [
+ { id: '#done', label: t('Completed'), color: '#2FA37C' },
+ { id: '#scope', label: t('Scope'), color: '#5B8DEF' },
+ ]
+ : [{ id: '#open', label: t('Remaining'), color: '#F7A600' }]
+
+ // POINTS MODE, decided once for the whole chart. A chart that switched
+ // between summed estimates and issue counts halfway along its own x axis
+ // would be two charts drawn on one pair of axes.
+ const rows = all.filter((s) => s.anchor && s.row).map((s) => s.row!)
+ const points = rows.length > 0 && rows.every(hasEstimates) && (!live || !!live.e)
+ const units: ChartData['units'] = points ? 'points' : 'issues'
+
+ const valueFor = (id: string, row: { n: Record<string, number>; e?: Record<string, number> }): number => {
+ if (points) {
+ const e = estimateOf(row as never, id)
+ return e ?? 0
+ }
+ return countOf(row as never, id)
+ }
+
+ const vector = (row: { n: Record<string, number>; e?: Record<string, number> }): number[] => {
+ if (kind === 'cfd') return bands.map((b) => valueFor(b.id, row))
+ let open = 0, done = 0
+ for (const id of Object.keys(row.n ?? {})) {
+ const v = valueFor(id, row)
+ if (OPEN(optionById(doc, id))) open += v
+ else done += v
+ }
+ if (kind === 'burnup') return [done, open + done]
+ return [open]
+ }
+
+ // ---- runs and gaps -------------------------------------------------------
+ const runs: Point[][] = []
+ const gaps: Array<[string, string]> = []
+ let run: Point[] = []
+ let gapFrom: string | null = null
+ const closeGap = (endDay: string) => {
+ if (gapFrom) { gaps.push([gapFrom, endDay]); gapFrom = null }
+ }
+ for (const s of all) {
+ if (s.kind === 'gap') {
+ if (run.length) { runs.push(run); run = [] }
+ gapFrom ??= s.day
+ continue
+ }
+ closeGap(addDays(s.day, -1))
+ if (!s.anchor) continue
+ run.push({ day: s.day, kind: s.kind === 'sample' ? 'sample' : 'day', v: vector(s.row!) })
+ }
+ if (gapFrom) gaps.push([gapFrom, all[all.length - 1]?.day ?? gapFrom])
+ if (run.length) runs.push(run)
+
+ // TODAY, derived. It replaces a trail row for the same day rather than
+ // sitting beside it — there is only one today.
+ if (live) {
+ const p: Point = { day: today, kind: 'day', v: vector(live), live: true }
+ const tail = runs[runs.length - 1]
+ if (tail && tail[tail.length - 1].day === today) tail[tail.length - 1] = p
+ else if (tail && daysBetween(tail[tail.length - 1].day, today) === 1) tail.push(p)
+ else runs.push([p])
+ // a live point ends any gap that was running up to today
+ if (gaps.length && gaps[gaps.length - 1][1] >= today) {
+ const g = gaps[gaps.length - 1]
+ if (g[0] >= today) gaps.pop()
+ else g[1] = addDays(today, -1)
+ }
+ }
+
+ // ---- the guides ----------------------------------------------------------
+ const first = runs[0]?.[0]
+ const base = period.base
+ let ideal: number | undefined
+ let committed: ChartData['committed']
+ if (kind === 'burndown') {
+ const start = points ? base?.e : base?.n
+ ideal = typeof start === 'number' && Number.isFinite(start) && start > 0
+ ? start
+ : first ? first.v[0] : undefined
+ }
+ if (kind === 'burnup' && base) {
+ const v = points ? base.e : base.n
+ if (typeof v === 'number' && Number.isFinite(v) && v >= 0) committed = { v, at: base.at }
+ }
+
+ const lastPoint = runs[runs.length - 1]?.slice(-1)[0]
+ const unestimated = lastPoint?.live
+ ? (live?.x ?? 0)
+ : (all.filter((s) => s.anchor && s.day === lastPoint?.day)[0]?.row?.x ?? 0)
+
+ return {
+ kind,
+ from: period.from,
+ to: period.to,
+ bands,
+ runs,
+ gaps,
+ ...(ideal !== undefined ? { ideal } : {}),
+ ...(committed ? { committed } : {}),
+ cut: wasCut(trail, series) && seriesRows(trail, series)[0]?.day >= period.from,
+ unestimated: typeof unestimated === 'number' && unestimated > 0 ? unestimated : 0,
+ units,
+ empty: !runs.length,
+ }
+}
+
+// ---- drawing ---------------------------------------------------------------
+
+const NS = 'http://www.w3.org/2000/svg'
+
+const el = <K extends keyof SVGElementTagNameMap>(
+ tag: K,
+ attrs: Record<string, string | number> = {},
+): SVGElementTagNameMap[K] => {
+ const n = document.createElementNS(NS, tag)
+ for (const k of Object.keys(attrs)) n.setAttribute(k, String(attrs[k]))
+ return n
+}
+
+/**
+ * A short day label — "6 Aug" — in the READER'S language.
+ *
+ * Through `Intl`, never a hand-written month table: the file is locale-neutral
+ * and the label is rendered, exactly as `journal.ts` renders its dates. The
+ * Date is built component-wise for the reason journal.ts states —
+ * `new Date('2026-08-06')` is UTC midnight, i.e. the previous day for every
+ * reader west of Greenwich.
+ */
+export function dayLabel(iso: string, loc?: string): string {
+ if (!isDay(iso)) return iso
+ const [y, m, d] = iso.split('-').map(Number)
+ try {
+ return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric' }).format(new Date(y, m - 1, d))
+ } catch {
+ return iso
+ }
+}
+
+function niceTop(max: number): { top: number; step: number } {
+ if (!(max > 0)) return { top: 1, step: 1 }
+ const raw = max / 4
+ const mag = Math.pow(10, Math.floor(Math.log10(raw)))
+ const step = [1, 2, 2.5, 5, 10].map((f) => f * mag).find((s) => s >= raw) ?? 10 * mag
+ return { top: Math.ceil(max / step) * step, step }
+}
+
+const W = 640
+const H = 300
+const PAD = { l: 44, r: 14, t: 14, b: 34 }
+
+let hatchSeq = 0
+
+export interface DrawOpts {
+ /** the reader's locale, for axis labels */
+ loc?: string
+}
+
+/**
+ * Draw one chart.
+ *
+ * The svg scales to its box (`viewBox` + `width: 100%`), so the same picture
+ * serves the editor, the reading view, the printed page and the file-manager
+ * still — one renderer, like everything else here.
+ *
+ * PATTERN IDS ARE DOCUMENT-GLOBAL. `url(#…)` resolves against the whole
+ * document, so two charts on one page sharing an id would paint each other's
+ * hatching. Every instance mints its own, the way slides mints per-instance
+ * gradient ids.
+ */
+export function drawChart(data: ChartData, opts: DrawOpts = {}): SVGSVGElement {
+ const loc = opts.loc ?? locale()
+ const svg = el('svg', {
+ viewBox: `0 0 ${W} ${H}`,
+ class: 'sp-chart-svg',
+ role: 'img',
+ preserveAspectRatio: 'xMidYMid meet',
+ })
+ svg.setAttribute('width', '100%')
+
+ const days = Math.max(1, daysBetween(data.from, data.to))
+ const x = (day: string) => PAD.l + (daysBetween(data.from, day) / days) * (W - PAD.l - PAD.r)
+
+ // the top of the value axis covers every drawn value, the ideal line and the
+ // committed line — a guide drawn off the top of its own chart is worse than
+ // no guide.
+ let max = 0
+ for (const run of data.runs) {
+ for (const p of run) {
+ const v = data.kind === 'cfd' ? p.v.reduce((a, b) => a + b, 0) : Math.max(...p.v)
+ if (v > max) max = v
+ }
+ }
+ if (data.ideal && data.ideal > max) max = data.ideal
+ if (data.committed && data.committed.v > max) max = data.committed.v
+ const { top, step } = niceTop(max)
+ const y = (v: number) => H - PAD.b - (v / top) * (H - PAD.t - PAD.b)
+
+ // ---- gridlines and axes --------------------------------------------------
+ for (let v = 0; v <= top + 1e-9; v += step) {
+ const gy = y(v)
+ svg.appendChild(el('line', {
+ x1: PAD.l, y1: gy, x2: W - PAD.r, y2: gy, class: 'sp-chart-grid',
+ }))
+ const label = el('text', { x: PAD.l - 6, y: gy + 4, class: 'sp-chart-axis', 'text-anchor': 'end' })
+ label.textContent = String(Math.round(v * 100) / 100)
+ svg.appendChild(label)
+ }
+
+ // x labels, thinned so they never collide
+ const every = Math.max(1, Math.ceil((days + 1) / 8))
+ for (let i = 0; i <= days; i += every) {
+ const day = addDays(data.from, i)
+ const label = el('text', { x: x(day), y: H - PAD.b + 16, class: 'sp-chart-axis', 'text-anchor': 'middle' })
+ label.textContent = dayLabel(day, loc)
+ svg.appendChild(label)
+ }
+
+ // ---- gaps, drawn as gaps -------------------------------------------------
+ //
+ // A HATCHED BAND, not a skipped day and not a zero. A chart that quietly
+ // steps over missing days implies a continuity it does not have, and a
+ // carried-forward value looks exactly like data. Weekends land here too,
+ // which is the other half of the argument against interpolating: an
+ // interpolated weekend shows work happening on Sunday.
+ if (data.gaps.length) {
+ const id = `sp-hatch-${++hatchSeq}`
+ const defs = el('defs')
+ const pat = el('pattern', {
+ id, width: 6, height: 6, patternUnits: 'userSpaceOnUse', patternTransform: 'rotate(45)',
+ })
+ pat.appendChild(el('line', { x1: 0, y1: 0, x2: 0, y2: 6, class: 'sp-chart-hatch' }))
+ defs.appendChild(pat)
+ svg.appendChild(defs)
+ for (const [a, b] of data.gaps) {
+ const x0 = x(a)
+ const x1 = x(b)
+ const band = el('rect', {
+ x: Math.min(x0, x1) - (W - PAD.l - PAD.r) / days / 2,
+ y: PAD.t,
+ width: Math.max(2, Math.abs(x1 - x0) + (W - PAD.l - PAD.r) / days),
+ height: H - PAD.t - PAD.b,
+ fill: `url(#${id})`,
+ class: 'sp-chart-gap',
+ })
+ const title = el('title')
+ title.textContent = t('Not recorded')
+ band.appendChild(title)
+ svg.appendChild(band)
+ }
+ }
+
+ // ---- the data ------------------------------------------------------------
+ if (data.kind === 'cfd') drawStacks(svg, data, x, y)
+ else drawLines(svg, data, x, y)
+
+ // ---- guides --------------------------------------------------------------
+ if (data.ideal !== undefined && data.ideal > 0) {
+ const line = el('line', {
+ x1: x(data.from), y1: y(data.ideal), x2: x(data.to), y2: y(0), class: 'sp-chart-ideal',
+ })
+ const title = el('title')
+ title.textContent = t('Ideal')
+ line.appendChild(title)
+ svg.appendChild(line)
+ }
+ if (data.committed) {
+ const line = el('line', {
+ x1: PAD.l, y1: y(data.committed.v), x2: W - PAD.r, y2: y(data.committed.v), class: 'sp-chart-committed',
+ })
+ const title = el('title')
+ title.textContent = t('Committed on {date}', { date: dayLabel(data.committed.at, loc) })
+ line.appendChild(title)
+ svg.appendChild(line)
+ }
+
+ // the left edge, when older rows were dropped
+ if (data.cut) {
+ svg.appendChild(el('line', {
+ x1: PAD.l, y1: PAD.t, x2: PAD.l, y2: H - PAD.b, class: 'sp-chart-cut',
+ }))
+ const label = el('text', { x: PAD.l + 4, y: PAD.t + 10, class: 'sp-chart-note' })
+ label.textContent = t('Recording starts here')
+ svg.appendChild(label)
+ }
+
+ // the x axis last, over the bands
+ svg.appendChild(el('line', {
+ x1: PAD.l, y1: H - PAD.b, x2: W - PAD.r, y2: H - PAD.b, class: 'sp-chart-axisline',
+ }))
+ return svg
+}
+
+/** A run's path, and whether any segment of it is a sample. */
+function runPath(run: Point[], i: number, x: (d: string) => number, y: (v: number) => number): string {
+ return run.map((p, j) => `${j ? 'L' : 'M'} ${x(p.day).toFixed(2)} ${y(p.v[i]).toFixed(2)}`).join(' ')
+}
+
+function drawLines(
+ svg: SVGSVGElement,
+ data: ChartData,
+ x: (d: string) => number,
+ y: (v: number) => number,
+): void {
+ data.bands.forEach((band, i) => {
+ for (const run of data.runs) {
+ if (run.length === 1) {
+ // A RUN OF ONE IS STILL A READING — a day surrounded by gaps, or today
+ // on its own. It gets a dot and the same tooltip every other point has;
+ // it must not be the one point a reader cannot interrogate.
+ const only = el('circle', { cx: x(run[0].day), cy: y(run[0].v[i]), r: 3, fill: band.color, class: 'sp-chart-dot' })
+ const t0 = el('title')
+ t0.textContent = `${dayLabel(run[0].day)} — ${band.label}: ${run[0].v[i]}`
+ only.appendChild(t0)
+ svg.appendChild(only)
+ continue
+ }
+ // ONE PATH PER SEGMENT, because a segment's style says what its right-hand
+ // point IS: a dashed segment means the reading it arrives at stands for
+ // more than one day, so a weekly sample can never be mistaken for a daily
+ // reading. A single path for the whole run could not say that.
+ for (let j = 1; j < run.length; j++) {
+ const seg = [run[j - 1], run[j]]
+ const p = el('path', {
+ d: runPath(seg, i, x, y),
+ fill: 'none',
+ stroke: band.color,
+ class: seg[1].kind === 'sample' ? 'sp-chart-line sp-chart-sampled' : 'sp-chart-line',
+ })
+ svg.appendChild(p)
+ }
+ for (const p of run) {
+ const dot = el('circle', {
+ cx: x(p.day), cy: y(p.v[i]), r: p.kind === 'sample' ? 3.5 : 2.5, fill: band.color,
+ class: p.kind === 'sample' ? 'sp-chart-dot sp-chart-sampledot' : 'sp-chart-dot',
+ })
+ const title = el('title')
+ title.textContent = `${dayLabel(p.day)} — ${band.label}: ${p.v[i]}`
+ dot.appendChild(title)
+ svg.appendChild(dot)
+ }
+ }
+ })
+}
+
+function drawStacks(
+ svg: SVGSVGElement,
+ data: ChartData,
+ x: (d: string) => number,
+ y: (v: number) => number,
+): void {
+ // BOTTOM-UP IN REVERSE SCHEMA ORDER, so the finished work is the floor and
+ // the backlog is the ceiling — the shape every CFD is read in, where the
+ // vertical distance between two boundaries is the work in that state and the
+ // horizontal distance is how long it stays there.
+ const order = [...data.bands].reverse()
+ for (const run of data.runs) {
+ if (run.length < 2) continue
+ const acc = run.map(() => 0)
+ for (const band of order) {
+ const i = data.bands.indexOf(band)
+ const lower = acc.slice()
+ run.forEach((p, j) => { acc[j] += p.v[i] })
+ const up = run.map((p, j) => `${j ? 'L' : 'M'} ${x(p.day).toFixed(2)} ${y(acc[j]).toFixed(2)}`).join(' ')
+ const down = run
+ .map((p, j) => ({ p, j }))
+ .reverse()
+ .map(({ p, j }) => `L ${x(p.day).toFixed(2)} ${y(lower[j]).toFixed(2)}`)
+ .join(' ')
+ const area = el('path', { d: `${up} ${down} Z`, fill: band.color, class: 'sp-chart-band' })
+ const title = el('title')
+ title.textContent = band.label
+ area.appendChild(title)
+ svg.appendChild(area)
+ }
+ }
+}
+
+// ---- the block -------------------------------------------------------------
+
+/**
+ * Render a `chart` block.
+ *
+ * A DANGLING `period` RENDERS AS "this chart's period is gone" AND NEVER AS AN
+ * EMPTY GRAPH. Slides drops a dangling connector; here the block is kept and
+ * says so, because a chart silently drawing nothing is precisely the failure
+ * this whole design is about.
+ */
+export function renderChartBlock(
+ host: HTMLElement,
+ block: { kind?: unknown; period?: unknown; html?: unknown },
+ doc: SpacesDoc,
+ today: string,
+ opts: { editable?: boolean } = {},
+): void {
+ const kind = chartKind(block.kind)
+ const id = typeof block.period === 'string' ? block.period : ''
+ const head = document.createElement('div')
+ head.className = 'sp-chart-head'
+ const name = document.createElement('span')
+ name.className = 'sp-chart-title'
+ head.appendChild(name)
+ host.appendChild(head)
+
+ const period = id ? periodOf(doc, id) : undefined
+
+ if (!id || !period) {
+ name.textContent = chartKindLabel(kind)
+ const note = document.createElement('p')
+ note.className = 'sp-chart-empty'
+ note.textContent = id
+ ? t("This chart's period is gone.")
+ : t('This chart has no period yet — a chart needs a window to draw.')
+ host.appendChild(note)
+ if (opts.editable) {
+ const btn = document.createElement('button')
+ btn.type = 'button'
+ btn.className = 'sp-btn'
+ btn.dataset.chartPeriod = ''
+ btn.textContent = t('Choose a period…')
+ host.appendChild(btn)
+ }
+ return
+ }
+
+ name.textContent = `${chartKindLabel(kind)} — ${period.label || t('Period')}`
+ const range = document.createElement('span')
+ range.className = 'sp-chart-range'
+ range.textContent = `${dayLabel(period.from)} – ${dayLabel(period.to)}`
+ head.appendChild(range)
+
+ // A COPY THAT LEFT THE RECORD OUT. `trail` is history class, so a view-only
+ // copy, the reading copy, a link or Copy document JSON carries the period
+ // (content) but none of the rows. Drawn as it stands, every past day would be
+ // a hatched "Not recorded" — a claim that nobody worked, when the truth is
+ // that this copy was not given the record. Say that instead.
+ if (!opts.editable && doc.trail === undefined) {
+ const note = document.createElement('p')
+ note.className = 'sp-chart-empty'
+ note.textContent = t('This copy does not include the day-by-day record.')
+ host.appendChild(note)
+ return
+ }
+
+ const data = chartData(doc, period, kind, today)
+ if (data.empty) {
+ const note = document.createElement('p')
+ note.className = 'sp-chart-empty'
+ note.textContent = t('Nothing recorded yet for this period.')
+ host.appendChild(note)
+ return
+ }
+ host.appendChild(drawChart(data))
+ host.appendChild(legend(data))
+ if (opts.editable) {
+ const btn = document.createElement('button')
+ btn.type = 'button'
+ btn.className = 'sp-btn sp-chart-pick'
+ btn.dataset.chartPeriod = id
+ btn.textContent = t('Change period…')
+ host.appendChild(btn)
+ }
+}
+
+/**
+ * The legend, which is also where the chart says what it could NOT see.
+ *
+ * "Not recorded" is listed with the same weight as a band. A chart whose gaps
+ * are only visible as hatching is a chart whose reader has to guess what the
+ * hatching means.
+ */
+function legend(data: ChartData): HTMLElement {
+ const box = document.createElement('div')
+ box.className = 'sp-chart-legend'
+ const chip = (label: string, cls: string, color?: string) => {
+ const s = document.createElement('span')
+ s.className = `sp-chart-key ${cls}`
+ const sw = document.createElement('i')
+ if (color) sw.style.background = color
+ const tx = document.createElement('span')
+ tx.textContent = label
+ s.append(sw, tx)
+ box.appendChild(s)
+ }
+ for (const b of data.bands) chip(b.label, 'sp-chart-keyband', b.color)
+ if (data.gaps.length) chip(t('Not recorded'), 'sp-chart-keygap')
+ if (data.runs.some((r) => r.some((p) => p.kind === 'sample'))) {
+ chip(t('Sampled, not daily'), 'sp-chart-keysample')
+ }
+ const units = document.createElement('span')
+ units.className = 'sp-chart-units'
+ units.textContent = data.units === 'points' ? t('Estimate points') : t('Issue count')
+ box.appendChild(units)
+ if (data.unestimated > 0) {
+ const warn = document.createElement('span')
+ warn.className = 'sp-chart-units'
+ warn.textContent = t('{n} with no estimate', { n: String(data.unestimated) })
+ box.appendChild(warn)
+ }
+ return box
+}
+
+// ---- the editor's one affordance -------------------------------------------
+
+export interface ChartWiring {
+ block: (id: string) => { kind?: unknown; period?: unknown; html?: unknown } | undefined
+ doc: () => SpacesDoc
+ commit: (fn: () => void) => void
+ repaint: () => void
+ today: () => string
+ /** mint an id for a new period */
+ uid: () => string
+ /** open the kernel's anchored menu through the editor's overlay door */
+ menu: (anchor: HTMLElement, label: string, fill: (m: Menu) => void) => void
+}
+
+/**
+ * Wire the period button on every chart in a painted page.
+ *
+ * ONE affordance, and it is the only one a chart needs to be usable: which
+ * window am I about? Everything else a chart could be configured with is either
+ * frozen onto the period (the scope) or not a choice at all (what a burndown
+ * draws). The kind is set when the block is inserted.
+ *
+ * Kept in this file rather than in editor.ts for the reason the canvas keeps its
+ * own wiring in canvas.ts: the block, its data and its one control are one
+ * feature, and editor.ts is contended by everybody.
+ */
+export function wireCharts(root: HTMLElement, w: ChartWiring): void {
+ for (const btn of root.querySelectorAll<HTMLElement>('[data-chart-period]')) {
+ btn.addEventListener('click', (e) => {
+ e.preventDefault()
+ const host = btn.closest<HTMLElement>('[data-block-id]')
+ const id = host?.dataset.blockId
+ if (!id) return
+ openPeriodMenu(btn, id, w)
+ })
+ }
+}
+
+function openPeriodMenu(anchor: HTMLElement, blockId: string, w: ChartWiring): void {
+ // The KERNEL's menu, through the editor's one anchored-menu door (menuAt):
+ // Escape with focus return, arrow keys, the outside press, a bottom sheet on
+ // a phone, and the editor's single-overlay bookkeeping — none of it rebuilt
+ // here. One-line rows, as every menu in this app (slides' rule).
+ const current = (w.block(blockId) as { period?: unknown } | undefined)?.period
+ const pick = (periodId: string) => {
+ w.commit(() => {
+ const b = w.block(blockId) as { period?: string } | undefined
+ if (b) b.period = periodId
+ })
+ w.repaint()
+ }
+ w.menu(anchor, t('Choose a period…'), (m) => {
+ for (const { id, period } of periodList(w.doc())) {
+ row(m, {
+ label: `${period.label || t('Period')} · ${dayLabel(period.from)} – ${dayLabel(period.to)}`,
+ selected: id === current,
+ run: () => pick(id),
+ })
+ }
+ row(m, {
+ label: t('New two-week period from today'),
+ run: () => {
+ const today = w.today()
+ const id = w.uid()
+ w.commit(() => {
+ // The baseline is taken RIGHT NOW, from live state, and `base.at`
+ // records that — so a period started on day 4 of a sprint says
+ // "committed on the 4th" rather than pretending it was the 1st. No
+ // past trail key is ever fabricated: the days before the record
+ // existed are gaps.
+ startPeriod(w.doc(), id, {
+ label: t('Period from {date}', { date: dayLabel(today) }),
+ from: today,
+ to: addDays(today, 13),
+ today,
+ })
+ const b = w.block(blockId) as { period?: string } | undefined
+ if (b) b.period = id
+ })
+ w.repaint()
+ },
+ })
+ })
+}
diff --git a/spaces/src/docclass.ts b/spaces/src/docclass.ts
index ee5d8226..109643a4 100644
--- a/spaces/src/docclass.ts
+++ b/spaces/src/docclass.ts
@@ -61,6 +61,13 @@ export const SPACES_FIELDS = {
fonts: 'content',
templates: 'content',
journalTemplate: 'content',
+ // content, not history: a period is something a person DECIDED (a sprint's
+ // window and committed scope), named by a chart block in a page, undone by
+ // ⌘Z, and synced per key. Classing it history would drop it from a reader
+ // copy while the chart block that names it stays — a dangling reference —
+ // and would stop collaborators sharing the sprint. It holds totals at one
+ // instant (base), never page ids and never a series; the series is `trail`.
+ periods: 'content',
} satisfies Record<DeclaredKeys<SpacesDoc>, FieldClass>
/** tsc fails here if the fields classed 'mode' stop being exactly the kernel's
@@ -77,6 +84,10 @@ void _modeOk
* keep. Spaces records a revision only inside a save's prepare step, into
* the bytes that save writes (history.ts) — so it is never unsaved work, and
* counting it would raise the recovery banner on every file reopened after a
- * download-save, whose recovery snapshot predates the revision. `trail` is
- * NOT listed: when it is written is its feature's call. */
+ * download-save, whose recovery snapshot predates the revision.
+ *
+ * `trail` is NOT listed, and must not be: it is written WHILE EDITING, on the
+ * 'doc' event (main.ts recordToday), outside any save. A row recorded since
+ * the last save is unsaved work only a recovery snapshot can keep, which is
+ * exactly the case the kernel's default exists for. */
export const SPACES_NOT_EDIT: ReadonlySet<string> = new Set(['modified', 'revisions'])
diff --git a/spaces/src/docmaps.ts b/spaces/src/docmaps.ts
new file mode 100644
index 00000000..30b74535
--- /dev/null
+++ b/spaces/src/docmaps.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Doc-level keys that are MAPS — merged per key by the CRDT, and folded back
+// out of a dotted top-level key by the parser.
+//
+// THIS FILE IS A LEAF: no imports at all. `model.ts parseDoc` calls
+// `foldDottedMapKeys` before anything else sees the document, so anything this
+// module imported at runtime would be imported by the parser.
+
+/**
+ * ONE list, read by `sync/crdt.ts` (which hands it to the kernel's `shape()`)
+ * and by `model.ts parseDoc` (which repairs what a peer running an older shape
+ * wrote). Two copies of it is precisely how the mitigation and the hazard drift
+ * apart.
+ *
+ * `periods` is here because two people defining or closing different periods
+ * in one week must both keep theirs; as one whole-value register, one of them
+ * would silently lose a period and every chart that names it.
+ *
+ * `trail` is NOT here, and must never be: it is the kernel's `history` class
+ * (docclass.ts), which the sync shape skips outright — each replica keeps its
+ * own record of what it saw, the way each keeps its own `revisions`.
+ */
+export const DOC_MAPS = ['periods'] as const
+
+const isObj = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v)
+
+/**
+ * Fold a dotted top-level key back into the map it belongs to, in place.
+ *
+ * THE MIXED-VERSION HAZARD, and its mitigation. A peer running a build whose
+ * `DocShape.maps` does not list `periods` receives `set k="periods.pd-1"`,
+ * fails the kernel's `mapKey()` lookup, and writes a literal top-level key
+ * named `"periods.pd-1"`. Additivity would then preserve that junk forever.
+ * Folding it back here is cheap, deterministic, self-healing, and repairs
+ * files that were damaged before the fix existed — no kernel handshake change.
+ *
+ * NEVER OVERWRITES a key the map already holds — the folded value is the one
+ * that build could not place, and the placed one is at least as new.
+ */
+export function foldDottedMapKeys(raw: Record<string, unknown>): number {
+ let folded = 0
+ for (const k of Object.keys(raw)) {
+ const at = k.indexOf('.')
+ if (at <= 0) continue
+ const field = k.slice(0, at)
+ if (!(DOC_MAPS as readonly string[]).includes(field)) continue
+ const entry = k.slice(at + 1)
+ if (!entry) continue
+ // a `periods` some newer build gave a different shape is left alone, and so
+ // is the dotted key beside it: a field this build cannot read is not one it
+ // may overwrite
+ if (raw[field] !== undefined && !isObj(raw[field])) continue
+ const map = isObj(raw[field]) ? (raw[field] as Record<string, unknown>) : {}
+ if (!Object.hasOwn(map, entry)) map[entry] = raw[k]
+ raw[field] = map
+ delete raw[k]
+ folded++
+ }
+ return folded
+}
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index 981cb911..d2aa20d4 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -21,6 +21,7 @@ import { renderPage, toneLabel, paintCode } from './render'
import { notesOnPage } from './footnotes.ts'
import { wireCanvas, placeNewCard } from './canvas.ts'
import { enableTouchDrag } from './touch.ts'
+import { wireCharts } from './charts.ts'
import { CODE_LANGS, langLabel, normLang } from './highlight'
import { canonicalize, escText, sanitizeInline, textOf } from './sanitize'
import { FormatBar } from './formatbar'
@@ -2829,6 +2830,17 @@ export class Editor {
}
this.wireBoard(view)
this.wireTables(view)
+ // Charts keep their own wiring in their own file, like the canvas: one
+ // control (which period) over data this file knows nothing about.
+ wireCharts(view, {
+ block: (id) => this.store.block(id),
+ doc: () => this.store.doc,
+ commit: (fn) => this.store.commit(fn),
+ repaint: () => this.paintPage(),
+ today: () => todayISO(),
+ uid: () => uid('pd'),
+ menu: (anchor, label, fill) => { this.menuAt(anchor, label, fill) },
+ })
// The canvas keeps its own wiring in its own file: the drag, the cards
// and the shape button are one feature and touch nothing else here.
wireCanvas(view, {
diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.ts
index f15f76e4..884e8a3f 100644
--- a/spaces/src/i18n/de.ts
+++ b/spaces/src/i18n/de.ts
@@ -966,6 +966,32 @@ export const de: Catalog = {
"Clear history…": "Verlauf löschen…",
"First version kept in this file": "Erste in dieser Datei aufbewahrte Version",
"Changes outside the pages — title, design, footnotes or templates": "Änderungen außerhalb der Seiten — Titel, Gestaltung, Fußnoten oder Vorlagen",
+ "Burndown": "Burndown-Diagramm",
+ "Burndown, burnup or cumulative flow": "Burndown, Burnup oder kumulierter Fluss",
+ "Burnup": "Burnup-Diagramm",
+ "Change period…": "Zeitraum ändern…",
+ "Chart of progress": "Fortschrittsdiagramm",
+ "Choose a period…": "Zeitraum wählen…",
+ "Committed on {date}": "Festgelegt am {date}",
+ "Completed": "Erledigt",
+ "Cumulative flow": "Kumulierter Fluss",
+ "Estimate points": "Schätzpunkte",
+ "Ideal": "Ideal",
+ "Issue count": "Anzahl Vorgänge",
+ "New two-week period from today": "Neuer Zweiwochenzeitraum ab heute",
+ "No status": "Ohne Status",
+ "Not recorded": "Nicht erfasst",
+ "Nothing recorded yet for this period.": "Für diesen Zeitraum ist noch nichts erfasst.",
+ "This copy does not include the day-by-day record.": "Diese Kopie enthält die tägliche Aufzeichnung nicht.",
+ "Period": "Zeitraum",
+ "Period from {date}": "Zeitraum ab {date}",
+ "Recording starts here": "Aufzeichnung beginnt hier",
+ "Remaining": "Verbleibend",
+ "Sampled, not daily": "Stichprobe, nicht täglich",
+ "Scope": "Umfang",
+ "This chart has no period yet — a chart needs a window to draw.": "Dieses Diagramm hat noch keinen Zeitraum — ein Diagramm braucht ein Zeitfenster.",
+ "This chart's period is gone.": "Der Zeitraum dieses Diagramms existiert nicht mehr.",
+ "{id} (unknown)": "{id} (unbekannt)",
"This copy includes the space’s version history.": "Diese Kopie enthält den Versionsverlauf des Space.",
"Leave version history out": "Versionsverlauf weglassen",
"Versions include text that was deleted. This file keeps them either way.": "Versionen enthalten auch gelöschten Text. Diese Datei behält sie in jedem Fall.",
diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.ts
index 7cfd3557..4b001078 100644
--- a/spaces/src/i18n/es.ts
+++ b/spaces/src/i18n/es.ts
@@ -966,6 +966,32 @@ export const es: Catalog = {
"Clear history…": "Borrar el historial…",
"First version kept in this file": "Primera versión guardada en este archivo",
"Changes outside the pages — title, design, footnotes or templates": "Cambios fuera de las páginas: título, diseño, notas al pie o plantillas",
+ "Burndown": "Trabajo pendiente",
+ "Burndown, burnup or cumulative flow": "Trabajo pendiente, completado o flujo acumulado",
+ "Burnup": "Trabajo completado",
+ "Change period…": "Cambiar periodo…",
+ "Chart of progress": "Gráfico de progreso",
+ "Choose a period…": "Elegir un periodo…",
+ "Committed on {date}": "Fijado el {date}",
+ "Completed": "Completado",
+ "Cumulative flow": "Flujo acumulado",
+ "Estimate points": "Puntos de estimación",
+ "Ideal": "Ideal",
+ "Issue count": "Número de incidencias",
+ "New two-week period from today": "Nuevo periodo de dos semanas desde hoy",
+ "No status": "Sin estado",
+ "Not recorded": "Sin registrar",
+ "Nothing recorded yet for this period.": "Todavía no hay nada registrado en este periodo.",
+ "This copy does not include the day-by-day record.": "Esta copia no incluye el registro diario.",
+ "Period": "Periodo",
+ "Period from {date}": "Periodo desde el {date}",
+ "Recording starts here": "El registro empieza aquí",
+ "Remaining": "Restante",
+ "Sampled, not daily": "Muestreado, no diario",
+ "Scope": "Alcance",
+ "This chart has no period yet — a chart needs a window to draw.": "Este gráfico aún no tiene periodo: un gráfico necesita una ventana que dibujar.",
+ "This chart's period is gone.": "El periodo de este gráfico ya no existe.",
+ "{id} (unknown)": "{id} (desconocido)",
"This copy includes the space’s version history.": "Esta copia incluye el historial de versiones del espacio.",
"Leave version history out": "Dejar fuera el historial de versiones",
"Versions include text that was deleted. This file keeps them either way.": "Las versiones incluyen texto que se borró. Este archivo las conserva en cualquier caso.",
diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.ts
index e1858d03..9d27aebd 100644
--- a/spaces/src/i18n/fr.ts
+++ b/spaces/src/i18n/fr.ts
@@ -966,6 +966,32 @@ export const fr: Catalog = {
"Clear history…": "Effacer l’historique…",
"First version kept in this file": "Première version conservée dans ce fichier",
"Changes outside the pages — title, design, footnotes or templates": "Modifications hors des pages — titre, design, notes de bas de page ou modèles",
+ "Burndown": "Reste à faire",
+ "Burndown, burnup or cumulative flow": "Reste à faire, travail réalisé ou flux cumulé",
+ "Burnup": "Travail réalisé",
+ "Change period…": "Changer de période…",
+ "Chart of progress": "Graphique d’avancement",
+ "Choose a period…": "Choisir une période…",
+ "Committed on {date}": "Figé le {date}",
+ "Completed": "Terminé",
+ "Cumulative flow": "Flux cumulé",
+ "Estimate points": "Points d’estimation",
+ "Ideal": "Idéal",
+ "Issue count": "Nombre de tickets",
+ "New two-week period from today": "Nouvelle période de deux semaines à partir d’aujourd’hui",
+ "No status": "Sans statut",
+ "Not recorded": "Non enregistré",
+ "Nothing recorded yet for this period.": "Rien n’est encore enregistré pour cette période.",
+ "This copy does not include the day-by-day record.": "Cette copie n’inclut pas l’historique jour par jour.",
+ "Period": "Période",
+ "Period from {date}": "Période depuis le {date}",
+ "Recording starts here": "L’enregistrement commence ici",
+ "Remaining": "Restant",
+ "Sampled, not daily": "Échantillonné, pas quotidien",
+ "Scope": "Périmètre",
+ "This chart has no period yet — a chart needs a window to draw.": "Ce graphique n’a pas encore de période — un graphique a besoin d’une fenêtre à dessiner.",
+ "This chart's period is gone.": "La période de ce graphique n’existe plus.",
+ "{id} (unknown)": "{id} (inconnu)",
"This copy includes the space’s version history.": "Cette copie inclut l’historique des versions de l’espace.",
"Leave version history out": "Ne pas inclure l’historique des versions",
"Versions include text that was deleted. This file keeps them either way.": "Les versions contiennent du texte supprimé. Ce fichier les conserve dans tous les cas.",
diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.ts
index b78fab1a..6f505bc9 100644
--- a/spaces/src/i18n/it.ts
+++ b/spaces/src/i18n/it.ts
@@ -966,6 +966,32 @@ export const it: Catalog = {
"Clear history…": "Cancella la cronologia…",
"First version kept in this file": "Prima versione conservata in questo file",
"Changes outside the pages — title, design, footnotes or templates": "Modifiche fuori dalle pagine: titolo, design, note a piè di pagina o modelli",
+ "Burndown": "Lavoro rimanente",
+ "Burndown, burnup or cumulative flow": "Lavoro rimanente, completato o flusso cumulativo",
+ "Burnup": "Lavoro completato",
+ "Change period…": "Cambia periodo…",
+ "Chart of progress": "Grafico di avanzamento",
+ "Choose a period…": "Scegli un periodo…",
+ "Committed on {date}": "Fissato il {date}",
+ "Completed": "Completato",
+ "Cumulative flow": "Flusso cumulativo",
+ "Estimate points": "Punti di stima",
+ "Ideal": "Ideale",
+ "Issue count": "Numero di attività",
+ "New two-week period from today": "Nuovo periodo di due settimane da oggi",
+ "No status": "Senza stato",
+ "Not recorded": "Non registrato",
+ "Nothing recorded yet for this period.": "Nulla di registrato per questo periodo.",
+ "This copy does not include the day-by-day record.": "Questa copia non include la registrazione giorno per giorno.",
+ "Period": "Periodo",
+ "Period from {date}": "Periodo dal {date}",
+ "Recording starts here": "La registrazione inizia qui",
+ "Remaining": "Rimanente",
+ "Sampled, not daily": "Campionato, non giornaliero",
+ "Scope": "Ambito",
+ "This chart has no period yet — a chart needs a window to draw.": "Questo grafico non ha ancora un periodo — un grafico ha bisogno di una finestra da disegnare.",
+ "This chart's period is gone.": "Il periodo di questo grafico non esiste più.",
+ "{id} (unknown)": "{id} (sconosciuto)",
"This copy includes the space’s version history.": "Questa copia include la cronologia delle versioni dello spazio.",
"Leave version history out": "Escludi la cronologia delle versioni",
"Versions include text that was deleted. This file keeps them either way.": "Le versioni includono testo eliminato. Questo file le conserva in ogni caso.",
diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.ts
index e732cdb5..4bf90dcd 100644
--- a/spaces/src/i18n/ja.ts
+++ b/spaces/src/i18n/ja.ts
@@ -966,6 +966,32 @@ export const ja: Catalog = {
"Clear history…": "履歴を削除…",
"First version kept in this file": "このファイルに記録された最初のバージョン",
"Changes outside the pages — title, design, footnotes or templates": "ページ以外の変更 — タイトル、デザイン、脚注、テンプレート",
+ "Burndown": "バーンダウン",
+ "Burndown, burnup or cumulative flow": "バーンダウン、バーンアップ、累積フロー",
+ "Burnup": "バーンアップ",
+ "Change period…": "期間を変更…",
+ "Chart of progress": "進捗のグラフ",
+ "Choose a period…": "期間を選択…",
+ "Committed on {date}": "{date} に確定",
+ "Completed": "完了",
+ "Cumulative flow": "累積フロー図",
+ "Estimate points": "見積りポイント",
+ "Ideal": "理想線",
+ "Issue count": "課題数",
+ "New two-week period from today": "今日から2週間の新しい期間",
+ "No status": "ステータスなし",
+ "Not recorded": "記録なし",
+ "Nothing recorded yet for this period.": "この期間の記録はまだありません。",
+ "This copy does not include the day-by-day record.": "このコピーには日ごとの記録が含まれていません。",
+ "Period": "期間",
+ "Period from {date}": "{date} からの期間",
+ "Recording starts here": "ここから記録開始",
+ "Remaining": "残り",
+ "Sampled, not daily": "サンプル(毎日ではありません)",
+ "Scope": "全体量",
+ "This chart has no period yet — a chart needs a window to draw.": "このグラフにはまだ期間がありません — グラフには対象期間が必要です。",
+ "This chart's period is gone.": "このグラフの期間は失われました。",
+ "{id} (unknown)": "{id}(不明)",
"This copy includes the space’s version history.": "このコピーには、スペースのバージョン履歴が含まれます。",
"Leave version history out": "バージョン履歴を含めない",
"Versions include text that was deleted. This file keeps them either way.": "バージョンには削除された本文も含まれます。このファイルにはどちらの場合も残ります。",
diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.ts
index 7f09204e..332ae085 100644
--- a/spaces/src/i18n/packed.ts
+++ b/spaces/src/i18n/packed.ts
@@ -62,7 +62,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Add a block below": ["下にブロックを追加","在下方添加块","在下方新增區塊","Añadir un bloque debajo","Ajouter un bloc en dessous","Block darunter hinzufügen","Aggiungi un blocco sotto","Adicionar um bloco abaixo"],
"Add a card": ["カードを追加","添加卡片","新增卡片","Añadir una tarjeta","Ajouter une carte","Karte hinzufügen","Aggiungi una scheda","Adicionar um cartão"],
"Add a card that opens a page": ["ページを開くカードを追加","添加一张打开页面的卡片","新增可開啟頁面的卡片","Añadir una tarjeta que abre una página","Ajouter une carte qui ouvre une page","Karte hinzufügen, die eine Seite öffnet","Aggiungi una scheda che apre una pagina","Adicionar um cartão que abre uma página"],
- "Add a chart of the issues in this space": ["この Space のイシューのグラフを追加","添加此空间中事项的图表","新增此空間中項目的圖表","Añadir un gráfico de las incidencias de este espacio","Ajouter un graphique des tickets de cet espace","Ein Diagramm der Issues in diesem Space hinzufügen","Aggiungi un grafico delle issue di questo spazio","Adicionar um gráfico das tarefas deste espaço"],
"Add a code block": ["コードブロックを追加","添加代码块","新增程式碼區塊","Añadir un bloque de código","Ajouter un bloc de code","Einen Codeblock hinzufügen","Aggiungi un blocco di codice","Adicionar um bloco de código"],
"Add a column after": ["右に列を追加","在右侧添加一列","在右側新增一欄","Añadir una columna después","Ajouter une colonne après","Spalte danach einfügen","Aggiungi una colonna dopo","Adicionar uma coluna depois"],
"Add a condition": ["条件を追加","添加条件","新增條件","Añadir una condición","Ajouter une condition","Bedingung hinzufügen","Aggiungi una condizione","Adicionar uma condição"],
@@ -127,6 +126,9 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Brown": ["茶","棕色","棕色","Marrón","Marron","Braun","Marrone","Marrom"],
"Bulleted list": ["箇条書き","项目符号列表","項目符號清單","Lista con viñetas","Liste à puces","Aufzählung","Elenco puntato","Lista com marcadores"],
"Bullets": ["箇条書き記号","项目符号","項目符號","Viñetas","Puces","Aufzählungszeichen","Punti elenco","Marcadores"],
+ "Burndown": ["バーンダウン","燃尽图","燃盡圖","Trabajo pendiente","Reste à faire","Burndown-Diagramm","Lavoro rimanente","Trabalho restante"],
+ "Burndown, burnup or cumulative flow": ["バーンダウン、バーンアップ、累積フロー","燃尽图、燃起图或累积流图","燃盡圖、燃起圖或累積流圖","Trabajo pendiente, completado o flujo acumulado","Reste à faire, travail réalisé ou flux cumulé","Burndown, Burnup oder kumulierter Fluss","Lavoro rimanente, completato o flusso cumulativo","Trabalho restante, concluído ou fluxo acumulado"],
+ "Burnup": ["バーンアップ","燃起图","燃起圖","Trabajo completado","Travail réalisé","Burnup-Diagramm","Lavoro completato","Trabalho concluído"],
"Calendar": ["カレンダー","日历","日曆","Calendario","Calendrier","Kalender","Calendario","Calendário"],
"Callout": ["コールアウト","标注","標註","Aviso","Encadré","Hinweisblock","Riquadro","Destaque"],
"Callout icon": ["囲みのアイコン","标注图标","標註圖示","Icono del aviso","Icône de l'encadré","Symbol des Hinweisfelds","Icona del riquadro","Ícone do destaque"],
@@ -141,6 +143,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Cell 2": ["セル 2","单元 2","單元 2","Celda 2","Case 2","Feld 2","Cella 2","Célula 2"],
"Cell 3": ["セル 3","单元 3","單元 3","Celda 3","Case 3","Feld 3","Cella 3","Célula 3"],
"Change password…": ["パスワードを変更…","更改密码…","變更密碼…","Cambiar contraseña…","Changer le mot de passe…","Passwort ändern…","Cambia password…","Alterar senha…"],
+ "Change period…": ["期間を変更…","更改周期…","變更週期…","Cambiar periodo…","Changer de période…","Zeitraum ändern…","Cambia periodo…","Mudar período…"],
"Change the kind of callout": ["囲みの種類を変更","更改标注类型","變更標註類型","Cambiar el tipo de aviso","Changer le type d'encadré","Art des Hinweisfelds ändern","Cambia il tipo di riquadro","Alterar o tipo de destaque"],
"Change the name used for your new comments and replies": ["新しいコメントと返信に使う名前を変更","更改新评论和回复所用的名字","變更新註解與回覆所用的名字","Cambiar el nombre para tus nuevos comentarios y respuestas","Changer le nom utilisé pour vos nouveaux commentaires et réponses","Namen für neue Kommentare und Antworten ändern","Cambia il nome usato per i tuoi nuovi commenti e risposte","Altere o nome usado nos seus novos comentários e respostas"],
"Change the shape of this canvas": ["このキャンバスの形を変更","更改此画布的形状","變更此畫布的形狀","Cambiar la forma de este lienzo","Changer la forme de ce canevas","Form dieser Leinwand ändern","Cambia la forma di questa tela","Alterar o formato desta tela"],
@@ -148,7 +151,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Change {field}": ["{field}を変更","更改{field}","變更{field}","Cambiar {field}","Modifier {field}","{field} ändern","Cambia {field}","Alterar {field}"],
"Changes": ["変更点","改动","變更","Cambios","Modifications","Änderungen","Modifiche","Alterações"],
"Changes outside the pages — title, design, footnotes or templates": ["ページ以外の変更 — タイトル、デザイン、脚注、テンプレート","页面之外的改动——标题、设计、脚注或模板","頁面之外的變更——標題、設計、註腳或範本","Cambios fuera de las páginas: título, diseño, notas al pie o plantillas","Modifications hors des pages — titre, design, notes de bas de page ou modèles","Änderungen außerhalb der Seiten — Titel, Gestaltung, Fußnoten oder Vorlagen","Modifiche fuori dalle pagine: titolo, design, note a piè di pagina o modelli","Alterações fora das páginas — título, design, notas de rodapé ou modelos"],
- "Chart": ["グラフ","图表","圖表","Gráfico","Graphique","Diagramm","Grafico","Gráfico"],
+ "Chart of progress": ["進捗のグラフ","进度图表","進度圖表","Gráfico de progreso","Graphique d’avancement","Fortschrittsdiagramm","Grafico di avanzamento","Gráfico de progresso"],
"Check for updates": ["更新を確認","检查更新","檢查更新","Buscar actualizaciones","Rechercher des mises à jour","Nach Updates suchen","Cerca aggiornamenti","Verificar atualizações"],
"Check for updates automatically at launch": ["起動時に自動で更新を確認","启动时自动检查更新","啟動時自動檢查更新","Buscar actualizaciones automáticamente al iniciar","Rechercher automatiquement les mises à jour au démarrage","Beim Start automatisch nach Updates suchen","Cerca aggiornamenti automaticamente all'avvio","Verificar atualizações automaticamente ao abrir"],
"Checkboxes": ["チェックボックス","复选框","核取方塊","Casillas","Cases à cocher","Kontrollkästchen","Caselle di spunta","Caixas de verificação"],
@@ -158,6 +161,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Choose a different file": ["別のファイルを選ぶ","选择另一个文件","選擇另一個檔案","Elegir otro archivo","Choisir un autre fichier","Eine andere Datei wählen","Scegli un altro file","Escolher outro ficheiro"],
"Choose a file…": ["ファイルを選ぶ…","选择文件…","選擇檔案…","Elegir un archivo…","Choisir un fichier…","Datei wählen…","Scegli un file…","Escolher um ficheiro…"],
"Choose a folder…": ["フォルダーを選ぶ…","选择文件夹…","選擇資料夾…","Elegir una carpeta…","Choisir un dossier…","Ordner wählen…","Scegli una cartella…","Escolher uma pasta…"],
+ "Choose a period…": ["期間を選択…","选择周期…","選擇週期…","Elegir un periodo…","Choisir une période…","Zeitraum wählen…","Scegli un periodo…","Escolher um período…"],
"Choose a space…": ["スペースを選ぶ…","选择一个空间…","選擇一個空間…","Elegir un espacio…","Choisir un espace…","Space auswählen…","Scegli uno spazio…","Escolher um espaço…"],
"Choose the field the bars come from": ["棒のもとになるフィールドを選ぶ","选择用作柱形的字段","選擇作為長條的欄位","Elige el campo del que salen las barras","Choisir le champ dont viennent les barres","Feld wählen, aus dem die Balken kommen","Scegli il campo da cui nascono le barre","Escolha o campo de onde vêm as barras"],
"Choose the field the columns come from": ["列のもとになるフィールドを選ぶ","选择用作分栏的字段","選擇作為欄的欄位","Elige el campo del que salen las columnas","Choisir le champ dont viennent les colonnes","Feld wählen, aus dem die Spalten kommen","Scegli il campo da cui nascono le colonne","Escolha o campo de onde vêm as colunas"],
@@ -186,6 +190,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Comment · page": ["コメント · ページ","评论 · 页面","註解 · 頁面","Comentario · página","Commentaire · page","Kommentar · Seite","Commento · pagina","Comentário · página"],
"Comment — on the block with the caret, or on this page": ["コメント — カーソルのあるブロック、またはこのページに","评论 — 针对光标所在的块,或此页面","註解 — 針對游標所在的區塊,或此頁面","Comentar — en el bloque donde está el cursor, o en esta página","Commenter — le bloc où se trouve le curseur, ou cette page","Kommentieren — den Block mit dem Cursor oder diese Seite","Commenta — il blocco con il cursore, o questa pagina","Comentar — o bloco onde está o cursor, ou esta página"],
"Comment:": ["コメント:","评论:","註解:","Comentario:","Commentaire :","Kommentar:","Commento:","Comentário:"],
+ "Committed on {date}": ["{date} に確定","于 {date} 确定","於 {date} 確定","Fijado el {date}","Figé le {date}","Festgelegt am {date}","Fissato il {date}","Fixado em {date}"],
+ "Completed": ["完了","已完成","已完成","Completado","Terminé","Erledigt","Completato","Concluído"],
"Condensed": ["コンデンス","窄体","窄體","Condensada","Condensée","Schmal","Condensato","Condensada"],
"Condition": ["条件","条件","條件","Condición","Condition","Bedingung","Condizione","Condição"],
"Conditions": ["条件","条件","條件","Condiciones","Conditions","Bedingungen","Condizioni","Condições"],
@@ -207,6 +213,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Couldn’t reach the live session": ["ライブセッションに接続できませんでした","无法连接实时会话","無法連線即時會話","No se pudo contactar la sesión en vivo","Impossible de joindre la session live","Live-Sitzung nicht erreichbar","Impossibile raggiungere la sessione live","Não foi possível alcançar a sessão ao vivo"],
"Cover": ["カバー","封面","封面","Portada","Couverture","Titelbild","Copertina","Capa"],
"Create “{name}”": ["「{name}」を作成","创建“{name}”","建立「{name}」","Crear «{name}»","Créer « {name} »","„{name}“ erstellen","Crea «{name}»","Criar “{name}”"],
+ "Cumulative flow": ["累積フロー図","累积流图","累積流圖","Flujo acumulado","Flux cumulé","Kumulierter Fluss","Flusso cumulativo","Fluxo acumulado"],
"Custom": ["カスタム","自定义","自訂","Personalizado","Personnalisé","Eigene","Personalizzato","Personalizado"],
"Customise design": ["デザインをカスタマイズ","自定义设计","自訂設計","Personalizar el diseño","Personnaliser le design","Gestaltung anpassen","Personalizza il design","Personalizar o design"],
"Customise…": ["カスタマイズ…","自定义…","自訂…","Personalizar…","Personnaliser…","Anpassen…","Personalizza…","Personalizar…"],
@@ -264,6 +271,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Embeds are not followed deeper than this.": ["埋め込みはこれ以上たどりません。","嵌入不会再向下展开。","嵌入不會再向下展開。","Las inserciones no se siguen más allá de aquí.","Les insertions ne sont pas suivies plus loin.","Einbettungen werden nicht tiefer verfolgt.","Le incorporazioni non vengono seguite più in profondità.","As incorporações não são seguidas para além deste ponto."],
"Encrypt with password…": ["パスワードで暗号化…","使用密码加密…","以密碼加密…","Cifrar con contraseña…","Chiffrer avec un mot de passe…","Mit Passwort verschlüsseln…","Cifra con password…","Criptografar com senha…"],
"Enter the password to open it.": ["開くにはパスワードを入力してください。","输入密码以打开。","請輸入密碼以開啟。","Introduce la contraseña para abrirlo.","Saisissez le mot de passe pour l’ouvrir.","Gib das Passwort ein, um ihn zu öffnen.","Inserisci la password per aprirlo.","Introduza a palavra-passe para o abrir."],
+ "Estimate points": ["見積りポイント","估算点数","估算點數","Puntos de estimación","Points d’estimation","Schätzpunkte","Punti di stima","Pontos de estimativa"],
"Every page opens wide on this screen from now on": ["この画面では今後すべてのページを広く表示します","在此屏幕上,之后所有页面都会以加宽方式打开","在此螢幕上,之後所有頁面都會以加寬方式開啟","A partir de ahora todas las páginas se abren anchas en esta pantalla","Désormais toutes les pages s’ouvrent en large sur cet écran","Auf diesem Bildschirm öffnen ab jetzt alle Seiten breit","Da ora tutte le pagine si aprono larghe su questo schermo","A partir de agora todas as páginas abrem largas neste ecrã"],
"Every page with a status": ["ステータスを持つすべてのページ","所有带状态的页面","所有帶狀態的頁面","Todas las páginas con estado","Toutes les pages ayant un statut","Jede Seite mit einem Status","Ogni pagina con uno stato","Todas as páginas com estado"],
"Every page, as one .md file": ["すべてのページを 1 つの .md ファイルに","所有页面合并为一个 .md 文件","所有頁面合併為一個 .md 檔","Todas las páginas, en un solo archivo .md","Toutes les pages, en un seul fichier .md","Jede Seite, in einer .md-Datei","Tutte le pagine, in un unico file .md","Todas as páginas num único ficheiro .md"],
@@ -326,6 +334,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"History takes {size} of this file.": ["履歴はこのファイルの {size} を使っています。","历史占用了此文件的 {size}。","歷史佔用了此檔案的 {size}。","El historial ocupa {size} de este archivo.","L’historique occupe {size} de ce fichier.","Der Verlauf belegt {size} dieser Datei.","La cronologia occupa {size} di questo file.","O histórico ocupa {size} deste ficheiro."],
"Humanist": ["ヒューマニスト","人文主义","人文主義","Humanista","Humane","Humanistisch","Umanista","Humanista"],
"Icon": ["アイコン","图标","圖示","Icono","Icône","Symbol","Icona","Ícone"],
+ "Ideal": ["理想線","理想线","理想線","Ideal","Idéal","Ideal","Ideale","Ideal"],
"Image": ["画像","图片","影像","Imagen","Image","Bild","Immagine","Imagem"],
"Image added ({size})": ["画像を追加しました({size})","已添加图片 ({size})","已新增圖片 ({size})","Imagen añadida ({size})","Image ajoutée ({size})","Bild hinzugefügt ({size})","Immagine aggiunta ({size})","Imagem adicionada ({size})"],
"Image added, resized to fit ({from} → {to})": ["画像を追加し、収まるように縮小しました({from} → {to})","已添加图片,已缩放以适配 ({from} → {to})","已新增圖片,已縮小尺寸 ({from} → {to})","Imagen añadida, redimensionada para que quepa ({from} → {to})","Image ajoutée, redimensionnée ({from} → {to})","Bild hinzugefügt, passend verkleinert ({from} → {to})","Immagine aggiunta, ridimensionata ({from} → {to})","Imagem adicionada, redimensionada para caber ({from} → {to})"],
@@ -349,6 +358,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Interface language": ["表示言語","界面语言","介面語言","Idioma de la interfaz","Langue de l’interface","Sprache der Oberfläche","Lingua dell’interfaccia","Idioma da interface"],
"Interface theme": ["表示テーマ","界面主题","介面主題","Tema de la interfaz","Thème de l’interface","Design der Oberfläche","Tema dell’interfaccia","Tema da interface"],
"Invite to edit…": ["編集に招待…","邀请编辑…","邀請編輯…","Invitar a editar…","Inviter à éditer…","Zum Bearbeiten einladen…","Invita a modificare…","Convidar para editar…"],
+ "Issue count": ["課題数","事项数量","議題數量","Número de incidencias","Nombre de tickets","Anzahl Vorgänge","Numero di attività","Número de tarefas"],
"Issues": ["イシュー","事项","項目","Incidencias","Tickets","Issues","Issue","Tarefas"],
"Issues across time": ["時間軸上のイシュー","按时间铺开的事项","依時間展開的項目","Incidencias a lo largo del tiempo","Tickets dans le temps","Issues über die Zeit","Issue nel tempo","Tarefas ao longo do tempo"],
"Issues as cards": ["カードとしてのイシュー","以卡片显示的事项","以卡片顯示的項目","Incidencias como tarjetas","Tickets en cartes","Issues als Karten","Issue come schede","Tarefas como cartões"],
@@ -425,6 +435,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"New pages can start as a copy of this one. The page itself is not changed.": ["新しいページをこのページの複製から始められます。このページ自体は変わりません。","新页面可以从这一页的副本开始。这一页本身不会被改动。","新頁面可以從這一頁的副本開始。這一頁本身不會被改動。","Las páginas nuevas pueden empezar como una copia de esta. La página en sí no cambia.","Les nouvelles pages peuvent commencer comme une copie de celle-ci. La page elle-même n’est pas modifiée.","Neue Seiten können als Kopie dieser Seite beginnen. Die Seite selbst bleibt unverändert.","Le nuove pagine possono partire da una copia di questa. La pagina stessa non viene modificata.","As páginas novas podem começar como uma cópia desta. A página em si não é alterada."],
"New property": ["新しいプロパティ","新建属性","新增屬性","Nueva propiedad","Nouvelle propriété","Neue Eigenschaft","Nuova proprietà","Nova propriedade"],
"New to Bento? Find templates, the gallery and the AI editing guide at {home} — or ⭐ it on {gh}.": ["Bento は初めてですか?テンプレート、ギャラリー、AI編集ガイドは {home} でどうぞ — {gh} で ⭐ もぜひ。","第一次用 Bento?在 {home} 查看模板、图库和 AI 编辑指南 — 也欢迎到 {gh} 点 ⭐。","第一次用 Bento?在 {home} 查看範本、圖庫和 AI 編輯指南 — 也歡迎到 {gh} 按 ⭐。","¿Nuevo en Bento? Encuentra plantillas, la galería y la guía de edición con IA en {home} — o dale ⭐ en {gh}.","Nouveau sur Bento ? Trouvez des modèles, la galerie et le guide d’édition par IA sur {home} — ou mettez une ⭐ sur {gh}.","Neu bei Bento? Vorlagen, die Galerie und den KI-Bearbeitungsleitfaden findest du auf {home} — oder gib ⭐ auf {gh}.","Nuovo su Bento? Trovi modelli, la galleria e la guida all’editing con IA su {home} — o metti una ⭐ su {gh}.","Novo no Bento? Encontre modelos, a galeria e o guia de edição com IA em {home} — ou dê uma ⭐ no {gh}."],
+ "New two-week period from today": ["今日から2週間の新しい期間","从今天起的两周新周期","從今天起的兩週新週期","Nuevo periodo de dos semanas desde hoy","Nouvelle période de deux semaines à partir d’aujourd’hui","Neuer Zweiwochenzeitraum ab heute","Nuovo periodo di due settimane da oggi","Novo período de duas semanas a partir de hoje"],
"News serif": ["ニュース用セリフ","新闻衬线体","新聞襯線體","Serifa de periódico","Caractère de journal","Zeitungs-Serifenschrift","Graziato da quotidiano","Serifa de jornal"],
"New… — page, journal, issue": ["新規… — ページ・ジャーナル・イシュー","新建… — 页面、日志、事项","新增… — 頁面、日誌、項目","Nuevo… — página, diario, incidencia","Nouveau… — page, journal, ticket","Neu… — Seite, Journal, Issue","Nuovo… — pagina, diario, issue","Novo… — página, diário, tarefa"],
"Next": ["次へ","下一页","下一頁","Siguiente","Suivant","Weiter","Successivo","Seguinte"],
@@ -441,6 +452,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"No pages yet": ["ページがまだありません","还没有页面","尚無頁面","Aún no hay páginas","Aucune page pour l’instant","Noch keine Seiten","Ancora nessuna pagina","Ainda sem páginas"],
"No recovery — lose the password and the space is gone": ["復元できません — パスワードを失うとスペースも失われます","无法找回 — 丢失密码,空间也就没了","無法找回 — 遺失密碼,空間也就沒了","Sin recuperación: si pierdes la contraseña, pierdes el espacio","Aucune récupération : perdez le mot de passe et l’espace est perdu","Keine Wiederherstellung — Passwort verloren, Space verloren","Nessun recupero: se perdi la password, perdi lo spazio","Sem recuperação — perca a senha e o espaço se perde"],
"No section named {name} on this page.": ["このページに「{name}」という見出しはありません。","本页没有名为“{name}”的标题。","本頁沒有名為「{name}」的標題。","No hay ninguna sección llamada {name} en esta página.","Aucune section nommée {name} sur cette page.","Kein Abschnitt namens {name} auf dieser Seite.","Nessuna sezione chiamata {name} in questa pagina.","Não há nenhuma secção chamada {name} nesta página."],
+ "No status": ["ステータスなし","无状态","無狀態","Sin estado","Sans statut","Ohne Status","Senza stato","Sem estado"],
"No tags match": ["一致するタグはありません","没有匹配的标签","沒有相符的標籤","Ninguna etiqueta coincide","Aucune étiquette ne correspond","Keine passenden Schlagwörter","Nessuna etichetta corrisponde","Nenhuma etiqueta corresponde"],
"No templates yet. Open a page you would like to reuse and choose “Save as template”.": ["まだテンプレートはありません。再利用したいページを開いて「テンプレートとして保存」を選んでください。","还没有模板。打开一个想重复使用的页面,选择“保存为模板”。","還沒有範本。開啟一個想重複使用的頁面,選擇「儲存為範本」。","Todavía no hay plantillas. Abre una página que quieras reutilizar y elige «Guardar como plantilla».","Aucun modèle pour l’instant. Ouvrez une page que vous voulez réutiliser et choisissez « Enregistrer comme modèle ».","Noch keine Vorlagen. Öffne eine Seite, die du wiederverwenden möchtest, und wähle „Als Vorlage sichern“.","Ancora nessun modello. Apri una pagina che vuoi riutilizzare e scegli «Salva come modello».","Ainda não há modelos. Abre uma página que queiras reutilizar e escolhe «Guardar como modelo»."],
"No versions yet — one is kept every time you save.": ["まだバージョンはありません。保存するたびに 1 つ記録されます。","还没有版本——每次保存都会记录一个。","還沒有版本——每次儲存都會記錄一個。","Aún no hay versiones: se guarda una cada vez que guardas.","Pas encore de versions — une est conservée à chaque enregistrement.","Noch keine Versionen — bei jedem Speichern wird eine aufbewahrt.","Ancora nessuna versione: ne viene tenuta una a ogni salvataggio.","Ainda não há versões — é guardada uma sempre que gravas."],
@@ -450,6 +462,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Not in this file: it needs the network, and the site is told when someone opens the page": ["このファイルの中にはありません。再生にはネットワークが必要で、誰かがこのページを開いたことがそのサイトに伝わります","不在此文件内:播放需要联网,而且该网站会知道有人打开了这个页面","不在這個檔案裡:播放需要網路,而且該網站會知道有人開啟了這個頁面","No está en este archivo: necesita la red, y ese sitio sabrá que alguien ha abierto esta página","N’est pas dans ce fichier : la lecture nécessite le réseau, et ce site saura que quelqu’un a ouvert cette page","Nicht in dieser Datei: das Abspielen braucht das Netz, und die Website erfährt, dass jemand diese Seite geöffnet hat","Non è dentro questo file: per riprodurla serve la rete, e quel sito saprà che qualcuno ha aperto questa pagina","Não está neste ficheiro: precisa da rede, e esse site fica a saber que alguém abriu esta página"],
"Not live — turns on when you share": ["未接続 — 共有すると自動的にライブになります","未上线 — 分享时自动开启","未上線 — 分享時自動開啟","Sin conexión — se activa al compartir","Hors ligne — s’active quand vous partagez","Nicht live — startet beim Teilen","Non live — si attiva quando condividi","Fora do ar — ativa quando você compartilha"],
"Not loaded — opening it would tell that site you opened this space.": ["未読み込み — 読み込むと、このスペースを開いたことがそのサイトに伝わります。","未加载 — 加载会让该网站知道你打开了这个空间。","未載入 — 載入會讓該網站知道你開啟了這個空間。","No cargada: al cargarla, ese sitio sabría que has abierto este espacio.","Non chargée : la charger indiquerait à ce site que vous avez ouvert cet espace.","Nicht geladen — beim Laden erfährt diese Website, dass du diesen Space geöffnet hast.","Non caricata: caricarla direbbe a quel sito che hai aperto questo spazio.","Não carregada — carregá-la diria a esse site que você abriu este espaço."],
+ "Not recorded": ["記録なし","未记录","未記錄","Sin registrar","Non enregistré","Nicht erfasst","Non registrato","Não registado"],
"Not sharing yet — click to start a live session": ["まだ共有していません — クリックしてライブセッションを開始","尚未共享 — 点击开始实时协作","尚未共享 — 點擊開始即時協作","Aún no se comparte — haz clic para iniciar una sesión en vivo","Pas encore partagé — cliquez pour démarrer une session en direct","Noch nicht geteilt — zum Starten einer Live-Sitzung klicken","Non ancora condiviso — clicca per avviare una sessione dal vivo","Ainda não está compartilhando — clique para iniciar uma sessão ao vivo"],
"Note": ["メモ","备注","備註","Nota","Note","Hinweis","Nota","Nota"],
"Nothing changed": ["変更はありません","没有任何改动","沒有任何變更","No cambió nada","Rien n’a changé","Nichts hat sich geändert","Non è cambiato nulla","Nada mudou"],
@@ -457,6 +470,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Nothing is fetched. A card shows what you type here — opening this space never contacts the site.": ["何も取得しません。カードにはここで入力した内容が表示され、このスペースを開いてもサイトに接続することはありません。","不会抓取任何内容。卡片显示的就是你在这里输入的内容——打开这个空间绝不会联系该网站。","不會抓取任何內容。卡片顯示的就是你在這裡輸入的內容——開啟這個空間絕不會連線到該網站。","No se descarga nada. La tarjeta muestra lo que escribas aquí: abrir este espacio nunca contacta con el sitio.","Rien n’est récupéré. La carte affiche ce que vous saisissez ici — ouvrir cet espace ne contacte jamais le site.","Es wird nichts abgerufen. Die Karte zeigt, was Sie hier eintragen — das Öffnen dieses Space kontaktiert die Website nie.","Non viene scaricato nulla. La scheda mostra ciò che scrivi qui: aprire questo spazio non contatta mai il sito.","Nada é obtido. O cartão mostra o que você escrever aqui — abrir este espaço nunca contacta o site."],
"Nothing leaves this file until you start a session.": ["セッションを開始するまで、このファイルから外に出るものはありません。","在你开始会话之前,没有任何内容离开这个文件。","在你開始工作階段之前,沒有任何內容離開這個檔案。","Nada sale de este archivo hasta que inicies una sesión.","Rien ne quitte ce fichier tant que vous n’avez pas démarré de session.","Nichts verlässt diese Datei, bis du eine Sitzung startest.","Niente esce da questo file finché non avvii una sessione.","Nada sai deste ficheiro até iniciares uma sessão."],
"Nothing on this canvas yet.": ["このキャンバスにはまだ何もありません。","此画布上还没有内容。","此畫布上還沒有內容。","Aún no hay nada en este lienzo.","Rien sur ce canevas pour l’instant.","Auf dieser Leinwand ist noch nichts.","Non c’è ancora nulla su questa tela.","Ainda não há nada nesta tela."],
+ "Nothing recorded yet for this period.": ["この期間の記録はまだありません。","此周期尚无记录。","此週期尚無記錄。","Todavía no hay nada registrado en este periodo.","Rien n’est encore enregistré pour cette période.","Für diesen Zeitraum ist noch nichts erfasst.","Nulla di registrato per questo periodo.","Ainda não há nada registado neste período."],
"Nothing to draw yet — link two pages with [[ and they will appear here.": ["まだ描くものがありません — [[ で 2 つのページをつなぐと、ここに現れます。","还没有可绘制的内容 — 用 [[ 链接两个页面,它们就会出现在这里。","還沒有可繪製的內容 — 用 [[ 連結兩個頁面,它們就會出現在這裡。","Todavía no hay nada que dibujar — enlaza dos páginas con [[ y aparecerán aquí.","Rien à dessiner pour l’instant — reliez deux pages avec [[ et elles apparaîtront ici.","Noch nichts zu zeichnen — verknüpfe zwei Seiten mit [[ und sie erscheinen hier.","Non c’è ancora nulla da disegnare — collega due pagine con [[ e appariranno qui.","Ainda não há nada para desenhar — liga duas páginas com [[ e aparecerão aqui."],
"Now an issue": ["イシューになりました","现在是事项了","現在是項目了","Ahora es una incidencia","C’est désormais un ticket","Jetzt ein Issue","Ora è una issue","Agora é uma tarefa"],
"Number": ["数値","数字","數字","Número","Nombre","Zahl","Numero","Número"],
@@ -500,6 +514,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Paste document JSON here…": ["ここにドキュメント JSON を貼り付け…","在此粘贴文档 JSON…","在此貼上文件 JSON…","Pega aquí el JSON del documento…","Collez le JSON du document ici…","Dokument-JSON hier einfügen…","Incolla qui il JSON del documento…","Cole aqui o JSON do documento…"],
"Paste or type a link": ["リンクを貼り付けるか入力してください","粘贴或输入链接","貼上或輸入連結","Pega o escribe un enlace","Collez ou saisissez un lien","Link einfügen oder eingeben","Incolla o scrivi un collegamento","Cole ou digite um link"],
"People": ["メンバー","成员","成員","Personas","Personnes","Personen","Persone","Pessoas"],
+ "Period": ["期間","周期","週期","Periodo","Période","Zeitraum","Periodo","Período"],
+ "Period from {date}": ["{date} からの期間","自 {date} 起的周期","自 {date} 起的週期","Periodo desde el {date}","Période depuis le {date}","Zeitraum ab {date}","Periodo dal {date}","Período desde {date}"],
"Person": ["担当者","人员","人員","Persona","Personne","Person","Persona","Pessoa"],
"Picture": ["画像","图片","圖片","Imagen","Image","Bild","Immagine","Imagem"],
"Picture…": ["画像…","图片…","圖片…","Imagen…","Image…","Bild…","Immagine…","Imagem…"],
@@ -531,10 +547,12 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Reading view": ["閲覧ビュー","阅读视图","閱讀檢視","Vista de lectura","Mode lecture","Leseansicht","Vista di lettura","Modo de leitura"],
"Reading view — press Esc or the eye to edit": ["閲覧ビュー — Esc か目のアイコンで編集に戻ります","阅读视图 — 按 Esc 或点击眼睛图标即可编辑","閱讀檢視 — 按 Esc 或眼睛圖示即可編輯","Vista de lectura — pulsa Esc o el ojo para editar","Vue lecture — appuyez sur Esc ou sur l’œil pour modifier","Leseansicht — Esc oder das Auge zum Bearbeiten","Vista di lettura — premi Esc o l’occhio per modificare","Vista de leitura — prima Esc ou o olho para editar"],
"Reading {n} file(s)…": ["{n} 個のファイルを読み込み中…","正在读取 {n} 个文件…","正在讀取 {n} 個檔案…","Leyendo {n} archivo(s)…","Lecture de {n} fichier(s)…","Lese {n} Datei(en)…","Lettura di {n} file…","A ler {n} ficheiro(s)…"],
+ "Recording starts here": ["ここから記録開始","记录从此开始","記錄從此開始","El registro empieza aquí","L’enregistrement commence ici","Aufzeichnung beginnt hier","La registrazione inizia qui","O registo começa aqui"],
"Red": ["赤","红色","紅色","Rojo","Rouge","Rot","Rosso","Vermelho"],
"Redo": ["やり直す","重做","重做","Rehacer","Rétablir","Wiederholen","Ripristina","Refazer"],
"Redo (⇧⌘Z)": ["やり直す (⇧⌘Z)","重做 (⇧⌘Z)","重做 (⇧⌘Z)","Rehacer (⇧⌘Z)","Rétablir (⇧⌘Z)","Wiederholen (⇧⌘Z)","Ripeti (⇧⌘Z)","Refazer (⇧⌘Z)"],
"Reload into new version": ["再読込して新バージョンへ","重新加载进入新版本","重新載入進入新版本","Recargar en la nueva versión","Recharger dans la nouvelle version","Neu laden in die neue Version","Ricarica nella nuova versione","Recarregar na nova versão"],
+ "Remaining": ["残り","剩余","剩餘","Restante","Restant","Verbleibend","Rimanente","Restante"],
"Remove": ["削除","移除","移除","Quitar","Retirer","Entfernen","Rimuovi","Remover"],
"Remove password…": ["パスワードを削除…","移除密码…","移除密碼…","Quitar contraseña…","Supprimer le mot de passe…","Passwort entfernen…","Rimuovi password…","Remover palavra-passe…"],
"Remove the password": ["パスワードを削除","移除密码","移除密碼","Quitar la contraseña","Supprimer le mot de passe","Passwort entfernen","Rimuovi la password","Remover a palavra-passe"],
@@ -583,6 +601,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Same as parent": ["親ページと同じ","与上级页面相同","與上層頁面相同","Igual que la página superior","Comme la page parente","Wie die übergeordnete Seite","Come la pagina superiore","Igual à página superior"],
"Same as space": ["スペースと同じ","与空间相同","與空間相同","Igual que el espacio","Comme l’espace","Wie der Space","Come lo spazio","Igual ao espaço"],
"Same pages, new identity — it never syncs with this one": ["同じページ、新しい ID — このスペースとは同期しません","页面相同,身份全新 — 永不与此空间同步","頁面相同,身分全新 — 永不與此空間同步","Las mismas páginas, una identidad nueva — nunca se sincroniza con este","Les mêmes pages, une nouvelle identité — il ne se synchronise jamais avec celui-ci","Dieselben Seiten, neue Identität — synchronisiert nie mit diesem Space","Le stesse pagine, una nuova identità — non si sincronizza mai con questo","As mesmas páginas, uma nova identidade — nunca sincroniza com este"],
+ "Sampled, not daily": ["サンプル(毎日ではありません)","抽样,非每日","抽樣,非每日","Muestreado, no diario","Échantillonné, pas quotidien","Stichprobe, nicht täglich","Campionato, non giornaliero","Amostrado, não diário"],
"Save": ["保存","保存","儲存","Guardar","Enregistrer","Speichern","Salva","Guardar"],
"Save (⌘S)": ["保存 (⌘S)","保存 (⌘S)","儲存 (⌘S)","Guardar (⌘S)","Enregistrer (⌘S)","Speichern (⌘S)","Salva (⌘S)","Guardar (⌘S)"],
"Save a copy…": ["コピーを保存…","保存副本…","儲存副本…","Guardar una copia…","Enregistrer une copie…","Kopie speichern…","Salva una copia…","Guardar uma cópia…"],
@@ -600,6 +619,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": ["送るためのコピーを保存します。開いた人はこの Space をあなたと一緒にライブ編集できます(エンドツーエンド暗号化)。あなたはオーナーのままで、メンバーリストからいつでも削除できます。","保存一份用于发送的副本。打开的人可与你实时共同编辑此 Space(端到端加密);你仍是所有者,可随时从成员列表中移除他们。","儲存一份用於傳送的副本。開啟的人可與你即時共同編輯此 Space(端對端加密);你仍是擁有者,可隨時從成員列表中移除他們。","Guarda una copia para enviar. Quien la abra editará este Space en vivo contigo (cifrado de extremo a extremo); tú sigues siendo el propietario y puedes quitarlos de la lista de Personas.","Enregistre une copie à envoyer. Qui l’ouvre édite cet espace en direct avec vous (chiffré de bout en bout) ; vous restez propriétaire et pouvez les retirer de la liste Personnes.","Speichert eine Kopie zum Versenden. Wer sie öffnet, bearbeitet diesen Space live mit dir (Ende-zu-Ende-verschlüsselt); du bleibst Eigentümer und kannst sie aus der Personenliste entfernen.","Salva una copia da inviare. Chi la apre modifica questo Space live con te (crittografia end-to-end); resti il proprietario e puoi rimuoverli dall’elenco Persone.","Salva uma cópia para enviar. Quem a abrir edita este Space ao vivo com você (com criptografia de ponta a ponta); você continua sendo o dono e pode removê-la na lista de Pessoas."],
"Saving a page keeps its blocks, its icon and its width.": ["ページを保存すると、ブロック・アイコン・幅がそのまま残ります。","保存页面会保留它的块、图标和宽度。","儲存頁面會保留它的區塊、圖示和寬度。","Al guardar una página se conservan sus bloques, su icono y su ancho.","Enregistrer une page conserve ses blocs, son icône et sa largeur.","Beim Sichern einer Seite bleiben ihre Blöcke, ihr Symbol und ihre Breite erhalten.","Salvando una pagina si conservano i suoi blocchi, la sua icona e la sua larghezza.","Guardar uma página mantém os seus blocos, o seu ícone e a sua largura."],
"Saving…": ["保存中…","保存中…","儲存中…","Guardando…","Enregistrement…","Speichere…","Salvataggio…","A guardar…"],
+ "Scope": ["全体量","总范围","總範圍","Alcance","Périmètre","Umfang","Ambito","Âmbito"],
"Search all pages (⌘K)": ["全ページを検索 (⌘K)","搜索所有页面 (⌘K)","搜尋所有頁面 (⌘K)","Buscar en todas las páginas (⌘K)","Rechercher dans toutes les pages (⌘K)","Alle Seiten durchsuchen (⌘K)","Cerca in tutte le pagine (⌘K)","Pesquisar em todas as páginas (⌘K)"],
"Search all pages, with nothing selected": ["何も選択せずに全ページを検索","未选中内容时,搜索所有页面","未選取內容時,搜尋所有頁面","Buscar en todas las páginas, sin nada seleccionado","Rechercher dans toutes les pages, sans sélection","Alle Seiten durchsuchen, wenn nichts markiert ist","Cerca in tutte le pagine, senza nulla selezionato","Pesquisar todas as páginas, sem nada selecionado"],
"Search all pages…": ["全ページを検索…","搜索所有页面…","搜尋所有頁面…","Buscar en todas las páginas…","Rechercher dans toutes les pages…","Alle Seiten durchsuchen…","Cerca in tutte le pagine…","Pesquisar em todas as páginas…"],
@@ -706,7 +726,10 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"This block has no settings of its own — its content is all of it.": ["このブロックに固有の設定はありません — 中身がすべてです。","这个块没有自己的设置 — 内容就是它的全部。","這個區塊沒有自己的設定 — 內容就是它的全部。","Este bloque no tiene ajustes propios: su contenido es todo lo que hay.","Ce bloc n’a pas de réglages à lui — son contenu, c’est tout.","Dieser Block hat keine eigenen Einstellungen — sein Inhalt ist alles.","Questo blocco non ha impostazioni proprie: il suo contenuto è tutto.","Este bloco não tem definições próprias — o conteúdo é tudo o que há."],
"This block is not nested": ["このブロックは入れ子になっていません","这个块没有嵌套","這個區塊沒有巢狀","Este bloque no está anidado","Ce bloc n’est pas imbriqué","Dieser Block ist nicht verschachtelt","Questo blocco non è annidato","Este bloco não está aninhado"],
"This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": ["このブラウザはファイルに書き戻せないため、保存のたびに新しいコピーができます。パソコンの Chrome と Edge なら直接上書き保存できます。","此浏览器无法写回原文件,因此每次保存都会生成新副本。电脑上的 Chrome 和 Edge 可以就地保存。","此瀏覽器無法寫回檔案,因此每次儲存都會產生新的副本。電腦版的 Chrome 和 Edge 可以就地儲存。","Este navegador no puede reescribir el archivo, así que cada guardado crea una copia nueva. Chrome y Edge en un ordenador sí pueden guardar en el sitio.","Ce navigateur ne peut pas réécrire le fichier : chaque enregistrement crée donc une nouvelle copie. Chrome et Edge sur ordinateur enregistrent sur place.","Dieser Browser kann nicht in die Datei zurückschreiben, deshalb entsteht bei jedem Speichern eine neue Kopie. Chrome und Edge auf dem Computer können direkt speichern.","Questo browser non può riscrivere il file, quindi ogni salvataggio crea una nuova copia. Chrome ed Edge su computer possono salvare sul posto.","Este navegador não consegue escrever de volta no ficheiro, por isso cada vez que guarda cria uma nova cópia. O Chrome e o Edge num computador conseguem guardar no local."],
+ "This chart has no period yet — a chart needs a window to draw.": ["このグラフにはまだ期間がありません — グラフには対象期間が必要です。","此图表尚无周期 — 图表需要一个时间窗口才能绘制。","此圖表尚無週期 — 圖表需要一個時間範圍才能繪製。","Este gráfico aún no tiene periodo: un gráfico necesita una ventana que dibujar.","Ce graphique n’a pas encore de période — un graphique a besoin d’une fenêtre à dessiner.","Dieses Diagramm hat noch keinen Zeitraum — ein Diagramm braucht ein Zeitfenster.","Questo grafico non ha ancora un periodo — un grafico ha bisogno di una finestra da disegnare.","Este gráfico ainda não tem período — um gráfico precisa de uma janela para desenhar."],
+ "This chart's period is gone.": ["このグラフの期間は失われました。","此图表的周期已不存在。","此圖表的週期已不存在。","El periodo de este gráfico ya no existe.","La période de ce graphique n’existe plus.","Der Zeitraum dieses Diagramms existiert nicht mehr.","Il periodo di questo grafico non esiste più.","O período deste gráfico já não existe."],
"This clip is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": ["このクリップは {size} あり、ファイルの中に一緒に入ります。その分、送る相手全員にとってファイルが大きくなります。それでも埋め込みますか?","这个片段有 {size},会嵌在文件内部,你发给谁,文件对谁就大出这么多。仍要嵌入吗?","這個片段有 {size},而且會跟著檔案一起走,你傳給的每個人拿到的檔案都會大這麼多。仍要嵌入嗎?","Este clip pesa {size} y viaja dentro del archivo, que crecerá otro tanto para todos a quienes se lo envíes. ¿Incrustarlo de todos modos?","Ce clip fait {size} et voyage dans le fichier, ce qui l’alourdit d’autant pour toutes les personnes à qui vous l’envoyez. L’intégrer quand même ?","Dieser Clip ist {size} groß und reist in der Datei mit — die Datei wird für jeden, dem du sie schickst, entsprechend größer. Trotzdem einbetten?","Questa clip è di {size} e viaggia dentro il file, rendendolo altrettanto più grande per chiunque la riceva. Incorporarla comunque?","Este clipe tem {size} e viaja dentro do ficheiro, tornando-o maior para todas as pessoas a quem o enviar. Incorporar mesmo assim?"],
+ "This copy does not include the day-by-day record.": ["このコピーには日ごとの記録が含まれていません。","此副本不包含逐日记录。","此副本不包含逐日記錄。","Esta copia no incluye el registro diario.","Cette copie n’inclut pas l’historique jour par jour.","Diese Kopie enthält die tägliche Aufzeichnung nicht.","Questa copia non include la registrazione giorno per giorno.","Esta cópia não inclui o registo diário."],
"This copy goes offline; the others carry on": ["このコピーはオフラインになります。ほかの人はそのまま続けられます","此副本将离线;其他人继续协作","此副本將離線;其他人繼續協作","Esta copia se desconecta; las demás siguen","Cette copie passe hors ligne ; les autres continuent","Diese Kopie geht offline; die anderen machen weiter","Questa copia va offline; le altre continuano","Esta cópia fica offline; as outras continuam"],
"This copy includes the space’s version history.": ["このコピーには、スペースのバージョン履歴が含まれます。","此副本包含空间的版本历史。","此副本包含空間的版本歷程。","Esta copia incluye el historial de versiones del espacio.","Cette copie inclut l’historique des versions de l’espace.","Diese Kopie enthält den Versionsverlauf des Space.","Questa copia include la cronologia delle versioni dello spazio.","Esta cópia inclui o histórico de versões do espaço."],
"This embed is inside itself — the loop stops here.": ["この埋め込みは自分自身を含んでいます。ここでループを止めました。","该嵌入包含了自身——循环在此停止。","這個嵌入包含了自身——迴圈在此停止。","Esta inserción se contiene a sí misma: el bucle se detiene aquí.","Cette insertion se contient elle-même — la boucle s’arrête ici.","Diese Einbettung enthält sich selbst – die Schleife endet hier.","Questa incorporazione contiene sé stessa — il ciclo si ferma qui.","Esta incorporação contém-se a si própria — o ciclo para aqui."],
@@ -867,6 +890,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"{a} to {b} — the end is before the start": ["{a} 〜 {b} — 終了日が開始日より前です","{a} 至 {b} — 结束日期早于开始日期","{a} 至 {b} — 結束日期早於開始日期","{a} a {b} — el fin es anterior al inicio","{a} à {b} — la fin est avant le début","{a} bis {b} — das Ende liegt vor dem Anfang","{a} – {b} — la fine è prima dell’inizio","{a} a {b} — o fim é anterior ao início"],
"{field} {op}": ["{field} が {op}","{field} {op}","{field} {op}","{field} {op}","{field} {op}","{field} {op}","{field} {op}","{field} {op}"],
"{field} {op} {value}": ["{field} が {value} {op}","{field} {op} {value}","{field} {op} {value}","{field} {op} {value}","{field} {op} {value}","{field} {op} {value}","{field} {op} {value}","{field} {op} {value}"],
+ "{id} (unknown)": ["{id}(不明)","{id}(未知)","{id}(未知)","{id} (desconocido)","{id} (inconnu)","{id} (unbekannt)","{id} (sconosciuto)","{id} (desconhecido)"],
"{i} of {n}": ["{i} / {n}","第 {i} 个,共 {n} 个","{i} / {n}","{i} de {n}","{i} sur {n}","{i} von {n}","{i} di {n}","{i} de {n}"],
"{name} joined": ["{name} が参加しました","{name} 已加入","{name} 已加入","{name} se ha unido","{name} a rejoint","{name} ist beigetreten","{name} si è unito","{name} entrou"],
"{name} left": ["{name} が退出しました","{name} 已离开","{name} 已離開","{name} se ha ido","{name} est parti","{name} hat verlassen","{name} se n'è andato","{name} saiu"],
diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.ts
index b82b657e..9b3525aa 100644
--- a/spaces/src/i18n/pt.ts
+++ b/spaces/src/i18n/pt.ts
@@ -966,6 +966,32 @@ export const pt: Catalog = {
"Clear history…": "Limpar o histórico…",
"First version kept in this file": "Primeira versão guardada neste ficheiro",
"Changes outside the pages — title, design, footnotes or templates": "Alterações fora das páginas — título, design, notas de rodapé ou modelos",
+ "Burndown": "Trabalho restante",
+ "Burndown, burnup or cumulative flow": "Trabalho restante, concluído ou fluxo acumulado",
+ "Burnup": "Trabalho concluído",
+ "Change period…": "Mudar período…",
+ "Chart of progress": "Gráfico de progresso",
+ "Choose a period…": "Escolher um período…",
+ "Committed on {date}": "Fixado em {date}",
+ "Completed": "Concluído",
+ "Cumulative flow": "Fluxo acumulado",
+ "Estimate points": "Pontos de estimativa",
+ "Ideal": "Ideal",
+ "Issue count": "Número de tarefas",
+ "New two-week period from today": "Novo período de duas semanas a partir de hoje",
+ "No status": "Sem estado",
+ "Not recorded": "Não registado",
+ "Nothing recorded yet for this period.": "Ainda não há nada registado neste período.",
+ "This copy does not include the day-by-day record.": "Esta cópia não inclui o registo diário.",
+ "Period": "Período",
+ "Period from {date}": "Período desde {date}",
+ "Recording starts here": "O registo começa aqui",
+ "Remaining": "Restante",
+ "Sampled, not daily": "Amostrado, não diário",
+ "Scope": "Âmbito",
+ "This chart has no period yet — a chart needs a window to draw.": "Este gráfico ainda não tem período — um gráfico precisa de uma janela para desenhar.",
+ "This chart's period is gone.": "O período deste gráfico já não existe.",
+ "{id} (unknown)": "{id} (desconhecido)",
"This copy includes the space’s version history.": "Esta cópia inclui o histórico de versões do espaço.",
"Leave version history out": "Deixar de fora o histórico de versões",
"Versions include text that was deleted. This file keeps them either way.": "As versões incluem texto que foi apagado. Este ficheiro guarda-as em qualquer caso.",
diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.ts
index b9e897e2..f50715e7 100644
--- a/spaces/src/i18n/zh-Hans.ts
+++ b/spaces/src/i18n/zh-Hans.ts
@@ -966,6 +966,32 @@ export const zh_Hans: Catalog = {
"Clear history…": "清除历史…",
"First version kept in this file": "此文件中保存的第一个版本",
"Changes outside the pages — title, design, footnotes or templates": "页面之外的改动——标题、设计、脚注或模板",
+ "Burndown": "燃尽图",
+ "Burndown, burnup or cumulative flow": "燃尽图、燃起图或累积流图",
+ "Burnup": "燃起图",
+ "Change period…": "更改周期…",
+ "Chart of progress": "进度图表",
+ "Choose a period…": "选择周期…",
+ "Committed on {date}": "于 {date} 确定",
+ "Completed": "已完成",
+ "Cumulative flow": "累积流图",
+ "Estimate points": "估算点数",
+ "Ideal": "理想线",
+ "Issue count": "事项数量",
+ "New two-week period from today": "从今天起的两周新周期",
+ "No status": "无状态",
+ "Not recorded": "未记录",
+ "Nothing recorded yet for this period.": "此周期尚无记录。",
+ "This copy does not include the day-by-day record.": "此副本不包含逐日记录。",
+ "Period": "周期",
+ "Period from {date}": "自 {date} 起的周期",
+ "Recording starts here": "记录从此开始",
+ "Remaining": "剩余",
+ "Sampled, not daily": "抽样,非每日",
+ "Scope": "总范围",
+ "This chart has no period yet — a chart needs a window to draw.": "此图表尚无周期 — 图表需要一个时间窗口才能绘制。",
+ "This chart's period is gone.": "此图表的周期已不存在。",
+ "{id} (unknown)": "{id}(未知)",
"This copy includes the space’s version history.": "此副本包含空间的版本历史。",
"Leave version history out": "不包含版本历史",
"Versions include text that was deleted. This file keeps them either way.": "版本中包含已删除的文字。无论如何,此文件都会保留它们。",
diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.ts
index 471be5f8..97b94585 100644
--- a/spaces/src/i18n/zh-Hant.ts
+++ b/spaces/src/i18n/zh-Hant.ts
@@ -966,6 +966,32 @@ export const zh_Hant: Catalog = {
"Clear history…": "清除歷史…",
"First version kept in this file": "此檔案中保存的第一個版本",
"Changes outside the pages — title, design, footnotes or templates": "頁面之外的變更——標題、設計、註腳或範本",
+ "Burndown": "燃盡圖",
+ "Burndown, burnup or cumulative flow": "燃盡圖、燃起圖或累積流圖",
+ "Burnup": "燃起圖",
+ "Change period…": "變更週期…",
+ "Chart of progress": "進度圖表",
+ "Choose a period…": "選擇週期…",
+ "Committed on {date}": "於 {date} 確定",
+ "Completed": "已完成",
+ "Cumulative flow": "累積流圖",
+ "Estimate points": "估算點數",
+ "Ideal": "理想線",
+ "Issue count": "議題數量",
+ "New two-week period from today": "從今天起的兩週新週期",
+ "No status": "無狀態",
+ "Not recorded": "未記錄",
+ "Nothing recorded yet for this period.": "此週期尚無記錄。",
+ "This copy does not include the day-by-day record.": "此副本不包含逐日記錄。",
+ "Period": "週期",
+ "Period from {date}": "自 {date} 起的週期",
+ "Recording starts here": "記錄從此開始",
+ "Remaining": "剩餘",
+ "Sampled, not daily": "抽樣,非每日",
+ "Scope": "總範圍",
+ "This chart has no period yet — a chart needs a window to draw.": "此圖表尚無週期 — 圖表需要一個時間範圍才能繪製。",
+ "This chart's period is gone.": "此圖表的週期已不存在。",
+ "{id} (unknown)": "{id}(未知)",
"This copy includes the space’s version history.": "此副本包含空間的版本歷程。",
"Leave version history out": "不包含版本歷程",
"Versions include text that was deleted. This file keeps them either way.": "版本中包含已刪除的文字。無論如何,此檔案都會保留它們。",
diff --git a/spaces/src/inserts.ts b/spaces/src/inserts.ts
index 6c8d3404..0369f1d0 100644
--- a/spaces/src/inserts.ts
+++ b/spaces/src/inserts.ts
@@ -90,11 +90,11 @@ const TABLE: Array<Omit<InsertFamily, 'items'> & { items: Entry[] }> = [
tip: 'Add a table — edit the cells in place',
items: ['table'],
},
- {
- id: 'chart', label: 'Chart', icon: 'chart',
- tip: 'Add a chart of the issues in this space',
- items: ['chart'],
- },
+ // THE CHART FAMILY was planned here as a bar button of its own. Interim
+ // (2026-10-10), exactly as Embed sits in Image ▾: one more button tips the
+ // bar out of slides' width at 1440, so the chart of progress rides in View ▾
+ // instead, behind a rule — it charts the same issues the views show. When
+ // the bar has room, it comes back as a family with id 'chart'.
{
id: 'view', label: 'View', icon: 'board',
tip: 'Add a view of the issues in this space — a board, a list, a table or a gallery',
@@ -106,6 +106,9 @@ const TABLE: Array<Omit<InsertFamily, 'items'> & { items: Entry[] }> = [
view({ layout: 'calendar', label: 'Calendar', hint: 'Issues on their dates' }),
view({ layout: 'gantt', label: 'Timeline', hint: 'Issues across time' }),
view({ layout: 'workload', label: 'Workload', hint: 'Issues by person' }),
+ // the issues over TIME, from the record the file keeps of itself
+ // (charts.ts): not a view of the pages, so a rule sets it apart
+ { type: 'chart', rule: true },
// not a view of the issues but a surface you arrange by hand — the
// diagram family will be its home when it exists
{ type: 'canvas', rule: true },
diff --git a/spaces/src/main.ts b/spaces/src/main.ts
index 599bd2e2..c51b499f 100644
--- a/spaces/src/main.ts
+++ b/spaces/src/main.ts
@@ -24,6 +24,8 @@ import { t, locale, applyDirection } from './i18n'
import { i18nApi } from '../../kernel/src/i18n.ts'
import { parseDoc, uid, newPage, type SpacesDoc, type ParseResult } from './model'
import { recoveryOffered, restoreInto } from './restoregate'
+import { recordTrail } from './observe.ts'
+import { protectedDays } from './periods.ts'
import {
validateDoc, outlineDoc, statsDoc,
planInsertBlocks, planUpdateBlock, planRemoveBlocks, planMoveBlock, planUpdatePage, planRemovePage,
@@ -398,6 +400,20 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
return saved.value
}
+ /**
+ * Today's row, if this space is a tracker and this copy may write at all.
+ *
+ * A READER COPY AND A SEALED READING COPY WRITE NOTHING. `store.readOnly`
+ * covers both, and it is the same check every other writer in this app makes
+ * — a trail row is a write, and "opening a file does not modify it" has no
+ * exception for a write the app made up itself.
+ */
+ const recordToday = (): void => {
+ if (store.readOnly) return
+ const today = todayISO()
+ recordTrail(store.doc, { today, protect: protectedDays(store.doc, today) })
+ }
+
// A recovery snapshot is the ONLY backstop on browsers with no file-system
// access — which is every browser on iOS.
//
@@ -422,6 +438,23 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
let timer: ReturnType<typeof setTimeout> | undefined
store.on('doc', () => {
clearTimeout(timer)
+ // THE TRAIL IS WRITTEN ON CHANGE, NEVER ON OPEN, and on the debounce that
+ // already exists rather than on a second one. It runs BEFORE the encryption
+ // guard below, on purpose: `doc.trail` is a document field, so it is inside
+ // the `bento/enc` envelope and encrypted by the same pass over the same
+ // JSON. There is no plaintext artefact beside the ciphertext, so — unlike a
+ // recovery snapshot — there is nothing to refuse. An encrypted space keeps
+ // its charts.
+ //
+ // Outside `store.commit` deliberately: a record of an observation is not an
+ // editing step and does not belong in anybody's undo stack (store.ts's
+ // snapshot excludes it — `trail` is history class). It is never synced
+ // either (the kernel's sync shape skips history fields): each replica keeps
+ // its own record of what it saw, as each keeps its own `revisions`.
+ //
+ // Written DURING editing, not at save — so, unlike `revisions`, it counts
+ // toward the recovery key (docclass.ts SPACES_NOT_EDIT does not list it).
+ recordToday()
if (isEncryptionActive()) return
timer = setTimeout(() => {
void putRecovery(store.doc)
diff --git a/spaces/src/model.ts b/spaces/src/model.ts
index 012dd149..90198ddd 100644
--- a/spaces/src/model.ts
+++ b/spaces/src/model.ts
@@ -23,6 +23,12 @@ import { esc, externalHref } from './sanitize.ts'
import { isPageRef } from './embed.ts'
import { projectForCopy, docContentKey as kernelContentKey } from '../../kernel/src/docfields.ts'
import { SPACES_FIELDS, SPACES_NOT_EDIT } from './docclass.ts'
+// A LEAF module (no imports at all), which is what lets the parser call into
+// it: the dotted-key fold has to run before anything else sees the document.
+import { foldDottedMapKeys } from './docmaps.ts'
+// Type-only, and therefore erased: no runtime dependency, no import cycle.
+import type { Trail } from './trail.ts'
+import type { Periods } from './periods.ts'
export const FORMAT = 'bento/spaces'
export const FORMAT_VERSION = 1
@@ -484,11 +490,22 @@ export interface SpacesDoc {
* read from a file is validated there before anything folds it. Absent when
* there is none — never `revisions: []`. `import type`, so no runtime cycle.
*
- * `trail` is declared for the tracker's burndown record; nothing in this
- * build reads or writes it.
+ * `trail` is THE RECORD: what was true on a day, for the tracker's burndown,
+ * burnup and cumulative-flow charts (trail.ts). Written while editing, never
+ * on open; each replica keeps its own. A row holds COUNTS and nothing else —
+ * no page ids, no assignee breakdown, no per-issue anything: that is a budget
+ * rule and a privacy rule at once, written here so a later session does not
+ * add the surveillance shape as the obvious next step.
*/
revisions?: SpacesRevision[]
- trail?: unknown
+ trail?: Trail
+ /**
+ * The windows the charts are about (periods.ts) — CONTENT, not history: a
+ * period is something a person decided, referenced by a chart block, undone
+ * by ⌘Z and synced (per key, `DOC_MAPS`). Totals only, never page ids.
+ * Absent until a period is started; deleted rather than emptied.
+ */
+ periods?: Periods
[extra: string]: unknown
}
@@ -580,6 +597,16 @@ export function parseDoc(json: string): ParseResult {
}
if (!isObj(raw)) return { ok: false, err: 'shape', detail: 'the document block is not a JSON object' }
+ // A PEER RUNNING AN OLDER SHAPE writes a doc-level map entry as a literal
+ // top-level key: it receives `set k="periods.pd-1"`, cannot resolve
+ // `periods` as a map, and stores the dotted name verbatim — which additivity
+ // would then preserve forever. Folding it back is cheap, deterministic and
+ // self-healing, and it repairs files that were damaged before this existed.
+ // Done HERE rather than in a kernel handshake: the hazard belongs to any
+ // future doc-level map, and six lines in a file this app owns beat a change
+ // to shared machinery every app depends on.
+ foldDottedMapKeys(raw)
+
if (raw.format !== FORMAT) {
return {
ok: false,
diff --git a/spaces/src/observe.ts b/spaces/src/observe.ts
new file mode 100644
index 00000000..a10a86fa
--- /dev/null
+++ b/spaces/src/observe.ts
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// COUNTING THE BOARD, and writing the count down once a day.
+//
+// ONE COUNTING RULE, NOT TWO. Rows are produced by the SAME code path the board
+// uses — `viewRows(doc, source)` and then the `ViewFilter` evaluator — so the
+// chart and the board can never disagree about what an issue is, and archived
+// pages are excluded from both because `viewRows` already excludes them. A
+// second counter here would be a second answer to a question the app has
+// already answered, and the two would drift the way two copies of one fact
+// always do.
+//
+// WHEN A ROW IS WRITTEN: on CHANGE, and NEVER ON OPEN.
+//
+// Writing on open is the tempting answer and it is wrong four separate ways.
+// Opening a file to read it must not modify it: a reading copy is sealed, the
+// static preview renders with JS off, a thumbnailer renders it, and
+// `doc.readonly` exists precisely so a file can be opened without being
+// touched. An open-writes trail would dirty a document nobody edited, prompt a
+// save, mint collaboration ops for merely looking, and add a row on a day the
+// team did no work — which is a lie in the shape of data.
+//
+// So: the first document change of the local day writes today's row, and every
+// later change of that day rewrites the same key. Two rows for one day is
+// unrepresentable, because the key IS the day; the second write overwrites the
+// first, so a day's row is the LAST observation of that day, which is also the
+// one a burndown wants. Save is not the trigger — but a save is a change, so an
+// ordinary session produces a row either way, and a live collaboration session
+// where nobody presses ⌘S still gets one.
+//
+// IMPLICIT: a space with no phase field writes no rows, so an ordinary notes
+// space is entirely unaffected and nothing turns itself on until somebody makes
+// their first issue.
+
+import type { SpacesDoc } from './model'
+import {
+ fieldsOf, phaseField, viewRows, passesFilter,
+ type FieldSpec, type ViewSource, type ViewFilter,
+} from './fields.ts'
+import {
+ type TrailRow, isDay, trailIsForeign, trailOf, writeRow, pruneTrail,
+ TRAIL_BUDGET, TRAIL_MAX, trailKey, clearTrail,
+} from './trail.ts'
+
+/** What the trail is counted over. Frozen onto a period at commit, so editing a
+ * view next month cannot retroactively redefine last month's sprint. */
+export interface Scope {
+ source?: ViewSource
+ filter?: ViewFilter
+}
+
+/**
+ * THE ESTIMATE FIELD — derived from the schema, never hardcoded.
+ *
+ * A document declares its own fields (`doc.fields`), so the number field a
+ * points burndown is about is whatever the schema says it is. `estimate` wins
+ * when it is a number field, because that is the default schema's name for it
+ * and a document that renamed something else to `estimate` deserves to be
+ * believed; otherwise the FIRST number field is it. No number field at all
+ * means a count burndown, which is a real answer rather than an empty chart.
+ */
+export function estimateField(doc: SpacesDoc): FieldSpec | undefined {
+ const fields = fieldsOf(doc)
+ const named = fields.find((f) => f?.key === 'estimate' && f.vt === 'number')
+ return named ?? fields.find((f) => f?.vt === 'number')
+}
+
+/** One day's counts, before they are filed under a key. */
+export interface Observation {
+ n: Record<string, number>
+ e?: Record<string, number>
+ x?: number
+}
+
+/**
+ * Count the board as it is RIGHT NOW.
+ *
+ * `null` when this space is not a tracker — no phase field, nothing to count,
+ * no row. That is also what makes today's point on every chart derived rather
+ * than read: this is the function the charts call for today.
+ *
+ * A status value this build does not know is counted under its own literal
+ * string, the rule `ViewFilter` already states — a newer build's option must
+ * not vanish from the count because this one cannot name it.
+ */
+export function observe(doc: SpacesDoc, scope: Scope = {}): Observation | null {
+ const pf = phaseField(doc)
+ if (!pf) return null
+ const ef = estimateField(doc)
+ const n: Record<string, number> = {}
+ const e: Record<string, number> = {}
+ let unestimated = 0
+ let anyEstimate = false
+
+ for (const row of viewRows(doc, scope.source)) {
+ if (!passesFilter(doc, row.values, scope.filter)) continue
+ const raw = row.values.get(pf.key)
+ // an issue with no status at all is still an issue; it is counted under the
+ // field's own default when it declares one, and otherwise under '' — which
+ // renders as "No status" rather than disappearing from the total.
+ const id = String(raw ?? pf.def ?? '')
+ n[id] = (n[id] ?? 0) + 1
+ if (!ef) continue
+ const v = Number(row.values.get(ef.key))
+ if (Number.isFinite(v)) { e[id] = (e[id] ?? 0) + v; anyEstimate = true }
+ else unestimated++
+ }
+
+ if (!Object.keys(n).length) return { n: {} }
+ return {
+ n,
+ // ABSENT when nothing is estimated, so a count-only board costs no bytes
+ // for a column of zeroes.
+ ...(anyEstimate ? { e } : {}),
+ // The count of issues with NO estimate. A points burndown drawn over a
+ // backlog where a third of the issues are unestimated is a picture of
+ // nothing — today you can see that, and on 3 September you could not.
+ ...(anyEstimate && unestimated ? { x: unestimated } : {}),
+ }
+}
+
+/** An observation as a row. Separate from `observe` so a period's baseline can
+ * be taken from the same numbers without minting a row. */
+export const rowOf = (obs: Observation): TrailRow => ({ ...obs })
+
+export interface RecordOpts extends Scope {
+ /** the LOCAL day, from journal.todayISO(). Injected so a rig is not at the
+ * mercy of a clock, and so the one place local time enters the trail is a
+ * call site rather than a library. */
+ today: string
+ /** the series this row belongs to; absent = the default series */
+ series?: string
+ /** days a prune must not thin — a period that is still running */
+ protect?: (day: string) => boolean
+}
+
+/**
+ * Write today's row and bring the trail back under `TRAIL_BUDGET`.
+ *
+ * Returns the row written, or null when nothing was (not a tracker, a foreign
+ * `trail`, a day this build cannot read, or a read-only document — the caller
+ * owns that last check).
+ *
+ * IDEMPOTENT WITHIN A DAY: N writes on one day produce exactly one key holding
+ * the last observation.
+ */
+export function recordTrail(doc: SpacesDoc, opts: RecordOpts): TrailRow | null {
+ if (trailIsForeign(doc) || !isDay(opts.today)) return null
+ const obs = observe(doc, opts)
+ if (!obs || !Object.keys(obs.n).length) return null
+
+ // keep whatever the existing row said about its own span: rewriting today
+ // after a thinning pass must not silently promote a sample back to a day.
+ const key = trailKey(opts.today, opts.series)
+ const prev = trailOf(doc)[key]
+ const row: TrailRow = rowOf(obs)
+ if (prev?.cut) row.cut = true
+
+ if (!writeRow(doc, opts.today, row, opts.series)) return null
+
+ const kept = pruneTrail(trailOf(doc), TRAIL_BUDGET, TRAIL_MAX, opts.protect ?? (() => false))
+ if (Object.keys(kept).length) doc.trail = kept
+ else clearTrail(doc)
+ return (doc.trail as Record<string, TrailRow> | undefined)?.[key] ?? row
+}
diff --git a/spaces/src/periods.ts b/spaces/src/periods.ts
new file mode 100644
index 00000000..d20411d1
--- /dev/null
+++ b/spaces/src/periods.ts
@@ -0,0 +1,235 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE PERIOD: the window a chart is about, and the scope it was committed to.
+//
+// ATTACHED TO THE DOCUMENT, not to a view and not to a page.
+//
+// · NOT A BLOCK. A sprint is not a property of one board. Two charts and three
+// views can be about the same sprint, and if the period lived on a block
+// each would carry its own copy and they would disagree about when the
+// sprint started. That is exactly the argument `fields.ts` makes for the
+// schema not being a value: "putting the status list on every issue would
+// copy it into every page and let two pages disagree about what Todo means."
+// · NOT A PAGE. Delete the page and the sprint's committed baseline dies with
+// it, retroactively falsifying every chart that referenced it.
+// · A MAP, not an array, for the reason `doc.trail` is one: two people
+// defining or closing different periods in one week must both keep theirs.
+// A fully-populated period is under 200 bytes and a period is never pruned,
+// so the budget question does not arise.
+//
+// SCOPE COMMITTED, WITHOUT DUPLICATING EVERY PAGE ID. `base` is a pair of
+// TOTALS — the issue count, the summed estimate and the unestimated count as
+// they were when the period was committed. That is the whole content of "scope
+// at commit time" for the chart that needs it: a burnup draws work completed
+// against total scope, and the gap between scope now and scope committed is the
+// scope-creep story. A line needs a number, not a membership list.
+//
+// What storing ids would add is knowing WHICH issues arrived mid-sprint, which
+// nobody asks a burnup for; what it would cost is ~14 bytes per issue per
+// period, a second copy of membership that can disagree with the pages, and
+// per-task data inside a mailed file, which the trail's privacy rule already
+// forbids. Said out loud, because it is a real loss: there is no per-issue
+// added/removed attribution, ever. If that turns out to matter, the honest
+// place for it is a scope-change EVENT somebody records deliberately, not a set
+// the app snapshots behind their back.
+//
+// THE SCOPE DEFINITION IS A FROZEN COPY of `ViewSource` + `ViewFilter`. Reusing
+// those two means no new selector language ships (the thing `fields.ts` warns
+// grows without limit and can never shrink), the chart's counting code is the
+// board's counting code, and freezing them at commit means editing a view next
+// month cannot retroactively redefine last month's sprint.
+
+import type { SpacesDoc } from './model'
+import type { ViewSource, ViewFilter } from './fields.ts'
+import { observe, type Scope } from './observe.ts'
+import { isDay, daysBetween, backfill, type TrailRow } from './trail.ts'
+
+export interface PeriodBase {
+ /** the day the baseline was ACTUALLY taken, which is not always `from` */
+ at: string
+ n: number
+ e?: number
+ x?: number
+}
+
+export interface Period {
+ label: string
+ /** inclusive local day labels */
+ from: string
+ to: string
+ /** FROZEN copies of the view selectors — the scope definition */
+ source?: ViewSource
+ filter?: ViewFilter
+ /** the trail series this period is charted from; absent = the default */
+ series?: string
+ /** scope AS COMMITTED. Totals only — never a list of page ids. */
+ base?: PeriodBase
+ closed?: true
+}
+
+export type Periods = Record<string, Period>
+
+const isObj = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v)
+
+/** A `periods` that is not an object is left alone and never written over —
+ * the rule additivity requires for a field this build cannot read. */
+export const periodsAreForeign = (doc: SpacesDoc): boolean =>
+ doc.periods !== undefined && !isObj(doc.periods)
+
+/**
+ * A period this build can draw.
+ *
+ * A period whose `to` precedes its `from`, whose dates are not days, or whose
+ * label is not a string arrives from a file somebody mailed you. None of them
+ * may throw and none may draw something misleading, so none of them is a
+ * period: `periodsOf` simply does not return it, and the chart that named it
+ * says its period is gone.
+ */
+export function isPeriod(v: unknown): v is Period {
+ if (!isObj(v)) return false
+ const { from, to } = v as { from?: unknown; to?: unknown }
+ if (!isDay(from) || !isDay(to)) return false
+ if (daysBetween(from, to) < 0) return false
+ return typeof v.label === 'string' || v.label === undefined
+}
+
+/** Every readable period, by id. Never creates the key by asking. */
+export function periodsOf(doc: SpacesDoc): Periods {
+ const raw = doc.periods
+ if (!isObj(raw)) return {}
+ const out: Periods = {}
+ for (const k of Object.keys(raw)) {
+ const p = raw[k]
+ if (isPeriod(p)) out[k] = { ...(p as Period), label: String((p as Period).label ?? '') }
+ }
+ return out
+}
+
+/** One period by id, or undefined — including for an id that is in the file but
+ * is not a period this build can read. */
+export const periodOf = (doc: SpacesDoc, id: string): Period | undefined => {
+ const all = periodsOf(doc)
+ return Object.hasOwn(all, id) ? all[id] : undefined
+}
+
+/** Periods in the order a chooser offers them: newest window first. */
+export function periodList(doc: SpacesDoc): Array<{ id: string; period: Period }> {
+ return Object.entries(periodsOf(doc))
+ .map(([id, period]) => ({ id, period }))
+ .sort((a, b) => (a.period.from < b.period.from ? 1 : a.period.from > b.period.from ? -1 : 0))
+}
+
+/** The scope a period was committed to. */
+export const scopeOf = (p: Period): Scope => ({
+ ...(p.source ? { source: p.source } : {}),
+ ...(p.filter ? { filter: p.filter } : {}),
+})
+
+/**
+ * Is this period still live — still running, or finished recently enough that
+ * its chart is still being read?
+ *
+ * This is what `pruneTrail` protects. A sprint that is still running must not
+ * have its own chart thinned underneath it, and neither must last sprint's
+ * retro. Thirty days after `to`, its rows are ordinary history.
+ */
+export function isLive(p: Period, today: string): boolean {
+ if (p.closed) return false
+ if (!isDay(today)) return true
+ return daysBetween(p.to, today) <= 30
+}
+
+/**
+ * The days no prune may thin: every day inside a live period's window.
+ *
+ * Returned as a PREDICATE rather than a set, because a window is a range and
+ * materialising a year of day strings to answer a question about one is waste.
+ */
+export function protectedDays(doc: SpacesDoc, today: string): (day: string) => boolean {
+ const live = Object.values(periodsOf(doc)).filter((p) => isLive(p, today))
+ if (!live.length) return () => false
+ return (day: string) =>
+ live.some((p) => daysBetween(p.from, day) >= 0 && daysBetween(day, p.to) >= 0)
+}
+
+export interface StartOpts {
+ label: string
+ from: string
+ to: string
+ /** the LOCAL day, from journal.todayISO() */
+ today: string
+ scope?: Scope
+ series?: string
+}
+
+/**
+ * Commit a period, in place. Returns its id, or null when the window is not one.
+ *
+ * `base` is computed from LIVE STATE right now, and `base.at` records the day
+ * that actually happened on. If `from` is in the past — somebody sets the chart
+ * up on day 4 — the chart labels the committed line "committed on 4 Sept"
+ * rather than pretending it was the 1st, and NO PAST TRAIL KEY IS FABRICATED.
+ * The days before the trail existed are gaps, and they are drawn as gaps.
+ *
+ * The one past key it may write is `from` itself, and only through `backfill`,
+ * which refuses to overwrite: a period committed today whose window starts
+ * today gets its first point immediately instead of an empty chart.
+ */
+export function startPeriod(doc: SpacesDoc, id: string, opts: StartOpts): string | null {
+ if (periodsAreForeign(doc)) return null
+ if (!isDay(opts.from) || !isDay(opts.to) || daysBetween(opts.from, opts.to) < 0) return null
+
+ const obs = observe(doc, opts.scope ?? {})
+ const period: Period = {
+ label: opts.label,
+ from: opts.from,
+ to: opts.to,
+ ...(opts.scope?.source ? { source: opts.scope.source } : {}),
+ ...(opts.scope?.filter ? { filter: opts.scope.filter } : {}),
+ ...(opts.series ? { series: opts.series } : {}),
+ }
+ if (obs) {
+ let n = 0
+ for (const k of Object.keys(obs.n)) n += obs.n[k]
+ let e: number | undefined
+ if (obs.e) { e = 0; for (const k of Object.keys(obs.e)) e += obs.e[k] }
+ period.base = {
+ at: isDay(opts.today) ? opts.today : opts.from,
+ n,
+ ...(e !== undefined ? { e } : {}),
+ ...(obs.x ? { x: obs.x } : {}),
+ }
+ // today's own row, if today is inside the window and nothing is there yet
+ if (isDay(opts.today) && daysBetween(opts.from, opts.today) >= 0 && daysBetween(opts.today, opts.to) >= 0) {
+ backfill(doc, opts.today, obs as TrailRow, opts.series)
+ }
+ }
+
+ const map: Periods = isObj(doc.periods) ? (doc.periods as Periods) : {}
+ map[id] = period
+ doc.periods = map
+ return id
+}
+
+/** Close a period: no further baseline recomputation, and its rows stop being
+ * protected from thinning. */
+export function closePeriod(doc: SpacesDoc, id: string): boolean {
+ if (periodsAreForeign(doc)) return false
+ const map = doc.periods as Periods | undefined
+ if (!isObj(map) || !Object.hasOwn(map, id) || !isPeriod(map[id])) return false
+ map[id] = { ...map[id], closed: true }
+ return true
+}
+
+/** Remove one period. The last one removed deletes the key outright — a space
+ * that had periods and then had none is byte-identical to one that never did. */
+export function removePeriod(doc: SpacesDoc, id: string): boolean {
+ if (periodsAreForeign(doc)) return false
+ const map = doc.periods as Periods | undefined
+ if (!isObj(map) || !Object.hasOwn(map, id)) return false
+ delete map[id]
+ if (!Object.keys(map).length) delete doc.periods
+ return true
+}
diff --git a/spaces/src/render.ts b/spaces/src/render.ts
index 5559b91b..e831d8fd 100644
--- a/spaces/src/render.ts
+++ b/spaces/src/render.ts
@@ -37,6 +37,7 @@ import { applyDesign, resolvePageDesign, type Resolved } from './designs.ts'
import { renderCanvasHead, placeCard } from './canvas.ts'
import { viewEmbed, anchorOf } from './embed.ts'
import { markRefs, notesOnPage, noteOf, noteId, refId, type PageNotes } from './footnotes.ts'
+import { renderChartBlock } from './charts.ts'
export interface RenderOpts {
/** editable per-block hosts (the editor); false for reader/print */
@@ -597,6 +598,16 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}, cal
return el
}
+ case 'chart': {
+ // A CHART OF THE TRAIL, not of the pages — see blocks.ts and charts.ts
+ // for why that makes it a block rather than a view layout. `todayISO()`
+ // is the reader's own wall-clock day: the today point is DERIVED from
+ // live state, every earlier day is read from the record.
+ el.classList.add('sp-chart')
+ renderChartBlock(el, b, doc, todayISO(), { editable: opts.editable === true })
+ return el
+ }
+
case 'callout': {
const raw = String(b.tone ?? 'note')
const known = TONE.has(raw) ? raw : 'note'
diff --git a/spaces/src/store.ts b/spaces/src/store.ts
index a02c99df..48e45a30 100644
--- a/spaces/src/store.ts
+++ b/spaces/src/store.ts
@@ -310,7 +310,11 @@ export class Store {
private snapshot(): string {
// assets are excluded: they are the largest thing in the document and never
// change during an ordinary edit, so snapshotting them 100 times is waste.
- // History fields are excluded too, and restored from live (keepLiveHistory)
+ // History fields are excluded too, and restored from live (keepLiveHistory).
+ // That includes `trail`: a row is an OBSERVATION written outside any
+ // commit, so an undo that restored it could put a stale row over a newer
+ // one. `periods` is content, NOT excluded: starting a period is something a
+ // person did, inside a commit, and ⌘Z takes it back like any other edit.
const { assets: _assets, ...rest } = this.doc as Record<string, unknown>
for (const k of HISTORY_KEYS) delete rest[k]
return JSON.stringify(rest)
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index d42eada1..f17ea829 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -2845,7 +2845,53 @@ body.sp-canvas-dragging { user-select: none; cursor: grabbing; }
.sp-cv-grip { display: none; }
}
+/* ——— CHARTS OF THE TRAIL ————————————————————————————————————————————————
+ Burndown, burnup, cumulative flow (src/charts.ts). The svg carries no
+ colours of its own beyond the band fills the schema declares, so the chrome
+ below is the one place light and dark are answered.
+
+ THE GAP AND THE SAMPLE ARE STYLED HERE AND NOWHERE ELSE. A hatched band
+ means "not recorded" and a dashed segment means "this reading stands for
+ more than a day"; both are content, not decoration, so both are legible on
+ a monochrome printout and neither depends on colour vision. */
+.sp-b-chart { margin: 0 0 18px; }
+.sp-chart-head { display: flex; align-items: baseline; flex-wrap: wrap; gap: 8px; margin-bottom: 6px; }
+.sp-chart-title { font-weight: 600; }
+.sp-chart-range { color: var(--muted); font-size: 12.5px; }
+.sp-chart-empty { color: var(--muted); font-size: 13.5px; margin: 6px 0; }
+/* 100% of the column, but never BIGGER than it was drawn: the viewBox is
+ 640×300, and scaling that up to a 1100px board page gave a 520px-tall chart
+ in the middle of a page of prose — measured. A chart is evidence in a
+ document, not a dashboard tile. */
+.sp-chart-svg { display: block; width: 100%; max-width: 640px; height: auto; overflow: visible; }
+.sp-chart-grid { stroke: var(--edge); stroke-width: 0.5; opacity: 0.5; }
+.sp-chart-axisline { stroke: var(--edge); stroke-width: 1; }
+.sp-chart-axis { fill: var(--muted); font-size: 10px; }
+.sp-chart-note { fill: var(--muted); font-size: 9.5px; }
+.sp-chart-hatch { stroke: var(--edge); stroke-width: 1.5; }
+.sp-chart-gap { opacity: 0.55; }
+.sp-chart-line { stroke-width: 2; fill: none; stroke-linecap: round; }
+/* A SAMPLE IS DASHED. Thinning keeps one row per week and drops the rest, so
+ the segment arriving at it covers days nobody observed one at a time — and a
+ weekly reading drawn as a solid daily line is the same lie as interpolating
+ a gap. */
+.sp-chart-sampled { stroke-dasharray: 5 4; }
+.sp-chart-sampledot { stroke: var(--bg); stroke-width: 1.5; }
+.sp-chart-band { opacity: 0.82; }
+.sp-chart-ideal { stroke: var(--muted); stroke-width: 1; stroke-dasharray: 2 4; }
+.sp-chart-committed { stroke: var(--muted); stroke-width: 1; stroke-dasharray: 8 4; }
+.sp-chart-cut { stroke: var(--edge); stroke-width: 2; }
+.sp-chart-legend { display: flex; flex-wrap: wrap; gap: 4px 14px; margin-top: 8px; font-size: 12px; color: var(--muted); }
+.sp-chart-key { display: inline-flex; align-items: center; gap: 6px; }
+.sp-chart-key i { width: 10px; height: 10px; border-radius: 2px; background: var(--edge); display: inline-block; }
+.sp-chart-keygap i { background: repeating-linear-gradient(45deg, var(--edge) 0 2px, transparent 2px 4px); }
+.sp-chart-keysample i { background: none; border-top: 2px dashed var(--muted); height: 0; border-radius: 0; }
+.sp-chart-pick { margin-top: 8px; }
+
@media print {
+ /* a chart is the page's evidence: it prints, whole, and without its control */
+ .sp-b-chart { break-inside: avoid; }
+ .sp-chart-pick, [data-chart-period] { display: none !important; }
/* the surface IS the content: it prints where it was placed, and it is not
broken across a page boundary */
.sp-b-canvas { break-inside: avoid; }
diff --git a/spaces/src/sync/crdt.ts b/spaces/src/sync/crdt.ts
index a8ea8932..5e0bec0d 100644
--- a/spaces/src/sync/crdt.ts
+++ b/spaces/src/sync/crdt.ts
@@ -13,6 +13,7 @@ export * from '../../../kernel/src/sync/crdt.ts'
import { SyncEngine, shape } from '../../../kernel/src/sync/crdt.ts'
import type { DocShape } from '../../../kernel/src/sync/crdt.ts'
+import { DOC_MAPS } from '../docmaps.ts'
/**
* bento/spaces: the document holds `pages`, a page holds `blocks`.
@@ -28,8 +29,19 @@ import type { DocShape } from '../../../kernel/src/sync/crdt.ts'
* pre-order array and the parent value, and cycle repair stays a pure function
* of the document. Trying to sync the tree as a hierarchy would put two sources
* of truth in the file.
+ *
+ * `DOC_MAPS` (docmaps.ts) are the doc-level keys merged PER KEY rather than as
+ * one value: today `periods`, so two people defining different periods in one
+ * week both keep theirs. `assets` and `blobs` are per-key for every app already.
+ *
+ * `trail` and `revisions` are not synced at all — the kernel's shape() skips
+ * every history-class field, so each replica keeps its own record.
+ *
+ * The list is docmaps.ts's, not a second copy: `model.ts parseDoc` folds dotted
+ * keys back using the same names, and two copies of that list is exactly how
+ * the hazard and its mitigation drift apart.
*/
-export const SPACES_SHAPE: DocShape = shape('pages', 'blocks')
+export const SPACES_SHAPE: DocShape = shape('pages', 'blocks', 'html', DOC_MAPS)
/** The engine bound to bento/spaces. */
export class SyncState extends SyncEngine {
diff --git a/spaces/src/trail.ts b/spaces/src/trail.ts
new file mode 100644
index 00000000..13d6f059
--- /dev/null
+++ b/spaces/src/trail.ts
@@ -0,0 +1,530 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE TRAIL: what was true on a day, written down because the day is over.
+//
+// THE RULE THIS FILE IS THE EXCEPTION-THAT-IS-NOT-ONE TO. `calc.ts` opens by
+// refusing to store an answer, `fields.ts viewRows` refuses to store the rows
+// ("a database that keeps its own copy of the rows is a database that disagrees
+// with the document"), and `model.ts tableOf` normalises at read time rather
+// than by rewriting. The rule underneath all three is narrower than "everything
+// derives", and this is it:
+//
+// Never store what the current document already implies.
+// Do store an observation it cannot reproduce.
+//
+// The past is not a function of the present state. No recomputation over
+// today's pages answers "how many points were open on 3 September", because the
+// only artefact that ever knew is gone. Four members of that class are already
+// in the format — `page.created`/`page.edited`, `Comment.at`, `Page.journal`
+// (the date a page IS) and `doc.revisions`. Every one is a
+// timestamped observation nobody can recompute. (docs/DECISIONS.md, 2026-09-11)
+//
+// THE FALSIFIABLE HALF, which the charts hold to: the TODAY point is derived
+// from live state, and only strictly-earlier days are read from here. Change an
+// estimate now and today's point moves immediately, exactly as calc.ts
+// promises. The trail is consulted only for days that have closed, where there
+// is nothing left to disagree with.
+//
+// WHAT A ROW MUST NEVER CONTAIN, and this is a budget rule and a privacy rule
+// at once: no page ids, no assignee breakdown, no per-issue anything. A "who
+// closed what, when" series is the surveillance shape of this feature, it grows
+// with the team, and it is excluded ON PURPOSE so a later session does not add
+// it as the obvious next step. What a trail DOES disclose, said plainly because
+// the field name does not suggest it: the CADENCE. Which days the file was
+// touched, which weeks nothing moved, work on a Sunday. That is why the field
+// map classes it `history` (docclass.ts): the kernel's copy table drops it from
+// every copy handed to someone else — a reader or view-only copy, the sealed
+// reading copy, a link, an audience copy, a template, Copy document JSON and a
+// page extract — and keeps it only in the file, a duplicate and an invite. No
+// builder strips it by hand; the class does, so a copy rule added later
+// covers it without anyone remembering to.
+//
+// FILE-LOCAL, NEVER SYNCED. The kernel's sync shape skips history-class fields,
+// so each replica keeps its own record of what it saw, as each keeps its own
+// `revisions`. Two people working on the same day each have a truthful row in
+// their own file; neither file is wrong.
+//
+// THIS FILE IS A LEAF: types only, no runtime imports.
+//
+// DAY ARITHMETIC IS TIMEZONE-FREE HERE, deliberately and unlike `journal.ts`.
+// A row key is a LOCAL day LABEL, minted once at the call site from
+// `journal.todayISO()` — the reader's own wall-clock day. Once it is a label,
+// turning it back into a local `Date` would reintroduce exactly the ambiguity
+// the label exists to have settled (and `new Date('2026-01-01')` is UTC
+// midnight, i.e. the previous day for half the planet). So every calculation
+// below goes through `dayIndex`, which is UTC ordinal arithmetic on the label
+// and cannot drift by a timezone, a DST boundary or a locale.
+
+import type { SpacesDoc } from './model'
+
+/**
+ * One day's observation.
+ *
+ * Keyed by STATUS OPTION ID, not by phase group. There are four groups and six
+ * default options; a CFD's bands are the board's columns, which are options —
+ * recording groups makes the CFD unbuildable, while recording options keeps it
+ * AND keeps burndown, because `FieldOption.group` derives a group from an
+ * option at render time. The reverse does not exist. Costs about 1.5× and buys
+ * the third chart.
+ *
+ * Consequence said out loud: the schema can change. An option deleted next
+ * month leaves a band in old rows with no label. The chart falls back to the
+ * raw id and says it does not know it — the rule `ViewFilter` already states
+ * for a value this build has never heard of.
+ */
+export interface TrailRow {
+ /** issues per status option id. Zero-valued options are omitted. */
+ n: Record<string, number>
+ /** summed estimate per status option id. Absent when nothing is estimated. */
+ e?: Record<string, number>
+ /** issues counted that carried no estimate, so a points chart can say so. */
+ x?: number
+ /** days this row stands for after thinning. Absent = 1 = a single day. */
+ s?: number
+ /** this is the oldest surviving row and older ones were dropped. */
+ cut?: true
+}
+
+/**
+ * `doc.trail`: observation key → what was true that day. A MAP, not an array.
+ *
+ * A MAP for two reasons:
+ *
+ * 1. "One row per day" becomes an invariant of the SHAPE rather than a rule
+ * somebody has to enforce. A second write on a day overwrites the first, so
+ * a day's row is the last observation of that day — which is also the one a
+ * burndown wants.
+ * 2. A row is addressable, so a write is idempotent.
+ *
+ * KEY: `YYYY-MM-DD`, or `<seriesId>/<YYYY-MM-DD>` when a period charts its own
+ * scope. The bare form IS the default series. Shipped now rather than later
+ * because the trail is PRE-AGGREGATED: the series is the only mechanism by
+ * which two different scopes can ever be charted, and retrofitting it would
+ * make every existing bare key mean "the default series" by archaeology.
+ */
+export type Trail = Record<string, TrailRow>
+
+// ---- days -----------------------------------------------------------------
+
+const SHAPE = /^\d{4}-\d{2}-\d{2}$/
+
+/**
+ * A REAL day label, not merely a digit-shaped string.
+ *
+ * `2026-13-99` matches the shape and is not a day; every formatter rolls it
+ * over into some OTHER real day and shows a confident wrong answer. The round
+ * trip is the check. UTC, not local — see the timezone note at the top: this is
+ * arithmetic on a label, and a label has no timezone.
+ */
+export function isDay(v: unknown): v is string {
+ if (typeof v !== 'string' || !SHAPE.test(v)) return false
+ const [y, m, d] = v.split('-').map(Number)
+ const at = new Date(Date.UTC(y, m - 1, d))
+ return at.getUTCFullYear() === y && at.getUTCMonth() === m - 1 && at.getUTCDate() === d
+}
+
+const DAY_MS = 86400000
+
+/** Days since the epoch, from the LABEL. Pure, and the same number in Kiritimati
+ * and in Niue — which is the whole point. */
+export function dayIndex(iso: string): number {
+ const [y, m, d] = iso.split('-').map(Number)
+ return Math.round(Date.UTC(y, m - 1, d) / DAY_MS)
+}
+
+const pad = (n: number) => String(n).padStart(2, '0')
+
+/** The label `n` days after `iso`. */
+export function addDays(iso: string, n: number): string {
+ return fromIndex(dayIndex(iso) + n)
+}
+
+export function fromIndex(i: number): string {
+ const at = new Date(i * DAY_MS)
+ return `${at.getUTCFullYear()}-${pad(at.getUTCMonth() + 1)}-${pad(at.getUTCDate())}`
+}
+
+/** Inclusive day count from `a` to `b`; negative when `b` precedes `a`. */
+export const daysBetween = (a: string, b: string): number => dayIndex(b) - dayIndex(a)
+
+/** Every day label from `from` to `to`, inclusive. Empty when `to` precedes
+ * `from` — a period whose `to` precedes its `from` must not throw and must not
+ * draw something misleading, so it draws nothing. Capped, because the range
+ * comes out of a file somebody mailed you. */
+export function dayRange(from: string, to: string, cap = 4000): string[] {
+ if (!isDay(from) || !isDay(to)) return []
+ const n = daysBetween(from, to)
+ if (n < 0) return []
+ const out: string[] = []
+ for (let i = 0; i <= Math.min(n, cap - 1); i++) out.push(addDays(from, i))
+ return out
+}
+
+/** The ISO-8601 week a day sits in, as a sortable `YYYY-Www` bucket key.
+ * Monday-based, because that is what "one row per week" means everywhere the
+ * sprint word is used. */
+export function weekKey(iso: string): string {
+ const i = dayIndex(iso)
+ // 1970-01-01 was a Thursday: (i + 3) makes Monday 0.
+ const monday = i - ((((i + 3) % 7) + 7) % 7)
+ return `w${monday}`
+}
+
+/** The month a day sits in. */
+export const monthKey = (iso: string): string => iso.slice(0, 7)
+
+// ---- keys ------------------------------------------------------------------
+
+/** The key a row is filed under. */
+export const trailKey = (day: string, series?: string): string =>
+ series ? `${series}/${day}` : day
+
+export interface TrailAddr { series: string; day: string }
+
+/**
+ * A key back into its parts, or null when it is not one this build can read.
+ *
+ * A key from a NEWER build (a second slash, a shape nobody here knows) is not
+ * an error and is never rewritten — it is simply not drawn, and it round-trips
+ * untouched like every other unknown thing in this format.
+ */
+export function parseTrailKey(k: string): TrailAddr | null {
+ const at = k.lastIndexOf('/')
+ const day = at < 0 ? k : k.slice(at + 1)
+ const series = at < 0 ? '' : k.slice(0, at)
+ if (!isDay(day)) return null
+ if (series.includes('/')) return null
+ return { series, day }
+}
+
+// ---- reading ---------------------------------------------------------------
+
+const isObj = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v)
+
+/**
+ * A `trail` that is not an object — some future build gave the name a different
+ * shape. It is LEFT ALONE and never written over, which is the rule history
+ * states for `revisions` and the rule additivity requires: a field this build
+ * cannot read is a field it must not destroy.
+ */
+export const trailIsForeign = (doc: SpacesDoc): boolean =>
+ doc.trail !== undefined && !isObj(doc.trail)
+
+/** The trail in force. `{}` when there is none, and never a key created as a
+ * side effect of asking. */
+export function trailOf(doc: SpacesDoc): Trail {
+ const raw = doc.trail
+ if (!isObj(raw)) return {}
+ const out: Trail = {}
+ for (const k of Object.keys(raw)) {
+ const row = raw[k]
+ // `Object.hasOwn` semantics by construction: Object.keys is own-enumerable
+ // only, so `trail.toString` from a hand-edited file is never reached.
+ if (isObj(row) && isObj(row.n)) out[k] = row as TrailRow
+ }
+ return out
+}
+
+/** One row's total issue count. Malformed and negative entries count as zero —
+ * a row out of a mailed file may say anything, and none of it may throw. */
+export function rowTotal(row: TrailRow): number {
+ let n = 0
+ for (const k of Object.keys(row.n ?? {})) {
+ const v = row.n[k]
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) n += v
+ }
+ return n
+}
+
+/** A row's count for one option id, clamped to a real, non-negative number. */
+export const countOf = (row: TrailRow, option: string): number => {
+ const m = row.n ?? {}
+ if (!Object.hasOwn(m, option)) return 0
+ const v = m[option]
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0
+}
+
+/** A row's summed estimate for one option id, or undefined when this row holds
+ * no estimates at all — which is different from an estimate of zero. */
+export function estimateOf(row: TrailRow, option: string): number | undefined {
+ const m = row.e
+ if (!isObj(m)) return undefined
+ if (!Object.hasOwn(m, option)) return 0
+ const v = (m as Record<string, unknown>)[option]
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0
+}
+
+/** Does this row carry estimates at all? */
+export const hasEstimates = (row: TrailRow): boolean => isObj(row.e)
+
+/** How many days a row stands for. Absent = 1. */
+export function spanOf(row: TrailRow): number {
+ const s = row.s
+ return typeof s === 'number' && Number.isFinite(s) && s >= 1 ? Math.floor(s) : 1
+}
+
+/** Every row of one series, oldest first. */
+export function seriesRows(trail: Trail, series = ''): Array<{ day: string; row: TrailRow }> {
+ const out: Array<{ day: string; row: TrailRow }> = []
+ for (const k of Object.keys(trail)) {
+ const addr = parseTrailKey(k)
+ if (!addr || addr.series !== series) continue
+ out.push({ day: addr.day, row: trail[k] })
+ }
+ out.sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : 0))
+ return out
+}
+
+/** The series ids present in a trail. '' is the default series. */
+export function seriesIds(trail: Trail): string[] {
+ const seen = new Set<string>()
+ for (const k of Object.keys(trail)) {
+ const addr = parseTrailKey(k)
+ if (addr) seen.add(addr.series)
+ }
+ return [...seen].sort()
+}
+
+// ---- writing ---------------------------------------------------------------
+
+/**
+ * Write one day's row, in place. Returns false when nothing was written.
+ *
+ * ONLY EVER TODAY'S KEY. There is no code path here that recomputes a past key
+ * — not "recompute the last 7 days", not "repair inconsistent rows". That is
+ * the guarantee behind "editing the past does not rewrite it": change an
+ * estimate today and yesterday's row cannot move, because nothing addresses it.
+ * The one other way a past key is created is `backfill`, below, which refuses
+ * to overwrite.
+ */
+export function writeRow(doc: SpacesDoc, day: string, row: TrailRow, series?: string): boolean {
+ if (trailIsForeign(doc) || !isDay(day)) return false
+ const trail: Trail = isObj(doc.trail) ? (doc.trail as Trail) : {}
+ trail[trailKey(day, series)] = row
+ doc.trail = trail
+ return true
+}
+
+/**
+ * Write a PAST key, only if it is absent. Returns false when one was already
+ * there.
+ *
+ * A row, once written, is immutable for the rest of the file's life. The only
+ * callers are committing a period whose window includes today and (if
+ * somebody writes one) a one-time import from `doc.revisions`.
+ */
+export function backfill(doc: SpacesDoc, day: string, row: TrailRow, series?: string): boolean {
+ if (trailIsForeign(doc) || !isDay(day)) return false
+ const trail = trailOf(doc)
+ if (Object.hasOwn(trail, trailKey(day, series))) return false
+ return writeRow(doc, day, row, series)
+}
+
+/**
+ * Remove the trail. NO KEY, never `trail: {}`.
+ *
+ * A space that was tracked and then cleared is byte-identical to one that never
+ * was — the rule `ViewFilter`, `ViewSource` and the view layout all follow, and
+ * the reason "Clear trail" can be offered as a real control rather than as a
+ * hide.
+ */
+export function clearTrail(doc: SpacesDoc): void {
+ delete doc.trail
+}
+
+// ---- the budget ------------------------------------------------------------
+//
+// THE TRAIL HAS ITS OWN CEILING, beside history's. `history.ts` keeps
+// `HISTORY_BUDGET` (128 KB) for `doc.revisions`; the trail keeps
+// `TRAIL_BUDGET` (32 KB) for itself. Together the record a space carries about
+// itself is at most 160 KB, the joint ceiling that was ruled acceptable — and
+// each side tiers on its own, so neither needs to know what the other is.
+//
+// 32 KB holds about six months of full daily rows (a year measured 61.5 KB at
+// ~172 B/row with estimates, 31.9 KB counts-only). Past it the oldest rows thin
+// to weekly, then monthly, then drop — the distant past loses resolution first.
+
+/** The trail's byte ceiling. With `HISTORY_BUDGET` it makes the 160 KB joint
+ * ceiling (scripts/test-spaces-trail.ts asserts the sum with a fixture). */
+export const TRAIL_BUDGET = 32 * 1024
+/** Rows kept at most, whatever their size. */
+export const TRAIL_MAX = 400
+
+const bytes = (v: unknown): number => (v === undefined ? 0 : JSON.stringify(v).length)
+
+/** What the trail currently costs, in serialized bytes. */
+export const trailBytes = (doc: SpacesDoc): number => bytes(doc.trail)
+
+// ---- pruning ---------------------------------------------------------------
+
+/**
+ * Bring a trail back under `TRAIL_BUDGET`, TIERING rather than failing —
+ * following PREVIEW_BUDGET and HISTORY_BUDGET.
+ *
+ * Tier 1 under both ceilings: every day kept, full resolution.
+ * Tier 2 thin the oldest rows to one per ISO week.
+ * Tier 3 thin the oldest rows to one per month.
+ * Tier 4 drop the oldest outright, and stamp `cut` on the new oldest.
+ *
+ * Resolution goes from the DISTANT PAST first: this quarter stays daily while
+ * last spring becomes weekly.
+ *
+ * THINNING SELECTS, IT NEVER AVERAGES. An averaged row is a number nobody
+ * observed — the same lie as interpolating a gap, written to disk. The survivor
+ * of a bucket is its LAST row, stamped `s` with the span it now stands for:
+ * from the earliest row it replaced through its own day. Days outside that span
+ * were never observed and stay gaps, so thinning cannot invent coverage.
+ *
+ * `protect` names days that must not be thinned — the rows of a period that is
+ * still running. A sprint must not have its own chart thinned underneath it.
+ */
+export function pruneTrail(
+ trail: Trail,
+ allowance = TRAIL_BUDGET,
+ max = TRAIL_MAX,
+ protect: (day: string) => boolean = () => false,
+): Trail {
+ let out: Trail = { ...trail }
+ const over = (t: Trail): boolean =>
+ bytes(t) > allowance || Object.keys(t).length > max
+ if (!over(out)) return out
+
+ for (const bucket of [weekKey, monthKey] as const) {
+ out = thin(out, bucket, protect)
+ if (!over(out)) return out
+ }
+
+ // Tier 4 — drop the oldest outright, per series, oldest first.
+ const keys = Object.keys(out)
+ .map((k) => ({ k, addr: parseTrailKey(k) }))
+ .filter((e): e is { k: string; addr: TrailAddr } => !!e.addr)
+ .sort((a, b) => (a.addr.day < b.addr.day ? -1 : a.addr.day > b.addr.day ? 1 : 0))
+ let cutAny = false
+ for (const e of keys) {
+ if (!over(out)) break
+ if (protect(e.addr.day)) continue
+ // never drop the last row of a series: a chart with no point at all says
+ // less than one with a single point and a "recording starts here" edge
+ if (seriesRows(out, e.addr.series).length <= 1) continue
+ delete out[e.k]
+ cutAny = true
+ }
+ if (cutAny) out = stampCut(out)
+ return out
+}
+
+/** Collapse each bucket to its last row, oldest bucket first, stopping as soon
+ * as the trail fits. */
+function thin(trail: Trail, bucket: (day: string) => string, protect: (day: string) => boolean): Trail {
+ const out: Trail = { ...trail }
+ for (const series of seriesIds(out)) {
+ const rows = seriesRows(out, series)
+ const groups = new Map<string, Array<{ day: string; row: TrailRow }>>()
+ for (const r of rows) {
+ const b = bucket(r.day)
+ const list = groups.get(b)
+ if (list) list.push(r)
+ else groups.set(b, [r])
+ }
+ for (const [, list] of groups) {
+ if (list.length < 2) continue
+ if (list.some((r) => protect(r.day))) continue
+ const keep = list[list.length - 1]
+ const first = list[0]
+ for (const r of list) if (r !== keep) delete out[trailKey(r.day, series || undefined)]
+ // the span it now stands for: from the earliest row it replaced through
+ // its own day, never further. Anything either side stays a gap.
+ const span = Math.max(spanOf(keep.row), daysBetween(first.day, keep.day) + spanOf(first.row))
+ const next: TrailRow = { ...keep.row }
+ if (span > 1) next.s = span
+ out[trailKey(keep.day, series || undefined)] = next
+ }
+ }
+ return stampCut(out)
+}
+
+/** `cut` marks the oldest surviving row of each series, so a chart draws its
+ * left edge as "recording starts here" instead of implying the project began
+ * at that value. Re-derived, never accumulated: a row that stops being the
+ * oldest loses the flag. */
+function stampCut(trail: Trail): Trail {
+ const out: Trail = { ...trail }
+ for (const series of seriesIds(out)) {
+ const rows = seriesRows(out, series)
+ rows.forEach((r, i) => {
+ const key = trailKey(r.day, series || undefined)
+ const wantCut = i === 0 && rows.length > 0
+ const had = r.row.cut === true
+ if (wantCut === had) return
+ const next = { ...r.row }
+ if (wantCut) next.cut = true
+ else delete next.cut
+ out[key] = next
+ })
+ }
+ return out
+}
+
+/** Was anything ever dropped from the front of this series? */
+export const wasCut = (trail: Trail, series = ''): boolean =>
+ seriesRows(trail, series)[0]?.row.cut === true
+
+// ---- drawing slots ---------------------------------------------------------
+
+/**
+ * WHAT A DAY IS, for anything that draws the trail.
+ *
+ * 'day' observed on that day, at full resolution.
+ * 'sample' covered by a thinned row that stands for a span ending later.
+ * 'gap' NOT RECORDED. Nobody opened the file; the weekend; a build that
+ * predates the feature.
+ *
+ * A GAP IS DRAWN AS A GAP. No interpolation, no carry-forward, no zero — a
+ * carried value is the worst of the three because it looks like data, and
+ * an interpolated weekend shows work happening on Sunday. Absent and zero must
+ * be visually distinct: a day with zero issues in `doing` is a point at zero, a
+ * day nobody opened the file is nothing at all.
+ */
+export type SlotKind = 'day' | 'sample' | 'gap'
+
+export interface Slot {
+ day: string
+ kind: SlotKind
+ /** the row this day reads from — absent for a gap */
+ row?: TrailRow
+ /** true on the day the row was actually keyed to (a sample's own day) */
+ anchor: boolean
+}
+
+/**
+ * One slot per day between `from` and `to`, inclusive.
+ *
+ * A thinned row covers the `s` days ending on its own key, and no more. The
+ * days it covers are 'sample'; its own day is the anchor, which is where a
+ * point is drawn.
+ */
+export function slots(trail: Trail, from: string, to: string, series = ''): Slot[] {
+ const days = dayRange(from, to)
+ if (!days.length) return []
+ const cover = new Map<string, { row: TrailRow; anchor: boolean; kind: SlotKind }>()
+ for (const { day, row } of seriesRows(trail, series)) {
+ const span = spanOf(row)
+ const kind: SlotKind = span > 1 ? 'sample' : 'day'
+ for (let back = 0; back < span; back++) {
+ const d = addDays(day, -back)
+ // a span never buries a day that was observed in its own right. Thinning
+ // deletes the rows it replaces so this cannot arise from our own writes,
+ // but the trail arrives in a file anyone can hand-edit.
+ if (back > 0 && cover.get(d)?.anchor) continue
+ cover.set(d, { row, anchor: back === 0, kind })
+ }
+ }
+ return days.map((day) => {
+ const c = cover.get(day)
+ return c
+ ? { day, kind: c.kind, row: c.row, anchor: c.anchor }
+ : { day, kind: 'gap' as const, anchor: false }
+ })
+}