nomad / scripts /README.md
LucioLiu's picture
Initial release - mirrors github.com/LucioLiu/nomad
0110783 verified
|
Raw
History Blame Contribute Delete
42.7 kB
# Nomad scripts/ — node-layer components (bilingual · 双语)
> English first, 中文对照见每节末尾缩进块。This is the Nomad **node layer**
> (`team-skeleton.md` §4) — optional acceleration on top of the required md
> layer, never a load-bearing dependency. If Node.js isn't installed, or you
> haven't wired the hooks yet, a Nomad team still works fully through its
> `AGENTS.md` self-driven instructions; these scripts just add automatic
> reminders on top.
>
> 这是 Nomad 的 **node 层**(`team-skeleton.md` §4)——建立在必需的 md 层之上的可选加速项,
> 不是硬依赖。没装 Node.js、或还没接线 hooks,团队照样能靠 `AGENTS.md` 里的自驱指令完整运转;
> 这套脚本只是在此之上加一层自动提醒。
## 0. Prerequisite: Node.js 前提
- Requires Node.js (any reasonably recent LTS; developed and tested against a
current Node 24.x runtime, no external npm dependencies — everything here is
plain Node core modules `fs`/`path`/`os`/`child_process`/`crypto`).
Check with `node --version`; install from nodejs.org if missing.
- 需要 Node.js(较新的 LTS 即可;本包开发/自测用的是当前 Node 24.x 运行时,**零 npm 外部依赖**
只用 Node 核心模块 `fs`/`path`/`os`/`child_process`/`crypto`)。用 `node --version` 检查,
没装去 nodejs.org 装。
- A `package.json` is included, but **only** to declare the Node version floor
(`engines`) and to pin the package as CommonJS (`"type": "commonjs"`, so these
scripts still parse correctly even if an ancestor directory happens to carry a
`"type": "module"` package.json once you copy `scripts/` into your tree). It
lists **no dependencies**`npm install` is still not required; `npm test`
(if you use npm) just runs `node selftest.js`.
- 包内含一个 `package.json`,但**仅**用于声明 Node 版本下限(`engines`)和把本包锁定为
CommonJS(`"type": "commonjs"`——这样把 `scripts/` 复制进你的目录树后,即使上层某个祖先
目录恰好带了 `"type": "module"` 的 package.json,这些脚本仍能被正确按 CommonJS 解析)。
**不含任何依赖**——依旧不需要 `npm install``npm test`(若你用 npm)只是跑
`node selftest.js`
- No `npm install` step — copy the *contents* of the `scripts/` folder
(including `lib/`) directly into `{TEAM_ROOT}/91-team-tools/`, so the files
land at `91-team-tools/session-start.js`, `91-team-tools/lib/config.js`,
etc. — **not** nested one level deeper at `91-team-tools/scripts/session-start.js`.
`91-team-tools/` itself is just a placeholder slot name; use your team's
equivalent node-layer slot per `team-skeleton.md` §1 if it differs (that
doc's own §1 diagram shows an extra `hooks-core/` subfolder — either layout
works, this package just assumes the flatter one below). Whichever folder
name and depth you actually use, **§3's wiring commands below must use that
same path** — that's the one thing that has to match.
- 不需要 `npm install`——把 `scripts/` 目录**里面的内容**(含 `lib/`)直接复制进
`{团队根}/91-团队工具/`,使文件落在 `91-团队工具/session-start.js`
`91-团队工具/lib/config.js` 等位置——**不要**多套一层变成
`91-团队工具/scripts/session-start.js``91-团队工具/` 本身只是个占位槽位名,你团队按
`team-skeleton.md` §1 约定的槽位若不同就用你实际的(该文档 §1 图示里还带了一层
`hooks-core/` 子目录——两种布局都行,本文档下文统一按不带这层子目录的扁平布局写)。
不管你实际用的目录名和层级是什么,**第三节下面的接线命令里的路径必须跟它一致**——这是
唯一必须对齐的地方。
## 1. What each file does 各脚本职责一句话
| File 文件 | Responsibility 职责 |
|---|---|
| `session-start.js` | SessionStart hook: injects a team-charter pointer (if `ARCHITECTURE.md`/`团队结构宪章.md` exists at the team root — the charter's own §9 "layer 2" routing) + team-log excerpt + kanban "in progress" summary + this agent's unread-inbox count + a cross-session soft-lock warning if applicable.<br>SessionStart 钩子:注入团队宪章指针(团队根存在 `ARCHITECTURE.md`/`团队结构宪章.md` 时——即宪章 §9 的"层 2"路由)+ 团队日志摘录 + 看板"进行中"摘要 + 本员工收件箱未读数 + (若有)跨会话软锁警告。 |
| `session-stop.js` | Stop hook: reminds the agent to flush memory + team log before ending, with loop-safe logic so it doesn't nag every single turn. Also releases the soft lock acquired by session-start.js.<br>Stop 钩子:提醒收工前落记忆+回写团队日志,带防死循环逻辑(不会每轮都催);同时对称释放 session-start.js 加的软锁。 |
| `precompact.js` | PreCompact hook: best-effort nudge to save progress before context gets compacted. Secondary mechanism — session-stop.js is the primary flush point.<br>PreCompact 钩子:压缩前尽力提醒先存进展。是次要机制——主力落盘时机是 session-stop.js。 |
| `append-log.js` | Concurrency-safe append tool for the shared team log (or any similar "insert a line, many writers" markdown file). Use this instead of directly editing the team log — direct concurrent edits have caused real corruption in production deployments.<br>团队日志(或任何类似"多写者插入一行"的 markdown 文件)的并发安全追加工具。别直接编辑团队日志——生产部署里无锁并发直改已造成过真实损坏。 |
| `frontmatter-touch.js` | Stop hook (optional, wire alongside `session-stop.js`): keeps the `updated` frontmatter field of charter-schema markdown files in sync with on-disk reality — **without git** (works in a plain zip-extracted folder). Mechanism, trade-offs and safety rails: §8.<br>Stop 钩子(可选,与 `session-stop.js` 并挂):让宪章 schema markdown 文件的 frontmatter `updated` 字段与磁盘现实保持同步——**不依赖 git**(zip 解压的普通文件夹即可用)。机制、取舍与防线见 §8。 |
| `append-team-log.js` / `追加团队日志.js` | Self-locating variant of the append tool for **assembled team workspaces** (bilingual file pair): resolves its target log relative to its own position inside the team tree and enforces the team charter's entry discipline. See §7 for how it differs from `append-log.js`.<br>面向**已装配成品团队**的追加工具自定位变体(双语文件对):按脚本自身在团队目录树里的位置解析目标日志,并执行团队宪章的条目纪律。与 `append-log.js` 的分工见 §7。 |
| `structure-sentinel.py` / `结构哨兵.py` | Dependency-free four-check structure sentinel (existence / orphan / frontmatter schema / broken links) for a team built on this skeleton — the machine-guarantee layer named by the governance charter. A guardrail, not a gate: reports, never blocks. Python, not Node — it ships here because `scripts/` is the "copy into your team's tool slot" layer. See §7.<br>零依赖四检结构哨兵(存在性/孤儿/frontmatter schema/断链),是治理宪章点名的机器保证层。护栏不是闸门:只报告不拦截。它是 Python 不是 Node——放在本目录是因为 `scripts/` 就是"复制进团队工具槽位"的发行层。见 §7。 |
| `selftest.js` | Offline regression test for this whole package. Run after any edit.<br>本包整体的离线回归自测。改完代码先跑这个。 |
| `lib/config.js` | Team root / agent home resolution (by directory structure, not by a hardcoded folder name) + team-config.json loading + language/shared-path resolution.<br>团队根/员工家定位(按目录结构而非写死文件夹名)+ team-config.json 加载 + 语言/共享路径解析。 |
| `lib/emit.js` | Hook stdin/stdout wrapper — reads hook input, wraps output per `--platform claude\|codex\|cursor`, handles double-fire dedup.<br>钩子 stdin/stdout 包装——读钩子输入,按 `--platform` 包装输出,处理双跑去重。 |
| `lib/file-lock.js` | Generic concurrency-safe file-locking primitive (atomic lock file + stale-lock self-heal + atomic replace-via-rename).<br>通用并发安全文件锁基建(原子锁文件 + 陈锁自愈 + 原子 rename 替换)。 |
| `lib/session-lock.js` | Cross-session soft lock — lets an agent notice "another harness/session might already be running here", never blocks.<br>跨会话软锁——让员工"发现自己可能不是唯一在场的会话",不阻塞任何人。 |
| `lib/frontmatter.js` | Minimal YAML-frontmatter reader (block extraction + column-zero scalar fields + line positions for surgical edits). Deliberately NOT a general YAML parser — see its header comment for the scope contract.<br>最小 YAML frontmatter 读取器(块提取 + 列首标量字段 + 供精准单行编辑的行号定位)。刻意**不是**通用 YAML 解析器——范围契约见其文件头注释。 |
| `lib/messages.js` | Bilingual (en / zh-CN) message table for everything these scripts emit.<br>本包所有输出文案的双语(en/zh-CN)表。 |
## 2. How path/config resolution works 路径与配置怎么解析(零硬编码设计)
Every script resolves paths through **directory structure**, never a literal
path baked into the template — per `team-skeleton.md` §5 hardcoding points
#1/#2/#6/#7:
每个脚本都通过**目录结构**解析路径,模板本身绝不写死字面路径——对齐
`team-skeleton.md` §5 焊死点 #1/#2/#6/#7:
- **Team root** = walk up from the current working directory until a folder
containing `team-config.json` is found. Override with env `NOMAD_TEAM_ROOT`
(only honored if that path actually contains `team-config.json` — an invalid
override is silently ignored, not blindly trusted).
**团队根** = 从 cwd 向上走,找到第一个含 `team-config.json` 的目录。可用环境变量
`NOMAD_TEAM_ROOT` 覆盖(仅当该路径确实含 `team-config.json` 才生效,无效值静默忽略、不盲信)。
- **Agent home** = walk up from cwd until a folder containing `AGENTS.md` is
found. This deliberately does NOT replicate the production hooks-core
approach of regex-matching one hardcoded parent-folder name (e.g.
`<agent-parent-dir>\(name)`) — a portable template can't assume any particular
folder name exists, whether the deployment names its folders in English,
Chinese, or anything else (`team-skeleton.md` §5 hardcoding point #5).
**员工/agent home** = 从 cwd 向上走,找到第一个含 `AGENTS.md` 的目录。这里刻意**没有**
照搬生产 hooks-core 的做法(正则匹配一个写死的父目录名,如 `<员工父目录>\(名字)`)——
通用模板不能假设任何特定目录名存在,无论部署用中文、英文还是别的目录命名
`team-skeleton.md` §5 焊死点 #5)。
- **Shared paths** (team log, kanban) come from `team-config.json`'s
`shared_paths` object, resolved relative to the team root.
**共享路径**(团队日志、看板)来自 `team-config.json``shared_paths` 对象,相对团队根解析。
- **Language** = env `NOMAD_LANG` (`en`|`zh-CN`) > `team-config.json`'s
`principal.language` (any `zh*` value normalizes to `zh-CN`) > `en` fallback.
This batch's design choice: default to English, let `team-config.json` opt
a deployment into Chinese — a portable template shouldn't silently assume
Chinese as the default the way the production original (built for one
Chinese-speaking deployment) reasonably does.
**语言** = 环境变量 `NOMAD_LANG``en`|`zh-CN`)> `team-config.json`
`principal.language`(任何 `zh*` 值归一化为 `zh-CN`)> 兜底 `en`。本批次的设计选择:默认英文,
`team-config.json` 显式选中文——通用模板不该像生产原版(本就为某个中文部署而生)那样默认中文。
### Naming-agnosticism note 目录/文件命名探测说明
`team-config.json` (per `team-skeleton.md` §3) has no field for "what is the
memory folder called" or "what is the inbox file called" inside an agent
home — `shared_paths` only covers team-root-level shared files. Rather than
proposing a new config field this batch wasn't asked to introduce, these
scripts **probe both naming conventions**: memory dir candidates are `记忆`
then `memory`; inbox file candidates (inside whichever memory dir was found)
are `收件箱.md` then `inbox.md`. Neither found → that section is silently
skipped (never blocks). See `lib/session-lock.js` and `session-start.js` for
where this is used.
`team-config.json`(按 `team-skeleton.md` §3)没有字段规定员工 home 内"记忆目录叫什么"
"收件箱文件叫什么"——`shared_paths` 只覆盖团队根级共享文件。本批次没有去新增一个
未被要求的配置字段,而是让脚本**两种命名候选都探测**:记忆目录候选 `记忆` 然后 `memory`
收件箱文件候选(在探测到的记忆目录下)`收件箱.md` 然后 `inbox.md`。两者都找不到则该段静默
跳过(不阻断)。用到这个探测逻辑的地方见 `lib/session-lock.js``session-start.js`
### Kanban parsing: structured-or-degrade 看板解析:结构化优先,不命中则降级
`team-skeleton.md` doesn't mandate any specific internal markdown structure
for `kanban.md` — it's just "a shared work-tracking board." `session-start.js`
first tries a structured parse matching the shape the production deployment
this was ported from actually uses (`## ` heading containing "In Progress"/
"进行中" → `### ` item title → a `- **Status**:`/`- **状态**:` line). If a
team's kanban.md doesn't match that shape (verified in practice against a
sandbox test team), it falls back to a plain head-of-file
excerpt instead of going silent, so a differently-formatted board still
surfaces *something* useful rather than nothing. If your team's kanban is
structured very differently and you want the structured summary, either
reshape kanban.md to the pattern above, or edit `parseKanbanHot()` in
`session-start.js` — this is a documented, honest limitation, not a hidden one.
`team-skeleton.md` 不规定 `kanban.md` 内部具体用什么 markdown 结构——只说它是"共享工作看板"。
`session-start.js` 先尝试匹配移植来源的生产部署实际用的结构化格式(`## ` 标题含"进行中"/
"In Progress" → `### ` 条目标题 → `- **状态**:`/`- **Status**:` 行)。若某团队的 kanban.md
不是这个结构(已用一个沙盒测试团队真机验证过命不中的情况),则降级为"文件头部原样
摘录"而不是完全静默,好歹让不同格式的看板也能带出点有用信息而不是什么都没有。若你的团队看板
结构差异很大又想要结构化摘要,要么把 kanban.md 改成上面那个格式,要么去改
`session-start.js` 里的 `parseKanbanHot()`——这是个如实写明的已知局限,不是藏起来的坑。
## 3. Per-platform hook wiring examples 各平台 hooks 接线示例
These are generated **at install time for one specific deployment** — the
template scripts themselves never contain a hardcoded path (per
`team-skeleton.md` §5 hardcoding point #1), but the config files below, once
you write them for your actual team, legitimately do.
以下是**为某个具体部署在装机时生成**的示例——模板脚本本身永不写死路径(对齐
`team-skeleton.md` §5 焊死点 #1),但下面这些配置文件一旦你为实际团队写出来,含具体路径是
合理且预期的。
⚠️ The JSON examples and `node` commands below are written with Windows
backslash (`\`) path syntax, since that's this batch's primary target
environment. **On macOS/Linux, replace every `\` with `/`** in both the
`"command"` string values and any bare paths — the hook JSON shape itself
(the `hooks`/`SessionStart`/`Stop`/`PreCompact`/`type`/`command` keys) is
identical across OSes, only the path separator changes.
⚠️ 下面的 JSON 示例和 `node` 命令用的是 Windows 反斜杠(`\`)路径写法,因为这是本批次的
主要目标环境。**在 macOS/Linux 上,把每个 `\` 换成 `/`** 即可——包括 `"command"` 字符串值
里的路径和任何裸路径;hook JSON 的结构本身(`hooks`/`SessionStart`/`Stop`/`PreCompact`/
`type`/`command` 这些键)跨操作系统完全一致,只有路径分隔符要换。
### Claude Code — `{AGENT_HOME}/.claude/settings.local.json`
```json
{
"hooks": {
"SessionStart": [
{ "hooks": [ { "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\session-start.js\" --platform claude", "timeout": 20 } ] }
],
"Stop": [
{ "hooks": [
{ "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\session-stop.js\" --platform claude", "timeout": 20 },
{ "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\frontmatter-touch.js\" --platform claude", "timeout": 20 }
] }
],
"PreCompact": [
{ "hooks": [ { "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\precompact.js\" --platform claude", "timeout": 20 } ] }
]
}
}
```
The second `Stop` entry (`frontmatter-touch.js`) is **optional** — drop that
line if your team doesn't use the charter's frontmatter metadata convention.
It emits nothing to the session (pure housekeeping, §8); the two Stop hooks
are independent, either can be wired without the other.
`Stop` 数组里第二条(`frontmatter-touch.js`)是**可选项**——你的团队不用宪章 frontmatter
元数据约定就删掉该行。它对会话零注入(纯后台内务,见 §8);两个 Stop 钩子相互独立,
接哪个不接哪个都行。
⚠️ **If `settings.local.json` already exists, MERGE — don't paste over it.**
Most agent homes already have a `settings.local.json` with `permissions`,
`additionalDirectories`, or other keys set. Pasting the JSON block above as
the whole file replaces those and silently deletes them — losing
`additionalDirectories` in particular breaks hook path resolution (the hook
process can no longer see the team root). Open the existing file, keep every
key it already has, and add only the `hooks` key (or merge into an existing
`hooks` key if one is already there) — never do a wholesale file replace.
⚠️ **`settings.local.json` 若已存在,要合并、不要整段覆盖。** 多数员工家已有一份带
`permissions``additionalDirectories` 等键的 `settings.local.json`。把上面这段 JSON
当整个文件粘贴进去会把这些键连带删掉——尤其丢了 `additionalDirectories` 会导致 hook 进程
定位不到团队根、直接失效。正确做法:打开现有文件,保留它已有的每个键,只新增 `hooks` 这一个键
(如果已有 `hooks` 键则并入其下)——不要整体替换文件。
⚠️ Known Claude Code gotcha (per `mounting-guide.md` §3): its project-level
config lookup climbs to the repository root, so if a repo-root
`.claude/settings.json` AND an agent-home-level `.claude/settings.local.json`
are both present, Claude Code fires **both** — a double-fire, not a misfire.
`lib/emit.js`'s `isDuplicateInvocation()` guards against this (5s window, same
session_id + event name = treated as one call) — it's already wired into all
three hook scripts, no extra setup needed.
⚠️ 已知 Claude Code 坑(见 `mounting-guide.md` §3):其项目级配置查找会回溯到仓库根,若仓根
`.claude/settings.json` 与员工家 `.claude/settings.local.json` 同时存在,Claude Code 会
**两个都触发**——是双跑不是误触发。`lib/emit.js` 的 `isDuplicateInvocation()` 已经防住这个
(5 秒窗口内同 session_id+事件名=判一次调用)——已经接进三个钩子脚本,不需要额外配置。
### Codex / ChatGPT Desktop — `{AGENT_HOME}/.codex/hooks.json`
```json
{
"hooks": {
"SessionStart": [
{ "hooks": [ { "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\session-start.js\" --platform codex", "timeout": 20 } ] }
],
"Stop": [
{ "hooks": [
{ "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\session-stop.js\" --platform codex", "timeout": 20 },
{ "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\frontmatter-touch.js\" --platform codex", "timeout": 20 }
] }
],
"PreCompact": [
{ "hooks": [ { "type": "command", "command": "node \"{TEAM_ROOT}\\91-team-tools\\precompact.js\" --platform codex", "timeout": 20 } ] }
]
}
}
```
(Same note as the Claude Code section: the second `Stop` entry is the optional
`frontmatter-touch.js` housekeeping hook — keep or drop per §8.)
(同 Claude Code 节的说明:`Stop` 第二条是可选的 `frontmatter-touch.js` 内务钩子——
按 §8 取舍去留。)
⚠️ Per `mounting-guide.md` §3: Codex requires an in-app trust review the
first time a hook runs (a per-hook trust card, commonly three prompts) —
don't assume "not injecting yet" means the script is broken, check whether
trust has actually been granted first.
⚠️ 按 `mounting-guide.md` §3:Codex 首次跑 hook 需要应用内信任审核(逐钩子信任卡片,通常三次
提示)——"还没注入"先别当脚本坏了,先确认信任是否真的已授予。
### Cursor — best-effort, not independently verified by this batch
`lib/emit.js` and all three hook scripts accept `--platform cursor` and
produce Cursor's documented output shapes (`additional_context` /
`followup_message` / `user_message`). Per `mounting-guide.md` §3, hooks are
**not reliably available on Cursor as of writing** — treat this as best-effort
plumbing, not a verified-working integration; the md-layer self-driven
fallback is the normal operating mode on this platform, not an edge case.
`lib/emit.js` 和三个钩子脚本都接受 `--platform cursor`,产出 Cursor 文档记载的输出形态
`additional_context`/`followup_message`/`user_message`)。按 `mounting-guide.md` §3,
截至撰写时 Cursor 上 **hooks 本就不可靠**——这是尽力而为的管路,不是已验证可用的集成;md 层
自驱回退在这个平台是正常运作模式,不是边缘情况。
## 4. `append-log.js` usage 用法
```
node append-log.js "<entry text>" [--target <path>] [--mode top|bottom] [--anchor <regex>]
node append-log.js --file <entry-file-path> [--target <path>] [--mode top|bottom] [--anchor <regex>]
node append-log.js --stdin [--target <path>] [--mode top|bottom] [--anchor <regex>]
```
Without `--target`, resolves the shared team log via
`team-config.json`'s `shared_paths.team_log` (team root found by walking up
from cwd). Unlike the production `append-teamlog.js` this was ported from,
this tool does **not** enforce a specific entry-text format — a portable
template can't assume every deployment's team log uses the exact same entry
grammar; format discipline is left to the caller.
不给 `--target` 时,通过 `team-config.json``shared_paths.team_log`(团队根从 cwd 向上找)
解析共享团队日志路径。与移植来源的生产版 `append-teamlog.js` 不同,本工具**不强制**特定条目
格式——通用模板不能假设每个部署的团队日志都用同一种条目语法;格式纪律交给调用方。
## 5. Selftest 自测
```
node selftest.js
```
Covers (as of this batch): config resolution boundaries, emit.js three-platform
payload shapes + cwd resolution + dedup guard, session-start.js pure parsers
(including the kanban structured-vs-degrade branch) + charter-pointer section,
session-stop.js's four-branch decide() logic, session-lock
acquire/release/conflict-warning, file-lock stale-lock self-heal, append-log.js
end-to-end including a real 15-concurrent-process write-safety test, all hook
scripts spawned as real subprocesses (normal/empty/bad-JSON stdin, double-fire
dedup), lib/frontmatter.js parsing boundaries, and frontmatter-touch.js both as
pure functions (decision matrix, CRLF/BOM preservation, exclusion rules) and
end-to-end against a mock NON-git team dir (refresh/insert/mtime-restore/
idempotence/cap/dedup). Results are written to a JSON file under the OS temp
dir; the printed path is the source of truth for a failing run — 153/153
passing as of 2026-07-23.
覆盖(截至本批次):config 路径解析边界、emit.js 三平台输出形态+cwd 解析+去重守卫、
session-start.js 纯解析函数(含看板结构化/降级两分支)+宪章指针段、session-stop.js 的
decide() 四分支、session-lock acquire/release/冲突警告、file-lock 陈锁自愈、append-log.js
端到端(含真实 15 进程并发写安全测试)、各钩子脚本的真实子进程调用(正常/空/坏JSON stdin、
双跑去重)、lib/frontmatter.js 解析边界、frontmatter-touch.js 纯函数(判定矩阵、CRLF/BOM
保持、排除规则)与端到端(对**非 git** mock 团队目录:刷新/插入/mtime 复原/幂等/上限/去重)。
结果落盘到系统临时目录下的 JSON 文件,失败时以该文件为准;截至 2026-07-23 为 153/153 通过。
### 5b. Post-install smoke check — did the hook actually get wired up? 装完自查:钩子真的接上了吗?
`node selftest.js` only proves the package itself isn't broken — it says
nothing about whether *your* harness is actually invoking these scripts.
After wiring the hooks per §3, manually feed a script the same JSON shape a
real hook host sends on stdin and read what comes back on stdout (see the
"manual testing" note in `lib/emit.js`'s `readStdin()` header comment for why
this always needs piped/redirected stdin, not an interactive terminal):
```
# macOS/Linux
echo '{"cwd":"/path/to/some/agent-home","session_id":"manual-test-1"}' | node session-start.js --platform claude
# Windows PowerShell
'{"cwd":"D:\\team-root\\some-agent-home","session_id":"manual-test-1"}' | node session-start.js --platform claude
```
Point `cwd` at a real path under your team root (ideally the agent home
you're testing) so path resolution has something real to find. A working
call prints one line of JSON to stdout — `{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"...multi-line text..."}}`
— and the `additionalContext` string should contain more than just the
opening-check line.
Common "it ran but did nothing useful" causes, if `additionalContext` comes
back as just one line:
| Symptom | Likely cause |
|---|---|
| Only the opening-check line, nothing else | `team-config.json` wasn't found walking up from `cwd` — either the `cwd` you fed in isn't really under a team root, or `team-config.json` doesn't exist there yet |
| Opening line + no team-log/kanban sections | `team-config.json` exists but `shared_paths.team_log` / `shared_paths.kanban` aren't set, or the files they point to don't exist on disk |
| Opening line + no inbox count | Neither `记忆`/`memory` nor `收件箱.md`/`inbox.md` naming candidates were found under the resolved agent home — or `cwd` didn't resolve at all (check your JSON is valid) |
| Nothing printed at all (empty stdout) | The script crashed before `emit.writeJson()` — this shouldn't happen (main() catches everything), so treat it as a real bug and check stderr / the Node version |
`session-stop.js` and `precompact.js` can be smoke-tested the same way —
swap in valid stdin JSON for those events and read stdout back.
`node selftest.js` 只证明这个包本身没坏——不能证明**你的 harness** 真的在调用这些脚本。
按第三节接好线之后,手动灌一份真实 hook host 会发到 stdin 的同样 JSON 结构,看 stdout 吐出
什么(为什么必须走管道/重定向 stdin、不能在交互式终端里直接跑,见 `lib/emit.js`
`readStdin()` 头注释的"手测法"说明):
```
# macOS/Linux
echo '{"cwd":"/path/to/some/agent-home","session_id":"manual-test-1"}' | node session-start.js --platform claude
# Windows PowerShell
'{"cwd":"D:\\team-root\\some-agent-home","session_id":"manual-test-1"}' | node session-start.js --platform claude
```
`cwd` 指向你团队根下一个真实存在的路径(最好就是你在测的那个员工 home),这样路径解析
才有真东西可找。跑通的话 stdout 会吐一行 JSON——
`{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"...多行文本..."}}`
——`additionalContext` 字符串里应该不止开场检查那一行。
`additionalContext` 只回来一行,常见"跑是跑了但啥也没干"的成因对照:
| 症状 | 常见成因 |
|---|---|
| 只有开场检查那一行,别的都没有 | 从 `cwd` 向上没找到 `team-config.json`——要么灌进去的 `cwd` 根本不在团队根下,要么那里还没建 `team-config.json` |
| 有开场行,但没有团队日志/看板段落 | `team-config.json` 存在,但 `shared_paths.team_log` / `shared_paths.kanban` 没配,或配了但指向的文件磁盘上不存在 |
| 有开场行,但没有收件箱未读数 | 在解析出的员工 home 下,`记忆`/`memory``收件箱.md`/`inbox.md` 两组命名候选都没找到——或者 `cwd` 根本没解析出来(检查你的 JSON 是否合法) |
| stdout 完全没输出 | 脚本在 `emit.writeJson()` 之前就崩了——理论上不该发生(main() 兜底捕获所有异常),出现这个当真 bug 处理,查 stderr 和 Node 版本 |
`session-stop.js``precompact.js` 也能用同样方法手测——换成这两个事件对应的合法 stdin
JSON,看 stdout 回什么。
## 6. Relationship to the production hooks-core 与生产 hooks-core 的关系
This package is a **parameterized, desensitized port**, not a copy — same
core algorithms (team-log/kanban/inbox parsing shape, the four-branch
stop-reminder decide logic, the lock-file concurrency primitive, the
double-fire dedup guard), rewritten so every path comes from
`team-config.json`/directory-structure resolution instead of one
deployment's hardcoded folder names. It does not import or depend on
anything under the source deployment's own tooling folder — copy `scripts/`
anywhere and it's self-contained (no `npm install`, no sibling-folder
requires outside its own `lib/`).
本包是**参数化、脱敏移植**,不是复制——核心算法一致(团队日志/看板/收件箱解析形状、
收工提醒四分支判定逻辑、锁文件并发基建、双跑去重守卫),但重写成一切路径都从
`team-config.json`/目录结构解析,而非某个部署写死的文件夹名。本包不 import、不依赖来源
部署自己工具目录下的任何东西——`scripts/` 整个复制到哪都能独立跑(零 `npm install`,除自己
`lib/` 外无跨目录 require)。
## 7. Governance tools (v0.5) 治理工具(v0.5)
As of v0.5, two governance tools live here alongside the hook scripts. They are
**upstreamed from an integration pack that assembles team workspaces from this
skeleton** — that pack now pulls them from this repo's published HEAD instead of
carrying private copies, so this directory is their single source of truth.
Both ship as bilingual file pairs (`<name>` English / Chinese-named twin with
Chinese-language output) because assembled teams run in one language end to end.
- **`structure-sentinel.py` / `结构哨兵.py`** — four checks over a team folder
(must-read existence / memory-index orphans / frontmatter schema in the
mandatory zones / broken relative links). Zero dependencies (Python standard
library). Run: `python3 structure-sentinel.py <team-root>` (Windows: `py -3 …`; add `--json <file>`
for a machine-readable report). Pairs with the charter + metadata-conventions
templates in `references/governance/`.
- **`append-team-log.js` vs `append-log.js`** — same locking core, two roles:
`append-log.js` is the **generic** tool for a team you wired yourself (target
resolved via `team-config.json`, entry format left to the caller);
`append-team-log.js` is the **assembled-team variant** (locates its target log
relative to its own position in the team tree, enforces the charter's entry
discipline, Chinese twin writes to the Chinese-named log). If you are building
a team by hand with this skill, use `append-log.js`; the assembled-team
variant exists so integration packs can drop it in as-is.
v0.5 起,两个治理工具与 hook 脚本同住本目录。它们是**从一个基于本骨架装配成品团队的整合包
上游归位而来**——该整合包现在从本仓已发布 HEAD 取料、不再私藏副本,本目录就是它们的唯一
真源。两者都以双语文件对发行(英文名版 / 中文名孪生版,后者输出中文),因为成品团队是
端到端单语言运行的。
- **`structure-sentinel.py` / `结构哨兵.py`**——对团队目录跑四项检查(必读文件存在性/
记忆索引孤儿/必挂区 frontmatter schema/相对链接断链)。零依赖(Python 标准库)。
用法:`python3 structure-sentinel.py <团队根>`(Windows 用 `py -3 …`;加 `--json <文件>` 出机器可读报告)。
`references/governance/` 里的宪章、元数据挂靠规则模板配套。
- **`append-team-log.js` 与 `append-log.js` 的分工**——同一套锁内核,两种角色:
`append-log.js`**通用版**(目标走 `team-config.json` 解析,条目格式交给调用方);
`append-team-log.js`**成品团队变体**(按自身在团队树里的位置定位目标日志,执行宪章
条目纪律,中文孪生版写中文实名日志)。自己按本 skill 手搭团队用 `append-log.js`
成品团队变体的存在意义是让整合包能原样取用落地。
## 8. `frontmatter-touch.js` — how it finds changes without git 改动发现机制(不依赖 git)
**What it maintains.** The governance charter's metadata convention (charter
§10) gives every team markdown file a YAML frontmatter with `owner` / `created`
/ `status` (mandatory) and `updated` (optional, meant to be machine-maintained).
This hook is that machine: at every session close-out it reconciles each
file's **declared** freshness against its **on-disk** freshness:
```
file mtime's calendar date > frontmatter `updated` (or `created` if no updated line)
→ set `updated: <mtime date>` (insert the line after `created` if absent)
```
**Why mtime reconciliation instead of `git status`.** The production
deployment this ports from finds "what changed this session" via git — but an
assembled Nomad team is typically a zip-extracted plain folder with no `.git`
in it, so the discovery mechanism was rebuilt rather than desensitized.
Reconciliation was chosen over the closer imitation ("files with today's
mtime") deliberately: it is an **asynchronous catch-up**. Edits made yesterday
on a harness with no hook support are still caught the next time any
hook-bearing session closes — this is the machine half of the charter's
"no-hook platforms reconcile on next start" compensation clause (§8.3 there).
`git status` and "today only" both miss that case. Accepted trade-off: mtime
is cruder than a git diff — a content-identical rewrite or a copy done with a
tool that refreshes mtimes still counts as "changed" and re-dates `updated`
once (then converges; see the rails below).
**Safety rails** (each exists for a concrete failure mode — full detail in the
script's header comment):
1. **Charter-schema gate** — only files whose frontmatter carries non-empty
`owner` + `created` + `status` are ever touched; malformed dates are left
alone, never guessed at. SKILL.md-style files with their own metadata
vocabulary are structurally invisible.
2. **mtime restore after write** — otherwise the hook's own write would look
like a fresh edit next run and re-date files forever.
3. **Per-run cap** (default 100; env `NOMAD_FMTOUCH_MAX_TOUCH`) — a bulk
copy/extraction with mtime-refreshing tools becomes bounded work per
close-out that converges across runs, not an IO storm inside a hook timeout.
4. **Scan-baseline state file** (OS temp dir) — steady state, only files whose
mtime moved since the last completed run get read at all; losing the state
file just costs one full (idempotent) re-read pass.
5. **Per-file lock + atomic write + read-back verify** — shares `<file>.lock`
naming with the append tools, so a touch and a concurrent append can never
lose each other's update. Lock busy → skip; next Stop catches up.
6. **Never blocks close-out** — every failure path is skip + a line in the
local log (`<OS temp dir>/nomad_fmtouch.log`); stdout stays empty (zero
injection budget).
**Structural exclusions** (never one deployment's folder names): dot-folders
(`.git`/`.claude`/...), `node_modules`, and the skeleton's `97`/`98`/`99`
slot prefixes (inbox-misc / archive / recycle-bin — the digits are the stable
signal across English and native-language layouts). Everything else is left to
the schema gate above.
**One deliberate divergence from the production original:** when a
charter-schema file has no `updated` line yet, this version **inserts** one.
The production deployment leaves missing fields to its structure sentinel to
report; in this package the sentinel (§7) reports but nothing else would ever
create the field, and Nomad-scaffolded teams ship with `updated` absent
everywhere — replace-only would be a permanent no-op exactly where this hook
ships. Verified against a real zip round-trip of an assembled sample team
(2026-07-23): factory-fresh extraction = 169 files scanned, zero touched
(no false positives); one real edit = exactly that file gained
`updated: <edit date>`, with its mtime restored to the edit time; second run =
zero candidates (converged).
**Smoke-testing note:** unlike the other hooks this one is silent on stdout by
design — to check it ran, read the last line of `nomad_fmtouch.log` in the OS
temp dir (one `done root=... touched=N ...` line per close-out).
**维护什么。**治理宪章的元数据约定(宪章 §10)给每份团队 markdown 一个 YAML
frontmatter:`owner`/`created`/`status` 必填、`updated` 选填(本意就是交给机器维护)。
本钩子就是那台机器:每次收工时,把每份文件**声明的**新鲜度与**磁盘上的**新鲜度对账:
```
文件 mtime 的日历日期 > frontmatter `updated`(无 updated 行则比 `created`)
→ 置 `updated: <mtime 日期>`(无该行则在 `created` 行后插入)
```
**为什么用 mtime 对账而不是 `git status`。**移植来源的生产部署靠 git 找"本会话改了什么"——
但装配出来的 Nomad 团队通常是 zip 解压的普通文件夹、没有 `.git`,所以改动发现机制是**重建**
的、不是脱敏搬运。刻意选对账而非更贴近原版的"今日 mtime 扫描":对账是**异步补账**——昨天在
无 hook 平台上做的编辑,下一次任何有 hook 的会话收工时照样补上——这正是宪章"无 hook 平台
下次开机对账"补偿条款(宪章 §8.3)的机器半边;`git status` 和"只看今天"都漏这个场景。
接受的代价:mtime 比 git diff 粗——内容未变的重写、或用会刷新 mtime 的工具做的复制,也会
被算作"改过"、把 `updated` 多刷一次(之后收敛;见下面防线)。
**防线**(每条都对应一个具体失效模式——完整细节见脚本头注释):
1. **宪章 schema 闸**——只碰 frontmatter 带非空 `owner`+`created`+`status` 的文件;日期
格式不合法的只跳过、绝不猜着"修"。SKILL.md 这类自带元数据体系的文件在结构上就不可见。
2. **写后复原 mtime**——否则钩子自己的写入下轮会被当成新编辑,日期被永远推着走。
3. **每轮上限**(默认 100;环境变量 `NOMAD_FMTOUCH_MAX_TOUCH`)——用刷新 mtime 的工具做的
批量复制/解压,变成每次收工有界的工作量、跨轮收敛,而不是 hook 超时窗口里的 IO 风暴。
4. **扫描基线状态文件**(系统临时目录)——稳态下只有 mtime 比上次完整跑动过的文件才会被
读内容;状态文件丢了只是多付一轮全量(幂等)重读。
5. **逐文件锁+原子写+回读验证**——与追加工具共用 `<文件>.lock` 命名,touch 和并发追加
永远不会互吞更新。锁忙就跳过;下次 Stop 自然补上。
6. **绝不阻断收工**——所有失败路径=跳过+本地日志一行(`<系统临时目录>/nomad_fmtouch.log`);
stdout 保持为空(零注入预算)。
**结构性排除**(永远不写死某个部署的目录名):点开头目录(`.git`/`.claude`/…)、
`node_modules`、骨架的 `97`/`98`/`99` 槽位前缀(待归纳/归档/回收站——数字前缀是中英文两种
布局共有的稳定信号)。其余交给上面的 schema 闸。
**与生产原版的一处有意分歧:**宪章 schema 文件没有 `updated` 行时,本版**插入**一行。
生产部署把缺字段留给它的结构哨兵去报告;本包里哨兵(§7)只报告、没有别的机制会创建该字段,
而 Nomad 装配出的团队出厂时全库都没有 `updated` 行——"只替换不插入"会让本钩子恰好在它发行
的环境里永久空转。已对装配样例团队做真实 zip 往返验证(2026-07-23):出厂解压态=扫 169 个
文件、0 个被碰(无误报);真实编辑 1 个文件=恰好该文件获得 `updated: <编辑日期>` 且 mtime
复原到编辑时刻;再跑一轮=0 候选(收敛)。
**手测提示:**与其他钩子不同,本钩子 stdout 刻意静默——确认它跑过,去读系统临时目录
`nomad_fmtouch.log` 的最后一行(每次收工一行 `done root=... touched=N ...`)。