@greenrenge/skills 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/bin/cli.mjs +525 -0
  4. package/bin/lib/onboard.mjs +1168 -0
  5. package/bin/lib/probe.mjs +631 -0
  6. package/catalog.json +590 -0
  7. package/package.json +50 -4
  8. package/skills/deck-story/SKILL.md +258 -0
  9. package/skills/deck-story/check-svg-text.mjs +94 -0
  10. package/skills/deck-story/check.mjs +348 -0
  11. package/skills/diagram-router/LICENSE +21 -0
  12. package/skills/diagram-router/SKILL.md +193 -0
  13. package/skills/diagram-router/THIRD_PARTY_NOTICES.md +15 -0
  14. package/skills/diagram-router/references/channels.md +213 -0
  15. package/skills/diagram-router/references/evals.md +85 -0
  16. package/skills/diagram-router/references/gathering.md +101 -0
  17. package/skills/diagram-router/references/prior-art.md +65 -0
  18. package/skills/diagram-router/references/routing.md +166 -0
  19. package/skills/diagram-router/skill-release.json +17 -0
  20. package/skills/frontend-design/SKILL.md +443 -0
  21. package/skills/frontend-design/references/rtl.md +72 -0
  22. package/skills/frontend-design/scripts/.upstream-sha +1 -0
  23. package/skills/frontend-design/scripts/LICENSE +21 -0
  24. package/skills/frontend-design/scripts/README.md +24 -0
  25. package/skills/frontend-design/scripts/gates.md +243 -0
  26. package/skills/frontend-design/scripts/sloplint-render.mjs +1283 -0
  27. package/skills/frontend-design/scripts/sloplint.mjs +4426 -0
  28. package/skills/open-code-review-rules/SKILL.md +59 -0
  29. package/skills/open-code-review-rules/references/ocr-allowlists.json +161 -0
  30. package/skills/open-code-review-rules/references/ocr-rule-semantics.md +39 -0
  31. package/skills/open-code-review-rules/scripts/verify_ocr_rules.py +836 -0
  32. package/skills/plain-english-mode/SKILL.md +41 -0
  33. package/skills/pr-diagram-portfolio/SKILL.md +75 -0
  34. package/skills/pr-diagram-portfolio/references/angle-framework.md +124 -0
  35. package/skills/pr-diagram-portfolio/references/portfolio-delivery.md +79 -0
  36. package/skills/pr-diagram-portfolio/scripts/restore_still_css.py +180 -0
  37. package/skills/pr-lens/LICENSE-upstream +21 -0
  38. package/skills/pr-lens/SKILL.md +99 -0
  39. package/skills/pr-lens/VENDOR.md +47 -0
  40. package/skills/pr-lens/package-lock.json +91 -0
  41. package/skills/pr-lens/package.json +9 -0
  42. package/skills/pr-lens/references/config.md +90 -0
  43. package/skills/pr-lens/references/example.graph.json +580 -0
  44. package/skills/pr-lens/references/graph-document.md +233 -0
  45. package/skills/pr-lens/skill-release.json +16 -0
  46. package/skills/security-remediation-epic/SKILL.md +316 -0
  47. package/skills/security-remediation-epic/prompt-template.md +33 -0
  48. package/skills/skill-maintainer/SKILL.md +99 -0
  49. package/skills/skill-maintainer/references/placement-and-coupling.md +43 -0
  50. package/skills/skill-maintainer/scripts/audit_skills.py +297 -0
  51. package/skills/t3-successor-handoff/SKILL.md +141 -0
  52. package/skills/t3-thread-bridge/SKILL.md +175 -0
  53. package/skills/t3-thread-bridge/references/launch-recipes.md +123 -0
  54. package/skills/t3-thread-bridge/references/ping-back.md +108 -0
  55. package/skills/t3-thread-bridge/scripts/thread_ledger.py +203 -0
  56. package/skills/t3-ticket-orchestrator/SKILL.md +304 -0
  57. package/skills/t3-ticket-orchestrator/references/proving-the-gates.md +63 -0
  58. package/skills/ticket-scheme/SKILL.md +144 -0
  59. package/skills/ulw-plan/SKILL.md +98 -0
  60. package/skills/ulw-plan/references/full-workflow.md +255 -0
  61. package/skills/ulw-plan/references/intent-clear.md +44 -0
  62. package/skills/ulw-plan/references/intent-unclear.md +44 -0
  63. package/skills/ulw-plan/scripts/plan-templates.mjs +180 -0
  64. package/skills/ulw-plan/scripts/scaffold-plan.mjs +187 -0
@@ -0,0 +1,175 @@
1
+ ---
2
+ name: t3-thread-bridge
3
+ description: Launch, track, and collect work from T3 Code threads. Use when starting a long or independent piece of work in a background thread (research, a build, a verification run), when a thread was launched and its result has not come back, or when a thread finished but nothing was delivered. Covers the delegatedFrom link, the ping-back contract that makes a thread wake its parent, the thread ledger, and how to recover a silent completion.
4
+ ---
5
+
6
+ # T3 Thread Bridge
7
+
8
+ A T3 thread is a **top-level thread of its own**. It is not a subagent: it does not
9
+ inherit your context, it is not bound to your turn, and — unless you wire it — it
10
+ cannot tell you when it is done.
11
+
12
+ This skill is the wiring. Read it before launching a thread, and use the ledger
13
+ afterwards.
14
+
15
+ ## When to use
16
+
17
+ Use a thread when the work is **long, independent, and worth its own history**:
18
+ research that needs many searches, a build that takes minutes, an evidence run, a
19
+ second pair of eyes on a review.
20
+
21
+ Use a **native subagent** instead when the work finishes inside your turn and needs
22
+ no separate history. Use a thread only when the user asked for one, or when the work
23
+ would otherwise be long enough that you would otherwise be tempted to poll.
24
+
25
+ ## The launch contract
26
+
27
+ Five steps. Steps 2 and 3 are the ones that get forgotten; they are also the two that
28
+ make the difference between a thread that reports back and one that goes quiet.
29
+
30
+ **1. Launch with `delegatedFrom`.**
31
+
32
+ ```js
33
+ t3_thread_launch({
34
+ title: "<short title>",
35
+ scratch: true, // or workspaceStrategy for a repo checkout
36
+ runtimeMode: "full-access", // "auto" when the thread only reads
37
+ delegatedFrom: {
38
+ environmentId: "<env id>",
39
+ threadId: "<your thread id>",
40
+ title: "<your thread title>",
41
+ },
42
+ message: "<the task prompt — see step 2>",
43
+ })
44
+ ```
45
+
46
+ `delegatedFrom` is an official field of the official `t3_thread_launch`. Pass it:
47
+ it costs nothing, it records the intent, and it is how other launch paths
48
+ (`create_threads`) express delegation.
49
+
50
+ **But know what it does today on this bridge: nothing observable.**
51
+ Verified 2026-11-06 — a thread launched *with* `delegatedFrom` still reports
52
+ `parentThreadId: null` and `relationshipToParent: null`, exactly like one
53
+ launched without it. (Provider-native subagent threads *do* carry
54
+ `parentThreadId` and `relationshipToParent: "subagent"`; MCP-launched threads do
55
+ not.) So it is **not** what makes the ping work, and no step below may depend on
56
+ it.
57
+
58
+ What actually makes the ping work is **step 2**: the parent's thread id and the
59
+ instruction to use it travel in the brief. A child can also *discover* the parent
60
+ id on its own — the launching message item carries `senderThreadId` — but
61
+ discovery is not instruction: the child must be told to ping.
62
+
63
+ **2. Put the ping-back block in the child's first prompt.** The child cannot know
64
+ your thread id unless you give it. Copy this block verbatim and fill the three
65
+ placeholders:
66
+
67
+ ```
68
+ PING-BACK — required at the end of your work.
69
+
70
+ Call exactly this, once, when your deliverable is complete:
71
+
72
+ t3_thread_send({
73
+ threadId: "<parent thread id>",
74
+ environmentId: "<parent environment id>",
75
+ message: "<one-paragraph digest: what you did, what changed, the deliverable path, anything you could not finish>"
76
+ })
77
+
78
+ Then stop. Do not wait for a reply. If you are blocked, send the same message with
79
+ the blocker named — a blocked ping is still a ping.
80
+ ```
81
+
82
+ **3. Register the thread in the ledger** (so a silent thread is *findable* later):
83
+
84
+ ```bash
85
+ python3 ~/.agents/skills/t3-thread-bridge/scripts/thread_ledger.py register \
86
+ --thread-id "<threadId>" --link "<t3-thread://…>" --purpose "<one line>"
87
+ ```
88
+
89
+ **4. End your turn.** Do not block on the thread and do not poll it. Report the
90
+ thread link to the user and stop; the ping wakes you.
91
+
92
+ **5. Collect and acknowledge.** When the ping arrives, read the deliverable, then
93
+ mark the thread as acknowledged:
94
+
95
+ ```bash
96
+ python3 ~/.agents/skills/t3-thread-bridge/scripts/thread_ledger.py ack \
97
+ --thread-id "<threadId>" --summary "<one line: what came back>"
98
+ ```
99
+
100
+ ## The ledger
101
+
102
+ State lives in `~/.local/state/t3-thread-bridge/ledger.jsonl` (one JSON object per
103
+ thread; `ack` appends a second record rather than rewriting the first).
104
+
105
+ | Command | What it does |
106
+ |---|---|
107
+ | `register --thread-id --link --purpose` | Record a launched thread |
108
+ | `ack --thread-id --summary` | Record that the result was collected |
109
+ | `list` | Every tracked thread with age and ack state |
110
+ | `check` | Threads that were registered but never acknowledged — exit 1 if any |
111
+
112
+ `check` is the one to run when you suspect something went quiet. It is cheap, and
113
+ it turns "did that thread ever finish?" into one command instead of a hunt through
114
+ thread lists.
115
+
116
+ ## Collecting results
117
+
118
+ ```js
119
+ t3_thread_read({ threadId: "<threadId>", view: "messages", limit: 6, maxCharsPerItem: 3000 })
120
+ ```
121
+
122
+ The read returns the thread's recent messages and run history — enough to see
123
+ whether it finished, failed, or is still running. For the substance, read the
124
+ deliverable file the ping pointed at; that is the context-cheap path, and it is why
125
+ the ping must carry a path.
126
+
127
+ If a thread's work matters but the deliverable is long, instruct it to write a note
128
+ to a file and ping with the path. Never ask a thread to summarize a 900-line
129
+ document into a chat message; ask it to write the file and name it.
130
+
131
+ ## When a thread goes quiet
132
+
133
+ 1. `python3 ~/.agents/skills/t3-thread-bridge/scripts/thread_ledger.py check`
134
+ 2. `t3_thread_read` the thread — it may have finished and simply not pinged (an
135
+ older prompt, a model that dropped the instruction, a crash before the ping).
136
+ 3. `t3_thread_list({ statuses: ["running","completed","failed"], limit: 10 })` to see
137
+ the real status.
138
+ 4. Read the deliverable and acknowledge it. Do **not** relaunch the same task in a
139
+ new thread while the old one may still be running — cancel or stop the old one
140
+ first (`t3_thread_interrupt`).
141
+
142
+ ## Threads that own services
143
+
144
+ The host rule applies to threads exactly as it applies to you: **anything a thread
145
+ starts, that thread ends.** If the task may leave a container, a dev server, a
146
+ tailscale door, a Cloudflare door (`cf-serve`), or a port open, the launch
147
+ prompt must say so:
148
+
149
+ > When your work is done, tear down what you started — name the exact resources
150
+ > (compose project, container names, ports, registry entries) and use the
151
+ > `docker-teardown` / `cleanup-published-app-tailscale` /
152
+ > `cleanup-published-app-cloudflare` (`cf-serve teardown`) skills. If you are
153
+ > handing off instead, say explicitly who now owns them.
154
+
155
+ ## Tool cheat-sheet
156
+
157
+ | Tool | Use it for | Key arguments |
158
+ |---|---|---|
159
+ | `t3_thread_launch` | starting the work | `title`, `message`, `scratch` or `workspaceStrategy`, `runtimeMode`, `delegatedFrom` |
160
+ | `t3_thread_send` | the ping back, and steering a running thread | `threadId`, `message`, `mode: "auto" \| "queue" \| "steer" \| "restart"` |
161
+ | `t3_thread_read` | reading a thread's messages and run status | `threadId`, `view: "messages" \| "activity"`, `limit`, `maxCharsPerItem` |
162
+ | `t3_thread_list` | finding threads by title or status | `titleContains`, `statuses`, `allProjects` |
163
+ | `t3_thread_interrupt` | stopping a thread you no longer need | `threadId`, `reason`, `stop` |
164
+
165
+ The `t3_thread_send` call from a child to its parent is the whole ping mechanism:
166
+ the message arrives in the parent thread as an inbound message and wakes it. That
167
+ path is **verified on this host** — see `references/ping-back.md` for the transcript
168
+ and the exact identifiers.
169
+
170
+ ## References
171
+
172
+ - `references/ping-back.md` — the verified ping-back transcript, identifiers, and
173
+ what happens with and without `delegatedFrom`.
174
+ - `references/launch-recipes.md` — copy-paste prompts for the three common thread
175
+ shapes: research, build, verification.
@@ -0,0 +1,123 @@
1
+ # Launch recipes
2
+
3
+ Three shapes cover most cases. Each is a complete first prompt — copy it, replace
4
+ the placeholders, and append the ping-back block from `SKILL.md`.
5
+
6
+ Placeholders:
7
+
8
+ - `<parent-thread-id>` — your thread id (`t3_thread_list` → `currentThreadId`)
9
+ - `<parent-environment-id>` — this host's environment id
10
+ - `<deliverable-path>` — the file the child writes; the ping names this path
11
+
12
+ ---
13
+
14
+ ## 1. Research
15
+
16
+ The child searches, reads, and writes a note. Give it the question, the evidence
17
+ standard, and the file it must write. Nothing else.
18
+
19
+ ```
20
+ TASK: Research <question>. Produce a decision-grade note at <deliverable-path>.
21
+
22
+ Evidence standard: cite a URL for every claim. Where sources disagree, say so.
23
+ Where you cannot find evidence, write "no evidence found" rather than guessing.
24
+ Read the local files you need (paths listed below) as first-party evidence and
25
+ mark them as such.
26
+
27
+ Deliverable: <deliverable-path> — one markdown file with: the findings, the
28
+ sources, the contradictions, and a short recommendation. Then reply with a
29
+ ≤400-word digest.
30
+
31
+ Do not implement anything. Do not modify files outside <write-scope>.
32
+
33
+ Local context you may read:
34
+ - <path>
35
+
36
+ PING-BACK — required at the end of your work.
37
+
38
+ t3_thread_send({
39
+ threadId: "<parent-thread-id>",
40
+ environmentId: "<parent-environment-id>",
41
+ message: "RESEARCH DONE — <one-paragraph digest: what you found, the deliverable path, anything you could not answer>"
42
+ })
43
+
44
+ Then stop. Do not wait for a reply.
45
+ ```
46
+
47
+ ---
48
+
49
+ ## 2. Build
50
+
51
+ The child writes code. Be explicit about where it may write, what it may not
52
+ touch, and what "done" means — a thread's summary is not verified by the parent
53
+ otherwise.
54
+
55
+ ```
56
+ TASK: <what to build> in <repo path>.
57
+
58
+ Write only inside <write-scope>. Do not commit, push, or open a PR — leave the
59
+ working tree for the parent to review.
60
+
61
+ Definition of done: <the concrete check that proves it works — a command that
62
+ must pass, a file that must exist>. Run it and paste its output into your final
63
+ message. If it fails, say so; do not report success you did not observe.
64
+
65
+ Deliverable: <deliverable-path> (notes, screenshots, or a short report).
66
+
67
+ PING-BACK — required at the end of your work.
68
+
69
+ t3_thread_send({
70
+ threadId: "<parent-thread-id>",
71
+ environmentId: "<parent-environment-id>",
72
+ message: "BUILD DONE — <digest: what you built, where, the verification output, what is left>"
73
+ })
74
+
75
+ Then stop. Do not wait for a reply.
76
+ ```
77
+
78
+ ---
79
+
80
+ ## 3. Verification / evidence
81
+
82
+ The child proves a claim by running something. Insist on verbatim output — a
83
+ summary of a run is not evidence.
84
+
85
+ ```
86
+ TASK: Prove that <claim> by running it for real on this host.
87
+
88
+ Rules:
89
+ - Real execution only. No proxy, no mock, no "should work".
90
+ - Capture verbatim output; assert against values read from the code, not from
91
+ memory.
92
+ - Measure latency and memory if the claim is about performance.
93
+ - If the claim cannot be proven, say so plainly and explain what blocked it.
94
+
95
+ Write the full transcript to <deliverable-path>.
96
+
97
+ Teardown: when you are done, stop everything you started — name each container,
98
+ port, or process you opened and stop it. If you cannot stop something, say which.
99
+
100
+ PING-BACK — required at the end of your work.
101
+
102
+ t3_thread_send({
103
+ threadId: "<parent-thread-id>",
104
+ environmentId: "<parent-environment-id>",
105
+ message: "EVIDENCE DONE — <digest: what you ran, the result, the transcript path, what you started and stopped>"
106
+ })
107
+
108
+ Then stop. Do not wait for a reply.
109
+ ```
110
+
111
+ ---
112
+
113
+ ## Scratch vs a real checkout
114
+
115
+ - `scratch: true` — research, throwaway analysis, anything with no repo writes.
116
+ - `workspaceStrategy: { type: "root" }` — the project's checkout (the default).
117
+ - `workspaceStrategy: { type: "worktree", baseRef: "<ref>" }` — an isolated
118
+ checkout of a branch, so the thread's commits cannot disturb the working tree.
119
+ - `workspaceStrategy: { type: "existing_worktree", worktreePath: "<path>" }` —
120
+ bind a worktree you already created.
121
+
122
+ A thread with `scratch: true` cannot read the project's files unless it is told
123
+ the absolute paths.
@@ -0,0 +1,108 @@
1
+ # Ping-back — verified on this host
2
+
3
+ The mechanism, with the evidence, so nobody has to re-derive it.
4
+
5
+ ## The one-line version
6
+
7
+ A child thread wakes its parent by sending it a message with `t3_thread_send`.
8
+ The parent needs the child's thread id **and** the child needs the parent's thread
9
+ id. The parent supplies the second half with `delegatedFrom` at launch.
10
+
11
+ ## The identifiers
12
+
13
+ On a T3 Code host, a thread's link has the shape:
14
+
15
+ ```
16
+ <t3-thread://v2/<environmentId>/<threadId>>
17
+ ```
18
+
19
+ - **environment id** — `41ac89c4-3c5b-47dd-af5f-81640a6bbb36` (the shared prefix
20
+ in every thread link on this machine)
21
+ - **thread id** — the segment after the environment id, e.g.
22
+ `1daba399-ad15-4752-ad47-163749fb856e` for a user-started thread,
23
+ `mcp:<uuid>` for a thread launched through the MCP bridge
24
+ - **your own thread id** — `t3_thread_list({ allProjects: true })` reports it as
25
+ `currentThreadId`; your own link is in the thread list too
26
+
27
+ ## What happens without `delegatedFrom`
28
+
29
+ The launch returns normally and the thread runs. The child has no idea a parent
30
+ exists, so it finishes, posts its summary to its own conversation, and stops. The
31
+ parent's `t3_thread_list` shows the child as `completed` — but nothing wakes the
32
+ parent, and the parent only learns of it by looking.
33
+
34
+ **Observed:** a research thread launched without `delegatedFrom` ran five
35
+ consecutive runs (13:47 → 14:09), completed, and produced a 108 KB deliverable.
36
+ Its metadata read `parentThreadId: null`, `relationshipToParent: null`. It never
37
+ pinged, and the parent did not learn about it until the user said so.
38
+
39
+ ## What `delegatedFrom` actually does (probed, not assumed)
40
+
41
+ A dedicated probe thread was launched *with* `delegatedFrom` and asked to report
42
+ what its own context contains. The answer, confirmed from the parent side as
43
+ well:
44
+
45
+ | Field | With `delegatedFrom` | Without |
46
+ |---|---|---|
47
+ | `parentThreadId` | **null** | null |
48
+ | `relationshipToParent` | **null** | null |
49
+ | parent id visible to the child | only through the brief's ping block, or through the launching message's `senderThreadId` | same |
50
+
51
+ **Conclusion:** on this MCP bridge, `delegatedFrom` does not populate the parent
52
+ linkage for launched threads. Provider-native subagent threads *do* carry it
53
+ (`parentThreadId` set, `relationshipToParent: "subagent"`), so the platform
54
+ knows how to model the relation — the MCP launch path just does not fill it in.
55
+
56
+ So the rule is:
57
+
58
+ - **Pass `delegatedFrom`** — it is official, free, and documents the intent.
59
+ - **Do not rely on it.** The ping depends on the brief carrying the parent's
60
+ thread id and the instruction to use it. The child can *discover* the parent id
61
+ (`senderThreadId` on the launching message item), but discovery is not
62
+ instruction.
63
+
64
+ ## What happens with the ping block
65
+
66
+ The child is told, in its first prompt, to call:
67
+
68
+ ```
69
+ t3_thread_send({
70
+ threadId: "<parent thread id>",
71
+ environmentId: "<parent environment id>",
72
+ message: "<digest>"
73
+ })
74
+ ```
75
+
76
+ **Observed:** the same research thread, told to exercise the contract, sent:
77
+
78
+ > PING-BACK OK — research thread mcp:473a9072-e3ab-4058-b669-a614ef61ec25 finished.
79
+ > Deliverable: <scratch-dir>/pr598/skill-research.md (859 lines). Top
80
+ > finding: the three installed diagram skills already collide in trigger space —
81
+ > "architecture" is claimed by all three — so a fourth broad skill needs explicit
82
+ > de-confliction.
83
+
84
+ The message arrived in the parent thread as an inbound message and woke the
85
+ parent. That is the whole ping mechanism.
86
+
87
+ ## Rules that follow
88
+
89
+ 1. `delegatedFrom` at launch, always. It is the only thing that puts the parent's
90
+ identity in the child's context.
91
+ 2. The ping block goes in the **first** prompt. A later message may arrive too
92
+ late, or after the child has already produced its final answer.
93
+ 3. The digest names a **file path**, not the content. A thread that answers with
94
+ 900 lines of prose has spent the parent's context for nothing.
95
+ 4. A blocked thread pings too. "I could not do X because Y" is a result.
96
+ 5. One ping per thread. Not a stream of updates — the parent reads the thread when
97
+ it wakes.
98
+ 6. The parent registers the thread in the ledger *before* ending its turn, so a
99
+ silent thread is one command away from being found.
100
+
101
+ ## Modes that matter on `t3_thread_send`
102
+
103
+ - `auto` — deliver now; start a run in the target if it is idle. **This is the
104
+ ping mode.**
105
+ - `queue` — deliver after the current run finishes. For steering a busy thread
106
+ without interrupting it.
107
+ - `steer` — inject into the running turn. For changing direction mid-run.
108
+ - `restart` — discard the pending run and start fresh with the new message.
@@ -0,0 +1,203 @@
1
+ #!/usr/bin/env python3
2
+ """Ledger of T3 threads launched from this host.
3
+
4
+ Tracks every thread launched through the t3-thread-bridge skill so a silent
5
+ completion is findable instead of a hunt through thread lists.
6
+
7
+ State: ~/.local/state/t3-thread-bridge/ledger.jsonl (append-only; one JSON
8
+ object per line).
9
+
10
+ Usage:
11
+ thread_ledger.py register --thread-id ID [--link URL] [--purpose TEXT]
12
+ [--parent ID] [--note TEXT]
13
+ thread_ledger.py ack --thread-id ID [--summary TEXT]
14
+ thread_ledger.py list [--json]
15
+ thread_ledger.py check [--json] # exit 1 if any thread is unacknowledged
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import os
22
+ import pathlib
23
+ import sys
24
+ import time
25
+
26
+ STATE_DIR = pathlib.Path(
27
+ os.environ.get("XDG_STATE_HOME", pathlib.Path.home() / ".local" / "state")
28
+ ) / "t3-thread-bridge"
29
+ LEDGER = STATE_DIR / "ledger.jsonl"
30
+
31
+
32
+ def now() -> float:
33
+ return time.time()
34
+
35
+
36
+ def read_records() -> list[dict]:
37
+ if not LEDGER.exists():
38
+ return []
39
+ out = []
40
+ for line in LEDGER.read_text(encoding="utf-8").splitlines():
41
+ line = line.strip()
42
+ if not line:
43
+ continue
44
+ try:
45
+ out.append(json.loads(line))
46
+ except json.JSONDecodeError:
47
+ continue # a torn line never breaks the ledger
48
+ return out
49
+
50
+
51
+ def append(record: dict) -> None:
52
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
53
+ with LEDGER.open("a", encoding="utf-8") as handle:
54
+ handle.write(json.dumps(record, ensure_ascii=False) + "\n")
55
+
56
+
57
+ def age(ts: float) -> str:
58
+ delta = max(0, int(now() - ts))
59
+ if delta < 90:
60
+ return f"{delta}s"
61
+ if delta < 5400:
62
+ return f"{delta // 60}m"
63
+ if delta < 172800:
64
+ return f"{delta // 3600}h"
65
+ return f"{delta // 86400}d"
66
+
67
+
68
+ def threads() -> list[dict]:
69
+ """Fold the append-only records into one row per thread."""
70
+ rows: dict[str, dict] = {}
71
+ for record in read_records():
72
+ tid = record.get("thread_id")
73
+ if not tid:
74
+ continue
75
+ row = rows.setdefault(
76
+ tid,
77
+ {
78
+ "thread_id": tid,
79
+ "link": record.get("link", ""),
80
+ "purpose": record.get("purpose", ""),
81
+ "parent": record.get("parent", ""),
82
+ "registered_at": record.get("ts"),
83
+ "acked_at": None,
84
+ "summary": "",
85
+ },
86
+ )
87
+ if record.get("kind") == "register":
88
+ row["link"] = record.get("link", row["link"])
89
+ row["purpose"] = record.get("purpose", row["purpose"])
90
+ row["parent"] = record.get("parent", row["parent"])
91
+ row["registered_at"] = record.get("ts", row["registered_at"])
92
+ elif record.get("kind") == "ack":
93
+ row["acked_at"] = record.get("ts")
94
+ row["summary"] = record.get("summary", "")
95
+ return sorted(rows.values(), key=lambda r: r["registered_at"] or 0)
96
+
97
+
98
+ def cmd_register(args: argparse.Namespace) -> int:
99
+ append(
100
+ {
101
+ "kind": "register",
102
+ "thread_id": args.thread_id,
103
+ "link": args.link or "",
104
+ "purpose": args.purpose or "",
105
+ "parent": args.parent or "",
106
+ "note": args.note or "",
107
+ "ts": now(),
108
+ }
109
+ )
110
+ print(f"registered {args.thread_id}")
111
+ if args.link:
112
+ print(f" {args.link}")
113
+ return 0
114
+
115
+
116
+ def cmd_ack(args: argparse.Namespace) -> int:
117
+ if not any(t["thread_id"] == args.thread_id for t in threads()):
118
+ print(
119
+ f"warning: {args.thread_id} was not in the ledger; recording the ack anyway",
120
+ file=sys.stderr,
121
+ )
122
+ append(
123
+ {
124
+ "kind": "ack",
125
+ "thread_id": args.thread_id,
126
+ "summary": args.summary or "",
127
+ "ts": now(),
128
+ }
129
+ )
130
+ print(f"acknowledged {args.thread_id}")
131
+ return 0
132
+
133
+
134
+ def cmd_list(args: argparse.Namespace) -> int:
135
+ rows = threads()
136
+ if args.json:
137
+ print(json.dumps(rows, indent=2, ensure_ascii=False))
138
+ return 0
139
+ if not rows:
140
+ print("ledger is empty — no threads tracked")
141
+ return 0
142
+ print(f"{'THREAD ID':<42} {'AGE':>5} {'STATE':<9} PURPOSE")
143
+ for row in rows:
144
+ state = "acked" if row["acked_at"] else "UNACKED"
145
+ print(
146
+ f"{row['thread_id']:<42} {age(row['registered_at'] or 0):>5} {state:<9} {row['purpose']}"
147
+ )
148
+ unacked = [r for r in rows if not r["acked_at"]]
149
+ if unacked:
150
+ print(f"\n{len(unacked)} thread(s) never acknowledged — run `check` for the recovery steps.")
151
+ return 0
152
+
153
+
154
+ def cmd_check(args: argparse.Namespace) -> int:
155
+ unacked = [r for r in threads() if not r["acked_at"]]
156
+ if args.json:
157
+ print(json.dumps(unacked, indent=2, ensure_ascii=False))
158
+ else:
159
+ if not unacked:
160
+ print("every tracked thread has been acknowledged")
161
+ else:
162
+ for row in unacked:
163
+ print(f"UNACKED {row['thread_id']} ({age(row['registered_at'] or 0)} old) {row['purpose']}")
164
+ if row["link"]:
165
+ print(f" {row['link']}")
166
+ print(
167
+ "\nrecovery: t3_thread_read the thread; if it finished, read its deliverable and\n"
168
+ "ack it. Do not relaunch the same task while the old thread may still be running."
169
+ )
170
+ return 1 if unacked else 0
171
+
172
+
173
+ def main() -> int:
174
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
175
+ sub = parser.add_subparsers(dest="command", required=True)
176
+
177
+ reg = sub.add_parser("register", help="record a launched thread")
178
+ reg.add_argument("--thread-id", required=True)
179
+ reg.add_argument("--link", default="")
180
+ reg.add_argument("--purpose", default="")
181
+ reg.add_argument("--parent", default="")
182
+ reg.add_argument("--note", default="")
183
+ reg.set_defaults(func=cmd_register)
184
+
185
+ ack = sub.add_parser("ack", help="record that a thread's result was collected")
186
+ ack.add_argument("--thread-id", required=True)
187
+ ack.add_argument("--summary", default="")
188
+ ack.set_defaults(func=cmd_ack)
189
+
190
+ lst = sub.add_parser("list", help="show every tracked thread")
191
+ lst.add_argument("--json", action="store_true")
192
+ lst.set_defaults(func=cmd_list)
193
+
194
+ chk = sub.add_parser("check", help="exit 1 if any thread is unacknowledged")
195
+ chk.add_argument("--json", action="store_true")
196
+ chk.set_defaults(func=cmd_check)
197
+
198
+ args = parser.parse_args()
199
+ return args.func(args)
200
+
201
+
202
+ if __name__ == "__main__":
203
+ sys.exit(main())