@sudoke/kernel 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -241,6 +241,18 @@ npm run validate:releases <previous.json|null> <current.json> # release manife
241
241
  `validate:releases` is a REPOSITORY check command — `scripts/` is deliberately outside the published
242
242
  `files` list; installed consumers validate manifests through `validateReleaseManifest` (exported).
243
243
 
244
- ## Upgrading from 0.3.x
245
-
246
- See [the upgrade guide](https://github.com/lancemoon/sudoke/blob/main/docs/agents/dev/kernel-upgrade-guide.md) (Korean) — dependency bumps, the 0.4→0.5 check items (`catalogVersion` rename, full `fields` listing, new MCP common tools, replay rights re-proof) and the now-mandatory contract regime.
244
+ ## Builder guides (shipped in this package)
245
+
246
+ The guides below ship inside the npm tarball (`docs/`), so an agent building an app on the kernel
247
+ needs nothing beyond the installed package (`node_modules/@sudoke/kernel/docs/`). The links resolve
248
+ through unpkg, which serves the published tarball directly:
249
+
250
+ - [Domain development guide](https://unpkg.com/@sudoke/kernel/docs/domain-development-guide.md) —
251
+ writing a domain: commands, policies, projections, event contracts, the check suite.
252
+ - [Surface development guide](https://unpkg.com/@sudoke/kernel/docs/surface-development-guide.md) —
253
+ building a surface over the kernel's catalog·queries (UI conventions, the shared check).
254
+ - [Undo scope guide](https://unpkg.com/@sudoke/kernel/docs/undo-scope-guide.md) — deciding which
255
+ event types to open to the common undo, and what a domain·surface must provide for each.
256
+ - [Kernel upgrade guide](https://unpkg.com/@sudoke/kernel/docs/kernel-upgrade-guide.md) — upgrading
257
+ an app across kernel versions (dependency pairing, boot requirements, contract-carried writes,
258
+ migration).
@@ -0,0 +1,347 @@
1
+ # Domain development guide — how to write commands
2
+
3
+ > This document holds the practical knowledge an agent developing a domain needs.
4
+ > For background and principles, go to the concept documents; when you must write a command NOW,
5
+ > read this one.
6
+
7
+ The real work of building a new app is "writing commands well". One command = one business intent
8
+ (one application form).
9
+
10
+ ## 0. Contract — these 5 lines have no exceptions
11
+
12
+ 1. **Every write is a command** — `execute()` returns **events only**. No direct DB mutation
13
+ (UPDATE·INSERT·DELETE). The kernel applies projections and records audit in the same transaction.
14
+ 2. **Refusals are GateError + a registered code** — never `throw new Error`. Register new codes in
15
+ `domain/error-codes.ts` first and declare them on the command's `errors` (declaring an
16
+ unregistered code fails the assembly).
17
+ 3. **One file = one command, `commands/<object>/<verb>.ts`** — the command name IS the path
18
+ (`client.setRegion` → `commands/client/setRegion.ts`). Never pile a whole domain into one file —
19
+ the registries may not care, but the checks and navigation do.
20
+ 4. **Every new command starts from a one-page feature request** (the planner's form: one sentence /
21
+ procedure / rules) — never from code.
22
+ 5. **An addition is a five-part set** — the definition file + one registry line + (for a new event
23
+ type) contract·projection·history summary + two map lines + a smoke success/refusal pair. Missing
24
+ any one part fails the build·assembly·checks.
25
+
26
+ **Check**: `npm run check:domain` — mechanically verifies the set (registry·maps·history summary)
27
+ and the documented counts (the same bar as "before you commit" below).
28
+
29
+ ## 1. Start from the request — write it in plain language first
30
+
31
+ Before writing a command, fill in the planner's form (one sentence / procedure / rules) — with no
32
+ technical terms.
33
+
34
+ - **One sentence**: "[why it hurts] [someone does something] [what should become true]" — if it will
35
+ not fit in one sentence, the intent is two. Split it into two requests.
36
+ - **The procedure is one of three**: a one-shot task (most) / a state-passing task (e.g.
37
+ propose→confirm) / a bundle that must go at once (e.g. a transfer). This choice decides the shape
38
+ (a plain command / a state machine / a batch).
39
+ - **Rules must translate into refusals**: "manage it appropriately" ❌ → "a confirmed item cannot be
40
+ proposed again" ⭕ — positive or negative phrasing is free, but violating the rule must be
41
+ expressible as a refusal, or the gate cannot verify it and the tests cannot check it.
42
+
43
+ Translation mapping: the sentence's **action → a command**, **desired outcome → a domain event**,
44
+ **procedure → the transition table**, **rules → gate stages (rights·preconditions·invariants·
45
+ transitions)**.
46
+
47
+ Below are real examples built through this mapping — a casebook of one-page requests translated
48
+ into single commands:
49
+
50
+ | # | 1a. Pain (bank analogy) | 1b. Action | 1c. Outcome | Rule highlights | → command |
51
+ | --- | --- | --- | --- | --- | --- |
52
+ | 1 | Cannot attach memos to account transactions | the author edits the memo | reflected with an edit trail | author only / concurrent edit refused / trail preserved | note.update |
53
+ | 2 | A departed employee's approval rights linger | an admin revokes the approval right | that client's counter service is immediately unavailable | immediate effect / revocation recorded | client.unassignManager |
54
+ | 3 | An account sits under the wrong product | an admin moves it | descendant accounts move together | no cycles / depth kept / same-name refused / links kept | function.move |
55
+ | 4 | A client changed its trade name | an admin corrects the account holder name | reflected on every screen | the account number (code) is immutable | client.rename |
56
+ | 5 | An employee's title changed | an admin changes the title | rights reflect immediately | a demotion strips assigned accounts at once, unconditionally | user.setRole |
57
+ | 6 | Handling a departed employee | an admin deactivates the employee number | login·rights vanish immediately | transaction history preserved / reactivatable | user.setActive |
58
+ | 7 | A dissolved subsidiary's accounts linger in lists | an admin marks the account dissolved | excluded from queries | new transactions forbidden / history preserved / reopenable | client.setActive |
59
+
60
+ How to read it: read vertically and each column aligns with a translation output — **the pain stays
61
+ as background, the action becomes the command, the outcome becomes the event, the rules become gate
62
+ checks.** Rules like "immediately unavailable / vanishes immediately" are re-checked by the gate at
63
+ every execution, so no separate synchronization code is needed.
64
+
65
+ **Intake — how to ask the user.** What you take from the user is the intent (pain·action·outcome),
66
+ and that is enough — the procedure choice, the action splitting and the rule wording are drafted by
67
+ the agent from standard patterns and the domain definitions (planners should still fill in as much
68
+ as they can). While filling, when you hit something that **needs the user's judgment** — a policy
69
+ (allow/deny), an operational fact ("what time is the same-day transfer cutoff?"), a data scope (what
70
+ to store) — never invent the answer on the spot; ask **one at a time, in order**: attach options and
71
+ a recommendation so the answer fits in one word. Write every answer back into the request's rules
72
+ column — only the confirmed request is a contract; what is not written is not kept.
73
+
74
+ ## 2. The command definition form — every field connects to a gate stage
75
+
76
+ ```ts
77
+ {
78
+ name: 'client.recode', // object.verb — the source of the REST·MCP tool name (immutable after deployment)
79
+ description: 'Change a client code — …', // exposed verbatim in the catalog (agents read it)
80
+ example: 'POST /api/commands/client.recode {"clientId":"…","newCode":"DAEHYUN"}',
81
+ allowedRoles: ['admin'], // ③ policy: who
82
+ scope: 'none' | 'client', // ③ policy: whether the assignment-scope check applies
83
+ targetOf: (i) => i.clientId, // ③ policy: the client extractor the scope check uses (when scope:'client', synchronous)
84
+ input: z.object({ … }), // ④ schema — .describe() on every field (the source of catalog descriptions)
85
+ output: z.object({ … }).strict(), // ⑧ execution — the shape of a successful result (the gate checks it before commit·rolls back on mismatch)
86
+ errors: ['client.code_conflict'], // business error codes this command can produce (published in the catalog)
87
+ transition: { machine, command, current: async (i) => ({ id, status }) }, // ⑦ transition — stateful domains only
88
+ precondition: async (i) => {}, // ⑤ precondition — "does it exist" (refuse with GateError+code)
89
+ invariants: async (i, identity) => {}, // ⑥ invariants — "is it allowed by the rules" (the request's rules land here)
90
+ execute: async (i, identity) => ({ events, result }), // ⑧ execution — returns events only (result is checked against output)
91
+ version: '1.0.0', // required — the command contract's compatibility semver
92
+ behaviorRevision: '…', // optional — declare by hand when a meaning the fingerprint cannot capture changes (function bodies·business logic)
93
+ }
94
+ ```
95
+
96
+ **Every hook that reads storage is async** — declare `transition.current`·`precondition`·
97
+ `invariants`·`execute` as `async` and `await` every `db.prepare(…).get/all/run(…)` inside (the
98
+ storage port is an async contract). Only `targetOf` is synchronous (a pure function extracting an id
99
+ from the input — it reads no storage). Hooks that read nothing still take `async` — the contract
100
+ requires a Promise.
101
+
102
+ The refusal throw — the human sentence (reason) and the machine contract (code) together:
103
+
104
+ ```ts
105
+ throw new GateError(5, 'precondition', 'Client not found', {
106
+ code: 'client.not_found', // a code registered in domain/error-codes.ts (survives wording changes)
107
+ recovery: { query: 'clients' }, // optional: the query the refresh action re-reads
108
+ })
109
+ ```
110
+
111
+ ### A complete real file — `client/setRegion.ts` (copy this to start)
112
+
113
+ ```ts
114
+ import { z } from 'zod'
115
+ import { db, GateError, type CommandDefinition } from '@sudoke/kernel'
116
+ const input = z.object({
117
+ clientId: z.string().uuid().describe('client id'),
118
+ region: z.enum(['domestic', 'overseas']).describe('the region to set (domestic | overseas)'),
119
+ })
120
+ const output = z.object({
121
+ clientId: z.string().uuid().describe('client id'),
122
+ region: z.enum(['domestic', 'overseas']).describe('the region after the change'),
123
+ }).strict()
124
+
125
+ export const clientSetRegion: CommandDefinition<z.infer<typeof input>, z.infer<typeof output>> = {
126
+ name: 'client.setRegion',
127
+ description: "Change a client's region (admins only)",
128
+ example: 'POST /api/commands/client.setRegion {"clientId":"…","region":"overseas"}',
129
+ allowedRoles: ['admin'],
130
+ scope: 'none',
131
+ input,
132
+ output,
133
+ errors: ['client.not_found', 'client.same_region'],
134
+ precondition: async (i) => {
135
+ if (!(await db.prepare(`SELECT id FROM clients WHERE id=?`).get(i.clientId)))
136
+ throw new GateError(5, 'precondition', 'Client not found', { code: 'client.not_found', recovery: { query: 'clients' } })
137
+ },
138
+ execute: async (i, identity) => {
139
+ const c = (await db.prepare(`SELECT name, region FROM clients WHERE id=?`).get(i.clientId)) as any
140
+ if (c.region === i.region)
141
+ throw new GateError(5, 'precondition', `Already ${i.region}`, { code: 'client.same_region' })
142
+ return {
143
+ events: [
144
+ {
145
+ type: 'client.regionChanged',
146
+ aggregate_type: 'client',
147
+ aggregate_id: i.clientId,
148
+ payload: { clientId: i.clientId, oldRegion: c.region, newRegion: i.region, changedBy: identity.userId },
149
+ },
150
+ ],
151
+ result: { clientId: i.clientId, region: i.region },
152
+ }
153
+ },
154
+ }
155
+ ```
156
+
157
+ ### The five-part set — what you touch beyond the definition file
158
+
159
+ ```ts
160
+ // ① the registry (src/domain/commands/index.ts) — one import + the name on the export list
161
+ import { clientSetRegion } from './client/setRegion.js'
162
+ // … add clientSetRegion to the export list
163
+
164
+ // ② the event contract (src/domain/event-contracts.ts) — when the event type is new
165
+ 'client.regionChanged': z.object({ clientId: z.string(), oldRegion: z.string(), newRegion: z.string(), changedBy: z.string() }),
166
+
167
+ // ③ the projection rule (src/domain/app-projector.ts) — on('client.regionChanged', …)
168
+ // ④ the history summary — a one-line case in the default surface's summarize switch, in the app's language
169
+ // (placement is the surface's freedom — app 1 uses pages/Events.tsx)
170
+ case 'client.regionChanged':
171
+ return `Region changed — ${client(p.clientId)} ${…}`
172
+
173
+ // ⑤ the surface contract maps (src/domain/command-input-map.ts) — one line on each of the two maps
174
+ 'client.setRegion': InputOf<typeof clientSetRegion>
175
+ 'client.setRegion': OutputOf<typeof clientSetRegion>
176
+ ```
177
+
178
+ ```js
179
+ // ⑥ smoke (smoke.mjs) — always a success/refusal pair (a refusal is a contract too)
180
+ show('region change succeeds', await call(admin, 'POST', '/api/commands/client.setRegion', { clientId: cRoots[0], region: 'overseas' }), (r) => r.ok === true && r.result.region === 'overseas')
181
+ show('same value again → stage-5 refusal', await call(admin, 'POST', '/api/commands/client.setRegion', { clientId: cRoots[0], region: 'overseas' }), (r) => r.status === 409 && r.stage === 5)
182
+ ```
183
+
184
+ ### Undo policies and command versions (provided by the kernel)
185
+
186
+ The kernel ships the common undo contract and command version·fingerprint management — a single
187
+ regime since 0.5.0 (no compat mode, no `configureKernel`): every event type declares an undo policy
188
+ at boot and every command·query declares a version. What you choose per event type is support vs
189
+ `unavailable`. Registrations added at the assembly layer — the contract and examples live in
190
+ [packages/kernel/README.md](../README.md):
191
+
192
+ ```ts
193
+ registerUndoPolicies({ 'client.deleted': { kind: 'supported', handlerId: 'client-undo' } }) // per event type — unsupported must be declared too
194
+ registerUndoHandler({ id: 'client-undo', version: '1.0.0', compensationCommand: 'client.restore', plan: async (source, identity) => ({ … }) }) // the compensation planner (read-only); declares its one compensation command
195
+ registerCatalogRelease({ catalogVersion: '4.0.0', changes: […] }) // what this release changed — the source for change queries and the release validator
196
+ ```
197
+
198
+ ## 3. Writing principles (checklist)
199
+
200
+ 1. **Name**: `object.verb`. Folder=object, file=verb (e.g. `client/recode.ts`). **A command name is
201
+ immutable once deployed** — it is a catalog contract; renaming is a MAJOR bump.
202
+ 2. **Keep execute pure**: no direct DB mutation — **return events only**. Projection application
203
+ (read tables) and audit recording happen in the kernel's transaction. That is what makes
204
+ replay·audit·undo possible.
205
+ 3. **`.describe()` on every input·output field**: those descriptions become the catalog's field
206
+ documentation that agents read. Write description·example as "the manual an agent reads".
207
+ 4. **The output contract is mandatory**: assembly fails without `output`. It must match execute's
208
+ return shape exactly (a mismatch is a stage-8 refusal before commit·rollback); declare `z.null()`
209
+ when there is nothing to return.
210
+ 5. **Where checks go**: existence → precondition (stage 5), domain rules → invariants (stage 6),
211
+ state → transitions (stage 7). **Refusals are GateError + an error code**: the reason is a
212
+ next-action sentence in the app's user language, the code is the machine identifier. Register new
213
+ codes in `domain/error-codes.ts` first (with recovery·canForce) and declare them on the command's
214
+ `errors` — declaring an unregistered code fails the assembly.
215
+ 6. **Dangerous work follows the warning pattern**: hard-to-reverse deletes·merges are not executed
216
+ outright — they **refuse once as a warning** and run only on a confirmed retry (force:true); the
217
+ warning code is marked `canForce: true` in the registry. At the same time, leave a **snapshot in
218
+ the event payload** so restoration stays possible.
219
+ 7. **Common options are never declared on the command**: `requestKey` (idempotency)·`dryRun`
220
+ (pre-judgment) are protocol options the gate handles behind the command's back — keep them out
221
+ of the command's zod schema.
222
+ 8. **Stateful features fill the transition table**: instead of if-else per command, fill the
223
+ `{from, to, command, roles}` table — stage 7 enforces it, and the table is exposed in the catalog
224
+ (transitions) so agents know "the next legal move".
225
+ 9. **Dedicated restore commands only for operations where the target VANISHES**: delete·merge →
226
+ build a restore (a vanished target has no recovery path through ordinary commands). Changes to
227
+ living targets (name·position·state·code) → build no restore command — re-running with the
228
+ original value restores it (the old value is in the ledger history), and when a state machine is
229
+ involved, the backward transition (e.g. approval cancel) owns it. Undo is not rewind — it is a
230
+ **forward compensation passing the gate (a NEW write)**; rewinding to the past collides with
231
+ everything after it. (2026-11-13 — the kernel now provides this principle's common contract:
232
+ undo registration·preview·execution. See "Undo policies and command versions" above; how
233
+ hand-made restore commands coexist with it is decided at adoption time.)
234
+ 10. **The catalog is per-accessor**: `allowedRoles`·delegation scopes filter the catalog·tool lists
235
+ from the same source, and target restrictions (`scope`≠none·delegation `command:target`) surface
236
+ as `restriction` hints (a kernel visibility derivation — the gate re-judges at execution).
237
+ Role-restricted queries are **declared through the definition's `allowedRoles`** (never
238
+ role-check inside the handler — executeQuery and the catalog share the same declaration, and a
239
+ mismatched declaration fails the assembly). `public` and `allowedRoles` are never combined (a
240
+ public query is role-independent — a contradiction; the assembly fails). Row-level scopes (a
241
+ delegation token's client·tenant filter) remain the handler's job.
242
+
243
+ ## DO / DON'T — the shape of writes and refusals
244
+
245
+ ```ts
246
+ ❌ execute: async (i) => { await db.prepare('UPDATE clients SET region=?').run(i.region); return { events: [], result: null } }
247
+ ✅ execute: async (i) => ({ events: [{ type: 'client.regionChanged', …, payload: { … } }], result: { … } })
248
+ // the DB may be READ (queries, awaited) but never mutated — events cause every state change
249
+
250
+ ❌ throw new Error('already domestic')
251
+ ✅ throw new GateError(5, 'precondition', 'Already domestic', { code: 'client.same_region' })
252
+
253
+ ❌ errors: ['client.duplicated'] // a code never registered in error-codes.ts
254
+ ✅ register it in domain/error-codes.ts first (recovery·canForce included) → then declare it in errors
255
+
256
+ ❌ omitting output // the assembly fails
257
+ ✅ output: z.object({ … }).strict() // nothing to return → z.null()
258
+
259
+ ❌ input: z.object({ name: z.string(), requestKey: z.string().optional() })
260
+ ✅ input: z.object({ name: z.string() }) // requestKey·dryRun are gate protocol options — keep them out
261
+
262
+ ❌ renaming the command later: 'client.changeRegion' → 'client.setRegion'
263
+ ✅ name is immutable after deployment — it is a catalog contract; renaming is MAJOR. Name it right the first time
264
+ ```
265
+
266
+ ## 4. What accompanies a new command
267
+
268
+ - Add to the registry list (`src/domain/commands/index.ts`) → **REST·MCP derive automatically**
269
+ (surfaces touch nothing)
270
+ - When a surface calls the command, add one line to EACH of the input·output maps in
271
+ `domain/command-input-map.ts` (missing it fails the surface build)
272
+ - For a new event type: add the event contract (`domain/event-contracts.ts`) + the projection
273
+ (replay) case + a history-screen summary case (missing it refuses writes or shows the raw event
274
+ type on screen)
275
+ - Extend the smoke — **always a success path and a refusal path as a pair** (a refusal is a
276
+ first-class result — a contract; assert the code·recovery too)
277
+ - Update the catalog counts·documented numbers + a version bump (an addition = minor)
278
+
279
+ ### Before you commit — the same bar as `npm run check:domain`
280
+
281
+ ```bash
282
+ npm run check:domain # missing set parts·counts are checked mechanically (violations fail)
283
+ npm run typecheck && npm run smoke # + mcp:test·policy:test (when kernel contracts·transitions·rights are touched)
284
+ ```
285
+
286
+ - [ ] registry 1 line·maps 2 lines·(new event type) contract+projection+history summary — zero
287
+ missing parts
288
+ - [ ] one file=one command, `commands/<object>/<verb>.ts` — the command name is the path
289
+ - [ ] the smoke gained a success·refusal PAIR — refusals are contracts (assert the code·recovery)
290
+ - [ ] execute returns events only — zero direct DB writes
291
+ - [ ] new error codes registered in error-codes.ts first
292
+ - [ ] catalog counts·AGENTS numbers updated + a catalog version bump (minor)
293
+
294
+ ## 5. Starting a new app — checklist (in order)
295
+
296
+ 1. **Define the domain** — data (entities·hierarchy) · processes (states·transition tables) · rights
297
+ (roles·client scopes) as tables first
298
+ 2. **Design the command catalog** — build the defined domain into commands through
299
+ request→translation (§1~3 above)
300
+ 3. **Get the kernel·physical layer** — take `@sudoke/kernel` (the gate·ledger·registries·the
301
+ rights-judgment slot·the ledger-reflection slot·the storage port. Zero business·physical imports —
302
+ you never rewrite it) and a physical implementation package: a synchronous engine →
303
+ `@sudoke/infra-sqlite`, a network Postgres (Supabase etc.) → `@sudoke/infra-postgres`. **The
304
+ storage port is an async contract** — any engine honoring the port contract (write-lock
305
+ acquisition·sequential ledger appends·idempotency uniqueness·overlapping-transaction
306
+ serialization) plugs in; when needed you write only the physical package (the SQLite
307
+ implementation wraps a synchronous engine; the Postgres one is the network-engine example).
308
+ Engines that cannot honor the contract (transactionless KV stores) are outside this port to begin
309
+ with
310
+ 4. **Write the domain + assemble** — commands·transition tables·app-policy (rights judgment)·
311
+ app-projector (projection rules)·schema·event format contracts·error codes, then inject them
312
+ (assemble.ts is the single source). **Injection order: the physical layer before anything else** —
313
+ one line `sqliteStorage({ dataDir: process.env.XXX_DATA_DIR, jwtSecret: process.env.XXX_JWT_SECRET })`,
314
+ then ensureAppSchema. `db` is still imported from `@sudoke/kernel` (the handle connecting to the
315
+ registered physical layer — how you write domain SQL is unchanged). **Every registration
316
+ (commands·transitions·contracts·policies·projections·protocol·queries·physical layer) ends at
317
+ assembly time — registering after assembly fails (registry seal; assembleApp runs once per
318
+ process)**. `--rebuild` reconstructs
319
+ 5. **The self-describing catalog** — versions·the protocol preamble (refusal=result,
320
+ code·recovery·canForce, force, dry-run, requestKey, batch, cursors, transitions)·query metadata·
321
+ transition tables·the error-code dictionary. **The catalog comes out per accessor** (only the
322
+ commands·queries·transition rules inside the current role·delegation range — surfaces use the
323
+ kernel visibility derivation)
324
+ 6. **Queries** — descriptions·scope labels, the public allowlist, role restrictions declared through
325
+ the definition's `allowedRoles` (omitted = every role), row filters (when agents arrive)
326
+ 7. **Auth** — human login + **delegation tokens** (actor audit from day one). Passwords only in the
327
+ core login
328
+ 8. **Start with two surfaces** — one admin UI + a getting-started page (copy the first message + a
329
+ delegation-issue panel)
330
+ 9. **Automate the checks** — smoke (every gate stage + replay verification), check isolation (temp
331
+ DBs·free ports), typecheck. **The contract checks live in the shared package `@sudoke/dev-checks`**
332
+ (zero dependencies, two files — shipped beside the kernel). Register it in the app root
333
+ `package.json`:
334
+ ```jsonc
335
+ // an app in the same repository — connect as a dependency (never copy — single source)
336
+ "dependencies": { "@sudoke/dev-checks": "*" },
337
+ "scripts": { "check:domain": "node ../dev-checks/check-domain.mjs", "check:ui": "node ../dev-checks/check-ui.mjs" }
338
+
339
+ // an app outside the repository — copy the package's check-domain.mjs·check-ui.mjs into the app's scripts/, then
340
+ "scripts": { "check:domain": "node scripts/check-domain.mjs", "check:ui": "node scripts/check-ui.mjs" }
341
+ ```
342
+ Run from the app root: `npm run check:domain`·`npm run check:ui` — the domain file names
343
+ (commands/·event-contracts·app-projector·command-input-map) must match this guide's structure for
344
+ the checks to run (only the history summary's placement is the surface's freedom)
345
+ 10. **Operations** — backup = the one data directory, catalog version-bump rules, feature additions
346
+ through the request procedure, seeds·demo data in natural names (the demo's quality is the
347
+ checks' quality)
@@ -0,0 +1,171 @@
1
+ # Kernel upgrade guide — 0.3/0.4/0.5.x → 0.6
2
+
3
+ ## 0. 0.5.x → 0.6.0 (undo contract corrections)
4
+
5
+ Attaching undo to a real domain for the first time on 0.5.1 surfaced four contract corrections.
6
+ The backbone (compensation as a NEW write, the plan hash, loss confirmation, the one-compensation
7
+ guard, redelivery rights re-proof) is unchanged.
8
+
9
+ | # | Change | What you do |
10
+ |---|---|---|
11
+ | ① | **Undo handlers must declare `compensationCommand`** — one compensation command, declared statically. The seal check verifies it is registered, and the kernel checks the current identity's access to the declared command BEFORE `plan()` runs (a refusal answers `denied` and no plan is computed). A plan naming any other command is `undo.plan_invalid` | Add one line to the handler registration. The `mayPreview` hook becomes OPTIONAL (runs after the base checks when present) — a hook that only checked "can this identity run the compensation command" can be deleted |
12
+ | ② | **One permission vocabulary — `denied`** — permission refusals from `previewUndo` (read gate, handler gate, compensation-command role·delegation, denied targets) answer `denied` instead of `blocked`. On execution (`executeUndo`) permission refusals keep their own stage and code (1~3, e.g. `gate.role_denied`·`gate.delegation_denied`) — the stage-8 re-wrap is gone | App code that mined `preview.status === 'blocked'` for permission refusals adds a `denied` branch (handle it on the premise that no operation facts are present) |
13
+ | ③ | **App-wide origin-read gate `registerUndoReadGate`** — register one `mayRead` for the whole app. A policy-level `mayRead` wins where present | Assemblies that attached the same function once per event type replace it with a single registration. Boot condition: "every policy has `mayRead` OR the default gate is registered" (neither fails the boot — read rights are a declared decision; that principle stands) |
14
+ | ④ | **`undoStatus` cap** — `sourceSeqs` beyond `UNDO_STATUS_MAX_SEQS` (100) is a stage-4 input refusal (`gate.schema_invalid`). The old behavior of quietly handling the first 100 is gone | Screens that queried more than 100 seqs must page. The constant is exported from the kernel |
15
+
16
+ Kernel version **0.6.0** (a required handler field added = a 0.x breaking change → minor bump),
17
+ `PROTOCOL_VERSION` **1.1.0** (a new status in the preview response and a new field in catalog policy
18
+ entries — additive changes).
19
+
20
+ ### 0.6.1 (follow-up corrections — patch)
21
+
22
+ Reviewing 0.6.0 in practice reproduced two inconsistencies. Public types are unchanged, so `^0.6.0`
23
+ consumers receive it automatically.
24
+
25
+ | # | Change | What you do |
26
+ |---|---|---|
27
+ | ① | **Status and preview answer the same identity the same way** — the compensation-command access check moved into the shared judgment. An unauthorized identity's `undoStatus` row answers `denied` (code only) instead of `supported` (with handlerId) | Nothing (a correction). A `mayPreview` that only confirmed "this identity may run the compensation command" can now be REMOVED — status answers correctly on its own; the kernel checks before the plan |
28
+ | ② | **Redelivery re-proof no longer depends on the preview state** — when the source operation carries a STORED compensation, its recorded envelope (command·recorded target) re-proves the rights whatever the CURRENT policy consensus says (supported·unavailable·mixed alike — the policy may have moved since the compensation was stored). A removed compensation command leaves nothing re-provable → refused | A resent requestKey being refused after rights were revoked is intended behavior (a restoration of the original principle) |
29
+
30
+ Apps using the physical layer through kernel packages must move to the infra pair built for
31
+ ^0.6.0 — **infra-sqlite·infra-postgres 0.5.0** (declare `^0.5.0`) — together: the old pair carries a
32
+ `@sudoke/kernel ^0.5.0` dependency that does not satisfy 0.6.0, so npm nested-installs a registry
33
+ 0.5.x kernel that the infra pair binds to instead of your workspace copy. The catalog undo-policy
34
+ entry now publishes `compensationCommand`, so `catalogRevision` moves — read the changes with
35
+ `catalog_status` on reconnect. If a case arises where one handler must plan several compensation
36
+ commands, report it to the kernel (the current contract is one compensation command per handler).
37
+
38
+ ---
39
+
40
+ Moving an app built on `@sudoke/kernel` 0.3.x/0.4.x to **0.5.0**.
41
+
42
+ > **0.5.0 changes direction.** Through 0.4 the contract regime was opt-in (strict mode); 0.5.0
43
+ > **removes the compat/strict split and applies the contract regime unconditionally** — the legacy
44
+ > compat path is gone, and `configureKernel` itself no longer exists (delete the call).
45
+ >
46
+ > **It does not arrive by itself.** Under semver 0.x, `^0.4.0` does not include 0.5 — this guide is
47
+ > for apps that decided to bump. Not bumping changes nothing. Climbing only to 0.4 and adapting
48
+ > gradually is also fine (0.4 still has compat mode).
49
+
50
+ ## 1. Dependency updates
51
+
52
+ ```jsonc
53
+ // package.json
54
+ {
55
+ "dependencies": {
56
+ "@sudoke/kernel": "^0.5.0"
57
+ // only apps using the physical layer through kernel packages (the pair must move together):
58
+ , "@sudoke/infra-sqlite": "^0.4.0"
59
+ }
60
+ }
61
+ ```
62
+
63
+ - infra 0.4.0 keeps **existing DBs as they are** — if the events table lacks the meta column at boot,
64
+ it adds it in place (a lossless migration). No data move, no backup restore.
65
+ - The same rule for apps on `@sudoke/infra-postgres` (`^0.4.0`, `ADD COLUMN IF NOT EXISTS`).
66
+ - Kernel API details: [packages/kernel/README.md](../README.md) (English, shipped in this package).
67
+
68
+ ## 2. Boot requirements — failing these means the app does not start
69
+
70
+ 0.5.0's boot checks are all **unconditional**. At seal time (first execution or an explicit seal):
71
+
72
+ | Requirement | Content |
73
+ |---|---|
74
+ | Command·query versions | every command and query declares a semver like `version: '1.0.0'` |
75
+ | Undo policies | every **registered event type** has a policy — `{kind:'supported', handlerId}` or `{kind:'unavailable', code, reason}`. Support is optional, but **the declaration is mandatory** (silence is a defect) |
76
+ | Read-rights hooks | `mayRead` on every policy, `mayPreview` on every handler — "who reads undo history" must be a declared decision |
77
+ | Storage capability | the physical engine provides operationLedger (infra ^0.4.0 already does) |
78
+
79
+ > **From 0.6.0 two rows of this table change** — read rights become "every policy `mayRead` OR one
80
+ > app-wide default gate (`registerUndoReadGate`)", and the handler requirement becomes the
81
+ > **compensation-command declaration (`compensationCommand`, mandatory)** instead of `mayPreview`.
82
+ > See §0 ①·③ above for the migration. The infra pair moves too — infra-sqlite·infra-postgres 0.5.0
83
+ > (their kernel dependency is ^0.6.0) — or npm nested-installs a registry 0.5.x kernel.
84
+
85
+ ```ts
86
+ // the common minimal pattern — an app not using undo yet
87
+ registerUndoPolicies(
88
+ Object.fromEntries(
89
+ Object.keys(APP_EVENT_CONTRACTS).map((type) => [
90
+ type,
91
+ { kind: 'unavailable', code: 'app.not_reversible', reason: 'this event is not reversible', mayRead: async () => {} },
92
+ ]),
93
+ ),
94
+ )
95
+ ```
96
+
97
+ (The `app.not_reversible` code must be registered in `registerErrorCodes`.)
98
+
99
+ ## 3. Every write carries a contract — **the core 0.5.0 change**
100
+
101
+ Attach the contract read from the catalog to every write request:
102
+
103
+ ```ts
104
+ { ...businessInput, contract: { commandVersion, commandRevision, protocolVersion } }
105
+ ```
106
+
107
+ - Absent → `gate.contract_required`, stale → `gate.contract_changed` — **the refusal IS the guidance
108
+ to re-read the catalog** (recovery: refresh).
109
+ - **Solve it in ONE place**: the surface's shared api client (a common function like runCommand)
110
+ caches catalog state and attaches the contract automatically. No call-site sweep is needed.
111
+ - **On `gate.contract_changed`, re-learning comes first**: read the catalog state and the change
112
+ record (`catalog_changes`·`command_contract`), understand WHAT changed (version·input
113
+ meaning·warnings), then judge whether the original request still means the same thing. **Bumping
114
+ the revision and auto-resending is not safe** — a MAJOR change like a unit flip from cents to
115
+ dollars passes the new contract check yet executes a different amount than the user intended. The
116
+ kernel cannot prove that the caller understood the new contract.
117
+ - **Auto-retry only when meaning preservation is verifiable**: automate the retry only when the app
118
+ can EXPLICITLY judge that the change record does not touch input meaning ("description text only"),
119
+ and leave that judgment written in the code. "Same MAJOR" alone never substitutes for a meaning
120
+ check. When in doubt, show the new contract to the caller·agent and have the request rebuilt.
121
+ - Idempotent redelivery (a requestKey re-send) is judged BEFORE the contract check — a stored
122
+ success returns as-is even if today's schema changed.
123
+ - MCP tools take a `contract` parameter — external agents read the catalog (the `command_contract`
124
+ tool) first and attach it.
125
+
126
+ ## 4. What changed along the way (0.4 changes included)
127
+
128
+ | # | Change | What you do |
129
+ |---|---|---|
130
+ | ① | Catalog document·status field `version` renamed to **`catalogVersion`** (the old alias is dropped) | Only code reading the kernel catalog renames the field (an app's own state responses are unaffected) |
131
+ | ② | A catalog command's `fields` lists **every field, including undocumented ones** (value `null`) | Handle `null` when iterating fields |
132
+ | ③ | 7 common tools added to MCP `tools/list` — `catalog`·`catalog_status`·`catalog_changes`·`command_contract`·`undo_status`·`undo_preview`·`undo_execute` | Refresh lists validating tool names (tests included) — all snake_case |
133
+ | ④ | **Redelivery (idempotent replay) re-proves rights** — a stored success's re-send is re-judged against the recorded role·delegation range and the current assignments | Flows re-sending the same requestKey after rights were revoked are now refused (intended). **Rows older than producer tracking** are refused too — no re-proof material (the old `{unknown:true}` marker is gone) |
134
+ | ⑤ | MCP write values are now identical to the direct API — the double normalization (coerce·trim twice) is removed | No changes needed. Apps that saw subtly different values now see the same ones |
135
+ | ⑥ | Replay responses carry `producedBy` (the contract that produced the result) | May be ignored (an extra field) |
136
+
137
+ New error codes: `gate.contract_required`·`gate.contract_changed` (§3) and the ten `undo.*` codes
138
+ (only apps with undo on) — only apps that enumerate codes exhaustively need to update.
139
+
140
+ ## 5. From here it is optional — read separately from the mandatory assembly (§2)
141
+
142
+ - **Undo execution** — §2's policy declaration and `mayRead` are MANDATORY assembly requirements.
143
+ The optional part comes after: attaching an actual handler with `{kind:'supported', handlerId}`
144
+ (`registerUndoHandler`) to turn on `previewUndo`·`executeUndo`·`undoStatus`. Ending at
145
+ `unavailable` declarations boots and runs 0.5.0 completely. Undo is a forward compensation (a
146
+ NEW write); the original history is immutable.
147
+ - **Contract discovery tools** — `command_contract` (a machine-readable contract per command)·
148
+ `catalog_status`·`catalog_changes` (only the delta on reconnect). All optional.
149
+
150
+ ## 6. Upgrade procedure
151
+
152
+ ```
153
+ 1. Dependency bump (§1) → npm install
154
+ 2. Meet the boot requirements (§2) — version declarations·undo policies·mayRead — boot the app to verify
155
+ 3. Contract auto-attach in the one write path (§3) — contract_changed means re-learn then rebuild; auto-retry only with a meaning-preservation check (§3)
156
+ 4. §4 checks (① catalog field names ② fields null ③ tool list ④ replay rights)
157
+ 5. Run the app's own checks (smoke/MCP/policy — each app's own)
158
+ 6. (Optional) adopting undo is its own task — §5
159
+ ```
160
+
161
+ ## FAQ
162
+
163
+ **Q. What if I don't upgrade?** — Nothing changes. 0.3.x/0.4.x stay on npm.
164
+ **Q. Can I stop at 0.4?** — Yes. 0.4 has compat mode; §4's checks suffice, and the unconditional 0.5
165
+ regime can wait until you are ready.
166
+ **Q. Must I turn undo on right away?** — No. §2's `unavailable` declaration (mandatory) can be the
167
+ end; actual handlers·UI (optional) can come any time.
168
+ **Q. What about the DB?** — infra 0.4.0 migrates the existing file in place. Backups are always
169
+ wise, but no procedure is required.
170
+ **Q. What if a write carries no contract?** — Every write is refused with `gate.contract_required`.
171
+ Solve it with auto-attach in the one write path.
@@ -0,0 +1,222 @@
1
+ # Surface development guide — UI pattern rules (admin screens · skeleton · tables)
2
+
3
+ Rules for the page skeleton and tables of admin CRUD·list screens (function management, client
4
+ management, …). Nothing here is domain-specific — a new app's surfaces start from this same bar.
5
+
6
+ ## 0. Contract — these 4 lines have no exceptions
7
+
8
+ 1. **UI components are imported from `@/components/ui/*` only.** No raw `<button>` `<select>`
9
+ `<table>`, no hand-rolled modal `<div>`s.
10
+ 2. **A missing component is never hand-built** — add it with `npx shadcn@latest add <name>`.
11
+ (Custom non-control widgets (matrix cells etc.) may be hand-built — with semantic tokens only for
12
+ color·type — R13·R12. When a raw element is truly required, mark the line with
13
+ `/* check:ui-allow: reason */`.)
14
+ 3. **Looks·sizes·spacing follow the official shadcn docs** — this guide sets no numbers. A missing
15
+ component is added with `npx shadcn@latest add <name>`.
16
+ 4. **A screen the planner specified starts from a one-page screen spec** (the planner's form) —
17
+ screens without a spec are the surface's discretion.
18
+
19
+ **Check**: `npm run check:ui` — the mechanical check of this contract. It must pass before you
20
+ commit (the same bar as "before you commit" below). The script lives in the shared package
21
+ **`@sudoke/dev-checks`** (`check-ui.mjs` — it scans `surface/main/src` outside `components/ui/`) —
22
+ copying·npm wiring follows domain guide §5-9.
23
+
24
+ ## DO / DON'T — controls are standard components
25
+
26
+ ```tsx
27
+ ❌ <button className="h-6 px-2 text-xs">Save</button>
28
+ ✅ <Button size="sm">Save</Button>
29
+
30
+ ❌ <button className="p-1 text-muted-foreground"><ChevronRight /></button> (an icon toggle)
31
+ ✅ <Button variant="ghost" size="icon"><ChevronRight /></Button>
32
+
33
+ ❌ <select className="border rounded px-2">…</select>
34
+ ✅ <Select><SelectTrigger className="w-full"><SelectValue /></SelectTrigger>…</Select>
35
+
36
+ ❌ <table className="w-full"><thead>…</thead></table>
37
+ ✅ <Table><TableHeader><TableRow><TableHead>…</TableHead></TableRow></TableHeader>…</Table>
38
+
39
+ ❌ <div className="fixed inset-0 z-50 bg-black/50">…a hand-rolled modal…</div>
40
+ ✅ <Dialog open={open} onOpenChange={setOpen}><DialogContent>…</DialogContent></Dialog>
41
+
42
+ ❌ hand-assembling a missing component (toast·popover·tabs) out of divs
43
+ ✅ npx shadcn@latest add popover → import { Popover } from '@/components/ui/popover'
44
+ ```
45
+
46
+ ### Style DO / DON'T
47
+
48
+ ```tsx
49
+ ❌ <Button size="sm" className="h-6 w-14">…</Button> (an arbitrary h-* — data-size wins, so don't write it)
50
+ ✅ <Button size="sm">…</Button> (sizes come from the shadcn size variants only)
51
+
52
+ ❌ <span className="text-red-600">Deleted</span> · className="bg-[#ff4d5e]"
53
+ ✅ <span className="text-destructive">Deleted</span> (colors are semantic tokens only)
54
+
55
+ ❌ <span className="text-13">…</span> (a custom font token — twMerge mistakes it for a color)
56
+ ✅ <span className="text-sm">…</span> (standard shadcn tokens)
57
+
58
+ ❌ <div style="margin-top: 8px"> (a static style)
59
+ ✅ <div className="mt-2"> (through classes)
60
+ ```
61
+
62
+ ## Rules
63
+
64
+ ### R1. Creation forms are never always-visible — toolbar button + dialog
65
+ - An always-visible form card competes with the body (the table) and wastes space when unused.
66
+ - Rule: a `[+ Add]` button in the top toolbar → a dialog on click. Short creations with three fields
67
+ or fewer fit a dialog.
68
+ - The dialog's field order matches the table column order (e.g. code→name); the first field takes
69
+ focus (autoFocus).
70
+
71
+ ### R2. Row edits are dialogs, not inline — one-shot manipulations excepted
72
+ - In-place inputs inside table cells change the row height, push surrounding content, and fall apart
73
+ with multiple fields.
74
+ - Rule: even a single-field edit goes through a **dialog (or popover)**. Only one-click manipulations
75
+ (an active/inactive toggle, a select choice) execute immediately.
76
+
77
+ ### R3. Expose 1~2 row actions — the rest goes into the kebab (⋯) menu
78
+ - Four buttons per row make scanning hard and the table look like a button list.
79
+ - Rule: expose at most the two most-used actions as buttons; the rest goes into the row-end `⋯`
80
+ overflow menu. Destructive actions (delete) take the destructive style inside the menu.
81
+
82
+ ### R4. Rare features move to secondary screens — progressive disclosure
83
+ - A rarely used feature occupying permanent space hurts learnability and density.
84
+ - Rule: low-frequency actions (restore, undo-merge) move to a dedicated secondary screen (the history
85
+ page) or an accordion. Ledger (event-log) based actions fit most naturally as a button on the
86
+ corresponding event row of the history screen.
87
+
88
+ ### R5. Dialog accessibility minimum
89
+ - Rule: close on Esc, a visible close button, focus trap + focus restored to the trigger on close,
90
+ no dialog inside a dialog. (shadcn Dialog provides these by default — holding as long as you never
91
+ hand-roll one.)
92
+
93
+ ### R6. Destructive work warns → confirms, two steps (the gate already owns this)
94
+ - The gate's warning=refusal → force retry pattern IS this rule's implementation.
95
+ - Rule: the UI's confirmation dialog states the outcome explicitly (what gets erased, what is
96
+ preserved), with the recovery path shown alongside.
97
+
98
+ ### R7. Tables are shadcn standard — no density·size numbers here
99
+ - Table·cell·control sizes and fonts follow **the shadcn standard as-is** — this guide sets no pixel
100
+ specs.
101
+ - **Pages still on raw `<table>` migrate to `ui/Table` when you touch that page** (`check:ui` flags
102
+ the debt). New code is always `ui/Table`.
103
+
104
+ ### R8. Low-information columns·badges become inline cues
105
+ - Columns that repeat what indentation or shape already tells you raise density and compete with the
106
+ body (state·actions).
107
+ - Rule: things structure already shows (hierarchy depth L1/L2…) get no column — indentation only.
108
+ State (active/inactive) also drops its dedicated column in favor of the name's tone
109
+ (inactive=muted) + a tooltip.
110
+ - Long raw data (event payloads etc.) becomes a one-line summary in the app's language in the
111
+ column, with the original in a row tooltip.
112
+
113
+ ### R9. Inactive·past states go behind a view toggle — progressive disclosure (view edition)
114
+ - Inactive items in management lists are needed only occasionally (reactivation·inspection).
115
+ Permanent display disturbs scanning the body.
116
+ - Rule: a `[Hide inactive / Show]` toggle in the toolbar (visible by default). Hiding removes the
117
+ items AND their **whole subtree** (no orphans).
118
+
119
+ ### R10. Page skeleton — title row / toolbar / table / pagination
120
+ - Skeleton order: title row → toolbar → table → pagination.
121
+ - The title row holds the title·a one-line description only (action buttons go to the toolbar).
122
+ - Toolbar: **filters left**, the primary action (`+ Add`) **right**. With no filters, the whole
123
+ toolbar right-aligns.
124
+ - Hint copy goes as a muted caption under the toolbar. Mid-body labels appear only with two or more
125
+ sections.
126
+ - Time notations are full dates including the year.
127
+
128
+ ### R11. Spacing comes from structure
129
+ - No spacing numbers — use shadcn component defaults and the Tailwind utility rhythm as-is.
130
+ - Adding margins to individual elements inside a `space-y` layout breaks the rhythm — change spacing
131
+ through the wrapper structure.
132
+ - Dialog form spacing follows the official shadcn form conventions as-is.
133
+
134
+ ### R12. Sizes·typography follow the shadcn scale
135
+ - Control sizes come from the shadcn standard **size variants** only — no arbitrary `h-*` in
136
+ `className` (the data-size class beats a plain `h-*` — tailwind-merge cannot remove it).
137
+ - **Controls side by side on one line share the same size variant** — at default, Button·Input·
138
+ Select align in height. Mixing variants skews the line (sm only when the whole line is sm).
139
+ - Fonts use standard shadcn tokens only — a custom `text-*` token gets mistaken for a color by
140
+ twMerge and is dropped in color variants.
141
+
142
+ ### R13. Colors are shadcn semantic tokens only
143
+ - Never reference the palette directly — semantic tokens only.
144
+
145
+ ### R14. Repeated values are quiet text — chips are for markers only
146
+ - A column where most rows share one value (e.g. 24 of 25 rows domestic) renders as muted text.
147
+ Wrapping everything in chips only adds information-free noise.
148
+ - Chips mark **structural markers** (a subsidiary) or the few targets that must stand out.
149
+ - To make a specific value (e.g. overseas) stand out, highlight that value alone — not the whole
150
+ column of chips (low-frequency emphasis).
151
+ - No repeated identical labels inside a cell — numbers·colors + a one-line legend (the "2 · 1 · 5"
152
+ matrix cell case).
153
+
154
+ ### R15. The component base is shadcn/ui — the official site is the reference
155
+ - Controls (buttons·dialogs·tables·dropdowns…) use the official shadcn/ui components as-is (no
156
+ in-house builds). Looks·variants·a11y follow the official docs.
157
+ - The ui component list (of the reference surface): badge·button·card·dialog·dropdown-menu·input·
158
+ label·scroll-area·select·separator·sheet·sonner·table·textarea. **A control missing from the list
159
+ is added with `npx shadcn@latest add <name>`** (never hand-assembled) — a new app applies the same
160
+ rule to its own list of added components.
161
+ - The theme is the token set extracted from the shadcn create page (Get Code → Theme tab) (tied to
162
+ R13's semantic tokens).
163
+ - When a size you need is absent from the shadcn default variants, add a **size variant** the shadcn
164
+ way — not an arbitrary `className` (R12).
165
+
166
+ ### R16. Screen shells come from the official Blocks — never hand-assembled
167
+ - Screen shells (sidebar·dashboard·login) start as-is from the official shadcn Blocks (sidebar·
168
+ dashboard, …) — menu structure·spacing·responsive behavior lock to the official example values
169
+ (as R15 is for components, the same principle for layouts).
170
+ - Only a structure absent from Blocks is built by hand, minimally — still inside R10's skeleton·
171
+ R11's spacing·R12·R13's token principles.
172
+
173
+ ### R17. An app has one per-role assignment table — not per-screen decisions
174
+ - At app start, define and document once a per-role typography·spacing assignment table (screen
175
+ title·description·section title·body·page vertical rhythm, … — **standard tokens only**) that
176
+ every screen follows.
177
+ - Even allowed tokens drift when every screen decides anew — consistency comes from "same role, same
178
+ token". The assignment picks which standard value to use; it never invents new ones.
179
+
180
+ ### R18. Screen copy is in the user's language — internal references stay hidden
181
+ - Every visible string (descriptions under titles·buttons·labels·states·empty states·errors·
182
+ confirmations) is written in the language of the people using that screen.
183
+ - Forbidden: request-row codes (A1·B2), internal mechanism vocabulary (ledger·gate·command·event·
184
+ projection·delegation token·idempotency·row_hash), development-process wording ("confirmed in the
185
+ screen spec"·"registered via request"). Sentences from the spec·request forms are design documents,
186
+ not screen copy — rewrite from the user's perspective when surfacing.
187
+ - The test: does the string tell the USER what this feature does, or tell a DEVELOPER how the system
188
+ is built — if the latter, remove or rewrite it.
189
+ - Exception: a development-roadmap notice the user asked to see (e.g. "this feature arrives in the
190
+ stage-③ statistics screen") — exposure is the point; stage·feature names only, with internal
191
+ structure mentions following the same rule.
192
+
193
+ ## Before you commit — the same bar as `npm run check:ui`
194
+
195
+ ```bash
196
+ npm run check:ui # the list below is checked mechanically (violations fail)
197
+ ```
198
+
199
+ - [ ] raw `<button>`·`<select>` — zero occurrences outside components/ui
200
+ - [ ] raw `<table>` — zero in new code (existing pages migrate to ui/Table when touched, R7)
201
+ - [ ] zero `style="` strings·static style objects — computed values (tree indentation) only
202
+ - [ ] zero arbitrary colors (`bg-[#…]` etc.) — shadcn semantic tokens only
203
+ - [ ] zero custom font tokens like `text-13` — standard shadcn tokens only
204
+ - [ ] new controls added via shadcn add — nothing hand-assembled for missing-from-ui (custom-widget
205
+ exceptions carry the `check:ui-allow: reason` marker)
206
+ - [ ] pages follow the skeleton order (title row→toolbar→table→pagination)
207
+ - [ ] sizes come from shadcn size variants — no arbitrary className (h-*)
208
+
209
+ ## URL naming rules
210
+
211
+ - **Singular = a view selecting one target** (`/function`, `/client`); **plural = a list·management**
212
+ (`/notes`, `/functions`, `/clients`) — the notes view IS the list itself, hence plural.
213
+
214
+ ## Appendix — the grounds for the rules
215
+
216
+ - R1: [NN/g Modal & Nonmodal Dialogs](https://www.nngroup.com/articles/modal-nonmodal-dialog) (modals fit short single tasks), [Atlassian Modal Dialog](https://atlassian.design/components/modal-dialog)
217
+ - R2: [SaaS UX Patterns](https://www.saasui.design/blog/saas-modal-dialog-ux-patterns), [a UX case study](https://rakibulism.medium.com/choosing-modals-over-inline-actions-a-ux-case-study-on-table-complexity-2552ee168b5c)
218
+ - R3: [Carbon Data Table](https://www.carbondesignsystem.com/building-blocks/core/components/data-table), [Carbon Menu Buttons](https://www.carbondesignsystem.com/building-blocks/core/components/menu-buttons), [Ant Design recommendation](https://github.com/ant-design/ant-design/issues/25799) (≤2 exposed actions per row), [NN/g Contextual Menus](https://www.nngroup.com/articles/contextual-menus-guidelines)
219
+ - R4·R9: [NN/g Progressive Disclosure](https://www.nngroup.com/articles/progressive-disclosure)
220
+ - R5: [WAI-ARIA Dialog Modal pattern](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal), [A11y Collective](https://www.a11y-collective.com/blog/modal-vs-dialog)
221
+ - R7: [Carbon Data Table](https://www.carbondesignsystem.com/building-blocks/core/components/data-table) (compact density), [Ant Design Table](https://ant.design/components/table) (size small/middle)
222
+ - R8: [NN/g How Users Read on the Web](https://www.nngroup.com/articles/how-users-read-on-the-web/)
@@ -0,0 +1,107 @@
1
+ # Undo scope guide
2
+
3
+ The criterion an agent creating or editing a domain uses to decide "which event types do we open to
4
+ the kernel-common undo?" Written against kernel 0.6.1; the kernel-side contract follows the Undo
5
+ section of [packages/kernel/README.md](../README.md).
6
+
7
+ ## Principle
8
+
9
+ **Open only what is hard to restore by hand after a mistake.** Everything else stays `unavailable`,
10
+ with an alternative written into the reason. Do not try to support everything — every supported event
11
+ type brings its handler, its tests and its event-format management with it.
12
+
13
+ The kernel requires an undo policy declaration for every event type. The requirement is not "support
14
+ everything" — it is "decide, per type, whether you support it".
15
+
16
+ ## Decision order
17
+
18
+ For each event type, ask top to bottom and decide at the first hit.
19
+
20
+ | # | Question | On a hit |
21
+ |---|---|---|
22
+ | 1 | Is it a secret, a right, or an external effect? | Do not support |
23
+ | 2 | Is it a record rather than a state? | Do not support |
24
+ | 3 | Would re-running the same command restore the original? | Do not support |
25
+ | 4 | Does one execution change or remove multiple rows? | **Support candidate** |
26
+ | 5 | Support candidate, but the event carries no prior state? | Fix the event first, then support it |
27
+
28
+ What each question means:
29
+
30
+ 1. **Secrets, rights, external effects.** Passwords, roles, delegation issue·revoke, account
31
+ deletion, outgoing mail. Undoing these would flip a security decision, or pretend something
32
+ already outside came back.
33
+ 2. **Records.** Decisions, approvals, proposals — things whose meaning is the fact itself, "this
34
+ happened then". You do not erase them; you overlay new records.
35
+ 3. **Re-runnable work.** Renames, active toggles, reordering, settings changes — one-value changes.
36
+ An unsupported reason like "set the previous value with the same command" is enough.
37
+ 4. **Multi-row work.** Deletes, merges, bulk changes, moves that take descendants along. Restoring
38
+ by hand requires remembering exactly what changed — that is what undo is for.
39
+ 5. **Events without prior state.** Undo quality is decided by the information the original event
40
+ carries. Opening it with insufficient data makes the "restore" a rough remake.
41
+
42
+ ## Priority
43
+
44
+ When several candidates remain, open them in this order:
45
+
46
+ - **Largest blast radius first.** Data loss, then structure changes, then value changes.
47
+ - **Agent-runnable first.** Commands inside delegation scopes are the most mistake-prone; undo is
48
+ their safety net.
49
+ - **Frequently used first.** Rarely-run commands wait.
50
+
51
+ ## Before opening — the checklist
52
+
53
+ For every event type you switch to supported, all of these must hold. If any one fails, it is not
54
+ time yet.
55
+
56
+ - The original event carries every value the restoration needs.
57
+ - The compensation command takes an identifier that points at the exact record, not "the latest one".
58
+ - What undo loses (changes made in between, etc.) can be stated in `losses`.
59
+ - Conditions that make undo impossible (parent gone, name conflict, already restored by hand) can be
60
+ stated in `blockers`.
61
+ - Every event type one command execution writes points at the same handler (otherwise the kernel
62
+ refuses with `undo.operation_mixed_policies`).
63
+
64
+ ## Signals you should NOT open it
65
+
66
+ - **You feel a need for undo-of-undo.** Reverting a restoration is "delete it again" — an ordinary
67
+ command does that.
68
+ - **The handler outgrows the compensation.** When the planning code is longer than the actual
69
+ restore code, the model does not fit this domain.
70
+ - **The preview's `changes` is a single line of "recreate everything".** The user gets nothing to
71
+ judge — guide to a re-run instead.
72
+
73
+ ## What the domain does
74
+
75
+ For every supported event type:
76
+
77
+ - **The handler declares its compensation command statically** (`compensationCommand`). The plan's
78
+ `command` must equal the declaration.
79
+ - **The handler answers exactly three things.** What changes (`changes`), what is lost (`losses`),
80
+ why not (`blockers`).
81
+ - **`changes.field` carries field names only** — no explanation sentences. Parts that do not restore
82
+ to the original belong in `losses`.
83
+ - **State the plan depends on — not values shown on screen — goes into `dependsOn` as tokens.**
84
+ Do not re-implement the projector or the command's computation inside the handler.
85
+ - **The handler blocks records already restored by hand.** The kernel does not know about a
86
+ compensation command invoked directly; its one-compensation guard only knows the undo path.
87
+ - **Origin-read rules share one judgment function with ledger reads.** What the ledger shows is what
88
+ undo may show. Register it once with `registerUndoReadGate`.
89
+ - **Never remove a compensation command from the assembly.** Removing it refuses the redelivery of
90
+ past undos performed through it — even for the actor who ran them.
91
+
92
+ For unsupported event types, write a concrete reason. Not "not supported" but "rename back with the
93
+ same command" — the next action spelled out. An agent reads this sentence and acts on it.
94
+
95
+ ## What the surface does
96
+
97
+ - **The screen never guesses undoability.** No code scanning the event list to compute "already
98
+ undone" — ask the kernel.
99
+ - **The flow is fixed at three steps.** Status decides the button, preview fills the confirmation
100
+ dialog, and the preview's `planHash` executes.
101
+ - **One confirmation dialog for all events.** The preview shape is common to every event type —
102
+ build no per-event-type dialogs.
103
+ - **A visible button can still be refused at preview.** Status does not compute domain blockers —
104
+ there must be a screen that shows the reasons for `blocked`·`unavailable`·`denied`·`already_undone`.
105
+ - **On `undo.plan_changed`, reload the preview and take the confirmation again.**
106
+ - **With losses (`warning`), send `acceptLosses: true` only after the user confirmed them.**
107
+ - **A status query carries at most 100 seqs.** More is an input refusal — page the query.
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@sudoke/kernel",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "SUDOKE kernel — the 9-stage command gate, ledger, registries and async storage port behind every sudoke app",
5
5
  "type": "module",
6
6
  "files": [
7
- "src"
7
+ "src",
8
+ "docs"
8
9
  ],
9
10
  "publishConfig": {
10
11
  "access": "public"