@sudoke/kernel 0.6.2 → 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 +15 -19
- package/docs/domain-development-guide.md +251 -142
- package/docs/kernel-upgrade-guide.md +111 -84
- package/docs/surface-development-guide.md +184 -127
- package/docs/undo-scope-guide.md +99 -84
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -241,22 +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
|
-
## Builder guides (
|
|
245
|
-
|
|
246
|
-
The guides below ship inside the npm tarball (`docs/`), so
|
|
247
|
-
nothing
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
See [the upgrade guide](docs/kernel-upgrade-guide.md) — dependency bumps, the 0.4→0.5 check items
|
|
261
|
-
(`catalogVersion` rename, full `fields` listing, new MCP common tools, replay rights re-proof) and
|
|
262
|
-
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).
|
|
@@ -1,96 +1,130 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
>
|
|
4
|
-
>
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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 |
|
|
31
51
|
| --- | --- | --- | --- | --- | --- |
|
|
32
|
-
| 1 |
|
|
33
|
-
| 2 |
|
|
34
|
-
| 3 |
|
|
35
|
-
| 4 |
|
|
36
|
-
| 5 |
|
|
37
|
-
| 6 |
|
|
38
|
-
| 7 |
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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
|
|
45
75
|
|
|
46
76
|
```ts
|
|
47
77
|
{
|
|
48
|
-
name: 'client.recode', //
|
|
49
|
-
description: '
|
|
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)
|
|
50
80
|
example: 'POST /api/commands/client.recode {"clientId":"…","newCode":"DAEHYUN"}',
|
|
51
|
-
allowedRoles: ['admin'], // ③
|
|
52
|
-
scope: 'none' | 'client', // ③
|
|
53
|
-
targetOf: (i) => i.clientId, // ③
|
|
54
|
-
input: z.object({ … }), // ④
|
|
55
|
-
output: z.object({ … }).strict(), // ⑧
|
|
56
|
-
errors: ['client.code_conflict'], //
|
|
57
|
-
transition: { machine, command, current: async (i) => ({ id, status }) }, // ⑦
|
|
58
|
-
precondition: async (i) => {}, // ⑤
|
|
59
|
-
invariants: async (i, identity) => {}, // ⑥
|
|
60
|
-
execute: async (i, identity) => ({ events, result }), // ⑧
|
|
61
|
-
version: '1.0.0', //
|
|
62
|
-
behaviorRevision: '…', //
|
|
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)
|
|
63
93
|
}
|
|
64
94
|
```
|
|
65
95
|
|
|
66
|
-
|
|
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.
|
|
67
101
|
|
|
68
|
-
|
|
102
|
+
The refusal throw — the human sentence (reason) and the machine contract (code) together:
|
|
69
103
|
|
|
70
104
|
```ts
|
|
71
|
-
throw new GateError(5, 'precondition', '
|
|
72
|
-
code: 'client.not_found', // domain/error-codes.ts
|
|
73
|
-
recovery: { query: 'clients' }, //
|
|
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
|
|
74
108
|
})
|
|
75
109
|
```
|
|
76
110
|
|
|
77
|
-
###
|
|
111
|
+
### A complete real file — `client/setRegion.ts` (copy this to start)
|
|
78
112
|
|
|
79
113
|
```ts
|
|
80
114
|
import { z } from 'zod'
|
|
81
115
|
import { db, GateError, type CommandDefinition } from '@sudoke/kernel'
|
|
82
116
|
const input = z.object({
|
|
83
|
-
clientId: z.string().uuid().describe('
|
|
84
|
-
region: z.enum(['domestic', 'overseas']).describe('
|
|
117
|
+
clientId: z.string().uuid().describe('client id'),
|
|
118
|
+
region: z.enum(['domestic', 'overseas']).describe('the region to set (domestic | overseas)'),
|
|
85
119
|
})
|
|
86
120
|
const output = z.object({
|
|
87
|
-
clientId: z.string().uuid().describe('
|
|
88
|
-
region: z.enum(['domestic', 'overseas']).describe('
|
|
121
|
+
clientId: z.string().uuid().describe('client id'),
|
|
122
|
+
region: z.enum(['domestic', 'overseas']).describe('the region after the change'),
|
|
89
123
|
}).strict()
|
|
90
124
|
|
|
91
125
|
export const clientSetRegion: CommandDefinition<z.infer<typeof input>, z.infer<typeof output>> = {
|
|
92
126
|
name: 'client.setRegion',
|
|
93
|
-
description: '
|
|
127
|
+
description: "Change a client's region (admins only)",
|
|
94
128
|
example: 'POST /api/commands/client.setRegion {"clientId":"…","region":"overseas"}',
|
|
95
129
|
allowedRoles: ['admin'],
|
|
96
130
|
scope: 'none',
|
|
@@ -99,12 +133,12 @@ export const clientSetRegion: CommandDefinition<z.infer<typeof input>, z.infer<t
|
|
|
99
133
|
errors: ['client.not_found', 'client.same_region'],
|
|
100
134
|
precondition: async (i) => {
|
|
101
135
|
if (!(await db.prepare(`SELECT id FROM clients WHERE id=?`).get(i.clientId)))
|
|
102
|
-
throw new GateError(5, 'precondition', '
|
|
136
|
+
throw new GateError(5, 'precondition', 'Client not found', { code: 'client.not_found', recovery: { query: 'clients' } })
|
|
103
137
|
},
|
|
104
138
|
execute: async (i, identity) => {
|
|
105
139
|
const c = (await db.prepare(`SELECT name, region FROM clients WHERE id=?`).get(i.clientId)) as any
|
|
106
140
|
if (c.region === i.region)
|
|
107
|
-
throw new GateError(5, 'precondition',
|
|
141
|
+
throw new GateError(5, 'precondition', `Already ${i.region}`, { code: 'client.same_region' })
|
|
108
142
|
return {
|
|
109
143
|
events: [
|
|
110
144
|
{
|
|
@@ -120,119 +154,194 @@ export const clientSetRegion: CommandDefinition<z.infer<typeof input>, z.infer<t
|
|
|
120
154
|
}
|
|
121
155
|
```
|
|
122
156
|
|
|
123
|
-
###
|
|
157
|
+
### The five-part set — what you touch beyond the definition file
|
|
124
158
|
|
|
125
159
|
```ts
|
|
126
|
-
// ①
|
|
160
|
+
// ① the registry (src/domain/commands/index.ts) — one import + the name on the export list
|
|
127
161
|
import { clientSetRegion } from './client/setRegion.js'
|
|
128
|
-
// …
|
|
162
|
+
// … add clientSetRegion to the export list
|
|
129
163
|
|
|
130
|
-
// ②
|
|
164
|
+
// ② the event contract (src/domain/event-contracts.ts) — when the event type is new
|
|
131
165
|
'client.regionChanged': z.object({ clientId: z.string(), oldRegion: z.string(), newRegion: z.string(), changedBy: z.string() }),
|
|
132
166
|
|
|
133
|
-
// ③
|
|
134
|
-
// ④
|
|
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)
|
|
135
170
|
case 'client.regionChanged':
|
|
136
|
-
return
|
|
171
|
+
return `Region changed — ${client(p.clientId)} ${…}`
|
|
137
172
|
|
|
138
|
-
// ⑤
|
|
173
|
+
// ⑤ the surface contract maps (src/domain/command-input-map.ts) — one line on each of the two maps
|
|
139
174
|
'client.setRegion': InputOf<typeof clientSetRegion>
|
|
140
175
|
'client.setRegion': OutputOf<typeof clientSetRegion>
|
|
141
176
|
```
|
|
142
177
|
|
|
143
178
|
```js
|
|
144
|
-
// ⑥
|
|
145
|
-
show('
|
|
146
|
-
show('
|
|
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)
|
|
147
182
|
```
|
|
148
183
|
|
|
149
|
-
###
|
|
184
|
+
### Undo policies and command versions (provided by the kernel)
|
|
150
185
|
|
|
151
|
-
|
|
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):
|
|
152
191
|
|
|
153
192
|
```ts
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
registerCatalogRelease({ catalogVersion: '4.0.0', changes: […] }) // 이번 릴리스가 뭘 바꿨는지 — 변경 내역 조회·검증기의 원천
|
|
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
|
|
158
196
|
```
|
|
159
197
|
|
|
160
|
-
## 3.
|
|
161
|
-
|
|
162
|
-
1.
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
|
174
244
|
|
|
175
245
|
```ts
|
|
176
246
|
❌ execute: async (i) => { await db.prepare('UPDATE clients SET region=?').run(i.region); return { events: [], result: null } }
|
|
177
247
|
✅ execute: async (i) => ({ events: [{ type: 'client.regionChanged', …, payload: { … } }], result: { … } })
|
|
178
|
-
// DB
|
|
248
|
+
// the DB may be READ (queries, awaited) but never mutated — events cause every state change
|
|
179
249
|
|
|
180
|
-
❌ throw new Error('
|
|
181
|
-
✅ throw new GateError(5, 'precondition', '
|
|
250
|
+
❌ throw new Error('already domestic')
|
|
251
|
+
✅ throw new GateError(5, 'precondition', 'Already domestic', { code: 'client.same_region' })
|
|
182
252
|
|
|
183
|
-
❌ errors: ['client.duplicated'] // error-codes.ts
|
|
184
|
-
✅ domain/error-codes.ts
|
|
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
|
|
185
255
|
|
|
186
|
-
❌ output
|
|
187
|
-
✅ output: z.object({ … }).strict() //
|
|
256
|
+
❌ omitting output // the assembly fails
|
|
257
|
+
✅ output: z.object({ … }).strict() // nothing to return → z.null()
|
|
188
258
|
|
|
189
259
|
❌ input: z.object({ name: z.string(), requestKey: z.string().optional() })
|
|
190
|
-
✅ input: z.object({ name: z.string() }) // requestKey·dryRun
|
|
260
|
+
✅ input: z.object({ name: z.string() }) // requestKey·dryRun are gate protocol options — keep them out
|
|
191
261
|
|
|
192
|
-
❌
|
|
193
|
-
✅ name
|
|
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
|
|
194
264
|
```
|
|
195
265
|
|
|
196
|
-
## 4.
|
|
266
|
+
## 4. What accompanies a new command
|
|
197
267
|
|
|
198
|
-
-
|
|
199
|
-
|
|
200
|
-
-
|
|
201
|
-
-
|
|
202
|
-
-
|
|
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)
|
|
203
278
|
|
|
204
|
-
###
|
|
279
|
+
### Before you commit — the same bar as `npm run check:domain`
|
|
205
280
|
|
|
206
281
|
```bash
|
|
207
|
-
npm run check:domain #
|
|
208
|
-
npm run typecheck && npm run smoke # + mcp:test·policy:test (
|
|
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)
|
|
209
284
|
```
|
|
210
285
|
|
|
211
|
-
- [ ]
|
|
212
|
-
|
|
213
|
-
- [ ]
|
|
214
|
-
- [ ]
|
|
215
|
-
- [ ]
|
|
216
|
-
- [ ]
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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`:
|
|
229
334
|
```jsonc
|
|
230
|
-
//
|
|
335
|
+
// an app in the same repository — connect as a dependency (never copy — single source)
|
|
231
336
|
"dependencies": { "@sudoke/dev-checks": "*" },
|
|
232
337
|
"scripts": { "check:domain": "node ../dev-checks/check-domain.mjs", "check:ui": "node ../dev-checks/check-ui.mjs" }
|
|
233
338
|
|
|
234
|
-
//
|
|
339
|
+
// an app outside the repository — copy the package's check-domain.mjs·check-ui.mjs into the app's scripts/, then
|
|
235
340
|
"scripts": { "check:domain": "node scripts/check-domain.mjs", "check:ui": "node scripts/check-ui.mjs" }
|
|
236
341
|
```
|
|
237
|
-
|
|
238
|
-
|
|
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)
|