teamsmith 0.1.1 → 0.2.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.
Files changed (104) hide show
  1. package/README.md +16 -8
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +55 -0
  4. package/skills/teamsmith/SKILL.md +18 -7
  5. package/skills/teamsmith/extension/team-bg.ts +47 -11
  6. package/skills/teamsmith/extension/team-notify.ts +143 -4
  7. package/skills/teamsmith/references/agent-adapters.md +7 -7
  8. package/skills/teamsmith/references/config.md +29 -15
  9. package/skills/teamsmith/references/migration.md +38 -2
  10. package/skills/teamsmith/references/openspec.md +23 -9
  11. package/skills/teamsmith/references/protocol.md +81 -13
  12. package/skills/teamsmith/references/workflows.md +31 -19
  13. package/skills/teamsmith/scripts/lib/cmd-agents.sh +210 -70
  14. package/skills/teamsmith/scripts/lib/cmd-bootstrap.sh +70 -9
  15. package/skills/teamsmith/scripts/lib/cmd-config.sh +222 -70
  16. package/skills/teamsmith/scripts/lib/cmd-death.sh +2 -15
  17. package/skills/teamsmith/scripts/lib/cmd-docs.sh +6 -3
  18. package/skills/teamsmith/scripts/lib/cmd-project.sh +134 -17
  19. package/skills/teamsmith/scripts/lib/cmd-reply.sh +96 -0
  20. package/skills/teamsmith/scripts/lib/cmd-review.sh +13 -10
  21. package/skills/teamsmith/scripts/lib/cmd-status.sh +42 -13
  22. package/skills/teamsmith/scripts/lib/cmd-watch.sh +75 -13
  23. package/skills/teamsmith/scripts/lib/common.sh +797 -71
  24. package/skills/teamsmith/scripts/monitor.mjs +34 -3
  25. package/skills/teamsmith/scripts/panel/README.md +22 -11
  26. package/skills/teamsmith/scripts/panel/panel.js +217 -215
  27. package/skills/teamsmith/scripts/panel/src/App.tsx +421 -164
  28. package/skills/teamsmith/scripts/panel/src/data.ts +84 -4
  29. package/skills/teamsmith/scripts/panel/src/layout.ts +502 -91
  30. package/skills/teamsmith/scripts/panel/src/main.tsx +97 -12
  31. package/skills/teamsmith/scripts/panel/src/settings.ts +1 -1
  32. package/skills/teamsmith/scripts/panel/src/strings/en.ts +56 -21
  33. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +56 -21
  34. package/skills/teamsmith/scripts/panel/src/types.ts +178 -16
  35. package/skills/teamsmith/scripts/replies.mjs +893 -0
  36. package/skills/teamsmith/scripts/team +1 -0
  37. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +15 -2
  38. package/skills/teamsmith/templates/BOARD.md.tmpl +2 -2
  39. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +7 -3
  40. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +17 -0
  41. package/skills/teamsmith/templates/config.sh.tmpl +10 -5
  42. package/skills/teamsmith/templates/memory-seed.md.tmpl +3 -0
  43. package/skills/teamsmith/templates/pm-prompt.md.tmpl +20 -1
  44. package/skills/teamsmith/templates/report.md.tmpl +12 -0
  45. package/skills/teamsmith/templates/task.md.tmpl +4 -0
  46. package/skills/teamsmith/tests/bg-ledger-harness.mjs +682 -0
  47. package/skills/teamsmith/tests/bg-ledger.sh +307 -0
  48. package/skills/teamsmith/tests/checkout-shape-probe.sh +287 -58
  49. package/skills/teamsmith/tests/config-cli.sh +162 -288
  50. package/skills/teamsmith/tests/death-cause.sh +5 -2
  51. package/skills/teamsmith/tests/install-shape.sh +4 -2
  52. package/skills/teamsmith/tests/key-replies-pty.sh +375 -0
  53. package/skills/teamsmith/tests/key-replies-ui.sh +332 -0
  54. package/skills/teamsmith/tests/key-replies.sh +1075 -0
  55. package/skills/teamsmith/tests/ledger-ban.sh +5 -5
  56. package/skills/teamsmith/tests/ledger-claim.sh +247 -0
  57. package/skills/teamsmith/tests/lib/checkout-shape.sh +66 -14
  58. package/skills/teamsmith/tests/lib/model-policy.sh +26 -0
  59. package/skills/teamsmith/tests/lib/model-routing-boundary.sh +420 -0
  60. package/skills/teamsmith/tests/lib/model-routing-expansion.sh +155 -0
  61. package/skills/teamsmith/tests/lib/model-routing-flips.py +136 -0
  62. package/skills/teamsmith/tests/lib/model-routing-roles.sh +250 -0
  63. package/skills/teamsmith/tests/lib/proc-io.sh +103 -0
  64. package/skills/teamsmith/tests/lib/reply-fixture.sh +372 -0
  65. package/skills/teamsmith/tests/lib/tmux-iso.sh +8 -0
  66. package/skills/teamsmith/tests/panel-b2.sh +1 -1
  67. package/skills/teamsmith/tests/panel-b3-stub.sh +27 -0
  68. package/skills/teamsmith/tests/panel-b3.sh +14 -10
  69. package/skills/teamsmith/tests/panel-choices.sh +74 -61
  70. package/skills/teamsmith/tests/panel-cpu.sh +1 -1
  71. package/skills/teamsmith/tests/panel-p21.sh +311 -190
  72. package/skills/teamsmith/tests/perf.sh +1 -1
  73. package/skills/teamsmith/tests/pm-box-real.sh +1 -1
  74. package/skills/teamsmith/tests/pulse-nudge-key.sh +1 -1
  75. package/skills/teamsmith/tests/routes.sh +43 -22
  76. package/skills/teamsmith/tests/section-budgets.tsv +9 -5
  77. package/skills/teamsmith/tests/section-paths.tsv +26 -16
  78. package/skills/teamsmith/tests/section-select.sh +99 -16
  79. package/skills/teamsmith/tests/smoke.sh +930 -216
  80. package/skills/teamsmith/tests/snapshots/zh-dark-120-detail.txt +2 -2
  81. package/skills/teamsmith/tests/snapshots/zh-dark-120-p4.txt +2 -2
  82. package/skills/teamsmith/tests/snapshots/zh-dark-120.txt +9 -9
  83. package/skills/teamsmith/tests/snapshots/zh-dark-160-p4.txt +2 -2
  84. package/skills/teamsmith/tests/snapshots/zh-dark-160.txt +9 -9
  85. package/skills/teamsmith/tests/snapshots/zh-dark-59-detail.txt +1 -1
  86. package/skills/teamsmith/tests/snapshots/zh-dark-59-p4.txt +1 -1
  87. package/skills/teamsmith/tests/snapshots/zh-dark-59.txt +5 -5
  88. package/skills/teamsmith/tests/snapshots/zh-dark-99-p4.txt +2 -2
  89. package/skills/teamsmith/tests/snapshots/zh-dark-99.txt +5 -5
  90. package/skills/teamsmith/tests/snapshots/zh-light-120-detail.txt +2 -2
  91. package/skills/teamsmith/tests/snapshots/zh-light-120-p4.txt +2 -2
  92. package/skills/teamsmith/tests/snapshots/zh-light-120.txt +9 -9
  93. package/skills/teamsmith/tests/snapshots/zh-light-160-p4.txt +2 -2
  94. package/skills/teamsmith/tests/snapshots/zh-light-160.txt +9 -9
  95. package/skills/teamsmith/tests/snapshots/zh-light-59-detail.txt +1 -1
  96. package/skills/teamsmith/tests/snapshots/zh-light-59-p4.txt +1 -1
  97. package/skills/teamsmith/tests/snapshots/zh-light-59.txt +5 -5
  98. package/skills/teamsmith/tests/snapshots/zh-light-99-p4.txt +2 -2
  99. package/skills/teamsmith/tests/snapshots/zh-light-99.txt +5 -5
  100. package/skills/teamsmith/tests/task-header-model.sh +2 -1
  101. package/skills/teamsmith/tests/task-model-routing.sh +1014 -0
  102. package/skills/teamsmith-init/SKILL.md +38 -38
  103. package/skills/teamsmith-init/references/bootstrap.md +6 -4
  104. package/skills/teamsmith-init/templates/bootstrap-prompt.md.tmpl +9 -5
@@ -0,0 +1,893 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * teamsmith · 关键回复(key replies)的存储与只读查询 helper。
4
+ *
5
+ * node replies.mjs post --main-root <项目根> --state-dir <state> --from <label> --title <t> [--stdin]
6
+ * node replies.mjs summary --main-root <项目根> --state-dir <state>
7
+ * node replies.mjs list --main-root <项目根> --state-dir <state> [--before <no>] [--format json|text]
8
+ * node replies.mjs show --main-root <项目根> --state-dir <state> --no <no> [--format json|text|raw]
9
+ *
10
+ * 存储布局(change: pulse-key-replies · design §2/§3):
11
+ * <state>/key-replies/writer.lock 正规文件,只供 OS advisory lock(flock)
12
+ * <state>/key-replies/index.v1 追加的固定 4096 字节提交槽位
13
+ * <state>/key-replies/bodies/<32hex>.md 不可变原文字节;文件名不来自标题/标签
14
+ * <state>/key-replies/.tmp-<32hex> 本次 publisher 的临时原文;读者永不枚举
15
+ *
16
+ * 每个槽位:前 4064 字节 = uint32BE(json_length) + UTF-8 JSON + 零填充,末 32 字节 = 前 4064 字节的 SHA-256。
17
+ * `no = slot_offset / 4096 + 1`;show 用算术直接定位。list 每次最多读 50 槽。summary 只读最后一个完整槽。
18
+ *
19
+ * 退出码(delta「key-replies」的合同):
20
+ * 0 成功(post 只有 durable 之后才 print saved 回执)
21
+ * 2 用法/输入失败 4 存储不可用/损坏 5 锁竞争(≤2000ms 等待) 6 已可见但持久性未确认
22
+ *
23
+ * 本文件只做存储;命令分发、身份分类与 JS 运行时解析在 scripts/lib/cmd-reply.sh。
24
+ * 只读面(summary/list/show)绝不 mkdir、绝不写盘、绝不等待 writer 锁。
25
+ */
26
+
27
+ import {
28
+ closeSync,
29
+ constants as C,
30
+ fsyncSync,
31
+ fstatSync,
32
+ ftruncateSync,
33
+ linkSync,
34
+ mkdirSync,
35
+ openSync,
36
+ readSync,
37
+ unlinkSync,
38
+ writeSync,
39
+ } from 'node:fs'
40
+ import { spawnSync } from 'node:child_process'
41
+ import { createHash, randomBytes } from 'node:crypto'
42
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
43
+ import { pathToFileURL } from 'node:url'
44
+
45
+ // ---------------------------------------------------------------- 常量
46
+ const SLOT_SIZE = 4096
47
+ const PAYLOAD_SIZE = SLOT_SIZE - 32
48
+ const VERSION = 1
49
+ const MAX_NO = 999999999999
50
+ const MAX_BODY_BYTES = 131072
51
+ const MAX_TITLE_CODEPOINTS = 160
52
+ const MAX_LABEL = 48
53
+ const LOCK_WAIT_SEC = 2
54
+ const STORE_NAME = 'key-replies'
55
+ const INDEX_NAME = 'index.v1'
56
+ const LOCK_NAME = 'writer.lock'
57
+ const BODIES_NAME = 'bodies'
58
+ const LIST_PAGE = 50
59
+ const HEX32 = /^[0-9a-f]{32}$/
60
+ const HEX64 = /^[0-9a-f]{64}$/
61
+ const LABEL_RE = /^[A-Za-z0-9._-]+$/
62
+
63
+ // ---------------------------------------------------------------- 错误与退出码
64
+ class ReplyError extends Error {
65
+ constructor(code, message) {
66
+ super(message)
67
+ this.code = code
68
+ }
69
+ }
70
+ const input = (m) => new ReplyError(2, m)
71
+ const unavailable = (m) => new ReplyError(4, m)
72
+ const busy = (m) => new ReplyError(5, m)
73
+ const unconfirmed = (m) => new ReplyError(6, m)
74
+
75
+ function fail(code, message) {
76
+ process.stderr.write(`reply: ${message}\n`)
77
+ process.exit(code)
78
+ }
79
+
80
+ function main(fn) {
81
+ try {
82
+ fn()
83
+ } catch (e) {
84
+ if (e instanceof ReplyError) fail(e.code, e.message)
85
+ // 未预期的异常也绝不能打印正文:只说类型。
86
+ fail(4, `内部错误(${e && e.constructor ? e.constructor.name : 'Error'})`)
87
+ }
88
+ }
89
+
90
+ // ---------------------------------------------------------------- 显示净化(与 panel/src/sanitize.ts 同一规则)
91
+ // 「共享同一规则并由双向测试防漂移」:本段的正则集与 panel/src/sanitize.ts 逐字相同,
92
+ // tests/key-replies.sh --select paths 用同一组敌意载荷对两边做双向断言(任何一边漂移都红)。
93
+ const OSC_RE = /\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g
94
+ const CSI_RE = /\u001B\[[0-?]*[ -/]*[@-~]/g
95
+ const C1_CSI_RE = /\u009B[0-?]*[ -/]*[@-~]/g
96
+ const ESC2_RE = /\u001B[@-Z\\-_]/g
97
+ const CTRL_RE =
98
+ /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B\u200E\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g
99
+
100
+ export function sanitize(value) {
101
+ return String(value ?? '')
102
+ .replace(OSC_RE, '')
103
+ .replace(CSI_RE, '')
104
+ .replace(C1_CSI_RE, '')
105
+ .replace(ESC2_RE, '')
106
+ .replace(CTRL_RE, '')
107
+ }
108
+
109
+ // 标题的输入校验比显示净化更严:终端控制与双向/不可见格式控制一律拒绝(不是删掉)。
110
+ const TITLE_FORBIDDEN_RE = new RegExp(
111
+ `[\\u0000-\\u001F\\u007F-\\u009F\\u00AD\\u061C\\u200B-\\u200F\\u2028-\\u202E\\u2060-\\u206F\\uFEFF]`,
112
+ )
113
+
114
+ // ---------------------------------------------------------------- 小工具
115
+ const sleepMs = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
116
+
117
+ // O_PATH(Linux x86-64;Node 的 fs.constants 不一定导出它):只做**锚点**的目录句柄,
118
+ // 不附读权限、不能 getdents —— 只读面用它打开 bodies/,于是一个「列举正文目录」的实现在
119
+ // 无读权限的目录上必然 EACCES,而按名直开仍然可用(夹具据此证明不枚举)。
120
+ const O_PATH = typeof C.O_PATH === 'number' ? C.O_PATH : 0o10000000
121
+
122
+ /**
123
+ * 故障注入旋钮(只在隔离夹具里用;不是产品配置键,也不改变任何默认路径):
124
+ * TEAM_REPLY_FAULT=kill:<point> → 在精确落点 SIGKILL 自己(模拟中断)
125
+ * TEAM_REPLY_FAULT=fail:<point> → 在该点抛出「存储不可用」
126
+ * points: body-write / body-fsync / body-staged / body-link / body-published /
127
+ * index-write / index-written / index-fsync / index-durable
128
+ */
129
+ function faultPoint(point, mode) {
130
+ if (process.env.TEAM_REPLY_FAULT !== `${mode}:${point}`) return false
131
+ if (mode === 'kill') {
132
+ process.kill(process.pid, 'SIGKILL')
133
+ sleepMs(5000)
134
+ }
135
+ throw unavailable(`故障注入:${point}`)
136
+ }
137
+
138
+ const hit = (point) => faultPoint(point, String(process.env.TEAM_REPLY_FAULT || '').split(':')[0])
139
+
140
+ function fdPath(fd, name) {
141
+ // /proc/self/fd/<fd> 是**已打开目录**的锚:目录中途被替换也解析到原来那个 inode(TOCTOU 防线)。
142
+ return `/proc/self/fd/${fd}/${name}`
143
+ }
144
+
145
+ function closeQuiet(fd) {
146
+ if (typeof fd === 'number' && fd >= 0) {
147
+ try {
148
+ closeSync(fd)
149
+ } catch {
150
+ /* 已经关了 */
151
+ }
152
+ }
153
+ }
154
+
155
+ function errnoOf(e) {
156
+ return e && typeof e === 'object' && 'code' in e ? String(e.code) : ''
157
+ }
158
+
159
+ /**
160
+ * 打开一个目录(相对已锚定的父 fd,O_NOFOLLOW|O_DIRECTORY)。结果:
161
+ * {ok:true, fd} | {ok:false, kind:'missing'|'unsafe'|'error', detail}
162
+ * `create` 只在 post 的存储创建路径上给:缺目录就 mkdir(模式 0700)。
163
+ * `oPath`(只读面给 bodies/ 用):只要锚点不要读权限 —— 不能 getdents,也不能配合写。
164
+ */
165
+ function openDirAt(parentFd, name, { create = false, oPath = false } = {}) {
166
+ const open = () => {
167
+ const flags = oPath ? O_PATH | C.O_DIRECTORY | C.O_NOFOLLOW : C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW
168
+ const fd = openSync(fdPath(parentFd, name), flags)
169
+ const st = fstatSync(fd)
170
+ if (!st.isDirectory()) {
171
+ closeQuiet(fd)
172
+ const e = new Error('not a directory')
173
+ e.code = 'ENOTDIR'
174
+ throw e
175
+ }
176
+ return fd
177
+ }
178
+ try {
179
+ return { ok: true, fd: open() }
180
+ } catch (e) {
181
+ const code = errnoOf(e)
182
+ if (code === 'ENOENT') {
183
+ if (!create) return { ok: false, kind: 'missing', detail: name }
184
+ try {
185
+ mkdirSync(fdPath(parentFd, name), { mode: 0o700 })
186
+ } catch (e2) {
187
+ const c2 = errnoOf(e2)
188
+ if (c2 !== 'EEXIST') return { ok: false, kind: 'error', detail: `${name}: ${c2 || e2.message}` }
189
+ }
190
+ try {
191
+ return { ok: true, fd: open(), created: true }
192
+ } catch (e2) {
193
+ return { ok: false, kind: 'unsafe', detail: `${name}: ${errnoOf(e2) || e2.message}` }
194
+ }
195
+ }
196
+ if (code === 'ELOOP') return { ok: false, kind: 'unsafe', detail: `${name}: symlink` }
197
+ if (code === 'ENOTDIR') return { ok: false, kind: 'unsafe', detail: `${name}: not a directory` }
198
+ return { ok: false, kind: 'error', detail: `${name}: ${code || e.message}` }
199
+ }
200
+ }
201
+
202
+ /**
203
+ * 打开一个正规文件(相对已锚定的父 fd,O_NOFOLLOW|O_NONBLOCK)+ 类型校验。
204
+ *
205
+ * `O_NONBLOCK` 是**读路径的安全前提**:不带它时,`open(2)` 一个 FIFO 会**一直等到有写者**——读命令
206
+ * 会永久挂住(V27 实测 `reply list`/`show` 对 FIFO 索引/正文 rc 124),而规格要求「拒绝且不读目标、
207
+ * 不阻塞在 FIFO 上」。带上它之后 FIFO 立刻打开成功,紧接着的 `fstat` 判定为非正规文件并拒绝。
208
+ * 对正规文件 `O_NONBLOCK` 无任何作用(POSIX:对 regular file 的 read/write 不受影响),因此这里
209
+ * 没有「检查后清位」这一步——Node 没有 fcntl 绑定,且对本用例而言它本就不需要清。
210
+ */
211
+ function openFileAt(parentFd, name, flags, mode) {
212
+ let fd
213
+ try {
214
+ fd = openSync(fdPath(parentFd, name), flags | C.O_NOFOLLOW | C.O_NONBLOCK, mode)
215
+ } catch (e) {
216
+ const code = errnoOf(e)
217
+ if (code === 'ENOENT') return { ok: false, kind: 'missing', detail: name }
218
+ if (code === 'ELOOP') return { ok: false, kind: 'unsafe', detail: `${name}: symlink` }
219
+ return { ok: false, kind: 'error', detail: `${name}: ${code || e.message}` }
220
+ }
221
+ const st = fstatSync(fd)
222
+ if (!st.isFile()) {
223
+ closeQuiet(fd)
224
+ return { ok: false, kind: 'unsafe', detail: `${name}: not a regular file` }
225
+ }
226
+ return { ok: true, fd }
227
+ }
228
+
229
+ /** 创建一个正规文件;已存在则按 `openFileAt` 打开(不跟随软链)。 */
230
+ function openOrCreateFileAt(parentFd, name, mode) {
231
+ try {
232
+ const fd = openSync(fdPath(parentFd, name), C.O_RDWR | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, mode)
233
+ return { ok: true, fd, created: true }
234
+ } catch (e) {
235
+ if (errnoOf(e) !== 'EEXIST') return openFileAtResult(e, name)
236
+ }
237
+ return openFileAt(parentFd, name, C.O_RDWR)
238
+ }
239
+
240
+ function openFileAtResult(e, name) {
241
+ const code = errnoOf(e)
242
+ if (code === 'ELOOP') return { ok: false, kind: 'unsafe', detail: `${name}: symlink` }
243
+ return { ok: false, kind: 'error', detail: `${name}: ${code || e.message}` }
244
+ }
245
+
246
+ // ---------------------------------------------------------------- 路径解析(main-root → state → key-replies)
247
+ function parseMainRoot(value) {
248
+ if (!value || !isAbsolute(value)) throw input('--main-root 需要绝对路径')
249
+ return value
250
+ }
251
+
252
+ /**
253
+ * 从 main_root 逐段锚定走到 state 目录。`out.fd` = state 目录 fd(调用方负责 close)。
254
+ * 缺失/不安全/不可用分别返回 kind。只读路径绝不创建。
255
+ */
256
+ export function openStateDir(mainRoot, stateDir, { create }) {
257
+ let rootFd
258
+ try {
259
+ rootFd = openSync(mainRoot, C.O_RDONLY | C.O_DIRECTORY)
260
+ } catch (e) {
261
+ return { ok: false, kind: 'error', detail: `main-root 打不开(${errnoOf(e) || e.message})` }
262
+ }
263
+ const rel = relative(resolve(mainRoot), resolve(stateDir))
264
+ if (rel === '') return { ok: true, fd: rootFd }
265
+ if (rel.startsWith('..') || isAbsolute(rel)) {
266
+ closeQuiet(rootFd)
267
+ return { ok: false, kind: 'unsafe', detail: 'state 目录逃出了 main_root(reply 存储必须落在项目内)' }
268
+ }
269
+ let fd = rootFd
270
+ for (const part of rel.split(sep).filter((p) => p && p !== '.')) {
271
+ const r = openDirAt(fd, part, { create })
272
+ closeQuiet(fd)
273
+ if (!r.ok) return r
274
+ fd = r.fd
275
+ }
276
+ return { ok: true, fd }
277
+ }
278
+
279
+ const kindReason = (r) =>
280
+ r.kind === 'unsafe' ? `存储路径不安全(${r.detail})` : `存储不可用(${r.detail})`
281
+
282
+ /**
283
+ * 打开 store。返回 {ok, kind, stateFd, krFd, indexFd, lockFd, bodiesFd?, created?}。
284
+ * mode='read' → 只读;缺失 = kind:'missing'(空 store)
285
+ * mode='write' → 创建缺失的目录/文件(state/key-replies/bodies/index/lock)
286
+ */
287
+ export function openStore(mainRoot, stateDir, mode) {
288
+ const create = mode === 'write'
289
+ const st = openStateDir(mainRoot, stateDir, { create })
290
+ if (!st.ok) return st
291
+ const stateFd = st.fd
292
+ const out = { ok: true, stateFd }
293
+
294
+ const kr = openDirAt(stateFd, STORE_NAME, { create })
295
+ if (!kr.ok) {
296
+ closeQuiet(stateFd)
297
+ if (kr.kind === 'missing') return { ok: false, kind: 'missing', detail: 'store' }
298
+ return { ...kr, stateFd: null }
299
+ }
300
+ out.krFd = kr.fd
301
+ out.created = Boolean(kr.created)
302
+
303
+ const idx = create
304
+ ? openOrCreateFileAt(out.krFd, INDEX_NAME, 0o600)
305
+ : openFileAt(out.krFd, INDEX_NAME, C.O_RDONLY)
306
+ if (!idx.ok) {
307
+ closeQuiet(out.krFd)
308
+ closeQuiet(stateFd)
309
+ if (idx.kind === 'missing') return { ok: false, kind: 'missing', detail: 'index' }
310
+ return { ...idx, stateFd: null }
311
+ }
312
+ out.indexFd = idx.fd
313
+
314
+ const bodies = openDirAt(out.krFd, BODIES_NAME, { create, oPath: !create })
315
+ out.bodiesCreated = Boolean(bodies.created)
316
+ if (!bodies.ok) {
317
+ if (bodies.kind === 'missing' && !create) {
318
+ // 只读面不要求 bodies/ 存在:list/summary 不读正文;show 会自己报不可用。
319
+ out.bodiesFd = null
320
+ } else {
321
+ closeQuiet(out.indexFd)
322
+ closeQuiet(out.krFd)
323
+ closeQuiet(stateFd)
324
+ if (bodies.kind === 'missing') return { ok: false, kind: 'missing', detail: 'bodies' }
325
+ return { ...bodies, stateFd: null }
326
+ }
327
+ } else {
328
+ out.bodiesFd = bodies.fd
329
+ }
330
+
331
+ if (create) {
332
+ const lock = openOrCreateFileAt(out.krFd, LOCK_NAME, 0o600)
333
+ if (!lock.ok) {
334
+ closeQuiet(out.bodiesFd)
335
+ closeQuiet(out.indexFd)
336
+ closeQuiet(out.krFd)
337
+ closeQuiet(stateFd)
338
+ return { ...lock, stateFd: null }
339
+ }
340
+ out.lockFd = lock.fd
341
+ // 新建的目录/文件按需 fsync(持久化布局本身;失败不致命,交给后面的内容 fsync 判定)。
342
+ try {
343
+ if (out.created || out.bodiesCreated || lock.created) fsyncSync(out.krFd)
344
+ } catch {
345
+ /* 后面的 fsync 会给出结论 */
346
+ }
347
+ }
348
+ return out
349
+ }
350
+
351
+ export function closeStore(store) {
352
+ if (!store) return
353
+ closeQuiet(store.lockFd)
354
+ closeQuiet(store.bodiesFd)
355
+ closeQuiet(store.indexFd)
356
+ closeQuiet(store.krFd)
357
+ closeQuiet(store.stateFd)
358
+ }
359
+
360
+ // ---------------------------------------------------------------- 槽位编解码
361
+ function encodeSlot(meta) {
362
+ const json = Buffer.from(JSON.stringify(meta), 'utf8')
363
+ if (4 + json.length > PAYLOAD_SIZE) throw unavailable('元数据超过一个槽位的容量')
364
+ const head = Buffer.alloc(PAYLOAD_SIZE)
365
+ head.writeUInt32BE(json.length, 0)
366
+ json.copy(head, 4)
367
+ const sum = createHash('sha256').update(head).digest()
368
+ return Buffer.concat([head, sum])
369
+ }
370
+
371
+ /** 读一个整槽(offset 起 4096 字节)。读不满 → null。 */
372
+ function readSlotBytes(fd, offset) {
373
+ const buf = Buffer.alloc(SLOT_SIZE)
374
+ let got = 0
375
+ while (got < SLOT_SIZE) {
376
+ const n = readSync(fd, buf, got, SLOT_SIZE - got, offset + got)
377
+ if (n <= 0) break
378
+ got += n
379
+ }
380
+ return got === SLOT_SIZE ? buf : null
381
+ }
382
+
383
+ /** → {ok:true, meta} | {ok:false, reason}。expectedNo 必须与槽位自述一致。 */
384
+ export function decodeSlot(buf, expectedNo) {
385
+ if (buf.length !== SLOT_SIZE) return { ok: false, reason: 'incomplete slot' }
386
+ const head = buf.subarray(0, PAYLOAD_SIZE)
387
+ const sum = buf.subarray(PAYLOAD_SIZE)
388
+ const got = createHash('sha256').update(head).digest()
389
+ if (!got.equals(sum)) return { ok: false, reason: 'checksum mismatch' }
390
+ const len = head.readUInt32BE(0)
391
+ if (len < 2 || 4 + len > PAYLOAD_SIZE) return { ok: false, reason: 'invalid metadata length' }
392
+ for (let i = 4 + len; i < PAYLOAD_SIZE; i++) {
393
+ if (head[i] !== 0) return { ok: false, reason: 'padding is not zero' }
394
+ }
395
+ let meta
396
+ try {
397
+ meta = JSON.parse(head.subarray(4, 4 + len).toString('utf8'))
398
+ } catch {
399
+ return { ok: false, reason: 'invalid metadata JSON' }
400
+ }
401
+ if (!meta || typeof meta !== 'object') return { ok: false, reason: 'metadata is not an object' }
402
+ if (meta.version !== VERSION) return { ok: false, reason: `unsupported version ${meta.version}` }
403
+ if (meta.no !== expectedNo) return { ok: false, reason: 'number mismatch' }
404
+ if (typeof meta.body_id !== 'string' || !HEX32.test(meta.body_id)) return { ok: false, reason: 'invalid body id' }
405
+ if (typeof meta.sha256 !== 'string' || !HEX64.test(meta.sha256)) return { ok: false, reason: 'invalid body hash' }
406
+ if (!Number.isSafeInteger(meta.bytes) || meta.bytes < 1 || meta.bytes > MAX_BODY_BYTES)
407
+ return { ok: false, reason: 'invalid body length' }
408
+ if (typeof meta.title !== 'string' || meta.title.length === 0) return { ok: false, reason: 'invalid title' }
409
+ if (typeof meta.from !== 'string' || !LABEL_RE.test(meta.from)) return { ok: false, reason: 'invalid publisher' }
410
+ if (typeof meta.at !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(meta.at))
411
+ return { ok: false, reason: 'invalid time' }
412
+ return { ok: true, meta }
413
+ }
414
+
415
+ function slotAt(fd, offset, no) {
416
+ const buf = readSlotBytes(fd, offset)
417
+ if (!buf) return { ok: false, reason: 'incomplete slot' }
418
+ return decodeSlot(buf, no)
419
+ }
420
+
421
+ // ---------------------------------------------------------------- 输入校验
422
+ function validateLabel(from) {
423
+ if (!from) throw input('缺少 --from <label>')
424
+ if (from.length > MAX_LABEL || !LABEL_RE.test(from))
425
+ throw input(`--from 必须是 1–${MAX_LABEL} 个 ASCII 字母/数字/点/下划线/连字符的平坦标识符`)
426
+ }
427
+
428
+ function validateTitle(title) {
429
+ if (typeof title !== 'string' || title.length === 0) throw input('缺少 --title <title>')
430
+ const points = Array.from(title).length
431
+ if (points > MAX_TITLE_CODEPOINTS) throw input(`--title 超过 ${MAX_TITLE_CODEPOINTS} 个码点`)
432
+ if (!/\S/.test(title)) throw input('--title 不能只有空白')
433
+ if (/\r|\n/.test(title)) throw input('--title 必须是单行')
434
+ if (TITLE_FORBIDDEN_RE.test(title)) throw input('--title 含终端控制或双向/不可见格式控制字符')
435
+ if ([...title].some((ch) => ch.codePointAt(0) >= 0xd800 && ch.codePointAt(0) <= 0xdfff))
436
+ throw input('--title 不是合法 UTF-8 文本')
437
+ }
438
+
439
+ /** 有界读 stdin:读满上界+1 字节即拒;不做无界缓冲。 */
440
+ function readStdinBounded() {
441
+ const chunks = []
442
+ let total = 0
443
+ const buf = Buffer.alloc(65536)
444
+ for (;;) {
445
+ let n
446
+ try {
447
+ n = readSync(0, buf, 0, buf.length, null)
448
+ } catch (e) {
449
+ if (errnoOf(e) === 'EAGAIN') {
450
+ sleepMs(5)
451
+ continue
452
+ }
453
+ if (errnoOf(e) === 'EINTR') continue
454
+ throw input(`读 stdin 失败(${errnoOf(e) || e.message})`)
455
+ }
456
+ if (n === 0) break
457
+ total += n
458
+ if (total > MAX_BODY_BYTES) throw input(`正文超过上界 ${MAX_BODY_BYTES} 字节(不截断)`)
459
+ chunks.push(Buffer.from(buf.subarray(0, n)))
460
+ }
461
+ const body = Buffer.concat(chunks, total)
462
+ if (body.length === 0) throw input('正文不能为空')
463
+ if (body.includes(0)) throw input('正文里不许有 NUL 字节')
464
+ try {
465
+ new TextDecoder('utf-8', { fatal: true }).decode(body)
466
+ } catch {
467
+ throw input('正文不是合法 UTF-8')
468
+ }
469
+ return body
470
+ }
471
+
472
+ // ---------------------------------------------------------------- 锁
473
+ function acquireLock(lockFd) {
474
+ // `stdio` 的第 4 项让子进程在 fd 3 上拿到**同一个** open-file description;flock 的参数
475
+ // 因此是子进程的 fd 号 3(不是父进程的 lockFd —— 子进程的 fd 表是重映射过的)。锁挂在那个
476
+ // OFD 上:flock 退出后父进程仍持有 fd 3,锁不释放;本进程退出/被 kill 时内核释放。
477
+ const r = spawnSync('flock', ['-w', String(LOCK_WAIT_SEC), '3'], {
478
+ stdio: ['ignore', 'ignore', 'ignore', lockFd],
479
+ })
480
+ if (r.error) {
481
+ if (errnoOf(r.error) === 'ENOENT') throw unavailable('本机没有 flock:无锁发布不可用')
482
+ throw unavailable(`flock 起不来(${errnoOf(r.error) || r.error.message})`)
483
+ }
484
+ if (r.status === 0) return
485
+ if (r.status === 1) throw busy(`写锁被占用超过 ${LOCK_WAIT_SEC * 1000}ms`)
486
+ throw unavailable(`flock 返回 ${r.status}`)
487
+ }
488
+
489
+ // ---------------------------------------------------------------- post
490
+ /** next number for `slots` committed slots; 越界一律 unavailable(不环绕、不覆盖)。 */
491
+ export function nextNumber(slots) {
492
+ const no = slots + 1
493
+ if (!Number.isSafeInteger(no) || no > MAX_NO) {
494
+ throw unavailable(`编号已达上界 ${MAX_NO}(不环绕、不覆盖)`)
495
+ }
496
+ return no
497
+ }
498
+
499
+ function cmdPost(args) {
500
+ const from = args.from
501
+ const title = args.title
502
+ validateLabel(from)
503
+ validateTitle(title)
504
+ if (!args.stdin) throw input('post 只从 stdin 取正文:必须显式给 --stdin')
505
+ const body = readStdinBounded()
506
+ const sha256 = createHash('sha256').update(body).digest('hex')
507
+
508
+ const store = openStore(args.mainRoot, args.stateDir, 'write')
509
+ if (!store.ok) throw storageError(store)
510
+ let tmpPath = null
511
+ try {
512
+ acquireLock(store.lockFd)
513
+ // ① 恢复:明确不足 4096 字节的尾部截到完整槽边界;完整坏槽不许当未提交尾巴处理。
514
+ let size = fstatSync(store.indexFd).size
515
+ let slots = Math.floor(size / SLOT_SIZE)
516
+ if (size % SLOT_SIZE !== 0) {
517
+ ftruncateSync(store.indexFd, slots * SLOT_SIZE)
518
+ fsyncSync(store.indexFd)
519
+ }
520
+ if (slots > 0) {
521
+ const last = slotAt(store.indexFd, (slots - 1) * SLOT_SIZE, slots)
522
+ if (!last.ok)
523
+ throw unavailable(`索引最后一个完整槽位不可用(no=${slots}:${last.reason})——不覆盖已提交槽位`)
524
+ }
525
+ const no = nextNumber(slots)
526
+ const at = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
527
+
528
+ // ② 原文先 durable:独占创建的临时文件 → fsync → 无覆盖地发布到 bodies/ → fsync 目录。
529
+ const bodyId = randomBytes(16).toString('hex')
530
+ const tmpName = `.tmp-${bodyId}`
531
+ tmpPath = fdPath(store.krFd, tmpName)
532
+ const tmpFd = openSync(tmpPath, C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW | C.O_NONBLOCK, 0o600)
533
+ try {
534
+ let off = 0
535
+ while (off < body.length) {
536
+ const n = writeSync(tmpFd, body, off, body.length - off)
537
+ off += n
538
+ hit('body-write')
539
+ }
540
+ hit('body-fsync')
541
+ fsyncSync(tmpFd)
542
+ } finally {
543
+ closeQuiet(tmpFd)
544
+ }
545
+ hit('body-staged')
546
+ hit('body-link')
547
+ linkSync(tmpPath, fdPath(store.bodiesFd, `${bodyId}.md`))
548
+ unlinkSync(tmpPath)
549
+ tmpPath = null
550
+ fsyncSync(store.bodiesFd)
551
+ hit('body-published')
552
+
553
+ // ③ 完整槽位 + fsync 之后才有可读条目。
554
+ const meta = { version: VERSION, no, body_id: bodyId, title, from, at, bytes: body.length, sha256 }
555
+ const slot = encodeSlot(meta)
556
+ let wrote = 0
557
+ if (process.env.TEAM_REPLY_FAULT === 'fail:index-write') {
558
+ writeSync(store.indexFd, slot, 0, Math.floor(SLOT_SIZE / 2), slots * SLOT_SIZE)
559
+ throw unavailable('故障注入:index-write')
560
+ }
561
+ while (wrote < SLOT_SIZE) wrote += writeSync(store.indexFd, slot, wrote, SLOT_SIZE - wrote, slots * SLOT_SIZE + wrote)
562
+ hit('index-written')
563
+ let durable = true
564
+ try {
565
+ // fail:index-fsync = 模拟**真的 fsync 失败**(普通错误 → durable=false → unconfirmed 路径)。
566
+ if (process.env.TEAM_REPLY_FAULT === 'fail:index-fsync') throw new Error('injected fsync failure')
567
+ fsyncSync(store.indexFd)
568
+ } catch (e) {
569
+ if (e instanceof ReplyError) throw e
570
+ durable = false
571
+ }
572
+ if (!durable) {
573
+ // append 已可见但最终 fsync 失败:unconfirmed + candidate_no,绝不自动重发。
574
+ process.stdout.write(
575
+ `${JSON.stringify({ outcome: 'unconfirmed', candidate_no: no, title, from, at, bytes: body.length, sha256 })}\n`,
576
+ )
577
+ process.exit(6)
578
+ }
579
+ hit('index-durable')
580
+ process.stdout.write(
581
+ `${JSON.stringify({ outcome: 'saved', no, title, from, at, bytes: body.length, sha256 })}\n`,
582
+ )
583
+ } finally {
584
+ if (tmpPath) {
585
+ try {
586
+ unlinkSync(tmpPath)
587
+ } catch {
588
+ /* kill 造成的孤立 blob 保留而不引入后台 GC */
589
+ }
590
+ }
591
+ closeStore(store)
592
+ }
593
+ }
594
+
595
+ function storageError(r) {
596
+ if (r.kind === 'missing') return unavailable('关键回复存储不可用(缺目录;post 需要能创建它)')
597
+ if (r.kind === 'unsafe') return unavailable(kindReason(r))
598
+ if (r.kind === 'error') return unavailable(kindReason(r))
599
+ return unavailable('关键回复存储不可用')
600
+ }
601
+
602
+ // ---------------------------------------------------------------- 只读面
603
+ /** 读者的 store 打开:缺失 = 空 store(返回 {empty:true});损坏/权限 = unavailable。 */
604
+ function openReadStore(args) {
605
+ const store = openStore(args.mainRoot, args.stateDir, 'read')
606
+ if (store.ok) return store
607
+ if (store.kind === 'missing') return { ok: true, empty: true }
608
+ throw unavailable(kindReason(store))
609
+ }
610
+
611
+ function indexWarnings(size) {
612
+ const w = []
613
+ if (size % SLOT_SIZE !== 0) w.push({ kind: 'partial-tail', bytes: size % SLOT_SIZE })
614
+ return w
615
+ }
616
+
617
+ function listEntry(meta) {
618
+ return {
619
+ no: meta.no,
620
+ available: true,
621
+ title: sanitize(meta.title),
622
+ from: sanitize(meta.from),
623
+ at: meta.at,
624
+ bytes: meta.bytes,
625
+ sha256: meta.sha256,
626
+ }
627
+ }
628
+
629
+ function cmdSummary(args) {
630
+ const store = openReadStore(args)
631
+ if (store.empty) {
632
+ process.stdout.write(`${JSON.stringify({ available: true, state: 'empty', total_slots: 0, warnings: [] })}\n`)
633
+ return
634
+ }
635
+ try {
636
+ const size = fstatSync(store.indexFd).size
637
+ const slots = Math.floor(size / SLOT_SIZE)
638
+ const warnings = indexWarnings(size)
639
+ if (slots === 0) {
640
+ process.stdout.write(
641
+ `${JSON.stringify({ available: true, state: 'empty', total_slots: 0, warnings })}\n`,
642
+ )
643
+ return
644
+ }
645
+ const last = slotAt(store.indexFd, (slots - 1) * SLOT_SIZE, slots)
646
+ if (!last.ok) {
647
+ process.stdout.write(
648
+ `${JSON.stringify({ available: true, state: 'unavailable', total_slots: slots, warnings, reason: last.reason })}\n`,
649
+ )
650
+ return
651
+ }
652
+ process.stdout.write(
653
+ `${JSON.stringify({ available: true, state: 'ok', total_slots: slots, warnings, entry: listEntry(last.meta) })}\n`,
654
+ )
655
+ } finally {
656
+ closeStore(store)
657
+ }
658
+ }
659
+
660
+ function parseCursor(raw) {
661
+ if (raw === undefined || raw === null) return null
662
+ const s = String(raw)
663
+ if (!/^[0-9]+$/.test(s)) throw input('--before 必须是正整数')
664
+ const n = Number(s)
665
+ if (!Number.isSafeInteger(n) || n < 1 || n > MAX_NO) throw input(`--before 超出编号域(1–${MAX_NO})`)
666
+ return n
667
+ }
668
+
669
+ function parseNo(raw) {
670
+ if (raw === undefined || raw === null) throw input('show 需要 --no <编号>')
671
+ const s = String(raw)
672
+ if (!/^[0-9]+$/.test(s)) throw input('--no 必须是正整数')
673
+ const n = Number(s)
674
+ if (!Number.isSafeInteger(n) || n < 1 || n > MAX_NO) throw input(`--no 超出编号域(1–${MAX_NO})`)
675
+ return n
676
+ }
677
+
678
+ function cmdList(args) {
679
+ const before = parseCursor(args.before)
680
+ const format = args.format || 'json'
681
+ const store = openReadStore(args)
682
+ if (store.empty) {
683
+ if (format === 'json')
684
+ process.stdout.write(
685
+ `${JSON.stringify({ available: true, state: 'empty', total_slots: 0, entries: [], next_before: null, warnings: [] })}\n`,
686
+ )
687
+ else process.stdout.write('(没有关键回复)\n')
688
+ return
689
+ }
690
+ try {
691
+ const size = fstatSync(store.indexFd).size
692
+ const slots = Math.floor(size / SLOT_SIZE)
693
+ const warnings = indexWarnings(size)
694
+ const newest = slots === 0 ? 0 : before === null ? slots : Math.min(before - 1, slots)
695
+ let hi = newest
696
+ const entries = []
697
+ while (hi >= 1 && entries.length < LIST_PAGE) {
698
+ const r = slotAt(store.indexFd, (hi - 1) * SLOT_SIZE, hi)
699
+ if (r.ok) entries.push(listEntry(r.meta))
700
+ else entries.push({ no: hi, available: false, reason: r.reason })
701
+ hi--
702
+ }
703
+ const oldest = entries.length ? entries[entries.length - 1].no : 0
704
+ const nextBefore = oldest > 1 ? oldest : null
705
+ if (format === 'json') {
706
+ process.stdout.write(
707
+ `${JSON.stringify({
708
+ available: true,
709
+ state: slots === 0 ? 'empty' : 'ok',
710
+ total_slots: slots,
711
+ entries,
712
+ next_before: nextBefore,
713
+ warnings,
714
+ })}\n`,
715
+ )
716
+ return
717
+ }
718
+ if (entries.length === 0) {
719
+ process.stdout.write('(没有关键回复)\n')
720
+ return
721
+ }
722
+ for (const e of entries) {
723
+ if (e.available) process.stdout.write(`#${e.no}\t${e.at}\t${e.from}\t${e.title}\n`)
724
+ else process.stdout.write(`#${e.no}\t不可用(${sanitize(e.reason)})\n`)
725
+ }
726
+ if (nextBefore) process.stdout.write(`older: team reply list --before ${nextBefore}\n`)
727
+ } finally {
728
+ closeStore(store)
729
+ }
730
+ }
731
+
732
+ function readBody(store, meta) {
733
+ if (typeof store.bodiesFd !== 'number') throw unavailable(`正文目录缺失(no=${meta.no})`)
734
+ const r = openFileAt(store.bodiesFd, `${meta.body_id}.md`, C.O_RDONLY)
735
+ if (!r.ok) {
736
+ if (r.kind === 'missing') throw unavailable(`正文文件缺失(no=${meta.no})`)
737
+ throw unavailable(kindReason(r))
738
+ }
739
+ try {
740
+ const st = fstatSync(r.fd)
741
+ if (st.size !== meta.bytes) throw unavailable(`正文长度与提交记录不一致(no=${meta.no})`)
742
+ if (st.size > MAX_BODY_BYTES) throw unavailable(`正文超过上界(no=${meta.no})`)
743
+ const buf = Buffer.alloc(st.size + 1)
744
+ let got = 0
745
+ while (got < st.size) {
746
+ const n = readSync(r.fd, buf, got, st.size - got, got)
747
+ if (n <= 0) break
748
+ got += n
749
+ }
750
+ const extra = readSync(r.fd, buf, st.size, 1, st.size)
751
+ if (got !== st.size || extra !== 0) throw unavailable(`正文读取不完整(no=${meta.no})`)
752
+ const body = buf.subarray(0, st.size)
753
+ const digest = createHash('sha256').update(body).digest('hex')
754
+ if (digest !== meta.sha256) throw unavailable(`正文哈希与提交记录不一致(no=${meta.no})`)
755
+ return body
756
+ } finally {
757
+ closeQuiet(r.fd)
758
+ }
759
+ }
760
+
761
+ function cmdShow(args) {
762
+ const no = parseNo(args.no)
763
+ const format = args.format || 'text'
764
+ const store = openReadStore(args)
765
+ if (store.empty) throw unavailable(`没有编号 ${no} 的关键回复(存储为空)`)
766
+ try {
767
+ const size = fstatSync(store.indexFd).size
768
+ const slots = Math.floor(size / SLOT_SIZE)
769
+ if (no > slots) throw unavailable(`没有编号 ${no} 的关键回复(已提交 ${slots} 个编号)`)
770
+ const r = slotAt(store.indexFd, (no - 1) * SLOT_SIZE, no)
771
+ if (!r.ok) throw unavailable(`编号 ${no} 不可用(${r.reason})`)
772
+ const meta = r.meta
773
+ const body = readBody(store, meta)
774
+ if (format === 'raw') {
775
+ process.stdout.write(body)
776
+ return
777
+ }
778
+ let display
779
+ try {
780
+ display = new TextDecoder('utf-8', { fatal: true }).decode(body)
781
+ } catch {
782
+ throw unavailable(`编号 ${no} 的正文不是合法 UTF-8`)
783
+ }
784
+ if (format === 'json') {
785
+ process.stdout.write(
786
+ `${JSON.stringify({
787
+ no: meta.no,
788
+ available: true,
789
+ title: sanitize(meta.title),
790
+ from: sanitize(meta.from),
791
+ at: meta.at,
792
+ bytes: meta.bytes,
793
+ sha256: meta.sha256,
794
+ text_kind: 'safe-display',
795
+ display_text: sanitize(display),
796
+ })}\n`,
797
+ )
798
+ return
799
+ }
800
+ process.stdout.write(`#${meta.no} ${sanitize(meta.title)}\n`)
801
+ process.stdout.write(
802
+ `来自 ${sanitize(meta.from)}(自称)· ${meta.at} · ${meta.bytes} 字节 · sha256 ${meta.sha256.slice(0, 16)}…\n\n`,
803
+ )
804
+ process.stdout.write(sanitize(display))
805
+ if (!display.endsWith('\n')) process.stdout.write('\n')
806
+ } finally {
807
+ closeStore(store)
808
+ }
809
+ }
810
+
811
+ // ---------------------------------------------------------------- 入口
812
+ function parseArgs(argv) {
813
+ const out = { _: [] }
814
+ for (let i = 0; i < argv.length; i++) {
815
+ const a = argv[i]
816
+ switch (a) {
817
+ case '--main-root':
818
+ case '--state-dir':
819
+ case '--from':
820
+ case '--title':
821
+ case '--before':
822
+ case '--no':
823
+ case '--format': {
824
+ const key = a.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase())
825
+ if (i + 1 >= argv.length) throw input(`${a} 缺少值`)
826
+ out[key] = argv[++i]
827
+ break
828
+ }
829
+ case '--stdin':
830
+ out.stdin = true
831
+ break
832
+ case '-h':
833
+ case '--help':
834
+ out.help = true
835
+ break
836
+ default:
837
+ throw input(`未知参数 ${a}`)
838
+ }
839
+ }
840
+ return out
841
+ }
842
+
843
+ function usage() {
844
+ process.stdout.write(
845
+ [
846
+ '用法(内部 helper;人用的入口是 team reply):',
847
+ ' replies.mjs post --main-root <dir> --state-dir <dir> --from <label> --title <t> --stdin',
848
+ ' replies.mjs summary --main-root <dir> --state-dir <dir>',
849
+ ' replies.mjs list --main-root <dir> --state-dir <dir> [--before <no>] [--format json|text]',
850
+ ' replies.mjs show --main-root <dir> --state-dir <dir> --no <no> [--format json|text|raw]',
851
+ '',
852
+ ].join('\n'),
853
+ )
854
+ }
855
+
856
+ const IS_ENTRY =
857
+ typeof process.argv[1] === 'string' && import.meta.url === pathToFileURL(process.argv[1]).href
858
+
859
+ if (IS_ENTRY) {
860
+ const cmd = process.argv[2]
861
+ const rest = process.argv.slice(3)
862
+ main(() => {
863
+ const args = parseArgs(rest)
864
+ if (args.help || !cmd) {
865
+ usage()
866
+ return
867
+ }
868
+ args.mainRoot = parseMainRoot(args.mainRoot)
869
+ if (!args.stateDir) throw input('缺少 --state-dir')
870
+ args.stateDir = resolve(args.mainRoot, args.stateDir)
871
+ switch (cmd) {
872
+ case 'post':
873
+ cmdPost(args)
874
+ return
875
+ case 'summary':
876
+ cmdSummary(args)
877
+ return
878
+ case 'list':
879
+ if (args.format && args.format !== 'json' && args.format !== 'text') throw input('--format 只接受 json|text')
880
+ cmdList(args)
881
+ return
882
+ case 'show':
883
+ if (args.format && !['json', 'text', 'raw'].includes(args.format))
884
+ throw input('--format 只接受 json|text|raw')
885
+ cmdShow(args)
886
+ return
887
+ default:
888
+ throw input(`未知子命令 ${cmd}`)
889
+ }
890
+ })
891
+ }
892
+
893
+ export { cmdList as _cmdList, cmdShow as _cmdShow, cmdSummary as _cmdSummary, cmdPost as _cmdPost }