teamsmith 0.4.6 → 0.4.7

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 (70) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +24 -0
  4. package/skills/teamsmith/SKILL.md +32 -23
  5. package/skills/teamsmith/extension/team-bg.ts +5 -3
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +14 -3
  7. package/skills/teamsmith/extension/team-notify.ts +20 -13
  8. package/skills/teamsmith/extension/team-remind.ts +189 -0
  9. package/skills/teamsmith/extension/team-reply.ts +4 -7
  10. package/skills/teamsmith/references/migration.md +101 -0
  11. package/skills/teamsmith/references/openspec.md +43 -27
  12. package/skills/teamsmith/references/protocol.md +26 -15
  13. package/skills/teamsmith/references/reminders.md +153 -161
  14. package/skills/teamsmith/references/troubleshooting.md +12 -7
  15. package/skills/teamsmith/references/workflows.md +84 -31
  16. package/skills/teamsmith/scripts/lib/cmd-agents.sh +10 -4
  17. package/skills/teamsmith/scripts/lib/cmd-project.sh +88 -6
  18. package/skills/teamsmith/scripts/lib/cmd-remind.sh +88 -2
  19. package/skills/teamsmith/scripts/lib/cmd-review.sh +42 -4
  20. package/skills/teamsmith/scripts/lib/cmd-watch.sh +48 -11
  21. package/skills/teamsmith/scripts/lib/common.sh +83 -13
  22. package/skills/teamsmith/scripts/panel/panel.js +179 -179
  23. package/skills/teamsmith/scripts/panel/src/data.ts +71 -15
  24. package/skills/teamsmith/scripts/panel/src/layout.ts +20 -8
  25. package/skills/teamsmith/scripts/panel/src/main.tsx +83 -21
  26. package/skills/teamsmith/scripts/remind-capability.mjs +261 -0
  27. package/skills/teamsmith/scripts/remind-store.mjs +55 -24
  28. package/skills/teamsmith/scripts/remind-tick.mjs +5 -2
  29. package/skills/teamsmith/scripts/reply-capture.mjs +8 -9
  30. package/skills/teamsmith/scripts/state-authority.mjs +72 -6
  31. package/skills/teamsmith/scripts/team +1 -0
  32. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +11 -8
  33. package/skills/teamsmith/templates/DECISIONS.md.tmpl +2 -2
  34. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +3 -3
  35. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +19 -14
  36. package/skills/teamsmith/templates/memory-seed.md.tmpl +2 -2
  37. package/skills/teamsmith/templates/pm-prompt.md.tmpl +31 -19
  38. package/skills/teamsmith/templates/report.md.tmpl +33 -0
  39. package/skills/teamsmith/tests/bg-ledger-harness.mjs +217 -33
  40. package/skills/teamsmith/tests/bg-ledger.sh +24 -10
  41. package/skills/teamsmith/tests/checkout-shape-probe.sh +7 -6
  42. package/skills/teamsmith/tests/fixtures/remind-adversarial-delay.ts +27 -0
  43. package/skills/teamsmith/tests/fixtures/remind-tool-provider.ts +65 -0
  44. package/skills/teamsmith/tests/help-surface.sh +3 -5
  45. package/skills/teamsmith/tests/isolation-ledger.sh +6 -2
  46. package/skills/teamsmith/tests/key-replies-ui.sh +53 -0
  47. package/skills/teamsmith/tests/key-replies.sh +307 -106
  48. package/skills/teamsmith/tests/lib/routes-pages.sh +243 -0
  49. package/skills/teamsmith/tests/loop-inventory.tsv +1 -0
  50. package/skills/teamsmith/tests/panel-b3-stub.sh +9 -2
  51. package/skills/teamsmith/tests/remind-adversarial-faults.mjs +163 -0
  52. package/skills/teamsmith/tests/remind-adversarial-faults.sh +26 -0
  53. package/skills/teamsmith/tests/remind-adversarial-real.sh +27 -0
  54. package/skills/teamsmith/tests/remind-cli.sh +108 -3
  55. package/skills/teamsmith/tests/remind-delivery-node.mjs +13 -0
  56. package/skills/teamsmith/tests/remind-delivery.sh +123 -35
  57. package/skills/teamsmith/tests/remind-lifecycle.sh +197 -0
  58. package/skills/teamsmith/tests/remind-pulse.sh +199 -0
  59. package/skills/teamsmith/tests/remind-recovery-real.sh +5 -0
  60. package/skills/teamsmith/tests/remind-recovery-unit.sh +118 -0
  61. package/skills/teamsmith/tests/remind-tool-node.mjs +159 -0
  62. package/skills/teamsmith/tests/remind-tool-real.mjs +754 -0
  63. package/skills/teamsmith/tests/remind-tool-real.sh +5 -0
  64. package/skills/teamsmith/tests/reply-capture-real.mjs +93 -2
  65. package/skills/teamsmith/tests/routes.sh +213 -293
  66. package/skills/teamsmith/tests/section-paths.tsv +10 -8
  67. package/skills/teamsmith/tests/smoke.sh +484 -28
  68. package/skills/teamsmith/tests/state-authority.sh +152 -8
  69. package/skills/teamsmith-init/SKILL.md +5 -5
  70. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
@@ -0,0 +1,243 @@
1
+ # routes-pages.sh — shared help-page parsing and content judgement for routes.sh.
2
+ # Test-only code: the caller owns rendering, fixtures, scratch roots and cleanup.
3
+
4
+ # Write the command/usage parser shared by manifest claims and every rendered page.
5
+ mr_write_parser() {
6
+ cat > "$tmp/walk-a.awk" <<'AWK'
7
+ function fail(ln, msg) { printf "FAIL\t%d\t%s\n", ln, msg }
8
+ function tokenize(s, arr, offs, rest, tok, n, pos) {
9
+ n=0; rest=s; pos=1
10
+ while (match(rest, /\[[^]]*\]|[^ \t]+/)) {
11
+ tok=substr(rest, RSTART, RLENGTH)
12
+ n++; arr[n]=tok; offs[n]=pos+RSTART-1
13
+ pos += RSTART-1+RLENGTH; rest=substr(rest, RSTART+RLENGTH)
14
+ }
15
+ return n
16
+ }
17
+ function isph(t) {
18
+ if (t ~ /^<.*>$/) return 1
19
+ if (t ~ /^".*"$/ || t ~ /^'.*'$/) return 1
20
+ if (t=="..." || t=="…" || t=="ID" || t=="N" || t=="X") return 1
21
+ return 0
22
+ }
23
+ function addverb(w) { if (!(w in VERBW)) { VERBW[w]=1; NV++; VERBW_LIST[NV]=w } }
24
+ function lastwordpos(s, w, re, off, best) {
25
+ re = "(^|[ \t])" w "([^ \t]|$)"
26
+ off=0; best=0
27
+ while (off < length(s) && match(substr(s, off+1), re)) {
28
+ best = off + RSTART
29
+ off = best + RLENGTH - 2
30
+ if (RLENGTH <= 0) break
31
+ }
32
+ return best
33
+ }
34
+ function emit(ln, path, flag, key) {
35
+ key = path "\t" flag
36
+ if (key in EMITTED) return
37
+ EMITTED[key]=1
38
+ printf "CLAIM\t%d\t%s\t%s\n", ln, path, flag
39
+ }
40
+ function one_fragment(frag, ln, nt, toks, offs, i, t, core, j, k, na, alts, ok, usage_end, rest, base, fl, fpos, bind, best, w, p, nnp, newp, isbr) {
41
+ nt = tokenize(frag, toks, offs)
42
+ # `version / help` (and only that shape): a plain ` / ` splits into fragments when BOTH sides
43
+ # start with a command; `perf … (交互首帧 / 帧装配 / …)` is description text and must not split.
44
+ if (nt >= 1) {
45
+ # handled by the caller (expand_slash)
46
+ }
47
+ t = toks[1]; gsub(/^\[|\]$/, "", t)
48
+ if (!(t in TOP)) { fail(ln, "这一行无法归属到命令(首 token「" t "」不是 CLI 的命令):" frag); return }
49
+ NP=1; PATHS[1]=t; NV=0; delete VERBW; delete VERBW_LIST; delete EMITTED
50
+ usage_end = offs[1]+length(toks[1])-1
51
+ for (i=2; i<=nt; i++) {
52
+ t=toks[i]
53
+ isbr = (t ~ /^\[.*\]$/)
54
+ core=t; if (isbr) core=substr(t,2,length(t)-2)
55
+ if (isph(core) || core ~ /^-/) { usage_end = offs[i]+length(t)-1; continue }
56
+ if (index(core, "|") > 0) {
57
+ na=split(core, alts, "|"); ok=1
58
+ for (j=1;j<=NP;j++) for (kk=1;kk<=na;kk++) if (!(PATHS[j] " " alts[kk] in SUB)) ok=0
59
+ if (ok) {
60
+ nnp=0
61
+ for (j=1;j<=NP;j++) for (kk=1;kk<=na;kk++) { nnp++; newp[nnp]=PATHS[j] " " alts[kk] }
62
+ NP=nnp; for (j=1;j<=nnp;j++) PATHS[j]=newp[j]
63
+ for (kk=1;kk<=na;kk++) addverb(alts[kk])
64
+ usage_end = offs[i]+length(t)-1
65
+ continue
66
+ }
67
+ # 未解析的组:可选的([...])当参数——如 standby [on|off|status];不带的则是一句「这个命令有这些子命令」
68
+ # 的假活,必须红(不能静默降级成只有主命令)。
69
+ if (isbr) break
70
+ fail(ln, "这一行的命令组无法解析(" core "):" frag); return
71
+ }
72
+ ok=1
73
+ for (j=1;j<=NP;j++) if (!(PATHS[j] " " core in SUB)) ok=0
74
+ if (ok) {
75
+ for (j=1;j<=NP;j++) PATHS[j]=PATHS[j] " " core
76
+ addverb(core)
77
+ usage_end = offs[i]+length(t)-1
78
+ continue
79
+ }
80
+ break # 参数/描述文本:命令部分到此为止
81
+ }
82
+ # every --flag on the line, judged at its own offset
83
+ rest=frag; base=0
84
+ while (match(rest, /--[a-z0-9-]+/)) {
85
+ fl=substr(rest, RSTART, RLENGTH)
86
+ fpos=base+RSTART
87
+ base=base+RSTART+RLENGTH-1
88
+ rest=substr(rest, RSTART+RLENGTH)
89
+ if (fpos <= usage_end) {
90
+ for (j=1;j<=NP;j++) emit(ln, PATHS[j], fl)
91
+ continue
92
+ }
93
+ # description flag: the nearest preceding verb token of this fragment's own group, else the
94
+ # fragment's command(s) — `board …(add [--allow-dup] …)` binds to `board add`, `perf …;--host …`
95
+ # to `perf`.
96
+ best=0
97
+ for (kk=1;kk<=NV;kk++) { p=lastwordpos(substr(frag, 1, fpos-1), VERBW_LIST[kk]); if (p>best) best=p }
98
+ bind=0
99
+ if (best > 0) {
100
+ for (kk=1;kk<=NV;kk++) {
101
+ w=VERBW_LIST[kk]
102
+ if (lastwordpos(substr(frag, 1, fpos-1), w) != best) continue
103
+ for (j=1;j<=NP;j++) if (PATHS[j] ~ ("(^| )" w "$")) { emit(ln, PATHS[j], fl); bind=1 }
104
+ }
105
+ }
106
+ if (bind == 0) {
107
+ for (j=1;j<=NP;j++) emit(ln, PATHS[j], fl)
108
+ }
109
+ }
110
+ }
111
+ function expand_slash(frag, ln, np, parts, i, first, ok) {
112
+ np = split(frag, parts, / \/ /)
113
+ if (np > 1) {
114
+ ok=1
115
+ for (i=1;i<=np;i++) { first=parts[i]; sub(/^[ \t]+/,"",first); sub(/[ \t].*/,"",first); if (!(first in TOP)) ok=0 }
116
+ if (ok) { for (i=1;i<=np;i++) one_fragment(parts[i], ln); return }
117
+ }
118
+ one_fragment(frag, ln)
119
+ }
120
+ BEGIN {
121
+ n=split(tops, ta, " "); for (i=1;i<=n;i++) { gsub(/^[ \t]+|[ \t]+$/, "", ta[i]); if (ta[i]!="") TOP[ta[i]]=1 }
122
+ m=split(subs, sa, ";")
123
+ for (i=1;i<=m;i++) {
124
+ if (sa[i]=="") continue
125
+ if (split(sa[i], kv, ":") < 2) continue
126
+ p=kv[1]; gsub(/^[ \t]+|[ \t]+$/, "", p)
127
+ c=split(kv[2], sb, ",")
128
+ for (j=1;j<=c;j++) { gsub(/^[ \t]+|[ \t]+$/, "", sb[j]); if (sb[j]!="") SUB[p " " sb[j]]=1 }
129
+ }
130
+ inblock=0; lastindent=-1
131
+ }
132
+ {
133
+ line=$0
134
+ if (line ~ /^[ \t]*$/) next
135
+ if (line ~ /^[ \t]*──/) { inblock=1; lastindent=-1; next }
136
+ if (!inblock) next
137
+ m=match(line, /[^ \t]/); ind=m-1; rest=substr(line, m)
138
+ first=rest; sub(/[ \t].*/,"",first)
139
+ isentry = (first in TOP)
140
+ if (ind == 0) {
141
+ # 列 0 的行:命令块的正文一律缩进(对齐的续行更深)。
142
+ # · 打旗标的 → 无法归属(修复前的 board 形状:列 0 + [--allow-dup])→ 红;
143
+ # · 首 token 是命令的 → 未缩进的条目(形状约定是 2 空格)→ 红;
144
+ # · 其余(help 末尾的 配置:/协议: 页脚,不打印旗标)→ 块到此为止,忽略。
145
+ if (line ~ /--[a-z0-9-]+/) { fail(NR, "命令块里列 0 的行带着旗标(无法归属到任何条目):" rest) }
146
+ else if (isentry) { fail(NR, "命令块里的命令条目没有缩进(列 0):" rest) }
147
+ inblock=0; next
148
+ }
149
+ if (lastindent >= 0 && ind > lastindent) { next } # 缩进更深的行是上一条目的续行(哪怕它首 token 像个命令)
150
+ if (!isentry) {
151
+ fail(NR, "这一行既不是命令条目,也没有比上一条目缩进更深(无法归属):" rest)
152
+ next
153
+ }
154
+ lastindent=ind
155
+ printf "ENTRY\t%d\n", NR
156
+ # 全角分隔符在 bash 侧先换成 \x1f —— awk(mawk)按字节看字符类,直接写 [|/] 会在
157
+ # 任何中文 UTF-8 字节上乱切(实测把一行劈成单字碎片)。
158
+ nf = split($0, frags, "\037")
159
+ for (i=1;i<=nf;i++) expand_slash(frags[i], NR)
160
+ }
161
+ AWK
162
+ }
163
+
164
+ # mr_page_usage <page-file> → usage entries, one per line (continuations joined).
165
+ mr_page_usage() {
166
+ awk '
167
+ function indent(l) { m=match(l, /[^ ]/); return m-1 }
168
+ { l=$0
169
+ if (l ~ /^[ \t]*$/) next
170
+ ind=indent(l)
171
+ if (l ~ /^──/) { inblock=1; lastindent=-1; cur=""; next }
172
+ if (!inblock) next
173
+ if (ind == 0) { if (cur!="") { print cur; cur="" }; inblock=0; next }
174
+ if (lastindent >= 0 && ind > lastindent && ind < 6) { if (cur != "") cur = cur " " substr(l, ind+1); next }
175
+ if (lastindent >= 0 && ind > lastindent) { next } # the description block: not part of the usage line
176
+ if (cur != "") print cur
177
+ cur=substr(l, ind+1); lastindent=ind
178
+ }
179
+ END { if (cur != "") print cur }
180
+ ' "$1"
181
+ }
182
+
183
+ # mr_page_judge <kind> <label> <actual-page-file>
184
+ # The caller supplies n_pages/n_entries/n_claims and LEVEL_OK in its current shell.
185
+ # A nonempty page counts as read even when its contents have findings; an empty file does not.
186
+ mr_page_judge() {
187
+ local kind="$1" label="$2" page="$3"
188
+ local failed=0 declared printed want got extra gone ln rest
189
+ [ -s "$page" ] || { finding "walk: 帮助面缺一页($kind $label)"; return 1; }
190
+ n_pages=$((n_pages + 1))
191
+ if [ "$kind" = "command" ]; then
192
+ # The page's own usage header must be there (a deleted header is a defect, never a skip).
193
+ grep -qE '^── (Usage|用法)' "$page" || { finding "walk: $label 的页没有用法头部(Usage:/用法:)"; failed=1; }
194
+ declared="$(awk -F'\t' -v c="$label" '$1==c {print $2}' < <(mr_fragments) | sort)"
195
+ printed="$(mr_page_usage "$page" | sort)"
196
+ if [ "$declared" != "$printed" ]; then
197
+ extra="$(comm -13 <(printf '%s\n' "$declared") <(printf '%s\n' "$printed") | head -3 | paste -sd ' ' -)"
198
+ gone="$(comm -23 <(printf '%s\n' "$declared") <(printf '%s\n' "$printed") | head -3 | paste -sd ' ' -)"
199
+ finding "walk: $label 的页与清单不一致(页上多出:${extra:-无};页上缺少:${gone:-无})"
200
+ failed=1
201
+ fi
202
+ if printf '%s\n' "$printed" | grep -q -- '--ghost-probe\|--frobnicate-probe'; then
203
+ finding "walk: $label 的页打印了清单没有的旗标($(printf '%s\n' "$printed" | grep -- '--ghost-probe\|--frobnicate-probe' | head -1))"
204
+ failed=1
205
+ fi
206
+ LEVEL_OK[command]=1
207
+ elif [ "$kind" = "group" ]; then
208
+ want="$(awk -F'\t' -v g="$label" '$1=="cmd" && $3==g {n=split($4,f," ;; "); print f[1]}' "$(mr_manifest)" | sort)"
209
+ got="$(mr_page_usage "$page" | sort)"
210
+ if [ "$want" != "$got" ]; then
211
+ finding "walk: 组页 $label 与清单不一致($(diff <(printf '%s\n' "$want") <(printf '%s\n' "$got") | grep '^[<>]' | head -2 | tr '\n' ' '))"
212
+ failed=1
213
+ fi
214
+ LEVEL_OK[group]=1
215
+ else
216
+ want="$(mr_begin | tr ' ' '\n' | grep -v '^$' | sort)"
217
+ got="$(mr_page_usage "$page" | awk '{print $1}' | sort)"
218
+ if [ "$want" != "$got" ]; then
219
+ finding "walk: 菜单的上手命令与清单的 begin 行不一致($(diff <(printf '%s\n' "$want") <(printf '%s\n' "$got") | grep '^[<>]' | head -2 | tr '\n' ' '))"
220
+ failed=1
221
+ fi
222
+ LEVEL_OK[menu]=1
223
+ fi
224
+ # The same parser reads every level (block rules unchanged).
225
+ awk -v tops="$MRI_TOPS" -v subs="$MRI_SUBS" -f "$tmp/walk-a.awk" "$page" > "$tmp/page-claims.tsv" 2>/dev/null
226
+ while IFS=$'\t' read -r _ ln rest; do
227
+ finding "walk: $kind $label 的第 $ln 行无法归属(解析器拒绝静默跳过):$rest"
228
+ failed=1
229
+ done < <(grep -a '^FAIL' "$tmp/page-claims.tsv")
230
+ n_entries=$((n_entries + $(grep -ac '^ENTRY' "$tmp/page-claims.tsv" || true)))
231
+ n_claims=$((n_claims + $(grep -ac '^CLAIM' "$tmp/page-claims.tsv" || true)))
232
+ ok "walk: $kind $label 判过($(grep -ac '^ENTRY' "$tmp/page-claims.tsv" || true) 条用法行,$(grep -ac '^CLAIM' "$tmp/page-claims.tsv" || true) 条断言)"
233
+ [ "$failed" -eq 0 ]
234
+ }
235
+
236
+ # Finish level judgement over the nonempty pages actually opened by mr_page_judge.
237
+ mr_level_finish() {
238
+ local failed=0 lv
239
+ for lv in menu group command; do
240
+ [ -n "${LEVEL_OK[$lv]:-}" ] || { finding "walk: $lv 这一级一条都没被判到(静默漏读)"; failed=1; }
241
+ done
242
+ [ "$failed" -eq 0 ]
243
+ }
@@ -12,6 +12,7 @@ panel-b3.sh 173 cap="$i" -le "${B3_CAP_ITERS:-600}" while [ "$i" -le "${B3_CAP
12
12
  panel-cpu.sh 248 bound=sub_end 计算出的截止时间(到点自己退出) while :; do
13
13
  panel-p21.sh 1813 cap="$_i" -le 15 while [ "$_i" -le 15 ]; do
14
14
  pm-box-real.sh 175 cap="$i" -lt "$READY_TRIES" while [ "$i" -lt "$READY_TRIES" ]; do
15
+ remind-pulse.sh 50 cap="$tries" -gt 0 while [ "$tries" -gt 0 ]; do
15
16
  smoke.sh 226 cap="$SNAP_W" -lt 50 SNAP_W=0; while kill -0 "$SNAP_CHILD" 2>/dev/null && [ "$SNAP_W" -lt 50 ]; do sleep 0.2; SNAP_W=$((SNAP_W + 1)); done
16
17
  smoke.sh 503 bound=等待者的耐心上限 lock_cap(每轮跟着持有者心跳现算:活 4W / 停或没有 W;到点 break 进超限分支) while :; do
17
18
  smoke.sh 1277 bound=停止位文件 SMOKE_TMP_STOP + 主 shell 寿命(M33 哨兵的文件握手) while [ ! -e "$SMOKE_TMP_STOP" ]; do
@@ -349,8 +349,14 @@ closed" ;;
349
349
  }
350
350
 
351
351
  # pulse-key-replies 的固定回复块(stub 面;见上面的三条 case)。
352
+ # 时间默认不变;P436 用同一固定 UTC 输入切换 TZ,并可注入非法值或省略字段验证显示降级。
353
+ reply_at_json() {
354
+ [ "${B3_STUB_REPLY_AT_OMIT:-0}" = "1" ] && return 0
355
+ printf '"at": %s, ' "$(json_str "${B3_STUB_REPLY_AT:-2026-09-16T09:59:00Z}")"
356
+ }
352
357
  reply_entry_json() {
353
- printf '{"no": 1, "available": true, "title": "固定关键回复", "from": "dev2", "at": "2026-09-16T09:59:00Z", "bytes": 24, "sha256": "%s"}' "$(printf 'a%.0s' {1..64})"
358
+ printf '{"no": 1, "available": true, "title": "固定关键回复", "from": "dev2", %s"bytes": 24, "sha256": "%s"}' \
359
+ "$(reply_at_json)" "$(printf 'a%.0s' {1..64})"
354
360
  }
355
361
  reply_summary_json() {
356
362
  case "${B3_STUB_REPLY:-empty}" in
@@ -367,7 +373,8 @@ reply_list_json() {
367
373
  esac
368
374
  }
369
375
  reply_body_json() {
370
- printf '%s\n' '{"no": 1, "available": true, "title": "固定关键回复", "from": "dev2", "at": "2026-09-16T09:59:00Z", "bytes": 24, "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "text_kind": "safe-display", "display_text": "固定回复正文\n第二行\n"}'
376
+ printf '{"no": 1, "available": true, "title": "固定关键回复", "from": "dev2", %s"bytes": 24, "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "text_kind": "safe-display", "display_text": %s}\n' \
377
+ "$(reply_at_json)" "$(json_str_ml $'固定回复正文\n第二行\n')"
371
378
  }
372
379
 
373
380
  case "$block" in
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ // P444: real SIGKILL injection around Reminder intent/observation and writeAtomic boundaries.
3
+ // Faults exist only in per-case scratch copies. Recovery always runs the unmodified production helper.
4
+ import assert from 'node:assert/strict'
5
+ import { spawnSync } from 'node:child_process'
6
+ import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join, resolve } from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { setTimeout as delay } from 'node:timers/promises'
10
+
11
+ const tests = dirname(fileURLToPath(import.meta.url)), skill = dirname(tests)
12
+ const root = mkdtempSync('/var/tmp/p444-remind-faults-'), home = join(root, 'home'), tmp = join(root, 'tmp')
13
+ mkdirSync(home, { recursive: true }); mkdirSync(tmp, { recursive: true })
14
+ const runner = process.execPath, team = join(skill, 'scripts/team'), original = join(skill, 'scripts/state-authority.mjs')
15
+ const env = { ...process.env, HOME: home, TMPDIR: tmp }
16
+ for (const key of Object.keys(env)) if (key.startsWith('TEAM_') || key === 'TMUX' || key === 'TMUX_PANE') delete env[key]
17
+ let passed = 0, failed = 0
18
+ const stateFile = repo => join(repo, '.pi/team/state/reminders/state.json')
19
+ const snap = repo => JSON.parse(readFileSync(stateFile(repo), 'utf8'))
20
+ const lastBatch = repo => snap(repo).batches.at(-1)
21
+ const run = (bin, args, options = {}) => {
22
+ const result = spawnSync(bin, args, { encoding: 'utf8', env, ...options })
23
+ assert.equal(result.error, undefined, `${bin}: ${result.error}`)
24
+ return result
25
+ }
26
+ const good = (result, label) => assert.equal(result.status, 0, `${label}: ${result.stdout}${result.stderr}`)
27
+ function newRepo(name) {
28
+ const repo = join(root, name); mkdirSync(repo, { recursive: true })
29
+ good(run('git', ['init', '-q', repo]), 'git init')
30
+ good(run('git', ['-C', repo, '-c', 'user.name=fixture', '-c', 'user.email=fixture@example.invalid',
31
+ 'commit', '-q', '--allow-empty', '-m', 'fixture']), 'git commit')
32
+ return repo
33
+ }
34
+ function authority(helper, repo, args, label = 'authority') {
35
+ const result = run(runner, [helper, '--cli', repo, join(repo, '.pi/team/state'), ...args],
36
+ { cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] })
37
+ writeFileSync(join(repo, 'last-authority.txt'), (result.stdout ?? '') + (result.stderr ?? ''))
38
+ return result
39
+ }
40
+ function goodAuthority(helper, repo, args, label) {
41
+ const result = authority(helper, repo, args, label)
42
+ good(result, `${label}: ${readFileSync(join(repo, 'last-authority.txt'), 'utf8')}`)
43
+ return JSON.parse(result.stdout)
44
+ }
45
+ function setup(op, point) {
46
+ const repo = newRepo(`${op}-${point}`)
47
+ const add = run('bash', [team, '--root', repo, 'remind', 'add', '--after', '1s', '--message', `P444 ${op} ${point}`], { cwd: repo })
48
+ good(add, 'real one-second Reminder create')
49
+ goodAuthority(original, repo, ['standby-on', '--reason', 'G1', '--json'], 'G1')
50
+ return repo
51
+ }
52
+ async function admit(repo) {
53
+ await delay(1100) // Real due time; the fixture never rewrites a clock or a callback timestamp.
54
+ const started = new Date(Date.now() - 10000).toISOString()
55
+ const result = run(runner, [join(skill, 'scripts/remind-tick.mjs'), '--root', repo, '--state-dir', join(repo, '.pi/team/state'),
56
+ '--pulse-started', started, '--json'], { cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] })
57
+ good(result, `due admission: ${result.stdout}${result.stderr}`)
58
+ assert.equal(snap(repo).reminders[0].phase, 'queued')
59
+ }
60
+ function makeIntent(repo) {
61
+ return goodAuthority(original, repo, ['remind-intent', '--session', 'p444-session', '--pid', '4242'], 'original intent')
62
+ }
63
+ function observeArgs(intent) {
64
+ return ['remind-observe', '--id', intent.batch.id, '--nonce', intent.batch.nonce,
65
+ '--session', 'p444-session', '--members', JSON.stringify(intent.batch.members)]
66
+ }
67
+ function faultyHelper(op, point) {
68
+ const dir = join(root, `helper-${op}-${point}`); mkdirSync(dir, { recursive: true })
69
+ cpSync(original, join(dir, 'state-authority.mjs')); cpSync(join(skill, 'scripts/remind-store.mjs'), join(dir, 'remind-store.mjs'))
70
+ const file = join(dir, 'state-authority.mjs'), source = readFileSync(file, 'utf8')
71
+ const fault = `
72
+ function p444Fault(point, op, value) {
73
+ if (process.env.P444_KILL_POINT !== point || process.env.P444_FAULT_OP !== op) return;
74
+ if (value) {
75
+ const auditOp = op === 'remind-intent' ? 'remind-intent' : 'remind-observed';
76
+ if (!value.audit?.some(entry => entry.op === auditOp)) return;
77
+ }
78
+ fs.appendFileSync(process.env.P444_FAULT_MARK, point + '\\n');
79
+ process.kill(process.pid, 'SIGKILL');
80
+ }
81
+ `
82
+ const atomicAnchor = 'function writeAtomic(file, value) {'
83
+ assert.equal(source.split(atomicAnchor).length, 2, 'writeAtomic injection anchor')
84
+ let changed = source.replace(atomicAnchor, `${fault}\n${atomicAnchor}`)
85
+ const anchors = [
86
+ [" const before = JSON.stringify(snapshot);", " p444Fault('before-apply', request.op, null);\n const before = JSON.stringify(snapshot);"],
87
+ [" const result = apply(snapshot, request, Date.now(), state);", " const result = apply(snapshot, request, Date.now(), state);\n p444Fault('after-apply', request.op, snapshot);"],
88
+ [" fs.writeFileSync(fd, JSON.stringify(value) + '\\n', 'utf8');", " fs.writeFileSync(fd, JSON.stringify(value) + '\\n', 'utf8');\n p444Fault('before-file-fsync', request.op, value);"],
89
+ [" fs.fsyncSync(fd);", " fs.fsyncSync(fd);\n p444Fault('after-file-fsync', request.op, value);"],
90
+ [" fs.renameSync(tmp, file);\n fsyncDir(dir);", " fs.renameSync(tmp, file);\n p444Fault('after-rename', request.op, value);\n fsyncDir(dir);\n p444Fault('after-dir-fsync', request.op, value);"],
91
+ ]
92
+ for (const [oldText, newText] of anchors) {
93
+ assert.equal(changed.split(oldText).length, 2, `fault anchor ${oldText}`)
94
+ changed = changed.replace(oldText, newText)
95
+ }
96
+ // writeAtomic has no request parameter; the scratch-only shim receives the selected operation via env.
97
+ changed = changed.replaceAll('request.op, value', 'process.env.P444_FAULT_OP, value')
98
+ writeFileSync(file, changed)
99
+ return join(dir, 'state-authority.mjs')
100
+ }
101
+ async function runCase(op, point) {
102
+ const repo = setup(op, point)
103
+ await admit(repo)
104
+ const intent = op === 'remind-intent' ? null : makeIntent(repo)
105
+ const helper = faultyHelper(op, point), mark = join(repo, 'fault-mark.txt')
106
+ const requestEnv = { ...env, P444_FAULT_OP: op, P444_KILL_POINT: point, P444_FAULT_MARK: mark }
107
+ const args = op === 'remind-intent' ? ['remind-intent', '--session', 'p444-session', '--pid', '4242'] : observeArgs(intent)
108
+ const result = spawnSync(runner, [helper, '--cli', repo, join(repo, '.pi/team/state'), ...args],
109
+ { cwd: repo, env: requestEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
110
+ assert.notEqual(result.status, 0, `${op} ${point}: injected process must die`)
111
+ assert.equal(readFileSync(mark, 'utf8').trim(), point, `${op} ${point}: exact death point reached`)
112
+ const committed = point === 'after-rename' || point === 'after-dir-fsync'
113
+ let current = snap(repo)
114
+ if (op === 'remind-intent') {
115
+ if (committed) {
116
+ assert.equal(current.batches.length, 1); assert.equal(current.reminders[0].phase, 'intent')
117
+ const recovered = goodAuthority(original, repo, args, 'restart with original helper')
118
+ assert.equal(recovered.action, 'wait', 'a durable intent is not sendable again after restart')
119
+ assert.equal(snap(repo).batches.length, 1)
120
+ } else {
121
+ assert.equal(current.batches.length, 0); assert.equal(current.reminders[0].phase, 'queued')
122
+ const recovered = goodAuthority(original, repo, args, 'restart with original helper')
123
+ assert.equal(recovered.action, 'send', 'a pre-intent crash remains eligible once')
124
+ assert.equal(snap(repo).batches.length, 1)
125
+ }
126
+ assert.equal(snap(repo).standby.on, true, 'intent and recovery never clear Standby')
127
+ } else {
128
+ if (committed) {
129
+ assert.equal(current.batches[0].phase, 'observed'); assert.equal(current.reminders[0].phase, 'observed')
130
+ assert.equal(current.standby.on, false); assert.equal(current.batches[0].rightSpentBy, 'wake')
131
+ assert.equal(current.audit.filter(entry => entry.op === 'remind-observed').length, 1)
132
+ } else {
133
+ assert.equal(current.batches[0].phase, 'intent'); assert.equal(current.reminders[0].phase, 'intent')
134
+ assert.equal(current.standby.on, true); assert.equal(current.batches[0].right, 'unspent')
135
+ assert.equal(current.audit.filter(entry => entry.op === 'remind-observed').length, 0)
136
+ }
137
+ goodAuthority(original, repo, ['standby-off', '--json'], 'manual off before fresh G2')
138
+ goodAuthority(original, repo, ['standby-on', '--reason', 'fresh G2', '--json'], 'fresh G2')
139
+ const replay = goodAuthority(original, repo, observeArgs(intent), 'original-helper replay')
140
+ assert.equal(replay.outcome, committed ? 'duplicate' : 'observed')
141
+ assert.equal(replay.standby, committed ? undefined : 'generation-ambiguous')
142
+ current = snap(repo)
143
+ assert.equal(current.standby.on, true); assert.equal(current.standby.generation, 2)
144
+ assert.equal(current.audit.filter(entry => entry.op === 'remind-observed').length, 1)
145
+ }
146
+ writeFileSync(join(repo, 'recovery-receipt.json'), JSON.stringify({ op, point, committed,
147
+ restart: snap(repo) }, null, 2))
148
+ }
149
+
150
+ const points = ['before-apply', 'after-apply', 'before-file-fsync', 'after-file-fsync', 'after-rename', 'after-dir-fsync']
151
+ try {
152
+ const lock = run('flock', ['--version'])
153
+ assert.equal(lock.status, 0, 'flock is required; missing evidence is a failure, not SKIP')
154
+ for (const op of ['remind-intent', 'remind-observe']) for (const point of points) {
155
+ try { await runCase(op, point); console.log(`FAULT PASS ${op} ${point}`); passed++ }
156
+ catch (error) { console.error(`FAULT FAIL ${op} ${point}: ${error.stack}`); failed++ }
157
+ }
158
+ } finally {
159
+ if (process.env.P444_KEEP) console.log(`kept fault evidence=${root}`)
160
+ else rmSync(root, { recursive: true, force: true })
161
+ }
162
+ console.log(`fault-matrix: passed=${passed} failed=${failed}`)
163
+ if (failed) process.exitCode = 1
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env bash
2
+ # P444: real process-death injection around intent/observation atomic commits.
3
+ set -uo pipefail
4
+ HERE="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
+ SKILL="$(cd -P "$HERE/.." && pwd)"
6
+ # shellcheck source=lib/main-team-fingerprint.sh
7
+ . "$HERE/lib/main-team-fingerprint.sh"
8
+ # shellcheck source=../scripts/lib/common.sh
9
+ . "$SKILL/scripts/lib/common.sh"
10
+ REAL_MAIN="$(main_team_project_root "$SKILL")"
11
+ STAMP="$(main_team_snapshot "${REAL_MAIN:-/nonexistent}/.pi/team")"
12
+ BEFORE="$(mktemp "$(team_tmp_root)/.teamsmith-p444-fault-before.XXXXXX")" || exit 3
13
+ AFTER="$(mktemp "$(team_tmp_root)/.teamsmith-p444-fault-after.XXXXXX")" || { rm -f "$BEFORE"; exit 3; }
14
+ printf '%s\n' "$STAMP" >"$BEFORE"
15
+ node "$HERE/remind-adversarial-faults.mjs" "$@"
16
+ RC=$?
17
+ main_team_snapshot "${REAL_MAIN:-/nonexistent}/.pi/team" >"$AFTER"
18
+ VIOL="$(main_team_violations "$BEFORE" "$AFTER")"
19
+ rm -f "$BEFORE" "$AFTER"
20
+ if [ -n "$VIOL" ]; then
21
+ printf 'remind-adversarial-faults: 主项目 .pi/team 出现非白名单变化:%s\n' "$VIOL" >&2
22
+ RC=1
23
+ elif [ "$RC" -eq 0 ]; then
24
+ printf 'remind-adversarial-faults: isolation=ok\n'
25
+ fi
26
+ exit "$RC"
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env bash
2
+ # P444: private real Pi/tmux controlled-model event, replay and process-death acceptance.
3
+ set -uo pipefail
4
+ HERE="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
+ SKILL="$(cd -P "$HERE/.." && pwd)"
6
+ # shellcheck source=lib/main-team-fingerprint.sh
7
+ . "$HERE/lib/main-team-fingerprint.sh"
8
+ # shellcheck source=../scripts/lib/common.sh
9
+ . "$SKILL/scripts/lib/common.sh"
10
+ REAL_MAIN="$(main_team_project_root "$SKILL")"
11
+ STAMP="$(main_team_snapshot "${REAL_MAIN:-/nonexistent}/.pi/team")"
12
+ BEFORE="$(mktemp "$(team_tmp_root)/.teamsmith-p444-real-before.XXXXXX")" || exit 3
13
+ AFTER="$(mktemp "$(team_tmp_root)/.teamsmith-p444-real-after.XXXXXX")" || { rm -f "$BEFORE"; exit 3; }
14
+ printf '%s\n' "$STAMP" >"$BEFORE"
15
+ export P442_EVIDENCE="${P442_EVIDENCE:-$(mktemp -d "$(team_tmp_root)/teamsmith-p444-real-evidence-$(team_project_ns).XXXXXX")}"
16
+ node "$HERE/remind-tool-real.mjs" --select=adversarial,death "$@"
17
+ RC=$?
18
+ main_team_snapshot "${REAL_MAIN:-/nonexistent}/.pi/team" >"$AFTER"
19
+ VIOL="$(main_team_violations "$BEFORE" "$AFTER")"
20
+ rm -f "$BEFORE" "$AFTER"
21
+ if [ -n "$VIOL" ]; then
22
+ printf 'remind-adversarial-real: 主项目 .pi/team 出现非白名单变化:%s\n' "$VIOL" >&2
23
+ RC=1
24
+ elif [ "$RC" -eq 0 ]; then
25
+ printf 'remind-adversarial-real: isolation=ok evidence=%s\n' "$P442_EVIDENCE"
26
+ fi
27
+ exit "$RC"