@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 +63 -25
- package/docs/domain-development-guide.md +238 -0
- package/docs/kernel-upgrade-guide.md +144 -0
- package/docs/surface-development-guide.md +165 -0
- package/docs/undo-scope-guide.md +92 -0
- package/package.json +3 -2
- package/src/catalog.ts +14 -7
- package/src/index.ts +3 -2
- package/src/mcp.ts +3 -3
- package/src/registry.ts +32 -15
- package/src/state.ts +5 -1
- package/src/storage.ts +6 -5
- package/src/types.ts +25 -13
- package/src/undo.ts +146 -117
- package/src/visibility.ts +44 -7
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# 서피스 개발 가이드 — UI 패턴 규칙(관리형 화면 공통·골격·표)
|
|
2
|
+
|
|
3
|
+
관리자 CRUD·목록 화면(기능 관리, 고객 관리 등)의 페이지 골격과 표에 적용할 규칙.
|
|
4
|
+
도메인 특성은 없다 — 새 앱의 서피스도 이 기준 그대로 시작한다.
|
|
5
|
+
|
|
6
|
+
## 0. 계약 — 이 4줄은 예외 없음
|
|
7
|
+
|
|
8
|
+
1. **UI 컴포넌트는 반드시 `@/components/ui/*`에서 import한다.** 로우 `<button>` `<select>` `<table>`·직접 만든 모달 `<div>`를 쓰지 않는다.
|
|
9
|
+
2. **필요한 컴포넌트가 ui/에 없으면 직접 짜지 않는다** — `npx shadcn@latest add <이름>`으로 추가한다. (컨트롤이 아닌 커스텀 위젯(매트릭스 셀 등)은 직접 만들어도 되되, 색·타이포는 시맨틱 토큰만 — R13·R12. 로우 요소가 꼭 필요하면 그 줄에 `/* check:ui-allow: 이유 */` 표식을 남긴다.)
|
|
10
|
+
3. **모양·크기·간격은 shadcn 공식 문서가 기준** — 이 가이드는 수치를 정하지 않는다. 필요한 컴포넌트가 ui/에 없으면 `npx shadcn@latest add <이름>`으로 추가한다.
|
|
11
|
+
4. **기획자가 지정한 화면은 화면 구성서 한 장에서 시작한다**(ui-request-guide.md) — 구성서 없는 화면은 서피스 재량으로 만든다.
|
|
12
|
+
|
|
13
|
+
**검증**: `npm run check:ui` — 이 계약의 기계적 검사다. 커밋 전에 통과해야 한다(아래 "커밋 전 점검"과 같은 기준). 스크립트는 공유 패키지 **`@sudoke/dev-checks`**의 `check-ui.mjs`(`components/ui/` 밖의 `surface/main/src`를 검사) — 복사·npm 등록 세팅은 도메인 개발 가이드 §5-9를 따른다.
|
|
14
|
+
|
|
15
|
+
## DO / DON'T — 컨트롤은 표준 컴포넌트로
|
|
16
|
+
|
|
17
|
+
```tsx
|
|
18
|
+
❌ <button className="h-6 px-2 text-xs">저장</button>
|
|
19
|
+
✅ <Button size="sm">저장</Button>
|
|
20
|
+
|
|
21
|
+
❌ <button className="p-1 text-muted-foreground"><ChevronRight /></button> (아이콘 토글)
|
|
22
|
+
✅ <Button variant="ghost" size="icon"><ChevronRight /></Button>
|
|
23
|
+
|
|
24
|
+
❌ <select className="border rounded px-2">…</select>
|
|
25
|
+
✅ <Select><SelectTrigger className="w-full"><SelectValue /></SelectTrigger>…</Select>
|
|
26
|
+
|
|
27
|
+
❌ <table className="w-full"><thead>…</thead></table>
|
|
28
|
+
✅ <Table><TableHeader><TableRow><TableHead>…</TableHead></TableRow></TableHeader>…</Table>
|
|
29
|
+
|
|
30
|
+
❌ <div className="fixed inset-0 z-50 bg-black/50">…직접 만든 모달…</div>
|
|
31
|
+
✅ <Dialog open={open} onOpenChange={setOpen}><DialogContent>…</DialogContent></Dialog>
|
|
32
|
+
|
|
33
|
+
❌ ui/에 없는 컴포넌트(토스트·팝오버·탭)를 div로 직접 조립
|
|
34
|
+
✅ npx shadcn@latest add popover → import { Popover } from '@/components/ui/popover'
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### 스타일 DO / DON'T
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
❌ <Button size="sm" className="h-6 w-14">…</Button> (임의 h-* — data-size가 이기지만 쓰지 않는다)
|
|
41
|
+
✅ <Button size="sm">…</Button> (크기는 shadcn size 변형만)
|
|
42
|
+
|
|
43
|
+
❌ <span className="text-red-600">삭제됨</span> · className="bg-[#ff4d5e]"
|
|
44
|
+
✅ <span className="text-destructive">삭제됨</span> (색은 시맨틱 토큰만)
|
|
45
|
+
|
|
46
|
+
❌ <span className="text-13">…</span> (커스텀 폰트 토큰 — twMerge가 색으로 오인)
|
|
47
|
+
✅ <span className="text-sm">…</span> (shadcn 표준 토큰)
|
|
48
|
+
|
|
49
|
+
❌ <div style="margin-top: 8px"> (정적 스타일)
|
|
50
|
+
✅ <div className="mt-2"> (클래스로)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## 규칙
|
|
54
|
+
|
|
55
|
+
### R1. 생성 폼은 항상 노출하지 않는다 — 툴바 버튼 + 다이얼로그
|
|
56
|
+
- 항상 보이는 입력 폼 카드는 본문(표)과 경쟁하고, 안 쓸 때는 공간 낭비다.
|
|
57
|
+
- 규칙: 화면 상단 툴바에 `[+ 추가]` 버튼 → 클릭 시 다이얼로그. 필드 3개 이하의 짧은 생성은 다이얼로그가 적합하다.
|
|
58
|
+
- 다이얼로그 필드 순서는 표 컬럼 순서와 일치(예: 코드→이름), 첫 필드에 포커스(autoFocus).
|
|
59
|
+
|
|
60
|
+
### R2. 행 편집은 인라인 대신 다이얼로그 — 단, 한 번에 끝나는 조작은 예외
|
|
61
|
+
- 표 칸 안에서 input으로 바뀌는 인라인 편집은 행 높이가 변하고 주변 컨텐츠가 밀리며, 여러 필드가 되면 감당 안 된다.
|
|
62
|
+
- 규칙: 필드 1개짜리라도 **다이얼로그(또는 팝오버)**로. 토글(활성/비활성)·셀렉트 선택처럼 클릭 한 번에 끝나는 것만 즉시 실행.
|
|
63
|
+
|
|
64
|
+
### R3. 행 작업은 1~2개만 노출, 나머지는 케밥(⋯) 메뉴로
|
|
65
|
+
- 행마다 버튼 4개가 늘어서면 스캔이 어렵고 표가 버튼 목록처럼 보인다.
|
|
66
|
+
- 규칙: 자주 쓰는 작업 최대 2개만 버튼 노출, 나머지는 행 끝 `⋯` 오버플로 메뉴. 파괴적 작업(삭제)은 메뉴 안에서 destructive 스타일.
|
|
67
|
+
|
|
68
|
+
### R4. 드문 기능은 2차 화면으로 — 점진적 공개
|
|
69
|
+
- 거의 안 쓰는 기능이 항상 자리를 차지하면 학습성과 밀도가 나빠진다.
|
|
70
|
+
- 규칙: 복원·병합 되돌리기 같은 저빈도 작업은 전용 2차 화면(이력 페이지)이나 아코디언으로 이동. 장부(이벤트 로그) 기반 작업은 이력 화면의 해당 이벤트 행에 버튼을 붙이는 게 가장 자연스럽다.
|
|
71
|
+
|
|
72
|
+
### R5. 다이얼로그 접근성 최소한
|
|
73
|
+
- 규칙: Esc로 닫기, 닫기 버튼 표시, 포커스 트랩 + 닫힐 때 트리거로 포커스 복귀, 다이얼로그 안에 다이얼로그 금지. (shadcn Dialog는 기본 제공 — 직접 만들지 않는 한 지켜진다.)
|
|
74
|
+
|
|
75
|
+
### R6. 파괴적 작업은 경고 → 확인 2단계 (이미 게이트가 담당)
|
|
76
|
+
- 게이트의 경고=거절 → force 재시도 패턴이 곧 이 규칙의 구현이다.
|
|
77
|
+
- 규칙: UI는 확인 다이얼로그에 결과를 명시(무엇이 지워지고 무엇이 보존되는지). 되돌림 경로를 함께 안내.
|
|
78
|
+
|
|
79
|
+
### R7. 표는 shadcn 표준 — 밀도·크기 수치는 정하지 않는다
|
|
80
|
+
- 표·셀·컨트롤의 크기와 폰트는 **shadcn 표준을 그대로** 쓴다 — 이 가이드는 픽셀 규격을 정하지 않는다.
|
|
81
|
+
- **기존 로우 `<table>` 페이지는 그 페이지를 건드릴 때 `ui/Table`로 이전한다**(`check:ui`가 부채로 알려준다). 새 코드는 무조건 `ui/Table`.
|
|
82
|
+
|
|
83
|
+
### R8. 저정보 컬럼·배지는 없애고 인라인 단서로
|
|
84
|
+
- 들여쓰기나 모양만으로 알 수 있는 정보를 컬럼으로 늘리면 밀도만 높아지고 본문(상태·액션)과 경쟁한다.
|
|
85
|
+
- 규칙: 계층 깊이(L1/L2…)처럼 구조로 알 수 있는 것은 컬럼 없이 들여쓰기로. 상태(활성/비활성)도 전용 컬럼 대신 이름 톤(비활성=muted)+툴팁으로.
|
|
86
|
+
- 긴 원본 데이터(이벤트 payload 등)는 컬럼에 한국어 한 줄 요약, 원본은 행 툴팁으로.
|
|
87
|
+
|
|
88
|
+
### R9. 비활성·과거 상태는 뷰 토글로 — 점진적 공개 (뷰 버전)
|
|
89
|
+
- 관리 목록의 비활성 항목은 가끔만 필요하다(재활성화·확인). 상시 노출은 본문 스캔을 방해한다.
|
|
90
|
+
- 규칙: 툴바에 `[비활성 숨기기/표시]` 토글(기본 표시). 숨길 때는 해당 항목과 **하위 전체**를 함께 감춘다(고아 방지).
|
|
91
|
+
|
|
92
|
+
### R10. 페이지 골격 — 제목 행 / 툴바 / 표 / 페이지네이션
|
|
93
|
+
- 골격 순서: 제목 행 → 툴바 → 표 → 페이지네이션.
|
|
94
|
+
- 제목 행은 제목·설명 한 줄만 담는다(동작 버튼은 툴바로).
|
|
95
|
+
- 툴바: **필터는 왼쪽**, 주요 동작(`+ 등록`)은 **오른쪽**. 필터가 없으면 툴바 전체를 오른쪽 정렬.
|
|
96
|
+
- 힌트 문구는 툴바 아래 보조 캡션(muted 톤)으로. 본문 중간 레이블은 섹션이 2개 이상일 때만 단다.
|
|
97
|
+
- 시각 표기는 연도 포함 풀 날짜.
|
|
98
|
+
|
|
99
|
+
### R11. 간격은 구조로
|
|
100
|
+
- 간격 수치는 정하지 않는다 — shadcn 컴포넌트 기본값과 Tailwind 유틸리티 리듬을 그대로 쓴다.
|
|
101
|
+
- `space-y` 레이아웃에서 개별 요소에 마진을 추가하면 리듬이 무너진다 — 간격을 바꾸려면 래퍼 구조로.
|
|
102
|
+
- 다이얼로그 폼 간격은 shadcn 공식 폼 관례를 그대로 따른다.
|
|
103
|
+
|
|
104
|
+
### R12. 크기·타이포는 shadcn 계층
|
|
105
|
+
- 컨트롤 크기는 shadcn 표준 **size 변형**만 쓴다 — `className`의 임의 `h-*` 금지 (data-size 클래스가 일반 `h-*`를 이긴다 — tailwind-merge가 못 지움).
|
|
106
|
+
- **한 줄에 나란히 놓이는 컨트롤은 같은 size 변형** — default끼리는 Button·Input·Select가 같은 높이로 맞는다. 섞으면 줄이 어긋난다(sm는 그 줄 전부가 sm일 때만).
|
|
107
|
+
- 폰트는 shadcn 표준 토큰만 쓴다 — 커스텀 `text-*` 토큰은 twMerge가 글자 색으로 오인해 색 변형에서 지워진다.
|
|
108
|
+
|
|
109
|
+
### R13. 색은 shadcn 시맨틱 토큰만
|
|
110
|
+
- 팔레트 직접 참조 금지 — 시맨틱 토큰만 쓴다.
|
|
111
|
+
|
|
112
|
+
### R14. 반복되는 값은 조용한 텍스트 — 칩은 마커에만
|
|
113
|
+
- 대부분의 행이 같은 값인 컬럼(예: 국내 25행 중 24행 국내)은 muted 텍스트로. 전부 칩(배지)으로 감싸면 정보 없는 노이즈만 늘어난다.
|
|
114
|
+
- 칩은 소속 관계(자회사) 같은 **구조 마커**나 눈에 띄어야 할 소수 대상에만 단다.
|
|
115
|
+
- 특정 값(예: 해외)을 눈에 띄게 하려면 전체 칩이 아니라 그 값만 강조한다(저빈도 표시).
|
|
116
|
+
- 셀 안에 같은 라벨 반복 금지 — 숫자·색 + 범례 한 줄로 담는다(전체 현황 매트릭스 셀 "2 · 1 · 5" 사례).
|
|
117
|
+
|
|
118
|
+
### R15. 컴포넌트 기반은 shadcn/ui — 공식 사이트가 기준
|
|
119
|
+
- 버튼·다이얼로그·표·드롭다운 등 컨트롤은 shadcn/ui 공식 컴포넌트를 그대로 쓴다(자체 제작 금지). 모양·변형·a11y는 공식 문서가 기준.
|
|
120
|
+
- ui 컴포넌트 목록(기준 서피스 것: badge·button·card·dialog·dropdown-menu·input·label·scroll-area·select·separator·sheet·sonner·table·textarea). **목록에 없는 컨트롤이 필요하면 `npx shadcn@latest add <이름>`으로 추가한다**(직접 조립 금지) — 새 앱은 자기가 add한 목록에 같은 규칙을 적용한다.
|
|
121
|
+
- 테마는 shadcn create 페이지(Get Code → Theme 탭)에서 추출한 토큰 세트를 쓴다(R13 시맨틱 토큰과 연결).
|
|
122
|
+
- 필요한 크기가 shadcn 기본 변형에 없으면 임의 `className` 말고 shadcn 관례대로 **size 변형을 추가**한다(R12).
|
|
123
|
+
|
|
124
|
+
### R16. 화면 뼈대는 공식 Blocks에서 — 직접 조립하지 않는다
|
|
125
|
+
- 사이드바·대시보드·로그인 같은 화면 뼈대는 shadcn 공식 Blocks(sidebar·dashboard 등)에서 선택해 그대로 시작한다 — 메뉴 구조·간격·반응형 동작이 공식 예제 값으로 고정된다(컴포넌트에 R15가 있듯 레이아웃의 같은 원칙).
|
|
126
|
+
- Blocks에 없는 구조만 최소로 직접 짠다 — 그때도 R10 골격·R11 간격·R12·R13 토큰 원칙 안에서.
|
|
127
|
+
|
|
128
|
+
### R17. 앱은 역할별 배정표를 가진다 — 화면마다 새로 정하지 않는다
|
|
129
|
+
- 앱 시작 시 역할별 타이포·간격 배정표(화면 제목·설명·섹션 제목·본문·페이지 수직 리듬 등 — **표준 토큰만으로**)을 한 번 정해 문서화하고, 모든 화면이 그 표를 따른다.
|
|
130
|
+
- 허용된 토큰만 쓰더라도 화면마다 제각각이 될 수 있다 — 일관성은 "같은 역할엔 같은 토큰"에서 나온다. 배정은 표준값 중 무엇을 쓸지 찍어두는 것이지 새 값을 발명하는 게 아니다.
|
|
131
|
+
|
|
132
|
+
### R18. 화면 문구는 사용자의 언어로 — 내부 참조를 노출하지 않는다
|
|
133
|
+
- 화면에 보이는 모든 문구(제목 아래 설명·버튼·라벨·상태·빈 상태·오류·확인 문구)는 그 화면을 쓰는 사용자의 언어로 쓴다.
|
|
134
|
+
- 금지: 요청서 행 코드(A1·B2 같은 코드), 내부 메커니즘(장부·게이트·커맨드·이벤트·투영·위임 토큰·멱등·row_hash), 개발 프로세스 어휘("화면 구성서에서 확정"·"요청서로 등록" 같은 것). 구성서·요청서의 문장은 설계 문서이지 화면 원문이 아니다 — 서피스를 쓸 때 사용자 관점으로 다시 쓴다.
|
|
135
|
+
- 판단 기준: 그 문구가 "이 기능으로 무엇을 할 수 있는지"를 사용자에게 말하는가, "이 시스템이 어떻게 지어졌는지"를 개발자에게 말하는가 — 후자면 지우거나 바꾼다.
|
|
136
|
+
- 예외: 사용자가 보기를 요청한 개발 로드맵 안내(예: "이 기능은 ③단계 통계 화면에서 만들어집니다")는 노출 자체가 목적이다 — 단계·기능명까지만 쓰고 내부 구조 언급은 같은 규칙을 따른다.
|
|
137
|
+
|
|
138
|
+
## 커밋 전 점검 — `npm run check:ui`와 같은 기준
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
npm run check:ui # 아래 목록이 기계적으로 검사된다 (위반 시 실패)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
- [ ] 로우 `<button>`·`<select>` — components/ui 밖 0건
|
|
145
|
+
- [ ] 로우 `<table>` — 새 코드 0건(기존 페이지는 건드릴 때 ui/Table로 이전, R7)
|
|
146
|
+
- [ ] `style="` 문자열·정적 style 객체 0건 — style은 계산값(트리 들여쓰기)만
|
|
147
|
+
- [ ] 임의 색(`bg-[#…]` 등) 0건 — shadcn 시맨틱 토큰만
|
|
148
|
+
- [ ] `text-13` 같은 커스텀 폰트 토큰 0건 — shadcn 표준 토큰만
|
|
149
|
+
- [ ] 새 컨트롤은 shadcn add로 추가했는가 — ui/에 없다고 직접 조립하지 않았는가 (커스텀 위젯 예외에는 `check:ui-allow: 이유` 표식)
|
|
150
|
+
- [ ] 페이지는 골격 스니펫 순서(제목행→툴바→표→페이지네이션)인가
|
|
151
|
+
- [ ] 크기는 shadcn size 변형 — 임의 className(h-*) 아님
|
|
152
|
+
|
|
153
|
+
## URL 명명 규칙
|
|
154
|
+
|
|
155
|
+
- **단수 = 대상을 선택해 보는 뷰** (`/function`, `/client`), **복수 = 목록·관리** (`/notes`, `/functions`, `/clients`) — 노트 뷰는 노트 목록 그 자체라 복수다.
|
|
156
|
+
|
|
157
|
+
## 부록 — 규칙의 근거
|
|
158
|
+
|
|
159
|
+
- R1: [NN/g Modal & Nonmodal Dialogs](https://www.nngroup.com/articles/modal-nonmodal-dialog) (짧은 단일 작업에 모달 적합), [Atlassian Modal Dialog](https://atlassian.design/components/modal-dialog)
|
|
160
|
+
- R2: [SaaS UX Patterns](https://www.saasui.design/blog/saas-modal-dialog-ux-patterns), [UX 사례 연구](https://rakibulism.medium.com/choosing-modals-over-inline-actions-a-ux-case-study-on-table-complexity-2552ee168b5c)
|
|
161
|
+
- 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 권장](https://github.com/ant-design/ant-design/issues/25799) (행당 노출 액션 ≤2), [NN/g Contextual Menus](https://www.nngroup.com/articles/contextual-menus-guidelines)
|
|
162
|
+
- R4·R9: [NN/g Progressive Disclosure](https://www.nngroup.com/articles/progressive-disclosure)
|
|
163
|
+
- R5: [WAI-ARIA Dialog Modal 패턴](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal), [A11y Collective](https://www.a11y-collective.com/blog/modal-vs-dialog)
|
|
164
|
+
- R7: [Carbon Data Table](https://www.carbondesignsystem.com/building-blocks/core/components/data-table) (compact 밀도), [Ant Design Table](https://ant.design/components/table) (size small/middle)
|
|
165
|
+
- R8: [NN/g How Users Read on the Web](https://www.nngroup.com/articles/how-users-read-on-the-web/)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# 되돌리기(undo) 대상 선정 가이드
|
|
2
|
+
|
|
3
|
+
도메인을 만들거나 고치는 에이전트가 "어떤 이벤트를 커널 공통 되돌리기로 지원할 것인가"를 정할 때 쓰는 기준이다.
|
|
4
|
+
커널 0.6.1 기준이며, 커널 쪽 계약은 [packages/kernel/README.md](../README.md)의 Undo 절을 따른다.
|
|
5
|
+
|
|
6
|
+
## 원칙
|
|
7
|
+
|
|
8
|
+
**실수했을 때 손으로 되돌리기 어려운 것만 지원한다.** 나머지는 `unavailable`로 두고 사유에 대안을 적는다.
|
|
9
|
+
전부 지원하려고 하지 않는다. 지원하는 이벤트마다 핸들러·테스트·이벤트 형식 관리가 따라오기 때문이다.
|
|
10
|
+
|
|
11
|
+
커널은 모든 이벤트 타입에 정책 선언을 요구한다. 이 요구는 "전부 지원하라"가 아니라
|
|
12
|
+
"지원 여부를 타입마다 결정하라"는 뜻이다.
|
|
13
|
+
|
|
14
|
+
## 판단 순서
|
|
15
|
+
|
|
16
|
+
이벤트 타입마다 위에서부터 차례로 묻고, 처음 걸리는 곳에서 결정한다.
|
|
17
|
+
|
|
18
|
+
| 순서 | 질문 | 걸리면 |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| 1 | 비밀·권한·외부 효과인가? | 지원하지 않는다 |
|
|
21
|
+
| 2 | 업무상 "상태"가 아니라 "기록"인가? | 지원하지 않는다 |
|
|
22
|
+
| 3 | 같은 커맨드를 다시 실행하면 원래대로 돌아가는가? | 지원하지 않는다 |
|
|
23
|
+
| 4 | 한 번의 실행이 여러 행을 바꾸거나 없애는가? | **지원 대상** |
|
|
24
|
+
| 5 | 지원 대상인데 이벤트에 이전 상태가 없는가? | 이벤트를 먼저 고치고, 그 뒤에 지원한다 |
|
|
25
|
+
|
|
26
|
+
각 질문의 뜻은 다음과 같다.
|
|
27
|
+
|
|
28
|
+
1. **비밀·권한·외부 효과.** 비밀번호, 역할, 위임 발급·회수, 계정 삭제, 메일 발송 같은 것이다.
|
|
29
|
+
되돌리기가 보안 결정을 뒤집거나, 이미 밖으로 나간 것을 되돌린 척하게 된다.
|
|
30
|
+
2. **기록.** 결정·승인·제안처럼 "그때 그렇게 했다"는 사실 자체가 의미인 것이다.
|
|
31
|
+
지우지 않고 새 기록으로 덮는다.
|
|
32
|
+
3. **다시 실행하면 되는 것.** 이름 변경, 활성 전환, 순서 변경, 설정값 변경처럼 값 하나를 바꾸는 것이다.
|
|
33
|
+
미지원 사유에 "같은 커맨드로 이전 값을 넣으세요"라고 안내하면 충분하다.
|
|
34
|
+
4. **여러 행이 함께 바뀌는 것.** 삭제, 병합, 일괄 변경, 하위 항목까지 딸려 가는 이동이다.
|
|
35
|
+
손으로 되돌리려면 무엇이 어떻게 바뀌었는지 기억해야 하는 작업이다.
|
|
36
|
+
5. **이전 상태가 없는 이벤트.** 되돌리기의 품질은 원본 이벤트가 담은 정보가 결정한다.
|
|
37
|
+
정보가 부족한 채로 열면 "복원"이 아니라 "비슷하게 다시 만들기"가 된다.
|
|
38
|
+
|
|
39
|
+
## 우선순위
|
|
40
|
+
|
|
41
|
+
지원 대상이 여럿이면 이 순서로 연다.
|
|
42
|
+
|
|
43
|
+
- **실수했을 때 피해가 큰 것 먼저.** 데이터가 사라지는 것, 구조가 바뀌는 것, 값이 바뀌는 것 순이다.
|
|
44
|
+
- **에이전트가 실행할 수 있는 것 먼저.** 위임 범위에 들어가는 커맨드는 실수 가능성이 높고, 되돌리기가 안전망이 된다.
|
|
45
|
+
- **자주 쓰는 것 먼저.** 드물게 쓰는 커맨드는 뒤로 미룬다.
|
|
46
|
+
|
|
47
|
+
## 열기 전에 갖출 것
|
|
48
|
+
|
|
49
|
+
지원으로 바꾸는 이벤트마다 아래를 모두 확인한다. 하나라도 안 되면 아직 열 때가 아니다.
|
|
50
|
+
|
|
51
|
+
- 원본 이벤트에 원상복구에 필요한 값이 모두 들어 있다.
|
|
52
|
+
- 보상 커맨드가 "가장 최근 것"이 아니라 정확한 건을 가리키는 식별자를 받는다.
|
|
53
|
+
- 되돌리면 잃는 것(그 사이에 생긴 변경 등)을 `losses`로 말할 수 있다.
|
|
54
|
+
- 되돌릴 수 없는 조건(부모가 사라짐, 이름 충돌, 이미 직접 복원됨)을 `blockers`로 말할 수 있다.
|
|
55
|
+
- 한 번의 커맨드 실행이 쓰는 모든 이벤트 타입이 같은 핸들러를 가리킨다
|
|
56
|
+
(다르면 커널이 `undo.operation_mixed_policies`로 막는다).
|
|
57
|
+
|
|
58
|
+
## 열지 않는 편이 나은 신호
|
|
59
|
+
|
|
60
|
+
- **되돌리기의 되돌리기가 필요해 보인다.** 복원을 다시 되돌리는 것은 "다시 삭제"와 같다. 일반 커맨드로 충분하다.
|
|
61
|
+
- **핸들러가 보상 커맨드보다 복잡해진다.** 계획을 세우는 코드가 실제 복원 코드보다 길면 모델이 그 도메인과 맞지 않는 것이다.
|
|
62
|
+
- **미리보기의 `changes`가 "전부 다시 만든다" 한 줄뿐이다.** 사용자가 판단할 정보가 없으므로 재실행 안내가 맞다.
|
|
63
|
+
|
|
64
|
+
## 도메인이 할 일
|
|
65
|
+
|
|
66
|
+
지원하는 이벤트마다 다음을 한다.
|
|
67
|
+
|
|
68
|
+
- **핸들러는 보상 커맨드를 정적으로 선언한다**(`compensationCommand`). 계획의 `command`는 선언과 같아야 한다.
|
|
69
|
+
- **핸들러는 세 가지만 답한다.** 무엇이 바뀌는가(`changes`), 무엇을 잃는가(`losses`), 왜 안 되는가(`blockers`).
|
|
70
|
+
- **`changes`의 `field`에는 필드 이름만 쓴다.** 안내 문장을 넣지 않는다. 원상복구가 아닌 부분은 `losses`로 알린다.
|
|
71
|
+
- **화면에 보일 값이 아니라 계획이 의존하는 상태는 `dependsOn`에 토큰으로 넣는다.**
|
|
72
|
+
투영기나 커맨드의 계산을 핸들러에서 다시 구현하지 않는다.
|
|
73
|
+
- **직접 복원된 건을 핸들러가 막는다.** 보상 커맨드를 직접 호출한 이력은 커널이 모른다.
|
|
74
|
+
커널의 보상 1회 가드는 undo 경로로 실행된 것만 안다.
|
|
75
|
+
- **원본 읽기 규칙은 장부 조회와 판정 함수 하나를 공유한다.** 장부에서 보이는 기록이면 되돌리기 정보도 보인다.
|
|
76
|
+
`registerUndoReadGate`로 한 번 등록한다.
|
|
77
|
+
- **보상 커맨드를 조립에서 제거하지 않는다.** 제거하면 그 커맨드로 수행된 과거 되돌리기의 재전송이
|
|
78
|
+
본인에게도 거절된다.
|
|
79
|
+
|
|
80
|
+
미지원으로 두는 이벤트는 사유를 구체적으로 적는다. "지원하지 않습니다" 대신
|
|
81
|
+
"이름은 같은 커맨드로 다시 바꾸세요"처럼 다음 행동을 알려 준다. 에이전트가 이 문장을 읽고 움직인다.
|
|
82
|
+
|
|
83
|
+
## 서피스가 할 일
|
|
84
|
+
|
|
85
|
+
- **되돌릴 수 있는지를 화면이 추측하지 않는다.** 이벤트 목록을 훑어 "이미 되돌렸는지"를 계산하는 코드를 두지 않고 커널에 묻는다.
|
|
86
|
+
- **흐름은 세 단계로 고정한다.** 상태 조회로 버튼을 정하고, 미리보기로 확인 창을 채우고, 미리보기의 `planHash`로 실행한다.
|
|
87
|
+
- **확인 창은 하나로 만든다.** 미리보기 형식이 모든 이벤트에 공통이므로 이벤트 타입별 전용 창을 만들지 않는다.
|
|
88
|
+
- **버튼이 보여도 미리보기에서 막힐 수 있다.** 상태 조회는 도메인 차단 조건을 계산하지 않는다.
|
|
89
|
+
`blocked`·`unavailable`·`denied`·`already_undone`의 사유를 보여 주는 화면이 반드시 있어야 한다.
|
|
90
|
+
- **`undo.plan_changed`를 받으면 미리보기를 다시 불러 확인을 다시 받는다.**
|
|
91
|
+
- **손실이 있으면(`warning`) 사용자가 확인한 뒤에만 `acceptLosses: true`를 보낸다.**
|
|
92
|
+
- **상태 조회는 한 번에 100건까지다.** 넘기면 입력 거절이 되므로 나눠서 조회한다.
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sudoke/kernel",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.2",
|
|
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"
|
package/src/catalog.ts
CHANGED
|
@@ -31,7 +31,7 @@ const revisionOf = (v: unknown) => 'r1:' + createHash('sha256').update(canonical
|
|
|
31
31
|
/** The kernel protocol format version — the shape of catalog·common request/response·undo contracts
|
|
32
32
|
* this kernel speaks. Managed by kernel semver releases, independent of the npm package version and of
|
|
33
33
|
* any app's catalogVersion. */
|
|
34
|
-
export const PROTOCOL_VERSION = '1.
|
|
34
|
+
export const PROTOCOL_VERSION = '1.1.0'
|
|
35
35
|
|
|
36
36
|
/** The full contract content of one command — hashed into its revision and embeddable into release
|
|
37
37
|
* manifests (the validator's structural breaking detection diffs these trees). Shared error-code
|
|
@@ -113,16 +113,23 @@ export function computeCatalogRevisions(): CatalogRevisions {
|
|
|
113
113
|
return { catalog, commands, queries }
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
-
/** The published form of an undo policy — supported entries carry the HANDLER's version
|
|
117
|
-
* contract (what it plans, how it judges conflicts) is
|
|
118
|
-
* the
|
|
119
|
-
*
|
|
120
|
-
*
|
|
116
|
+
/** The published form of an undo policy — supported entries carry the HANDLER's version and the
|
|
117
|
+
* DECLARED compensation command: the handler contract (what it plans, how it judges conflicts) is
|
|
118
|
+
* part of the undo surface, so its version and declaration move the catalog revision and show in the
|
|
119
|
+
* catalog document. (Event-scoped policies cannot be folded into per-command revisions statically —
|
|
120
|
+
* which command compensates for an event is a plan-time decision. catalogRevision·catalogStatus is
|
|
121
|
+
* the discovery surface for policy and handler changes.) */
|
|
121
122
|
export function publishedUndoPolicy(p: import('./types.js').EventUndoPolicy) {
|
|
122
123
|
// the mayRead hook is enforcement, not published contract (functions never serialize); `roles` IS
|
|
123
124
|
// published — it scopes this entry's catalog exposure and moves the catalog revision when it changes
|
|
124
125
|
return p.kind === 'supported'
|
|
125
|
-
? {
|
|
126
|
+
? {
|
|
127
|
+
kind: p.kind,
|
|
128
|
+
handlerId: p.handlerId,
|
|
129
|
+
handlerVersion: undoHandlerOf(p.handlerId)?.version ?? null,
|
|
130
|
+
compensationCommand: undoHandlerOf(p.handlerId)?.compensationCommand ?? null,
|
|
131
|
+
...(p.roles ? { roles: [...p.roles] } : {}),
|
|
132
|
+
}
|
|
126
133
|
: { kind: p.kind, code: p.code, reason: p.reason, ...(p.roles ? { roles: [...p.roles] } : {}) }
|
|
127
134
|
}
|
|
128
135
|
|
package/src/index.ts
CHANGED
|
@@ -19,12 +19,13 @@ export { registerAppProtocol, protocolPreamble, PROTOCOL_BATCH, PROTOCOL_DELEGAT
|
|
|
19
19
|
export { registerQuery, lookupQuery, allQueries, contractViolations, executeQuery, describeShape, queryAccessOf } from './queries.js'
|
|
20
20
|
export type { QueryDefinition, QueryOutcome, QueryRefusal } from './queries.js'
|
|
21
21
|
export { registerRoles, registerCommand, lookupCommand, allCommands, inputShapeOf, catalogMeta, registerTransitionMachine, transitionRulesOf, allTransitionMachines, registerEventContracts, eventContractOf, allEventContractTypes, registerErrorCodes, errorCodeOf, allErrorCodes, catalogConsistencyErrors, completeAssembly, sealRegistries } from './registry.js'
|
|
22
|
-
export { registerUndoHandler, registerUndoPolicies, undoPolicyOf, undoHandlerOf, allUndoPolicies, registerEventVersions, eventVersionOf, allEventVersions, registerCatalogRelease } from './registry.js'
|
|
22
|
+
export { registerUndoHandler, registerUndoPolicies, registerUndoReadGate, undoPolicyOf, undoHandlerOf, undoReadGateOf, allUndoPolicies, registerEventVersions, eventVersionOf, allEventVersions, registerCatalogRelease } from './registry.js'
|
|
23
23
|
export type { TransitionRule } from './registry.js'
|
|
24
24
|
export { buildCatalogDocument, catalogStatus, catalogChanges, catalogRevisionOf, commandRevisionOf, queryRevisionOf, viewRevisionOf, commandContractShape, queryContractShape, computeCatalogRevisions, responseMetaOf, PROTOCOL_VERSION } from './catalog.js'
|
|
25
25
|
export { validateReleaseManifest, structuralBreakingChanges } from './releases.js'
|
|
26
26
|
export type { CatalogReleaseManifest, ReleaseManifestContract } from './releases.js'
|
|
27
|
-
export { previewUndo, executeUndo, undoStatus } from './undo.js'
|
|
27
|
+
export { previewUndo, executeUndo, undoStatus, UNDO_STATUS_MAX_SEQS } from './undo.js'
|
|
28
|
+
export type { UndoStatusRow } from './undo.js'
|
|
28
29
|
export { roleAllowsCommand, delegationScopeEntries, commandAccessOf, visibleCatalogMeta, visibleQueriesFor, visibleTransitionMachinesFor } from './visibility.js'
|
|
29
30
|
export type { CommandAccess, CommandRestriction } from './visibility.js'
|
|
30
31
|
export { registriesSealed, resetKernelForTests } from './state.js'
|
package/src/mcp.ts
CHANGED
|
@@ -20,7 +20,7 @@ import { executeCommand } from './gate.js'
|
|
|
20
20
|
import { identityFromToken, unauthenticated } from './auth.js'
|
|
21
21
|
import { allQueries, executeQuery } from './queries.js'
|
|
22
22
|
import { buildCatalogDocument, catalogChanges, catalogStatus } from './catalog.js'
|
|
23
|
-
import { executeUndo, previewUndo, undoStatus } from './undo.js'
|
|
23
|
+
import { executeUndo, previewUndo, undoStatus, UNDO_STATUS_MAX_SEQS } from './undo.js'
|
|
24
24
|
import { allCommands, inputShapeOf } from './registry.js'
|
|
25
25
|
import { commandAccessOf, visibleQueriesFor } from './visibility.js'
|
|
26
26
|
|
|
@@ -230,7 +230,7 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
|
|
|
230
230
|
'undo_status',
|
|
231
231
|
{
|
|
232
232
|
description: 'Per-sequence undo support·processing state (exact ledger sequences — the status is a list view, not an execution guarantee)',
|
|
233
|
-
inputSchema: { sourceSeqs: z.array(z.number().int()).describe(
|
|
233
|
+
inputSchema: { sourceSeqs: z.array(z.number().int()).describe(`exact ledger sequences to check (at most ${UNDO_STATUS_MAX_SEQS} per call — a larger bundle is refused as an input error, never truncated)`) },
|
|
234
234
|
},
|
|
235
235
|
async (args: { sourceSeqs?: number[] }) => {
|
|
236
236
|
const live = await requireLive('undo_status')
|
|
@@ -242,7 +242,7 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
|
|
|
242
242
|
server.registerTool(
|
|
243
243
|
'undo_preview',
|
|
244
244
|
{
|
|
245
|
-
description: 'Preview the undo of the operation behind a ledger sequence — the compensation plan, conflicts, losses and the plan hash, judged for your current identity against current state',
|
|
245
|
+
description: 'Preview the undo of the operation behind a ledger sequence — the compensation plan, conflicts, losses and the plan hash, judged for your current identity against current state (status denied = a permission refusal carrying no operation facts)',
|
|
246
246
|
inputSchema: { sourceSeq: z.number().int().describe('any event sequence of the operation — the whole atomic operation is resolved') },
|
|
247
247
|
},
|
|
248
248
|
async (args: { sourceSeq?: number }) => {
|
package/src/registry.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GateError, type CommandDefinition, type ErrorCodeDefinition, type EventUndoPolicy, type UndoHandler, type CatalogRelease } from './types.js'
|
|
1
|
+
import { GateError, type CommandDefinition, type ErrorCodeDefinition, type EventUndoPolicy, type UndoHandler, type UndoMayRead, type CatalogRelease } from './types.js'
|
|
2
2
|
import type { ZodTypeAny } from 'zod'
|
|
3
3
|
import { describeShape } from './queries.js'
|
|
4
4
|
import { assertOpenFor, defaultKernelState, frozenCopyOf, sealFor } from './state.js'
|
|
@@ -178,18 +178,35 @@ export function registerUndoPolicies(policies: Record<string, EventUndoPolicy>):
|
|
|
178
178
|
}
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
-
/** Undo-handler registration — the domain's compensation planner.
|
|
182
|
-
* one
|
|
181
|
+
/** Undo-handler registration — the domain's compensation planner. `compensationCommand` names the
|
|
182
|
+
* one registered command the handler plans with (existence is resolved at the seal — registration
|
|
183
|
+
* order is free). plan() is read-only and runs inside one consistent read snapshot (preview) or
|
|
184
|
+
* inside the execution transaction (execute). */
|
|
183
185
|
export function registerUndoHandler(handler: UndoHandler): void {
|
|
184
186
|
assertOpenFor(defaultKernelState, `registerUndoHandler ${handler.id}`)
|
|
185
187
|
if (!handler.id?.trim() || !handler.version?.trim() || typeof handler.plan !== 'function')
|
|
186
188
|
throw new Error('An undo handler needs id, version and a plan function')
|
|
189
|
+
if (!handler.compensationCommand?.trim())
|
|
190
|
+
throw new Error(`An undo handler needs compensationCommand — the registered command it plans with: ${handler.id}`)
|
|
187
191
|
if (defaultKernelState.undoHandlers.has(handler.id)) throw new Error(`Undo handler registered twice: ${handler.id}`)
|
|
188
192
|
defaultKernelState.undoHandlers.set(handler.id, frozenCopyOf({ ...handler }) as UndoHandler)
|
|
189
193
|
}
|
|
190
194
|
|
|
195
|
+
/** The app-wide default origin-read gate — one registration serves every undo policy that declares
|
|
196
|
+
* no mayRead of its own (a policy-level hook wins where present). Undo answers never read without a
|
|
197
|
+
* decision: policies without mayRead AND no default gate fail the boot. The kernel does not interpret
|
|
198
|
+
* read scopes — the gate is the app's business judgment. */
|
|
199
|
+
export function registerUndoReadGate(gate: UndoMayRead): void {
|
|
200
|
+
assertOpenFor(defaultKernelState, 'registerUndoReadGate')
|
|
201
|
+
if (defaultKernelState.undoReadGate) throw new Error('The default undo read gate is registered twice — one gate per assembly')
|
|
202
|
+
if (typeof gate !== 'function') throw new Error('The default undo read gate must be a function')
|
|
203
|
+
defaultKernelState.undoReadGate = gate
|
|
204
|
+
}
|
|
205
|
+
|
|
191
206
|
export const undoPolicyOf = (type: string): EventUndoPolicy | undefined => defaultKernelState.undoPolicies.get(type)
|
|
192
207
|
export const undoHandlerOf = (id: string): UndoHandler | undefined => defaultKernelState.undoHandlers.get(id)
|
|
208
|
+
/** The registered default origin-read gate, when one exists — policies without their own mayRead fall back to it */
|
|
209
|
+
export const undoReadGateOf = (): UndoMayRead | undefined => defaultKernelState.undoReadGate ?? undefined
|
|
193
210
|
/** All registered undo policies — a fresh record, published by the catalog document */
|
|
194
211
|
export const allUndoPolicies = (): Record<string, EventUndoPolicy> => Object.fromEntries([...defaultKernelState.undoPolicies.entries()])
|
|
195
212
|
|
|
@@ -208,9 +225,6 @@ export const eventVersionOf = (type: string): number | undefined => defaultKerne
|
|
|
208
225
|
/** All registered event versions — a fresh record (catalog fingerprint input) */
|
|
209
226
|
export const allEventVersions = (): Record<string, number> => Object.fromEntries([...defaultKernelState.eventVersions.entries()])
|
|
210
227
|
|
|
211
|
-
/** Kernel assembly options — compat (default) keeps the historical contract; strict additionally
|
|
212
|
-
* demands undo coverage, declared versions, the operation-ledger capability and per-write contracts.
|
|
213
|
-
* Sealed with the registries — configuring after the seal is a defect. */
|
|
214
228
|
/** Registers the served catalog release declaration — the app-declared compatibility version plus the
|
|
215
229
|
* change list of this release (what catalogChanges serves and the release validator checks). */
|
|
216
230
|
export function registerCatalogRelease(release: CatalogRelease): void {
|
|
@@ -305,18 +319,21 @@ export function catalogConsistencyErrors(): string[] {
|
|
|
305
319
|
const badQueryVersions = [...s.queries.values()].filter((q) => q.version !== undefined && !SEMVER_RE.test(q.version)).map((q) => q.name)
|
|
306
320
|
if (badQueryVersions.length > 0)
|
|
307
321
|
errors.push(`valid semver query versions are required: [${badQueryVersions.join(', ')}]`)
|
|
308
|
-
// (the release catalogVersion is semver-checked at registration time
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
)
|
|
322
|
+
// (the release catalogVersion is semver-checked at registration time — no duplicate check here)
|
|
323
|
+
// the DECLARED compensation command must exist — the kernel checks plan-entry rights against it
|
|
324
|
+
// before the planner runs, so a dangling declaration would break every preview of this handler
|
|
325
|
+
const unregisteredCompensations = [...s.undoHandlers.values()]
|
|
326
|
+
.filter((h) => !s.commands.has(h.compensationCommand))
|
|
327
|
+
.map((h) => `${h.id} → '${h.compensationCommand}'`)
|
|
328
|
+
if (unregisteredCompensations.length > 0)
|
|
329
|
+
errors.push(`an undo handler's compensationCommand must be a registered command — dangling: [${unregisteredCompensations.join(', ')}]`)
|
|
314
330
|
// the OPERATION-level read gate is a declared decision too — unavailable and mixed branches answer
|
|
315
|
-
// operation facts, so every policy (not only supported handlers) must state who may read them
|
|
331
|
+
// operation facts, so every policy (not only supported handlers) must state who may read them:
|
|
332
|
+
// its own mayRead hook, or the app-wide default gate registered once (registerUndoReadGate)
|
|
316
333
|
const readless = [...s.undoPolicies.entries()].filter(([, p]) => typeof p.mayRead !== 'function').map(([t]) => t)
|
|
317
|
-
if (readless.length > 0)
|
|
334
|
+
if (readless.length > 0 && !s.undoReadGate)
|
|
318
335
|
errors.push(
|
|
319
|
-
`a mayRead hook
|
|
336
|
+
`every undo policy needs a mayRead hook (or the app-wide default gate — registerUndoReadGate) — origin-read rights are a declared decision, never a default allow — missing: [${readless.join(', ')}]`,
|
|
320
337
|
)
|
|
321
338
|
if (!s.storage?.operationLedger)
|
|
322
339
|
errors.push('the registered storage engine does not provide the operation-ledger capability — the kernel requires it')
|
package/src/state.ts
CHANGED
|
@@ -23,7 +23,7 @@ import type { ProjectionHandler } from './projections.js'
|
|
|
23
23
|
import type { QueryDefinition } from './queries.js'
|
|
24
24
|
import type { TransitionRule } from './registry.js'
|
|
25
25
|
import type { StoragePort } from './storage.js'
|
|
26
|
-
import type { CommandDefinition, ErrorCodeDefinition, EventUndoPolicy, CatalogRelease, CatalogRevisions, UndoHandler } from './types.js'
|
|
26
|
+
import type { CommandDefinition, ErrorCodeDefinition, EventUndoPolicy, CatalogRelease, CatalogRevisions, UndoHandler, UndoMayRead } from './types.js'
|
|
27
27
|
|
|
28
28
|
/** Registered projector — the app contract (AppProjector) collected into handler maps */
|
|
29
29
|
export interface RegisteredProjector {
|
|
@@ -48,6 +48,9 @@ export interface KernelState {
|
|
|
48
48
|
undoPolicies: Map<string, EventUndoPolicy>
|
|
49
49
|
/** Undo handlers by id (registerUndoHandler) — domain-owned compensation planners */
|
|
50
50
|
undoHandlers: Map<string, UndoHandler>
|
|
51
|
+
/** The app-wide default origin-read gate (registerUndoReadGate) — serves any undo policy that
|
|
52
|
+
* declares no mayRead of its own; null until registered (one per assembly) */
|
|
53
|
+
undoReadGate: UndoMayRead | null
|
|
51
54
|
/** Event payload format versions per type (registerEventVersions) — absent = 1 */
|
|
52
55
|
eventVersions: Map<string, number>
|
|
53
56
|
/** The served catalog release declaration (registerCatalogRelease) — null when the app declares none */
|
|
@@ -134,6 +137,7 @@ export function freshKernelState(): KernelState {
|
|
|
134
137
|
sealed: false,
|
|
135
138
|
undoPolicies: new Map(),
|
|
136
139
|
undoHandlers: new Map(),
|
|
140
|
+
undoReadGate: null,
|
|
137
141
|
eventVersions: new Map(),
|
|
138
142
|
catalogRelease: null,
|
|
139
143
|
revisions: null,
|
package/src/storage.ts
CHANGED
|
@@ -128,11 +128,12 @@ export interface StoragePort {
|
|
|
128
128
|
/** Release the physical connection (optional) — file removal, e.g. test cleanup, requires it on platforms that lock open files */
|
|
129
129
|
close?(): void
|
|
130
130
|
|
|
131
|
-
/** Operation-ledger extension
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
131
|
+
/** Operation-ledger extension — REQUIRED by the kernel's assembly check: an engine without it
|
|
132
|
+
* fails the boot (undo is part of the kernel contract). Engines that implement it persist the
|
|
133
|
+
* kernel's event envelope (EventOperationMeta) beside the payload and serve the exact lookups the
|
|
134
|
+
* undo contract needs. The field stays optional on the PORT (registerStorage accepts engines in
|
|
135
|
+
* earlier build stages; the seal is where completeness is demanded). Write methods here join the
|
|
136
|
+
* same serialized write lane as every other writer.
|
|
136
137
|
*
|
|
137
138
|
* Implementation requirements for engine authors (SQLite shape; other engines equivalently):
|
|
138
139
|
* - a nullable metadata column beside the payload (JSON of EventOperationMeta) — legacy rows stay NULL
|
package/src/types.ts
CHANGED
|
@@ -83,8 +83,8 @@ export interface CommandDefinition<I = any, O = any> {
|
|
|
83
83
|
* result is checked against the output contract */
|
|
84
84
|
execute: (input: I, identity: Identity) => Promise<{ events: DomainEvent[]; result: O }>
|
|
85
85
|
/** Command contract version (semver) — the domain declares it for the whole contract
|
|
86
|
-
* (input·output·refusal·permission·transition semantics). Required
|
|
87
|
-
* publishes it and
|
|
86
|
+
* (input·output·refusal·permission·transition semantics). Required on every command (the seal
|
|
87
|
+
* refuses an undeclared version); the catalog publishes it and every write carries it back (ContractMeta) */
|
|
88
88
|
version?: string
|
|
89
89
|
/** Explicit revision for meaning changes no fingerprint can derive (functional refine bodies,
|
|
90
90
|
* business-logic semantics). Bumped by the domain; folded into the command revision */
|
|
@@ -115,7 +115,7 @@ export interface EventOperationMeta {
|
|
|
115
115
|
policyTarget?: string
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
-
/** The contract identity
|
|
118
|
+
/** The contract identity every write carries beside the business input — the caller's view of
|
|
119
119
|
* the command contract. Refused before execution when it no longer matches (gate.contract_changed /
|
|
120
120
|
* gate.contract_required). Riding splitProtocolOptions, it never reaches the business schema. */
|
|
121
121
|
export interface ContractMeta {
|
|
@@ -132,10 +132,12 @@ export interface ContractMeta {
|
|
|
132
132
|
export type UndoMayRead = (source: SourceOperation, identity: Identity) => Promise<void>
|
|
133
133
|
|
|
134
134
|
/** Undo policy per event type — supported (a handler plans the compensation) or explicitly unavailable
|
|
135
|
-
* (a stable code + a concrete reason). Both kinds are declared;
|
|
136
|
-
* registered event type AND
|
|
137
|
-
*
|
|
138
|
-
*
|
|
135
|
+
* (a stable code + a concrete reason). Both kinds are declared; the kernel requires a policy for every
|
|
136
|
+
* registered event type AND an origin-read decision for every policy — a `mayRead` hook on the policy
|
|
137
|
+
* itself, or the app-wide default gate registered once (registerUndoReadGate); a policy-level mayRead
|
|
138
|
+
* wins where present, and an assembly declaring neither fails the boot — origin-read rights are never
|
|
139
|
+
* a default allow. `roles` limits the policy's CATALOG exposure (absent = every authenticated
|
|
140
|
+
* identity sees the policy entry; it never affects the mayRead verdict).
|
|
139
141
|
* Audit rows are never undo targets. */
|
|
140
142
|
export type EventUndoPolicy =
|
|
141
143
|
| { kind: 'supported'; handlerId: string; mayRead?: UndoMayRead; roles?: readonly Role[] }
|
|
@@ -195,21 +197,31 @@ export interface UndoPlan {
|
|
|
195
197
|
blockers?: UndoPlanBlocker[]
|
|
196
198
|
}
|
|
197
199
|
|
|
198
|
-
/** Undo handler — owned by the domain.
|
|
199
|
-
*
|
|
200
|
+
/** Undo handler — owned by the domain. `compensationCommand` statically declares the ONE registered
|
|
201
|
+
* command this handler plans with: the kernel checks the current identity's access to it BEFORE the
|
|
202
|
+
* planner runs (an unauthorized identity never triggers plan computation — and never learns the
|
|
203
|
+
* blockers a plan would have named), the seal refuses a handler whose declared command is not
|
|
204
|
+
* registered, and a plan naming any other command is a defect (undo.plan_invalid). plan() is
|
|
205
|
+
* read-only (no business writes, no ledger appends, no idempotency storage, no external effects) and
|
|
206
|
+
* runs inside one consistent read snapshot. */
|
|
200
207
|
export interface UndoHandler {
|
|
201
208
|
id: string
|
|
202
209
|
version: string
|
|
210
|
+
compensationCommand: string
|
|
203
211
|
plan: (source: SourceOperation, identity: Identity) => Promise<UndoPlan>
|
|
204
|
-
/** Optional per-source read
|
|
205
|
-
*
|
|
212
|
+
/** Optional per-source read refinement — runs AFTER the kernel's compensation-command access
|
|
213
|
+
* check, still before any state judgment (an identity without history rights learns nothing, not
|
|
214
|
+
* even whether a compensation exists). Throw GateError (stage 1~3) to refuse. */
|
|
206
215
|
mayPreview?: (source: SourceOperation, identity: Identity) => Promise<void>
|
|
207
216
|
}
|
|
208
217
|
|
|
209
218
|
/** Preview of one undo, judged for the current user against the current state — static "a handler
|
|
210
|
-
* exists" and "this call can run now" are different questions (status answers the latter).
|
|
219
|
+
* exists" and "this call can run now" are different questions (status answers the latter).
|
|
220
|
+
* `denied` is the permission verdict (origin-read hook, handler gate, compensation-command role·
|
|
221
|
+
* delegation): like every permission refusal it carries no operation facts — no operationId, no
|
|
222
|
+
* processing state. */
|
|
211
223
|
export interface UndoPreview {
|
|
212
|
-
status: 'available' | 'warning' | 'blocked' | 'unavailable' | 'already_undone'
|
|
224
|
+
status: 'available' | 'warning' | 'blocked' | 'unavailable' | 'already_undone' | 'denied'
|
|
213
225
|
sourceSeq: number
|
|
214
226
|
operationId?: string
|
|
215
227
|
handlerId?: string
|