teamsmith 0.4.1 → 0.4.2

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.
@@ -1364,10 +1364,9 @@ function replyNavLine(ctx: Ctx, innerW: number): PlacedLine {
1364
1364
  }
1365
1365
 
1366
1366
  /**
1367
- * Page 5's list block. It draws the nav row, the page's one-line self-description (what this page
1368
- * holds and who publishes into it), the slot count (never a claim about readable replies), the tail
1369
- * warning when the reader reported one, and the windowed rows. The returned window is what the App
1370
- * clamps `↑`/`↓` against; `focus` is the focused slot's number.
1367
+ * Page 5's list block. It draws the nav row, the slot count (never a claim about readable
1368
+ * replies), the tail warning when the reader reported one, and the windowed rows. The returned
1369
+ * window is what the App clamps `↑`/`↓` against; `focus` is the focused slot's number.
1371
1370
  */
1372
1371
  function replyListBlock(ctx: Ctx): Block | null {
1373
1372
  const { s, blocks, deg, view } = ctx
@@ -1384,18 +1383,17 @@ function replyListBlock(ctx: Ctx): Block | null {
1384
1383
  replyList: win,
1385
1384
  summary: { line: truncLine(ln(seg(` ${s.replyHeading}`, 'heading')), ctx.width) },
1386
1385
  })
1387
- const lines: PlacedLine[] = [
1388
- replyNavLine(ctx, innerW),
1389
- { line: truncLine(ln(seg(` ${s.replyPageNote}`, 'dim')), innerW) },
1390
- ]
1386
+ const lines: PlacedLine[] = [replyNavLine(ctx, innerW)]
1391
1387
  if (!data || deg.has('reply_list')) {
1392
1388
  lines.push({ line: truncLine(ln(seg(` ${data ? s.dash : s.replyLoading}`, 'dim')), innerW) })
1393
1389
  return build(lines, { focus: 0, offset: 0, visible: 0, count: 0 })
1394
1390
  }
1395
1391
  // An empty store says so in one line: the slot count would only repeat "0" (and it is never a
1396
- // claim about readable replies when the store does have slots).
1392
+ // claim about readable replies when the store does have slots). A one-slot store gets the
1393
+ // singular form, because "1 replies" reads as a defect on the English page.
1397
1394
  if (data.state !== 'empty') {
1398
- lines.push({ line: truncLine(ln(seg(` ${fill(s.replyTotalSlots, { n: data.total_slots })}`, 'dim')), innerW) })
1395
+ const count = data.total_slots === 1 ? s.replyTotalSlotOne : s.replyTotalSlots
1396
+ lines.push({ line: truncLine(ln(seg(` ${fill(count, { n: data.total_slots })}`, 'dim')), innerW) })
1399
1397
  }
1400
1398
  if ((data.warnings ?? []).some((w) => w.kind === 'partial-tail')) {
1401
1399
  lines.push({ line: truncLine(ln(seg(` ${s.replyTailWarning}`, 'warn')), innerW) })
@@ -413,9 +413,9 @@ export const en = {
413
413
  replyNewer: 'Newer',
414
414
  replyBack: 'Back',
415
415
  replyScrollHint: '↑/↓ PgUp/PgDn Home/End scroll',
416
- replyTotalSlots: '{n} numbered slots',
416
+ replyTotalSlots: '{n} replies',
417
+ replyTotalSlotOne: '{n} reply',
417
418
  replyTailWarning: 'the index tail is incomplete (the last append did not finish)',
418
- replyPageNote: '"who is this reply written for?" — replies the PM wrote for the user',
419
419
 
420
420
  // Global keys (footer)
421
421
  keyCompose: 'm compose',
@@ -411,9 +411,10 @@ export const zh = {
411
411
  replyNewer: '更新',
412
412
  replyBack: '返回',
413
413
  replyScrollHint: '↑/↓ PgUp/PgDn Home/End 滚动',
414
- replyTotalSlots: '{n} 个编号槽位',
414
+ replyTotalSlots: '{n} 条',
415
+ // Chinese has no singular form; this key exists so the English table can say "1 reply".
416
+ replyTotalSlotOne: '{n} 条',
415
417
  replyTailWarning: '索引尾部不完整(上一次追加没有写完)',
416
- replyPageNote: '「这条回复是写给谁的?」——PM 写给用户的回复都在这里',
417
418
 
418
419
  // 全局键位(页脚)
419
420
  keyCompose: 'm 写信',
@@ -172,19 +172,9 @@ export function processIdentity(pid) {
172
172
  }
173
173
  }
174
174
 
175
- /** Groups this process can write as; a directory owned by one of them is not a foreign trust domain. */
176
- const writableGroups = () => new Set([process.getgid(), process.getegid(), ...process.getgroups()])
177
- /** Why a writable ancestor is unsafe: someone outside this process's groups can replace its entries. */
178
- function foreignWriter(mode, gid, groups) {
179
- if (mode & 0o1000) return '' // Sticky directories (system temp) protect entries the caller does not own.
180
- if (mode & 0o002) return 'is other-writable'
181
- if ((mode & 0o020) && !groups.has(gid)) return 'is group-writable outside the effective groups'
182
- return ''
183
- }
184
- /** Canonical, nonsymlink ancestry. Sticky system temp parents are allowed; so are own-group 775 layouts. */
175
+ /** Canonical, nonsymlink ancestry of plain directories. Mode bits are not a judgement (D232). */
185
176
  export function safeDirectory(path, create = false) {
186
177
  if (!isAbsolute(path) || resolve(path) !== path) throw new Error('noncanonical directory')
187
- const groups = writableGroups()
188
178
  let at = sep
189
179
  for (const part of path.split(sep).filter(Boolean)) {
190
180
  at = join(at, part)
@@ -195,19 +185,19 @@ export function safeDirectory(path, create = false) {
195
185
  st = lstatSync(at)
196
186
  }
197
187
  if (!st.isDirectory() || st.isSymbolicLink()) throw new Error(`unsafe directory ancestry: ${at} is not a plain directory`)
198
- const unsafe = foreignWriter(st.mode, st.gid, groups)
199
- if (unsafe) throw new Error(`unsafe directory ancestry: ${at} ${unsafe}`)
200
188
  }
201
189
  if (realpathSync(path) !== path) throw new Error('directory identity changed')
202
190
  return path
203
191
  }
204
192
 
193
+ /** A plain file this process owns, opened without following a symlink; mode and link count are not a judgement (D232). */
205
194
  function regular(path, flags, mode = 0o600) {
206
195
  const fd = openSync(path, flags | C.O_NOFOLLOW | C.O_NONBLOCK, mode)
207
196
  const st = fstatSync(fd)
208
- if (!st.isFile() || st.nlink !== 1 || (st.mode & 0o022)) {
197
+ const unsafe = !st.isFile() ? 'is not a regular file' : st.uid !== process.getuid() ? 'is not owned by this process' : ''
198
+ if (unsafe) {
209
199
  closeSync(fd)
210
- throw new Error('unsafe regular file')
200
+ throw new Error(`unsafe regular file: ${path} ${unsafe}`)
211
201
  }
212
202
  return fd
213
203
  }
@@ -155,5 +155,7 @@ case "$CMD" in
155
155
  local tf="$TEAM_MAIN_ROOT/${TEAM_TOKEN_FILE:-.gh-pat}"
156
156
  team_dim " 例:GH_TOKEN=\"\$(< ${TEAM_TOKEN_FILE:-.gh-pat})\" gh pr list # token 文件:$tf"
157
157
  exit 2 ;;
158
- *) team_usage_die "未知子命令:$CMD(team help 看全部;最近有破坏性变更,team version --check 检查 skill 版本)" ;;
158
+ # D228:CLI 面向用户的文案用英文。这一行自带 `team help` 的指路,所以不再走 team_usage_die
159
+ # 的通用尾巴(`run: team help` 会把同一件事再说一遍)。
160
+ *) team_err "unknown command: $CMD (see: team help)"; exit 2 ;;
159
161
  esac
@@ -92,8 +92,8 @@ kr_group_pages() {
92
92
  start_panel || { bad "pages:面板起不来"; return 1; }
93
93
  keys "5"; sleep 0.6
94
94
  want_frame list5 "pages:第 5 页列表帧(编号/标题/发布者标签)" "#2 第二份回复" "#1 完整结论与取舍" "关键回复"
95
- assert_has "$tmp/$current/list5.txt" "「这条回复是写给谁的?」" "pages:第 5 页说明行带着判据的自测题(删整行或只删自测题都会红)"
96
- assert_has "$tmp/$current/list5.txt" "个编号槽位" "pages:列表带编号槽位计数"
95
+ assert_not "$tmp/$current/list5.txt" "「这条回复是写给谁的?」" "pages:第 5 页不再有反问式说明行(把说明行加回去必须变红)"
96
+ assert_has "$tmp/$current/list5.txt" "2 条" "pages:列表显示条数(新文案「{n} 条」,不再是内部行话)"
97
97
  assert_has "$tmp/$current/list5.txt" "更早" "pages:Older 控件可见"
98
98
  ev_save "$tmp/$current/list5.txt" "pty-pages-list5.txt"
99
99
  # 原 1–4 页不动 + Tab 回绕:5 → 1
@@ -148,7 +148,7 @@ PYT
148
148
  start_panel || { bad "overview:面板起不来"; return 1; }
149
149
  want_frame ov_pane "overview:面板总览上的摘要行" "#1 总览入口标题" "最新关键回复"
150
150
  keys "5"; sleep 0.6
151
- want_frame ov_page5 "overview:按 5 到第 5 页最新列表" "#1 总览入口标题" "个编号槽位"
151
+ want_frame ov_page5 "overview:按 5 到第 5 页最新列表" "#1 总览入口标题" "1 条"
152
152
  keys Enter; sleep 0.6
153
153
  want_frame ov_body "overview:列表上 Enter 用同一正文视窗打开" "总览入口回复" "只读 · 按发布的原文显示"
154
154
  ev_save "$tmp/$current/ov_pane.txt" "pty-overview-summary.txt"
@@ -163,7 +163,7 @@ kr_group_list() {
163
163
  for i in $(seq 2 60); do kr_cli "$ROOT" reply post --from dev2 --title "第 $i 号" --stdin <"$b" >/dev/null; done
164
164
  start_panel || { bad "list:面板起不来"; return 1; }
165
165
  keys "5"; sleep 0.6
166
- want_frame page1 "list:第 1 页(最新)" "#60 第 60 号" "个编号槽位"
166
+ want_frame page1 "list:第 1 页(最新)" "#60 第 60 号" "60 条"
167
167
  keys Left; sleep 1.2
168
168
  want_frame page2 "list:Older 拿到更旧的一页(50 个槽位一页,最旧页只剩 10 条)" "#10 第 10 号" "#1 第 1 号"
169
169
  keys Left; sleep 1.0
@@ -181,7 +181,7 @@ kr_group_list() {
181
181
  keys Right; sleep 1.2
182
182
  want_frame newer "list:Newer 回到上一页(最新页顶行 #60)" "#60 第 60 号"
183
183
  keys "r"; sleep 1.2
184
- want_frame newest "list:r 回到最新页" "#60 第 60 号" "个编号槽位"
184
+ want_frame newest "list:r 回到最新页" "#60 第 60 号" "60 条"
185
185
  ev_save "$tmp/$current/page3.txt" "pty-list-oldest.txt"
186
186
  }
187
187
 
@@ -202,7 +202,7 @@ kr_group_body() {
202
202
  keys PageDown; sleep 0.6
203
203
  want_frame pgdn "body:PgDn 回到结尾" "END-MARKER-P234"
204
204
  keys "q"; sleep 0.6
205
- want_frame ret "body:q 回列表(不是收起控制台)" "个编号槽位"
205
+ want_frame ret "body:q 回列表(不是收起控制台)" "1 条"
206
206
  assert_eq "body:q 后窗格仍然活着" "$(pty_pane_state | cut -d: -f1)" "0"
207
207
  # 坏正文:本地不可用提示 + 同样的返回路
208
208
  local KR="$state/key-replies" body_id
@@ -221,7 +221,7 @@ PYB
221
221
  want_frame bad "body:坏正文给出不可用提示" "不可用"
222
222
  assert_has "$tmp/$current/bad.txt" "返回" "body:坏正文同样有返回路"
223
223
  keys "q"; sleep 0.6
224
- want_frame bad_back "body:坏正文返回后列表仍在" "个编号槽位"
224
+ want_frame bad_back "body:坏正文返回后列表仍在" "1 条"
225
225
  ev_save "$tmp/$current/end.txt" "pty-body-end.txt"
226
226
  }
227
227
 
@@ -440,7 +440,7 @@ kr_group_resize() {
440
440
  want_frame narrow "resize:59 列下页签身份与 Older 仍在" "关键回复" "更早"
441
441
  tmux -L "$sock" resize-window -t "$sess:panel" -x 140 -y 34 2>/dev/null || true
442
442
  sleep 0.8
443
- want_frame wide "resize:放大后在仍在第 5 页且列表可用" "#1 缩放一号" "个编号槽位"
443
+ want_frame wide "resize:放大后在仍在第 5 页且列表可用" "#1 缩放一号" "1 条"
444
444
  keys Enter; sleep 0.6
445
445
  tmux -L "$sock" resize-window -t "$sess:panel" -x 61 -y 18 2>/dev/null || true
446
446
  sleep 0.8
@@ -457,7 +457,7 @@ kr_group_language() {
457
457
  printf 'lang=en\n' >"$state/panel.conf"
458
458
  start_panel || { bad "language:面板起不来"; return 1; }
459
459
  keys "5"; sleep 0.6
460
- want_frame en "language:en 表下第 5 页标签与路由完整(含说明行的自测题)" "key replies" "Older" "Older" '"who is this reply written for?"'
460
+ want_frame en "language:en 表下第 5 页标签与路由完整(说明行已删:反问句不在,单数用单数式)" "key replies" "Older" "#1 语言一号" "1 reply" "!written for the user"
461
461
  printf 'lang=zh\n' >"$state/panel.conf"
462
462
  start_panel || bad "language:重启失败"
463
463
  keys "5"; sleep 0.6
@@ -481,7 +481,7 @@ kr_group_async() {
481
481
  # ② 进第 5 页 → 多一个 list,无 body
482
482
  reset_argv
483
483
  keys "5"; sleep 1.2
484
- want_frame list "async:第 5 页列表到达" "个编号槽位"
484
+ want_frame list "async:第 5 页列表到达" "2 条"
485
485
  assert_eq "async:进第 5 页后 body 仍为 0" "$(block_calls reply_body)" "0"
486
486
  assert_match "$(kr_argv)" 'reply_list' "async:list 调用进 argv 日志"
487
487
  # ③ 打开正文 → 一个带编号的 body 调用
@@ -530,7 +530,7 @@ kr_group_compose() {
530
530
  want_frame draft "compose:第 5 页上 m 打开写信面板" "写信"
531
531
  assert_has "$tmp/$current/draft.txt" "Esc" "compose:写信面板带取消提示"
532
532
  keys Escape; sleep 0.5
533
- want_frame after "compose:Esc 回到第 5 页列表" "个编号槽位"
533
+ want_frame after "compose:Esc 回到第 5 页列表" "1 条"
534
534
  local after_store
535
535
  after_store="$(find "$state/key-replies" -printf '%p %s %T@\n' | sort | sha256sum | cut -d' ' -f1)"
536
536
  assert_eq "compose:写信不写 key-replies store(前后哈希一致)" "$after_store" "$before_store"
@@ -183,7 +183,7 @@ kr_group_pane() {
183
183
  keys "5"; sleep 0.6
184
184
  want_frame list5 "pane:第 5 页列表帧(编号 + 标题 + 发布者标签)" "#3 长正文" "#2 第二份回复" "#1 完整结论与取舍" "关键回复"
185
185
  assert_has "$tmp/$current/list5.txt" "关键回复" "pane:页签显示第 5 页身份"
186
- assert_has "$tmp/$current/list5.txt" "个编号槽位" "pane:列表带编号槽位计数(不冒充可读回复数)"
186
+ assert_has "$tmp/$current/list5.txt" "3 条" "pane:列表显示条数(新文案「{n} 条」,计数不是可读数)"
187
187
  ev_save "$tmp/$current/list5.txt" "pane-list5.txt"
188
188
  # ② Enter 打开焦点(最新号)→ 正文视窗;End 滚到最后一行,END-MARKER 可达
189
189
  keys Enter; sleep 0.6
@@ -199,7 +199,7 @@ kr_group_pane() {
199
199
  ev_save "$tmp/$current/viewer_end.txt" "pane-viewer-end.txt"
200
200
  # ③ q 返回列表(不是收起整个控制台):列表在、窗格没死
201
201
  keys "q"; sleep 0.6
202
- want_frame back "pane:q 回到列表(同页状态)" "#3 长正文" "个编号槽位"
202
+ want_frame back "pane:q 回到列表(同页状态)" "#3 长正文" "3 条"
203
203
  assert_eq "pane:q 后窗格仍然活着(0 表示活)" "$(pty_pane_state | cut -d: -f1)" "0"
204
204
  # ④ 重启后仍可读:面板页记的是第 5 页,store 不变 → 列表照旧
205
205
  start_panel || bad "pane:重启失败"
@@ -236,7 +236,7 @@ kr_group_demand() {
236
236
  # ② 进第 5 页:多一个 reply_list(带 cursor 或 newest 形态)
237
237
  reset_argv
238
238
  keys "5"; sleep 1.5
239
- want_frame list "demand:第 5 页列表到达" "个编号槽位"
239
+ want_frame list "demand:第 5 页列表到达" "2 条"
240
240
  assert_eq "demand:进第 5 页后 body 调用仍为 0" "$(block_calls reply_body)" "0"
241
241
  if [ "$(block_calls reply_list)" -ge 1 ]; then ok "demand:进第 5 页后 list 被调度($(block_calls reply_list) 次)"; else bad "demand:进第 5 页后没有 list 调用"; fi
242
242
  assert_has "$(kr_argv)" 'reply_list' "demand:argv 日志里能看到 reply_list 的真实参数"
@@ -250,7 +250,7 @@ kr_group_demand() {
250
250
  # ④ 返回列表:不再请求 body
251
251
  reset_argv
252
252
  keys "q"; sleep 1.2
253
- want_frame back "demand:返回列表" "个编号槽位"
253
+ want_frame back "demand:返回列表" "2 条"
254
254
  assert_eq "demand:返回列表后 body 不再被请求" "$(block_calls reply_body)" "0"
255
255
  # ⑤ 离开第 5 页:list/body 都不再请求
256
256
  reset_argv
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /** Product parser/source evidence. All fixtures and mutations stay here, never in product code. */
3
3
  import assert from 'node:assert/strict'
4
- import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, copyFileSync, existsSync, symlinkSync, openSync, closeSync, appendFileSync, chmodSync, lstatSync, realpathSync, constants as C } from 'node:fs'
4
+ import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, copyFileSync, existsSync, symlinkSync, linkSync, openSync, closeSync, appendFileSync, chmodSync, lstatSync, realpathSync, constants as C } from 'node:fs'
5
5
  import { dirname, join, resolve } from 'node:path'
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url'
7
7
  import { spawn, spawnSync } from 'node:child_process'
@@ -9,7 +9,7 @@ import { spawn, spawnSync } from 'node:child_process'
9
9
  const here = dirname(fileURLToPath(import.meta.url))
10
10
  const modulePath = process.env.TEST_CAPTURE_MODULE ?? resolve(here, '../scripts/reply-capture.mjs')
11
11
  const product = await import(pathToFileURL(modulePath).href)
12
- const { parseReply, CaptureJournal, ReplyCapture, runReplyWriter, processIdentity, sourceKey, safeDirectory, inspectRuntime, resolvePMIdentity } = product
12
+ const { parseReply, CaptureJournal, ReplyCapture, runReplyWriter, processIdentity, sourceKey, safeDirectory, inspectRuntime, resolvePMIdentity, updateRuntime } = product
13
13
  const tests = []
14
14
  const test = (name, run) => tests.push({ name, run })
15
15
  const message = (text, extra = {}) => ({ role: 'assistant', content: [{ type: 'text', text }], stopReason: 'stop', timestamp: 1, ...extra })
@@ -522,17 +522,18 @@ for (const fault of ['kill:body-staged', 'kill:index-written', 'kill:index-durab
522
522
  }))
523
523
  }
524
524
 
525
- // P415 · The ancestry refusal must name what it refuses, and an own-group 775 layout is not a foreign trust
526
- // domain. Both sides run: the acceptance would go red under the stricter pre-P415 rule (see ancestryFlip).
527
- const ancestryTests = []
528
- const ancestry = (name, run) => ancestryTests.push({ name, run })
529
- const ancestryTemp = () => realpathSync(mkdtempSync('/var/tmp/p415-ancestry.'))
530
- const foreignGroups = () => {
531
- const saved = [process.getgid, process.getegid, process.getgroups]
532
- process.getgid = () => 0
533
- process.getegid = () => 0
534
- process.getgroups = () => [0]
535
- return () => { [process.getgid, process.getegid, process.getgroups] = saved }
525
+ // D232 · The criteria defend against real failures, not imagined attackers: no permission-mode policing.
526
+ // A file must be a plain non-symlink file this process owns; a directory must be a plain non-symlink on a
527
+ // canonical path. 664 files and 775 (even 777) directories are normal layouts and must work — the old
528
+ // mode/nlink rule is what disabled capture everywhere (P415, P418).
529
+ const ownershipTests = []
530
+ const ownership = (name, run) => ownershipTests.push({ name, run })
531
+ const ownershipTemp = () => realpathSync(mkdtempSync('/var/tmp/p418-owner.'))
532
+ /** Simulate "this file is not mine" without root: the rule compares st.uid with process.getuid(). */
533
+ const foreignUid = () => {
534
+ const saved = process.getuid
535
+ process.getuid = () => 0
536
+ return () => { process.getuid = saved }
536
537
  }
537
538
  const refusal = (run, ...fragments) => {
538
539
  try { run() } catch (e) {
@@ -542,112 +543,180 @@ const refusal = (run, ...fragments) => {
542
543
  }
543
544
  return assert.fail('expected an ancestry refusal, the directory was accepted')
544
545
  }
545
- ancestry('0755 ancestry is accepted (baseline)', () => {
546
- const root = ancestryTemp()
547
- try { assert.equal(safeDirectory(root), root) } finally { rmSync(root, { recursive: true, force: true }) }
546
+ function ownershipProject(root) {
547
+ const state = join(root, '.pi/team/state'), config = join(root, '.pi/team/config.sh'), session = join(root, 'session.jsonl')
548
+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main', root]).status, 0)
549
+ mkdirSync(state, { recursive: true })
550
+ writeFileSync(config, "TEAM_PROJECT='p418'\n")
551
+ writeFileSync(session, '')
552
+ return { state, config, session }
553
+ }
554
+ /** The real entry point, in a real git project, with the fixture files' modes chosen by the caller. */
555
+ function register(root, files, modes) {
556
+ for (const [key, mode] of Object.entries(modes)) chmodSync(files[key], mode)
557
+ const context = { cwd: root, sessionId: 'p418', sessionFile: files.session }
558
+ const env = { TEAM_STATE_DIR: files.state, TEAM_CONFIG_FILE: files.config, TEAM_PM_WINDOW: 'pm', TEAM_SESSION: 'p418' }
559
+ const cwd = process.cwd()
560
+ process.chdir(root)
561
+ try { return { identity: resolvePMIdentity(context, env) } }
562
+ catch (e) { return { error: e } }
563
+ finally { process.chdir(cwd) }
564
+ }
565
+ ownership('0755 / 0775 / 0777 / 1777 directories are accepted: mode is not a judgement', () => {
566
+ const root = ownershipTemp()
567
+ try {
568
+ for (const [name, mode] of [['plain', 0o755], ['own-group', 0o775], ['open', 0o777], ['sticky', 0o1777]]) {
569
+ const dir = join(root, name)
570
+ mkdirSync(dir); chmodSync(dir, mode)
571
+ assert.equal(safeDirectory(dir), dir, `${name} (${mode.toString(8)}) must be accepted`)
572
+ }
573
+ } finally { rmSync(root, { recursive: true, force: true }) }
548
574
  })
549
- ancestry('0775 owned by this process group is accepted (this machine layout)', () => {
550
- const root = ancestryTemp()
551
- const dir = join(root, 'own-group')
575
+ ownership('symlinked directory is refused by path', () => {
576
+ const root = ownershipTemp()
552
577
  try {
553
- mkdirSync(dir); chmodSync(dir, 0o775)
554
- assert.equal(lstatSync(dir).gid, process.getgid(), 'fixture premise: the directory belongs to this process group')
555
- assert.equal(safeDirectory(dir), dir)
578
+ const real = join(root, 'real'), link = join(root, 'link')
579
+ mkdirSync(real); symlinkSync(real, link)
580
+ refusal(() => safeDirectory(link), link, 'is not a plain directory')
556
581
  } finally { rmSync(root, { recursive: true, force: true }) }
557
582
  })
558
- ancestry('1777 sticky temp parent stays accepted', () => {
559
- const root = ancestryTemp()
560
- const dir = join(root, 'sticky')
583
+ ownership('noncanonical directory path is refused', () => {
584
+ const root = ownershipTemp()
561
585
  try {
562
- mkdirSync(dir); chmodSync(dir, 0o1777)
563
- assert.equal(safeDirectory(dir), dir)
586
+ assert.throws(() => safeDirectory(`${root}/./nested`), e => e.message === 'noncanonical directory')
587
+ assert.throws(() => safeDirectory('relative/dir'), e => e.message === 'noncanonical directory')
564
588
  } finally { rmSync(root, { recursive: true, force: true }) }
565
589
  })
566
- ancestry('0777 other-writable ancestor is refused by path', () => {
567
- const root = ancestryTemp()
568
- const dir = join(root, 'open')
590
+ ownership('real git project: a 0775 root and 0775 state register (this machine layout)', () => {
591
+ const root = ownershipTemp()
569
592
  try {
570
- mkdirSync(dir); chmodSync(dir, 0o777)
571
- refusal(() => safeDirectory(dir), dir, 'is other-writable')
593
+ const files = ownershipProject(root)
594
+ chmodSync(root, 0o775); chmodSync(files.state, 0o775)
595
+ const { error } = register(root, files, { session: 0o664, config: 0o664 })
596
+ // Reaching the tmux fact proves the directory and file checks accepted; a refusal would stop earlier.
597
+ assert.equal(error?.message, 'no actual tmux pane', `a 0775 layout must not be refused: ${error?.message ?? 'accepted'}`)
572
598
  } finally { rmSync(root, { recursive: true, force: true }) }
573
599
  })
574
- ancestry('0775 owned by a group outside the process groups is refused by path', () => {
575
- const root = ancestryTemp()
576
- const dir = join(root, 'foreign-group')
600
+ ownership('doctor reason names the refused directory and the rule, not an errno class', () => {
601
+ const root = ownershipTemp()
577
602
  try {
578
- mkdirSync(dir); chmodSync(dir, 0o775)
579
- const restore = foreignGroups()
580
- try { refusal(() => safeDirectory(dir), dir, 'is group-writable outside the effective groups') } finally { restore() }
603
+ const files = ownershipProject(root), link = join(root, 'state-link')
604
+ symlinkSync(files.state, link)
605
+ const seen = inspectRuntime({ root, state: link, config: files.config, session: 'p418', window: 'pm', skill: resolve(here, '..') })
606
+ assert.equal(seen.state, 'unknown')
607
+ assert.ok(seen.reason.startsWith('not registered: unsafe directory ancestry: '), `unexpected reason: ${seen.reason}`)
608
+ assert.ok(seen.reason.includes(link) && seen.reason.includes('is not a plain directory'), `the refused directory is missing: ${seen.reason}`)
581
609
  } finally { rmSync(root, { recursive: true, force: true }) }
582
610
  })
583
- ancestry('real git project: own-group 0775 resolves, 0777 root and 0777 state are refused', () => {
584
- const root = ancestryTemp()
585
- const state = join(root, '.pi/team/state'), config = join(root, '.pi/team/config.sh'), cwd = process.cwd()
586
- const context = { cwd: root, sessionId: 'p415-fixture', sessionFile: join(root, 'session.jsonl') }
611
+ ownership('664 session file and 664 config register (this machine layout)', () => {
612
+ const root = ownershipTemp()
587
613
  try {
588
- assert.equal(spawnSync('git', ['init', '-q', '-b', 'main', root]).status, 0)
589
- mkdirSync(state, { recursive: true })
590
- writeFileSync(config, '# fixture\n')
591
- writeFileSync(join(root, 'session.jsonl'), '')
592
- chmodSync(root, 0o775)
593
- process.chdir(root)
594
- try {
595
- // Own group: the ancestry passes and the same entry stops at the next fact it actually needs.
596
- assert.throws(() => resolvePMIdentity(context, {}), e => e.message === 'missing directed PM launch environment')
597
- chmodSync(root, 0o777)
598
- refusal(() => resolvePMIdentity(context, {}), root)
599
- chmodSync(root, 0o775); chmodSync(state, 0o777)
600
- refusal(() => resolvePMIdentity(context, { TEAM_STATE_DIR: state, TEAM_CONFIG_FILE: config, TEAM_PM_WINDOW: 'pm', TEAM_SESSION: 'p415' }), state)
601
- } finally { process.chdir(cwd) }
614
+ const files = ownershipProject(root)
615
+ const { error } = register(root, files, { session: 0o664, config: 0o664 })
616
+ assert.equal(lstatSync(files.session).uid, process.getuid(), 'fixture premise: the session file belongs to this process')
617
+ assert.equal(error?.message, 'no actual tmux pane', `a 664 session file must not be refused: ${error?.message ?? 'accepted'}`)
602
618
  } finally { rmSync(root, { recursive: true, force: true }) }
603
619
  })
604
- ancestry('doctor reason names the directory and the rule, not an errno class', () => {
605
- const root = ancestryTemp()
606
- const state = join(root, '.pi/team/state'), config = join(root, '.pi/team/config.sh')
620
+ ownership('666 session file also registers: mode is not a judgement', () => {
621
+ const root = ownershipTemp()
607
622
  try {
608
- mkdirSync(state, { recursive: true })
609
- writeFileSync(config, '# fixture\n')
610
- chmodSync(root, 0o775)
611
- const args = { root, state, config, session: 'p415', window: 'pm', skill: resolve(here, '..') }
612
- assert.equal(inspectRuntime(args).reason, 'registration:ENOENT', 'a missing registration is not a refusal')
613
- const restore = foreignGroups()
623
+ const files = ownershipProject(root)
624
+ const { error } = register(root, files, { session: 0o666, config: 0o664 })
625
+ assert.equal(error?.message, 'no actual tmux pane', `mode bits must not refuse a file we own: ${error?.message ?? 'accepted'}`)
626
+ } finally { rmSync(root, { recursive: true, force: true }) }
627
+ })
628
+ ownership('hardlinked session file (nlink 2) registers: link count is not a judgement', () => {
629
+ const root = ownershipTemp()
630
+ try {
631
+ const files = ownershipProject(root)
632
+ chmodSync(files.session, 0o664)
633
+ linkSync(files.session, join(root, 'session-alias.jsonl'))
634
+ assert.equal(lstatSync(files.session).nlink, 2, 'fixture premise: a hardlinked session file')
635
+ const { error } = register(root, files, { config: 0o664 })
636
+ assert.equal(error?.message, 'no actual tmux pane', `nlink alone must not refuse a file we own: ${error?.message ?? 'accepted'}`)
637
+ } finally { rmSync(root, { recursive: true, force: true }) }
638
+ })
639
+ ownership('symlinked session file is refused, never followed', () => {
640
+ const root = ownershipTemp()
641
+ try {
642
+ const files = ownershipProject(root)
643
+ const target = join(root, 'real-session.jsonl')
644
+ writeFileSync(target, ''); chmodSync(target, 0o664); rmSync(files.session); symlinkSync(target, files.session)
645
+ const { error } = register(root, files, { config: 0o644 })
646
+ assert.equal(error?.code, 'ELOOP', `a symlink must be refused without following it: ${error?.message ?? 'accepted'}`)
647
+ } finally { rmSync(root, { recursive: true, force: true }) }
648
+ })
649
+ ownership('project config owned by another user is refused and names the file', () => {
650
+ const root = ownershipTemp()
651
+ try {
652
+ const files = ownershipProject(root)
653
+ const restore = foreignUid()
614
654
  try {
615
- const refused = inspectRuntime(args)
616
- assert.equal(refused.state, 'unknown')
617
- assert.ok(refused.reason.startsWith('not registered: unsafe directory ancestry: '), `unexpected reason: ${refused.reason}`)
618
- assert.ok(refused.reason.includes(root), `the refused directory is missing: ${refused.reason}`)
619
- assert.ok(refused.reason.includes('is group-writable outside the effective groups'), `the rule is missing: ${refused.reason}`)
655
+ const { error } = register(root, files, { session: 0o644, config: 0o664 })
656
+ assert.ok(error && error.message.startsWith('unsafe regular file: ') && error.message.includes(files.config) &&
657
+ error.message.includes('is not owned by this process'), `a foreign owner must be refused by path: ${error?.message ?? 'accepted'}`)
620
658
  } finally { restore() }
621
659
  } finally { rmSync(root, { recursive: true, force: true }) }
622
660
  })
623
- async function ancestryFlip() {
624
- const root = mkdtempSync('/var/tmp/p415-flip.')
661
+ ownership('our own runtime.json: 664 is written (mode is not a judgement)', () => {
662
+ const root = ownershipTemp()
663
+ try {
664
+ const files = ownershipProject(root)
665
+ const directory = join(files.state, 'reply-capture'); mkdirSync(directory)
666
+ const path = join(directory, 'runtime.json')
667
+ writeFileSync(path, '{"owner":"us"}\n'); chmodSync(path, 0o664)
668
+ updateRuntime({ state: files.state }, () => ({ reason: 'probe' }))
669
+ assert.equal(readFileSync(path, 'utf8'), '{"reason":"probe"}\n', 'a 664 registry we own must be replaced, not refused')
670
+ } finally { rmSync(root, { recursive: true, force: true }) }
671
+ })
672
+ ownership('a runtime lock owned by another user is refused and names the file', () => {
673
+ const root = ownershipTemp()
674
+ try {
675
+ const files = ownershipProject(root)
676
+ const directory = join(files.state, 'reply-capture'); mkdirSync(directory)
677
+ const restore = foreignUid()
678
+ let error
679
+ try { updateRuntime({ state: files.state }, () => ({ reason: 'probe' })) } catch (e) { error = e }
680
+ finally { restore() }
681
+ assert.ok(error && error.message.includes('runtime.lock') && error.message.includes('is not owned by this process'),
682
+ `the ownership check must cover our own write surface: ${error?.message ?? 'written'}`)
683
+ assert.equal(existsSync(join(directory, 'runtime.json')), false, 'a refused transaction must not write the registry')
684
+ } finally { rmSync(root, { recursive: true, force: true }) }
685
+ })
686
+ async function ownershipFlip() {
687
+ const root = mkdtempSync('/var/tmp/p418-owner-flip.')
625
688
  try {
626
689
  const scripts = join(root, 'scripts'); mkdirSync(scripts)
627
690
  copyFileSync(resolve(here, '../scripts/replies.mjs'), join(scripts, 'replies.mjs'))
628
691
  const source = readFileSync(modulePath, 'utf8')
629
- const anchor = " if (mode & 0o1000) return '' // Sticky directories (system temp) protect entries the caller does not own.\n" +
630
- " if (mode & 0o002) return 'is other-writable'\n" +
631
- " if ((mode & 0o020) && !groups.has(gid)) return 'is group-writable outside the effective groups'\n return ''"
632
- assert.equal(source.split(anchor).length, 2, 'flip: unique target for the pre-P415 rule')
633
- const target = join(scripts, 'reply-capture.mjs')
634
- writeFileSync(target, source.replace(anchor, " return (mode & 0o022) && !(mode & 0o1000) ? 'is other-writable or group-writable' : ''"))
635
- const red = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--select', 'ancestry'],
636
- { env: { ...process.env, TEST_CAPTURE_MODULE: target }, encoding: 'utf8' })
637
- const lines = `${red.stdout}${red.stderr}`.split('\n')
638
- assert.equal(red.status, 1, `pre-P415 rule must fail the acceptance: ${lines.join(' | ')}`)
639
- const flipped = lines.find(line => line.startsWith('FAIL ') && line.includes('0775 owned by this process group'))
640
- assert.ok(flipped, 'the own-group acceptance must be the assertion that goes red')
641
- for (const kept of ['0777 other-writable ancestor is refused by path', '1777 sticky temp parent stays accepted']) {
642
- assert.ok(lines.includes(`PASS ${kept}`), `the flip must not change the ${kept} verdict`)
643
- assert.ok(!lines.some(line => line.startsWith('FAIL ') && line.includes(kept)), `the flip changed the ${kept} verdict`)
692
+ const rule = " const unsafe = !st.isFile() ? 'is not a regular file' : st.uid !== process.getuid() ? 'is not owned by this process' : ''"
693
+ const owner = "st.uid !== process.getuid() ? 'is not owned by this process' : ''"
694
+ assert.equal(source.split(rule).length, 2, 'flip: unique target for the file rule')
695
+ assert.equal(source.split(owner).length, 2, 'flip: unique target for the owner clause')
696
+ const arms = [
697
+ ['mode-policing', rule,
698
+ " const unsafe = !st.isFile() || st.nlink !== 1 || (st.mode & 0o022) ? 'is not an exclusively owned regular file' : ''",
699
+ '664 session file and 664 config register', ['symlinked session file is refused, never followed']],
700
+ ['no-owner-check', owner, "''",
701
+ 'project config owned by another user is refused', ['664 session file and 664 config register (this machine layout)']],
702
+ ]
703
+ for (const [name, old, replacement, red, kept] of arms) {
704
+ const target = join(scripts, 'reply-capture.mjs')
705
+ writeFileSync(target, source.replace(old, replacement))
706
+ const result = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--select', 'ownership'],
707
+ { env: { ...cleanEnv, TEST_CAPTURE_MODULE: target }, encoding: 'utf8' })
708
+ const lines = `${result.stdout}${result.stderr}`.split('\n')
709
+ assert.equal(result.status, 1, `${name}: the mutated rule must fail the acceptance: ${lines.join(' | ')}`)
710
+ const flipped = lines.find(line => line.startsWith('FAIL ') && line.includes(red))
711
+ assert.ok(flipped, `${name}: named assertion must go red: ${red}`)
712
+ for (const stay of kept) {
713
+ assert.ok(lines.includes(`PASS ${stay}`), `${name}: the flip must not change the ${stay} verdict`)
714
+ assert.ok(!lines.some(line => line.startsWith('FAIL ') && line.includes(stay)), `${name}: the flip changed the ${stay} verdict`)
715
+ }
716
+ console.log(`PASS flip ${name}: named assertion red (${flipped})`)
644
717
  }
645
- console.log(`PASS flip pre-P415 rule: own-group acceptance red (${flipped})`)
646
718
  } finally { rmSync(root, { recursive: true, force: true }) }
647
719
  }
648
- // The shipped instruction surfaces print a concrete marker example. This group runs that printed text
649
- // through the product parser and the real writer, so the promise "printed example works" is exercised
650
- // rather than asserted about prose. A broken example must fail here (no vacuous pass).
651
720
  async function shippedExample() {
652
721
  const file = process.env.TEST_EXAMPLE_FILE
653
722
  assert.ok(file, 'TEST_EXAMPLE_FILE must name the shipped marker example')
@@ -716,10 +785,10 @@ if (args[0] === '--recover-child') { await recoverChild(args[1]); process.exit(0
716
785
  if (args[0] === '--crash-child') crashChild(args[1], args[2])
717
786
  let groups = ['parser']
718
787
  if (args.length && args[0] !== '--all') {
719
- if (args[0] !== '--select' || args.length !== 2) throw new Error('usage: reply-capture.mjs --all | --select parser,state,mutations,state-mutations,ancestry (or --select example with TEST_EXAMPLE_FILE)')
788
+ if (args[0] !== '--select' || args.length !== 2) throw new Error('usage: reply-capture.mjs --all | --select parser,state,mutations,state-mutations,ownership (or --select example with TEST_EXAMPLE_FILE)')
720
789
  groups = args[1].split(',')
721
- } else if (args[0] === '--all') groups = ['parser', 'state', 'mutations', 'state-mutations', 'ancestry']
722
- if (groups.some(g => !['parser', 'state', 'mutations', 'state-mutations', 'ancestry', 'example'].includes(g))) throw new Error('unknown test group')
790
+ } else if (args[0] === '--all') groups = ['parser', 'state', 'mutations', 'state-mutations', 'ownership']
791
+ if (groups.some(g => !['parser', 'state', 'mutations', 'state-mutations', 'ownership', 'example'].includes(g))) throw new Error('unknown test group')
723
792
  let passed = 0, failed = 0
724
793
  if (groups.includes('parser')) for (const { name, run } of tests) {
725
794
  try { await run(); passed++; console.log(`PASS ${name}`) }
@@ -737,15 +806,15 @@ if (groups.includes('state-mutations')) {
737
806
  try { await stateMutations(); passed += 4 }
738
807
  catch (e) { failed++; console.log(`FAIL state mutations: ${e.stack}`) }
739
808
  }
740
- if (groups.includes('ancestry')) {
741
- for (const { name, run } of ancestryTests) {
809
+ if (groups.includes('ownership')) {
810
+ for (const { name, run } of ownershipTests) {
742
811
  try { await run(); passed++; console.log(`PASS ${name}`) }
743
- catch (e) { failed++; console.log(`FAIL ${name}: ${e.stack}`) }
812
+ catch (e) { failed++; console.log(`FAIL ${name}: ${e.message}`) }
744
813
  }
745
814
  // The flip mutates the module under test, so it is meaningless again inside its own child run.
746
815
  if (!process.env.TEST_CAPTURE_MODULE) {
747
- try { await ancestryFlip(); passed++ }
748
- catch (e) { failed++; console.log(`FAIL ancestry flip: ${e.stack}`) }
816
+ try { await ownershipFlip(); passed++ }
817
+ catch (e) { failed++; console.log(`FAIL ownership flip: ${e.stack}`) }
749
818
  }
750
819
  }
751
820
  if (groups.includes('example')) {