@sudoke/kernel 0.5.1 → 0.6.2

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
@@ -41,8 +41,11 @@ There is a single assembly regime — the historical compat/strict split was rem
41
41
  consistency check demands, at seal time:
42
42
 
43
43
  - an undo policy for every registered event type (declaring support or `{ kind: 'unavailable' }` —
44
- the answer is declared, silence is a defect), each with a `mayRead` hook (origin-read rights are a
45
- declared decision, never a default allow), and every undo handler a `mayPreview` hook;
44
+ the answer is declared, silence is a defect), each with an origin-read decision — a `mayRead` hook
45
+ on the policy itself, or the app-wide default gate registered once (`registerUndoReadGate`;
46
+ a policy-level hook wins where present). Read rights are a declared decision, never a default
47
+ allow — an assembly declaring neither fails the boot;
48
+ - every undo handler a declared `compensationCommand` that resolves to a registered command;
46
49
  - a declared semver version on every command and query;
47
50
  - a storage engine providing the operation-ledger capability.
48
51
 
@@ -105,7 +108,11 @@ including the caller's `viewRevision`. A replayed
105
108
  success additionally carries `producedBy` — the contract that PRODUCED the stored result (commandName·
106
109
  versions·protocolVersion·the role that executed); rows older than producer tracking answer
107
110
  `{ unknown: true }`. Redeliveries re-check the current rights first — undo redeliveries re-derive the
108
- permission view structurally (the verdict never depends on error-code spelling), and a removed
111
+ permission view structurally (the verdict never depends on error-code spelling); when the source
112
+ operation carries a STORED compensation, its recorded envelope re-proves the rights whatever the
113
+ CURRENT policy consensus says (supported·unavailable·mixed alike — the policy may have moved since
114
+ the compensation was stored; a removed compensation command leaves nothing re-provable → refused),
115
+ and a removed
109
116
  command's stored result returns only while the account is valid AND the recorded rights still hold:
110
117
  the producer's role AND, for scoped commands, the app policy's verdict on the RECORDED normalized
111
118
  target (stamped beside every result and on every event envelope as `policyTarget` at write time —
@@ -120,13 +127,19 @@ envelope (`undoOfOperationId`·`undoSourceSeq`·`undoHandlerVersion`).
120
127
 
121
128
  ```ts
122
129
  const status = await undoStatus({ sourceSeqs: [seq] }, identity) // per-seq support·processing state
130
+ // at most UNDO_STATUS_MAX_SEQS (100) seqs per call — a larger bundle is a stage-4 input refusal,
131
+ // never a silent truncation
123
132
  const preview = await previewUndo({ sourceSeq: seq }, identity)
124
- // preview.status: available | warning | blocked | unavailable | already_undone
133
+ // preview.status: available | warning | blocked | unavailable | already_undone | denied
134
+ // denied = a permission refusal (read gate, handler gate, compensation-command role·delegation) —
135
+ // carries no operation facts, the same vocabulary undoStatus answers 'denied' with
125
136
  // preview.changes (before = current value, after = the value execution will set), losses, blockers, planHash
126
137
  const done = await executeUndo(
127
138
  { sourceSeq: seq, expectedPlanHash: preview.planHash, acceptLosses: true, requestKey: 'retry-key' },
128
139
  identity,
129
140
  )
141
+ // a permission refusal on execution keeps its OWN stage and code (1~3 — e.g. gate.role_denied);
142
+ // business blockers (a later change, plan defects) answer as stage-8 undo refusals
130
143
  ```
131
144
 
132
145
  Contract highlights:
@@ -134,25 +147,34 @@ Contract highlights:
134
147
  - **The unit is the operation** — one atomic command run (batch items are separate operations under one
135
148
  batchId). Selecting any event row of the operation resolves to the whole operation; partial undo does
136
149
  not exist. `undoStatus` and `previewUndo` share ONE per-operation judgment — every event row of one
137
- operation answers the same read verdict and the same undo consensus (a single unavailable event type
138
- makes the whole operation unavailable; multiple handlers answer `undo.operation_mixed_policies`),
139
- while the response keeps the requested seq as the anchor.
140
- - **The planner is domain-owned** (`registerUndoHandler`): `plan(source, identity)` is read-only and
141
- returns exactly one registered compensation command, `dependsOn` state tokens, `changes`·`preserved`·
142
- `losses`·`blockers`. The plan is machine-consumed, so the kernel validates its shape completely
143
- (required `changes` array, string `preserved` entries, JSON-representable `before`/`after`,
144
- non-negative integer loss counts) — a malformed plan answers `undo.plan_invalid` and never reaches
145
- the hash, the preview or the execution.
146
- - **Origin-read rights live on the POLICY** (`mayRead` on every `registerUndoPolicies` entry) — REQUIRED
147
- in strict mode: it runs before ANY branch (supported·unavailable·mixed·legacy·already-undone) answers
148
- anything about an operation, and a refusal carries no operation facts (no id, no processing state, no
149
- policy reason). Supported handlers refine further with `mayPreview` (equally required). An
150
- optional `roles` on the policy scopes its CATALOG exposure; exposure and the read verdict are
151
- independent decisions.
150
+ operation answers the same read verdict, the same compensation-command verdict and the same undo
151
+ consensus (a single unavailable event type makes the whole operation unavailable; multiple handlers
152
+ answer `undo.operation_mixed_policies`), while the response keeps the requested seq as the anchor.
153
+ A status row never promises a handler to an identity that cannot run the compensation: the shared
154
+ gates (origin-read → declared compensation command → handler hook) run in that fixed order before
155
+ any state — `already_undone` included — is consulted, on both paths.
156
+ - **The planner is domain-owned** (`registerUndoHandler`) and DECLARES its compensation command
157
+ (`compensationCommand` — exactly one registered command, resolved at the seal): the kernel checks the
158
+ current identity's access to the declared command BEFORE `plan()` runs (an unauthorized identity
159
+ never triggers plan computation and never learns the blockers a plan would have named), and a plan
160
+ naming any other command is a defect (`undo.plan_invalid`). `plan(source, identity)` is read-only and
161
+ returns `dependsOn` state tokens, `changes`·`preserved`·`losses`·`blockers`. The plan is
162
+ machine-consumed, so the kernel validates its shape completely (required `changes` array, string
163
+ `preserved` entries, JSON-representable `before`/`after`, non-negative integer loss counts) — a
164
+ malformed plan answers `undo.plan_invalid` and never reaches the hash, the preview or the execution.
165
+ - **Origin-read rights are a declared decision** — a `mayRead` hook on the policy, or the app-wide
166
+ default gate (`registerUndoReadGate`, one registration serving every policy that declares no
167
+ `mayRead`; the policy-level hook wins where present). It runs before ANY branch
168
+ (supported·unavailable·mixed·legacy·already-undone) answers anything about an operation, and a
169
+ refusal carries no operation facts (no id, no processing state, no policy reason). For a supported
170
+ consensus the DECLARED compensation command's access check follows (same refusal shape — status and
171
+ preview agree), then the OPTIONAL `mayPreview` hook refines further. An optional `roles` on the
172
+ policy scopes its CATALOG exposure; exposure and the read verdict are independent decisions.
152
173
  - **The preview judges the compensation through the SAME static+dynamic checks a direct call would
153
174
  face** (schema·delegation·role·app-policy target·preconditions·invariants·transitions) — 'available'
154
- means a call NOW would pass stages 1~7; a denied target blocks and leaks nothing (status answers
155
- carry a 'denied' state too).
175
+ means a call NOW would pass stages 1~7. Every permission refusal (read gate, handler gate,
176
+ compensation-command role·delegation, denied target) answers `denied` and leaks nothing; on
177
+ execution such refusals keep their own stage and code (1~3), never a stage-8 re-wrap.
156
178
  - **Conflicts are sequence-based, never value-based** — the planner decides with ledger facts; a later
157
179
  same-field change blocks even when the value round-tripped. Hard conflicts are never forceable; the
158
180
  confirmation pair is `acceptLosses` + `expectedPlanHash` (`undo.confirmation_required`,
@@ -168,9 +190,9 @@ Contract highlights:
168
190
  through the shared gate pipeline (no bypass lane, no nested transaction), and events·linkage·
169
191
  idempotency·audit commit or roll back together.
170
192
  - **Undoing an undo** compensates the compensation — it is a normal operation with its own policy. Undo
171
- handler versions are catalog content: a handler bump moves catalogRevision (and the published policy
172
- carries `handlerVersion`); per-command revisions stay stable — which command compensates an event is a
173
- plan-time decision, so catalogRevision·catalogStatus is the discovery surface for policy changes.
193
+ handler declarations are catalog content: a handler bump or a `compensationCommand` change moves
194
+ catalogRevision (the published policy carries `handlerVersion`·`compensationCommand`); per-command
195
+ revisions stay stable — catalogRevision·catalogStatus is the discovery surface for policy changes.
174
196
  - **Legacy rows** (written before the envelope) are addressed by exact seq; unprovable grouping answers
175
197
  `undo.legacy_operation_unknown`, missing prior state `undo.snapshot_missing`.
176
198
 
@@ -219,6 +241,22 @@ npm run validate:releases <previous.json|null> <current.json> # release manife
219
241
  `validate:releases` is a REPOSITORY check command — `scripts/` is deliberately outside the published
220
242
  `files` list; installed consumers validate manifests through `validateReleaseManifest` (exported).
221
243
 
244
+ ## Builder guides (Korean — shipped in this package)
245
+
246
+ The guides below ship inside the npm tarball (`docs/`), so agents building an app on the kernel need
247
+ nothing but the installed package:
248
+
249
+ - [docs/kernel-upgrade-guide.md](docs/kernel-upgrade-guide.md) — upgrading an app across kernel
250
+ versions (dependency pairing, boot requirements, the contract-carried writes and how to migrate).
251
+ - [docs/undo-scope-guide.md](docs/undo-scope-guide.md) — deciding which event types to open to the
252
+ common undo, and what a domain·surface must provide for each.
253
+ - [docs/domain-development-guide.md](docs/domain-development-guide.md) — writing a domain: commands,
254
+ policies, projections, event contracts, the check suite.
255
+ - [docs/surface-development-guide.md](docs/surface-development-guide.md) — building a surface over
256
+ the kernel's catalog·queries (UI conventions, the shared check).
257
+
222
258
  ## Upgrading from 0.3.x
223
259
 
224
- 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.
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.
@@ -0,0 +1,238 @@
1
+ # 도메인 개발 가이드 — 커맨드를 작성하는 법
2
+
3
+ > 이 문서는 도메인을 개발하는 에이전트에게 필요한 실무 지식을 담는다.
4
+ > 배경과 원리가 궁금하면 정의서로, 지금 커맨드를 만들어야 하면 이 문서를 본다.
5
+
6
+ 새 앱 개발의 실질적인 일은 "커맨드를 잘 쓰는 것"이다. 커맨드 하나 = 하나의 업무 의도(신청서).
7
+
8
+ ## 0. 계약 — 이 5줄은 예외 없음
9
+
10
+ 1. **모든 쓰기는 커맨드다** — `execute()`는 **이벤트만 반환**한다. DB 직접 수정(UPDATE·INSERT·DELETE)을 하지 않는다. 투영 적용·감사 기록은 커널이 같은 트랜잭션에서 한다.
11
+ 2. **거절은 GateError + 등록된 코드** — `throw new Error`를 쓰지 않는다. 새 코드는 `domain/error-codes.ts`에 먼저 등록하고 커맨드 `errors`에 선언한다(등록 안 된 코드를 선언하면 조립이 실패).
12
+ 3. **한 파일 = 한 커맨드, `commands/<오브젝트>/<동사>.ts`** — 커맨드명이 곧 경로다(`client.setRegion` → `commands/client/setRegion.ts`). 도메인 전체를 한 파일에 몰아넣지 않는다 — 등록소는 몰라도 검증·탐색이 안다.
13
+ 4. **새 커맨드는 요청서 한 장에서 시작한다**(`feature-request-guide.md`) — 코드에서 시작하지 않는다.
14
+ 5. **추가는 5종 세트** — 정의 파일 + 등록부 1줄 + (새 이벤트면) 계약·투영·이력 요약 + 지도 2줄 + 스모크 성공/거절 쌍. 하나라도 빠지면 빌드·조립·검증이 실패한다.
15
+
16
+ **검증**: `npm run check:domain` — 세트 누락(등록부·지도·이력 요약)과 문서 수치를 기계적으로 검사한다(아래 "커밋 전 점검"과 같은 기준).
17
+
18
+ ## 1. 시작은 요청서 — 자연어로 먼저 쓴다
19
+
20
+ 커맨드를 만들기 전에 기획자 양식(`docs/agents/dev/feature-request-guide.md`: 한 문장 / 절차 / 규칙)을 채운다. 기술 용어 없이.
21
+
22
+ - **한 문장**: "[불편한 이유] [누가 무엇을 하면] [무엇이 되기를 바란다]" — 한 문장으로 안 쓰이면 의도가 두 개다. 두 장으로 나눈다.
23
+ - **절차**는 셋 중 하나: 한 번에 끝나는 일(대부분) / 상태를 거치는 일(예: 제안→확정) / 한 번에 몰아서 해야 하는 묶음(예: 이체). 이 선택이 구조(단순 커맨드 / 상태 절차 / 묶음 처리)를 결정한다.
24
+ - **규칙은 거절로 옮길 수 있게**: "적절히 관리한다" ❌ → "이미 확정된 건은 다시 제안할 수 없다" ⭕ — 형식(부정문·긍정문)은 자유이되, 어기는 시도를 거절로 옮길 수 있어야 게이트 검증·테스트가 된다.
25
+
26
+ 번역 대응: 문장의 **행동 → 커맨드**, **바라는 결과 → 도메인 이벤트**, **절차 → 전이표**, **규칙 → 게이트 단계(권한·전제·불변식·전이)**.
27
+
28
+ 아래는 이 대응으로 실제 시스템이 만들어진 예시들이다 — 요청서 한 장이 커맨드 한 개로 번역된 사례집:
29
+
30
+ | # | 1a. 불편 (은행 비유) | 1b. 행동 | 1c. 결과 | 규칙 하이라이트 | → 커맨드 |
31
+ | --- | --- | --- | --- | --- | --- |
32
+ | 1 | 통장 거래 내역에 메모를 못 붙임 | 작성자가 메모를 고친다 | 수정 이력이 남은 채 반영 | 작성자만 / 동시 수정 거절 / 흔적 보존 | note.update |
33
+ | 2 | 그만둔 직원의 결재권이 남아있음 | 관리자가 결재권을 회수한다 | 그 고객 창구 업무 즉시 불가 | 즉시 효력 / 회수 기록 | client.unassignManager |
34
+ | 3 | 계좌가 잘못된 상품 아래에 있음 | 관리자가 상품을 바꿔 옮긴다 | 하위 계좌까지 함께 이동 | 사이클 금지 / depth 유지 / 동명 거절 / 연결 유지 | function.move |
35
+ | 4 | 고객이 상호를 변경함 | 관리자가 예금주 명의를 고친다 | 전 화면 반영 | 계좌번호(코드) 불변 | client.rename |
36
+ | 5 | 직원의 직급이 바뀜 | 관리자가 직급을 바꾼다 | 즉시 권한 반영 | 직급 내리면 담당 계좌 무관 즉시 박탈 | user.setRole |
37
+ | 6 | 퇴사한 직원 처리 | 관리자가 사번을 비활성화한다 | 로그인·권한 즉시 소멸 | 거래 기록 보존 / 재활성 가능 | user.setActive |
38
+ | 7 | 해지된 자회사 계좌가 목록에 남음 | 관리자가 계좌를 해지 상태로 둔다 | 조회에서 제외 | 신규 거래 금지 / 거래 내역 보존 / 재개 가능 | client.setActive |
39
+
40
+ 읽는 법: 세로로 보면 각 열이 번역 결과와 정렬된다 — **불편은 배경으로 남고, 행동이 커맨드가 되고, 결과가 이벤트가 되고, 규칙이 게이트 검증이 된다.** "즉시 불가/즉시 소멸" 같은 규칙은 실행 순간마다 게이트가 다시 검사하므로 별도 동기화 코드가 필요 없다.
41
+
42
+ **접수 — 사용자에게 묻는 법.** 사용자에게 받는 것은 의도(불편·행동·결과)로 충분하다 — 절차 선택·행동 분리·규칙 문구는 에이전트가 표준 패턴과 도메인 정의에서 초안으로 채운다(기획자는 여전히 최대한 채워 오는 것이 좋다). 채우다가 **사용자의 판단이 필요한 것** — 정책(허용/금지), 운영 사실("당일 이체 마감은 몇 시인가"), 데이터 범위(무엇을 저장할지) — 을 발견하면 그 자리에서 정답을 지어 쓰지 말고 **순서대로 하나씩** 묻는다: 선택지와 추천을 함께 붙여 답이 한 단어로 끝나게. 받은 답은 요청서의 규칙 칸에 옮겨 적는다 — 확정된 요청서만 계약이고, 안 쓴 것은 지켜지지 않는다.
43
+
44
+ ## 2. 커맨드 정의 양식 — 각 칸이 게이트 단계와 연결된다
45
+
46
+ ```ts
47
+ {
48
+ name: 'client.recode', // 오브젝트.동사 — REST·MCP 툴 이름의 원천 (배포 후 불변)
49
+ description: '고객 코드 변경 — …', // 카탈로그에 그대로 노출 (에이전트가 읽는다)
50
+ example: 'POST /api/commands/client.recode {"clientId":"…","newCode":"DAEHYUN"}',
51
+ allowedRoles: ['admin'], // ③ 정책: 누가
52
+ scope: 'none' | 'client', // ③ 정책: 담당 범위 검사 대상 여부
53
+ targetOf: (i) => i.clientId, // ③ 정책: 범위 검사가 쓸 고객 추출기 (scope:'client'일 때, 동기)
54
+ input: z.object({ … }), // ④ 스키마 — 필드마다 .describe() (카탈로그 설명의 원천)
55
+ output: z.object({ … }).strict(), // ⑧ 실행 — 성공 result의 모양 (게이트가 커밋 전에 검사·위반 시 롤백)
56
+ errors: ['client.code_conflict'], // 이 커맨드가 낼 수 있는 업무 오류 코드 (카탈로그에 공개)
57
+ transition: { machine, command, current: async (i) => ({ id, status }) }, // ⑦ 전이 — 상태가 있는 도메인만
58
+ precondition: async (i) => {}, // ⑤ 전제조건 — "존재하는가" (거절은 GateError+코드로)
59
+ invariants: async (i, identity) => {}, // ⑥ 불변식 — "규칙에 맞는가" (요청서의 규칙이 여기 들어간다)
60
+ execute: async (i, identity) => ({ events, result }), // ⑧ 실행 — 이벤트만 반환 (result는 output과 대조된다)
61
+ version: '1.0.0', // 선택(2026-11-13) — 커맨드 계약의 호환성 버전. strict 조립에서는 필수
62
+ behaviorRevision: '…', // 선택 — 지문이 못 잡는 의미 변화(함수 몸통·업무 로직)를 바꿀 때 직접 선언
63
+ }
64
+ ```
65
+
66
+ **저장을 읽는 훅은 전부 async다** — `transition.current`·`precondition`·`invariants`·`execute`는 `async`로 선언하고 안의 `db.prepare(…).get/all/run(…)`마다 `await`를 붙인다(저장 포트가 비동기 계약이므로). `targetOf`만 동기다(입력에서 id를 뽑는 순수 함수 — 저장을 안 읽는다). db를 읽지 않는 훅도 `async`는 붙인다 — 계약이 Promise 반환을 요구한다.
67
+
68
+ 거절 throw의 형태 — 문장(reason)과 기계용 계약(code)을 함께:
69
+
70
+ ```ts
71
+ throw new GateError(5, 'precondition', '고객이 존재하지 않습니다', {
72
+ code: 'client.not_found', // domain/error-codes.ts에 등록된 코드 (문구가 바뀌어도 유지)
73
+ recovery: { query: 'clients' }, // 선택: refresh 행동에서 다시 읽을 조회
74
+ })
75
+ ```
76
+
77
+ ### 실제 파일 전체 — `client/setRegion.ts` (여기서 복사해 시작한다)
78
+
79
+ ```ts
80
+ import { z } from 'zod'
81
+ import { db, GateError, type CommandDefinition } from '@sudoke/kernel'
82
+ const input = z.object({
83
+ clientId: z.string().uuid().describe('고객 id'),
84
+ region: z.enum(['domestic', 'overseas']).describe('변경할 국내/해외 (domestic=국내, overseas=해외)'),
85
+ })
86
+ const output = z.object({
87
+ clientId: z.string().uuid().describe('고객 id'),
88
+ region: z.enum(['domestic', 'overseas']).describe('변경된 국내/해외 값'),
89
+ }).strict()
90
+
91
+ export const clientSetRegion: CommandDefinition<z.infer<typeof input>, z.infer<typeof output>> = {
92
+ name: 'client.setRegion',
93
+ description: '고객의 국내/해외 변경 (관리자만)',
94
+ example: 'POST /api/commands/client.setRegion {"clientId":"…","region":"overseas"}',
95
+ allowedRoles: ['admin'],
96
+ scope: 'none',
97
+ input,
98
+ output,
99
+ errors: ['client.not_found', 'client.same_region'],
100
+ precondition: async (i) => {
101
+ if (!(await db.prepare(`SELECT id FROM clients WHERE id=?`).get(i.clientId)))
102
+ throw new GateError(5, 'precondition', '고객이 존재하지 않습니다', { code: 'client.not_found', recovery: { query: 'clients' } })
103
+ },
104
+ execute: async (i, identity) => {
105
+ const c = (await db.prepare(`SELECT name, region FROM clients WHERE id=?`).get(i.clientId)) as any
106
+ if (c.region === i.region)
107
+ throw new GateError(5, 'precondition', `이미 ${i.region === 'domestic' ? '국내' : '해외'}입니다`, { code: 'client.same_region' })
108
+ return {
109
+ events: [
110
+ {
111
+ type: 'client.regionChanged',
112
+ aggregate_type: 'client',
113
+ aggregate_id: i.clientId,
114
+ payload: { clientId: i.clientId, oldRegion: c.region, newRegion: i.region, changedBy: identity.userId },
115
+ },
116
+ ],
117
+ result: { clientId: i.clientId, region: i.region },
118
+ }
119
+ },
120
+ }
121
+ ```
122
+
123
+ ### 5종 세트 — 정의 파일 밖에 손대는 곳
124
+
125
+ ```ts
126
+ // ① 등록부 (src/domain/commands/index.ts) — import 1줄 + 배열에 이름
127
+ import { clientSetRegion } from './client/setRegion.js'
128
+ // … export 목록에 clientSetRegion 추가
129
+
130
+ // ② 이벤트 계약 (src/domain/event-contracts.ts) — 새 이벤트 타입이면
131
+ 'client.regionChanged': z.object({ clientId: z.string(), oldRegion: z.string(), newRegion: z.string(), changedBy: z.string() }),
132
+
133
+ // ③ 투영 규칙 (src/domain/app-projector.ts) — on('client.regionChanged', …)
134
+ // ④ 이력 요약 — 기본 서피스의 summarize switch에 한국어 한 줄 케이스 (위치는 서피스의 자유 — 앱 1은 pages/Events.tsx)
135
+ case 'client.regionChanged':
136
+ return `국내/해외 변경 — ${client(p.clientId)} ${…}`
137
+
138
+ // ⑤ 서피스 계약 지도 (src/domain/command-input-map.ts) — 입력·출력 두 지도에 각각 한 줄
139
+ 'client.setRegion': InputOf<typeof clientSetRegion>
140
+ 'client.setRegion': OutputOf<typeof clientSetRegion>
141
+ ```
142
+
143
+ ```js
144
+ // ⑥ 스모크 (smoke.mjs) — 성공과 거절을 항상 세트로 (거절도 계약이다)
145
+ show('국내/해외 변경 성공', await call(admin, 'POST', '/api/commands/client.setRegion', { clientId: cRoots[0], region: 'overseas' }), (r) => r.ok === true && r.result.region === 'overseas')
146
+ show('같은 값 재설정 → 5단계 거절', await call(admin, 'POST', '/api/commands/client.setRegion', { clientId: cRoots[0], region: 'overseas' }), (r) => r.status === 409 && r.stage === 5)
147
+ ```
148
+
149
+ ### 선택 등록 — 계약 버전·되돌리기 (커널 2026-11-13 제공, 앱 1은 아직 미사용)
150
+
151
+ 커널이 공통 되돌리기 계약과 커맨드 버전·지문 관리를 제공한다(앱 1은 호환 모드라 등록 없이 그대로 동작). 쓰고 싶을 때 조립 계층에 더하는 등록 네 가지 — 계약·예제는 `packages/kernel/README.md`:
152
+
153
+ ```ts
154
+ configureKernel({ mode: 'strict' }) // strict — 되돌리기 정책 전 커버·전 커맨드/조회 버전·쓰기 계약 지문 필수
155
+ registerUndoPolicies({ 'client.deleted': { kind: 'supported', handlerId: 'client-undo' } }) // 이벤트별 되돌림 가능 여부(불가도 명시)
156
+ registerUndoHandler({ id: 'client-undo', version: '1.0.0', plan: async (source, identity) => ({ … }) }) // 보상 계획(읽기 전용)
157
+ registerCatalogRelease({ catalogVersion: '4.0.0', changes: […] }) // 이번 릴리스가 뭘 바꿨는지 — 변경 내역 조회·검증기의 원천
158
+ ```
159
+
160
+ ## 3. 작성 원칙 (체크리스트)
161
+
162
+ 1. **이름**: `오브젝트.동사`. 폴더=오브젝트, 파일=동사 (예: `client/recode.ts`). **커맨드명은 한 번 배포하면 불변** — 카탈로그 계약이므로 바꾸면 MAJOR 버전.
163
+ 2. **execute는 순수하게**: DB를 직접 고치지 않고 **이벤트만 반환**한다. 투영(읽기 테이블) 적용과 감사 기록은 커널이 같은 트랜잭션에서 한다. 그래야 재생·감사·되돌림이 성립한다.
164
+ 3. **입력·출력 필드마다 `.describe()`**: 이 설명이 카탈로그의 필드 문서가 되어 에이전트가 읽는다. description·example도 "에이전트가 읽는 설명서"라고 생각하고 쓴다.
165
+ 4. **출력 계약은 필수**: `output`이 없으면 조립이 실패한다. execute의 반환 모양과 정확히 일치해야 하고(불일치는 커밋 전 8단계 거절·롤백), 반환값이 없으면 `z.null()`로 명시한다.
166
+ 5. **검증의 배치**: 존재 확인은 precondition(5단계), 도메인 규칙은 invariants(6단계), 상태는 전이(7단계). **거절은 GateError + 오류 코드**로: 문구(reason)는 다음 행동을 알려주는 한국어 문장, 코드는 기계용 식별자. 새 코드는 `domain/error-codes.ts`에 먼저 등록하고(복구 행동·canForce 포함) 커맨드 `errors`에 선언 — 등록 안 된 코드를 선언하면 조립이 실패한다.
167
+ 6. **위험한 일은 경고 패턴으로**: 되돌리기 어려운 삭제·병합은 그냥 실행하지 않고 **한 번 거절로 알려주고**, 확인 재시도(force:true)로만 실행 — 경고 코드는 등록소에 `canForce: true`로 표시한다. 동시에 **이벤트 payload에 스냅샷**을 남겨 복원 가능하게.
168
+ 7. **공통 옵션은 커맨드에 선언하지 않는다**: `requestKey`(멱등)·`dryRun`(사전 판정)은 게이트가 커맨드 몰래 처리하는 프로토콜 옵션이다 — 커맨드의 zod 스키마에 넣지 않는다.
169
+ 8. **상태가 있는 기능은 전이표를 채운다**: 커맨드마다 if-else를 짜는 게 아니라 `{from, to, command, roles}` 표를 채우면 게이트 7단계가 집행하고, 그 표는 카탈로그(transitions)에 노출돼 에이전트가 "다음 합법적 수"를 안다.
170
+ 9. **되돌림 커맨드는 "대상이 사라지는" 오퍼레이션에만**: 삭제·병합 → 전용 restore를 만든다(사라진 대상은 정상 커맨드로 복구할 길이 없다). 살아있는 대상의 변경(이름·위치·상태·코드) → 되돌림 커맨드를 만들지 않는다 — 원래 값으로 다시 실행하면 복구되고(옛값은 장부 이력으로 확인), 상태가 있으면 전이표의 뒤로 가는 전이(예: 승인 취소)가 담당한다. 되돌림은 rewind가 아니라 **게이트를 통과하는 순방향 보상(새로운 쓰기)**이다 — 과거로 되감으면 그 이후의 변경과 충돌한다. (2026-11-13 — 커널이 이 원칙의 공통 계약을 제공한다: 되돌리기 등록·미리보기·실행. 위 "선택 등록" 참고. 앱이 직접 만드는 restore 커맨드와 배치되는 관계는 채택 시점에 정한다.)
171
+ 10. **카탈로그는 접속자 권한별 안이다**: `allowedRoles`·위임 스코프가 같은 원천으로 카탈로그·도구 목록을 거르고, 대상 제한(`scope`≠none·위임 `커맨드:대상`)은 `restriction`으로 조건을 표시한다(커널 가시성 파생 — 실행은 게이트가 재판정). 역할 제한 조회는 **정의의 `allowedRoles`로 선언**한다(핸들러 안에서 역할을 가리지 않는다 — 실행(executeQuery)·카탈로그가 같은 선언을 쓰고, 어긴 선언은 조립이 실패한다). `public`과 `allowedRoles`는 함께 쓰지 않는다(공개 조회는 역할과 무관하므로 모순 — 조립 실패). 행 단위 범위(위임 토큰의 고객·테넌트 필터)는 여전히 핸들러가 담당한다.
172
+
173
+ ## DO / DON'T — 쓰기와 거절의 형태
174
+
175
+ ```ts
176
+ ❌ execute: async (i) => { await db.prepare('UPDATE clients SET region=?').run(i.region); return { events: [], result: null } }
177
+ ✅ execute: async (i) => ({ events: [{ type: 'client.regionChanged', …, payload: { … } }], result: { … } })
178
+ // DB는 읽어도(조회, await) 고치지 않는다 — 상태 변화는 이벤트가 일으킨다
179
+
180
+ ❌ throw new Error('이미 국내입니다')
181
+ ✅ throw new GateError(5, 'precondition', '이미 국내입니다', { code: 'client.same_region' })
182
+
183
+ ❌ errors: ['client.duplicated'] // error-codes.ts에 등록 안 한 코드
184
+ ✅ domain/error-codes.ts에 먼저 등록(복구 행동·canForce 포함) → errors에 선언
185
+
186
+ ❌ output 생략 // 조립이 실패한다
187
+ ✅ output: z.object({ … }).strict() // 반환값이 없으면 z.null()
188
+
189
+ ❌ input: z.object({ name: z.string(), requestKey: z.string().optional() })
190
+ ✅ input: z.object({ name: z.string() }) // requestKey·dryRun은 게이트의 프로토콜 옵션 — 넣지 않는다
191
+
192
+ ❌ 나중에 커맨드명 정리: 'client.changeRegion' → 'client.setRegion'
193
+ ✅ name은 배포 후 불변 — 카탈로그 계약이므로 바꾸면 MAJOR. 처음에 제대로 짓는다
194
+ ```
195
+
196
+ ## 4. 새 커맨드를 추가할 때 함께할 일
197
+
198
+ - 등록부 목록(`src/domain/commands/index.ts`)에 추가 → **REST·MCP에 자동 파생** (서피스는 손댈 곳 없음)
199
+ - 서피스가 그 커맨드를 부르면 `domain/command-input-map.ts`의 **입력·출력 두 지도에 각각 한 줄** 추가 (빠뜨리면 서피스 빌드가 실패)
200
+ - 새 이벤트 타입이면: 이벤트 계약(`domain/event-contracts.ts`) + 투영(재생) case + 이력 화면 요약 케이스 추가 (빠뜨리면 쓰기가 거절되거나 화면에 영어 타입이 그대로 보인다)
201
+ - 스모크 확장 — **성공 경로와 거절 경로를 항상 세트로** (거절이 1급 결과이므로 거절도 계약이다. 코드·복구까지 대조)
202
+ - 카탈로그 개수·문서 수치 갱신 + 버전 범프 (추가=minor)
203
+
204
+ ### 커밋 전 점검 — `npm run check:domain`과 같은 기준
205
+
206
+ ```bash
207
+ npm run check:domain # 아래 세트 누락·수치가 기계적으로 검사된다 (위반 시 실패)
208
+ npm run typecheck && npm run smoke # + mcp:test·policy:test (커널 계약·전이표·권한을 건드렸다면)
209
+ ```
210
+
211
+ - [ ] 등록부 1줄·지도 2줄·(새 이벤트면) 계약+투영+이력 요약 — 세트 누락 0건
212
+ - [ ] 한 파일=한 커맨드, `commands/<오브젝트>/<동사>.ts` — 커맨드명이 곧 경로다
213
+ - [ ] 스모크에 성공·거절 **쌍** 추가 — 거절도 계약(코드·복구까지 대조)
214
+ - [ ] execute가 이벤트만 반환 — DB 직접 쓰기 0건
215
+ - [ ] 새 오류 코드는 error-codes.ts에 먼저 등록했는가
216
+ - [ ] 카탈로그 개수·AGENTS 수치 갱신 + 카탈로그 버전 범프(minor)
217
+
218
+ ## 5. 새 앱을 시작할 때 — 체크리스트 (순서대로)
219
+
220
+ 1. **도메인 정의** — 데이터(엔티티·계층) · 프로세스(상태와 전이표) · 권한(역할·고객 범위)을 먼저 표로 정리
221
+ 2. **커맨드 카탈로그 설계** — 정의한 도메인을 요청서→번역(위 §1~3 절차)으로 커맨드로 쌓는다
222
+ 3. **커널·물리 계층 확보** — 커널 `@sudoke/kernel`(게이트·장부·등록소·권한 판정 빈칸·장부 반영 빈칸·물리 저장 포트. 업무·물리 import 0건 — 새로 안 짜도 된다)과 물리 구현 패키지를 가져간다 — 동기 엔진이면 `@sudoke/infra-sqlite`, 네트워크 Postgres(Supabase 등)면 `@sudoke/infra-postgres`. **저장 포트는 비동기 계약이다** — 포트 계약(쓰기 잠금 선점·순차 장부 적립·멱등 유일성·겹치는 트랜잭션 직렬화)을 지키는 엔진이라면 커널은 그대로 두고 **물리 패키지만 새로 쓴다**(SQLite 구현이 동기 엔진을 감싼 예시, Postgres 구현이 네트워크 엔진의 예시다). 계약을 지킬 수 없는 엔진(트랜잭션 없는 KV 저장소 등)은 애초에 이 포트의 밖이다
223
+ 4. **도메인 작성 + 조립** — 커맨드·전이표·app-policy(권한 판정)·app-projector(투영 규칙)·schema·이벤트 형식 계약·오류 코드를 쓰고 주입(assemble.ts가 단일 원천). **주입 순서: 물리 계층이 무엇보다 먼저** — `sqliteStorage({ dataDir: process.env.XXX_DATA_DIR, jwtSecret: process.env.XXX_JWT_SECRET })` 한 줄, 이어 ensureAppSchema. `db`는 여전히 `@sudoke/kernel`에서 import한다(등록된 물리 계층으로 연결되는 핸들 — 도메인 SQL 작성법은 변함없음). **모든 등록(커맨드·전이표·계약·정책·투영·프로토콜·조회·물리 계층)은 조립 시점에 끝난다 — 조립 완료 후 등록은 실패한다(등록소 봉인, assembleApp은 프로세스에 한 번)**. `--rebuild` 재구성 동작
224
+ 5. **자기설명 카탈로그** — 버전·프로토콜 프리앰블(거절=결과, code·recovery·canForce, force, dry-run, requestKey, batch, 커서, 전이표)·조회 메타·전이표·오류 코드 사전. **카탈로그는 접속자 권한별로 나온다**(현재 역할·위임 범위 안의 커맨드·조회·전이 규칙만 — 서피스는 커널 가시성 파생을 쓴다)
225
+ 6. **조회** — 설명·범위 표시, 공개 허용목록, 역할 제한은 정의의 `allowedRoles` 선언(생략=모든 역할), (에이전트 도입 시) 행 필터
226
+ 7. **인증** — 사람 로그인 + **위임 토큰**(처음부터 actor 감사 포함). 비밀번호는 코어 로그인에서만
227
+ 8. **서피스 2개로 시작** — 관리 UI 하나 + 시작 안내 페이지(첫 메시지 복사 + 위임 발급 패널)
228
+ 9. **검증 자동화** — 스모크(게이트 전 단계 + 재생 검증), 검증 격리(임시 DB·자유 포트), typecheck. **계약 검사는 공유 패키지 `@sudoke/dev-checks`**(의존성 0, 파일 2개 — 커널과 함께 배포). 앱 루트 `package.json`에 등록한다:
229
+ ```jsonc
230
+ // 같은 저장소 안의 앱 — 의존성으로 연결(복사 금지 — 단일 원천)
231
+ "dependencies": { "@sudoke/dev-checks": "*" },
232
+ "scripts": { "check:domain": "node ../dev-checks/check-domain.mjs", "check:ui": "node ../dev-checks/check-ui.mjs" }
233
+
234
+ // 저장소 밖 앱 — 패키지의 check-domain.mjs·check-ui.mjs 두 파일을 앱 scripts/에 복사한 뒤
235
+ "scripts": { "check:domain": "node scripts/check-domain.mjs", "check:ui": "node scripts/check-ui.mjs" }
236
+ ```
237
+ 앱 루트에서 `npm run check:domain`·`npm run check:ui`로 실행한다 — 도메인 파일 이름(commands/·event-contracts·app-projector·command-input-map)이 이 가이드 구조 그대로여야 검증이 돈다(이력 요약의 위치만 서피스의 자유다).
238
+ 10. **운영 규칙** — 백업=데이터 디렉터리 하나, 카탈로그 버전 범프 규칙, 요청서 절차로 기능 추가, 시드·데모는 자연스러운 이름으로(데모의 품질이 검증의 품질)
@@ -0,0 +1,144 @@
1
+ # 커널 업그레이드 가이드 — 0.3/0.4/0.5.x → 0.6
2
+
3
+ ## 0. 0.5.x → 0.6.0 (되돌리기 계약 보정)
4
+
5
+ 0.5.1에서 되돌리기를 실제 도메인에 처음 붙인 경험으로 계약을 4건 보정했습니다. 뼈대(새 쓰기로서의
6
+ 보상, 계획 해시, 손실 확인, 보상 1회 가드, 재전송 권한 재증명)는 그대로입니다.
7
+
8
+ | # | 변경 | 할 일 |
9
+ |---|---|---|
10
+ | ① | **되돌리기 핸들러에 `compensationCommand` 선언이 필수** — 보상 커맨드 하나를 정적으로 선언. 봉인 검사가 등록 여부를 확인하고, 커널이 `plan()` 호출 **전에** 선언된 커맨드의 접근 권한을 검사(거절이면 `denied`로 답하고 계획을 만들지 않음). 계획이 다른 커맨드를 담으면 `undo.plan_invalid` | 핸들러 등록에 한 줄 추가. `mayPreview` 훅은 **선택**으로 내려감(있으면 기본 검사 뒤에 실행) — "보상 커맨드를 쓸 수 있는가"만 검사하던 훅은 삭제 |
11
+ | ② | **권한 거절 어휘 통일 — `denied`** — `previewUndo`의 권한 거절(읽기 게이트·핸들러 게이트·보상 커맨드 역할/위임·거절 대상)이 `blocked` 대신 `denied`로 답함. 실행(`executeUndo`)에서도 권한 거절은 원래 단계·코드(1~3, 예: `gate.role_denied`·`gate.delegation_denied`)를 유지 — 8단계 재포장 폐지 | `preview.status === 'blocked'` 분기에서 권한 거절을 가려내던 앱 코드는 `denied` 분기 추가(작업 사실이 없음을 전제로 처리) |
12
+ | ③ | **기본 원본 읽기 게이트 `registerUndoReadGate`** — 앱 전체의 `mayRead`를 한 번 등록. 정책 항목의 `mayRead`가 있으면 그것이 우선 | 같은 함수를 이벤트 유형 수만큼 붙이던 조립은 한 번 등록으로 교체. 부팅 조건: "모든 정책에 mayRead 있음 **또는** 기본 게이트 등록"(둘 다 없으면 부팅 실패 — 읽기 권한은 선언된 결정이라는 원칙 유지) |
13
+ | ④ | **`undoStatus` 상한** — `sourceSeqs`가 `UNDO_STATUS_MAX_SEQS`(100)를 넘으면 4단계 입력 거절(`gate.schema_invalid`). 100건을 넘기며 앞 100건만 조용히 처리하던 절단 폐지 | 100건 넘는 조회를 하던 화면은 페이지 처리. 상수는 커널에서 export |
14
+
15
+ 커널 버전 **0.6.0**(핸들러 필수 필드 추가 = 0.x의 breaking → minor 범프), `PROTOCOL_VERSION` **1.1.0**
16
+ (미리보기 응답에 새 상태·카탈로그 정책 항목에 신규 필드 — 추가적 변화).
17
+
18
+ ### 0.6.1 (0.6.0 후속 보정 — 패치)
19
+
20
+ 0.6.0을 실제로 검토하며 재현된 두 불일치를 고쳤습니다. 공개 타입은 그대로라 `^0.6.0` 소비자에게 자동으로 흐릅니다.
21
+
22
+ | # | 변경 | 할 일 |
23
+ |---|---|---|
24
+ | ① | **상태 조회와 미리보기가 같은 신원에게 같은 답을 한다** — 보상 커맨드 접근 검사가 공유 판정 안으로 이동. 권한 없는 신원의 `undoStatus` 행이 `supported`(handlerId 포함) 대신 `denied`(코드만)로 답한다 | 없음(교정). `mayPreview`가 "보상 커맨드를 쓸 수 있는 신원인가" 확인뿐이면 **이제 제거해도 상태 조회가 올바르게 답한다** — 커널이 계획 앞에서 검사함 |
25
+ | ② | **재전송 재증명이 미리보기 상태와 무관** — 저장된 보상이 있으면 현재 정책(지원·미지원·혼합 무관)과 무관하게 기록된 봉투(커맨드·기록된 대상)로 권한 재증명. 커맨드가 제거됐으면 재료 부재로 거절 | 권한이 회수된 뒤 같은 requestKey 재요청이 거절되는 것은 의도된 동작(기존 원칙의 누락 복원) |
26
+
27
+ 물리 계층을 커널 패키지로
28
+ 쓰는 앱은 **infra ^0.6.0 짝(infra-sqlite·infra-postgres 0.5.0)**으로 함께 올려야 로컬 워크스페이스
29
+ 커널과 연결됩니다(^0.5.0은 0.6.0과 맞지 않아 npm이 레지스트리 0.5.x를 중첩 설치합니다).
30
+ 카탈로그 되돌리기 정책 항목에
31
+ `compensationCommand`가 함께 공개되므로 `catalogRevision`이 이동합니다 — 재접속 시 `catalog_status`로
32
+ 변경분을 읽으세요. 한 핸들러가 여러 보상 커맨드를 계획해야 하는 사례가 생기면 커널에 보고 바랍니다
33
+ (현재 계약은 핸들러당 보상 커맨드 하나).
34
+
35
+ ---
36
+
37
+ `@sudoke/kernel` 0.3.x/0.4.x로 만든 앱을 **0.5.0**으로 올리는 안내.
38
+
39
+ > **0.5.0은 방향이 다릅니다.** 0.4까지는 계약 체제가 선택(strict 모드)이었지만, 0.5.0은
40
+ > **compat/strict 이중 모드를 없애고 계약 체제를 무조건 적용**합니다 — 과거 호환 경로는 제거됐고
41
+ > `configureKernel` 호출 자체가 사라졌습니다(호출부는 삭제하세요).
42
+ >
43
+ > **자동으로 올라가지 않습니다.** semver 0.x에서 `^0.4.0`은 0.5를 포함하지 않습니다 —
44
+ > 이 가이드는 직접 버전을 올리기로 한 앱을 위한 문서입니다. 올리지 않으면 아무 것도 바뀌지 않습니다.
45
+ > 0.4까지만 올려 점진적으로 적응하는 것도 좋습니다(0.4는 여전히 compat 모드가 있습니다).
46
+
47
+ ## 1. 의존성 업데이트
48
+
49
+ ```jsonc
50
+ // package.json
51
+ {
52
+ "dependencies": {
53
+ "@sudoke/kernel": "^0.5.0"
54
+ // 물리 계층을 커널 패키지로 쓰는 앱만 (같이 올려야 짝이 맞음):
55
+ , "@sudoke/infra-sqlite": "^0.4.0"
56
+ }
57
+ }
58
+ ```
59
+
60
+ - infra 0.4.0은 **기존 DB를 그대로** 씁니다 — 부팅 시 events 테이블에 meta 열이 없으면 그 자리에서 추가합니다(무손실 마이그레이션). 데이터 이동·백업 복원이 필요 없습니다.
61
+ - `@sudoke/infra-postgres`를 쓰는 앱도 같은 규칙(`^0.4.0`, `ADD COLUMN IF NOT EXISTS`).
62
+ - 커널 API 상세는 [packages/kernel/README.md](../README.md) (영어, 이 패키지에 동봉).
63
+
64
+ ## 2. 부팅 요건 — 통과 못 하면 앱이 켜지지 않습니다
65
+
66
+ 0.5.0의 부팅 검사는 전부 **무조건**입니다. 봉인(첫 실행 또는 명시적 seal) 시점에:
67
+
68
+ | 요건 | 내용 |
69
+ |---|---|
70
+ | 커맨드·조회 버전 | 모든 커맨드와 조회에 `version: '1.0.0'` 같은 semver 선언 |
71
+ | 되돌리기 정책 | 등록된 **모든 이벤트 유형**에 정책 — `{kind:'supported', handlerId}` 또는 `{kind:'unavailable', code, reason}`. 지원은 선택이지만 **선언은 필수** (없는 침묵은 결함) |
72
+ | 읽기 권한 훅 | 모든 정책에 `mayRead`, 모든 핸들러에 `mayPreview` — "누가 되돌림 내역을 읽나"는 선언된 결정이어야 함 |
73
+ | 저장소 능력 | 물리 엔진이 operationLedger 제공 (infra ^0.4.0이면 이미 갖춰짐) |
74
+
75
+ > **0.6.0부터 이 표의 두 행이 바뀝니다** — 읽기 권한은 "모든 정책 `mayRead` **또는** 앱 전체 기본 게이트
76
+ > (`registerUndoReadGate`) 한 번", 핸들러 요건은 `mayPreview` 대신 **보상 커맨드 선언
77
+ > (`compensationCommand`, 필수)**. 자세한 이행은 맨 위 §0의 ①·③을 보세요. infra 짝 버전도
78
+ > ^0.5.0 → ^0.6.0(infra 0.5.0)으로 올라야 로컬 워크스페이스 커널과 연결됩니다.
79
+
80
+ ```ts
81
+ // 가장 흔한 최소 패턴 — 되돌림을 당장 안 쓰는 앱의 선언
82
+ registerUndoPolicies(
83
+ Object.fromEntries(
84
+ Object.keys(APP_EVENT_CONTRACTS).map((type) => [
85
+ type,
86
+ { kind: 'unavailable', code: 'app.not_reversible', reason: '이 이벤트는 되돌림 없음', mayRead: async () => {} },
87
+ ]),
88
+ ),
89
+ )
90
+ ```
91
+
92
+ (이때 `app.not_reversible` 코드는 `registerErrorCodes`에 등록돼 있어야 합니다.)
93
+
94
+ ## 3. 모든 쓰기에 계약 첨부 — **0.5.0의 핵심 변화**
95
+
96
+ 모든 쓰기 요청에 카탈로그에서 읽은 계약을 붙여야 합니다:
97
+
98
+ ```ts
99
+ { ...비즈니스입력, contract: { commandVersion, commandRevision, protocolVersion } }
100
+ ```
101
+
102
+ - 없으면 `gate.contract_required`, 낡았으면 `gate.contract_changed` — **거부는 계약을 다시 읽으라는 안내**입니다(recovery: refresh).
103
+ - **통로 한 곳에서 해결합니다**: 화면·스크립트의 api 클라이언트(runCommand 같은 공통 함수)가 카탈로그 상태를 캐시해 자동 첨부합니다. 호출부 전면 수정은 필요 없습니다.
104
+ - **`gate.contract_changed`를 받으면 재학습이 먼저입니다**: ① 카탈로그 상태와 변경 내용(`catalog_changes`·`command_contract`)을 읽고 ② 무엇이 바뀌었는지(버전·입력 의미·경고) 확인한 뒤 ③ 기존 요청의 의미가 그대로 유효한지 판단합니다. **revision만 바꿔 자동 재전송하는 것은 안전하지 않습니다** — 같은 숫자라도 단위가 센트에서 달러로 바뀐 MAJOR 변경이라면 새 계약 검사는 통과하지만 사용자의 원래 의도와 다른 금액으로 실행될 수 있습니다. 커널은 "호출자가 새 계약을 이해했는지"를 증명할 수 없습니다.
105
+ - **자동 재시도는 의미 보존을 확인할 수 있을 때만**: 변경 기록이 "설명 문구만 바뀜"처럼 입력 의미에 닿지 않음을 **앱이 명시적으로 판정할 수 있는 경우에만** 재시도를 자동화하고, 그 판정 근거를 코드에 남기세요. "같은 MAJOR 안"이라는 사실만으로 의미 확인을 대체할 수 없습니다. 판단이 서지 않으면 호출자·에이전트에게 새 계약을 보여주고 요청을 다시 구성하게 합니다.
106
+ - 멱등 재전송(requestKey 재요청)은 계약 검사보다 **먼저** 판정됩니다 — 이미 저장된 성공은 오늘의 스키마가 바뀌었어도 그대로 반환됩니다.
107
+ - MCP 도구는 `contract` 파라미터를 받습니다 — 외부 에이전트는 카탈로그(`command_contract` 도구)를 먼저 읽고 첨부합니다.
108
+
109
+ ## 4. 함께 달라진 것 (0.4 변경분 포함)
110
+
111
+ | # | 변경 | 할 일 |
112
+ |---|---|---|
113
+ | ① | 카탈로그 문서·상태의 버전 필드명 `version` → **`catalogVersion`** (옛 이름 alias 폐지) | 커널 카탈로그를 읽는 코드만 필드명 교체 (앱이 스스로 내놓는 상태 응답은 무관) |
114
+ | ② | 카탈로그 커맨드 항목의 `fields`가 **문서화되지 않은 필드까지 전부 나열** (값 `null`) | fields를 순회하는 코드에서 `null` 처리 |
115
+ | ③ | MCP `tools/list`에 공통 도구 7종 추가 — `catalog`·`catalog_status`·`catalog_changes`·`command_contract`·`undo_status`·`undo_preview`·`undo_execute` | 도구 이름을 검증하는 목록(테스트 포함) 갱신 — 전부 snake_case |
116
+ | ④ | **재전송(멱등 재생)이 권한을 재증명** — 저장된 성공의 재요청은 기록된 역할·위임 범위·현행 할당으로 다시 판정 | 권한이 회수된 뒤 같은 requestKey로 재요청하던 흐름은 이제 거부(의도된 동작). **생산자 추적 이전의 오래된 행**도 재증명 재료가 없어 거부됩니다(예전의 `{unknown:true}` 마커 폐지) |
117
+ | ⑤ | MCP 쓰기 값이 직접 API와 동일해짐 — 이중 정규화(coerce·trim 두 번) 제거 | 수정 불필요. 미묘하게 값이 달라지던 앱은 이제 같음 |
118
+ | ⑥ | 재생 응답에 `producedBy`(그 결과를 만든 계약) 부가 | 무시해도 됨 (부가 필드) |
119
+
120
+ 새 오류 코드: `gate.contract_required`·`gate.contract_changed`(§3)와 `undo.*` 10종(되돌리기를 켠 앱만) — **코드 목록을 전수 검증하는 앱만** 사전 갱신.
121
+
122
+ ## 5. 여기서부턴 선택 — 필수 조립(§2)과 구분해서 읽으세요
123
+
124
+ - **되돌리기 실행 기능** — §2의 정책 선언과 `mayRead`는 **필수 조립 요건**입니다. 선택인 것은 그 다음: `{kind:'supported', handlerId}`로 실제 핸들러(`registerUndoHandler` — 플랜 계산·`mayPreview`)를 붙여 `previewUndo`·`executeUndo`·`undoStatus`를 켜는 일. `unavailable` 선언만으로 끝내도 0.5.0은 완전히 부팅·동작합니다. 되돌림은 순방향 보상(새 쓰기)이고 원본 이력은 불변입니다.
125
+ - **계약 발견 도구** — `command_contract`(커맨드 하나의 기계 판독 계약)·`catalog_status`·`catalog_changes`(재접속 시 변경분만). 쓰지 않아도 무방합니다.
126
+
127
+ ## 6. 업그레이드 절차
128
+
129
+ ```
130
+ 1. 의존성 범프(§1) → npm install
131
+ 2. 부팅 요건 충족(§2) — 버전 선언·되돌리기 정책·mayRead — 앱을 켜서 부팅 확인
132
+ 3. 쓰기 통로에 계약 자동 첨부(§3) — contract_changed는 재학습 후 재구성, 자동 재시도는 의미 보존 판정이 있을 때만(§3)
133
+ 4. §4의 확인(① 카탈로그 필드명 ② fields null ③ 도구 목록 ④ 재전송 권한)
134
+ 5. 앱 자체 검증 실행 (스모크/MCP/정책 — 각 앱의 것)
135
+ 6. (선택) 되돌리기 도입은 별도 작업으로 — §5
136
+ ```
137
+
138
+ ## FAQ
139
+
140
+ **Q. 안 올리면?** — 아무 변화 없음. 0.3.x/0.4.x는 그대로 npm에 있습니다.
141
+ **Q. 0.4까지만 올려도 되나요?** — 됩니다. 0.4는 compat 모드가 있어 §4의 확인만으로 충분하고, 0.5의 무조건 체제는 준비되면 갑니다.
142
+ **Q. 되돌리기를 바로 켜야 하나요?** — 아니요. §2의 `unavailable` 선언(필수)으로 끝낼 수 있고, 실제 핸들러·UI 도입(선택)은 나중에 언제든.
143
+ **Q. DB는?** — infra 0.4.0이 기존 파일을 그 자리에서 마이그레이션합니다. 백업은 늘 권장하지만 절차는 필요 없습니다.
144
+ **Q. 계약 첨부를 안 하면?** — 모든 쓰기가 `gate.contract_required`로 거부됩니다. 통로 한 곳에서 자동 첨부로 해결하세요.