sisyo 1.9.0 → 1.10.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.
- package/README.md +7 -3
- package/bin/known-hashes.json +22 -0
- package/package.json +1 -1
- package/templates/.claude/rules/decision-memory.md +40 -0
- package/templates/.claude/rules/docs.md +43 -10
- package/templates/.claude/skills/kicho-devflow/SKILL.md +185 -0
- package/templates/.claude/skills/kicho-devflow/kdev.mjs +1404 -0
- package/templates/.claude/skills/kicho-devflow/templates/handbook.md +32 -0
- package/templates/.claude/skills/kicho-devflow/templates/request.json +63 -0
- package/templates/.claude/skills/kicho-devflow/templates/request.md +57 -0
- package/templates/.claude/skills/vibe-docs/SKILL.md +103 -65
- package/templates/SISYO.md +9 -9
|
@@ -0,0 +1,1404 @@
|
|
|
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 = `${sprint ? `${sprint.title} · ` : ''}${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
|
+
'## Báo cáo',
|
|
484
|
+
'_Kết quả của từng mục nằm trong thẻ của mục đó; agent ghi tóm tắt phát hành ở đây._',
|
|
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 (await hasTool('list_comments')) console.log('\n' + (await call('list_comments', { page_id: req.id, include_resolved: !!opt.resolved })))
|
|
611
|
+
else console.log('\n(comments: this Kicho server has no list_comments tool yet; only the page body was read)')
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Tell the owner the answers were read: agentReadAt on the page's approval bar. */
|
|
615
|
+
async function cmdReqAck({ pos }) {
|
|
616
|
+
const cfg = loadConfig()
|
|
617
|
+
const req = await findRequest(cfg, pos[0] ?? die('usage: kdev req ack <REQ-NNN|page_id>'))
|
|
618
|
+
console.log((await call('resolve_cards', { page_id: req.id, mark_read: true, updates: [] })).split('\n')[0])
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** A page ref: a page id / URL, or a request id (REQ-007). */
|
|
622
|
+
async function pageRef(cfg, ref) {
|
|
623
|
+
if (UUID.test(ref ?? '')) return UUID.exec(ref)[0]
|
|
624
|
+
return (await findRequest(cfg, ref)).id
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** Definition of Done items: the project's list (.kicho-devflow.json "dod", else the default). --dod all | "item,item"
|
|
628
|
+
* (those done, the rest not), --dod-na "i18n=no new text" (not applicable: counted as done, with the note). */
|
|
629
|
+
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)']
|
|
630
|
+
function dodList(cfg, opt) {
|
|
631
|
+
if (!opt.dod && !opt['dod-na']) return null
|
|
632
|
+
const items = Array.isArray(cfg?.dod) && cfg.dod.length ? cfg.dod : DEFAULT_DOD
|
|
633
|
+
const listOf = (v) => many(v).flatMap((d) => String(d).split(',')).map((x) => x.trim()).filter(Boolean)
|
|
634
|
+
const done = opt.dod === 'all' ? items : listOf(opt.dod)
|
|
635
|
+
const na = listOf(opt['dod-na']).map((x) => x.split(/=(.*)/s)).map(([k, v]) => [k.trim().toLowerCase(), (v ?? 'không áp dụng').trim()])
|
|
636
|
+
const starts = (item, key) => item.toLowerCase().startsWith(String(key).toLowerCase())
|
|
637
|
+
return items.map((item) => {
|
|
638
|
+
const n = na.find(([k]) => starts(item, k))
|
|
639
|
+
if (n) return { item, done: true, note: n[1] }
|
|
640
|
+
return { item, done: done.some((d) => starts(item, d)) }
|
|
641
|
+
})
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** The sprint being run (status Đang chạy, newest first), for new task rows; null without a sprint database. */
|
|
645
|
+
|
|
646
|
+
async function cmdCard({ pos, opt }, sub) {
|
|
647
|
+
const cfg = loadConfig()
|
|
648
|
+
const pageId = await pageRef(cfg, pos[0] ?? die('usage: kdev card resolve|result <REQ-NNN> <KEY>… (see help)'))
|
|
649
|
+
let updates
|
|
650
|
+
if (sub === 'resolve') {
|
|
651
|
+
if (opt.file) updates = JSON.parse(readInput(opt.file)) // [{ key, status?, decided? }]
|
|
652
|
+
else {
|
|
653
|
+
const keys = pos.slice(1)
|
|
654
|
+
if (!keys.length) die('usage: kdev card resolve <REQ> <KEY>… [--status S] [--decided "…"|@file] | --file decisions.json')
|
|
655
|
+
updates = keys.map((key) => ({ key: String(key).replace(/^R\d+-/, ''), ...(opt.status ? { status: opt.status } : {}), ...(opt.decided ? { decided: readInput(opt.decided) } : {}) }))
|
|
656
|
+
}
|
|
657
|
+
} else {
|
|
658
|
+
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]')
|
|
659
|
+
const result = { outcome: opt.outcome || 'done' }
|
|
660
|
+
for (const k of ['summary', 'verification', 'limits']) if (opt[k]) result[k] = readInput(opt[k])
|
|
661
|
+
if (opt.commit) result.commit = opt.commit
|
|
662
|
+
const dod = dodList(cfg, opt)
|
|
663
|
+
if (dod) result.dod = dod
|
|
664
|
+
const status = opt.status || { done: 'done', changed: 'done', dropped: 'dropped', deferred: 'later' }[result.outcome]
|
|
665
|
+
updates = [{ key, result, ...(status ? { status } : {}) }]
|
|
666
|
+
}
|
|
667
|
+
console.log((await call('resolve_cards', { page_id: pageId, updates })).split('\n').slice(0, 3).join('\n'))
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function rowValues(opt) {
|
|
671
|
+
const v = {}
|
|
672
|
+
if (opt.status) v['Trạng thái'] = opt.status
|
|
673
|
+
if (opt.agent) v.Agent = opt.agent
|
|
674
|
+
if (opt.commit) v.Commit = opt.commit
|
|
675
|
+
if (opt.req) v['Yêu cầu'] = opt.req
|
|
676
|
+
if (opt.area) v['Hạng mục'] = opt.area
|
|
677
|
+
if (opt.start || opt.end) v['Thời gian'] = { start: opt.start || today(), ...(opt.end ? { end: opt.end } : {}) }
|
|
678
|
+
return v
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
async function cmdTasksAdd({ pos, opt }) {
|
|
682
|
+
const cfg = loadConfig()
|
|
683
|
+
const rows = JSON.parse(readInput(pos[0] ?? die('usage: kdev tasks add <rows.json> [--req REQ-NNN]')))
|
|
684
|
+
for (const r of rows) {
|
|
685
|
+
r.values ??= {}
|
|
686
|
+
if (opt.req && !r.values['Yêu cầu']) r.values['Yêu cầu'] = opt.req
|
|
687
|
+
if (!r.values['Trạng thái']) r.values['Trạng thái'] = opt.status || 'Chờ duyệt'
|
|
688
|
+
}
|
|
689
|
+
for (let i = 0; i < rows.length; i += 100) {
|
|
690
|
+
const text = await call('add_rows', { database_id: cfg.tasks_db, rows: rows.slice(i, i + 100) })
|
|
691
|
+
console.log(text.split('\n')[0])
|
|
692
|
+
}
|
|
693
|
+
console.log(url(cfg.tasks_page))
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/** Row refs: row ids stay; an item code ("F2", "R10") becomes the id of the row titled "F2 · …" (with --req, in that
|
|
697
|
+
* request); anything else is passed as an exact title. (query_database shortens long titles, so codes beat titles.) */
|
|
698
|
+
async function resolveRows(cfg, refs, req) {
|
|
699
|
+
let table = null
|
|
700
|
+
const out = []
|
|
701
|
+
for (const ref of refs) {
|
|
702
|
+
if (UUID.test(ref)) {
|
|
703
|
+
out.push(UUID.exec(ref)[0])
|
|
704
|
+
continue
|
|
705
|
+
}
|
|
706
|
+
if (/^(?:R\d+-)?[A-Za-z]{1,3}\d{0,3}$/.test(ref)) {
|
|
707
|
+
const code0 = req && /^R\d+$/.test(req) && !/^R\d+-/.test(ref) ? `${req}-${ref}` : ref
|
|
708
|
+
const j = await callJson('query_database', {
|
|
709
|
+
database_id: cfg.tasks_db,
|
|
710
|
+
limit: 5,
|
|
711
|
+
properties: [],
|
|
712
|
+
title_starts_with: `${code0} · `,
|
|
713
|
+
...(req ? { filters: [{ property: 'Yêu cầu', operator: 'is', value: req }] } : {}),
|
|
714
|
+
}, { soft: true })
|
|
715
|
+
if (j?.rows) {
|
|
716
|
+
if (j.rows.length === 1) {
|
|
717
|
+
out.push(j.rows[0].id)
|
|
718
|
+
continue
|
|
719
|
+
}
|
|
720
|
+
if (j.rows.length > 1) die(`${ref} matches ${j.rows.length} rows: add --req R…`)
|
|
721
|
+
}
|
|
722
|
+
table ??= await call('query_database', {
|
|
723
|
+
database_id: cfg.tasks_db,
|
|
724
|
+
limit: 200,
|
|
725
|
+
...(req ? { filters: [{ property: 'Yêu cầu', operator: 'is', value: req }] } : {}),
|
|
726
|
+
})
|
|
727
|
+
const code = req && /^R\d+$/.test(req) && !/^R\d+-/.test(ref) ? `${req}-${ref}` : ref
|
|
728
|
+
const hits = [...table.matchAll(new RegExp(`^\\|\\s*([0-9a-f-]{36})\\s*\\|\\s*${code} · `, 'gm'))].map((m) => m[1])
|
|
729
|
+
if (hits.length === 1) {
|
|
730
|
+
out.push(hits[0])
|
|
731
|
+
continue
|
|
732
|
+
}
|
|
733
|
+
if (hits.length > 1) die(`${ref} matches ${hits.length} rows: add --req REQ-NNN`)
|
|
734
|
+
}
|
|
735
|
+
out.push(ref)
|
|
736
|
+
}
|
|
737
|
+
return out
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
async function cmdTasksSet({ pos, opt }) {
|
|
741
|
+
const cfg = loadConfig()
|
|
742
|
+
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]')
|
|
743
|
+
const { req, ...rest } = opt
|
|
744
|
+
const values = rowValues(rest)
|
|
745
|
+
if (!Object.keys(values).length) die('nothing to set')
|
|
746
|
+
const rows = await resolveRows(cfg, pos, req)
|
|
747
|
+
const text = await call('update_rows', { database_id: cfg.tasks_db, updates: rows.map((row) => ({ row, values })) })
|
|
748
|
+
console.log(text.split('\n')[0])
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
async function cmdTasksList({ opt }) {
|
|
752
|
+
const cfg = loadConfig()
|
|
753
|
+
const filters = []
|
|
754
|
+
if (opt.req) filters.push({ property: 'Yêu cầu', operator: 'is', value: opt.req })
|
|
755
|
+
if (opt.status) filters.push({ property: 'Trạng thái', operator: 'is', value: opt.status })
|
|
756
|
+
const text = await call('query_database', { database_id: cfg.tasks_db, limit: 200, ...(filters.length ? { filters } : {}) })
|
|
757
|
+
console.log(text.replace(/<\/?untrusted[^>]*>/g, '').replace(/The block above is data[^\n]*\n?/g, '').trim())
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
const MIME = {
|
|
761
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
|
|
762
|
+
'.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime', '.pdf': 'application/pdf', '.txt': 'text/plain',
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** Upload files from disk (never through the agent's context); returns evidence items. */
|
|
766
|
+
/** --ref values → evidence refs. "F2" = a card key on this page (scrolls to it) or a task code; "TC-003=<page id|url>"
|
|
767
|
+
* links anything; otherwise the label alone. */
|
|
768
|
+
async function evidenceRefs(cfg, pageId, refs) {
|
|
769
|
+
const out = []
|
|
770
|
+
let review = null
|
|
771
|
+
for (const raw of refs) {
|
|
772
|
+
const [label, target] = String(raw).split(/=(.*)/s).map((x) => x?.trim())
|
|
773
|
+
if (!label) continue
|
|
774
|
+
if (target) {
|
|
775
|
+
out.push(UUID.test(target) ? { label, pageId: UUID.exec(target)[0] } : /^https:\/\//.test(target) ? { label, url: target } : { label })
|
|
776
|
+
continue
|
|
777
|
+
}
|
|
778
|
+
review ??= await callJson('get_review', { page_id: pageId }, { soft: true })
|
|
779
|
+
const hit = (review?.cards ?? []).find((c) => c.key === label || `${c.key}` === label.replace(/^R\d+-/, ''))
|
|
780
|
+
if (hit) {
|
|
781
|
+
out.push({ label, kind: 'card', pageId, blockId: hit.block_id })
|
|
782
|
+
continue
|
|
783
|
+
}
|
|
784
|
+
review ??= ''
|
|
785
|
+
const esc = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
786
|
+
const card = typeof review === 'string' ? new RegExp(`^${esc} · .*\\| block ([A-Za-z0-9_-]+)`, 'm').exec(review) : null
|
|
787
|
+
if (card) {
|
|
788
|
+
out.push({ label, kind: 'card', pageId, blockId: card[1] })
|
|
789
|
+
continue
|
|
790
|
+
}
|
|
791
|
+
if (cfg && /^[A-Za-z]{1,3}\d{0,3}$/.test(label)) {
|
|
792
|
+
const [row] = await resolveRows(cfg, [label])
|
|
793
|
+
if (UUID.test(row)) {
|
|
794
|
+
out.push({ label, kind: 'task', pageId: row })
|
|
795
|
+
continue
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
out.push({ label })
|
|
799
|
+
}
|
|
800
|
+
return out
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** --field "Env=staging" (repeatable) → [{label, value}] */
|
|
804
|
+
const evidenceFields = (opt) =>
|
|
805
|
+
many(opt.field)
|
|
806
|
+
.map((f) => String(f).split(/=(.*)/s))
|
|
807
|
+
.filter(([k]) => k?.trim())
|
|
808
|
+
.map(([k, v]) => ({ label: k.trim(), value: (v ?? '').trim() }))
|
|
809
|
+
|
|
810
|
+
async function uploadAll(pageId, files, opt, extras = {}) {
|
|
811
|
+
if (!(await hasTool('upload_file'))) die('this Kicho server has no upload_file tool yet; use `kdev log` for text evidence')
|
|
812
|
+
const items = []
|
|
813
|
+
for (const f of files) {
|
|
814
|
+
const data = readFileSync(f)
|
|
815
|
+
const mime = MIME[path.extname(f).toLowerCase()] ?? 'application/octet-stream'
|
|
816
|
+
const up = await callJson('upload_file', { page_id: pageId, filename: path.basename(f), mime, data_base64: data.toString('base64') })
|
|
817
|
+
const fileUrl = up?.url ?? die('upload_file gave no url')
|
|
818
|
+
const caption = files.length === 1 && opt.caption ? opt.caption : opt.caption ? `${opt.caption} · ${path.basename(f)}` : path.basename(f)
|
|
819
|
+
items.push({
|
|
820
|
+
url: fileUrl,
|
|
821
|
+
kind: mime.startsWith('image/') ? 'image' : mime.startsWith('video/') ? 'video' : 'file',
|
|
822
|
+
caption,
|
|
823
|
+
...(opt.device ? { device: opt.device } : {}),
|
|
824
|
+
...(opt.verdict ? { verdict: opt.verdict } : {}),
|
|
825
|
+
...(opt.role ? { role: opt.role } : {}),
|
|
826
|
+
...extras,
|
|
827
|
+
})
|
|
828
|
+
console.log(`${path.basename(f)} → ${fileUrl}`)
|
|
829
|
+
}
|
|
830
|
+
return items
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
async function cmdEvidence({ pos, opt }) {
|
|
834
|
+
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]'
|
|
835
|
+
const files = pos.slice(1)
|
|
836
|
+
if (!pos[0] || !files.length) die(usage)
|
|
837
|
+
const cfg = findConfig() ? loadConfig() : null
|
|
838
|
+
const pageId = UUID.test(pos[0]) ? UUID.exec(pos[0])[0] : cfg ? await pageRef(cfg, pos[0]) : die(usage)
|
|
839
|
+
const refs = await evidenceRefs(cfg, pageId, many(opt.ref))
|
|
840
|
+
const fields = evidenceFields(opt)
|
|
841
|
+
const extras = {
|
|
842
|
+
...(refs.length ? { refs } : {}),
|
|
843
|
+
...(fields.length ? { fields } : {}),
|
|
844
|
+
...(opt.note ? { note: readInput(opt.note) } : {}),
|
|
845
|
+
...(opt.run ? { runRef: opt.run } : {}),
|
|
846
|
+
}
|
|
847
|
+
const items = await uploadAll(pageId, files, opt, extras)
|
|
848
|
+
if (opt.card) {
|
|
849
|
+
// inside the card's result (resolve_cards appends)
|
|
850
|
+
const r = await call('resolve_cards', { page_id: pageId, updates: [{ key: opt.card, add_evidence: items }] })
|
|
851
|
+
console.log(r.split('\n')[0])
|
|
852
|
+
return
|
|
853
|
+
}
|
|
854
|
+
const layout = items.some((i) => i.role) ? 'compare' : 'grid'
|
|
855
|
+
const r = await call('insert_blocks', {
|
|
856
|
+
page_id: pageId,
|
|
857
|
+
blocks: [{ type: 'evidence', props: { title: opt.title || '', layout, items } }],
|
|
858
|
+
...(opt.after ? { after_block_id: opt.after } : {}),
|
|
859
|
+
})
|
|
860
|
+
console.log(`${r.split('\n')[0].replace(/ New block ids:.*/, '')}\nblock ${newBlockIds(r).at(-1) ?? '?'}`)
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
// ---------- project documents, sprints, gates (REQ-003 P2 / P3): kdev init-docs ----------
|
|
864
|
+
|
|
865
|
+
const hasProp = (info, name) => new RegExp(`^- ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\(`, 'm').test(info)
|
|
866
|
+
|
|
867
|
+
/** Two-way relation from db `from` (property `name`) to db `to` (paired property `paired`), unless it exists. */
|
|
868
|
+
async function ensureRelation(from, name, to, paired) {
|
|
869
|
+
const info = await call('get_database', { database_id: from })
|
|
870
|
+
if (hasProp(info, name)) return 'kept'
|
|
871
|
+
const r = await call('add_property', { database_id: from, name, type: 'relation', target_database: to, two_way: true, paired_name: paired }, { soft: true })
|
|
872
|
+
return r ? 'added' : 'FAILED (server without relations?)'
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
async function ensureRollup(db, name, relation, fn) {
|
|
876
|
+
const info = await call('get_database', { database_id: db })
|
|
877
|
+
if (hasProp(info, name)) return 'kept'
|
|
878
|
+
const r = await call('add_property', { database_id: db, name, type: 'rollup', relation, function: fn }, { soft: true })
|
|
879
|
+
return r ? 'added' : 'FAILED'
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** The project documents (📚 Tài liệu dự án): [config key, icon, title, what goes in]. Short pages, overview first. */
|
|
883
|
+
const DOC_PAGES = [
|
|
884
|
+
['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`)._'],
|
|
885
|
+
['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`)._'],
|
|
886
|
+
['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`)._'],
|
|
887
|
+
['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`)._'],
|
|
888
|
+
]
|
|
889
|
+
|
|
890
|
+
async function cmdInitDocs() {
|
|
891
|
+
const cfgFile = findConfig() ?? die(`no ${CONFIG}: run kdev init first`)
|
|
892
|
+
const cfg = loadConfig()
|
|
893
|
+
const ids = { ...cfg }
|
|
894
|
+
delete ids.file
|
|
895
|
+
const sprints = await ensureDatabase(cfg.hub, '🏃', 'Sprint', async (db) => {
|
|
896
|
+
await call('add_property', { database_id: db, name: 'Trạng thái', type: 'status', show_on_cards: true, options: [
|
|
897
|
+
{ name: 'Lên kế hoạch', color: 'grey', group: 'todo' }, { name: 'Đang chạy', color: 'orange', group: 'in_progress' },
|
|
898
|
+
{ name: 'Review', color: 'purple', group: 'in_progress' }, { name: 'Xong', color: 'green', group: 'complete' }] })
|
|
899
|
+
await call('add_property', { database_id: db, name: 'Mục tiêu', type: 'text', show_on_cards: true })
|
|
900
|
+
await call('add_property', { database_id: db, name: 'Thời gian', type: 'date', show_on_cards: true })
|
|
901
|
+
await call('add_property', { database_id: db, name: 'Yêu cầu', type: 'multi_select', options: [], show_on_cards: true })
|
|
902
|
+
await call('add_property', { database_id: db, name: 'Commit', type: 'text', show_on_cards: false })
|
|
903
|
+
await call('add_view', { database_id: db, type: 'timeline', name: 'Timeline', date_property: 'Thời gian' })
|
|
904
|
+
})
|
|
905
|
+
ids.sprints_page = sprints.pageId
|
|
906
|
+
ids.sprints_db = sprints.databaseId
|
|
907
|
+
ids.gates_page = await ensurePage(cfg.hub, '🚦', 'Cột mốc',
|
|
908
|
+
'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.')
|
|
909
|
+
ids.docs_page = await ensurePage(cfg.hub, '📚', 'Tài liệu dự án',
|
|
910
|
+
'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.')
|
|
911
|
+
// four short pages for people (owner 2026-11-30): what the system is, why, how it is tested, what improved
|
|
912
|
+
for (const [key, icon, title, hint] of DOC_PAGES) ids[key] ??= await ensurePage(ids.docs_page, icon, title, hint)
|
|
913
|
+
// the hub: links to the new pages + "Cài đặt dự án" (evidence fields of this project, Definition of Done)
|
|
914
|
+
const { raw, list } = await blocks(cfg.hub, 30000)
|
|
915
|
+
const links = [ids.sprints_page, ids.gates_page, ids.docs_page].filter((p) => !raw.includes(`page ${p}`))
|
|
916
|
+
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' } : {}) })
|
|
917
|
+
if (!list.some((b) => b.type === 'heading' && /Cài đặt dự án/.test(b.text))) {
|
|
918
|
+
await call('insert_blocks', {
|
|
919
|
+
page_id: cfg.hub,
|
|
920
|
+
markdown: `## Cài đặt dự án
|
|
921
|
+
|
|
922
|
+
**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.
|
|
923
|
+
|
|
924
|
+
| Trường | Khi nào ghi |
|
|
925
|
+
|---|---|
|
|
926
|
+
| | |
|
|
927
|
+
|
|
928
|
+
**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.`,
|
|
929
|
+
})
|
|
930
|
+
}
|
|
931
|
+
writeFileSync(cfgFile, JSON.stringify(ids, null, 2) + '\n')
|
|
932
|
+
for (const k of ['sprints_db', 'gates_page', 'docs_page', ...DOC_PAGES.map((d) => d[0])]) console.log(`${k} ${ids[k]}`)
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// ---------- decision memory: Hindsight (REQ-004 B3) ----------
|
|
936
|
+
// The owner decides for every agent, so his decisions live in ONE bank shared with doraemon (Paperclip): the company
|
|
937
|
+
// bank named in .kicho-devflow.json "memory_bank" (never written in a public repo). Its conventions are doraemon's:
|
|
938
|
+
// each record carries exactly one project tag — `project:<memory_project>` for this project, `project:cong-ty` for
|
|
939
|
+
// company-wide rules — and kdev reads only those two (other projects' memories, e.g. clients under NDA, never come
|
|
940
|
+
// in). Records are one line, word for word (strategy verbatim-record, no LLM): kind board-decision / board-order for
|
|
941
|
+
// the owner's decisions, project-change for an agent's record of what went live. The bank's missions, config and
|
|
942
|
+
// mental models belong to doraemon's plugin: kdev never changes them. URL + key per machine: HINDSIGHT_URL /
|
|
943
|
+
// HINDSIGHT_API_KEY, else ~/.config/kicho/hindsight.env. Recall fails open.
|
|
944
|
+
|
|
945
|
+
function memoryEnv() {
|
|
946
|
+
const env = { url: process.env.HINDSIGHT_URL, key: process.env.HINDSIGHT_API_KEY }
|
|
947
|
+
const f = path.join(homedir(), '.config', 'kicho', 'hindsight.env')
|
|
948
|
+
if ((!env.url || !env.key) && existsSync(f)) {
|
|
949
|
+
for (const line of readFileSync(f, 'utf8').split('\n')) {
|
|
950
|
+
const m = /^\s*(HINDSIGHT_URL|HINDSIGHT_API_KEY)\s*=\s*(.*)\s*$/.exec(line)
|
|
951
|
+
if (m && m[1] === 'HINDSIGHT_URL') env.url ??= m[2]
|
|
952
|
+
if (m && m[1] === 'HINDSIGHT_API_KEY') env.key ??= m[2]
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
return env
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
const COMPANY_TAG = 'project:cong-ty'
|
|
959
|
+
const memoryBank = (cfg) => cfg.memory_bank || die(`no "memory_bank" in ${CONFIG}: the shared decision bank (see the skill)`)
|
|
960
|
+
const memoryProject = (cfg) => `project:${cfg.memory_project || String(cfg.project || 'project').toLowerCase().replace(/[^a-z0-9-]+/g, '-')}`
|
|
961
|
+
|
|
962
|
+
/** macOS: a process that no GUI app is responsible for (VS Code Remote-SSH's server, launchd jobs) cannot be granted
|
|
963
|
+
* Local Network access (System Settings lists only apps), so Node's fetch to a LAN address fails with EHOSTUNREACH,
|
|
964
|
+
* while Apple's own /usr/bin/curl is allowed. Same request through curl; the key and the body go through stdin
|
|
965
|
+
* (curl -K -), never the command line. Returns {status, text}. */
|
|
966
|
+
function curlRequest(method, full, key, body, timeoutMs) {
|
|
967
|
+
const q = (v) => `"${String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
|
|
968
|
+
const cfg = [
|
|
969
|
+
`url = ${q(full)}`,
|
|
970
|
+
`request = ${q(method)}`,
|
|
971
|
+
`header = ${q(`Authorization: Bearer ${key}`)}`,
|
|
972
|
+
...(body ? [`header = ${q('Content-Type: application/json')}`, `data-binary = ${q(JSON.stringify(body))}`] : []),
|
|
973
|
+
].join('\n')
|
|
974
|
+
const out = execFileSync('/usr/bin/curl', ['-sS', '--max-time', String(Math.ceil(timeoutMs / 1000)), '-w', '\n%{http_code}', '-K', '-'], {
|
|
975
|
+
input: cfg + '\n',
|
|
976
|
+
encoding: 'utf8',
|
|
977
|
+
maxBuffer: 32 << 20,
|
|
978
|
+
timeout: timeoutMs + 2000,
|
|
979
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
980
|
+
})
|
|
981
|
+
const cut = out.lastIndexOf('\n')
|
|
982
|
+
return { status: Number(out.slice(cut + 1)), text: out.slice(0, cut) }
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
const LAN_BLOCKED = new Set(['EHOSTUNREACH', 'ENETUNREACH'])
|
|
986
|
+
|
|
987
|
+
async function hindsight(method, pathPart, body, { soft = false, timeoutMs = 8000 } = {}) {
|
|
988
|
+
const { url, key } = memoryEnv()
|
|
989
|
+
if (!url || !key) {
|
|
990
|
+
if (soft) return null
|
|
991
|
+
die('no Hindsight URL / key: set HINDSIGHT_URL + HINDSIGHT_API_KEY or ~/.config/kicho/hindsight.env')
|
|
992
|
+
}
|
|
993
|
+
const full = `${url.replace(/\/$/, '')}${pathPart}`
|
|
994
|
+
let status, text
|
|
995
|
+
try {
|
|
996
|
+
try {
|
|
997
|
+
const res = await fetch(full, {
|
|
998
|
+
method,
|
|
999
|
+
headers: { Authorization: `Bearer ${key}`, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
1000
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
1001
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
1002
|
+
})
|
|
1003
|
+
status = res.status
|
|
1004
|
+
text = await res.text()
|
|
1005
|
+
} catch (e) {
|
|
1006
|
+
if (!(process.platform === 'darwin' && LAN_BLOCKED.has(e?.cause?.code) && existsSync('/usr/bin/curl'))) throw e
|
|
1007
|
+
;({ status, text } = curlRequest(method, full, key, body, timeoutMs))
|
|
1008
|
+
}
|
|
1009
|
+
if (!(status >= 200 && status < 300)) {
|
|
1010
|
+
if (soft) return null
|
|
1011
|
+
return { httpStatus: status, text }
|
|
1012
|
+
}
|
|
1013
|
+
return text ? JSON.parse(text) : {}
|
|
1014
|
+
} catch (e) {
|
|
1015
|
+
if (soft) return null
|
|
1016
|
+
die(`Hindsight unreachable: ${e?.message ?? e}`)
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
const bankPath = (cfg) => `/v1/default/banks/${encodeURIComponent(memoryBank(cfg))}`
|
|
1021
|
+
|
|
1022
|
+
async function cmdMemory({ pos }) {
|
|
1023
|
+
const cfg = loadConfig()
|
|
1024
|
+
const sub = pos[0]
|
|
1025
|
+
if (sub === 'init') {
|
|
1026
|
+
const r = await hindsight('GET', '/v1/default/banks?limit=1000')
|
|
1027
|
+
const ok = (r?.banks ?? []).some((b) => b.bank_id === memoryBank(cfg))
|
|
1028
|
+
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)')
|
|
1029
|
+
return
|
|
1030
|
+
}
|
|
1031
|
+
if (sub === 'model') {
|
|
1032
|
+
// doraemon's summary of how the owner decides (company-wide), read only
|
|
1033
|
+
const m = await hindsight('GET', `${bankPath(cfg)}/mental-models/operator-working-style?detail=content`, null, { soft: true })
|
|
1034
|
+
console.log(m?.content && !/^Generating content/.test(m.content) ? m.content : '(no summary yet)')
|
|
1035
|
+
return
|
|
1036
|
+
}
|
|
1037
|
+
die('usage: kdev memory init | model')
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
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' }
|
|
1041
|
+
|
|
1042
|
+
/** One decision of the owner (one line, ≤ 300 characters). --company for a rule that applies to every project.
|
|
1043
|
+
* --file items.json for many: [{text, kind?, source?, company?, id?, date?}]. The same id replaces a record. */
|
|
1044
|
+
async function cmdRemember({ pos, opt }) {
|
|
1045
|
+
const cfg = loadConfig()
|
|
1046
|
+
const list = opt.file
|
|
1047
|
+
? JSON.parse(readInput(opt.file))
|
|
1048
|
+
: [{ 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 }]
|
|
1049
|
+
const items = list.map((x) => {
|
|
1050
|
+
const kind = KIND_MAP[x.kind || 'owner-decision'] ?? die(`unknown kind ${x.kind}`)
|
|
1051
|
+
const text = String(x.text).trim()
|
|
1052
|
+
if (text.length > 300) die(`a record is one line of at most 300 characters (${text.length}): ${text.slice(0, 60)}…`)
|
|
1053
|
+
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)}…`)
|
|
1054
|
+
const project = x.company ? COMPANY_TAG : memoryProject(cfg)
|
|
1055
|
+
const day = x.date || today()
|
|
1056
|
+
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"
|
|
1057
|
+
return {
|
|
1058
|
+
content: text,
|
|
1059
|
+
context: `[Kicho devflow${x.source ? `, ${x.source}` : ''}] ${who}${kind === 'project-change' ? '' : ' (the Board = the owner, anh)'}.`.slice(0, 380),
|
|
1060
|
+
timestamp: `${day}T12:00:00Z`,
|
|
1061
|
+
document_id: `kicho-devflow:${x.id || `${kind}:${createHash('sha1').update(text).digest('hex').slice(0, 16)}`}`,
|
|
1062
|
+
tags: ['source:kicho-devflow', `kind:${kind}`, project, ...(x.source ? [`ref:${x.source}`] : [])],
|
|
1063
|
+
metadata: { kind, source: 'kicho-devflow', project: project.slice('project:'.length), ...(x.source ? { ref: x.source } : {}) },
|
|
1064
|
+
strategy: 'verbatim-record',
|
|
1065
|
+
}
|
|
1066
|
+
})
|
|
1067
|
+
for (let i = 0; i < items.length; i += 50) {
|
|
1068
|
+
let r = await hindsight('POST', `${bankPath(cfg)}/memories`, { items: items.slice(i, i + 50), async: true })
|
|
1069
|
+
// a bank configured before the strategy existed: store them the old way
|
|
1070
|
+
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 })
|
|
1071
|
+
if (r?.httpStatus) die(`Hindsight POST /memories: HTTP ${r.httpStatus} ${r.text.slice(0, 200)}`)
|
|
1072
|
+
}
|
|
1073
|
+
const company = items.filter((x) => x.tags.includes(COMPANY_TAG)).length
|
|
1074
|
+
console.log(`remembered ${items.length} record(s) (${items.length - company} ${memoryProject(cfg)}, ${company} ${COMPANY_TAG}); searchable in a minute`)
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
/** What the owner already decided about something (before asking him): this project + company-wide only. */
|
|
1078
|
+
async function cmdRecall({ pos, opt }) {
|
|
1079
|
+
const cfg = loadConfig()
|
|
1080
|
+
const query = pos.join(' ').slice(0, 700) || die('usage: kdev recall "<what you are about to ask / decide>" [--top 6]')
|
|
1081
|
+
const r = await hindsight(
|
|
1082
|
+
'POST',
|
|
1083
|
+
`${bankPath(cfg)}/memories/recall`,
|
|
1084
|
+
{ query, budget: 'mid', max_tokens: Number(opt.max || 800), types: ['world', 'experience'], tag_groups: [{ tags: [memoryProject(cfg), COMPANY_TAG], match: 'any_strict' }] },
|
|
1085
|
+
{ soft: true, timeoutMs: 6000 },
|
|
1086
|
+
)
|
|
1087
|
+
const results = Array.isArray(r?.results) ? r.results : []
|
|
1088
|
+
if (!results.length) {
|
|
1089
|
+
console.log(r ? '(no matching decision in memory)' : '(memory unavailable: decide as usual)')
|
|
1090
|
+
return
|
|
1091
|
+
}
|
|
1092
|
+
// the closest few only, without Hindsight's "| Involving: …" suffix: small in the agent's context
|
|
1093
|
+
for (const e of results.slice(0, Number(opt.top || 6))) {
|
|
1094
|
+
const day = String(e.occurred_start || e.mentioned_at || '').slice(0, 10)
|
|
1095
|
+
console.log(`- ${day ? `(${day}) ` : ''}${String(e.text).replace(/\s*\|\s*Involving:.*$/s, '').replace(/\s+/g, ' ').trim()}`)
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/** The owner answered in the chat (REQ-003 P1): his answers go into the cards, marked "qua chat", his words quoted. */
|
|
1100
|
+
async function cmdAnswer({ pos, opt }) {
|
|
1101
|
+
const cfg = loadConfig()
|
|
1102
|
+
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}})'))
|
|
1103
|
+
const quote = opt.quote ? readInput(opt.quote) : die('--quote is required: the owner\'s chat message, verbatim')
|
|
1104
|
+
const answers = JSON.parse(readInput(opt.file ?? die('--file answers.json is required')))
|
|
1105
|
+
const text = await call('record_answers', { page_id: req.id, chat_quote: quote, ...answers })
|
|
1106
|
+
console.log(text.split('\n').slice(0, 12).join('\n'))
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// ---------- sprints and gates (REQ-003 P2) ----------
|
|
1110
|
+
|
|
1111
|
+
/** A sprint page (owner 2026-11-30: short, the page he reads): filled at the release by `kdev sprint review`. */
|
|
1112
|
+
const SPRINT_TEMPLATE = (goal) => `## Mục tiêu
|
|
1113
|
+
|
|
1114
|
+
${goal || '_…_'}
|
|
1115
|
+
|
|
1116
|
+
## Yêu cầu
|
|
1117
|
+
|
|
1118
|
+
_Chưa có yêu cầu._
|
|
1119
|
+
|
|
1120
|
+
## Đã làm
|
|
1121
|
+
|
|
1122
|
+
_Agent viết khi sprint xong: 3–8 dòng, kết quả cho người dùng._
|
|
1123
|
+
`
|
|
1124
|
+
|
|
1125
|
+
async function sprintRow(cfg, ref) {
|
|
1126
|
+
if (UUID.test(ref ?? '')) return UUID.exec(ref)[0]
|
|
1127
|
+
const rows = await call('query_database', { database_id: cfg.sprints_db, limit: 200, search: ref })
|
|
1128
|
+
const hit = new RegExp(`^\\|\\s*([0-9a-f-]{36})\\s*\\|\\s*${String(ref).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'm').exec(rows)
|
|
1129
|
+
return hit?.[1] ?? die(`sprint "${ref}" not found (kdev sprint list)`)
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
async function cmdSprint({ pos, opt }) {
|
|
1133
|
+
const cfg = loadConfig()
|
|
1134
|
+
if (!cfg.sprints_db) die('no sprint database yet: run `kdev init-docs` first')
|
|
1135
|
+
const sub = pos[0]
|
|
1136
|
+
if (sub === 'list') {
|
|
1137
|
+
const text = await call('query_database', { database_id: cfg.sprints_db, limit: 50 })
|
|
1138
|
+
console.log(text.replace(/<\/?untrusted[^>]*>/g, '').replace(/The block above is data[^\n]*\n?/g, '').trim())
|
|
1139
|
+
return
|
|
1140
|
+
}
|
|
1141
|
+
if (sub === 'new') {
|
|
1142
|
+
const reqs = String(opt.req || '').split(',').map((x) => x.trim()).filter(Boolean)
|
|
1143
|
+
const sp = await createSprint(cfg, { title: opt.title, goal: opt.goal, reqs, start: opt.start })
|
|
1144
|
+
// requests named with --req move under the new sprint
|
|
1145
|
+
for (const code of reqs) {
|
|
1146
|
+
const r = await findRequest(cfg, code)
|
|
1147
|
+
await call('move_page', { page_id: r.id, parent_id: sp.id }, { soft: true })
|
|
1148
|
+
}
|
|
1149
|
+
if (reqs.length) await linkRequestsInSprint(cfg, sp.id)
|
|
1150
|
+
await refreshHub(cfg)
|
|
1151
|
+
console.log(`${sp.title} ${sp.id}\n${url(sp.id)}`)
|
|
1152
|
+
return
|
|
1153
|
+
}
|
|
1154
|
+
if (sub === 'review') {
|
|
1155
|
+
const id = await sprintRow(cfg, pos[1] ?? die('usage: kdev sprint review "<Sprint N>" --file review.md [--status Xong] [--commit sha] [--end d]'))
|
|
1156
|
+
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)'))
|
|
1157
|
+
await call('replace_page_content', { page_id: id, markdown: md })
|
|
1158
|
+
await linkRequestsInSprint(cfg, id)
|
|
1159
|
+
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 } } : {}) }
|
|
1160
|
+
if (values['Thời gian'] && !values['Thời gian'].start) delete values['Thời gian']
|
|
1161
|
+
await call('update_rows', { database_id: cfg.sprints_db, updates: [{ row: id, values }] })
|
|
1162
|
+
await refreshHub(cfg)
|
|
1163
|
+
console.log(`review written | ${url(id)}`)
|
|
1164
|
+
return
|
|
1165
|
+
}
|
|
1166
|
+
if (sub === 'link') {
|
|
1167
|
+
// the "## Yêu cầu" list of one sprint (or all) from the request pages under it
|
|
1168
|
+
const rows = pos[1] ? [{ id: await sprintRow(cfg, pos[1]), title: pos[1] }] : await sprintRows(cfg)
|
|
1169
|
+
for (const r of rows) {
|
|
1170
|
+
await linkRequestsInSprint(cfg, r.id)
|
|
1171
|
+
console.log(`${r.title} linked | ${url(r.id)}`)
|
|
1172
|
+
}
|
|
1173
|
+
return
|
|
1174
|
+
}
|
|
1175
|
+
die('usage: kdev sprint new | review | link [S<n>] | list')
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/** A gate review page (G6 QA, G7 Release …): the checklist, then a Go / No-go decision card and an approval bar. */
|
|
1179
|
+
async function cmdGate({ pos, opt }) {
|
|
1180
|
+
const cfg = loadConfig()
|
|
1181
|
+
const gate = pos[0] === 'new' ? pos[1] : pos[0]
|
|
1182
|
+
if (!gate) die('usage: kdev gate new <G6|G7|…> --title "…" [--file checklist.md]')
|
|
1183
|
+
if (!cfg.gates_page) die('no gate page yet: run `kdev init-docs` first')
|
|
1184
|
+
const title = `${gate} · ${today()} · ${opt.title || 'Gate review'}`
|
|
1185
|
+
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'
|
|
1186
|
+
const text = await call('create_page', { parent_id: cfg.gates_page, title, icon: '🚦', markdown: `${body}\n\n## Quyết định\n` })
|
|
1187
|
+
const id = /page_id ([0-9a-f-]{36})/.exec(text)?.[1] ?? die(`create_page: ${text.slice(0, 200)}`)
|
|
1188
|
+
const { list } = await blocks(id, 20000)
|
|
1189
|
+
const head = list.find((b) => b.type === 'heading' && b.text.trim() === 'Quyết định')?.id
|
|
1190
|
+
await call('add_cards', {
|
|
1191
|
+
page_id: id,
|
|
1192
|
+
...(head ? { after_block_id: head } : {}),
|
|
1193
|
+
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' }] }] }],
|
|
1194
|
+
})
|
|
1195
|
+
console.log(`${title} ${id}\n${url(id)}`)
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/** Replace a project document page (design, dbdesign or any page id) with a Markdown file. */
|
|
1199
|
+
async function cmdDoc({ pos }) {
|
|
1200
|
+
const cfg = loadConfig()
|
|
1201
|
+
if (pos[0] !== 'set' || !pos[1] || !pos[2]) die('usage: kdev doc set <architecture|database|clusters|metrics|page_id> <file.md>')
|
|
1202
|
+
const named = {
|
|
1203
|
+
architecture: cfg.architecture_page ?? cfg.design_page,
|
|
1204
|
+
database: cfg.database_page ?? cfg.dbdesign_page,
|
|
1205
|
+
clusters: cfg.clusters_page,
|
|
1206
|
+
metrics: cfg.metrics_page,
|
|
1207
|
+
design: cfg.architecture_page ?? cfg.design_page,
|
|
1208
|
+
dbdesign: cfg.database_page ?? cfg.dbdesign_page,
|
|
1209
|
+
}
|
|
1210
|
+
const key = named[pos[1]] ?? (UUID.test(pos[1]) ? UUID.exec(pos[1])[0] : null)
|
|
1211
|
+
if (!key) die(`unknown document ${pos[1]} (run kdev init-docs, or give a page id)`)
|
|
1212
|
+
console.log((await call('replace_page_content', { page_id: key, markdown: readInput(pos[2]) })).split('\n')[0] + `\n${url(key)}`)
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
/** Block ids from an insert_blocks result ("New block ids: a, b."); the last one is where to insert next. */
|
|
1216
|
+
const newBlockIds = (text) => (/New block ids: ([^.]*)\./.exec(text)?.[1] ?? '').split(',').map((x) => x.trim()).filter(Boolean)
|
|
1217
|
+
|
|
1218
|
+
/** Numbers from a vitest / jest style summary ("Tests 2 failed | 455 passed | 3 skipped (460)", "Duration 5.1s"). */
|
|
1219
|
+
function parseTestOutput(text) {
|
|
1220
|
+
const line = text.split('\n').reverse().find((l) => /^\s*Tests?\s/.test(l) && /passed|failed/.test(l)) ?? ''
|
|
1221
|
+
const n = (w) => Number(new RegExp(`(\\d+) ${w}`).exec(line)?.[1] ?? 0)
|
|
1222
|
+
const d = /Duration\s+([\d.]+)\s*(ms|s)\b/.exec(text)
|
|
1223
|
+
return { passed: n('passed'), failed: n('failed'), skipped: n('skipped'), durationMs: d ? Math.round(Number(d[1]) * (d[2] === 's' ? 1000 : 1)) : 0 }
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
async function cmdTest({ pos, opt }) {
|
|
1227
|
+
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]'
|
|
1228
|
+
if (!pos[0] || !opt.suite) die(usage)
|
|
1229
|
+
const cfg = findConfig() ? loadConfig() : null
|
|
1230
|
+
const pageId = UUID.test(pos[0]) ? UUID.exec(pos[0])[0] : cfg ? await pageRef(cfg, pos[0]) : die(usage)
|
|
1231
|
+
const log = opt.from ? readFileSync(opt.from, 'utf8') : ''
|
|
1232
|
+
const parsed = log ? parseTestOutput(log) : { passed: 0, failed: 0, skipped: 0, durationMs: 0 }
|
|
1233
|
+
const num = (k, d) => (opt[k] !== undefined ? Number(opt[k]) : d)
|
|
1234
|
+
const t = {
|
|
1235
|
+
suite: opt.suite,
|
|
1236
|
+
passed: num('passed', parsed.passed),
|
|
1237
|
+
failed: num('failed', parsed.failed),
|
|
1238
|
+
skipped: num('skipped', parsed.skipped),
|
|
1239
|
+
durationMs: num('duration', parsed.durationMs),
|
|
1240
|
+
}
|
|
1241
|
+
if (opt.card) {
|
|
1242
|
+
const r = await call('resolve_cards', { page_id: pageId, updates: [{ key: opt.card, add_tests: [t] }] })
|
|
1243
|
+
console.log(r.split('\n')[0])
|
|
1244
|
+
return
|
|
1245
|
+
}
|
|
1246
|
+
const tail = log.length > 8000 ? log.slice(-8000) : log
|
|
1247
|
+
const r = await call('insert_blocks', {
|
|
1248
|
+
page_id: pageId,
|
|
1249
|
+
blocks: [{ type: 'testResult', props: { ...t, commit: opt.commit || '', at: new Date().toISOString(), log: tail } }],
|
|
1250
|
+
...(opt.after ? { after_block_id: opt.after } : {}),
|
|
1251
|
+
})
|
|
1252
|
+
console.log(`${t.suite}: ${t.passed} passed, ${t.failed} failed, ${t.skipped} skipped\nblock ${newBlockIds(r).at(-1) ?? '?'}`)
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
async function cmdLog({ pos, opt }) {
|
|
1256
|
+
const pageId = UUID.exec(pos[0] ?? '')?.[0] ?? die('usage: kdev log <page_id> <file|-> [--title "…"] [--lang text] [--max 6000] [--after block_id]')
|
|
1257
|
+
let text = readFileSync(pos[1] === '-' || !pos[1] ? 0 : pos[1], 'utf8')
|
|
1258
|
+
const max = Number(opt.max || 6000)
|
|
1259
|
+
if (text.length > max) text = `… (${text.length - max} characters cut; the end is kept)\n` + text.slice(-max)
|
|
1260
|
+
const out = []
|
|
1261
|
+
if (opt.title) out.push({ type: 'paragraph', text: `**${opt.title}**` })
|
|
1262
|
+
out.push({ type: 'codeBlock', text, language: opt.lang || 'text' })
|
|
1263
|
+
const r = await call('insert_blocks', { page_id: pageId, blocks: out, ...(opt.after ? { after_block_id: opt.after } : {}) })
|
|
1264
|
+
console.log(r.split('\n')[0])
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
async function cmdRelease({ pos, opt }) {
|
|
1268
|
+
const cfg = loadConfig()
|
|
1269
|
+
if (pos[0] !== 'add') die('usage: kdev release add --sha <sha> --req REQ-001[,REQ-002] [--result ok|failed] [--backup name] [--note file.md]')
|
|
1270
|
+
const sha = opt.sha || die('--sha is required')
|
|
1271
|
+
const reqs = String(opt.req || '').split(',').map((s) => s.trim()).filter(Boolean)
|
|
1272
|
+
const row = {
|
|
1273
|
+
title: `${today()} · ${sha}`,
|
|
1274
|
+
values: {
|
|
1275
|
+
Ngày: today(),
|
|
1276
|
+
Commit: sha,
|
|
1277
|
+
...(reqs.length ? { 'Yêu cầu': reqs } : {}),
|
|
1278
|
+
'Kết quả': opt.result === 'failed' ? 'Lỗi, đã rollback' : 'Thành công',
|
|
1279
|
+
...(opt.backup ? { Backup: opt.backup } : {}),
|
|
1280
|
+
},
|
|
1281
|
+
...(opt.note ? { body_markdown: readInput(opt.note) } : {}),
|
|
1282
|
+
}
|
|
1283
|
+
const text = await call('add_rows', { database_id: cfg.releases_db, rows: [row] })
|
|
1284
|
+
console.log(text.split('\n')[0] + `\n${url(cfg.releases_page)}`)
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/** The hub page's "Đang mở" section: one page link per open request (the link shows the live icon = status). */
|
|
1288
|
+
const NO_SPRINT = '_Không có sprint nào đang chạy._'
|
|
1289
|
+
|
|
1290
|
+
/** The sprint shown on the project page: the running one (Đang chạy / Review), else the latest. */
|
|
1291
|
+
async function hubSprint(cfg) {
|
|
1292
|
+
if (!cfg.sprints_db) return null
|
|
1293
|
+
const j = await callJson('query_database', { database_id: cfg.sprints_db, limit: 200, properties: ['Trạng thái', 'Mục tiêu'] }, { soft: true })
|
|
1294
|
+
const num = (r) => Number(/\d+/.exec(r.title ?? '')?.[0] ?? 0)
|
|
1295
|
+
const rows = (j?.rows ?? []).sort((a, b) => num(b) - num(a))
|
|
1296
|
+
const running = rows.find((r) => ['Đang chạy', 'Review'].includes(r.values?.['Trạng thái']))
|
|
1297
|
+
return running ? { ...running, running: true } : rows[0] ? { ...rows[0], running: false } : null
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/** Replace the top-level blocks between a "## <title>" heading and the next heading. */
|
|
1301
|
+
async function replaceSection(pageId, list, title, fresh) {
|
|
1302
|
+
const head = list.find((b) => b.depth === 0 && b.type === 'heading' && b.text.trim().startsWith(title))
|
|
1303
|
+
if (!head) return false
|
|
1304
|
+
const old = []
|
|
1305
|
+
for (const b of list.slice(list.indexOf(head) + 1)) {
|
|
1306
|
+
if (b.depth === 0 && b.type === 'heading') break
|
|
1307
|
+
if (b.depth === 0) old.push(b.id)
|
|
1308
|
+
}
|
|
1309
|
+
await call('insert_blocks', { page_id: pageId, after_block_id: head.id, blocks: fresh })
|
|
1310
|
+
if (old.length) await call('delete_blocks', { page_id: pageId, block_ids: old })
|
|
1311
|
+
return true
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
/** The project page's live sections: "Sprint hiện tại" (when the page has it) and "Đang mở". */
|
|
1315
|
+
async function refreshHub(cfg) {
|
|
1316
|
+
requestCache = null
|
|
1317
|
+
const open = (await allRequests(cfg)).filter((r) => OPEN_ICONS.has(r.icon))
|
|
1318
|
+
const { list } = await blocks(cfg.hub, 20000)
|
|
1319
|
+
if (list.some((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === 'Sprint hiện tại')) {
|
|
1320
|
+
const s = await hubSprint(cfg)
|
|
1321
|
+
const goal = s?.values?.['Mục tiêu']
|
|
1322
|
+
const fresh = !s
|
|
1323
|
+
? [{ type: 'paragraph', text: NO_SPRINT }]
|
|
1324
|
+
: s.running
|
|
1325
|
+
? [{ type: 'pageLink', props: { pageId: s.id } }, ...(goal ? [{ type: 'paragraph', text: `Mục tiêu: ${goal}` }] : [])]
|
|
1326
|
+
: [{ type: 'paragraph', text: `${NO_SPRINT} Gần nhất:` }, { type: 'pageLink', props: { pageId: s.id } }]
|
|
1327
|
+
await replaceSection(cfg.hub, list, 'Sprint hiện tại', fresh)
|
|
1328
|
+
}
|
|
1329
|
+
if (cfg.sprints_db && !list.some((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === 'Timeline sprint')) {
|
|
1330
|
+
const info = await call('get_database', { database_id: cfg.sprints_db })
|
|
1331
|
+
const view = /"Timeline" view_id=([0-9a-f-]{36})/.exec(info)?.[1] ?? ''
|
|
1332
|
+
const at = list.find((b) => b.depth === 0 && b.type === 'heading' && b.text.trim() === 'Lối tắt')
|
|
1333
|
+
await call('insert_blocks', {
|
|
1334
|
+
page_id: cfg.hub,
|
|
1335
|
+
...(at ? { after_block_id: list[list.indexOf(at) - 1]?.id ?? at.id } : {}),
|
|
1336
|
+
blocks: [{ type: 'heading', level: 2, text: 'Timeline sprint' }, { type: 'databaseView', props: { databaseId: cfg.sprints_db, viewId: view } }],
|
|
1337
|
+
})
|
|
1338
|
+
}
|
|
1339
|
+
await replaceSection(cfg.hub, list, 'Đang mở', open.length
|
|
1340
|
+
? open.map((r) => ({ type: 'pageLink', props: { pageId: r.id } }))
|
|
1341
|
+
: [{ type: 'paragraph', text: '_Không có yêu cầu nào đang mở._' }])
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
async function cmdHub() {
|
|
1345
|
+
const cfg = loadConfig()
|
|
1346
|
+
await refreshHub(cfg)
|
|
1347
|
+
console.log(url(cfg.hub))
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
async function cmdCall({ pos }) {
|
|
1351
|
+
const name = pos[0] ?? die('usage: kdev call <tool> [<json> | @file.json | -]')
|
|
1352
|
+
const args = pos[1] ? JSON.parse(readInput(pos[1])) : {}
|
|
1353
|
+
console.log(await call(name, args))
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
const HELP = `kdev: Kicho devflow helper (skill kicho-devflow)
|
|
1357
|
+
init <project page> [--project Name] [--summary "…"] [--handbook id | --company id]
|
|
1358
|
+
the project page is the hub: its children + the company's 📘 Quy trình làm việc; writes ${CONFIG} here
|
|
1359
|
+
show sprints → their requests (status icons), then the inbox
|
|
1360
|
+
req new <spec.json> [--sprint S6|new] request page S5 · R6 · title inside the sprint (task rows only with "tasks": true)
|
|
1361
|
+
req adopt <R6> <spec.json> the owner's own page in the inbox → card page moved into the sprint
|
|
1362
|
+
req new <page.md> --title "…" Markdown page (old servers; {{REQ}} {{STATUS}} {{DATE}} filled in)
|
|
1363
|
+
req read <R5> [--all] [--since t] open cards only by default (compact get_review) + comments; --full = whole page
|
|
1364
|
+
req ack <REQ-NNN> "agent read at" on the approval bar
|
|
1365
|
+
req status <REQ-NNN> <status> ${Object.keys(REQ_STATUS).join(' | ')}: icon, header, hub list
|
|
1366
|
+
memory init | model check the shared decision bank / doraemon's "how the owner decides" summary
|
|
1367
|
+
remember "<decision>" [--kind …] [--source R5/T1] [--company] the owner's decision, one line (or --file items.json)
|
|
1368
|
+
recall "<question>" [--top 6] what he already decided (before asking him); fails open
|
|
1369
|
+
answer <REQ-NNN> --quote "…" --file answers.json the owner answered in the chat: record it in the cards ("qua chat")
|
|
1370
|
+
sprint new [--title S6] [--goal …] [--req R6] | sprint review S5 --file s5.md [--commit sha] [--end d]
|
|
1371
|
+
sprint link [S5] | sprint list keep the sprint page's request links and multi-select in step
|
|
1372
|
+
gate new <G6|G7|…> --title "…" [--file checklist.md] gate review page with a Go / No-go card
|
|
1373
|
+
doc set <architecture|database|clusters|metrics|page_id> <file.md> replace a project document page
|
|
1374
|
+
card resolve <REQ> <KEY>… [--status S] [--decided "…"|@file] or --file decisions.json ([{key,status,decided}])
|
|
1375
|
+
card result <REQ> <KEY> --outcome done|changed|dropped|deferred [--summary @f] [--verification …] [--limits …] [--commit sha] [--dod all|"items"] [--dod-na "i18n=…"]
|
|
1376
|
+
evidence <REQ|page> <files…> [--card KEY] [--caption …] [--device phone] [--verdict pass] [--role before|after] [--ref F2] [--field Env=…] [--note …]
|
|
1377
|
+
test <REQ|page> --suite S (--from out.txt | --passed N --failed N) [--card KEY] [--commit sha]
|
|
1378
|
+
tasks add <rows.json> [--req REQ-NNN] add rows ([{title, values:{…}, body_markdown}]); status defaults to Chờ duyệt
|
|
1379
|
+
tasks set <row id|code>… [--req REQ-NNN] --status S [--agent A] [--commit sha] [--start d] [--end d]
|
|
1380
|
+
tasks list [--req REQ-NNN] [--status S]
|
|
1381
|
+
log <page_id> <file|-> [--title "…"] [--lang text] [--max 6000] text as a code block (end kept)
|
|
1382
|
+
release add --sha <sha> --req REQ-001[,…] [--result ok|failed] [--backup name] [--note file.md]
|
|
1383
|
+
hub refresh "Sprint hiện tại" and "Đang mở" on the project page
|
|
1384
|
+
call <tool> [<json>|@file|-] any Kicho MCP tool`
|
|
1385
|
+
|
|
1386
|
+
const [cmd, sub, ...rest] = process.argv.slice(2)
|
|
1387
|
+
const twoWord = {
|
|
1388
|
+
req: { new: cmdReqNew, adopt: cmdReqAdopt, status: cmdReqStatus, read: cmdReqRead, ack: cmdReqAck },
|
|
1389
|
+
tasks: { add: cmdTasksAdd, set: cmdTasksSet, list: cmdTasksList },
|
|
1390
|
+
card: { resolve: (a) => cmdCard(a, 'resolve'), result: (a) => cmdCard(a, 'result') },
|
|
1391
|
+
}
|
|
1392
|
+
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 }
|
|
1393
|
+
try {
|
|
1394
|
+
if (twoWord[cmd]) {
|
|
1395
|
+
const fn = twoWord[cmd][sub] ?? die(`unknown: ${cmd} ${sub ?? ''}\n${HELP}`)
|
|
1396
|
+
await fn(parseArgs(rest))
|
|
1397
|
+
} else if (oneWord[cmd]) {
|
|
1398
|
+
await oneWord[cmd](parseArgs([sub, ...rest].filter((x) => x !== undefined)))
|
|
1399
|
+
} else {
|
|
1400
|
+
console.log(HELP)
|
|
1401
|
+
}
|
|
1402
|
+
} catch (e) {
|
|
1403
|
+
die(e?.message ?? String(e))
|
|
1404
|
+
}
|