sisyo 1.9.0 → 1.12.0

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.
@@ -0,0 +1,1504 @@
1
+ #!/usr/bin/env node
2
+ // kdev: the Kicho devflow helper (skill kicho-devflow). Talks to Kicho's MCP endpoint over HTTP with the machine's
3
+ // personal token and prints only short results (ids, links, compact text), so screenshots, logs and long pages never
4
+ // pass through the agent's context. Node 18+, no dependencies. `node kdev.mjs help` lists the commands.
5
+ import { execFileSync } from 'node:child_process'
6
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
7
+ import { homedir } from 'node:os'
8
+ import { createHash } from 'node:crypto'
9
+ import path from 'node:path'
10
+
11
+ const BASE = (process.env.KICHO_URL || 'https://kicho.hoang.jp').replace(/\/$/, '')
12
+ const CONFIG = '.kicho-devflow.json'
13
+ const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
14
+
15
+ // Request status → page icon (the icon shows the status in the page tree) and the label on the "Trạng thái" line.
16
+ const REQ_STATUS = {
17
+ review: ['🟡', 'Chờ anh duyệt'],
18
+ approved: ['🟢', 'Đã duyệt, chờ triển khai'],
19
+ doing: ['🔨', 'Đang triển khai'],
20
+ testing: ['🧪', 'Đang kiểm thử'],
21
+ released: ['✅', 'Đã phát hành'],
22
+ paused: ['⏸️', 'Tạm dừng'],
23
+ cancelled: ['✖️', 'Đã huỷ'],
24
+ }
25
+ const OPEN_ICONS = new Set(['🟡', '🟢', '🔨', '🧪', '⏸️'])
26
+
27
+ // Layout (owner, 2026-11-25): <Company> / 📘 Quy trình làm việc (one process for every project) and
28
+ // <Company> / Projects / <Project> = the hub (overview, current sprint, open requests, task board) with the pages
29
+ // below as its children (created by `init`, found again by title). No "Develop" level any more.
30
+ const HANDBOOK_PAGE = ['📘', 'Quy trình làm việc']
31
+ const HUB_PAGES = {
32
+ requests: ['📥', 'Yêu cầu'],
33
+ brainstorm: ['🧠', 'Brainstorm'],
34
+ }
35
+ const TASKS_DB = ['✅', 'Việc của agent']
36
+ const RELEASES_DB = ['🚀', 'Phát hành']
37
+
38
+ const TASK_STATUS = [
39
+ { name: 'Chờ duyệt', color: 'yellow', group: 'todo' },
40
+ { name: 'Sẵn sàng', color: 'blue', group: 'todo' },
41
+ { name: 'Hoãn', color: 'grey', group: 'todo' },
42
+ { name: 'Đang làm', color: 'orange', group: 'in_progress' },
43
+ { name: 'Kiểm thử', color: 'purple', group: 'in_progress' },
44
+ { name: 'Xong', color: 'green', group: 'complete' },
45
+ { name: 'Bỏ', color: 'red', group: 'complete' },
46
+ ]
47
+
48
+ function die(msg) {
49
+ process.stderr.write(`kdev: ${msg}\n`)
50
+ process.exit(1)
51
+ }
52
+
53
+ function token() {
54
+ if (process.env.KICHO_TOKEN) return process.env.KICHO_TOKEN.trim()
55
+ const f = path.join(homedir(), '.config', 'kicho', 'token')
56
+ if (existsSync(f)) return readFileSync(f, 'utf8').trim()
57
+ const cj = path.join(homedir(), '.claude.json')
58
+ if (existsSync(cj)) {
59
+ const h = JSON.parse(readFileSync(cj, 'utf8'))?.mcpServers?.kicho?.headers?.Authorization
60
+ if (h) return String(h).replace(/^Bearer\s+/i, '')
61
+ }
62
+ die('no Kicho token: set KICHO_TOKEN or ~/.config/kicho/token, or add the kicho MCP server with a Bearer header (skill kicho)')
63
+ }
64
+
65
+ let rpcId = 0
66
+ async function rpc(method, params) {
67
+ const res = await fetch(`${BASE}/api/mcp`, {
68
+ method: 'POST',
69
+ headers: {
70
+ 'Content-Type': 'application/json',
71
+ Accept: 'application/json, text/event-stream',
72
+ Authorization: `Bearer ${token()}`,
73
+ // Cloudflare refuses some default client signatures (error 1010): always send our own.
74
+ 'User-Agent': 'kicho-devflow/1.0',
75
+ },
76
+ body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method, params }),
77
+ })
78
+ if (res.status === 401) die('401 from Kicho: the token is invalid or expired (skill kicho → Connect a machine)')
79
+ if (!res.ok) die(`HTTP ${res.status} from Kicho: ${(await res.text()).slice(0, 200)}`)
80
+ const r = await res.json()
81
+ if (r.error) die(`MCP error: ${JSON.stringify(r.error).slice(0, 300)}`)
82
+ return r.result
83
+ }
84
+
85
+ async function call(name, args, { soft = false } = {}) {
86
+ const r = await rpc('tools/call', { name, arguments: args })
87
+ const text = (r.content ?? []).map((c) => c.text ?? '').join('\n')
88
+ if (r.isError) {
89
+ if (soft) return null
90
+ die(`${name}: ${text.slice(0, 600)}`)
91
+ }
92
+ return text
93
+ }
94
+
95
+ // The server's tool names, cached for a day per server (tools/list is ~100 KB): a missing name refreshes once.
96
+ /** A tool call with `output: "json"` (REQ-004 B1): the parsed object, or null on a server without JSON output
97
+ * (the caller then falls back to reading the text). */
98
+ async function callJson(name, args, opts = {}) {
99
+ const text = await call(name, { ...args, output: 'json' }, opts)
100
+ if (text === null) return null
101
+ try {
102
+ return JSON.parse(text)
103
+ } catch {
104
+ return null
105
+ }
106
+ }
107
+
108
+ let toolNames = null
109
+ const toolCache = () => path.join(homedir(), '.cache', 'kdev', `tools-${BASE.replace(/[^a-z0-9]+/gi, '_')}.json`)
110
+ async function fetchTools() {
111
+ const names = ((await rpc('tools/list', {})).tools ?? []).map((t) => t.name)
112
+ try {
113
+ mkdirSync(path.dirname(toolCache()), { recursive: true })
114
+ writeFileSync(toolCache(), JSON.stringify({ at: Date.now(), names }))
115
+ } catch {}
116
+ return new Set(names)
117
+ }
118
+ async function hasTool(name) {
119
+ if (!toolNames) {
120
+ try {
121
+ const c = JSON.parse(readFileSync(toolCache(), 'utf8'))
122
+ if (Date.now() - c.at < 86_400_000) toolNames = new Set(c.names)
123
+ } catch {}
124
+ }
125
+ toolNames ??= await fetchTools()
126
+ if (!toolNames.has(name)) toolNames = await fetchTools()
127
+ return toolNames.has(name)
128
+ }
129
+
130
+ // ---------- args, config ----------
131
+
132
+ /** An option given once or several times (--field a=1 --field b=2) as a list. */
133
+ const many = (v) => (v === undefined || v === false ? [] : Array.isArray(v) ? v : [v])
134
+
135
+ function parseArgs(argv) {
136
+ const pos = []
137
+ const opt = {}
138
+ for (let i = 0; i < argv.length; i++) {
139
+ const a = argv[i]
140
+ if (a.startsWith('--')) {
141
+ const k = a.slice(2)
142
+ const next = argv[i + 1]
143
+ const v = next === undefined || next.startsWith('--') ? true : argv[++i]
144
+ opt[k] = k in opt ? [...many(opt[k]), v] : v
145
+ } else pos.push(a)
146
+ }
147
+ return { pos, opt }
148
+ }
149
+
150
+ function findConfig(dir = process.cwd()) {
151
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
152
+ const f = path.join(d, CONFIG)
153
+ if (existsSync(f)) return f
154
+ if (path.dirname(d) === d) return null
155
+ }
156
+ }
157
+
158
+ function loadConfig() {
159
+ const f = findConfig()
160
+ if (!f) die(`no ${CONFIG} in this folder or above: run \`kdev init <project page id>\` in the project root`)
161
+ return { file: f, ...JSON.parse(readFileSync(f, 'utf8')) }
162
+ }
163
+
164
+ const url = (id) => `${BASE}/p/${id}`
165
+ /** The local date (the owner's day, not UTC). */
166
+ const today = () => {
167
+ const d = new Date()
168
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
169
+ }
170
+ const nowLocal = () => {
171
+ const d = new Date()
172
+ const p = (n) => String(n).padStart(2, '0')
173
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
174
+ }
175
+
176
+ function readInput(arg) {
177
+ if (arg === '-') return readFileSync(0, 'utf8')
178
+ if (typeof arg === 'string' && arg.startsWith('@')) return readFileSync(arg.slice(1), 'utf8')
179
+ if (typeof arg === 'string' && existsSync(arg) && statSync(arg).isFile()) return readFileSync(arg, 'utf8')
180
+ return arg
181
+ }
182
+
183
+ // ---------- page helpers ----------
184
+
185
+ /** Children of a page: [{icon, title, id}] from list_pages. */
186
+ async function children(parentId) {
187
+ const j = await callJson('list_pages', { parent_id: parentId }, { soft: true })
188
+ if (j?.pages) return j.pages.map((p) => ({ icon: p.icon ?? '', title: p.title ?? '', id: p.id }))
189
+ const text = await call('list_pages', { parent_id: parentId })
190
+ const out = []
191
+ for (const line of text.split('\n')) {
192
+ const m = /^- (.*?) \| id: ([0-9a-f-]{36})/.exec(line.trim())
193
+ if (!m) continue
194
+ const label = m[1]
195
+ const sp = label.indexOf(' ')
196
+ const first = sp > 0 ? label.slice(0, sp) : ''
197
+ const isIcon = first && !/^[\p{L}\p{N}]/u.test(first)
198
+ out.push({ icon: isIcon ? first : '', title: isIcon ? label.slice(sp + 1) : label, id: m[2] })
199
+ }
200
+ return out
201
+ }
202
+
203
+ /** Body blocks of a page: [{id, type, attrs, text, depth}] from get_page format=blocks. */
204
+ async function blocks(pageId, maxChars = 60000) {
205
+ const text = await call('get_page', { page_id: pageId, max_chars: maxChars })
206
+ const out = []
207
+ for (const line of text.split('\n')) {
208
+ const m = /^(\s*)([A-Za-z0-9_-]{6,64}) \| ([A-Za-z]+)(\(([^)]*)\))? \| ?(.*)$/.exec(line)
209
+ if (m) out.push({ depth: m[1].length, id: m[2], type: m[3], attrs: m[5] ?? '', text: m[6] ?? '' })
210
+ }
211
+ return { raw: text, list: out }
212
+ }
213
+
214
+ async function ensurePage(parentId, icon, title, markdown) {
215
+ const found = (await children(parentId)).find((c) => c.title === title)
216
+ if (found) return found.id
217
+ const text = await call('create_page', { parent_id: parentId, title, icon, ...(markdown ? { markdown } : {}) })
218
+ return UUID.exec(/page_id ([0-9a-f-]{36})/.exec(text)?.[1] ?? '')?.[0] ?? die(`create_page: no id in ${text.slice(0, 200)}`)
219
+ }
220
+
221
+ /** A full-page database under parentId, found by title or created; returns {pageId, databaseId}. */
222
+ async function ensureDatabase(parentId, icon, title, setup) {
223
+ const found = (await children(parentId)).find((c) => c.title === title)
224
+ let pageId = found?.id
225
+ if (!pageId) {
226
+ const text = await call('create_database', { title, template: 'empty', inline: false, parent_id: parentId })
227
+ pageId = /page_id ([0-9a-f-]{36})/.exec(text)?.[1] ?? die(`create_database: no page_id in ${text.slice(0, 300)}`)
228
+ await call('update_page', { page_id: pageId, icon })
229
+ const info = await call('get_database', { database_id: pageId })
230
+ const dbId = /database_id[ :=]+([0-9a-f-]{36})/.exec(info)?.[1] ?? pageId
231
+ // the empty template brings a "Tags" column and a "Table" view: drop the column, name the view
232
+ if (/- Tags \(multi_select\)/.test(info)) await call('delete_property', { database_id: dbId, property: 'Tags' })
233
+ if (/"Table" view_id=/.test(info)) await call('update_view', { database_id: dbId, view: 'Table', name: 'Tất cả' })
234
+ await setup(dbId)
235
+ return { pageId, databaseId: dbId }
236
+ }
237
+ const info = await call('get_database', { database_id: pageId })
238
+ return { pageId, databaseId: /database_id[ :=]+([0-9a-f-]{36})/.exec(info)?.[1] ?? pageId }
239
+ }
240
+
241
+ /** Sprint rows, newest first: [{id, title, status}] (owner 2026-11-30: pages grouped by sprint, then R). */
242
+ async function sprintRows(cfg) {
243
+ if (!cfg.sprints_db) return []
244
+ const j = await callJson('query_database', { database_id: cfg.sprints_db, limit: 200, properties: ['Trạng thái'] }, { soft: true })
245
+ const num = (t) => Number(/\d+/.exec(t ?? '')?.[0] ?? 0)
246
+ return (j?.rows ?? []).map((r) => ({ id: r.id, title: r.title, status: r.values?.['Trạng thái'] ?? '' })).sort((a, b) => num(b.title) - num(a.title))
247
+ }
248
+
249
+ /** Every request page: the inbox (📥 Yêu cầu: new or written by the owner, not yet in a sprint) and each sprint page. */
250
+ let requestCache = null
251
+ async function allRequests(cfg) {
252
+ if (requestCache) return requestCache
253
+ const out = []
254
+ for (const c of await children(cfg.requests)) if (reqNumber(c.title)) out.push({ ...c, sprint: null, sprintId: null })
255
+ for (const r of await sprintRows(cfg)) for (const c of await children(r.id)) if (reqNumber(c.title)) out.push({ ...c, sprint: r.title, sprintId: r.id })
256
+ requestCache = out
257
+ return out
258
+ }
259
+ const reqCode = (title, num) => (/(?:^|· )REQ-/.test(title) ? `REQ-${String(num).padStart(3, '0')}` : `R${num}`)
260
+
261
+ async function findRequest(cfg, ref) {
262
+ if (UUID.test(ref)) return { id: UUID.exec(ref)[0] }
263
+ const num = Number(/(\d+)/.exec(ref)?.[1] ?? NaN)
264
+ if (!num) die(`not a request id: ${ref}`)
265
+ const hit = (await allRequests(cfg)).find((c) => reqNumber(c.title) === num)
266
+ return hit ? { ...hit, req: reqCode(hit.title, num) } : die(`request ${num} not found (inbox ${url(cfg.requests)} or the sprint pages)`)
267
+ }
268
+
269
+ // ---------- commands ----------
270
+
271
+ const HANDBOOK = path.join(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), 'templates', 'handbook.md')
272
+
273
+ /** The top-level page (the company, e.g. HoangLLC) whose tree holds pageId within `depth` levels, or null. */
274
+ async function companyOf(pageId, depth = 4) {
275
+ const top = (await callJson('list_pages', { parent_id: null }))?.pages ?? []
276
+ if (top.some((p) => p.id === pageId)) return pageId
277
+ for (const t of top) {
278
+ let level = [t]
279
+ for (let d = 0; d < depth && level.length; d++) {
280
+ const next = []
281
+ for (const p of level.filter((x) => x.hasChildren !== false)) {
282
+ const kids = (await callJson('list_pages', { parent_id: p.id }, { soft: true }))?.pages ?? []
283
+ if (kids.some((k) => k.id === pageId)) return t.id
284
+ next.push(...kids.filter((k) => k.hasChildren && k.kind !== 'database'))
285
+ }
286
+ level = next
287
+ }
288
+ }
289
+ return null
290
+ }
291
+
292
+ /** The company's 📘 Quy trình làm việc, shared by all its projects: --handbook, else the page with that title right
293
+ * under the company that holds the project page (created there from the template when missing). */
294
+ async function companyHandbook(hub, opt) {
295
+ const given = UUID.exec(opt.handbook ?? '')?.[0]
296
+ if (given) return given
297
+ const company = UUID.exec(opt.company ?? '')?.[0] ?? (await companyOf(hub))
298
+ if (!company || company === hub) die('cannot find the company above the project page: pass --company <company page id> or --handbook <page id>')
299
+ return ensurePage(company, ...HANDBOOK_PAGE, existsSync(HANDBOOK) ? readFileSync(HANDBOOK, 'utf8') : undefined)
300
+ }
301
+
302
+ async function cmdInit({ pos, opt }) {
303
+ const hub = UUID.exec(pos[0] ?? '')?.[0] ?? die('usage: kdev init <project page id or url> [--project Name] [--summary "one line"] [--handbook id | --company id]')
304
+ const project = opt.project || path.basename(process.cwd())
305
+ const ids = { project, hub }
306
+ ids.handbook = await companyHandbook(hub, opt)
307
+ ids.requests = await ensurePage(hub, ...HUB_PAGES.requests,
308
+ 'Hộp thư yêu cầu: trang anh tự viết (REQ-NNN / ghi chú) chờ agent nhận. Khi nhận, agent đưa nó vào trang sprint: `S5 · R6 · tóm tắt`. Icon là trạng thái: 🟡 chờ anh duyệt · 🟢 đã duyệt · 🔨 đang làm · 🧪 kiểm thử · ✅ đã phát hành · ⏸️ tạm dừng · ✖️ huỷ.')
309
+ ids.brainstorm = await ensurePage(hub, ...HUB_PAGES.brainstorm,
310
+ 'Ý tưởng bàn cùng AI, mỗi buổi một trang con. Ý tưởng nào chốt làm thì thành một yêu cầu (REQ) và ghi link ngược về đây.')
311
+ // the agents' task database only with --tasks (owner 2026-11-30: he follows requests and sprints, not task progress)
312
+ const tasks = opt.tasks ? await ensureDatabase(hub, ...TASKS_DB, async (db) => {
313
+ await call('add_property', { database_id: db, name: 'ID', type: 'unique_id', show_on_cards: true })
314
+ await call('add_property', { database_id: db, name: 'Trạng thái', type: 'status', options: TASK_STATUS, show_on_cards: false })
315
+ await call('add_property', { database_id: db, name: 'Yêu cầu', type: 'select', options: [], show_on_cards: true })
316
+ await call('add_property', { database_id: db, name: 'Hạng mục', type: 'select', options: [], show_on_cards: true })
317
+ await call('add_property', { database_id: db, name: 'Loại', type: 'select', show_on_cards: false,
318
+ options: [{ name: 'Tính năng', color: 'blue' }, { name: 'Cải tiến', color: 'green' }, { name: 'Sửa lỗi', color: 'red' }, { name: 'Hạ tầng', color: 'grey' }] })
319
+ await call('add_property', { database_id: db, name: 'Ưu tiên', type: 'select', show_on_cards: true,
320
+ options: [{ name: 'P0', color: 'red' }, { name: 'P1', color: 'orange' }, { name: 'P2', color: 'grey' }] })
321
+ await call('add_property', { database_id: db, name: 'Agent', type: 'select', options: [], show_on_cards: true })
322
+ await call('add_property', { database_id: db, name: 'Thời gian', type: 'date', show_on_cards: false })
323
+ await call('add_property', { database_id: db, name: 'Commit', type: 'text', show_on_cards: false })
324
+ await call('add_view', { database_id: db, type: 'board', name: 'Bảng', group_by: 'Trạng thái' })
325
+ await call('add_view', { database_id: db, type: 'timeline', name: 'Timeline', date_property: 'Thời gian' })
326
+ await call('add_view', { database_id: db, type: 'table', name: 'Chờ anh duyệt', filters: [{ property: 'Trạng thái', operator: 'is', value: 'Chờ duyệt' }] })
327
+ }) : null
328
+ if (tasks) {
329
+ ids.tasks_page = tasks.pageId
330
+ ids.tasks_db = tasks.databaseId
331
+ }
332
+ const rel = await ensureDatabase(hub, ...RELEASES_DB, async (db) => {
333
+ await call('add_property', { database_id: db, name: 'Ngày', type: 'date', show_on_cards: true })
334
+ await call('add_property', { database_id: db, name: 'Commit', type: 'text', show_on_cards: true })
335
+ await call('add_property', { database_id: db, name: 'Yêu cầu', type: 'multi_select', options: [], show_on_cards: true })
336
+ await call('add_property', { database_id: db, name: 'Kết quả', type: 'select', show_on_cards: true,
337
+ options: [{ name: 'Thành công', color: 'green' }, { name: 'Lỗi, đã rollback', color: 'red' }] })
338
+ await call('add_property', { database_id: db, name: 'Backup', type: 'text', show_on_cards: false })
339
+ })
340
+ ids.releases_page = rel.pageId
341
+ ids.releases_db = rel.databaseId
342
+ await writeHubBody(ids, opt.summary)
343
+ const file = path.join(process.cwd(), CONFIG)
344
+ writeFileSync(file, JSON.stringify(ids, null, 2) + '\n')
345
+ console.log(`hub ${url(hub)}\nconfig ${file}`)
346
+ for (const [k, v] of Object.entries(ids)) if (k !== 'project' && k !== 'hub') console.log(`${k} ${v}`)
347
+ }
348
+
349
+ /** The project page body (= the hub), written once while it is empty: a short overview, the current sprint, open
350
+ * requests, the task board, shortcuts. The owner's own text on a project page is never replaced. */
351
+ async function writeHubBody(ids, summary) {
352
+ const { list } = await blocks(ids.hub, 2000)
353
+ if (list.length) return
354
+ await call('insert_blocks', {
355
+ page_id: ids.hub,
356
+ blocks: [
357
+ { type: 'paragraph', text: `${String(summary || `Trang chính của dự án ${ids.project}`).replace(/[.。]\s*$/, '')}. Yêu cầu → duyệt → triển khai → bằng chứng → phát hành theo 📘 Quy trình làm việc (chung cho mọi dự án).` },
358
+ { type: 'heading', level: 2, text: 'Sprint hiện tại' },
359
+ { type: 'paragraph', text: NO_SPRINT },
360
+ { type: 'heading', level: 2, text: 'Đang mở' },
361
+ { type: 'paragraph', text: '_Không có yêu cầu nào đang mở._' },
362
+ { type: 'heading', level: 2, text: 'Lối tắt' },
363
+ ...[ids.handbook, ids.requests, ids.releases_page, ids.brainstorm].filter(Boolean).map((pageId) => ({ type: 'pageLink', props: { pageId } })),
364
+ ],
365
+ })
366
+ }
367
+
368
+ async function cmdShow() {
369
+ const cfg = loadConfig()
370
+ console.log(`${cfg.project}: hub ${url(cfg.hub)}`)
371
+ const reqs = await allRequests(cfg)
372
+ for (const sp of await sprintRows(cfg)) {
373
+ console.log(`${sp.title} (${sp.status}) | ${url(sp.id)}`)
374
+ for (const r of reqs.filter((x) => x.sprintId === sp.id)) console.log(` ${r.icon || '·'} ${r.title} | ${url(r.id)}`)
375
+ }
376
+ const inbox = reqs.filter((x) => !x.sprintId)
377
+ if (inbox.length) console.log('Yêu cầu chưa vào sprint:')
378
+ for (const r of inbox) console.log(` ${r.icon || '·'} ${r.title} | ${url(r.id)}`)
379
+ }
380
+
381
+ /** Request numbers (REQ-004 B2): new requests are R5, R6 …; old pages REQ-001 … REQ-004 keep their names. */
382
+ const reqNumber = (title) => Number(/(?:^|· )(?:REQ-|R)(\d+)\b/.exec(title)?.[1] ?? 0)
383
+ async function nextReq(cfg) {
384
+ const existing = await allRequests(cfg)
385
+ return `R${Math.max(0, ...existing.map((c) => reqNumber(c.title))) + 1}`
386
+ }
387
+
388
+ /** The sprint a new request goes into: --sprint S6 | new, else the running one, else a new one. */
389
+ async function sprintFor(cfg, ref, goal) {
390
+ if (!cfg.sprints_db) return null
391
+ const rows = await sprintRows(cfg)
392
+ if (ref && ref !== 'new') {
393
+ const hit = rows.find((r) => r.id === ref || r.title === ref || r.title.startsWith(`${ref} `)) ?? die(`sprint "${ref}" not found (kdev sprint list)`)
394
+ return hit
395
+ }
396
+ const running = !ref && rows.find((r) => ['Đang chạy', 'Review'].includes(r.status))
397
+ return running || (await createSprint(cfg, { goal }))
398
+ }
399
+
400
+ /** A new sprint row "S{n}" with the compact page template; returns {id, title, status}. */
401
+ async function createSprint(cfg, { title, goal, reqs = [], start } = {}) {
402
+ const rows = await sprintRows(cfg)
403
+ const n = Math.max(0, ...rows.map((r) => Number(/^S(?:print\s*)?(\d+)/i.exec(r.title)?.[1] ?? 0))) + 1
404
+ const name = title || `S${n}`
405
+ const out = await callJson('add_rows', {
406
+ database_id: cfg.sprints_db,
407
+ rows: [{ title: name, values: { 'Trạng thái': 'Đang chạy', 'Thời gian': { start: start || today() }, ...(goal ? { 'Mục tiêu': goal } : {}), ...(reqs.length ? { 'Yêu cầu': reqs } : {}) }, body_markdown: SPRINT_TEMPLATE(goal) }],
408
+ })
409
+ const id = out?.rows?.[0]?.id ?? die('add_rows gave no sprint row id')
410
+ requestCache = null
411
+ return { id, title: name, status: 'Đang chạy' }
412
+ }
413
+
414
+ /** Keep the sprint page's "## Yêu cầu" list and its "Yêu cầu" column in step with the requests under it. */
415
+ async function linkRequestsInSprint(cfg, sprintId) {
416
+ requestCache = null
417
+ const reqs = (await allRequests(cfg)).filter((r) => r.sprintId === sprintId).sort((a, b) => reqNumber(a.title) - reqNumber(b.title))
418
+ const { list } = await blocks(sprintId, 20000)
419
+ const fresh = reqs.length ? reqs.map((r) => ({ type: 'pageLink', props: { pageId: r.id } })) : [{ type: 'paragraph', text: '_Chưa có yêu cầu._' }]
420
+ if (!(await replaceSection(sprintId, list, 'Yêu cầu', fresh))) {
421
+ await call('insert_blocks', { page_id: sprintId, position: 'start', blocks: [{ type: 'heading', level: 2, text: 'Yêu cầu' }, ...fresh] })
422
+ }
423
+ const codes = reqs.map((r) => reqCode(r.title, reqNumber(r.title)))
424
+ if (codes.length) await call('update_rows', { database_id: cfg.sprints_db, updates: [{ row: sprintId, values: { 'Yêu cầu': codes } }] }, { soft: true })
425
+ }
426
+ /** "R5-T1" for new requests, "T1" for the old REQ-NNN ones (their task rows were named "T1 · …"). */
427
+ const taskCode = (req, key) => (/^R\d+$/.test(req) ? `${req}-${key}` : key)
428
+
429
+ const DEFAULT_INTRO =
430
+ 'Trả lời ngay trong từng thẻ: chọn phương án (không chọn = theo đề xuất), bấm **Đồng ý / Có sửa / Để sau / Bỏ**, ghi chú nếu cần. Cuối trang chọn cách duyệt rồi nhắn agent.'
431
+
432
+ const quoteBlock = (s) =>
433
+ String(s)
434
+ .trim()
435
+ .split('\n')
436
+ .map((l) => (l.trim() ? `> ${l}` : '>'))
437
+ .join('\n')
438
+
439
+ /** card spec → add_cards input */
440
+ const cardInput = (c) => ({
441
+ key: c.key,
442
+ title: c.title,
443
+ ...(c.size ? { size: c.size } : {}),
444
+ ...(c.area ? { area: c.area } : {}),
445
+ ...(c.quote ? { quote: c.quote } : {}),
446
+ ...(c.current ? { current: c.current } : {}),
447
+ ...(c.proposal ? { proposal: c.proposal } : {}),
448
+ ...(c.questions?.length ? { questions: c.questions } : {}),
449
+ })
450
+
451
+
452
+ /** A request page made of review blocks from a JSON spec (see templates/request.json). */
453
+ /** A card page from a spec: a new page (req new), or the owner's own REQ page (req adopt: his notes stay below,
454
+ * under "Ghi chú của anh", block ids and comments untouched). New / adopted requests go to the top of Yêu cầu. */
455
+ async function reqNewFromSpec(cfg, spec, opt, adopt = null) {
456
+ if (!(await hasTool('add_cards'))) die('this Kicho server has no add_cards tool yet: write the confirmation as Markdown (templates/request.md)')
457
+ const title = opt.title || spec.title || die('the spec needs "title" (or --title)')
458
+ const req = adopt ? adopt.req : await nextReq(cfg)
459
+ const sprint = await sprintFor(cfg, opt.sprint || spec.sprint, spec.sprintGoal || title)
460
+ const pageTitle = `${req} · ${title}`
461
+ const parent = sprint?.id ?? cfg.requests
462
+ const status = spec.status || 'review'
463
+ const [icon] = REQ_STATUS[status] ?? die(`unknown status ${status}`)
464
+ const cards = spec.cards ?? []
465
+ if (!cards.length) die('the spec has no cards')
466
+ const keys = new Set()
467
+ for (const c of cards) {
468
+ if (!c.key || !c.title) die('every card needs "key" and "title"')
469
+ if (keys.has(c.key)) die(`duplicate card key ${c.key}`)
470
+ keys.add(c.key)
471
+ }
472
+ const mainCards = cards.filter((c) => !c.extra)
473
+ const extra = cards.filter((c) => c.extra)
474
+ const summary = ['| # | Mục | Độ lớn |', '|---|---|---|', ...cards.map((c) => `| ${c.key} | ${c.title}${c.extra ? ' *(đề xuất thêm)*' : ''} | ${c.size ?? ''} |`)].join('\n')
475
+ const markdown = [
476
+ spec.intro || DEFAULT_INTRO,
477
+ '## Tóm tắt',
478
+ summary,
479
+ '## Các mục',
480
+ ...(extra.length ? ['## Đề xuất thêm'] : []),
481
+ ...(spec.plan ? ['## Kế hoạch triển khai', spec.plan] : []),
482
+ '## Duyệt',
483
+ '## Kết quả',
484
+ `_Mỗi vòng agent viết một trang con «${req} · Kết quả N»: đã chốt, đã làm, câu hỏi tiếp theo. Thẻ ở trên chỉ ghi trạng thái và link._`,
485
+ ...(spec.raw ? ['## Nguyên văn yêu cầu', quoteBlock(spec.raw)] : []),
486
+ ].join('\n\n')
487
+ let id
488
+ if (adopt) {
489
+ id = adopt.id
490
+ const { list: before } = await blocks(id, 4000)
491
+ await call('insert_blocks', { page_id: id, position: 'start', markdown: before.length ? `${markdown}\n\n## Ghi chú của anh` : markdown })
492
+ await call('update_page', { page_id: id, title: pageTitle, icon })
493
+ if (parent !== cfg.requests) await call('move_page', { page_id: id, parent_id: parent }, { soft: true })
494
+ } else {
495
+ const text = await call('create_page', { parent_id: parent, title: pageTitle, icon, markdown })
496
+ id = /page_id ([0-9a-f-]{36})/.exec(text)?.[1] ?? die(`create_page: ${text.slice(0, 200)}`)
497
+ }
498
+ const { list } = await blocks(id, 20000)
499
+ const head = (t) => list.find((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === t)?.id ?? die(`heading "${t}" not found`)
500
+ const ids = {}
501
+ for (const [group, at] of [
502
+ [mainCards, 'Các mục'],
503
+ [extra, 'Đề xuất thêm'],
504
+ ]) {
505
+ if (!group.length) continue
506
+ let after = head(at)
507
+ for (let i = 0; i < group.length; i += 30) {
508
+ const out = await callJson('add_cards', { page_id: id, after_block_id: after, cards: group.slice(i, i + 30).map(cardInput) })
509
+ for (const c of out?.cards ?? []) ids[c.key] = c.block_id
510
+ after = ids[group[Math.min(i + 30, group.length) - 1].key] ?? after
511
+ }
512
+ }
513
+ await call('insert_blocks', { page_id: id, after_block_id: head('Duyệt'), blocks: [{ type: 'approvalBar', props: { req } }] })
514
+ await call('insert_blocks', {
515
+ page_id: id,
516
+ position: 'start',
517
+ blocks: [{ type: 'reqHeader', props: { req, mode: spec.mode || 'review', status, submittedAt: today(), agent: spec.agent || '', tasksDb: spec.tasks === true ? cfg.tasks_db ?? '' : '', reqProperty: 'Yêu cầu' } }],
518
+ })
519
+ // task rows only when asked ("tasks": true): the owner follows requests and sprints, not agent task progress (2026-11-30)
520
+ if (spec.tasks === true) {
521
+ const rows = cards.map((c) => ({
522
+ title: `${taskCode(req, c.key)} · ${c.title}`,
523
+ values: {
524
+ 'Yêu cầu': req,
525
+ ...(sprint ? { Sprint: [sprint.title] } : {}),
526
+ 'Trạng thái': 'Chờ duyệt',
527
+ ...(c.area ? { 'Hạng mục': c.area } : {}),
528
+ ...(c.kind ? { Loại: c.kind } : {}),
529
+ ...(c.priority ? { 'Ưu tiên': c.priority } : {}),
530
+ ...(c.agent ? { Agent: c.agent } : {}),
531
+ },
532
+ body_markdown: `Mục **${c.key}** của [${req}](${url(id)}).`,
533
+ }))
534
+ const out = await callJson('add_rows', { database_id: cfg.tasks_db, rows })
535
+ const byTitle = new Map((out?.rows ?? []).map((r) => [r.title, r.id]))
536
+ const updates = []
537
+ for (const c of cards) {
538
+ const row = byTitle.get(`${taskCode(req, c.key)} · ${c.title}`)
539
+ if (row && ids[c.key]) updates.push({ block_id: ids[c.key], props: { taskRef: row } })
540
+ }
541
+ if (updates.length) await call('update_blocks', { page_id: id, updates }, { soft: true })
542
+ }
543
+ if (sprint) await linkRequestsInSprint(cfg, sprint.id)
544
+ await refreshHub(cfg)
545
+ console.log(`${req} ${id} (sprint ${sprint?.title ?? '-'})\n${url(id)}\ncards ${Object.keys(ids).length}/${cards.length}`)
546
+ }
547
+
548
+ /** The owner created a REQ page himself (title "REQ-NNN", maybe notes): turn it into a card page from a spec. */
549
+ async function cmdReqAdopt({ pos, opt }) {
550
+ const cfg = loadConfig()
551
+ const ref = pos[0] ?? die('usage: kdev req adopt <REQ-NNN|page_id> <spec.json>')
552
+ const page = UUID.test(ref) ? { id: UUID.exec(ref)[0] } : await findRequest(cfg, ref)
553
+ const info = await call('get_page', { page_id: page.id, max_chars: 500 })
554
+ const num = /title="(?:REQ-|R)(\d+)/.exec(info)?.[1] ?? /(?:REQ-|R)(\d+)/.exec(ref)?.[1] ?? die('the page title must start with REQ-NNN or R<n>')
555
+ return reqNewFromSpec(cfg, JSON.parse(readInput(pos[1] ?? die('spec.json missing'))), opt, { id: page.id, req: `R${Number(num)}` })
556
+ }
557
+
558
+ async function cmdReqNew({ pos, opt }) {
559
+ const cfg = loadConfig()
560
+ const src = pos[0] ?? die('usage: kdev req new <spec.json | page.md> [--title "short summary"]')
561
+ if (/\.json$/i.test(src) || opt.json) return reqNewFromSpec(cfg, JSON.parse(readInput(src)), opt)
562
+ const body = readInput(src)
563
+ const title = opt.title || die('--title is required')
564
+ const req = await nextReq(cfg)
565
+ const status = opt.status || 'review'
566
+ const [icon, label] = REQ_STATUS[status] ?? die(`unknown status ${status}`)
567
+ const markdown = body.replaceAll('{{REQ}}', req).replaceAll('{{STATUS}}', `${icon} ${label} (${nowLocal()})`).replaceAll('{{DATE}}', today())
568
+ const text = await call('create_page', { parent_id: cfg.requests, title: `${req} · ${today()} · ${title}`, icon, markdown })
569
+ const id = /page_id ([0-9a-f-]{36})/.exec(text)?.[1] ?? die(`create_page: ${text.slice(0, 200)}`)
570
+ await refreshHub(cfg)
571
+ console.log(`${req} ${id}\n${url(id)}`)
572
+ }
573
+
574
+ async function setStatusLine(pageId, icon, label) {
575
+ const { list } = await blocks(pageId, 4000)
576
+ const line = list.slice(0, 15).find((b) => /Trạng thái:/.test(b.text))
577
+ if (!line) return false
578
+ const rest = line.text.replace(/^.*?Trạng thái:\**\s*/, '')
579
+ const tail = rest.includes(' · ') ? rest.slice(rest.indexOf(' · ')) : ''
580
+ await call('update_blocks', { page_id: pageId, updates: [{ block_id: line.id, text: `**Trạng thái:** ${icon} ${label} (${nowLocal()})${tail}` }] })
581
+ return true
582
+ }
583
+
584
+ async function cmdReqStatus({ pos }) {
585
+ const cfg = loadConfig()
586
+ const req = await findRequest(cfg, pos[0] ?? die('usage: kdev req status <REQ-NNN|page_id> <' + Object.keys(REQ_STATUS).join('|') + '>'))
587
+ const [icon, label] = REQ_STATUS[pos[1]] ?? die(`status must be one of ${Object.keys(REQ_STATUS).join(', ')}`)
588
+ await call('update_page', { page_id: req.id, icon })
589
+ // card pages: the reqHeader block; Markdown pages: the "Trạng thái:" line
590
+ const { list } = await blocks(req.id, 8000)
591
+ const header = list.find((b) => b.type === 'reqHeader')
592
+ let where = 'icon only'
593
+ if (header) {
594
+ const ok = await call('update_blocks', { page_id: req.id, updates: [{ block_id: header.id, props: { status: pos[1] } }] }, { soft: true })
595
+ where = ok ? 'header' : 'icon only (header not writable on this server)'
596
+ } else if (await setStatusLine(req.id, icon, label)) where = 'status line'
597
+ await refreshHub(cfg)
598
+ console.log(`${icon} ${label} (${where}) | ${url(req.id)}`)
599
+ }
600
+
601
+ async function cmdReqRead({ pos, opt }) {
602
+ const cfg = loadConfig()
603
+ const req = await findRequest(cfg, pos[0] ?? die('usage: kdev req read <R5|REQ-NNN|page_id> [--all | --answered] [--since ISO] [--full] [--markdown]'))
604
+ // card pages: the compact review state; --full (or old servers / Markdown pages): the whole page
605
+ const compact = !opt.full && !opt.markdown && (await hasTool('get_review'))
606
+ const text = compact
607
+ ? await call('get_review', { page_id: req.id, only: opt.all ? 'all' : opt.answered ? 'answered' : 'open', ...(opt.since ? { since: opt.since } : {}) })
608
+ : await call('get_page', { page_id: req.id, max_chars: 60000, ...(opt.markdown ? { format: 'markdown' } : {}) })
609
+ console.log(text)
610
+ if (compact) {
611
+ for (const page of await resultPagesOf(req.id)) {
612
+ const review = await call('get_review', { page_id: page.id, only: opt.all ? 'all' : 'open' }, { soft: true })
613
+ if (review && !/\b0 cards\b/.test(review)) console.log(`\n${page.title} (${page.id}):\n${review}`)
614
+ }
615
+ }
616
+ if (await hasTool('list_comments')) console.log('\n' + (await call('list_comments', { page_id: req.id, include_resolved: !!opt.resolved })))
617
+ else console.log('\n(comments: this Kicho server has no list_comments tool yet; only the page body was read)')
618
+ }
619
+
620
+ // ---------- result pages (R6, owner 2026-12-02): the request page keeps his answers; each round's outcome and the
621
+ // next questions go to a child page "R6 · Kết quả N", and the cards only get their status and a link ----------
622
+
623
+ const RESULT_TEMPLATE = [
624
+ '## Tóm tắt',
625
+ '_1–3 dòng: đã làm gì, commit, đã lên production chưa._',
626
+ '## Đã chốt',
627
+ '_Mỗi mục một dòng theo câu trả lời của anh._',
628
+ '## Đã làm',
629
+ '_Mỗi mục: kết quả ngắn, ảnh khi cần, test._',
630
+ '## Câu hỏi tiếp theo',
631
+ 'Không có.',
632
+ ].join('\n\n')
633
+
634
+ const resultTitle = (req, round) => `${req} · Kết quả ${round}`
635
+ const resultRound = (title) => Number(/· Kết quả (\d+)$/.exec(title)?.[1] ?? 0)
636
+
637
+ async function resultPagesOf(requestId) {
638
+ return (await children(requestId)).filter((c) => resultRound(c.title)).map((c) => ({ ...c, round: resultRound(c.title) })).sort((a, b) => a.round - b.round)
639
+ }
640
+
641
+ const cardKeys = (arg) => String(arg ?? '').split(',').map((k) => k.trim()).filter(Boolean)
642
+
643
+ async function linkCardsToResult(requestId, keys, resultPageId, status) {
644
+ if (!keys.length) return
645
+ const updates = keys.map((key) => ({ key, status, result_page_id: resultPageId }))
646
+ console.log((await call('resolve_cards', { page_id: requestId, updates })).split('\n').slice(0, 3).join('\n'))
647
+ }
648
+
649
+ async function listResultOnRequest(requestId, resultPageId) {
650
+ const { list } = await blocks(requestId, 20000)
651
+ const head = list.find((b) => b.depth === 0 && b.type === 'heading' && /^(Kết quả|Báo cáo)$/.test(b.text.trim()))
652
+ const link = { type: 'pageLink', props: { pageId: resultPageId } }
653
+ if (!head) return call('insert_blocks', { page_id: requestId, position: 'end', blocks: [{ type: 'heading', level: 2, text: 'Kết quả' }, link] })
654
+ const section = []
655
+ for (const b of list.slice(list.indexOf(head) + 1)) {
656
+ if (b.depth === 0 && b.type === 'heading') break
657
+ if (b.depth === 0) section.push(b)
658
+ }
659
+ const lastLink = section.filter((b) => b.type === 'pageLink').at(-1)
660
+ return call('insert_blocks', { page_id: requestId, after_block_id: (lastLink ?? head).id, blocks: [link] })
661
+ }
662
+
663
+ async function addFollowUpQuestions(pageId, title, cardsFile) {
664
+ const spec = JSON.parse(readInput(cardsFile))
665
+ const cards = Array.isArray(spec) ? spec : (spec.cards ?? die('--cards: a list of cards or {"cards": [...]}'))
666
+ if (!cards.length) return 0
667
+ const { list } = await blocks(pageId, 20000)
668
+ const head = list.find((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === 'Câu hỏi tiếp theo')
669
+ const placeholder = head ? list[list.indexOf(head) + 1] : null
670
+ const out = await callJson('add_cards', { page_id: pageId, ...(head ? { after_block_id: head.id } : {}), cards: cards.map(cardInput) })
671
+ const added = out?.cards ?? []
672
+ const lastCard = added.at(-1)?.block_id
673
+ await call('insert_blocks', { page_id: pageId, ...(lastCard ? { after_block_id: lastCard } : { position: 'end' }), blocks: [{ type: 'approvalBar', props: { req: title } }] })
674
+ if (placeholder && placeholder.depth === 0 && /^Không có\.?$/.test(placeholder.text.trim())) await call('delete_blocks', { page_id: pageId, block_ids: [placeholder.id] })
675
+ return added.length
676
+ }
677
+
678
+ async function cmdResultNew({ pos, opt }) {
679
+ const cfg = loadConfig()
680
+ const request = await findRequest(cfg, pos[0] ?? die('usage: kdev result new <R6> [--file result.md] [--cards next.json] [--done A,B] [--status done|doing]'))
681
+ const req = request.req ?? `R${reqNumber(request.title ?? '') || '?'}`
682
+ const round = ((await resultPagesOf(request.id)).at(-1)?.round ?? 0) + 1
683
+ const title = resultTitle(req, round)
684
+ const markdown = opt.file ? readInput(opt.file) : RESULT_TEMPLATE
685
+ const text = await call('create_page', { parent_id: request.id, title, icon: '🧾', markdown })
686
+ const pageId = /page_id ([0-9a-f-]{36})/.exec(text)?.[1] ?? die(`create_page: ${text.slice(0, 200)}`)
687
+ const questions = opt.cards ? await addFollowUpQuestions(pageId, title, opt.cards) : 0
688
+ await listResultOnRequest(request.id, pageId)
689
+ await linkCardsToResult(request.id, cardKeys(opt.done), pageId, opt.status || 'done')
690
+ console.log(`${title} ${pageId}\n${url(pageId)}\nfollow-up questions ${questions}`)
691
+ }
692
+
693
+ async function cmdResultLink({ pos, opt }) {
694
+ const cfg = loadConfig()
695
+ const request = await findRequest(cfg, pos[0] ?? die('usage: kdev result link <R6> <A,B> [--round N] [--status done|doing|dropped|later]'))
696
+ const rounds = await resultPagesOf(request.id)
697
+ const page = (opt.round ? rounds.find((r) => r.round === Number(opt.round)) : rounds.at(-1)) ?? die('no result page yet: kdev result new first')
698
+ await linkCardsToResult(request.id, cardKeys(pos[1] ?? die('which cards? e.g. A,B')), page.id, opt.status || 'done')
699
+ }
700
+
701
+ async function cmdResultQuestions({ pos, opt }) {
702
+ const cfg = loadConfig()
703
+ const request = await findRequest(cfg, pos[0] ?? die('usage: kdev result questions <R6> <next.json> [--round N]'))
704
+ const rounds = await resultPagesOf(request.id)
705
+ const page = (opt.round ? rounds.find((r) => r.round === Number(opt.round)) : rounds.at(-1)) ?? die('no result page yet: kdev result new first')
706
+ const added = await addFollowUpQuestions(page.id, page.title, pos[1] ?? die('next.json missing'))
707
+ console.log(`${page.title}: ${added} follow-up question card(s)\n${url(page.id)}`)
708
+ }
709
+
710
+ /** Tell the owner the answers were read: agentReadAt on the page's approval bar. */
711
+ async function cmdReqAck({ pos }) {
712
+ const cfg = loadConfig()
713
+ const req = await findRequest(cfg, pos[0] ?? die('usage: kdev req ack <REQ-NNN|page_id>'))
714
+ console.log((await call('resolve_cards', { page_id: req.id, mark_read: true, updates: [] })).split('\n')[0])
715
+ }
716
+
717
+ /** A page ref: a page id / URL, or a request id (REQ-007). */
718
+ async function pageRef(cfg, ref) {
719
+ if (UUID.test(ref ?? '')) return UUID.exec(ref)[0]
720
+ return (await findRequest(cfg, ref)).id
721
+ }
722
+
723
+ /** Definition of Done items: the project's list (.kicho-devflow.json "dod", else the default). --dod all | "item,item"
724
+ * (those done, the rest not), --dod-na "i18n=no new text" (not applicable: counted as done, with the note). */
725
+ const DEFAULT_DOD = ['Test viết và qua', 'Có bằng chứng', 'Tài liệu cập nhật (repo + Kicho)', 'Chữ giao diện đủ vi / en / ja', 'Rà bảo mật (đăng nhập / upload / quyền)']
726
+ function dodList(cfg, opt) {
727
+ if (!opt.dod && !opt['dod-na']) return null
728
+ const items = Array.isArray(cfg?.dod) && cfg.dod.length ? cfg.dod : DEFAULT_DOD
729
+ const listOf = (v) => many(v).flatMap((d) => String(d).split(',')).map((x) => x.trim()).filter(Boolean)
730
+ const done = opt.dod === 'all' ? items : listOf(opt.dod)
731
+ const na = listOf(opt['dod-na']).map((x) => x.split(/=(.*)/s)).map(([k, v]) => [k.trim().toLowerCase(), (v ?? 'không áp dụng').trim()])
732
+ const starts = (item, key) => item.toLowerCase().startsWith(String(key).toLowerCase())
733
+ return items.map((item) => {
734
+ const n = na.find(([k]) => starts(item, k))
735
+ if (n) return { item, done: true, note: n[1] }
736
+ return { item, done: done.some((d) => starts(item, d)) }
737
+ })
738
+ }
739
+
740
+ /** The sprint being run (status Đang chạy, newest first), for new task rows; null without a sprint database. */
741
+
742
+ async function cmdCard({ pos, opt }, sub) {
743
+ const cfg = loadConfig()
744
+ const pageId = await pageRef(cfg, pos[0] ?? die('usage: kdev card resolve|result <REQ-NNN> <KEY>… (see help)'))
745
+ let updates
746
+ if (sub === 'resolve') {
747
+ if (opt.file) updates = JSON.parse(readInput(opt.file)) // [{ key, status?, decided? }]
748
+ else {
749
+ const keys = pos.slice(1)
750
+ if (!keys.length) die('usage: kdev card resolve <REQ> <KEY>… [--status S] [--decided "…"|@file] | --file decisions.json')
751
+ updates = keys.map((key) => ({ key: String(key).replace(/^R\d+-/, ''), ...(opt.status ? { status: opt.status } : {}), ...(opt.decided ? { decided: readInput(opt.decided) } : {}) }))
752
+ }
753
+ } else {
754
+ const key = String(pos[1] ?? '').replace(/^R\d+-/, '') || die('usage: kdev card result <REQ> <KEY> --outcome done|changed|dropped|deferred [--summary …] [--verification …] [--limits …] [--commit sha] [--status done]')
755
+ const result = { outcome: opt.outcome || 'done' }
756
+ for (const k of ['summary', 'verification', 'limits']) if (opt[k]) result[k] = readInput(opt[k])
757
+ if (opt.commit) result.commit = opt.commit
758
+ const dod = dodList(cfg, opt)
759
+ if (dod) result.dod = dod
760
+ const status = opt.status || { done: 'done', changed: 'done', dropped: 'dropped', deferred: 'later' }[result.outcome]
761
+ updates = [{ key, result, ...(status ? { status } : {}) }]
762
+ }
763
+ console.log((await call('resolve_cards', { page_id: pageId, updates })).split('\n').slice(0, 3).join('\n'))
764
+ }
765
+
766
+ function rowValues(opt) {
767
+ const v = {}
768
+ if (opt.status) v['Trạng thái'] = opt.status
769
+ if (opt.agent) v.Agent = opt.agent
770
+ if (opt.commit) v.Commit = opt.commit
771
+ if (opt.req) v['Yêu cầu'] = opt.req
772
+ if (opt.area) v['Hạng mục'] = opt.area
773
+ if (opt.start || opt.end) v['Thời gian'] = { start: opt.start || today(), ...(opt.end ? { end: opt.end } : {}) }
774
+ return v
775
+ }
776
+
777
+ async function cmdTasksAdd({ pos, opt }) {
778
+ const cfg = loadConfig()
779
+ const rows = JSON.parse(readInput(pos[0] ?? die('usage: kdev tasks add <rows.json> [--req REQ-NNN]')))
780
+ for (const r of rows) {
781
+ r.values ??= {}
782
+ if (opt.req && !r.values['Yêu cầu']) r.values['Yêu cầu'] = opt.req
783
+ if (!r.values['Trạng thái']) r.values['Trạng thái'] = opt.status || 'Chờ duyệt'
784
+ }
785
+ for (let i = 0; i < rows.length; i += 100) {
786
+ const text = await call('add_rows', { database_id: cfg.tasks_db, rows: rows.slice(i, i + 100) })
787
+ console.log(text.split('\n')[0])
788
+ }
789
+ console.log(url(cfg.tasks_page))
790
+ }
791
+
792
+ /** Row refs: row ids stay; an item code ("F2", "R10") becomes the id of the row titled "F2 · …" (with --req, in that
793
+ * request); anything else is passed as an exact title. (query_database shortens long titles, so codes beat titles.) */
794
+ async function resolveRows(cfg, refs, req) {
795
+ let table = null
796
+ const out = []
797
+ for (const ref of refs) {
798
+ if (UUID.test(ref)) {
799
+ out.push(UUID.exec(ref)[0])
800
+ continue
801
+ }
802
+ if (/^(?:R\d+-)?[A-Za-z]{1,3}\d{0,3}$/.test(ref)) {
803
+ const code0 = req && /^R\d+$/.test(req) && !/^R\d+-/.test(ref) ? `${req}-${ref}` : ref
804
+ const j = await callJson('query_database', {
805
+ database_id: cfg.tasks_db,
806
+ limit: 5,
807
+ properties: [],
808
+ title_starts_with: `${code0} · `,
809
+ ...(req ? { filters: [{ property: 'Yêu cầu', operator: 'is', value: req }] } : {}),
810
+ }, { soft: true })
811
+ if (j?.rows) {
812
+ if (j.rows.length === 1) {
813
+ out.push(j.rows[0].id)
814
+ continue
815
+ }
816
+ if (j.rows.length > 1) die(`${ref} matches ${j.rows.length} rows: add --req R…`)
817
+ }
818
+ table ??= await call('query_database', {
819
+ database_id: cfg.tasks_db,
820
+ limit: 200,
821
+ ...(req ? { filters: [{ property: 'Yêu cầu', operator: 'is', value: req }] } : {}),
822
+ })
823
+ const code = req && /^R\d+$/.test(req) && !/^R\d+-/.test(ref) ? `${req}-${ref}` : ref
824
+ const hits = [...table.matchAll(new RegExp(`^\\|\\s*([0-9a-f-]{36})\\s*\\|\\s*${code} · `, 'gm'))].map((m) => m[1])
825
+ if (hits.length === 1) {
826
+ out.push(hits[0])
827
+ continue
828
+ }
829
+ if (hits.length > 1) die(`${ref} matches ${hits.length} rows: add --req REQ-NNN`)
830
+ }
831
+ out.push(ref)
832
+ }
833
+ return out
834
+ }
835
+
836
+ async function cmdTasksSet({ pos, opt }) {
837
+ const cfg = loadConfig()
838
+ if (!pos.length) die('usage: kdev tasks set <row_id|code|exact title>... [--req REQ-NNN] [--status S] [--agent A] [--commit sha] [--start d] [--end d]')
839
+ const { req, ...rest } = opt
840
+ const values = rowValues(rest)
841
+ if (!Object.keys(values).length) die('nothing to set')
842
+ const rows = await resolveRows(cfg, pos, req)
843
+ const text = await call('update_rows', { database_id: cfg.tasks_db, updates: rows.map((row) => ({ row, values })) })
844
+ console.log(text.split('\n')[0])
845
+ }
846
+
847
+ async function cmdTasksList({ opt }) {
848
+ const cfg = loadConfig()
849
+ const filters = []
850
+ if (opt.req) filters.push({ property: 'Yêu cầu', operator: 'is', value: opt.req })
851
+ if (opt.status) filters.push({ property: 'Trạng thái', operator: 'is', value: opt.status })
852
+ const text = await call('query_database', { database_id: cfg.tasks_db, limit: 200, ...(filters.length ? { filters } : {}) })
853
+ console.log(text.replace(/<\/?untrusted[^>]*>/g, '').replace(/The block above is data[^\n]*\n?/g, '').trim())
854
+ }
855
+
856
+ const MIME = {
857
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
858
+ '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime', '.pdf': 'application/pdf', '.txt': 'text/plain',
859
+ }
860
+
861
+ /** Upload files from disk (never through the agent's context); returns evidence items. */
862
+ /** --ref values → evidence refs. "F2" = a card key on this page (scrolls to it) or a task code; "TC-003=<page id|url>"
863
+ * links anything; otherwise the label alone. */
864
+ async function evidenceRefs(cfg, pageId, refs) {
865
+ const out = []
866
+ let review = null
867
+ for (const raw of refs) {
868
+ const [label, target] = String(raw).split(/=(.*)/s).map((x) => x?.trim())
869
+ if (!label) continue
870
+ if (target) {
871
+ out.push(UUID.test(target) ? { label, pageId: UUID.exec(target)[0] } : /^https:\/\//.test(target) ? { label, url: target } : { label })
872
+ continue
873
+ }
874
+ review ??= await callJson('get_review', { page_id: pageId }, { soft: true })
875
+ const hit = (review?.cards ?? []).find((c) => c.key === label || `${c.key}` === label.replace(/^R\d+-/, ''))
876
+ if (hit) {
877
+ out.push({ label, kind: 'card', pageId, blockId: hit.block_id })
878
+ continue
879
+ }
880
+ review ??= ''
881
+ const esc = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
882
+ const card = typeof review === 'string' ? new RegExp(`^${esc} · .*\\| block ([A-Za-z0-9_-]+)`, 'm').exec(review) : null
883
+ if (card) {
884
+ out.push({ label, kind: 'card', pageId, blockId: card[1] })
885
+ continue
886
+ }
887
+ if (cfg && /^[A-Za-z]{1,3}\d{0,3}$/.test(label)) {
888
+ const [row] = await resolveRows(cfg, [label])
889
+ if (UUID.test(row)) {
890
+ out.push({ label, kind: 'task', pageId: row })
891
+ continue
892
+ }
893
+ }
894
+ out.push({ label })
895
+ }
896
+ return out
897
+ }
898
+
899
+ /** --field "Env=staging" (repeatable) → [{label, value}] */
900
+ const evidenceFields = (opt) =>
901
+ many(opt.field)
902
+ .map((f) => String(f).split(/=(.*)/s))
903
+ .filter(([k]) => k?.trim())
904
+ .map(([k, v]) => ({ label: k.trim(), value: (v ?? '').trim() }))
905
+
906
+ async function uploadAll(pageId, files, opt, extras = {}) {
907
+ if (!(await hasTool('upload_file'))) die('this Kicho server has no upload_file tool yet; use `kdev log` for text evidence')
908
+ const items = []
909
+ for (const f of files) {
910
+ const data = readFileSync(f)
911
+ const mime = MIME[path.extname(f).toLowerCase()] ?? 'application/octet-stream'
912
+ const up = await callJson('upload_file', { page_id: pageId, filename: path.basename(f), mime, data_base64: data.toString('base64') })
913
+ const fileUrl = up?.url ?? die('upload_file gave no url')
914
+ const caption = files.length === 1 && opt.caption ? opt.caption : opt.caption ? `${opt.caption} · ${path.basename(f)}` : path.basename(f)
915
+ items.push({
916
+ url: fileUrl,
917
+ kind: mime.startsWith('image/') ? 'image' : mime.startsWith('video/') ? 'video' : 'file',
918
+ caption,
919
+ ...(opt.device ? { device: opt.device } : {}),
920
+ ...(opt.verdict ? { verdict: opt.verdict } : {}),
921
+ ...(opt.role ? { role: opt.role } : {}),
922
+ ...extras,
923
+ })
924
+ console.log(`${path.basename(f)} → ${fileUrl}`)
925
+ }
926
+ return items
927
+ }
928
+
929
+ async function cmdEvidence({ pos, opt }) {
930
+ const usage = 'usage: kdev evidence <REQ-NNN|page_id> <file>... [--card KEY] [--caption "…"] [--device desktop|phone|tablet] [--verdict pass|fail] [--role before|after] [--ref F2 …] [--field Env=staging …] [--note "備考"] [--run <row id>] [--title "…"] [--after block_id]'
931
+ const files = pos.slice(1)
932
+ if (!pos[0] || !files.length) die(usage)
933
+ const cfg = findConfig() ? loadConfig() : null
934
+ const pageId = UUID.test(pos[0]) ? UUID.exec(pos[0])[0] : cfg ? await pageRef(cfg, pos[0]) : die(usage)
935
+ const refs = await evidenceRefs(cfg, pageId, many(opt.ref))
936
+ const fields = evidenceFields(opt)
937
+ const extras = {
938
+ ...(refs.length ? { refs } : {}),
939
+ ...(fields.length ? { fields } : {}),
940
+ ...(opt.note ? { note: readInput(opt.note) } : {}),
941
+ ...(opt.run ? { runRef: opt.run } : {}),
942
+ }
943
+ const items = await uploadAll(pageId, files, opt, extras)
944
+ if (opt.card) {
945
+ // inside the card's result (resolve_cards appends)
946
+ const r = await call('resolve_cards', { page_id: pageId, updates: [{ key: opt.card, add_evidence: items }] })
947
+ console.log(r.split('\n')[0])
948
+ return
949
+ }
950
+ const layout = items.some((i) => i.role) ? 'compare' : 'grid'
951
+ const r = await call('insert_blocks', {
952
+ page_id: pageId,
953
+ blocks: [{ type: 'evidence', props: { title: opt.title || '', layout, items } }],
954
+ ...(opt.after ? { after_block_id: opt.after } : {}),
955
+ })
956
+ console.log(`${r.split('\n')[0].replace(/ New block ids:.*/, '')}\nblock ${newBlockIds(r).at(-1) ?? '?'}`)
957
+ }
958
+
959
+ // ---------- project documents, sprints, gates (REQ-003 P2 / P3): kdev init-docs ----------
960
+
961
+ const hasProp = (info, name) => new RegExp(`^- ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\(`, 'm').test(info)
962
+
963
+ /** Two-way relation from db `from` (property `name`) to db `to` (paired property `paired`), unless it exists. */
964
+ async function ensureRelation(from, name, to, paired) {
965
+ const info = await call('get_database', { database_id: from })
966
+ if (hasProp(info, name)) return 'kept'
967
+ const r = await call('add_property', { database_id: from, name, type: 'relation', target_database: to, two_way: true, paired_name: paired }, { soft: true })
968
+ return r ? 'added' : 'FAILED (server without relations?)'
969
+ }
970
+
971
+ async function ensureRollup(db, name, relation, fn) {
972
+ const info = await call('get_database', { database_id: db })
973
+ if (hasProp(info, name)) return 'kept'
974
+ const r = await call('add_property', { database_id: db, name, type: 'rollup', relation, function: fn }, { soft: true })
975
+ return r ? 'added' : 'FAILED'
976
+ }
977
+
978
+ /** The project documents (📚 Tài liệu dự án): [config key, icon, title, what goes in]. Short pages, overview first. */
979
+ const DOC_PAGES = [
980
+ ['architecture_page', '🧭', 'Kiến trúc hệ thống', '_Luồng đi của request (sơ đồ), các phần chính và vì sao chọn chúng. Agent cập nhật khi kiến trúc đổi (`kdev doc set architecture`)._'],
981
+ ['database_page', '🗄️', 'Cơ sở dữ liệu', '_Các bảng đang có, mỗi bảng một dòng: nhiệm vụ, dữ liệu chính. Không vẽ ER (`kdev doc set database`)._'],
982
+ ['clusters_page', '🧪', 'Cụm chức năng & test', '_Các cụm chức năng, test của từng cụm và số case đạt; sửa cụm nào test lại cụm đó, test tổng trước khi lên production / store (`kdev doc set clusters`)._'],
983
+ ['metrics_page', '📈', 'Số đo & cải tiến', '_Hiệu năng, kích thước, số test qua các sprint; mỗi dòng có trước / sau (`kdev doc set metrics`)._'],
984
+ ]
985
+
986
+ async function cmdInitDocs() {
987
+ const cfgFile = findConfig() ?? die(`no ${CONFIG}: run kdev init first`)
988
+ const cfg = loadConfig()
989
+ const ids = { ...cfg }
990
+ delete ids.file
991
+ const sprints = await ensureDatabase(cfg.hub, '🏃', 'Sprint', async (db) => {
992
+ await call('add_property', { database_id: db, name: 'Trạng thái', type: 'status', show_on_cards: true, options: [
993
+ { name: 'Lên kế hoạch', color: 'grey', group: 'todo' }, { name: 'Đang chạy', color: 'orange', group: 'in_progress' },
994
+ { name: 'Review', color: 'purple', group: 'in_progress' }, { name: 'Xong', color: 'green', group: 'complete' }] })
995
+ await call('add_property', { database_id: db, name: 'Mục tiêu', type: 'text', show_on_cards: true })
996
+ await call('add_property', { database_id: db, name: 'Thời gian', type: 'date', show_on_cards: true })
997
+ await call('add_property', { database_id: db, name: 'Yêu cầu', type: 'multi_select', options: [], show_on_cards: true })
998
+ await call('add_property', { database_id: db, name: 'Commit', type: 'text', show_on_cards: false })
999
+ await call('add_view', { database_id: db, type: 'timeline', name: 'Timeline', date_property: 'Thời gian' })
1000
+ })
1001
+ ids.sprints_page = sprints.pageId
1002
+ ids.sprints_db = sprints.databaseId
1003
+ ids.gates_page = await ensurePage(cfg.hub, '🚦', 'Cột mốc',
1004
+ 'Gate review trước những mốc lớn (theo `stage-gate-dev`: G0 discovery … G5 production batch, G6 QA, G7 release). Trong lúc phát triển agent tự quyết; trước khi phát hành sản phẩm / lên store có trang gate với checklist, test kỹ, tổng kết và thẻ **Go / No-go** để anh duyệt.')
1005
+ ids.docs_page = await ensurePage(cfg.hub, '📚', 'Tài liệu dự án',
1006
+ 'Tài liệu **cho người đọc**: ngắn, tổng quan, có link tới bằng chứng để truy vết. Tài liệu chuyên sâu cho agent (path file, quy tắc code) nằm trong `docs/` của repo.')
1007
+ // four short pages for people (owner 2026-11-30): what the system is, why, how it is tested, what improved
1008
+ for (const [key, icon, title, hint] of DOC_PAGES) ids[key] ??= await ensurePage(ids.docs_page, icon, title, hint)
1009
+ // the hub: links to the new pages + "Cài đặt dự án" (evidence fields of this project, Definition of Done)
1010
+ const { raw, list } = await blocks(cfg.hub, 30000)
1011
+ const links = [ids.sprints_page, ids.gates_page, ids.docs_page].filter((p) => !raw.includes(`page ${p}`))
1012
+ if (links.length) await call('insert_blocks', { page_id: cfg.hub, blocks: links.map((pageId) => ({ type: 'pageLink', props: { pageId } })), ...(list.some((b) => b.type === 'heading' && /Cài đặt dự án/.test(b.text)) ? { position: 'end' } : {}) })
1013
+ if (!list.some((b) => b.type === 'heading' && /Cài đặt dự án/.test(b.text))) {
1014
+ await call('insert_blocks', {
1015
+ page_id: cfg.hub,
1016
+ markdown: `## Cài đặt dự án
1017
+
1018
+ **Trường bằng chứng** của dự án này (agent ghi bằng \`kdev evidence --field Tên=giá trị\`; anh sửa bảng này là đổi). Dự án làm một mình thì để trống.
1019
+
1020
+ | Trường | Khi nào ghi |
1021
+ |---|---|
1022
+ | | |
1023
+
1024
+ **Definition of Done**: test viết và qua · có bằng chứng (case đại diện) · tài liệu cập nhật (repo + Kicho) · chữ giao diện đủ vi / en / ja · rà bảo mật khi đụng đăng nhập / upload / quyền.`,
1025
+ })
1026
+ }
1027
+ writeFileSync(cfgFile, JSON.stringify(ids, null, 2) + '\n')
1028
+ for (const k of ['sprints_db', 'gates_page', 'docs_page', ...DOC_PAGES.map((d) => d[0])]) console.log(`${k} ${ids[k]}`)
1029
+ }
1030
+
1031
+ // ---------- decision memory: Hindsight (REQ-004 B3) ----------
1032
+ // The owner decides for every agent, so his decisions live in ONE bank shared with doraemon (Paperclip): the company
1033
+ // bank named in .kicho-devflow.json "memory_bank" (never written in a public repo). Its conventions are doraemon's:
1034
+ // each record carries exactly one project tag — `project:<memory_project>` for this project, `project:cong-ty` for
1035
+ // company-wide rules — and kdev reads only those two (other projects' memories, e.g. clients under NDA, never come
1036
+ // in). Records are one line, word for word (strategy verbatim-record, no LLM): kind board-decision / board-order for
1037
+ // the owner's decisions, project-change for an agent's record of what went live. The bank's missions, config and
1038
+ // mental models belong to doraemon's plugin: kdev never changes them. URL + key per machine: HINDSIGHT_URL /
1039
+ // HINDSIGHT_API_KEY, else ~/.config/kicho/hindsight.env. Recall fails open.
1040
+
1041
+ function memoryEnv() {
1042
+ const env = { url: process.env.HINDSIGHT_URL, key: process.env.HINDSIGHT_API_KEY }
1043
+ const f = path.join(homedir(), '.config', 'kicho', 'hindsight.env')
1044
+ if ((!env.url || !env.key) && existsSync(f)) {
1045
+ for (const line of readFileSync(f, 'utf8').split('\n')) {
1046
+ const m = /^\s*(HINDSIGHT_URL|HINDSIGHT_API_KEY)\s*=\s*(.*)\s*$/.exec(line)
1047
+ if (m && m[1] === 'HINDSIGHT_URL') env.url ??= m[2]
1048
+ if (m && m[1] === 'HINDSIGHT_API_KEY') env.key ??= m[2]
1049
+ }
1050
+ }
1051
+ return env
1052
+ }
1053
+
1054
+ const COMPANY_TAG = 'project:cong-ty'
1055
+ const memoryBank = (cfg) => cfg.memory_bank || die(`no "memory_bank" in ${CONFIG}: the shared decision bank (see the skill)`)
1056
+ const memoryProject = (cfg) => `project:${cfg.memory_project || String(cfg.project || 'project').toLowerCase().replace(/[^a-z0-9-]+/g, '-')}`
1057
+
1058
+ /** macOS: a process that no GUI app is responsible for (VS Code Remote-SSH's server, launchd jobs) cannot be granted
1059
+ * Local Network access (System Settings lists only apps), so Node's fetch to a LAN address fails with EHOSTUNREACH,
1060
+ * while Apple's own /usr/bin/curl is allowed. Same request through curl; the key and the body go through stdin
1061
+ * (curl -K -), never the command line. Returns {status, text}. */
1062
+ function curlRequest(method, full, key, body, timeoutMs) {
1063
+ const q = (v) => `"${String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
1064
+ const cfg = [
1065
+ `url = ${q(full)}`,
1066
+ `request = ${q(method)}`,
1067
+ `header = ${q(`Authorization: Bearer ${key}`)}`,
1068
+ ...(body ? [`header = ${q('Content-Type: application/json')}`, `data-binary = ${q(JSON.stringify(body))}`] : []),
1069
+ ].join('\n')
1070
+ const out = execFileSync('/usr/bin/curl', ['-sS', '--max-time', String(Math.ceil(timeoutMs / 1000)), '-w', '\n%{http_code}', '-K', '-'], {
1071
+ input: cfg + '\n',
1072
+ encoding: 'utf8',
1073
+ maxBuffer: 32 << 20,
1074
+ timeout: timeoutMs + 2000,
1075
+ stdio: ['pipe', 'pipe', 'pipe'],
1076
+ })
1077
+ const cut = out.lastIndexOf('\n')
1078
+ return { status: Number(out.slice(cut + 1)), text: out.slice(0, cut) }
1079
+ }
1080
+
1081
+ const LAN_BLOCKED = new Set(['EHOSTUNREACH', 'ENETUNREACH'])
1082
+
1083
+ async function hindsight(method, pathPart, body, { soft = false, timeoutMs = 8000 } = {}) {
1084
+ const { url, key } = memoryEnv()
1085
+ if (!url || !key) {
1086
+ if (soft) return null
1087
+ die('no Hindsight URL / key: set HINDSIGHT_URL + HINDSIGHT_API_KEY or ~/.config/kicho/hindsight.env')
1088
+ }
1089
+ const full = `${url.replace(/\/$/, '')}${pathPart}`
1090
+ let status, text
1091
+ try {
1092
+ try {
1093
+ const res = await fetch(full, {
1094
+ method,
1095
+ headers: { Authorization: `Bearer ${key}`, ...(body ? { 'Content-Type': 'application/json' } : {}) },
1096
+ body: body ? JSON.stringify(body) : undefined,
1097
+ signal: AbortSignal.timeout(timeoutMs),
1098
+ })
1099
+ status = res.status
1100
+ text = await res.text()
1101
+ } catch (e) {
1102
+ if (!(process.platform === 'darwin' && LAN_BLOCKED.has(e?.cause?.code) && existsSync('/usr/bin/curl'))) throw e
1103
+ ;({ status, text } = curlRequest(method, full, key, body, timeoutMs))
1104
+ }
1105
+ if (!(status >= 200 && status < 300)) {
1106
+ if (soft) return null
1107
+ return { httpStatus: status, text }
1108
+ }
1109
+ return text ? JSON.parse(text) : {}
1110
+ } catch (e) {
1111
+ if (soft) return null
1112
+ die(`Hindsight unreachable: ${e?.message ?? e}`)
1113
+ }
1114
+ }
1115
+
1116
+ const bankPath = (cfg) => `/v1/default/banks/${encodeURIComponent(memoryBank(cfg))}`
1117
+
1118
+ async function cmdMemory({ pos }) {
1119
+ const cfg = loadConfig()
1120
+ const sub = pos[0]
1121
+ if (sub === 'init') {
1122
+ const r = await hindsight('GET', '/v1/default/banks?limit=1000')
1123
+ const ok = (r?.banks ?? []).some((b) => b.bank_id === memoryBank(cfg))
1124
+ console.log(ok ? `shared bank found; this project writes ${memoryProject(cfg)} (+ ${COMPANY_TAG} for company-wide rules) and reads both` : 'the shared bank is missing on this Hindsight server (doraemon creates it)')
1125
+ return
1126
+ }
1127
+ if (sub === 'model') {
1128
+ // doraemon's summary of how the owner decides (company-wide), read only
1129
+ const m = await hindsight('GET', `${bankPath(cfg)}/mental-models/operator-working-style?detail=content`, null, { soft: true })
1130
+ console.log(m?.content && !/^Generating content/.test(m.content) ? m.content : '(no summary yet)')
1131
+ return
1132
+ }
1133
+ die('usage: kdev memory init | model')
1134
+ }
1135
+
1136
+ const KIND_MAP = { 'owner-decision': 'board-decision', 'owner-rule': 'board-decision', 'owner-order': 'board-order', 'tech-decision': 'project-change', 'board-decision': 'board-decision', 'board-order': 'board-order', 'project-change': 'project-change' }
1137
+
1138
+ /** One decision of the owner (one line, ≤ 300 characters). --company for a rule that applies to every project.
1139
+ * --file items.json for many: [{text, kind?, source?, company?, id?, date?}]. The same id replaces a record. */
1140
+ async function cmdRemember({ pos, opt }) {
1141
+ const cfg = loadConfig()
1142
+ const list = opt.file
1143
+ ? JSON.parse(readInput(opt.file))
1144
+ : [{ text: pos.join(' ') || die('usage: kdev remember "<the owner\'s decision, one line>" [--kind owner-decision|owner-order|tech-decision] [--source R5/T1] [--company] [--id doc-id]'), kind: opt.kind, source: opt.source, company: !!opt.company, id: opt.id, date: opt.date }]
1145
+ const items = list.map((x) => {
1146
+ const kind = KIND_MAP[x.kind || 'owner-decision'] ?? die(`unknown kind ${x.kind}`)
1147
+ const text = String(x.text).trim()
1148
+ if (text.length > 300) die(`a record is one line of at most 300 characters (${text.length}): ${text.slice(0, 60)}…`)
1149
+ if (/kicho_pat_|sk-ant-|-----BEGIN|password\s*[:=]/i.test(text)) die(`refusing to store something that looks like a secret: ${text.slice(0, 40)}…`)
1150
+ const project = x.company ? COMPANY_TAG : memoryProject(cfg)
1151
+ const day = x.date || today()
1152
+ const who = kind === 'project-change' ? "an agent's record of what changed or went live" : "an agent's one-line summary of the Board's decision"
1153
+ return {
1154
+ content: text,
1155
+ context: `[Kicho devflow${x.source ? `, ${x.source}` : ''}] ${who}${kind === 'project-change' ? '' : ' (the Board = the owner, anh)'}.`.slice(0, 380),
1156
+ timestamp: `${day}T12:00:00Z`,
1157
+ document_id: `kicho-devflow:${x.id || `${kind}:${createHash('sha1').update(text).digest('hex').slice(0, 16)}`}`,
1158
+ tags: ['source:kicho-devflow', `kind:${kind}`, project, ...(x.source ? [`ref:${x.source}`] : [])],
1159
+ metadata: { kind, source: 'kicho-devflow', project: project.slice('project:'.length), ...(x.source ? { ref: x.source } : {}) },
1160
+ strategy: 'verbatim-record',
1161
+ }
1162
+ })
1163
+ for (let i = 0; i < items.length; i += 50) {
1164
+ let r = await hindsight('POST', `${bankPath(cfg)}/memories`, { items: items.slice(i, i + 50), async: true })
1165
+ // a bank configured before the strategy existed: store them the old way
1166
+ if (r?.httpStatus && /strateg/i.test(r.text)) r = await hindsight('POST', `${bankPath(cfg)}/memories`, { items: items.slice(i, i + 50).map(({ strategy: _s, ...x }) => x), async: true })
1167
+ if (r?.httpStatus) die(`Hindsight POST /memories: HTTP ${r.httpStatus} ${r.text.slice(0, 200)}`)
1168
+ }
1169
+ const company = items.filter((x) => x.tags.includes(COMPANY_TAG)).length
1170
+ console.log(`remembered ${items.length} record(s) (${items.length - company} ${memoryProject(cfg)}, ${company} ${COMPANY_TAG}); searchable in a minute`)
1171
+ }
1172
+
1173
+ /** What the owner already decided about something (before asking him): this project + company-wide only. */
1174
+ async function cmdRecall({ pos, opt }) {
1175
+ const cfg = loadConfig()
1176
+ const query = pos.join(' ').slice(0, 700) || die('usage: kdev recall "<what you are about to ask / decide>" [--top 6]')
1177
+ const r = await hindsight(
1178
+ 'POST',
1179
+ `${bankPath(cfg)}/memories/recall`,
1180
+ { query, budget: 'mid', max_tokens: Number(opt.max || 800), types: ['world', 'experience'], tag_groups: [{ tags: [memoryProject(cfg), COMPANY_TAG], match: 'any_strict' }] },
1181
+ { soft: true, timeoutMs: 6000 },
1182
+ )
1183
+ const results = Array.isArray(r?.results) ? r.results : []
1184
+ if (!results.length) {
1185
+ console.log(r ? '(no matching decision in memory)' : '(memory unavailable: decide as usual)')
1186
+ return
1187
+ }
1188
+ // the closest few only, without Hindsight's "| Involving: …" suffix: small in the agent's context
1189
+ for (const e of results.slice(0, Number(opt.top || 6))) {
1190
+ const day = String(e.occurred_start || e.mentioned_at || '').slice(0, 10)
1191
+ console.log(`- ${day ? `(${day}) ` : ''}${String(e.text).replace(/\s*\|\s*Involving:.*$/s, '').replace(/\s+/g, ' ').trim()}`)
1192
+ }
1193
+ }
1194
+
1195
+ /** The owner answered in the chat (REQ-003 P1): his answers go into the cards, marked "qua chat", his words quoted. */
1196
+ async function cmdAnswer({ pos, opt }) {
1197
+ const cfg = loadConfig()
1198
+ const req = await findRequest(cfg, pos[0] ?? die('usage: kdev answer <REQ-NNN> --quote "<his message, verbatim>" --file answers.json ({cards:[{key,verdict?,note?,choices?:{q1:{selected:[…]}}}], questions?, approval?:{choice}})'))
1199
+ const quote = opt.quote ? readInput(opt.quote) : die('--quote is required: the owner\'s chat message, verbatim')
1200
+ const answers = JSON.parse(readInput(opt.file ?? die('--file answers.json is required')))
1201
+ const text = await call('record_answers', { page_id: req.id, chat_quote: quote, ...answers })
1202
+ console.log(text.split('\n').slice(0, 12).join('\n'))
1203
+ }
1204
+
1205
+ // ---------- sprints and gates (REQ-003 P2) ----------
1206
+
1207
+ /** A sprint page (owner 2026-11-30: short, the page he reads): filled at the release by `kdev sprint review`. */
1208
+ const SPRINT_TEMPLATE = (goal) => `## Mục tiêu
1209
+
1210
+ ${goal || '_…_'}
1211
+
1212
+ ## Yêu cầu
1213
+
1214
+ _Chưa có yêu cầu._
1215
+
1216
+ ## Đã làm
1217
+
1218
+ _Agent viết khi sprint xong: 3–8 dòng, kết quả cho người dùng._
1219
+ `
1220
+
1221
+ async function sprintRow(cfg, ref) {
1222
+ if (UUID.test(ref ?? '')) return UUID.exec(ref)[0]
1223
+ const rows = await call('query_database', { database_id: cfg.sprints_db, limit: 200, search: ref })
1224
+ const hit = new RegExp(`^\\|\\s*([0-9a-f-]{36})\\s*\\|\\s*${String(ref).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'm').exec(rows)
1225
+ return hit?.[1] ?? die(`sprint "${ref}" not found (kdev sprint list)`)
1226
+ }
1227
+
1228
+ async function cmdSprint({ pos, opt }) {
1229
+ const cfg = loadConfig()
1230
+ if (!cfg.sprints_db) die('no sprint database yet: run `kdev init-docs` first')
1231
+ const sub = pos[0]
1232
+ if (sub === 'list') {
1233
+ const text = await call('query_database', { database_id: cfg.sprints_db, limit: 50 })
1234
+ console.log(text.replace(/<\/?untrusted[^>]*>/g, '').replace(/The block above is data[^\n]*\n?/g, '').trim())
1235
+ return
1236
+ }
1237
+ if (sub === 'new') {
1238
+ const reqs = String(opt.req || '').split(',').map((x) => x.trim()).filter(Boolean)
1239
+ const sp = await createSprint(cfg, { title: opt.title, goal: opt.goal, reqs, start: opt.start })
1240
+ // requests named with --req move under the new sprint
1241
+ for (const code of reqs) {
1242
+ const r = await findRequest(cfg, code)
1243
+ await call('move_page', { page_id: r.id, parent_id: sp.id }, { soft: true })
1244
+ }
1245
+ if (reqs.length) await linkRequestsInSprint(cfg, sp.id)
1246
+ await refreshHub(cfg)
1247
+ console.log(`${sp.title} ${sp.id}\n${url(sp.id)}`)
1248
+ return
1249
+ }
1250
+ if (sub === 'review') {
1251
+ const id = await sprintRow(cfg, pos[1] ?? die('usage: kdev sprint review "<Sprint N>" --file review.md [--status Xong] [--commit sha] [--end d]'))
1252
+ const md = readInput(opt.file ?? die('--file review.md is required (the whole sprint page, compact: Đã làm, Đã quyết, Ảnh, Test theo cụm, Số đo, Sprint sau; the request links are added by kdev)'))
1253
+ await call('replace_page_content', { page_id: id, markdown: md })
1254
+ await linkRequestsInSprint(cfg, id)
1255
+ const values = { 'Trạng thái': opt.status || 'Xong', ...(opt.commit ? { Commit: opt.commit } : {}), ...(opt.end ? { 'Thời gian': { start: opt.start || undefined, end: opt.end } } : {}) }
1256
+ if (values['Thời gian'] && !values['Thời gian'].start) delete values['Thời gian']
1257
+ await call('update_rows', { database_id: cfg.sprints_db, updates: [{ row: id, values }] })
1258
+ await refreshHub(cfg)
1259
+ console.log(`review written | ${url(id)}`)
1260
+ return
1261
+ }
1262
+ if (sub === 'link') {
1263
+ // the "## Yêu cầu" list of one sprint (or all) from the request pages under it
1264
+ const rows = pos[1] ? [{ id: await sprintRow(cfg, pos[1]), title: pos[1] }] : await sprintRows(cfg)
1265
+ for (const r of rows) {
1266
+ await linkRequestsInSprint(cfg, r.id)
1267
+ console.log(`${r.title} linked | ${url(r.id)}`)
1268
+ }
1269
+ return
1270
+ }
1271
+ die('usage: kdev sprint new | review | link [S<n>] | list')
1272
+ }
1273
+
1274
+ /** A gate review page (G6 QA, G7 Release …): the checklist, then a Go / No-go decision card and an approval bar. */
1275
+ async function cmdGate({ pos, opt }) {
1276
+ const cfg = loadConfig()
1277
+ const gate = pos[0] === 'new' ? pos[1] : pos[0]
1278
+ if (!gate) die('usage: kdev gate new <G6|G7|…> --title "…" [--file checklist.md]')
1279
+ if (!cfg.gates_page) die('no gate page yet: run `kdev init-docs` first')
1280
+ const title = `${gate} · ${today()} · ${opt.title || 'Gate review'}`
1281
+ const body = opt.file ? readInput(opt.file) : '## Tiêu chí\n\n- [ ] …\n\n## Bằng chứng\n\n## Lỗi còn mở\n'
1282
+ const text = await call('create_page', { parent_id: cfg.gates_page, title, icon: '🚦', markdown: `${body}\n\n## Quyết định\n` })
1283
+ const id = /page_id ([0-9a-f-]{36})/.exec(text)?.[1] ?? die(`create_page: ${text.slice(0, 200)}`)
1284
+ const { list } = await blocks(id, 20000)
1285
+ const head = list.find((b) => b.type === 'heading' && b.text.trim() === 'Quyết định')?.id
1286
+ await call('add_cards', {
1287
+ page_id: id,
1288
+ ...(head ? { after_block_id: head } : {}),
1289
+ cards: [{ key: gate, title: `${gate}: Go / No-go`, questions: [{ id: 'go', text: `Qua ${gate}?`, kind: 'single', options: [{ id: 'go', label: 'Go', recommended: true }, { id: 'nogo', label: 'No-go: sửa tiếp' }] }] }],
1290
+ })
1291
+ console.log(`${title} ${id}\n${url(id)}`)
1292
+ }
1293
+
1294
+ /** Replace a project document page (design, dbdesign or any page id) with a Markdown file. */
1295
+ async function cmdDoc({ pos }) {
1296
+ const cfg = loadConfig()
1297
+ if (pos[0] !== 'set' || !pos[1] || !pos[2]) die('usage: kdev doc set <architecture|database|clusters|metrics|page_id> <file.md>')
1298
+ const named = {
1299
+ architecture: cfg.architecture_page ?? cfg.design_page,
1300
+ database: cfg.database_page ?? cfg.dbdesign_page,
1301
+ clusters: cfg.clusters_page,
1302
+ metrics: cfg.metrics_page,
1303
+ design: cfg.architecture_page ?? cfg.design_page,
1304
+ dbdesign: cfg.database_page ?? cfg.dbdesign_page,
1305
+ }
1306
+ const key = named[pos[1]] ?? (UUID.test(pos[1]) ? UUID.exec(pos[1])[0] : null)
1307
+ if (!key) die(`unknown document ${pos[1]} (run kdev init-docs, or give a page id)`)
1308
+ console.log((await call('replace_page_content', { page_id: key, markdown: readInput(pos[2]) })).split('\n')[0] + `\n${url(key)}`)
1309
+ }
1310
+
1311
+ /** Block ids from an insert_blocks result ("New block ids: a, b."); the last one is where to insert next. */
1312
+ const newBlockIds = (text) => (/New block ids: ([^.]*)\./.exec(text)?.[1] ?? '').split(',').map((x) => x.trim()).filter(Boolean)
1313
+
1314
+ /** Numbers from a vitest / jest style summary ("Tests 2 failed | 455 passed | 3 skipped (460)", "Duration 5.1s"). */
1315
+ function parseTestOutput(text) {
1316
+ const line = text.split('\n').reverse().find((l) => /^\s*Tests?\s/.test(l) && /passed|failed/.test(l)) ?? ''
1317
+ const n = (w) => Number(new RegExp(`(\\d+) ${w}`).exec(line)?.[1] ?? 0)
1318
+ const d = /Duration\s+([\d.]+)\s*(ms|s)\b/.exec(text)
1319
+ return { passed: n('passed'), failed: n('failed'), skipped: n('skipped'), durationMs: d ? Math.round(Number(d[1]) * (d[2] === 's' ? 1000 : 1)) : 0 }
1320
+ }
1321
+
1322
+ async function cmdTest({ pos, opt }) {
1323
+ const usage = 'usage: kdev test <REQ-NNN|page_id> --suite S (--from output.txt | --passed N [--failed N] [--skipped N]) [--duration ms] [--commit sha] [--card KEY] [--after block_id]'
1324
+ if (!pos[0] || !opt.suite) die(usage)
1325
+ const cfg = findConfig() ? loadConfig() : null
1326
+ const pageId = UUID.test(pos[0]) ? UUID.exec(pos[0])[0] : cfg ? await pageRef(cfg, pos[0]) : die(usage)
1327
+ const log = opt.from ? readFileSync(opt.from, 'utf8') : ''
1328
+ const parsed = log ? parseTestOutput(log) : { passed: 0, failed: 0, skipped: 0, durationMs: 0 }
1329
+ const num = (k, d) => (opt[k] !== undefined ? Number(opt[k]) : d)
1330
+ const t = {
1331
+ suite: opt.suite,
1332
+ passed: num('passed', parsed.passed),
1333
+ failed: num('failed', parsed.failed),
1334
+ skipped: num('skipped', parsed.skipped),
1335
+ durationMs: num('duration', parsed.durationMs),
1336
+ }
1337
+ if (opt.card) {
1338
+ const r = await call('resolve_cards', { page_id: pageId, updates: [{ key: opt.card, add_tests: [t] }] })
1339
+ console.log(r.split('\n')[0])
1340
+ return
1341
+ }
1342
+ const tail = log.length > 8000 ? log.slice(-8000) : log
1343
+ const r = await call('insert_blocks', {
1344
+ page_id: pageId,
1345
+ blocks: [{ type: 'testResult', props: { ...t, commit: opt.commit || '', at: new Date().toISOString(), log: tail } }],
1346
+ ...(opt.after ? { after_block_id: opt.after } : {}),
1347
+ })
1348
+ console.log(`${t.suite}: ${t.passed} passed, ${t.failed} failed, ${t.skipped} skipped\nblock ${newBlockIds(r).at(-1) ?? '?'}`)
1349
+ }
1350
+
1351
+ async function cmdLog({ pos, opt }) {
1352
+ const pageId = UUID.exec(pos[0] ?? '')?.[0] ?? die('usage: kdev log <page_id> <file|-> [--title "…"] [--lang text] [--max 6000] [--after block_id]')
1353
+ let text = readFileSync(pos[1] === '-' || !pos[1] ? 0 : pos[1], 'utf8')
1354
+ const max = Number(opt.max || 6000)
1355
+ if (text.length > max) text = `… (${text.length - max} characters cut; the end is kept)\n` + text.slice(-max)
1356
+ const out = []
1357
+ if (opt.title) out.push({ type: 'paragraph', text: `**${opt.title}**` })
1358
+ out.push({ type: 'codeBlock', text, language: opt.lang || 'text' })
1359
+ const r = await call('insert_blocks', { page_id: pageId, blocks: out, ...(opt.after ? { after_block_id: opt.after } : {}) })
1360
+ console.log(r.split('\n')[0])
1361
+ }
1362
+
1363
+ async function cmdRelease({ pos, opt }) {
1364
+ const cfg = loadConfig()
1365
+ if (pos[0] !== 'add') die('usage: kdev release add --sha <sha> --req REQ-001[,REQ-002] [--result ok|failed] [--backup name] [--note file.md]')
1366
+ const sha = opt.sha || die('--sha is required')
1367
+ const reqs = String(opt.req || '').split(',').map((s) => s.trim()).filter(Boolean)
1368
+ const row = {
1369
+ title: `${today()} · ${sha}`,
1370
+ values: {
1371
+ Ngày: today(),
1372
+ Commit: sha,
1373
+ ...(reqs.length ? { 'Yêu cầu': reqs } : {}),
1374
+ 'Kết quả': opt.result === 'failed' ? 'Lỗi, đã rollback' : 'Thành công',
1375
+ ...(opt.backup ? { Backup: opt.backup } : {}),
1376
+ },
1377
+ ...(opt.note ? { body_markdown: readInput(opt.note) } : {}),
1378
+ }
1379
+ const text = await call('add_rows', { database_id: cfg.releases_db, rows: [row] })
1380
+ console.log(text.split('\n')[0] + `\n${url(cfg.releases_page)}`)
1381
+ }
1382
+
1383
+ /** The hub page's "Đang mở" section: one page link per open request (the link shows the live icon = status). */
1384
+ const NO_SPRINT = '_Không có sprint nào đang chạy._'
1385
+
1386
+ /** The sprint shown on the project page: the running one (Đang chạy / Review), else the latest. */
1387
+ async function hubSprint(cfg) {
1388
+ if (!cfg.sprints_db) return null
1389
+ const j = await callJson('query_database', { database_id: cfg.sprints_db, limit: 200, properties: ['Trạng thái', 'Mục tiêu'] }, { soft: true })
1390
+ const num = (r) => Number(/\d+/.exec(r.title ?? '')?.[0] ?? 0)
1391
+ const rows = (j?.rows ?? []).sort((a, b) => num(b) - num(a))
1392
+ const running = rows.find((r) => ['Đang chạy', 'Review'].includes(r.values?.['Trạng thái']))
1393
+ return running ? { ...running, running: true } : rows[0] ? { ...rows[0], running: false } : null
1394
+ }
1395
+
1396
+ /** Replace the top-level blocks between a "## <title>" heading and the next heading. */
1397
+ async function replaceSection(pageId, list, title, fresh) {
1398
+ const head = list.find((b) => b.depth === 0 && b.type === 'heading' && b.text.trim().startsWith(title))
1399
+ if (!head) return false
1400
+ const old = []
1401
+ for (const b of list.slice(list.indexOf(head) + 1)) {
1402
+ if (b.depth === 0 && b.type === 'heading') break
1403
+ if (b.depth === 0) old.push(b.id)
1404
+ }
1405
+ await call('insert_blocks', { page_id: pageId, after_block_id: head.id, blocks: fresh })
1406
+ if (old.length) await call('delete_blocks', { page_id: pageId, block_ids: old })
1407
+ return true
1408
+ }
1409
+
1410
+ /** The project page's live sections: "Sprint hiện tại" (when the page has it) and "Đang mở". */
1411
+ async function refreshHub(cfg) {
1412
+ requestCache = null
1413
+ const open = (await allRequests(cfg)).filter((r) => OPEN_ICONS.has(r.icon))
1414
+ const { list } = await blocks(cfg.hub, 20000)
1415
+ if (list.some((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === 'Sprint hiện tại')) {
1416
+ const s = await hubSprint(cfg)
1417
+ const goal = s?.values?.['Mục tiêu']
1418
+ const fresh = !s
1419
+ ? [{ type: 'paragraph', text: NO_SPRINT }]
1420
+ : s.running
1421
+ ? [{ type: 'pageLink', props: { pageId: s.id } }, ...(goal ? [{ type: 'paragraph', text: `Mục tiêu: ${goal}` }] : [])]
1422
+ : [{ type: 'paragraph', text: `${NO_SPRINT} Gần nhất:` }, { type: 'pageLink', props: { pageId: s.id } }]
1423
+ await replaceSection(cfg.hub, list, 'Sprint hiện tại', fresh)
1424
+ }
1425
+ if (cfg.sprints_db && !list.some((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === 'Timeline sprint')) {
1426
+ const info = await call('get_database', { database_id: cfg.sprints_db })
1427
+ const view = /"Timeline" view_id=([0-9a-f-]{36})/.exec(info)?.[1] ?? ''
1428
+ const at = list.find((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === 'Lối tắt')
1429
+ await call('insert_blocks', {
1430
+ page_id: cfg.hub,
1431
+ ...(at ? { after_block_id: list[list.indexOf(at) - 1]?.id ?? at.id } : {}),
1432
+ blocks: [{ type: 'heading', level: 2, text: 'Timeline sprint' }, { type: 'databaseView', props: { databaseId: cfg.sprints_db, viewId: view } }],
1433
+ })
1434
+ }
1435
+ await replaceSection(cfg.hub, list, 'Đang mở', open.length
1436
+ ? open.map((r) => ({ type: 'pageLink', props: { pageId: r.id } }))
1437
+ : [{ type: 'paragraph', text: '_Không có yêu cầu nào đang mở._' }])
1438
+ }
1439
+
1440
+ async function cmdHub() {
1441
+ const cfg = loadConfig()
1442
+ await refreshHub(cfg)
1443
+ console.log(url(cfg.hub))
1444
+ }
1445
+
1446
+ async function cmdCall({ pos }) {
1447
+ const name = pos[0] ?? die('usage: kdev call <tool> [<json> | @file.json | -]')
1448
+ const args = pos[1] ? JSON.parse(readInput(pos[1])) : {}
1449
+ console.log(await call(name, args))
1450
+ }
1451
+
1452
+ const HELP = `kdev: Kicho devflow helper (skill kicho-devflow)
1453
+ init <project page> [--project Name] [--summary "…"] [--handbook id | --company id]
1454
+ the project page is the hub: its children + the company's 📘 Quy trình làm việc; writes ${CONFIG} here
1455
+ show sprints → their requests (status icons), then the inbox
1456
+ req new <spec.json> [--sprint S6|new] request page S5 · R6 · title inside the sprint (task rows only with "tasks": true)
1457
+ req adopt <R6> <spec.json> the owner's own page in the inbox → card page moved into the sprint
1458
+ req new <page.md> --title "…" Markdown page (old servers; {{REQ}} {{STATUS}} {{DATE}} filled in)
1459
+ req read <R5> [--all] [--since t] open cards only by default (compact get_review) + comments; --full = whole page
1460
+ req ack <REQ-NNN> "agent read at" on the approval bar
1461
+ req status <REQ-NNN> <status> ${Object.keys(REQ_STATUS).join(' | ')}: icon, header, hub list
1462
+ memory init | model check the shared decision bank / doraemon's "how the owner decides" summary
1463
+ remember "<decision>" [--kind …] [--source R5/T1] [--company] the owner's decision, one line (or --file items.json)
1464
+ recall "<question>" [--top 6] what he already decided (before asking him); fails open
1465
+ answer <REQ-NNN> --quote "…" --file answers.json the owner answered in the chat: record it in the cards ("qua chat")
1466
+ sprint new [--title S6] [--goal …] [--req R6] | sprint review S5 --file s5.md [--commit sha] [--end d]
1467
+ sprint link [S5] | sprint list keep the sprint page's request links and multi-select in step
1468
+ gate new <G6|G7|…> --title "…" [--file checklist.md] gate review page with a Go / No-go card
1469
+ doc set <architecture|database|clusters|metrics|page_id> <file.md> replace a project document page
1470
+ result new <R6> [--file r.md] [--cards next.json] [--done A,B] [--status S] child page "R6 · Kết quả N" (summary, decided, done, next questions); cards get status + link
1471
+ result link <R6> <A,B> [--round N] [--status S] point cards at a result page (default: the latest)
1472
+ result questions <R6> <next.json> [--round N] follow-up question cards + approval bar on the result page
1473
+ card resolve <REQ> <KEY>… [--status S] [--decided "…"|@file] old pages only: writes into the card
1474
+ card result <REQ> <KEY> --outcome done|changed|dropped|deferred [--summary @f] [--verification …] [--limits …] [--commit sha] [--dod all|"items"] [--dod-na "i18n=…"]
1475
+ evidence <REQ|page> <files…> [--card KEY] [--caption …] [--device phone] [--verdict pass] [--role before|after] [--ref F2] [--field Env=…] [--note …]
1476
+ test <REQ|page> --suite S (--from out.txt | --passed N --failed N) [--card KEY] [--commit sha]
1477
+ tasks add <rows.json> [--req REQ-NNN] add rows ([{title, values:{…}, body_markdown}]); status defaults to Chờ duyệt
1478
+ tasks set <row id|code>… [--req REQ-NNN] --status S [--agent A] [--commit sha] [--start d] [--end d]
1479
+ tasks list [--req REQ-NNN] [--status S]
1480
+ log <page_id> <file|-> [--title "…"] [--lang text] [--max 6000] text as a code block (end kept)
1481
+ release add --sha <sha> --req REQ-001[,…] [--result ok|failed] [--backup name] [--note file.md]
1482
+ hub refresh "Sprint hiện tại" and "Đang mở" on the project page
1483
+ call <tool> [<json>|@file|-] any Kicho MCP tool`
1484
+
1485
+ const [cmd, sub, ...rest] = process.argv.slice(2)
1486
+ const twoWord = {
1487
+ req: { new: cmdReqNew, adopt: cmdReqAdopt, status: cmdReqStatus, read: cmdReqRead, ack: cmdReqAck },
1488
+ tasks: { add: cmdTasksAdd, set: cmdTasksSet, list: cmdTasksList },
1489
+ card: { resolve: (a) => cmdCard(a, 'resolve'), result: (a) => cmdCard(a, 'result') },
1490
+ result: { new: cmdResultNew, link: cmdResultLink, questions: cmdResultQuestions },
1491
+ }
1492
+ const oneWord = { memory: cmdMemory, remember: cmdRemember, recall: cmdRecall, 'init-docs': cmdInitDocs, init: cmdInit, show: cmdShow, evidence: cmdEvidence, test: cmdTest, log: cmdLog, release: cmdRelease, hub: cmdHub, call: cmdCall, answer: cmdAnswer, sprint: cmdSprint, gate: cmdGate, doc: cmdDoc }
1493
+ try {
1494
+ if (twoWord[cmd]) {
1495
+ const fn = twoWord[cmd][sub] ?? die(`unknown: ${cmd} ${sub ?? ''}\n${HELP}`)
1496
+ await fn(parseArgs(rest))
1497
+ } else if (oneWord[cmd]) {
1498
+ await oneWord[cmd](parseArgs([sub, ...rest].filter((x) => x !== undefined)))
1499
+ } else {
1500
+ console.log(HELP)
1501
+ }
1502
+ } catch (e) {
1503
+ die(e?.message ?? String(e))
1504
+ }