teamsmith 0.4.5 → 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 (81) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +37 -1
  4. package/skills/teamsmith/SKILL.md +32 -23
  5. package/skills/teamsmith/extension/team-bg.ts +12 -11
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +149 -5
  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 +28 -18
  13. package/skills/teamsmith/references/reminders.md +133 -98
  14. package/skills/teamsmith/references/troubleshooting.md +12 -7
  15. package/skills/teamsmith/references/workflows.md +85 -34
  16. package/skills/teamsmith/scripts/lib/cmd-agents.sh +28 -5
  17. package/skills/teamsmith/scripts/lib/cmd-project.sh +100 -15
  18. package/skills/teamsmith/scripts/lib/cmd-remind.sh +135 -10
  19. package/skills/teamsmith/scripts/lib/cmd-review.sh +42 -4
  20. package/skills/teamsmith/scripts/lib/cmd-update.sh +90 -88
  21. package/skills/teamsmith/scripts/lib/cmd-watch.sh +322 -159
  22. package/skills/teamsmith/scripts/lib/common.sh +156 -26
  23. package/skills/teamsmith/scripts/panel/panel.js +182 -182
  24. package/skills/teamsmith/scripts/panel/src/data.ts +113 -6
  25. package/skills/teamsmith/scripts/panel/src/layout.ts +26 -4
  26. package/skills/teamsmith/scripts/panel/src/main.tsx +103 -14
  27. package/skills/teamsmith/scripts/remind-capability.mjs +261 -0
  28. package/skills/teamsmith/scripts/remind-store.mjs +404 -17
  29. package/skills/teamsmith/scripts/remind-tick.mjs +105 -0
  30. package/skills/teamsmith/scripts/reminder-delivery.mjs +76 -0
  31. package/skills/teamsmith/scripts/reply-capture.mjs +8 -9
  32. package/skills/teamsmith/scripts/state-authority.mjs +334 -20
  33. package/skills/teamsmith/scripts/strings/commands.tsv +3 -3
  34. package/skills/teamsmith/scripts/strings/help.en.tsv +12 -12
  35. package/skills/teamsmith/scripts/strings/help.zh.tsv +12 -12
  36. package/skills/teamsmith/scripts/team +4 -3
  37. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +13 -11
  38. package/skills/teamsmith/templates/DECISIONS.md.tmpl +2 -2
  39. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +3 -3
  40. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +19 -14
  41. package/skills/teamsmith/templates/memory-seed.md.tmpl +2 -2
  42. package/skills/teamsmith/templates/pm-prompt.md.tmpl +36 -18
  43. package/skills/teamsmith/templates/report.md.tmpl +33 -0
  44. package/skills/teamsmith/tests/bg-ledger-harness.mjs +217 -33
  45. package/skills/teamsmith/tests/bg-ledger.sh +24 -10
  46. package/skills/teamsmith/tests/checkout-shape-probe.sh +7 -6
  47. package/skills/teamsmith/tests/death-cause.sh +5 -0
  48. package/skills/teamsmith/tests/fixtures/remind-adversarial-delay.ts +27 -0
  49. package/skills/teamsmith/tests/fixtures/remind-tool-provider.ts +65 -0
  50. package/skills/teamsmith/tests/help-surface.sh +14 -151
  51. package/skills/teamsmith/tests/isolation-ledger.sh +89 -0
  52. package/skills/teamsmith/tests/key-replies-ui.sh +53 -0
  53. package/skills/teamsmith/tests/key-replies.sh +307 -106
  54. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +17 -1
  55. package/skills/teamsmith/tests/lib/routes-pages.sh +243 -0
  56. package/skills/teamsmith/tests/live-capture-probe.sh +12 -2
  57. package/skills/teamsmith/tests/loop-inventory.tsv +1 -0
  58. package/skills/teamsmith/tests/panel-b3-stub.sh +9 -2
  59. package/skills/teamsmith/tests/pulse-nudge-key.sh +5 -0
  60. package/skills/teamsmith/tests/remind-adversarial-faults.mjs +163 -0
  61. package/skills/teamsmith/tests/remind-adversarial-faults.sh +26 -0
  62. package/skills/teamsmith/tests/remind-adversarial-real.sh +27 -0
  63. package/skills/teamsmith/tests/remind-cli.sh +108 -3
  64. package/skills/teamsmith/tests/remind-delivery-node.mjs +189 -0
  65. package/skills/teamsmith/tests/remind-delivery.sh +699 -0
  66. package/skills/teamsmith/tests/remind-lifecycle.sh +197 -0
  67. package/skills/teamsmith/tests/remind-pulse.sh +199 -0
  68. package/skills/teamsmith/tests/remind-recovery-real.sh +5 -0
  69. package/skills/teamsmith/tests/remind-recovery-unit.sh +118 -0
  70. package/skills/teamsmith/tests/remind-tool-node.mjs +159 -0
  71. package/skills/teamsmith/tests/remind-tool-real.mjs +754 -0
  72. package/skills/teamsmith/tests/remind-tool-real.sh +5 -0
  73. package/skills/teamsmith/tests/reply-capture-real.mjs +93 -2
  74. package/skills/teamsmith/tests/routes.sh +213 -293
  75. package/skills/teamsmith/tests/section-paths.tsv +14 -12
  76. package/skills/teamsmith/tests/smoke.sh +876 -130
  77. package/skills/teamsmith/tests/state-authority.sh +392 -28
  78. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +58 -8
  79. package/skills/teamsmith/tests/tmux-identity-leak.sh +12 -16
  80. package/skills/teamsmith-init/SKILL.md +5 -5
  81. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
@@ -36,7 +36,7 @@ for arg in "$@"; do
36
36
  case "$arg" in
37
37
  --flip=*)
38
38
  case "${arg#--flip=}" in
39
- view-stored|no-prune|highwater-lax|past-time|key-conflict-gone) FLIPS+=("${arg#--flip=}") ;;
39
+ view-stored|no-prune|highwater-lax|past-time|key-conflict-gone|key-not-released|no-key-dedup|json-refusal) FLIPS+=("${arg#--flip=}") ;;
40
40
  *) printf 'remind-cli:不认识的 --flip 值 [%s]\n' "${arg#--flip=}" >&2; exit 2 ;;
41
41
  esac ;;
42
42
  -h|--help) sed -n '2,26p' "$0"; exit 0 ;;
@@ -187,6 +187,11 @@ printf 'first line — 中文 100%%\nsecond line\n\n' > "$ROOT/msg/full.txt"
187
187
  FULL_BYTES="$(wc -c < "$ROOT/msg/full.txt" | tr -d ' ')"
188
188
  printf 'line one\nline two\n' > "$ROOT/msg/two.txt"
189
189
  printf 'probe text\n' > "$ROOT/msg/x.txt"
190
+ python3 - "$ROOT/msg/large.txt" <<'PY'
191
+ import sys
192
+ with open(sys.argv[1], 'wb') as f:
193
+ f.write(b'x' * (64 * 1024) + b'\n')
194
+ PY
190
195
  : > "$ROOT/msg/empty.txt"
191
196
  : > "$ROOT/msg/none"
192
197
  printf 'a\000b' > "$ROOT/msg/nul.bin"
@@ -252,6 +257,42 @@ assert_has "A list:取消后计数跟着变(cancelled=1,只剩 2099 那条
252
257
  "视图 scheduled=1 derived-due=0 queued=0 intent=0 observed=0 unknown=0 cancelled=1 resolved=0"
253
258
  assert_has "A list:取消的那条仍在保留的终结历史里" "$(cat "$ROOT/out/a7.txt")" "另有 1 条已终结"
254
259
 
260
+ # 无额度:100 条活跃记录 + 最近一分钟 20 次创建之后,1 秒延迟与 64 KiB 全文仍然合法。
261
+ Q="$(new_repo Q)" || { bad "夹具建不出仓库 Q"; result; exit 1; }
262
+ run_team "$Q" "$ROOT/msg/none" "$ROOT/out/q0.txt" remind add --after 2h --message seed
263
+ [ "$RC" = "0" ] || bad "Q 夹具:种子提醒没建成($(head -1 "$ROOT/out/q0.txt"))"
264
+ cat > "$ROOT/script/q-fill.mjs" <<'JS'
265
+ snap.reminders = Array.from({ length: 100 }, (_, index) => ({
266
+ id: 'rem-' + snap.project.id + '-' + (index + 1), seq: index + 1, owner: 'pm', source: 'cli', task: null, key: null,
267
+ phase: 'scheduled', createdAt: new Date().toISOString(), request: { form: 'after', value: '2h' },
268
+ dueAt: new Date(Date.now() + 7200000).toISOString(), message: 'active ' + (index + 1), endedAt: null,
269
+ }));
270
+ snap.sequences.reminder = 101;
271
+ snap.audit = Array.from({ length: 20 }, () => ({ at: new Date().toISOString(), op: 'remind-add', ids: ['recent'], source: 'cli' }));
272
+ JS
273
+ edit_snapshot "$Q" "$ROOT/script/q-fill.mjs"
274
+ run_team "$Q" "$ROOT/msg/large.txt" "$ROOT/out/q1.txt" remind add --after 1s --message-file "$ROOT/msg/large.txt"
275
+ assert_eq "Q 100 条活跃 + 20 次近期创建后,1s/64KiB 请求仍建成" "$RC" "0"
276
+ Q_ID="$(sed -n 's/^已创建 \(rem-[^ ]*\) · .*/\1/p' "$ROOT/out/q1.txt")"
277
+ assert_has "Q 新记录使用第 101 个单调 ID" "$Q_ID" '-101'
278
+ run_team "$Q" "$ROOT/msg/none" "$ROOT/out/q2.txt" remind show "$Q_ID" --json
279
+ if jdump "$ROOT/out/q2.txt" reminder.message "$ROOT/out/q-show-message.txt" \
280
+ && cmp -s "$ROOT/msg/large.txt" "$ROOT/out/q-show-message.txt"; then
281
+ ok "Q show 保留 64 KiB + 末尾换行(65537 字节)"
282
+ else
283
+ bad "Q show 的正文被截断或改写字节"
284
+ fi
285
+ run_team "$Q" "$ROOT/msg/none" "$ROOT/out/q3.txt" remind list --json
286
+ "$RUNNER" -e '
287
+ import fs from "node:fs";
288
+ const result = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
289
+ const record = result.active.find(item => item.id === process.argv[2]);
290
+ if (!record) process.exit(3);
291
+ fs.writeFileSync(process.argv[3], record.message);
292
+ ' "$ROOT/out/q3.txt" "$Q_ID" "$ROOT/out/q-list-message.txt"
293
+ cmp -s "$ROOT/msg/large.txt" "$ROOT/out/q-list-message.txt" \
294
+ && ok "Q list 保留同一份全文与末尾换行" || bad "Q list 的正文与原文不同"
295
+
255
296
  # ---------------------------------------------------------------- B. refusals (each names its reason, writes nothing)
256
297
  B="$(new_repo B)" || { bad "夹具建不出仓库 B"; result; exit 1; }
257
298
  run_team "$B" "$ROOT/msg/none" "$ROOT/out/b0.txt" remind add --after 2h --message seed
@@ -283,6 +324,15 @@ refuse "NUL 正文" "NUL byte" --after 2h --message-file "$ROOT/msg/nul.bin"
283
324
  refuse "非 UTF-8 正文" "not valid UTF-8" --after 2h --message-file "$ROOT/msg/bad.bin"
284
325
  refuse "key 用了非 ASCII" "outside printable ASCII" --after 2h --message-file "$ROOT/msg/x.txt" --key 有中文
285
326
 
327
+ # V150:机器调用方带 --json 时,stdin 解码/NUL 拒绝也必须是结构化结果,不能退回人读行。
328
+ for kind in nul bad; do
329
+ run_team "$B" "$ROOT/msg/none" "$ROOT/out/b-json-$kind.txt" remind add --after 2h --message-file "$ROOT/msg/$kind.bin" --json
330
+ assert_eq "B $kind 的 --json 拒绝:rc=1" "$RC" "1"
331
+ assert_eq "B $kind 的 --json 拒绝:refusal 字段" "$(jfield "$ROOT/out/b-json-$kind.txt" refusal)" "bad-message"
332
+ "$RUNNER" -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$ROOT/out/b-json-$kind.txt" \
333
+ && ok "B $kind 的 --json 拒绝:stdout 是可解析 JSON" || bad "B $kind 的 --json 拒绝混入了人读行"
334
+ done
335
+
286
336
  run_team "$B" "$ROOT/msg/none" "$ROOT/out/b-flag.txt" remind add --after 2h --message x --frobnicate
287
337
  assert_eq "B 未知参数:rc(用法错误)" "$RC" "2"
288
338
  assert_has "B 未知参数:点名该参数" "$(cat "$ROOT/out/b-flag.txt")" "--frobnicate"
@@ -320,6 +370,30 @@ else
320
370
  bad "C 终结后复用 key:没有新建(拿到 [$C_NEW])"
321
371
  fi
322
372
 
373
+ run_team "$C" "$ROOT/msg/none" "$ROOT/out/c6.txt" remind add --after 2h --message "identical without key"
374
+ C_NK1="$(sed -n 's/^已创建 \(rem-[^ ]*\) · .*/\1/p' "$ROOT/out/c6.txt")"
375
+ run_team "$C" "$ROOT/msg/none" "$ROOT/out/c7.txt" remind add --after 2h --message "identical without key"
376
+ C_NK2="$(sed -n 's/^已创建 \(rem-[^ ]*\) · .*/\1/p' "$ROOT/out/c7.txt")"
377
+ if [ -n "$C_NK1" ] && [ -n "$C_NK2" ] && [ "$C_NK1" != "$C_NK2" ]; then
378
+ ok "C 无 key 的相同正文与时长是两个独立 ID($C_NK1 / $C_NK2)"
379
+ else
380
+ bad "C 无 key 相同请求被错误去重([$C_NK1] / [$C_NK2])"
381
+ fi
382
+
383
+ # observed 也释放 key:下一次同 key 请求是新的单调一次性提醒,而不是全局幂等。
384
+ R="$(new_repo R)" || { bad "夹具建不出仓库 R"; result; exit 1; }
385
+ run_team "$R" "$ROOT/msg/none" "$ROOT/out/r1.txt" remind add --after 2h --message "cycle text" --key cycle
386
+ R_ID="$(sed -n 's/^已创建 \(rem-[^ ]*\) · .*/\1/p' "$ROOT/out/r1.txt")"
387
+ printf "const r = snap.reminders.find(item => item.id === '%s'); r.phase = 'observed'; r.endedAt = new Date().toISOString();\n" "$R_ID" > "$ROOT/script/r-observed.mjs"
388
+ edit_snapshot "$R" "$ROOT/script/r-observed.mjs"
389
+ run_team "$R" "$ROOT/msg/none" "$ROOT/out/r2.txt" remind add --after 2h --message "cycle text" --key cycle
390
+ R_NEW="$(sed -n 's/^已创建 \(rem-[^ ]*\) · .*/\1/p' "$ROOT/out/r2.txt")"
391
+ if [ -n "$R_NEW" ] && [ "$R_NEW" != "$R_ID" ]; then
392
+ ok "C observed 后同 key 新建:新单调 ID($R_ID → $R_NEW)"
393
+ else
394
+ bad "C observed 后同 key 没有新建([$R_ID] / [$R_NEW])"
395
+ fi
396
+
323
397
  # ---------------------------------------------------------------- D. views are derived, never stored
324
398
  V="$(new_repo V)" || { bad "夹具建不出仓库 V"; result; exit 1; }
325
399
  run_team "$V" "$ROOT/msg/none" "$ROOT/out/d1.txt" remind add --after 2h --message "queued one"
@@ -478,13 +552,18 @@ flip_prepare() { # <id> <helper>
478
552
  mutate "$store" " if (parsed.seq >= highWater) bad(" " if (false) bad(" ;;
479
553
  past-time) mutate "$store" " if (dueMs <= nowMs) {" " if (false) {" ;;
480
554
  key-conflict-gone) mutate "$store" " if (!sameRequest(active, candidate)) {" " if (false) {" ;;
555
+ key-not-released) mutate "$store" "const KEY_HOLDING = new Set(['scheduled', 'queued', 'intent', 'unknown']);" \
556
+ "const KEY_HOLDING = new Set(['scheduled', 'queued', 'intent', 'unknown', 'observed']);" ;;
557
+ no-key-dedup) mutate "$store" " if (key.key) {" " if (true) {" ;;
558
+ json-refusal) mutate "$2" "process.stdout.write(json ? JSON.stringify(refusal, null, 2) + '\\n' : renderRemind(requestData.op, refusal));" \
559
+ "process.stdout.write(renderRemind(requestData.op, refusal));" ;;
481
560
  *) return 1 ;;
482
561
  esac
483
562
  }
484
563
  flip_probe() { # <id> <helper>
485
564
  local id="$1" helper="$2" repo rid out
486
565
  case "$id" in
487
- view-stored|no-prune|highwater-lax|past-time|key-conflict-gone) repo="$(new_repo "flip-$id")" ;;
566
+ view-stored|no-prune|highwater-lax|past-time|key-conflict-gone|key-not-released|no-key-dedup|json-refusal) repo="$(new_repo "flip-$id")" ;;
488
567
  *) return 1 ;;
489
568
  esac
490
569
  case "$id" in
@@ -545,10 +624,36 @@ JS
545
624
  else
546
625
  bad "flip(活跃 key 的不同请求照旧返回):仍然拒绝了(rc=$RC),这条红侧是橡皮章"
547
626
  fi ;;
627
+ key-not-released)
628
+ run_helper "$helper" "$repo" "$ROOT/msg/x.txt" "$ROOT/out/p.txt" remind-add --after 2h --key cycle
629
+ rid="$(sed -n 's/^已创建 \(rem-[^ ]*\) · .*/\1/p' "$ROOT/out/p.txt")"
630
+ printf "const r = snap.reminders.find(item => item.id === '%s'); r.phase = 'observed'; r.endedAt = new Date().toISOString();\n" "$rid" > "$ROOT/script/p-cycle.mjs"
631
+ edit_snapshot "$repo" "$ROOT/script/p-cycle.mjs"
632
+ run_helper "$helper" "$repo" "$ROOT/msg/x.txt" "$ROOT/out/p2.txt" remind-add --after 2h --key cycle --json
633
+ if [ "$(jfield "$ROOT/out/p2.txt" 'reminder.id')" = "$rid" ]; then
634
+ ok "flip(observed 不释放 key):同 key 续建返回旧 ID —— C 的「观察后新 ID」会红"
635
+ else
636
+ bad "flip(observed 不释放 key):仍分配了新 ID,这条红侧是橡皮章"
637
+ fi ;;
638
+ no-key-dedup)
639
+ run_helper "$helper" "$repo" "$ROOT/msg/x.txt" "$ROOT/out/p.txt" remind-add --after 2h
640
+ run_helper "$helper" "$repo" "$ROOT/msg/x.txt" "$ROOT/out/p2.txt" remind-add --after 2h --json
641
+ if [ "$(jfield "$ROOT/out/p2.txt" 'duplicate')" = "true" ]; then
642
+ ok "flip(无 key 也去重):相同正文被合并 —— C 的「两个独立 ID」会红"
643
+ else
644
+ bad "flip(无 key 也去重):仍分配了两个 ID,这条红侧是橡皮章"
645
+ fi ;;
646
+ json-refusal)
647
+ run_helper "$helper" "$repo" "$ROOT/msg/nul.bin" "$ROOT/out/p.txt" remind-add --after 2h --json
648
+ if ! "$RUNNER" -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$ROOT/out/p.txt" 2>/dev/null; then
649
+ ok "flip(--json 拒绝退回人读行):JSON.parse 失败 —— B 的结构化拒绝断言会红"
650
+ else
651
+ bad "flip(--json 拒绝退回人读行):输出仍是 JSON,这条红侧是橡皮章"
652
+ fi ;;
548
653
  esac
549
654
  }
550
655
 
551
- for flip_id in view-stored no-prune highwater-lax past-time key-conflict-gone; do
656
+ for flip_id in view-stored no-prune highwater-lax past-time key-conflict-gone key-not-released no-key-dedup json-refusal; do
552
657
  arm_selected "$flip_id" || continue
553
658
  FLIPS_RUN="${FLIPS_RUN:+$FLIPS_RUN,}$flip_id"
554
659
  if ! helper="$(helper_copy "$flip_id")"; then
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ // remind-delivery-node.mjs — the Node half of tests/remind-delivery.sh (P423 · agent-self-reminder 3.1/3.2).
3
+ //
4
+ // Three groups, each printing `RD PASS|FAIL <name> [:: detail]` lines (the bash fixture owns the
5
+ // authority-level lifecycle; this file owns the presentation/match contract and the watcher itself):
6
+ //
7
+ // content reminderContent(): every Reminder's text byte for byte, ids, due/enqueued/attempt times,
8
+ // source/task/overdue, no truncation; reminderDetails() carries the correlation identity.
9
+ // match matchesObservation(): only our custom message with the frozen batch id, nonce and member
10
+ // set matches; role, type, nonce, batch and members each fail it on their own.
11
+ // watcher the real extension with a fake Pi host: one frozen batch → exactly one sendMessage
12
+ // (followUp, triggerTurn), durable intent before the call, the correlated message_start
13
+ // commits observed + one automatic Standby exit, a duplicate event changes nothing.
14
+ //
15
+ // Isolation: the caller (the fixture) prepares a repository, HOME/TMPDIR and strips the inherited team
16
+ // identity; this file only touches the repository path it is given and never the real project.
17
+ import { readFileSync } from 'node:fs'
18
+ import { join, resolve } from 'node:path'
19
+ import { pathToFileURL } from 'node:url'
20
+
21
+ const [skillArg, repoArg, group] = process.argv.slice(2)
22
+ if (!skillArg || !repoArg || !group) {
23
+ console.error('usage: remind-delivery-node.mjs <skill-dir> <fixture-repo> <content|match|watcher>')
24
+ process.exit(2)
25
+ }
26
+ const SKILL = resolve(skillArg)
27
+ const REPO = resolve(repoArg)
28
+ const MOD = await import(pathToFileURL(join(SKILL, 'scripts/reminder-delivery.mjs')).href)
29
+
30
+ let pass = 0
31
+ let fail = 0
32
+ const ok = (name, detail = '') => { pass++; process.stdout.write(`RD PASS ${name}${detail ? ` :: ${detail}` : ''}\n`) }
33
+ const bad = (name, detail = '') => { fail++; process.stdout.write(`RD FAIL ${name}${detail ? ` :: ${detail}` : ''}\n`) }
34
+ const check = (name, condition, detail = '') => (condition ? ok(name, detail) : bad(name, detail))
35
+ const snapshot = () => JSON.parse(readFileSync(join(REPO, '.pi/team/state/reminders/state.json'), 'utf8'))
36
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
37
+ async function waitFor(fn, timeoutMs, name) {
38
+ const deadline = Date.now() + timeoutMs
39
+ while (Date.now() < deadline) {
40
+ try { const value = fn(); if (value) return value } catch { /* the file may not exist yet */ }
41
+ await sleep(100)
42
+ }
43
+ bad(`${name}(等待超时 ${timeoutMs}ms)`)
44
+ return null
45
+ }
46
+
47
+ const MESSAGE = '第一行 hello 100%\nsecond line\n\n' // trailing blank line: the bytes are part of the text
48
+
49
+ function batchFixture(overrides = {}) {
50
+ return {
51
+ id: 'bat-00000000-0000-0000-0000-000000000000-3',
52
+ nonce: 'nonce-abc',
53
+ generation: 'off',
54
+ intentAt: '2026-11-05T10:00:00.000Z',
55
+ session: 'sess-1',
56
+ members: [
57
+ { id: 'rem-x-1', dueAt: '2026-11-05T10:00:00.000Z', enqueuedAt: '2026-11-05T10:00:09.000Z', overdue: false,
58
+ source: 'cli', task: null, key: null, message: MESSAGE },
59
+ { id: 'rem-x-2', dueAt: '2026-11-05T09:59:00.000Z', enqueuedAt: '2026-11-05T10:00:09.000Z', overdue: true,
60
+ source: 'cli', task: 'P423', key: 'check', message: 'second reminder' },
61
+ ],
62
+ ...overrides,
63
+ }
64
+ }
65
+
66
+ if (group === 'content') {
67
+ const batch = batchFixture()
68
+ const text = MOD.reminderContent(batch)
69
+ check('content 每条正文逐字节出现(含结尾空行)', text.includes(MESSAGE) && text.includes('second reminder'))
70
+ check('content 点名批次与 nonce', text.includes(batch.id) && text.includes('Nonce: nonce-abc'))
71
+ check('content 点名每条 id / due / enqueued / attempted', ['rem-x-1', 'rem-x-2'].every(id => text.includes(id)) &&
72
+ text.includes('Due: 2026-11-05T09:59:00.000Z') && text.includes('Enqueued: 2026-11-05T10:00:09.000Z') &&
73
+ text.includes('Attempted: 2026-11-05T10:00:00.000Z'))
74
+ check('content 标出补发与来源/任务/key', text.includes('overdue: the patrol queued it late') &&
75
+ text.includes('source cli') && text.includes('task P423') && text.includes('key check'))
76
+ check('content 不截断:整条正文长度原样留在消息里', (text.match(new RegExp(MESSAGE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) ?? []).length === 1)
77
+ const large = `${'x'.repeat(64 * 1024)}\n`
78
+ const largeText = MOD.reminderContent(batchFixture({ members: [{ ...batch.members[0], message: large }] }))
79
+ check('content 64 KiB + 末尾换行逐字进入投递消息', Buffer.byteLength(large, 'utf8') === 65537 &&
80
+ largeText.includes(`${large}\n\n---\n`))
81
+ const details = MOD.reminderDetails(batch)
82
+ check('details 带批次身份与成员(模型看不见的那一半)', details.batchId === batch.id && details.nonce === 'nonce-abc' &&
83
+ details.members.join(',') === 'rem-x-1,rem-x-2')
84
+ const line = MOD.deliveryLogLine(batch, 'intent-sent')
85
+ check('账本行点名批次/条数/来源,且不含提醒正文', line.includes(batch.id) && line.includes('n=2') && !line.includes('hello'))
86
+ process.stdout.write(`== remind-delivery-node content 结果 == ✓${pass} ✗${fail}\n`)
87
+ process.exit(fail ? 1 : 0)
88
+ }
89
+
90
+ if (group === 'match') {
91
+ const batch = batchFixture()
92
+ const good = { role: 'custom', customType: 'team-reminder', details: MOD.reminderDetails(batch), content: 'x' }
93
+ check('match 我们那条消息 + 冻结的身份 → 真', MOD.matchesObservation(good, batch) === true)
94
+ check('match 别的 customType → 假', MOD.matchesObservation({ ...good, customType: 'team-inbox' }, batch) === false)
95
+ check('match 非 custom 角色(助手/用户)→ 假', MOD.matchesObservation({ ...good, role: 'assistant' }, batch) === false)
96
+ check('match 没有 details → 假(身份无从证明)', MOD.matchesObservation({ ...good, details: undefined }, batch) === false)
97
+ check('match 别的 nonce → 假', MOD.matchesObservation({ ...good, details: { ...good.details, nonce: 'other' } }, batch) === false)
98
+ check('match 别的批次 → 假', MOD.matchesObservation({ ...good, details: { ...good.details, batchId: 'bat-other' } }, batch) === false)
99
+ check('match 成员集不同 → 假', MOD.matchesObservation({ ...good, details: { ...good.details, members: ['rem-x-1'] } }, batch) === false)
100
+ process.stdout.write(`== remind-delivery-node match 结果 == ✓${pass} ✗${fail}\n`)
101
+ process.exit(fail ? 1 : 0)
102
+ }
103
+
104
+ if (group !== 'watcher') {
105
+ console.error(`remind-delivery-node: unknown group ${group}`)
106
+ process.exit(2)
107
+ }
108
+
109
+ // ---------------------------------------------------------------- watcher (fake Pi host)
110
+ process.env.TEAM_REMIND_POLL_MS = '200'
111
+ const EXT = join(SKILL, 'extension/team-inbox-watch.ts')
112
+ const sent = []
113
+ const handlers = {}
114
+ let factory
115
+ try {
116
+ factory = (await import(pathToFileURL(EXT).href)).default
117
+ } catch (e) {
118
+ bad(`watcher 扩展导入失败(需要 bun/tsx 这类能直接跑 .ts 的运行时):${e.message}`)
119
+ process.stdout.write(`== remind-delivery-node watcher 结果 == ✓${pass} ✗${fail}\n`)
120
+ process.exit(1)
121
+ }
122
+ factory({
123
+ on: (name, fn) => { (handlers[name] ||= []).push(fn) },
124
+ registerTool() {},
125
+ registerCommand() {},
126
+ sendMessage: (message, options) => { sent.push({ message, options }) },
127
+ })
128
+ if (!handlers.session_start?.length || !handlers.message_start?.length) {
129
+ bad('watcher 没有注册 session_start / message_start')
130
+ process.stdout.write(`== remind-delivery-node watcher 结果 == ✓${pass} ✗${fail}\n`)
131
+ process.exit(1)
132
+ }
133
+
134
+ let sessionId = 'sess-live'
135
+ const ctx = { cwd: REPO, sessionManager: { getSessionId: () => sessionId } }
136
+ await handlers.session_start[0]({ reason: 'startup' }, ctx)
137
+ const frozen = await waitFor(() => snapshot().batches.some(b => b.phase === 'intent') || null, 8000, 'watcher 把到点提醒冻结成一批')
138
+ check('watcher 冻结后不再有 queued 记录(同一批,不会重复入队)',
139
+ Boolean(frozen) && snapshot().reminders.every(r => r.phase !== 'queued'))
140
+ const waiting = await waitFor(() => (sent.length ? sent : null), 8000, 'watcher 在一批冻结后发出消息')
141
+ const first = sent[0]
142
+ check('watcher 只发一条完整消息(一批一条)', sent.length === 1, `sent=${sent.length}`)
143
+ check('watcher 用 followUp + triggerTurn(不打断当前回合)', first?.options?.triggerTurn === true && first?.options?.deliverAs === 'followUp')
144
+ check('watcher 的 customType 是我们自己的', first?.message?.customType === 'team-reminder')
145
+ const body = String(first?.message?.content ?? '')
146
+ check('watcher 的正文带完整提醒文本(不截断)', body.includes('watcher reminder text'))
147
+ check('watcher 先写 intent 再发(快照里已有该批次)', (() => {
148
+ const snap = snapshot()
149
+ const batch = snap.batches.find(b => b.id === first?.message?.details?.batchId)
150
+ return Boolean(batch) && batch.phase === 'intent' && batch.right === 'unspent'
151
+ })(), 'snapshot has no matching intent')
152
+ const intentBatch = snapshot().batches.find(b => b.id === first?.message?.details?.batchId)
153
+ check('watcher 的意图绑定了当前待命代次', intentBatch?.generation === 1, `generation=${intentBatch?.generation}`)
154
+
155
+ // A real event with the batch id and nonce but a different frozen member set is not this message.
156
+ // It must not spend the right or clear Standby before the genuine observation arrives.
157
+ await handlers.message_start[0]({ message: { role: 'custom', customType: first.message.customType,
158
+ details: { ...first.message.details, members: [] } } })
159
+ const mismatched = snapshot()
160
+ check('watcher 批次和 nonce 相同但成员集不同 → 拒绝,权利与待命都不动',
161
+ mismatched.batches.find(b => b.id === first.message.details.batchId)?.phase === 'intent' &&
162
+ mismatched.batches.find(b => b.id === first.message.details.batchId)?.right === 'unspent' && mismatched.standby.on === true)
163
+
164
+ // the observation: Pi's own message_start for that very message
165
+ await handlers.message_start[0]({ message: { role: 'custom', customType: first.message.customType, details: first.message.details } })
166
+ const after = snapshot()
167
+ const observed = after.batches.find(b => b.id === first.message.details.batchId)
168
+ check('watcher 观察到匹配事件 → 批次 observed、right 花掉', observed?.phase === 'observed' && observed?.right === 'spent', `${observed?.phase}/${observed?.right}`)
169
+ check('watcher 的观察原子地退出待命(auto-off)', after.standby.on === false && observed?.outcome?.standby === 'auto-off',
170
+ `standby=${after.standby.on}/${observed?.outcome?.standby}`)
171
+ const observedAudit = after.audit.filter(a => a.op === 'remind-observed')
172
+ check('watcher 的审计点名批次与每个提醒(含来源)', observedAudit.length === 1 &&
173
+ observedAudit[0].batch === observed.id && observedAudit[0].ids.length === 1 && observedAudit[0].sources.length === 1)
174
+
175
+ // a duplicate/late event must change nothing and must not exit a newer generation
176
+ await handlers.message_start[0]({ message: { role: 'custom', customType: first.message.customType, details: first.message.details } })
177
+ await sleep(400)
178
+ const again = snapshot()
179
+ check('watcher 重复事件不产生第二次自动退待命', again.audit.filter(a => a.op === 'remind-observed').length === 1 &&
180
+ again.batches.find(b => b.id === observed.id)?.rightSpentBy === 'wake')
181
+
182
+ // shutdown clears the timer: nothing is sent afterwards
183
+ await handlers.session_shutdown[0]({}, ctx)
184
+ const sentAtShutdown = sent.length
185
+ await sleep(700)
186
+ check('watcher shutdown 后不再发送', sent.length === sentAtShutdown, `sent=${sent.length}`)
187
+
188
+ process.stdout.write(`== remind-delivery-node watcher 结果 == ✓${pass} ✗${fail}\n`)
189
+ process.exit(fail ? 1 : 0)