Files
assist/skills/assistant/SKILL.md
jiantw83andClaude Opus 5 98dd0761fa docs(assistant): 被權限擋下的指令,回報要帶完整指令列
實測踩到一輪:它報「寫入監控頁失敗——系統的核准機制擋下這個寫入指令,重試
一次仍被擋下,不是 Gitea 回傳的錯誤碼」,然後照規則中止、釋放鎖、不寫心跳。
中止的行為完全正確,寫不成頁就不該假裝跑完。

但那一輪沒說是哪一支工具、哪一條指令。事後把明顯的嫌疑一個一個排除——那一支
腳本實測在無人值守下放行、暫存檔路徑落在檔案規則的範圍內、條目也帶著寫入
確認旗標——真正被擋的那一條始終沒找到。那一輪到現在還是原因不明。

問題在於「擋下」不是工具回的錯誤:沒有結束碼、沒有 stderr、工具自己的日誌上
也沒有痕跡。指令字面是唯一的證據,也是唯一能拿去對允許清單的東西,而清單
比對的是還沒展開的指令字面。所以少了那一行,事後就只能猜。

兩處都加:寫監控頁那一步的失敗分流加一條,界線那一段再加一條通則,涵蓋整輪
任何一次被擋。要求含環境變數前綴——那算指令字面的一部分,今天量過。

三份 manifest 版號從 0.2.9 升到 0.3.1。原本寫 0.2.10,同步 manifest 那一支
把它正規化掉了——那一支不收兩位數的修訂號。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 10:13:31 +08:00

470 lines
91 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
name: assistant
description: 'Start, inspect, patrol or stop the background assistant: jsc-hooks/hooks/heartbeat.sh owns the freshness verdict, tools/schedule.sh the system scheduler, tools/patrol.sh one round. The heartbeat is written by a completed round and by nothing else, so the schedule carries the patrol entry only, its period from the heartbeat TTL; start runs one round then installs that entry - absolute CLI path, environment snapshot, unattended write confirmation, which cron lacks - status prints heartbeat, schedule and task book read-only, stop removes the entry before clearing the heartbeat. Before that first round, start reconciles the built-in check items against jsc-meta''s delegation list through tools/seed-tasks.sh - seeding and rebuilding are one idempotent call, conditional rows are held back with their condition printed, and an origin user entry is never touched; status reports the same comparison through plan, which writes nothing, and a patrol round runs neither. One round reads five independent sources - skill and chain usage, version gaps and the restart gate, SDLC stage and work-package locks, the heartbeat''s own report, and the status event stream that jsc-hooks/tools/report-status.sh drains and rotates, whose starts with no matching end are the only evidence an earlier skill run aborted - then rewrites wiki MONITOR_{HASH} through jsc-gitea:wiki as three fixed blocks - basic data untouched, the latest round replaced whole, a 24-row summary table - and upserts its MONITOR_CONTENTS entry through jsc-gitea/tools/wiki-contents.sh, which reads the separate CONTENTS wiki repo and keeps one H2 block per machine - the heading is the monitor page''s own name, the fields are bullets under it, and one of them links that page by its absolute wiki-url. Every link on either page is written as [text](URL) and is verified by jsc-gitea/tools/link-check.sh before that page is written, so a dead link stops the write instead of landing on the page. A round that cannot record its result writes no heartbeat; one that starts while the previous holds the lock stands down. Use when someone starts, patrols or stops the assistant, or asks whether it runs and what is queued; not for environment health checks (jsc-cli:doctor), not for skill usage counts (jsc-log:stats).'
---
# assistant — start, status, patrol, stop
The background assistant runs where nobody is watching it. Its heartbeat is the only evidence that it is alive, so this skill is the single entry point for the four operations that touch that evidence: `patrol` writes it, `status` reads it, `stop` clears it, and `start` bootstraps the whole loop.
`{CURRENT}/jsc-hooks/hooks/heartbeat.sh` owns every heartbeat operation, including the freshness verdict. Never read, parse, write or delete `$JSC_HOME/assistant/heartbeat` directly — one verdict, one source.
`{CURRENT}/jsc-assist/tools/schedule.sh` owns every system-scheduler operation: installing an entry, removing it, and reading which entries exist. Never call `crontab` or `schtasks` from this skill, and never edit a crontab by hand.
`{CURRENT}/jsc-assist/tools/patrol.sh` owns one patrol round: taking the round lock, reading the five sources, composing the monitor page's blocks, and — after the page carries this round — writing the heartbeat. Never re-read a source this skill already handed to that script, and never compose a block by hand; the script prints the file paths.
All three flows have fixed inputs and outputs, so all three live in scripts. The task book is the only thing this skill reads for itself, and that is one directory listing.
## Step 0 — take the tool root from the invocation
Every operation starts here, before its own step 1. **This document calls the tool root `{CURRENT}`**, and every `{CURRENT}` below is replaced by it character for character: `{CURRENT}/jsc-assist/tools/patrol.sh` is run as `/root/.jsc/current/jsc-assist/tools/patrol.sh`.
The root comes from outside this skill. `schedule.sh` resolves it while a person is installing the schedule, and writes it into the entry's prompt as `工具根目錄={literal absolute path}`, so the round that entry wakes reads the root out of the text that woke it and runs no command at all.
| Who invoked this round | Where `{CURRENT}` comes from |
| --- | --- |
| the schedule — an unattended round, the `patrol` whose trigger is 排程 | the path after `工具根目錄=` in the invocation text, taken verbatim. No command is run |
| a person, in front of the terminal | the same token when the invocation carries one; otherwise `readlink -f "${JSC_HOME:-$HOME/.jsc}/current"`, run once |
**An unattended round that finds no root in its invocation stops there.** Report that the scheduled entry carries no `工具根目錄=` — an entry written by an older `schedule.sh` — say the fix is to run `start` again, or `jsc-assist/tools/schedule.sh install patrol` under `$JSC_HOME/current`, so the entry is rewritten with the root in it. Then take the operation's `aborted` status, write the `skill-end`, and stop.
Never work the root out instead. `readlink -f "${JSC_HOME:-$HOME/.jsc}/current"`, `ls -d "$JSC_HOME/current"` and every other resolve are refused in an unattended session — measured, see the table below — so running one does not produce a root, it produces a round that stops one step earlier having recorded nothing. Never fall back to `$JSC_HOME/current` as a written-out path either, never take a path from the plugin prompt or a previous transcript, and never guess.
**Only an attended invocation may resolve the root itself.** `readlink -f "${JSC_HOME:-$HOME/.jsc}/current"` prints one literal absolute path. It raises one permission prompt, and a person is there to answer it once. That is the whole reason the branch exists: portability survives where somebody can approve it, and nowhere else.
**The `:-$HOME/.jsc` half is load-bearing, and dropping it is how this line was wrong before.** `$JSC_HOME` is documented as defaulting to `~/.jsc`, and the shell does not know that: with the variable unset, a bare `$JSC_HOME/current` expands to `/current`, which is not a fallback to anything. Write the default into the expansion or the documented default never happens.
Take the root once per invocation and reuse that one answer. Never resolve it again per call, never print it as a report line of its own, and never add a tool that prints it. Never test the root with a command either — an unattended round cannot, and the first script call is the test that matters anyway.
An empty token, an empty `readlink` result, a path that is not absolute, or a resolved path that is not an existing directory means there is no root to work with. **That fourth item is the one the other three wave through**, so the attended resolve is only accepted once `[ -d "{the path just printed}" ]` says that directory exists, run in the same approved step as the resolve itself. It stays a separate check even now that the expansion carries its own default, because the ways a resolve can print a plausible path that is not there do not end with an unset variable: `JSC_HOME` set to a directory that no longer exists, `HOME` unset in a stripped environment, or the link farm simply never deployed all reach this line with something absolute in hand.
**How that guard earned its place is worth keeping.** This step used to resolve a bare `$JSC_HOME/current`, and on a machine that had never set `JSC_HOME` — the documented default being `~/.jsc` — it printed `/current` and exited 0: non-empty, absolute, and past every other item. The directory check was the only thing that caught it, and it caught it while pointing at the wrong culprit, because a resolve that cannot be trusted looks exactly like a root that is not there. The expansion above is the fix; this check is what noticed. The unattended round tests nothing, exactly as above: its root was written into the entry by whoever installed the schedule, and its first script call is what fails if that root is wrong. Report it, say `jsc-cli:deploy` has to run, take the operation's `aborted` status, and stop. Never fall back to a cache path, and never create the root here. Completion condition: one literal absolute path is in hand and every later command line carries it, or the missing root was reported and the operation stopped.
## Every script call carries a literal absolute path
**No command line in this skill carries a variable or a tilde, and the one resolve above is the single exception, allowed only when a person is watching.** Never type `$JSC_HOME`, `${JSC_HOME}` or `~` into any other command line.
The reason is the permission layer: it matches its rules against the command text as written, before the shell expands anything. Two properties follow from what was measured on this machine, and every rule in this skill rests on them:
1. **Unattended, only a full literal command that is on the allow list runs.** There is no such thing as a read-only command that is safe by default: a bare `ls -d` is refused exactly like everything else, and a refusal in a session with nobody in it is silent.
2. **A wildcard in the middle of a path does not match.** The rule and the command both have to be complete literals. A rule holding `*` where a version number goes matches nothing, so a cache path is refused however the rule is written.
| Command | Result |
| --- | --- |
| `/root/.jsc/current/jsc-assist/tools/patrol.sh` — a literal rule for it is on the allow list | ran |
| `$JSC_HOME/current/jsc-assist/tools/patrol.sh` | refused |
| `~/.jsc/current/jsc-assist/tools/patrol.sh` | refused |
| `readlink -f "$JSC_HOME/current"` | refused |
| `ls -d "$JSC_HOME/current"` | refused |
| `ls -d /root/.jsc/current` — literal, read-only, no rule for it | refused |
| `/root/.claude/plugins/cache/jsc/jsc-assist/0.1.0/tools/patrol.sh` — rule written with `*` for the version segment | refused |
A literal allow rule that itself starts with `$JSC_HOME` was added to the settings file and the same call was still refused, so no permission rule makes the variable form work either. The literal path is the whole fix, on both sides.
Row 4 was measured before the resolve carried its own default, and the verdict is the same for `readlink -f "${JSC_HOME:-$HOME/.jsc}/current"`: the rule is matched against the text as written, and that text still holds variables. The default fixed which path the resolve produces, not whether an unattended round may run it — that round still gets its root handed in, and this line stays the attended branch only.
**These rules outrank portability, and the next maintainer is the one who has to know why.** A variable in the path reads as the portable choice and costs nothing while a person is watching: the prompt appears, somebody approves it, the round carries on. The scheduled round has nobody to approve it. It stops at its first script call, records nothing, writes no heartbeat, and the machine then reads as a stopped assistant with no trace of the refusal anywhere. And the resolve is no way out of that, because row 4 of the table is the resolve itself: a round that cannot run a script cannot run the command that would have told it which script to run. That is why the root is handed in by whoever installed the schedule, and why anything written into a command line here is already literal.
## Tool paths
Every tool below is addressed through `{CURRENT}/{plugin}`, with `{CURRENT}` standing for the literal path step 0 took:
| What it does | Path to run |
| --- | --- |
| one patrol round, and joining the monitor page's three blocks | `{CURRENT}/jsc-assist/tools/patrol.sh` |
| the system scheduler | `{CURRENT}/jsc-assist/tools/schedule.sh` |
| the task book, the only writer there is | `{CURRENT}/jsc-assist/tools/tasks.sh` |
| the built-in check items, reconciled against the delegation list | `{CURRENT}/jsc-assist/tools/seed-tasks.sh` |
| the due built-in check items, actually run | `{CURRENT}/jsc-assist/tools/run-due.sh` |
| the heartbeat | `{CURRENT}/jsc-hooks/hooks/heartbeat.sh` |
| the status event stream | `{CURRENT}/jsc-hooks/tools/report-status.sh` |
| the wiki, through `jsc-gitea:wiki` | `{CURRENT}/jsc-gitea/tools/gitea.sh` |
| the `MONITOR_CONTENTS` entry | `{CURRENT}/jsc-gitea/tools/wiki-contents.sh` |
| the link check every write depends on | `{CURRENT}/jsc-gitea/tools/link-check.sh` |
**The delegation list is read across a plugin boundary, and the same rule applies to it.** `seed-tasks.sh` reads `{CURRENT}/jsc-meta/tools/delegate-spec.tsv`, so the root goes to it as `--root {CURRENT}` — the literal absolute path step 0 already took — and it resolves nothing for itself. `jsc-meta` is declared in this plugin's `jsc.requires` for that reason; when it is not installed the script exits 1 and changes not one entry, because a list that cannot be read is indistinguishable from a list saying nothing is delegable, and acting on the second reading deletes every built-in item at once.
**A `Skill(...)` rule permits invoking that skill and nothing more.** Every Bash call inside it is still checked on its own, so `jsc-gitea:wiki` reaching the wiki depends on `gitea.sh` carrying its own rule, the directory entry depends on `wiki-contents.sh` carrying one too, and both writes depend on `link-check.sh` carrying one — without them the round is refused locally, before any request leaves the machine, and the page never gets written.
**Never build a tool path out of the base directory the CLI hands you in the skill prompt.** That directory points into the plugin cache and carries a version segment, and the permission gate allows exactly the paths above and nothing else. A cache path is therefore refused silently: the round stops on a permission prompt nobody can answer, records nothing, writes no heartbeat, and the refusal looks exactly like a broken tool. Read the paths off this table every time — not off the prompt, not off a previous transcript, not off `crontab -l`.
Both scripts check this for themselves: run from anywhere outside `{CURRENT}`, they print a `[WARN]` line on stderr naming the path they were started from and the path they should have been started from, and then carry on. That line means this round is on the wrong path — quote it, fix the path, and do not treat the round's success as proof that the path was fine.
`current` is a set of version-free links that `jsc-cli:deploy` maintains, so an upgrade moves the cache and leaves these paths alone. When one of them is missing, report the missing link and say `jsc-cli:deploy` has to run; never fall back to a cache path to get the round through, and never create the link here.
## Two rules bind every link this skill writes
Both pages this round writes carry links, and both rules below hold for every one of them — the monitor page and the directory entry alike.
**Rule A — a link is always written as `[{text}]({URL})`.** The wiki's own `[[page]]` and `[[text|page]]` forms are not used here at all, and neither is the split between "same repo" and "cross repo" writing. The URL comes from `{CURRENT}/jsc-gitea/tools/gitea.sh wiki-url {repo} {page}`; never assemble a path by hand. `[[...]]` resolves only inside the wiki it sits in: the monitor page and the directory page live in two different repos, so a `[[MONITOR_{HASH}]]` written into the directory entry renders as an ordinary-looking link that goes nowhere, and nothing reports it.
**Rule B — a link is verified before it is written, never after.** Collect every link that is about to go into the page, hand the whole set to `{CURRENT}/jsc-gitea/tools/link-check.sh`, and write only on exit 0. The script prints one `{OK|DEAD|SKIP}<TAB>{URL}<TAB>{note}` line per URL and checks Gitea URLs through the API, never through the web status code — a private repo answers 404 to a logged-out web request, so a status-code check condemns live pages.
| Exit | Meaning | Do |
| --- | --- | --- |
| 0 | every link resolves | write the page |
| 1 | at least one link is dead | write nothing, report the `DEAD` lines verbatim, and take the step's own abort row |
| 2 | usage error — no URL was given | a defect in the call: pass the URLs and run it once more |
| 3 | a Gitea URL is in the list but `GITEA_HOST` is unset | report the variable and stop; never skip the check to get the write through |
| 7 | Gitea authentication failed (401, 403) | stop and report it as a token problem, never as dead links — an expired token makes live private pages look missing |
A round with no link to write skips the call and says so; a round that cannot verify writes nothing.
## Pick the operation
Run exactly one operation per invocation. Take it from the request: starting, launching or waking the assistant is `start`; asking whether it runs, what it is doing, or what is queued is `status`; running one round, patrolling, or a scheduled wake-up is `patrol`; stopping, halting or shutting it down is `stop`. When the request names none of the four, or names more than one, ask through the `jsc-ask:ask` decision tree with those four as the options, each stating its effect — `start` runs one round and installs the scheduled entry that keeps running rounds, `status` changes nothing, `patrol` runs one round and writes one heartbeat, `stop` removes that entry and deletes the heartbeat. **The one exception: a `patrol` invocation never asks anything at all** (see 界線 1 below). Never guess, and never run a second operation the caller did not ask for. Completion condition: exactly one of `start`, `status`, `patrol`, `stop` is chosen and named in the report.
## Every operation ends with one status event
The last thing any of the four operations does, after its report is printed, is write its own end event:
`{CURRENT}/jsc-hooks/tools/report-status.sh skill-end jsc-assist:assistant {status} {exit} "{one line}"`
The `start` half is already on record — a hook writes it when this skill loads — so this call is what tells the difference between an operation that finished and one that stopped half way. **Skipping it makes this skill's own run look aborted**, and the next patrol round reports it as such, on the page this skill writes. Pick the status from what actually happened:
| status | When |
| --- | --- |
| `ok` | the operation reached its own completion condition |
| `blocked` | the round stood down because another round holds the lock, or `install heartbeat` was refused — nothing was done and nothing is wrong |
| `failed` | a step returned a code that stopped the operation: `collect` exit 5 or 6, a monitor-page write that could not be made, `remove` non-zero in `stop` |
| `degraded` | the operation finished with a known gap: the directory entry was left unwritten, or the schedule entry was installed but the cron service is stopped |
| `aborted` | the operation stopped because a precondition did not hold, such as an empty `hash=` or a missing `current` link |
The call never changes the outcome: it returns 0 even when it cannot write, and a non-zero from it is reported as a defect in the reporting chain, never as a failure of the operation that just succeeded. Completion condition for all four operations: exactly one `skill-end` was written, and its status matches the outcome that was reported.
## Data sources
| Path | Read by | Format |
| --- | --- | --- |
| `$JSC_HOME/assistant/heartbeat` | `heartbeat.sh` only, never this skill | `key=value` lines: `ts`, `pid`, `cli`, `session` |
| `$JSC_HOME/assistant/schedule.log` | nobody here — the scheduled entry appends to it | free text; point the operator at it when a scheduled round misbehaves |
| `$JSC_HOME/assistant/tasks/{id}` | this skill reads it directly; every write goes through `tasks.sh` | `key=value` lines, one task per file: `id`, `created`, `kind` (`check` / `todo`), `title`, `action`, `trigger`, `recur`, `repo`, `due`, `state` (`pending` / `done` / `paused`), `last_run`, `next_run`, `fail_count`, `origin` (`user` / `assistant`), `spec_key` (`jsc-{domain}:{skill}` for a built-in item, empty for anything a person asked for) |
| `{CURRENT}/jsc-meta/tools/delegate-spec.tsv` | `seed-tasks.sh` only, read-only | the delegation list, tab-separated, one skill per row. `verdict`, `way`, `trigger` and `recur` decide whether a skill gets a built-in check item and on what schedule; column 12, `probe`, decides what that item's `action` actually is — a one-line read-only command, `pending:{reason}` for a slice whose entry point is not wired yet, or `-` for a row that has none. A list with only 11 columns predates that column and is handled as if every row said `-` |
| `$JSC_HOME/assistant/patrol.lock/` | `patrol.sh` only | the round lock, a directory. `info` holds `round`, `pid`, `started` |
| `$JSC_HOME/assistant/patrol/` | `patrol.sh` only | one round's scratch files, including `latest.md`, `summary.md`, `summary-row.md`, `newpage.md` and `contents-entry.md` |
| `$JSC_HOME/assistant/usage-prev.tsv` | `patrol.sh` only | last recorded round's cumulative usage counts, so the next round can print a real per-round delta |
| `$JSC_HOME/usage/events.jsonl` | `report-status.sh` only, never this skill and never `patrol.sh` by hand | one JSON object per line: `ts`, `cli`, `session`, `kind`, `name`, `phase`, `status`, `exit`, optional `ms` and `detail` |
| `$JSC_HOME/assistant/events-open.tsv` | `patrol.sh` only | the starts still waiting for a matching end, carried from round to round: `session`, `name`, `kind`, first-seen epoch, the event's own `ts` |
`$JSC_HOME` defaults to `~/.jsc`. `heartbeat.sh report` prints the resolved heartbeat path in its `file=` field, so take the assistant directory from there rather than rebuilding it.
**The verdict is time-based only.** A heartbeat counts as fresh when the file exists and its `ts` is less than the TTL behind now (300 seconds by default, `JSC_ASSISTANT_HEARTBEAT_TTL` overrides it). `pid` liveness is never tested: five CLIs and container processes cannot see each other's pids, so a live-looking pid proves nothing and a missing one proves nothing either. Report `pid` as a hint for whoever has to find a blocking process, and give it no weight in the verdict.
## heartbeat.sh exit codes
Every call in every operation below is judged by this table. Report the code you got, then take the row's action — never retry a code silently, and never downgrade a failure into a success.
| Code | Meaning | What to do |
| --- | --- | --- |
| 0 | `write` wrote the heartbeat, `clear` finished and the file is gone, `report` printed its line, `check` says fresh | Carry on with the operation's next step. For `report`, the state still has to be read out of the printed `state=` field |
| 1 | `check`: the heartbeat exists but is at or past the TTL — the last patrol round finished more than one TTL ago | Report `助理未運行`, name the age in seconds, and say the assistant has to be started again. `report` returns this state as `state=stale` with exit 0 |
| 2 | The script did not run at all — it failed to load its `lib.sh` | Report that the heartbeat state is unknown, name the script path and the code, and stop the operation. Never claim the assistant is running, and never claim it is stopped |
| 3 | `check`: no heartbeat file — no patrol round has ever finished | Report `助理未運行` and say to run `start`. `report` returns this state as `state=absent` with exit 0. In `stop` this state cannot appear, because `clear` treats a missing file as success |
| 4 | `check`: the heartbeat exists but its `ts` is missing, empty or not a number — the file is damaged, the assistant is not merely stopped | Treat it as not fresh; falling back to fresh is forbidden. Report the file as damaged, say the state cannot be read from it, and tell the operator to run `stop` and then `start` to rebuild it. `report` returns this state as `state=invalid` with exit 0 |
| 5 | Filesystem failure — `write` could not write the file, or `clear` could not delete it and the file is still there | Serious. Report it loudly with the stderr text and the path, and follow the operation's own step for this code. Never report the operation as done |
| 6 | Usage error — an unknown subcommand, or none at all | This is a defect in the call, not a state of the assistant. Report the exact command line that was run, correct it to one of `write`, `check`, `report`, `clear`, and run it once more. Report a second exit 6 as a defect in this skill and stop |
## The scheduler
Nothing in a background assistant runs on its own. The system scheduler is what makes it periodic, and `{CURRENT}/jsc-assist/tools/schedule.sh` is the only thing here that touches it. One job exists, written as exactly one entry carrying the fixed marker `# jsc-assist:assistant patrol`:
| Job | Period | Runs | Installed by `start` |
| --- | --- | --- | --- |
| `patrol` | derived from the heartbeat TTL (`*/2 * * * *` at the default TTL of 300 seconds) | one patrol round through the caller's CLI | yes, always |
| `heartbeat` | — | nothing. This job existed in the previous version and is no longer installable | no — `install heartbeat` exits 6 |
**The heartbeat job is gone on purpose.** It used to call `heartbeat.sh write` every minute, which made a fresh heartbeat prove only that cron was alive. Anything that writes a heartbeat outside a finished patrol round brings that back, so `install heartbeat` is refused, and `install patrol` deletes any leftover `heartbeat` entry from an older install and reports `legacy_removed=1`. Say that number in the report — a surviving legacy entry silently undoes this whole design.
**The period is derived, never guessed.** The heartbeat now moves once per patrol round, so the round period has to fit inside the freshness threshold. `schedule.sh` reads the machine's effective threshold from `heartbeat.sh report`'s `ttl=` field and picks the largest whole-hour-dividing minute count `P` with `2 × P × 60 < ttl`: one missed round still reads fresh, two missed rounds read stale. At the default 300 seconds that is every 2 minutes; raise `JSC_ASSISTANT_HEARTBEAT_TTL` to 1800 and it becomes every 12 minutes. Report both numbers (`ttl=`, `period=`) so the operator can see the trade-off and change it in one place. `--period` overrides the calculation and is checked against the same inequality; a period that does not fit exits 6 rather than installing a schedule that keeps the heartbeat permanently stale.
The mechanism follows the platform: `crontab` on Linux, WSL and macOS, `schtasks` on Windows. macOS keeps `crontab` — a `launchd` user who wants a plist writes it themselves; this skill does not generate one.
Four properties of that script matter enough to state here, because a report that ignores any of them is wrong:
- **It only ever touches its own entries.** Install filters out its own old entries by marker and appends the new one; it never rewrites a crontab it failed to read, and it counts everybody else's lines before and after to prove none went missing. Remove takes out its own markers only. Say this in the report — the operator is entitled to know their own cron entries survived.
- **A written entry is not a running entry.** WSL does not start cron by default, and this is the machine's most likely state. Exit 1 from `install` means the entry is on disk and will never fire. Report that as a failure of the start, name `sudo service cron start`, and say it has to be run again after every WSL restart. Never soften exit 1 into "scheduling is set up".
- **The log lives at `$JSC_HOME/assistant/schedule.log`**, deliberately outside every repository. Do not offer to move it into a project.
- **The entry runs with no human present.** The command is installed with `</dev/null`, so nothing it runs can block on input. A patrol round that stops to ask for a tool permission hangs that round, and the lock it holds stands the next round down until the lock ages out — which is why `patrol` asks nothing, of anybody, ever.
- **The entry carries its own environment.** cron gives it a short `PATH`, no settings file and no tty, so `schedule.sh` writes three things into the entry: the CLI resolved to an absolute path with `command -v`, a snapshot of the wiki variables taken at install time (`GITEA_HOST`, `GITEA_TOKEN`, `JSC_HOME`, `JSC_ASSISTANT_HEARTBEAT_TTL` and every set `JSC_WIKI_REPO*` — `JSC_WIKI_REPO`, `JSC_WIKI_REPO_MONITOR` for the monitor page and `JSC_WIKI_REPO_CONTENTS` for the directory page, which the script picks up from the environment rather than from a hardcoded list), and `JSC_GITEA_CONFIRM=yes`, because the write confirmation only recognises a tty and an unattended round has nobody to confirm. Two consequences belong in every report: the entry holds a copy of the token, so the crontab file has to stay readable by its owner alone, and a changed variable only reaches the entry after another `install`. `install` prints the snapshotted names in `env_snapshot=` and masks the token in every entry it prints — never print an entry read from `crontab -l` yourself.
- **`install` prints the permission rules that round needs.** One `allow_rule=` line each, every path a full literal under `current` — no variable, no tilde, and no wildcard inside the path, because a rule holding one matches nothing. Hand them to the operator verbatim: an unattended round that hits a permission prompt hangs until the lock ages out, and nobody is there to approve it. `Write(...)` rules do nothing for file writes — only `Edit(...)` is recognised — so never turn a printed `Edit` rule into a `Write` one.
- **`install` writes the tool root into the entry.** The round it schedules cannot resolve the root for itself, so `schedule.sh` puts the literal path into the entry's prompt as `工具根目錄={path}` and prints the same value as `patrol_root=`. Report that value, and treat any hand-edit of the entry that drops it as breaking every future round: from then on each one stops at step 0 with nothing recorded.
### What a fresh heartbeat actually proves
The heartbeat is written in exactly one place: `{CURRENT}/jsc-assist/tools/patrol.sh finish`, and `finish` is called only after that round's result is on the monitor page. So the verdict 新鮮 now proves one thing that is worth proving — **the last patrol round ran to the end and its result was recorded** — and it still does not prove three others:
- **Not that the round was clean.** Four sources are read independently and a round with three failures still records and still beats. The health of a round is `本輪判定` on the monitor page, never the heartbeat.
- **Not that any task in the book moved.** The task rows — `last_run`, `next_run`, `fail_count` — are the only evidence about work.
- **Not that the round did anything about what it found.** The patrol reports; a human acts. 界線 6.
The failure this design buys is the one worth having: a round that cannot read its sources, cannot reach the wiki, or dies half way writes no heartbeat, so the heartbeat ages past the TTL and every reader sees 過期. **A silent patrol is now indistinguishable from a stopped assistant, which is exactly right.** `status` still prints the heartbeat, the schedule and the task book as three separate facts, and the same limit binds whatever gate reads this heartbeat later: a fresh heartbeat is grounds for not blocking, never grounds for saying the assistant is doing its job.
## schedule.sh exit codes
| Code | Meaning | What to do |
| --- | --- | --- |
| 0 | `install` wrote the entry and read it back, the scheduler service is running; `remove` finished, or there was nothing to remove; `status` printed its lines | Carry on. For `status`, the state still has to be read out of the `installed=` fields |
| 1 | `install` wrote the entry, but the cron service is not running — the entry will never fire | The start did not succeed. Report the entry as installed and inert, quote the fix (`sudo service cron start`, and again after each WSL restart), and never claim the assistant will keep itself alive |
| 2 | `{CURRENT}/jsc-hooks/hooks/heartbeat.sh` was not found, so the TTL cannot be read and the period cannot be derived | Report that `jsc-hooks` is missing or too old (0.3.7 or newer is required) and stop the operation |
| 3 | No usable scheduler on this machine | Report the platform and that neither `crontab` nor `schtasks` was found, and stop. Never fall back to some other mechanism |
| 4 | The scheduler operation failed — the existing schedule could not be read for a reason other than "no crontab", or the write or delete returned non-zero | Report the stderr text verbatim. A read failure means nothing was written, so the user's other entries are untouched; say so |
| 5 | Read-back verification failed — the entry is missing after a successful write, is present twice, is still there after a delete, or somebody else's line count changed | Serious. Report it loudly with the printed numbers, and tell the operator to inspect `crontab -l` by hand before anything else is run |
| 6 | Usage error — an unknown subcommand or job name, a missing option value, `install heartbeat`, a `--period` that does not fit the TTL, the patrol CLI could not be determined, that CLI's executable is not on `PATH` so no absolute path can be written, or `JSC_HOME` does not resolve to an absolute path so no literal root can go into the entry | A defect in the call or a CLI that is not installed, not a state of the machine. The stderr line names which one it is; quote it, correct the command line, and run it once more. Report a second exit 6 as a defect in this skill and stop |
## The status event stream — the fifth source
`$JSC_HOME/usage/events.jsonl` is where every skill and every hook records how its run ended. A hook writes a skill's `start` for free; the matching `end` can only be written by the skill itself, in its own closing step. **So a `start` with no matching `end` is an aborted run, and it is the only evidence of one that exists anywhere.** That is what this source is for; the counts around it are secondary.
`{CURRENT}/jsc-assist/tools/patrol.sh collect` owns the whole of it — it calls `{CURRENT}/jsc-hooks/tools/report-status.sh drain`, then `rotate`, then does the pairing, and writes the 執行狀態事件 subsection into `latest_file`. **Never run `drain` from this skill.** Four properties make that the only safe arrangement, and each one is a way to lose events:
- **`drain` is a consuming read.** It prints everything written since the last drain and then moves the offset in `$JSC_HOME/usage/scan-state/events.offset`. The same events never come back. Read into a transcript instead of a file, they are one dropped line away from gone; a second `drain` in the same round returns exit 3 and the first drain's events are already spent.
- **Exit 3 means there were no new events, and that is a normal round, not a failure.** Most rounds have nothing new. The script also uses 3 when the stream file does not exist yet.
- **`rotate` has to follow `drain` immediately.** It renames the stream and resets the offset once the file passes its size limit, so anything appended between the two calls is moved aside without ever being drained. One script, one run, smallest possible gap.
- **Pairing is by `session` plus `name`, and it carries across rounds.** Five CLIs run the same skill in different sessions at once, so `name` alone lets one session's `end` cancel another session's `start`. And a round lasts about two minutes while a skill run can last much longer, so an unmatched `start` is held in `$JSC_HOME/assistant/events-open.tsv` and matched against later rounds. It is reported as an abort only once it has stayed open longer than the heartbeat TTL; below that it counts as still running.
Neither `drain` nor `rotate` may stop a round. A missing `report-status.sh`, a `drain` that returns anything other than 0 or 3, and a failed `rotate` each mark this one item failed or add one 警示來源 — exactly like the other four sources — and the round carries on to record itself. The reporting chain breaking must never break the round that is doing the reporting.
## patrol.sh exit codes
One table for all three subcommands. Read `collect`'s codes carefully: **1 and 3 are results, not aborts.** A round with failed items still has a result to record, and refusing to record it would hide the failure instead of showing it.
| Code | Meaning | What to do |
| --- | --- | --- |
| 0 | `collect`: all five items read to the end, empty sources included. `finish`: heartbeat written, snapshot promoted, lock released. `abort`: lock released | Carry on with the operation's next step |
| 1 | `collect`: partial success — at least one item failed and at least one produced a result | **Write the page anyway.** The latest-round block already marks the failed items and the round verdict is 警示. Name the failed items and their `note=` text in the report |
| 2 | `finish`: `{CURRENT}/jsc-hooks/hooks/heartbeat.sh` was not found | The round completed and is recorded, but no heartbeat exists to prove it. Report the round as recorded and the heartbeat as not written, say `jsc-hooks` 0.3.7 or newer has to be installed, and run `{CURRENT}/jsc-assist/tools/patrol.sh abort --round {id}` to release the lock |
| 3 | `collect`: all five items failed | **Write the page anyway**, with verdict 異常. A page listing five failures is the signal; a missing page is not. Then carry on to `finish` as usual — the round did complete |
| 4 | Another round holds the lock (`collect`), or the lock is no longer this round's (`finish`, `abort`) | Not a failure. On `collect`: report 本輪讓開 and name the holder and its age from the printed `lock=busy` line, then write nothing and stop. On `finish`: the previous round overran and was taken over, so this round's result does not count — report it, write no heartbeat, and stop |
| 5 | Filesystem failure — the lock could not be created or released, a scratch file could not be written, the snapshot could not be promoted, or `heartbeat.sh write` returned non-zero | Serious. Report it loudly with the stderr text and the path. On a `finish` failure the round is recorded but unproven: say so plainly and never claim the round beat |
| 6 | Usage error — an unknown subcommand, a missing `--round`, or an option with no value | A defect in the call. Correct it and run it once more; report a second exit 6 as a defect in this skill and stop |
## Built-in check items and the delegation list
The delegation list holds one row per jsc skill and records whether that skill can be handed to the background assistant. Every row that is delegable and carries a `trigger` and a `recur` earns one `check` entry in the task book, with `origin: assistant` and `spec_key` set to `jsc-{domain}:{skill}`. `{CURRENT}/jsc-assist/tools/seed-tasks.sh` is the only thing that creates or removes those entries, and it does it by reconciling the two sides rather than by remembering whether it has run before:
| Situation | What the reconcile does |
| --- | --- |
| The list has a delegable row, the task book has no entry for it | add one, `origin: assistant`, `spec_key` set |
| The task book has an entry whose `spec_key` is no longer a delegable row — removed from the list, or changed to `none` | remove that entry, so no orphan is left pointing at a skill nobody delegates any more |
| The entry is `origin: user` | leave it exactly as it is, always. A skill being re-judged is never a reason to delete something a person asked for |
| The row is still delegable but its `trigger`, `recur` or `way` changed | report it as `drift=` and change nothing, unless `--refresh` was passed |
| The row's `verdict` is `cond` | hold it: seed nothing, print a `held=` line carrying the condition text, unless `--allow-cond {key}` named that row |
## What a built-in item actually does, and the `probe` column
`way` decides the shape of the entry's `action`, and column 12 `probe` decides the rest of it:
| `way` | `probe` | `action` | Also printed |
| --- | --- | --- | --- |
| contains `invoke` | ignored entirely | the skill name | a `probe_bad=` line if `probe` held a command — the list's own header says an `invoke` row carries `-`, and honouring a command there would turn a whole delegated skill into one script call that writes none of the pages that skill exists to write, while looking perfectly healthy |
| `patrol`, `remind`, `patrol,remind` | a one-line command | that command, substituted | a `probe=` line with the command and its remaining holes |
| `patrol`, `remind`, `patrol,remind` | `pending:{reason}` | `remind` | a `pending=` line carrying the reason verbatim |
| `patrol`, `remind`, `patrol,remind` | `-`, empty, or the whole list is 11 columns | `remind` | nothing — this is the behaviour that predates the column |
**A `probe` that cannot be substituted falls back to `remind` and is reported, never dropped.** The path is not `{root}/jsc-{domain}/...`, the command carries a `$` or a `~`, a brace other than the three known holes survived, the root could not be resolved, or the script is not on this machine: each prints `probe_bad=` and the entry is still seeded, as a reminder. Not seeding it would mean removing it on `apply`, so one mistyped cell upstream would delete an entry carrying its own `last_run` and `fail_count` history.
**`{root}` is substituted here; `{cli}` and `{repo}` are deliberately left in the value.** The CLI list has to be detected and the repositories have to be scanned, and neither is known at seeding time. Expanding into several entries instead would give one `spec_key` several files — the reconcile treats that as `dup=` and refuses to touch any of them — and would go stale the moment a CLI is installed or a repository cloned, with re-expansion costing the history it just protected. So the hole stays, and one rule pays for it: **an `action` containing a brace is not yet a runnable command and must never be executed as written.** `run-due.sh` is what executes one, and it is the only thing that does: `tasks.sh` stores the value, `due.sh` prints it, `status` and the monitor page print it. That tool substitutes `{cli}` from `jsc-cli/tools/detect-clis.sh` and runs once per target, with the targets' results together counting as the entry's one success or failure. `{repo}` has no source yet — the repository scan is not built — so an entry carrying that hole is held, reported, and left with its `last_run` and `fail_count` untouched. **Holding is not failing**: an entry that cannot be given a target did nothing wrong, and recording it as a failure grows a counter nobody can bring down by fixing that entry, which is exactly what that counter exists to make visible.
**A `pending` row stays a reminder but is never reported as an ordinary one.** The reason lives in the report, as a `pending=` line, and nothing is written into the task file. Putting the marker in the title would change the `id` and cut that entry's history, and the drift check compares `kind`, `action`, `trigger` and `recur` but not the title, so a stale marker would never be caught; adding a sixteenth key would change the task book's fixed storage format for a piece of upstream prose the task book has no way to edit later. `status` runs `plan`, so `pending=`, `held=` and `drift=` all reach a human in the same place.
**Neither repository's merge order can break the other.** `seed-tasks.sh` measures the list's column count once: 12 or more and `probe` applies, 11 or fewer and every non-`invoke` row seeds as `remind` exactly as before, with a single note saying why rather than one warning per row. On the round after `jsc-meta` gains the column, the four command rows show up as `drift=` and change nothing until a human passes `--refresh` — report that as the expected transition, not as a fault.
**Seeding and rebuilding are the same call.** There is no first-run flag and no second code path: what happens is decided by comparing the list against the task book, so the first call seeds every item and every later call is a no-op until the list actually changes. That is why `start` runs it every time rather than only once.
**A `cond` row is held back on purpose, and the report has to say so.** The condition lives in prose in the list, so no script can evaluate it, and one of them says in as many words that its own scripts still resolve through version-carrying paths — seeding it would have the assistant invoke, every single round, something that stops on its first script call with no error, no output and a heartbeat that still looks healthy. So the default is to hold, and every held row is printed with its condition and the half that stays with a human. Never quietly drop them: a missing item nobody can account for is the failure this reporting prevents.
## seed-tasks.sh exit codes
| Code | Meaning | What to do |
| --- | --- | --- |
| 0 | The two sides are reconciled — `plan` printed its verdict, or `apply` made the changes. Zero changes is this code too | Carry on, and carry the `added=`, `removed=`, `kept=`, `drift=`, `held=`, `bad=`, `probe=`, `pending=` and `probe_bad=` counts into the report |
| 1 | The delegation list could not be read, so **nothing was touched** | Report `jsc-meta` as missing or unreadable and say the built-in items were left exactly as they were. Never report this as "the list has no delegable skills" |
| 2 | The list was read but not one delegable row came out of it, so **nothing was touched** | Report the list itself as suspect — a half-synced or damaged list would otherwise delete every built-in item. Point at the file and stop |
| 3 | `tasks.sh` was not found, so **nothing was touched** | Report the installation as incomplete: the task book has exactly one writer and it is missing |
| 4 | At least one `add` or `remove` failed; the rest were done | Report every `add_failed=` and `remove_failed=` line with the `tasks.sh` exit code it carries, and judge each by that script's own code table |
| 5 | Filesystem failure — the scratch directory or a scratch file could not be written | Report it with the path; the reconcile could not even be computed |
| 6 | Usage error — an unknown subcommand or option, a `--root` that is not absolute, or an `--allow-cond` value that is not `jsc-{domain}:{skill}` | A defect in the call. Correct it and run it once more |
## run-due.sh exit codes
| Code | Meaning | What to do |
| --- | --- | --- |
| 0 | The round's due entries were dealt with. Zero due entries, and every entry held for want of a target, are both this code | Carry on, and carry the `done=`, `failed=`, `held=`, `skip=` and `write_failed=` counts into the report |
| 1 | At least one entry's command returned non-zero. That entry is already recorded as failed and its failure count went up; the rest still ran | Report every `failed=` and `target_fail=` line with the command and the first line of its output. This is a finding about the thing that was checked, not a fault in the round |
| 2 | The due list could not be read, or its column count is not the one this tool knows, so **nothing ran** | Report it and say the judging step has not run, or its output format changed. Never read this as "nothing was due" |
| 4 | At least one write-back to `tasks.sh` failed. The command ran but the task book did not record it, so the same entry runs again next round | Say that out loud with the `write_failed=` lines and their `tasks.sh` codes — a command that runs every round and is never recorded is the failure mode this code exists to name |
| 5 | Filesystem failure — a scratch file could not be written | Report it with the path |
| 6 | Usage error — an unknown sub-command or option, a missing option value, or a `--root` that is not absolute | A defect in the call. Correct it and run it once more |
**A held entry is not a failed entry.** `held=` covers an entry whose `{cli}` or `{repo}` could not be given a target, and one whose command no longer passes the shape check. Its `last_run` and `fail_count` are left exactly as they were, and the report has to keep that distinction: an entry nobody could give a target to did nothing wrong, and letting its failure count climb buries the entries that really are broken under ones that are merely unwired.
## Boundaries
The six limits in `AGENTS.md`「助理的界線」 hold for all four operations. Four of them need saying out loud here:
- **This skill never judges a gate.** It maintains the heartbeat and prints what the heartbeat says. Whether a stale heartbeat blocks a skill call is decided by a hook, synchronously and offline; nothing in this skill blocks or waves through anything. 界線 2.
- **A command the permission layer refuses is reported with its full command line, wherever in the round it happened.** A refusal is not an error the tool returned: there is no exit code, no stderr, and nothing in the tool's own log. The command text is the only evidence, and it is the only thing that can be checked against the allow list — which matches the text as written, before the shell expands anything. So quote the line verbatim, prefix included, and name the step that submitted it. 界線 1 says a round never asks; this is what makes a refused round diagnosable instead of merely reported. One round wrote 「the write was refused」 and named neither the command nor the tool: every obvious suspect was ruled out afterwards and the real one was never found, so that round is still unexplained.
- **A patrol round asks nothing.** It runs from cron with nobody present, so there is no one to answer and a question hangs the round. Every branch in the patrol steps below resolves without a question: a missing source is recorded as missing, an ambiguous result is recorded verbatim, and a round that cannot proceed aborts and reports. Never call `jsc-ask:ask` from `patrol`. A command that is not on the allow list is a question too — the permission prompt is one, and it is the one nobody sees — which is why step 0 hands that round its root instead of letting it resolve one. 界線 1.
- **A patrol round rewrites the monitor page as three fixed blocks.** Read the old page back first; keep 本頁基本資料 as it stands, replace 最新一輪 whole, put this round's row on top of the summary table and cut it to 24; then put the whole page. The directory page is a separate write in a separate wiki repo, and `wiki-contents.sh` does it: that page keeps one H2 block per machine, and this machine's block is the only one that is updated. A page that could not be read is a page that does not get written — the summary table only survives if the old one came back. 界線 4.
- **A patrol round reports; it never acts on what it found.** The 待人處理 rows name an entry point for a human. The patrol does not run that entry point, does not fix a hook, does not update a plugin and does not touch a repository. 界線 3 and 界線 6.
- **Running the due built-in items is not an exception to that.** Those entries are the assistant's own scheduled work, put there by a reconcile against a delegation list that goes through review; a 待人處理 row is a finding about somebody else's machine state. The first is a round doing the job it was given, the second is a round deciding what somebody else's job is. Step 5 keeps the line where it belongs by running only read-only probe commands from the list, never the skill named by an `invoke` row and never anything a person entered by hand — and the moment a command that writes appears in that column, this paragraph is the one that has to be re-argued, not quietly widened.
- **Only a human-initiated operation reconciles the built-in items; an unattended round reports the difference and stops there.** `start` runs `seed-tasks.sh apply`, because somebody asked for it and is there to read what it added and removed. `status` runs `seed-tasks.sh plan`, which writes nothing. `patrol` runs neither: removing a check entry destroys that entry's `last_run` and `fail_count` history, and 界線 5 keeps destructive cleanup with the human — a round that deletes a row at three in the morning because the list was mid-sync leaves nobody able to see that the row ever existed. The consequence is worth stating: on a machine nobody starts or inspects, a list change reaches the task book only at the next `start`. 界線 3 and 界線 5.
- **`stop` clearing the heartbeat and removing the schedule is not a breach of 界線 5「不刪除狀態檔」.** That limit protects state that records work — the task book, worktrees, wiki pages — from a background process nobody is watching. The heartbeat records one fact only, "the last patrol round finished", and the schedule entry is what keeps rounds running, so a `stop` that leaves either behind leaves a lie behind. Clearing both is the whole job of `stop`, and they are the only deletions any operation here performs, both of them entries this skill installed itself. `stop` touches nothing under `tasks/`, nobody else's cron entry, no worktree and no wiki page. Do not "restore" this limit later by taking either removal out of `stop`.
## Crash exit needs no cleanup
An assistant that is killed, crashes, or dies with the machine writes no farewell. It does not need to. The heartbeat is a timestamp, not a lock: the last one written stays on disk, ages past the TTL on its own, and every reader from then on sees 過期. No shutdown handler, no cleanup hook and no pid check is involved, so there is nothing left that can fail to run.
The round lock is the one thing a crash does leave behind, and it ages out the same way: `patrol.sh collect` breaks a lock older than the heartbeat TTL, takes it, and prints `lock_broken=1` so the takeover lands on the monitor page instead of happening quietly. The overrun round that lost its lock then gets exit 4 from `finish` and writes no heartbeat, which is correct — it never reached the end.
That property holds only while nothing fakes a heartbeat. **`write` is called by `{CURRENT}/jsc-assist/tools/patrol.sh finish` and nowhere else.** `start` does not call it, `status` does not call it, `stop` does not call it, no scheduled entry calls it, and no other skill calls it. A heartbeat written by anything that is not a finished round says a round finished when none did, and the reader has no way to tell the difference. This is also why `stop` removes the scheduled entry before clearing the heartbeat, and never in the other order.
## start
`start` proves the loop works before it schedules it: the built-in items first, then one patrol round, then the scheduled entry. It installs no daemon and writes no bare heartbeat.
1. **Reconcile the built-in check items against the delegation list.** Run `{CURRENT}/jsc-assist/tools/seed-tasks.sh apply --root {CURRENT}`. This comes before the round, so the round's own task-book section already shows the items this machine is supposed to be checking. Judge the result by the seed-tasks.sh exit-code table, and keep every `add=`, `remove=`, `drift=`, `held=`, `bad=`, `dup=`, `skip_user=`, `probe=`, `pending=` and `probe_bad=` line plus the summary counts for the report. **Exit 1, 2 and 3 do not stop the start.** Nothing was touched in any of those cases, so the assistant still has whatever items it had before and the round is still worth running: record what the code means, put it into the closing report, and carry on to step 2. Exit 4 is the same — the entries that did get added or removed stand, and the failed ones are named. Never pass `--force` and never pass `--allow-cond` on your own initiative: the first would let this step delete something a person asked for, and the second asserts a condition only a person can check. Completion condition: the exit code and the summary counts are recorded, with every `held=` row's skill name kept for the report, or the code was recorded as "nothing was touched" and step 2 was reached anyway.
2. **Run one patrol round.** Follow every step of the `patrol` operation below, start to finish. This is what writes the first heartbeat — there is no shortcut past it, because a heartbeat that no round produced is exactly the lie this design removes. When that round ends without a heartbeat for any reason (`collect` exit 4, 5 or 6, an empty `hash=`, a failed write of the monitor page, a directory-entry failure other than exit 3, or `finish` exit 2, 4 or 5), the start has failed: report the round's outcome and the code, do not run step 4, and do not claim a started assistant. A round that completed with failed items (`collect` exit 1 or 3) is still a completed round — carry on to step 3 and name the failures in the closing report. Completion condition: `patrol.sh finish` exited 0, or the failure report naming the step and the code has been printed and no start was claimed.
3. **Confirm the heartbeat.** Run `{CURRENT}/jsc-hooks/hooks/heartbeat.sh report` and read its `state=`, `ts=`, `ttl=`, `pid=`, `cli=`, `session=` and `file=` fields. `state=fresh` is the expected result. Any other state right after a successful round means something rewrote or removed the file in between: report the state, the path and that the heartbeat did not survive its own write, and do not claim a started assistant. Completion condition: the report line was read and either `state=fresh` was recorded with its seven fields, or the mismatch was reported.
4. **Install the patrol entry.** Run `{CURRENT}/jsc-assist/tools/schedule.sh install patrol`. Judge the result by the schedule.sh exit-code table, and keep the printed `entry=`, `ttl=`, `period=`, `legacy_removed=`, `others_kept=`, `env_snapshot=`, `patrol_root=`, every `allow_rule=` line and `service=` for the report. Exit 1 is the case to get right: the entry is installed and inert, so step 5 reports a started assistant whose heartbeat will expire, not a scheduled one. Exit 6 with a CLI executable that is not on `PATH` is the second one: nothing was installed, and the fix is to install that CLI or to pass `--patrol-cmd`, not to write a bare command name into the entry. On 2, 3, 4, 5 or 6 nothing is scheduled — report the code, say the round ran but no further round will, and do not claim the assistant will stay alive. Completion condition: the exit code is recorded, and on exit 0 the entry line, the TTL, the period, the legacy count, the surviving-entry count, the snapshotted variable names, the tool root the entry carries and the allow rules are recorded with it.
5. **Report the start.** Print the round's verdict and its four item results, the monitor page that was written, the heartbeat path, the local time of `ts`, the TTL in seconds, `pid`, `cli` and `session` as hints, then the scheduler mechanism, the derived period, the installed entry line as the script printed it with the token already masked, the `patrol_root=` the entry carries — that is what every later round reads its tool root from — how many legacy heartbeat entries were removed, and how many other entries were left untouched. Then hand over the two operator items the install printed: the `allow_rule=` lines verbatim, so the unattended round never meets a permission prompt, and the reminder that the entry holds a snapshot of the listed variables including the token — keep the crontab file readable by its owner alone, and run `install` again after any of those variables changes.
**Then report step 1's reconcile in its own block**, because it is the only place the built-in items are accounted for: how many were added, how many removed, how many left alone, then every held `cond` row by name with the reason it was held, every `bad=` row as a defect in the list rather than in this machine, every `drift=` row with the change the list now asks for and the note that `--refresh` is what applies it, and every `dup=` or `skip_user=` row as an entry a person has to settle. **Then account for the `probe` column separately**: every `probe=` row as an item that now runs a read-only command rather than only reminding, naming any `{cli}` or `{repo}` hole still in it; every `pending=` row as a slice whose entry point is not wired yet, with the list's own reason — that is the only place those are distinguishable from the rows that were always reminders; and every `probe_bad=` row as an item that fell back to reminding, with what stopped the substitution. When the summary carries `spec_cols=11`, say that this machine's `jsc-meta` predates the column and that no item runs a command this round. An exit of 1, 2 or 3 is reported here as "the built-in items were left as they were" with the reason, never as "there is nothing to check". Close with the notice that matches step 4's outcome, printed literally with `{ttl}` replaced by the TTL just read and `{period}` by the derived period:
| Step 4 | Notice |
| --- | --- |
| exit 0 | 助理已啟動,第一輪巡檢跑完了,結果寫上監控頁了,心跳也寫了。排程接上了,之後每 {period} 分鐘跑一輪,每一輪跑完才寫一次心跳。心跳新鮮代表上一輪巡檢真的做完了;那一輪各項有沒有全過,看監控頁的本輪判定。 |
| exit 1 | 助理已啟動,第一輪巡檢跑完了,排程條目也寫進去了,但 cron 服務沒在跑,那一筆一次都不會被執行。心跳過了 {ttl} 秒就會過期。請先跑 `sudo service cron start`,重開 WSL 之後要再跑一次。 |
| 其他結束碼 | 助理已啟動,第一輪巡檢跑完了,但排程沒接上(結束碼 {code})。不會再有下一輪,心跳過了 {ttl} 秒就會過期,屆時請再跑一次 start。 |
Completion condition: the report carries the round verdict, the monitor page name, the path, the local heartbeat time, the TTL, the period, the three hint fields, the scheduler outcome, the tool root the entry carries, the allow rules and the snapshot reminder; the reconcile block carries the three counts and one line per held, drifted, rejected or duplicated row; and exactly one notice above appears with the real numbers.
## patrol
One round: read five sources, record the result, then beat. Everything before the heartbeat is read-only except the round's own scratch files. Ask nobody anything.
1. **Collect.** Run `{CURRENT}/jsc-assist/tools/patrol.sh collect --trigger 排程` (use `--trigger 手動` when a person asked for this round). That is the same split step 0 branched on: 排程 is the unattended round that read its root out of the invocation text, 手動 the round somebody asked for. Judge the exit code by the patrol.sh table. Exit 4 stands the round down — report the holder and its age from the printed `lock=busy` line, and stop; write no page and no heartbeat. Exit 5 and 6 stop the round the same way, with the code and the stderr text. Exit 0, 1 and 3 all carry on to step 2. Record `round=`, `lock_broken=`, `hash=`, `page=`, `verdict=`, `failed_sources=`, `warn_sources=`, `pending=`, every `item=` line, and the file paths `latest_file=`, `summary_file=`, `summary_row_file=`, `newpage_file=`, `contents_file=` and `due_rows_file=` — that last one is what step 5 has to be given, and an empty value there means the judging step produced no list, so step 5 has nothing to act on and says so rather than falling back to anything. Completion condition: the round id, the page name and the five file paths are recorded, or the stand-down or the failure was reported and the round stopped.
**The status event lines come out of the same call.** `collect` drained the stream and rotated it (see 「The status event stream」 above), so record `events_total=`, `events_bad=`, `events_unpaired=`, `events_running=`, `events_rotated=` and `events_file=` alongside the rest, and read `item=D-11` for whether that source was readable at all. The 執行狀態事件 subsection of `latest_file` already carries the two detail tables — the non-`ok` events and the starts with no matching end — so never rebuild either by hand and never call `report-status.sh` yourself: a second `drain` this round would either return exit 3 or eat events that then reach no page at all.
2. **Check the page name.** An empty `hash=` means `jsc-gitea/tools/hash-id` could not be found or could not run, so there is no page to write to and nothing can be recorded. Run `{CURRENT}/jsc-assist/tools/patrol.sh abort --round {round}`, report that the round found its results but has nowhere to put them, name `jsc-gitea` as missing, and stop.
**Never invent a page name, and never work the hash out by hand** — a hand-made name lands the content on a page nobody reads. `hash-id` hashes `{host}/{user}` and prints the full 40-character uppercase hexadecimal SHA-1: no truncation to 8, no `H` prefix, and an empty input exits 2 rather than hashing the empty string. So `page=` is either `MONITOR_` plus that 40-character string, exactly as the script printed it, or nothing at all. Completion condition: `page=` holds a `MONITOR_{HASH}` name taken verbatim from `collect`, or the abort ran and the round was reported as unrecorded.
3. **Rebuild `MONITOR_{HASH}` from its three blocks.** Hand it to `jsc-gitea:wiki` with page type `MONITOR`, so the repo is the one `gitea.sh wiki-repo MONITOR` resolves — `JSC_WIKI_REPO_MONITOR`, then `JSC_WIKI_REPO`, then exit 3. This is the content page and it stays in that repo; only the directory page of step 4 moved to the `CONTENTS` repo, and neither chain ever falls back to the other. Read the page back first, then build the new body out of what came back plus this round's files, in this order and with nothing else on the page:
**The three blocks are joined by `{CURRENT}/jsc-assist/tools/patrol.sh rebuild --old {the file the old page was read into}`, never by hand.** It prints `rebuilt_file=` — put that file. It also prints `old_format=`, `blocks=`, `summary_rows=` and `old_rows_kept=`; carry those into the report. Exit 6 means an argument was rejected or the old-page file is not there, exit 5 a scratch file could not be written; both take step 3's abort row.
Joining them by hand is what this replaces, and the reason is worth keeping. The join is a fixed shape, so leaving it to the caller meant a fresh agent picked its own tools for it every round: one round reached for `awk`, was refused by the permission gate twice, worked around it because somebody was there to watch, and said in its own report that the same refusal would hang an unattended round — with the round lock already taken. The scratch directory had accumulated 124 files by then, named `newpage.md`, `new-page.md`, `new_page.md`, `page-new.md` and so on: the same join, redone every round, under a different set of names. **A step with one correct shape does not belong in a prompt.** What the script joins:
| Block | Where it comes from |
| --- | --- |
| 本頁基本資料 | the old page, byte for byte from its heading to the line before 最新一輪. Never rewritten, never re-derived — the script does not even normalise its trailing blank lines |
| 最新一輪 | the whole content of `latest_file`, replacing the old block entirely |
| 近 24 輪摘要 | `summary_file`, which already holds the heading, the five-column table header (`巡檢時間`、`本輪判定`、`各項成敗`、`待人處理`、`警示來源`) and this round's row; then the old table's data rows in their old order underneath, cut so the table holds at most 24 rows |
An old-format page — per-round sections stacked up, no 最新一輪 heading — is detected by the script itself, which keeps the basic-data block, drops the stacked sections, starts the table with this round's row, and prints `old_format=yes converted=1`. Report that the page was converted.
**Verify the page's links before the write.** List every link the rebuilt body carries — the ones the latest-round block brought in, and any that survived in the block carried over from the old page — and run `{CURRENT}/jsc-gitea/tools/link-check.sh` over the whole list. Exit 0 is the only result that permits the write. On exit 1 report the `DEAD` lines verbatim, then run `{CURRENT}/jsc-assist/tools/patrol.sh abort --round {round}` and stop: a round that writes a dead link records a false trail nobody can follow back. Exits 2, 3 and 7 take the same abort, each reported by the rule B table above. A body carrying no link at all needs no call — say so in the report rather than claiming a check that never ran.
Put the whole page. Only exit 4 from the read permits creating the page instead, and then the body is the whole content of `newpage_file`, which already carries all three blocks. Exit 7 and exit 8 mean the old content is unknown: create nothing, write nothing — rebuilding a page from an unknown original throws the summary table away. On any write failure — including exit 3 with no wiki repo configured for `MONITOR`, which the patrol cannot ask about — run `{CURRENT}/jsc-assist/tools/patrol.sh abort --round {round}`, report the code, and stop. **When the write did not fail but was refused — the permission layer stopped the command before it ran — the report MUST carry the command line verbatim, exactly as it was submitted.** A refusal has no exit code and no stderr from the tool, so the command text is the only thing that can be held against the allow list, and the allow list matches the text as written. A report that says only 「the write was refused」 cannot be acted on: this happened, and the round that hit it named neither the command nor the tool, so every obvious suspect had to be ruled out one at a time and the actual one was never found. Quote the whole line — the environment-variable prefix included, since that counts as part of what the rule is matched against — and say which step submitted it. **No record, no heartbeat**, and that verdict belongs to this step alone: the round's result lives on this page, so a repo this step cannot resolve leaves the round with nowhere to be recorded. Step 4 is judged on its own terms. Completion condition: `link-check.sh` exited 0 over the body's links or the body carried none, the put or the create returned success, and the page holds exactly three blocks with the summary table at 24 rows or fewer and this round's row on top, or the abort ran and the round was reported as unrecorded with its exit code.
4. **Update this machine's block in `MONITOR_CONTENTS`, through `jsc-gitea/tools/wiki-contents.sh`.** That page is a directory every machine writes to, and it lives in the repo `gitea.sh wiki-repo CONTENTS` resolves — `JSC_WIKI_REPO_CONTENTS`, then `JSC_WIKI_REPO`, then exit 3, and never a fallback to `JSC_WIKI_REPO_MONITOR`. The page carries no table: it is an H1, a `>` preamble, and then one H2 block per machine — the heading is that machine's monitor page name, and the fields are one `- {name}:{value}` bullet each underneath. The script owns the read-match-write of one block, so never read this page and rebuild it by hand, never write it through `jsc-gitea:wiki`, and never rebuild it the way step 3 rebuilds the content page — every other block here belongs to a machine that is not this one, and one careless whole-page write deletes their records.
**Finish the block first.** `contents_file` holds this machine's whole block — `## MONITOR_{HASH}`, a blank line, then the bullets — and its 監控頁 bullet already carries the rule A shape `[{page name}]({URL})` with the placeholder `{監控頁絕對網址}` standing in for the URL, because the absolute URL cannot be known until step 3 has actually put the page. Run `{CURRENT}/jsc-gitea/tools/gitea.sh wiki-url {the MONITOR repo step 3 resolved} MONITOR_{HASH}`, replace the placeholder with what it prints, and write the finished block to a file. Exit 4 there means step 3's write has not landed — go back to step 3 rather than writing a block. Exit 5 means the page carries no `html_url`: report it and never assemble a URL by hand. Exit 7 or 8: report the code and take the abort row below. **Any other non-zero exit takes the same abort row**, a missing argument included — a URL that never arrived would otherwise leave that bullet holding the raw placeholder, and the block would still be written.
**Then verify that URL before the block goes anywhere.** Run `{CURRENT}/jsc-gitea/tools/link-check.sh {the URL just substituted}` and read the exit code by the rule B table above. Exit 0 is the only result that permits the upsert. On exit 1 the directory would gain a block pointing at a page that is not there: report the `DEAD` line verbatim, write no block, and treat the directory entry as not updated — the round's own result is already on `MONITOR_{HASH}`, so carry on to step 5 and write the heartbeat, exactly as exit 3 from the upsert does, and put the dead link into the 待人處理 rows. Exits 2, 3 and 7 are reported the same way and the block is left unwritten. Never write the block first and check afterwards: the directory is what other people read to find this machine, and a dead link there sends every one of them to a page that does not exist.
Then run, with the template as the fifth argument every time:
`{CURRENT}/jsc-gitea/tools/wiki-contents.sh upsert MONITOR 1 "MONITOR_{HASH}" {block file} {CURRENT}/jsc-assist/templates/monitor-contents.md`
**The key is the H2 heading — the page name `MONITOR_{HASH}`**, taken from `collect`'s `page=` line verbatim, with no link, no brackets and no URL around it. The script compares the heading text, so the 監控頁 bullet cannot be the key: it holds `GITEA_HOST` and the wiki's encoding of the page name, so a changed host, a `JSC_WIKI_REPO_MONITOR` pointed at another repo, or a different URL encoding changes that text and stops it matching. This page is written once every round, so from the moment matching breaks every round appends one more block for this same machine and the old block is never updated again. The page name depends on `{host}/{user}` alone, which none of those three touch. That bullet's link stays in the block for people to click, and never for matching. A key typed by hand matches nothing either, and appends the same duplicate block.
**The `1` is the third argument, `key-col`, and it only matters while an old page is still a table.** A directory page written in the previous format holds a markdown table, and the script converts the whole page to blocks before it upserts; `key-col` tells it which column of that table held the identity, counting from 1. Column 1 of this page's old table was the monitor-page link, whose cell is `[MONITOR_{HASH}]({URL})`, and the conversion takes the text out of it as the H2 heading. Once the page is in the block format the argument is ignored — pass `1` regardless, and never a column number worked out from the current page.
| Exit | Do |
| --- | --- |
| 0 | The block is in place. The script prints `updated` or `added` plus the page it wrote — carry that word into the report, and carry on to step 5 |
| 1 | The page content could not be built, or the write failed. Run `{CURRENT}/jsc-assist/tools/patrol.sh abort --round {round}`, report the code, and stop. A page with no matching block is not this code: an unmatched key is an append |
| 2 | An argument was rejected and nothing was written. A template path that does not exist lands here too, and means the plugin installation is incomplete. Correct the call and run it once more; report a second exit 2 as a defect in this skill, then abort and stop |
| 3 | No `CONTENTS` wiki repo is configured. **This one does not stop the round.** Carry on to step 5 and write the heartbeat: the round's result is already on `MONITOR_{HASH}`, and that is exactly what a heartbeat stands for. Report the directory entry as not updated, name `JSC_WIKI_REPO_CONTENTS` and `JSC_WIKI_REPO` as the two variables to set, and add that to the 待人處理 rows. Never abort a recorded round over the directory page — a missing directory block loses one index entry, an aborted round loses the whole round, and the patrol cannot ask anybody for the missing setting |
| 4 | The page is absent and no template reached the script. The call above always passes the template as its fifth argument, so this code cannot come out of it — getting it means that argument was dropped, so restore it and run the call once more. A template path that does not exist is rejected as exit 2, never as 4 |
| 7 | The token is invalid or lacks permission, so the other machines' blocks are unknown. The script wrote nothing, which is what keeps those blocks alive. Abort, report the key problem, and stop |
| 8 | Some other API failure. Abort, report the status, and stop |
Completion condition: `link-check.sh` exited 0 over the block's URL and the script exited 0 with exactly one `## MONITOR_{HASH}` block on the page carrying this round's values, or exit 3 from the upsert or a non-zero `link-check.sh` was reported as an unwritten directory entry and the round carried on, or one of the other non-zero codes — `wiki-url`'s included — was reported after the abort ran.
5. **Run the built-in check items that are due.** Run `{CURRENT}/jsc-assist/tools/run-due.sh run --root {CURRENT} --rows {the `due_rows_file=` step 1 printed}`. **That path is not optional and there is no default.** The judging step writes its output into the directory whoever called it chose, so a default would point somewhere else — and it did: the tool shipped with one, and every round read a file a person had left behind by running the judge by hand. That file sat on this machine for 67 hours while each round acted on it, one round even running an entry that had already been removed. Nothing looked wrong, because the stale list had been correct when it was written and its contents happened not to change. Passing the path makes each round say which round's data it is acting on; the tool also refuses a list older than the heartbeat TTL, because a list older than that cannot describe this round. This is the one step of the round that changes something outside the round's own files, and it is deliberately narrow: it runs only the entries whose `action` is a command and whose `spec_key` is set, so a reminder, a skill name and anything a person entered by hand are all left alone. Judge the exit code by the run-due.sh table, and keep every `done=`, `failed=`, `held=`, `skip=`, `write_failed=`, `target_ok=` and `target_fail=` line plus the summary counts for the report. **`cli_missing=` is the one to read carefully.** It names the CLIs the scheduled entry recorded at install time that this round could not detect, and it is the only place that gap shows: every target that was detected still ran, still passed, and the round still reports "all of them ran", because without that comparison nothing knows how many there should have been. One round reported four CLIs all passing on a machine with five installed. The usual cause is a CLI whose executable sits in a directory that expires — one here lives under a process-numbered multishell path — while the entry's `PATH` was snapshotted at install time. Report the named CLIs, say that a clean pass is not the same as a full pass, and name re-running the schedule install as what refreshes the snapshot. **No exit code from this step stops the round.** Exit 1 means an entry's command failed and that entry now carries one more failure — that is a finding, not a broken round; exit 4 means a write-back failed, so the same entry will run again next round, which is worth saying out loud; exit 2, 5 and 6 mean nothing ran, and the round still has a result to record. Completion condition: the exit code and the summary counts are recorded, and step 6 was reached whatever that code was.
6. **Write the heartbeat.** Run `{CURRENT}/jsc-assist/tools/patrol.sh finish --round {round}`. This is the last step for a reason: it is the only thing that turns a fresh heartbeat into a true statement. Judge the exit code by the patrol.sh table — 2, 4 and 5 all mean the round is recorded but unproven, and each has its own report line there. Completion condition: `finish` exited 0, or the failure was reported as "recorded but no heartbeat" with its code.
7. **Report the round.** Print the round verdict and, when it is `警示`, the `warn_sources=` text that says why — a round can read all five sources and still come out `警示`, and that column is the only place the reason appears; then one line per item with its `status=` and, for a failure, its `note=`; the monitor page name, the link-check verdict for each of the two writes — passed, skipped for a body with no link, or refused with its exit code and its `DEAD` lines — and the directory entry as `updated`, `added`, or not written with the exit code and the reason; whether the heartbeat was written; and, when `lock_broken=1`, that the previous round's lock was taken over because it had aged past the TTL.
**The event numbers get their own line, and the unpaired starts get their own list.** Print `events_total=` and `events_bad=` as this round's event count and its non-`ok` count, then every non-`ok` event with its `kind`, `name`, `status`, `exit` and `detail`, then — separately, never folded into the same list — every start with no matching end, by `name` and `session`. A non-zero `events_unpaired=` is the round's most important finding: each row is a skill run that started and never reached its closing step. Say `events_rotated=` too when it is `rotated` or `failed`. When `item=D-11` failed, say the source could not be read rather than reporting zero events — zero read events and zero existing events look identical in a report and mean opposite things.
**Then report step 5 in its own block**, because it is the only place the task book's own work is accounted for: how many entries were due, how many ran, how many came back clean and how many failed, then every `failed=` row by name with the first line of its command's output, every `held=` row with what could not be given a target, and every `write_failed=` row as an entry that ran without being recorded. Say plainly that a held entry's history was left untouched. Close with the 待人處理 rows from the latest-round block, verbatim, and nothing else — the patrol names an entry point and stops there. Completion condition: all five items appear in the report, the event count, the non-`ok` count and the unpaired starts are stated, the heartbeat outcome is stated as written or not written, and no suggestion in 待人處理 was acted on.
## status
Read-only throughout. This operation creates, modifies and deletes nothing under `$JSC_HOME`, and it never calls `write` or `clear`. It compares the built-in items against the delegation list with `seed-tasks.sh plan`, never with `apply`.
1. **Read the heartbeat through the script.** Run `{CURRENT}/jsc-hooks/hooks/heartbeat.sh report` and split the line on spaces, taking `file=` last so a path containing spaces stays intact. Map `state=` to the verdict: `fresh` → `新鮮`, `stale` → `過期`, `invalid` → `心跳檔損壞`, `absent` → `不存在`. Print `助理未運行` for `stale`, `invalid` and `absent`. Never re-derive the verdict from `ts` yourself, and never treat `invalid` as fresh. On exit 2 or 6, follow that code's row, record the heartbeat state as unknown, and carry on to step 2 — the task book is still worth printing. Completion condition: the heartbeat state holds one of `新鮮`, `過期`, `心跳檔損壞`, `不存在` or unknown, and `ts`, `age`, `ttl`, `pid`, `cli`, `session` and `file` are recorded as read or as empty.
2. **Read the task book.** Take the assistant directory from the `file=` path of step 1, list the regular files directly under its `tasks/` subdirectory, and parse each one as `key=value` lines. Branch on the outcome.
| Outcome | Do |
| --- | --- |
| Directory absent | Report zero entries. This is a normal result, not an error |
| Directory present, no files | Report zero entries |
| A file cannot be read, or holds no recognisable key | Keep it as one row, put the file name in the title column, name the read or parse error in that row, and carry on with the remaining files |
| A key is missing from a readable file | Print `-` in that column |
Completion condition: every file under `tasks/` produced exactly one row, or zero entries was reported.
3. **Read the schedule.** Run `{CURRENT}/jsc-assist/tools/schedule.sh status`. It writes nothing. Record `mechanism=`, `service=`, `ttl=`, `period=` and the `installed=` value of both jobs. A `heartbeat` job reported as installed is a leftover from an older version: say so, and say `start` or `schedule.sh install patrol` removes it. On exit 2, 3 or 6 nothing was read: record the schedule state as unknown with its code and carry on — the heartbeat and the task book still print. Completion condition: both jobs have an installed state, or the schedule state is recorded as unknown with its code.
4. **Print the status table.** Lead with the heartbeat block — verdict, last heartbeat time rendered from `ts` in local time, age in seconds, TTL, `cli`, `session`, `pid`, and the task count. Follow it with the schedule block — mechanism, service state, derived period, and one line per job saying installed or not. Then one row per task carrying `state`, `title`, `next_run` and `fail_count`, in the order the files were listed. Completion condition: the heartbeat block holds all eight values, the schedule block holds both jobs and the period, and the row count equals the task count from step 2.
5. **Say what the two blocks together mean.** Four combinations get an explicit sentence, because each one reads as something it is not:
| Heartbeat | Schedule | Say |
| --- | --- | --- |
| 新鮮 | patrol installed, service running | 上一輪巡檢跑完了,結果也記上監控頁了,排程還在跑。那一輪各項有沒有全過,要看監控頁的本輪判定 |
| 新鮮 | not installed, or service stopped | 上一輪巡檢跑完了,但沒有排程在叫下一輪,過了 TTL 心跳就會過期 |
| 過期 or 不存在 | patrol installed, service running | 排程裝著卻沒有新的心跳,巡檢自己跑失敗了,去看 `$JSC_HOME/assistant/schedule.log` 與監控頁的最新一輪 |
| any | `heartbeat` job installed | 舊版的心跳排程還留著,它會蓋掉「心跳等於巡檢跑完」這件事。請跑一次 `start`,或 `schedule.sh install patrol` 把它清掉 |
Completion condition: every matching sentence is printed, or none of the four combinations applied.
6. **Flag the repeatedly failing tasks.** Append 已連續失敗 N 次 to every row whose `fail_count` is above 0, with `N` taken verbatim from the file. A broken entry that retries every round with nobody noticing is the reason this field exists, so let no such row leave the table unmarked. Completion condition: every row with `fail_count` above 0 carries the marker and its number matches the file.
7. **Check the built-in items against the delegation list, read-only.** Run `{CURRENT}/jsc-assist/tools/seed-tasks.sh plan --root {CURRENT}`. `plan` writes nothing at all — it prints what a reconcile would do and stops — which is what makes it safe here, and `apply` must never be run from `status`. Judge the code by the seed-tasks.sh table and report the difference: the count of items the list expects but the task book lacks, the count of orphans the task book still holds, every `held=` row by name, every `drift=` row with the change the list asks for, every `pending=` row as a slice with an entry point still unwired — this is where a human finds out which reminders are waiting on plumbing rather than on them — and every `probe_bad=` row as an item that fell back to reminding. Say plainly that `start` is what applies any of it. On exit 1, 2 or 3 report that the comparison could not be made and why, and never present that as an aligned task book. Completion condition: the difference is reported with its counts and the held rows named, or the reason it could not be computed is reported, and nothing under `$JSC_HOME` was written.
8. **Finish successfully.** `助理未運行`, an absent `tasks/` directory, an empty `tasks/` directory and an uninstalled schedule are normal results — never exit non-zero for any of them. Reserve a failure report for a condition none of the tables above covers, and state which path and which error produced it. Completion condition: the report is printed and nothing under `$JSC_HOME` has been created, modified or deleted.
## stop
1. **Record what is being stopped.** Run `{CURRENT}/jsc-hooks/hooks/heartbeat.sh report` first and keep its `state=`, `ts=`, `pid=`, `cli=` and `file=` fields for the closing report — after the clear they are gone for good. `state=absent` means no round has finished; say so and still run steps 2 and 3, because a scheduled entry can outlive its heartbeat and `clear` on a missing file is a success, so running both leaves the outcome unambiguous. On exit 2 or 6, follow that code's row, record the previous state as unknown, and carry on to step 2. Completion condition: the previous state and its fields are recorded, or the previous state is recorded as unknown with its code.
2. **Remove the schedule first.** Run `{CURRENT}/jsc-assist/tools/schedule.sh remove all` — both job names, so the patrol entry and any leftover heartbeat entry from an older install both go. This comes before the clear and never after: clear first and the next scheduled round writes a fresh heartbeat over the stopped assistant, and every reader from then on is told a dead assistant is alive. Judge the result by the schedule.sh exit-code table, and keep `removed=` and `others_kept=` for the report. On any non-zero code the schedule is still installed: report the code, say plainly that rounds will keep running and the assistant therefore cannot be stopped, name the manual fix (`crontab -l` to look, then remove the line carrying `# jsc-assist:assistant` by hand), and skip steps 3 and 4 — clearing a heartbeat that the next round rewrites only hides the problem. Completion condition: `remove` exited 0 with its counts recorded, or the failure report has been printed and no stop was claimed.
3. **Clear the heartbeat.** Run `{CURRENT}/jsc-hooks/hooks/heartbeat.sh clear`. On exit 5 the file is still there: report the failure with the script's stderr line and the path, say plainly that every reader still sees a heartbeat claiming a round just finished and that the assistant is therefore not reliably stopped, name the manual fix (delete that path by hand, then run `status` to confirm `助理未運行`), and skip step 4 — the closing notice must not be printed after a failed clear. On exit 2 or 6, follow that code's row and stop the same way. Completion condition: `clear` exited 0, or the failure report naming the code, the path and the manual fix has been printed and no stop was claimed.
4. **Report the stop and what it means for the gate.** Print the previous state and heartbeat time from step 1 and the entries removed in step 2, then this literally:
> 助理已停止,排程移除了,心跳也清掉了,其他人的排程一筆都沒動。靠心跳判定的 jsc 技能閘門一讀到沒有心跳就會擋下技能呼叫;閘門目前還沒接線,所以這一刻誰都擋不到。要再工作就先跑一次 start。
Say it exactly this way. The blocking is the designed consequence of a cleared heartbeat, and whoever stops the assistant has to know it is coming; the clause about the gate being unwired is the part that keeps the notice honest while that is still true. When the gate is wired, that clause is what gets rewritten — not the rest. Completion condition: the notice appears with all three clauses, and the previous state, the heartbeat time and the removal counts are printed above it.
## Round lock and a round that will not stop leaving one behind
A patrol round holds `$JSC_HOME/assistant/patrol.lock` from `collect` to `finish` or `abort`, which spans the wiki writes — the slow part. Two consequences bind every branch above:
- **Every path out of a started round ends in `finish` or `abort`.** Steps 2, 3 and 4 of `patrol` each name their abort. A round that stops without either leaves the lock standing until it ages out, which stands the next rounds down for up to one TTL. There is no third option.
- **`stop` does not remove the lock.** It is not a state file that records work, but it is also not this skill's to delete while a round may still be using it; it ages out on its own within one TTL. If an operator reports that every round stands down, tell them the holder and age from the `lock=busy` line and let them decide — 界線 5 keeps destructive cleanup with the human.