forgedock 1.35.0 → 1.37.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 (129) hide show
  1. package/README.md +78 -324
  2. package/bin/bot-token-status.mjs +26 -0
  3. package/bin/engine/events.mjs +161 -0
  4. package/bin/engine/events.test.mjs +142 -0
  5. package/bin/engine/outcome-codes.mjs +39 -1
  6. package/bin/engine/phases.mjs +65 -5
  7. package/bin/engine/telemetry-seam.mjs +5 -4
  8. package/bin/engine/telemetry-seam.test.mjs +4 -0
  9. package/bin/engine-cli.mjs +372 -46
  10. package/bin/engine.mjs +3 -1
  11. package/bin/experiment.mjs +55 -0
  12. package/bin/forgedock.mjs +108 -5
  13. package/bin/hooks/reread-nudge.mjs +15 -4
  14. package/bin/labels.json +50 -0
  15. package/bin/lean/batch.mjs +52 -6
  16. package/bin/lean/batch.test.mjs +176 -2
  17. package/bin/lean/conformance.e2e.test.mjs +1 -1
  18. package/bin/lean/conformance.mjs +136 -11
  19. package/bin/lean/conformance.test.mjs +148 -1
  20. package/bin/lean/decisions.mjs +181 -0
  21. package/bin/lean/decisions.test.mjs +71 -0
  22. package/bin/lean/effects.mjs +32 -14
  23. package/bin/lean/execution.mjs +62 -16
  24. package/bin/lean/execution.test.mjs +59 -2
  25. package/bin/lean/gatewatch.mjs +31 -0
  26. package/bin/lean/gatewatch.test.mjs +59 -0
  27. package/bin/lean/guardgate.mjs +170 -0
  28. package/bin/lean/guardgate.test.mjs +153 -0
  29. package/bin/lean/guards.mjs +243 -0
  30. package/bin/lean/guards.test.mjs +177 -0
  31. package/bin/lean/heavy.mjs +54 -8
  32. package/bin/lean/heavy.test.mjs +74 -1
  33. package/bin/lean/hostkill.mjs +1 -1
  34. package/bin/lean/i18n.mjs +65 -0
  35. package/bin/lean/i18n.test.mjs +47 -0
  36. package/bin/lean/integration.mjs +276 -0
  37. package/bin/lean/integration.test.mjs +189 -0
  38. package/bin/lean/lane.mjs +5 -2
  39. package/bin/lean/lean.mjs +169 -30
  40. package/bin/lean/lean.test.mjs +360 -24
  41. package/bin/lean/lifecycle.mjs +129 -0
  42. package/bin/lean/lifecycle.test.mjs +118 -0
  43. package/bin/lean/light.mjs +1 -1
  44. package/bin/lean/milestonesync.mjs +130 -0
  45. package/bin/lean/milestonesync.test.mjs +133 -0
  46. package/bin/lean/orchestrate.mjs +132 -20
  47. package/bin/lean/parked-sweep.mjs +45 -0
  48. package/bin/lean/parked-sweep.test.mjs +71 -0
  49. package/bin/lean/postdeploy-check.mjs +181 -0
  50. package/bin/lean/postdeploy-check.test.mjs +206 -0
  51. package/bin/lean/postdeploy-monitor.mjs +97 -0
  52. package/bin/lean/postdeploy-monitor.test.mjs +147 -0
  53. package/bin/lean/precheck.mjs +6 -4
  54. package/bin/lean/precheck.test.mjs +17 -2
  55. package/bin/lean/prefilter.mjs +106 -21
  56. package/bin/lean/prefilter.test.mjs +86 -6
  57. package/bin/lean/probe.mjs +4 -3
  58. package/bin/lean/probe.test.mjs +1 -1
  59. package/bin/lean/prompts.mjs +23 -9
  60. package/bin/lean/resume.test.mjs +1 -1
  61. package/bin/lean/retry.mjs +28 -0
  62. package/bin/lean/sandbox-provider.contract.test.mjs +36 -3
  63. package/bin/lean/sandbox-remote.mjs +11 -4
  64. package/bin/lean/schedd.mjs +77 -13
  65. package/bin/lean/schedd.test.mjs +131 -5
  66. package/bin/lean/sequence.mjs +24 -0
  67. package/bin/lean/sequence.test.mjs +31 -1
  68. package/bin/lean/signoff.mjs +66 -0
  69. package/bin/lean/signoff.test.mjs +102 -0
  70. package/bin/lean/train.mjs +177 -0
  71. package/bin/lean/train.test.mjs +113 -0
  72. package/bin/pool/cli.mjs +2 -0
  73. package/bin/pool/health.mjs +30 -0
  74. package/bin/review-context.mjs +298 -0
  75. package/bin/runner.mjs +26 -3
  76. package/bin/stats/aggregate.mjs +1 -1
  77. package/bin/stats/compounding.mjs +157 -0
  78. package/bin/stats/compounding.test.mjs +74 -0
  79. package/bin/stats/experiment.mjs +44 -0
  80. package/bin/stats/github-source.mjs +2 -1
  81. package/bin/stats/index.mjs +62 -3
  82. package/bin/stats/release.mjs +75 -0
  83. package/bin/stats/release.test.mjs +68 -0
  84. package/commands/bootstrap.md +10 -8
  85. package/commands/deploy-info.md +3 -0
  86. package/commands/issue.md +2 -0
  87. package/commands/milestone.md +43 -54
  88. package/commands/orchestrate/phase-4-execution.md +2 -0
  89. package/commands/orchestrate.md +15 -3
  90. package/commands/pipeline-status.md +20 -0
  91. package/commands/review-pr.md +1 -0
  92. package/commands/work-on/build/implement.md +1 -1
  93. package/commands/work-on/build.md +4 -2
  94. package/commands/work-on/investigate.md +3 -1
  95. package/commands/work-on/remediate.md +1 -1
  96. package/docs/CONFIG.md +120 -2
  97. package/docs/EVENTS.md +65 -0
  98. package/docs/OUTCOME-CODES.md +9 -1
  99. package/docs/STATS.md +51 -0
  100. package/docs/TELEMETRY.md +3 -1
  101. package/docs/site/install.md +89 -0
  102. package/docs/site/start-a-new-project.md +1 -1
  103. package/docs/spec/label-state-machine.md +6 -0
  104. package/package.json +1 -1
  105. package/pool/install/install-agent.sh +4 -2
  106. package/pool/install/install-router.sh +4 -2
  107. package/pool/install/install-schedd.sh +28 -0
  108. package/pool/install/unit-hardening.sh +34 -0
  109. package/scripts/acceptance-red-green.sh +19 -2
  110. package/scripts/acceptance-red-green.test.sh +2 -0
  111. package/scripts/bench-lightlane.mjs +2 -1
  112. package/scripts/bootstrap-create.mjs +3 -2
  113. package/scripts/bootstrap-validate.mjs +31 -4
  114. package/scripts/eval-gate-scorecard.mjs +7 -0
  115. package/scripts/file-deferred-followups.sh +286 -77
  116. package/scripts/file-deferred-followups.test.sh +117 -2
  117. package/scripts/hotspots.sh +23 -2
  118. package/scripts/hotspots.test.sh +9 -0
  119. package/scripts/plan-validate-live.mjs +111 -0
  120. package/scripts/readiness.mjs +141 -0
  121. package/scripts/review-prepare.sh +17 -1
  122. package/scripts/review-prepare.test.sh +17 -0
  123. package/scripts/settle-scope.mjs +74 -0
  124. package/scripts/systemd/forgedock-bot-token-refresh.service +7 -0
  125. package/scripts/systemd/forgedock-bot-token-refresh.timer +11 -0
  126. package/scripts/wait-ci-green.sh +14 -3
  127. package/scripts/wait-ci-green.test.sh +3 -1
  128. package/templates/bootstrap/needs-human-issue.md +4 -1
  129. package/templates/github-actions/migration-journal-guard.test.mjs +26 -0
package/README.md CHANGED
@@ -4,382 +4,136 @@
4
4
 
5
5
  <h1>ForgeDock</h1>
6
6
 
7
- <p><strong>Point it at an issue and get a merged, reviewed PR; point it at a <strong>milestone</strong> and get parallel pipelines with conflict-aware scheduling.</strong></p>
7
+ <p><strong>From GitHub issues to reviewed, tested, merged changes, autonomously.</strong></p>
8
8
 
9
- <p>LLMs generate the code. ForgeDock owns everything else — <strong>state, scheduling, recovery, review, and memory</strong> — as durable, inspectable structure on the GitHub you already have. Issues are the queue. PRs are the ledger. Annotations are the memory. Deterministic orchestration for autonomous software engineering.</p>
10
-
11
- <p><em>ForgeDock (not ForgeRock) — this project is unrelated to ForgeRock's identity and access management platform.</em></p>
12
-
13
- <p>📖 <a href="https://rapiercraftstudios.github.io/ForgeDock/">Full documentation site</a></p>
9
+ <p>ForgeDock runs AI coding agents through validation, implementation, review, CI and merge, one issue per lane, many lanes in parallel. Every step is recorded on GitHub, so runs survive crashes, later agents build on earlier ones, and you can audit everything.</p>
14
10
 
15
11
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-AGPL--3.0-blue.svg" alt="License: AGPL-3.0" /></a>
16
- <a href="https://github.com/RapierCraftStudios/ForgeDock/stargazers"><img src="https://img.shields.io/github/stars/RapierCraftStudios/ForgeDock?style=social" alt="GitHub Stars" /></a>
17
- <a href="https://docs.anthropic.com/en/docs/claude-code"><img src="https://img.shields.io/badge/Built%20for-Claude%20Code-blueviolet" alt="Claude Code" /></a>
18
12
  <a href="https://www.npmjs.com/package/forgedock"><img src="https://img.shields.io/npm/v/forgedock?color=cb3837&logo=npm" alt="npm" /></a>
19
- <a href="https://www.npmjs.com/package/forgedock"><img src="https://img.shields.io/npm/dm/forgedock?color=cb3837&logo=npm&label=downloads" alt="npm downloads per month" /></a>
20
- <a href="https://github.com/RapierCraftStudios/ForgeDock/pulls"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome" /></a>
21
- <a href="https://github.com/sponsors/RapierCraftStudios"><img src="https://img.shields.io/badge/Sponsor-❤-ea4aaa.svg" alt="Sponsor" /></a>
22
-
23
- </div>
24
-
25
- <br />
26
-
27
- <div align="center">
28
-
29
- <img src="docs/demo.gif" alt="ForgeDock orchestrating multiple GitHub issues in parallel — agents investigate, build, review, and flip workflow labels through to merged" width="900" />
13
+ <a href="https://docs.anthropic.com/en/docs/claude-code"><img src="https://img.shields.io/badge/Built%20for-Claude%20Code-blueviolet" alt="Claude Code" /></a>
14
+ <a href="https://github.com/RapierCraftStudios/ForgeDock/stargazers"><img src="https://img.shields.io/github/stars/RapierCraftStudios/ForgeDock?style=social" alt="GitHub Stars" /></a>
30
15
 
31
- <p><em><strong>One <code>/orchestrate</code> runs a whole milestone.</strong> Agents pick up issues in parallel, drive each through investigate → build → review, and flip the GitHub labels to <code>merged</code> — live.</em></p>
16
+ <p>📖 <a href="https://rapiercraftstudios.github.io/ForgeDock/">Documentation</a> · <a href="#try-it-in-30-seconds">Try it</a> · <a href="#the-evidence">Evidence</a> · <a href="#what-works-today">What works today</a></p>
32
17
 
33
18
  </div>
34
19
 
35
- **This repository builds itself with ForgeDock.** In its first 30 days (June 4 → July 4, 2026): **693 issues filed, 605 closed, 603 PRs merged — median 56 minutes from open to merged-and-closed.** 57% of those issues were filed by the pipeline itself; 49% are findings its own review agents raised, filed, and then fixed. Every run leaves a public audit trail — [click through the receipts](#watch-the-machine-work), or count them yourself:
36
-
37
- ```bash
38
- gh issue list -R RapierCraftStudios/ForgeDock --state closed --limit 1000 --json number --jq 'length'
39
- ```
40
-
41
- **A single run, up close** — a real one, [issue #1230](https://github.com/RapierCraftStudios/ForgeDock/issues/1230):
42
-
43
- ```console
44
- $ /work-on #1230 "orchestrate: Layer 5 co-change signal is dead code"
45
-
46
- ✓ investigate CONFIRMED/HIGH — feature shipped 3h earlier (PR #1204) reads a
47
- never-populated variable; the co-change query can never fire
48
- ✓ build fix branch, 1 file
49
- ✓ review caught a defect in the fix itself: stray backticks in the grep
50
- meant every git-log pathspec silently matched zero commits —
51
- "the fix would not have actually worked." Corrected.
52
- ✓ merged 30m 37s → staging
53
-
54
- filed by the pipeline's own staging review. fixed before a human read it.
55
- ```
56
-
57
- ### Try it in 30 seconds — on a throwaway repo, nothing to lose
58
-
59
- **Requires for this demo:** [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (subscription or `ANTHROPIC_API_KEY`) · [GitHub CLI](https://cli.github.com/) (authenticated) · Node.js ≥ 18.
60
-
61
- ```bash
62
- npx forgedock demo # spins up a risk-free demo repo and shows you the pipeline end to end
63
- ```
64
-
65
- Ready to use it for real? **`npx forgedock`** walks you through one continuous setup: it checks your environment, installs the slash commands, reads your repo, and hands you a single annotated `forge.yaml` to review — you press Enter once.
66
-
67
- > ⭐ **If ForgeDock saves you time, [star the repo](https://github.com/RapierCraftStudios/ForgeDock/stargazers)** — it's the whole marketing budget.
68
-
69
- ---
70
-
71
- **Your AI coding agent forgets everything after every session.** It re-explores the codebase from scratch, re-makes mistakes that were already fixed, and has no idea why the code it's touching looks the way it does. ForgeDock fixes that by making **GitHub itself the memory** — every pipeline stage writes structured findings that every later agent reads.
72
-
73
- ## Without ForgeDock vs. With ForgeDock
74
-
75
- | Without ForgeDock | With ForgeDock |
76
- |---|---|
77
- | Agent starts every session blind — no context from prior work | Agent reads structured investigation, root cause, and history straight from GitHub |
78
- | The same bugs get reintroduced across PRs | Review agents surface known pitfalls from past PRs *before* you commit |
79
- | A crash or compaction loses the run | State lives on GitHub and in an event-sourced run log — the pipeline resumes where it stopped |
80
- | You write the issue, plan the fix, open the PR, and review it | `/work-on #42` → investigated, built, reviewed, merged |
81
- | Review depends on whoever has capacity | 9 domain-specialist agents (security, billing, DB, concurrency…) review every PR |
82
- | One task at a time, serialized by your attention | `/orchestrate` runs a whole milestone — many issues in parallel, each its own full pipeline |
83
-
84
- ---
85
-
86
- ## The idea in one paragraph
87
-
88
- AI agents have **no lookback**. They don't know a function was shaped by a bug fix in #347, that an approach was tried and reverted in PR #891, or that three other files need the same change. Context window isn't the bottleneck — **memory is.** But GitHub already stores everything an agent needs: commits, PRs, issues, blame, cross-references. It's a citation graph; agents just don't use it as one. ForgeDock makes every stage write **machine-readable annotations** to issues and PRs, and every downstream agent read them. The `gh` CLI becomes the query interface to institutional memory. The result: agents that follow structured data, not vibes.
89
-
90
- ```
91
- ┌──────────────────────────────────────────────────────────────────┐
92
- │ GITHUB (Knowledge Graph) │
93
- │ │
94
- │ Issues: FORGE:INVESTIGATOR → FORGE:CONTEXT → FORGE:ARCHITECT │
95
- │ → FORGE:TRAJECTORY (the run's full audit trail) │
96
- │ PRs: FORGE:BUILDER → structured review FINDING blocks │
97
- │ Links: git blame → commit → PR → issue → related issues │
98
- │ │
99
- │ Every agent reads this. Every agent writes to it. │
100
- │ Nothing is lost between conversations. │
101
- └──────────────────────────────────────────────────────────────────┘
102
- ```
103
-
104
- ---
105
-
106
- ## Watch the machine work
107
-
108
- Not a staged demo — these are real, public runs on this repository. Open any of them and read the full trail:
109
-
110
- - **[#1230](https://github.com/RapierCraftStudios/ForgeDock/issues/1230)** — the pipeline's staging review caught dead code in a feature the pipeline had shipped three hours earlier; review then caught a bug in the fix itself. Intent to merged: **30 minutes**.
111
- - **[#1172](https://github.com/RapierCraftStudios/ForgeDock/issues/1172)** — review found an `ANTHROPIC_API_KEY` exfiltration path in the headless runner (an in-process file read bypassed the env scrub), with exact line evidence. Fixed and merged in **18 minutes**, with regression tests. A later re-review found a second-order bypass of the first fix ([#1243](https://github.com/RapierCraftStudios/ForgeDock/issues/1243)) — the pipeline red-teams its own fixes.
112
- - **[#952](https://github.com/RapierCraftStudios/ForgeDock/issues/952)** — the investigator closed the pipeline's *own proposal* as INVALID with receipts: the deliverable had already shipped weeks earlier. Zero code written, 34 minutes, full explanation.
113
- - **[#1256](https://github.com/RapierCraftStudios/ForgeDock/issues/1256)** — decomposition that respects the existing graph: it created only the two net-new sub-issues no open issue already claimed, then sequenced three existing issues into the dependency order.
114
- - **[#1322](https://github.com/RapierCraftStudios/ForgeDock/issues/1322)** — a heavyweight feature (the durable execution engine itself): 9 TDD tasks, whole-branch review caught two Criticals pre-merge, merged in **under 2 hours**.
115
-
116
- And the part that makes it compound — the context phase citing past bugs *by number* before a line is written (from [#1196](https://github.com/RapierCraftStudios/ForgeDock/issues/1196)):
117
-
118
- > "`commands/orchestrate.md` has a dense review-finding history from PR #1081/#1107/#1126… associative-array declaration mistakes (#1113), array-element removal via pattern substitution corrupting partial matches (#1108)… the new Layer 5 subsection should not introduce a competing edge-direction convention that could reintroduce a cycle class."
119
-
120
- > Numbers on this page are point-in-time (2026-07-04), from this repository's first 30 days of dogfooding. A reproducible cost-per-issue benchmark is a hard gate on our own launch plan — [#1264](https://github.com/RapierCraftStudios/ForgeDock/issues/1264): no estimated efficiency claims.
121
-
122
- ---
123
-
124
- ## Orchestrate an entire milestone
125
-
126
- `/work-on` ships one issue. **`/orchestrate` ships a milestone.** It decomposes the milestone into dependency-ordered waves and runs a full `/work-on` pipeline on each issue **in parallel** — investigating, building, reviewing, and merging many at once, while GitHub labels track every agent's state live. On this repo's record day, that meant **29 issues taken to merged inside a single hour**.
127
-
128
- Scheduling is conflict-aware before it is parallel. Five detection layers decide what may run concurrently: same-file overlap, directory proximity, shared-module fan-in, a conservative fallback when file extraction is low-confidence, and **historical co-change coupling mined from `git log`** — files that changed together in the past are assumed to conflict now. Database-touching issues are always serialized. The resulting graph is cycle-checked (Kahn's algorithm) and executed in topologically sorted waves; overlapping work is expressed as ordinary `Depends on #N` edges anyone can read.
129
-
130
20
  <div align="center">
131
- <img src="assets/orchestration.svg" alt="One milestone fanned out into parallel work-on pipelines, each issue advancing through investigating, building, in-review, and merged" width="920" />
132
- </div>
133
21
 
134
- ```bash
135
- /orchestrate milestone/checkout-v2 # decompose → conflict-aware waves → merged PRs
136
- ```
22
+ <img src="docs/demo.gif" alt="ForgeDock running several GitHub issues in parallel: lanes validate, build, review and merge, flipping workflow labels live" width="900" />
137
23
 
138
- ---
24
+ </div>
139
25
 
140
- ## How it works
26
+ ## What it does
141
27
 
142
- Each stage reads the structured output of the stages before it and writes its own findings back:
28
+ You file issues. ForgeDock turns each one into a merged pull request:
143
29
 
144
30
  ```
145
- Issue → Investigate → Context → Architect → Build → Quality Gate → Review → Merge
146
- └──────────── each stage reads & writes GitHub ────────────┘
31
+ issue → validate → plan (frozen contract) → implement → review → PR → CI → merge
147
32
  ```
148
33
 
149
- | Stage | Reads | Writes |
150
- | --- | --- | --- |
151
- | **Investigate** | Issue body, `git blame`, related issues/PRs | `FORGE:INVESTIGATOR` — verdict, root cause, affected files, severity |
152
- | **Context** | Historical findings from related PRs, known pitfalls | `FORGE:CONTEXT` — institutional memory for this module |
153
- | **Architect** | Investigation + context | `FORGE:ARCHITECT` — ordered plan, code paths, risks |
154
- | **Build** | Everything above | `FORGE:BUILDER` — branch, commits, files changed |
155
- | **Quality Gate** | Builder output, domain-specific checks | gate results, recorded in the run's trajectory |
156
- | **Review** | PR diff, contract, gate results | `FORGE:REVIEW_STARTED` on the issue; per-agent findings as structured `FINDING` blocks on the PR |
157
- | **Close** | All of the above | `FORGE:TRAJECTORY` — the full audit trail of the run |
34
+ - **One lane per issue, many in parallel.** `forgedock orchestrate` schedules a batch from the issues' `Depends on #N` lines, runs up to K lanes at once, and recovers the mechanical failures itself (CI red, merge conflicts, engine errors). It asks you only about product, spend, credentials and releases.
35
+ - **Durable.** Each lane records its state on the issue and in a crash-safe run log. Kill it, restart it, or lose the session: it resumes from what GitHub says, and two lanes never own the same issue.
36
+ - **Checked, not trusted.** Each change is held to a contract frozen before implementation. It must pass a separate review (which blocks on unimplemented requirements and regressions) and CI. On paths you mark as risky, the full contract-conformance gate also blocks. Before anything reaches your default branch, a staging review with a panel of domain reviewers (security, concurrency, auth, CLI, regression risk…) must post a gate marker.
37
+ - **GitHub is the memory.** Findings, decisions and trajectories are written as structured comments that later lanes read. Nothing lives only in a chat window.
158
38
 
159
- **GitHub as the database.** Every annotation is wrapped in an HTML comment (`<!-- FORGE:INVESTIGATOR -->`) that makes it machine-parseable. When an agent starts — even in a brand-new conversation after compaction — it queries the issue via `gh` and reconstructs full context from these tags. Workflow labels (`workflow:investigating`, `workflow:in-review`, `workflow:merged`…) track state, and the pipeline resumes from whatever state GitHub reports. The annotation format is an open standard — see the [FORGE Annotation Protocol](docs/spec/forge-protocol-v1.md).
39
+ ForgeDock orchestrates delivery. It does not replace the model: it runs on your Claude Code account and resells no compute.
160
40
 
161
- **Durable by design.** Headless runs are backed by a real execution engine, not prompt-hope: every phase transition is appended to an event-sourced, crash-safe run log, mirrored to the issue as a compact `FORGE:STATE` index, and guarded by leases so two agents can never own the same issue. Kill the process mid-run and restart it — the engine reconciles local state against GitHub (GitHub wins), adopts branches and PRs that already exist instead of re-running the LLM, and escalates to `needs-human` after bounded retries instead of looping. Phase selection is a pure rule-based state machine: **the engine, not the model, decides what happens next.** The headless core shipped in [PR #1326](https://github.com/RapierCraftStudios/ForgeDock/pull/1326); wiring the interactive path onto the same engine is in progress ([#1323](https://github.com/RapierCraftStudios/ForgeDock/issues/1323)–[#1325](https://github.com/RapierCraftStudios/ForgeDock/issues/1325)).
41
+ ## Try it in 30 seconds
162
42
 
163
- **Domain-specialist review.** Every PR is reviewed by agents with deep, narrow expertise — Security, Auth & Access Control, Billing Integrity, Database, Concurrency, Frontend, API, Performance, Infrastructure. Findings carry a confidence level, and a **reproduction gate** keeps them honest: a finding only blocks if the reviewer traced an actual code path or input that triggers it — pattern-match suspicions are downgraded, not merged into noise. Findings above the severity threshold are **automatically filed as new issues** that enter the same pipeline: on this repo, that loop produced 49% of all issues ever filed.
164
-
165
- **It measures itself.** `/pipeline-health` correlates every prompt change against review-finding rates, build failures, and manual fix-up commits, then files its own report — including failing grades — as an issue. `/autopilot` pulls production signals (errors, CI failures, stale issues, analytics), files issues from them, and optionally runs `/work-on` on the top ones. The pipeline also invalidates its own bad ideas: proposals that turn out to be already-shipped or wrong are closed `workflow:invalid` with the reasoning attached ([example](https://github.com/RapierCraftStudios/ForgeDock/issues/952)).
166
-
167
- ---
168
-
169
- ## Built for the ways agents fail
170
-
171
- Every mechanism above exists because autonomous agents fail in predictable ways. The skeptics are right about the failure modes — the answer is structure, not optimism:
172
-
173
- | "We've all seen this go wrong…" | The mechanism |
174
- | --- | --- |
175
- | Parallel agents just turn typing time into *reading* time | Review is a pipeline stage: domain specialists with confidence ratings and a reproduction gate — not a pile of raw diffs |
176
- | Agents game their own checks (or delete the tests) | Builders never grade their own work — the quality gate and reviewers are separate agents reading the diff cold |
177
- | Third retry = increasingly creative excuses | Engine-owned state machine: bounded retries, then escalation to `needs-human` |
178
- | One runaway agent wrecks the codebase | 1 issue = 1 agent, bounded by decomposition; conflict-aware scheduling; isolated worktrees |
179
- | No institutional memory — "it can't read the Slack thread from 2023" | Every run writes citable annotations to GitHub; the context phase quotes past bugs by number |
180
- | No way to tell when an agent drifts | A `FORGE:TRAJECTORY` receipt on the issue records what every phase actually did |
181
- | Humans rubber-stamp 95%-good output | Specialist review raises the floor *before* a human looks at the PR |
182
- | The economics are opaque | ForgeDock runs on your existing Claude account — it resells no compute and takes no per-task cut. Cost-per-issue benchmarks are tracked in the open ([#1264](https://github.com/RapierCraftStudios/ForgeDock/issues/1264)) |
183
-
184
- ---
185
-
186
- ## Commands
187
-
188
- **The core loop:**
189
-
190
- | Command | What it does |
191
- | --- | --- |
192
- | **`/work-on`** | Full issue lifecycle: investigate → build → quality gate → review → merge |
193
- | `/orchestrate` | A whole milestone in parallel — conflict-aware waves, one pipeline per issue |
194
- | `/issue` | Creates pipeline-ready GitHub issues |
195
- | `/milestone` | Create, manage, and ship milestones |
196
- | `/review-pr` | Context-aware PR review with domain-specialist agents |
197
- | `/quality-gate` | Pre-commit checks, gated by the domains your change actually touches |
198
- | `/test-gate` | Acceptance verification against running code before anything deploys |
199
-
200
- **Observe & recover** — the durable-state story, as commands:
201
-
202
- | Command | What it does |
203
- | --- | --- |
204
- | `/pipeline-status` | Fleet view of every in-flight issue, straight from workflow labels |
205
- | `/pipeline-resume` | Resume an interrupted run from whatever state GitHub reports |
206
- | `/diagnose` | Trace why a run failed, from its annotations |
207
- | `/explain` | Translate the FORGE annotations on any issue into plain language |
208
- | `/replay` | Replay a past run's full audit trail |
209
- | `/changelog` | Release notes assembled from merged PRs and trajectory receipts |
210
-
211
- **Ops:**
212
-
213
- | Command | What it does |
214
- | --- | --- |
215
- | `/deploy-info` | Staging vs. main diff with risk assessment |
216
- | `/rollback` | Automated revert PR for production incidents |
217
- | `/autopilot` | Production signals → triaged issues → fixes |
218
- | `/security-audit` | Multi-phase security posture audit |
219
- | `/cleanup` | Sweeps stale issues, branches, worktrees |
220
-
221
- More ship today (web-property analytics, browser QA sweeps, self-benchmarking) — see the [full command reference](docs/site/command-reference.md). A leaner, tiered install that keeps the core loop front and center is planned in [#1257](https://github.com/RapierCraftStudios/ForgeDock/issues/1257).
222
-
223
- ---
224
-
225
- ## Install
226
-
227
- **Requirements:** [Claude Code](https://docs.anthropic.com/en/docs/claude-code) or [OpenCode](https://opencode.ai/) · [GitHub CLI](https://cli.github.com/) (authenticated) · Node.js ≥ 18.
43
+ **Needs:** [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (subscription or `ANTHROPIC_API_KEY`) · [GitHub CLI](https://cli.github.com/) (authenticated) · Node.js ≥ 18.
228
44
 
229
45
  ```bash
230
- npx forgedock # checks your environment, installs commands into ~/.claude/commands/ (available in every Claude Code session on this machine), detects your repo, and hands you a reviewed forge.yaml
46
+ npx forgedock demo # creates a throwaway repo and runs the pipeline end to end
231
47
  ```
232
48
 
233
- For OpenCode, install namespaced native commands without changing your provider
234
- or user-owned settings. When migrating an older ForgeDock adapter, it removes
235
- only exact ForgeDock-managed legacy entries from `opencode.json`:
49
+ To use it on your own repo:
236
50
 
237
51
  ```bash
238
- npx forgedock opencode install
239
- # restart OpenCode, then: /forge/work-on <issue>
52
+ npm install -g forgedock # the CLI and the durable engine
53
+ forgedock # checks your environment, installs the commands, writes a forge.yaml for you to review
54
+ forgedock run-issue 42 # one issue, start to merge
55
+ forgedock orchestrate 41 42 43 --parallel 3 # a batch, scheduled from its Depends-on lines
240
56
  ```
241
57
 
242
- See [OpenCode support](docs/OPENCODE.md) for architecture, token-loading rules,
243
- current parity boundaries, and lifecycle commands.
244
-
245
- **Install is always global**, to `~/.claude/commands/`. `--global` is still accepted on the command line for backward compatibility but has no effect — there's no other install location to opt out of.
246
-
247
- > **Want engine-mode dispatch?** `npx forgedock` is transient — the `forgedock` binary isn't persisted in PATH after install. `/orchestrate` and `/autopilot` use agent dispatch mode by default, which is fully functional. To enable engine-mode dispatch (`forgedock run-issue`) with its durable phase table and fail-closed review gate, run `npm install -g forgedock` instead.
248
-
249
- One command does everything: it checks your environment, installs the slash commands into Claude Code, detects your repo (owner, branches, paths), and hands you a single annotated `forge.yaml` to review — press Enter to accept. Run `npx forgedock init` any time afterward to re-generate the config only.
250
-
251
- Installing also registers a SessionStart hook, so every Claude Code session
252
- in a forge-managed directory starts already knowing ForgeDock runs it.
253
- Per-directory control: `npx forgedock enable` / `disable` / `status`.
254
-
255
- Then just open Claude Code and run `/work-on <issue>`.
256
-
257
- > **Cost:** ForgeDock is free and open-source. It orchestrates sessions on **your** Claude account — no compute resold, no per-task markup. A typical `/work-on` run on a straightforward bug costs about what a 15–20 minute manual Claude Code session does.
258
-
259
- <details>
260
- <summary><strong>Other install options & commands</strong></summary>
261
-
262
- **Claude Code plugin marketplace** (Claude Code v2.1.143+):
263
-
264
- ```
265
- /plugin marketplace add RapierCraftStudios/ForgeDock
266
- /plugin install forgedock@forgedock
267
- ```
58
+ Inside Claude Code the same flows are `/work-on 42` and `/orchestrate`. All install options (plugin marketplace, OpenCode, headless/CI) are in [Install](docs/site/install.md).
268
59
 
269
- Commands then appear as `/forgedock:work-on`, etc. You still run `npx forgedock init` to generate `forge.yaml`.
60
+ ## The evidence
270
61
 
271
- **Headless / CI:** the pipeline also runs outside Claude Code. `npx forgedock run work-on <issue> --dry-run` previews the assembled prompt and tool plan. `npx forgedock run` picks an execution backend automatically (`--backend auto`, the default): if the Claude Code CLI (`claude`) is installed and already authenticated (Pro/Max subscription or a CLI-managed key), it drives the command through that — **no separate `ANTHROPIC_API_KEY` required**. It never falls back to the paid Anthropic API implicitly: without a CLI it fails with `CLI_BACKEND_UNAVAILABLE` unless the owner opted in (forge.yaml `execution.agent_backend: api` plus `FORGEDOCK_ALLOW_API_BACKEND=1`; see [CONFIG.md](docs/CONFIG.md#execution-optional)). Force either path explicitly with `--backend cli` / `--backend api` (or `FORGEDOCK_BACKEND=cli|api`) — the API backend is what CI environments without an interactive `claude` login should use. `npx forgedock run-issue <issue>` executes the same command specs on the durable engine (event-sourced run log, leases, crash-safe resume).
62
+ **ForgeDock is built with ForgeDock.** Every number below is from this repository's public history and you can recount it.
272
63
 
273
- **Brand-new project?** `/bootstrap "<idea>"` (or `npx forgedock bootstrap "<idea>" --dry-run` to preview) turns an idea into a validated, milestone-ordered GitHub backlog that `/orchestrate` can build. See [Start a New Project with ForgeDock](docs/site/start-a-new-project.md).
274
-
275
- **Explicit install command:**
276
-
277
- ```bash
278
- npx forgedock install # installs into ~/.claude/commands/
279
- npx forgedock install --global # same thing — --global is accepted but is a no-op
280
- ```
281
-
282
- **Maintenance:**
64
+ | Last 30 days (2026-09-24 → 2026-10-23) | |
65
+ |---|---|
66
+ | Issues filed / closed | 800 / 784 |
67
+ | Pull requests merged | 613 |
68
+ | Issues that are the pipeline's own review findings | 396 (about half) |
69
+ | Issue opened → merged and closed, median | 2 h 19 min (p25 55 min, p75 10 h; 475 issues) |
70
+ | **Since 2026-06-04:** PRs merged / releases | 1,961 / 85 |
283
71
 
284
72
  ```bash
285
- npx forgedock update # relink commands + refresh the SessionStart hook
286
- npx forgedock enable # turn ForgeDock on for this directory
287
- npx forgedock disable # turn ForgeDock off for this directory
288
- npx forgedock status # show ForgeDock's state for this directory
289
- npx forgedock doctor # installation health check with fix hints
290
- npx forgedock report # 30-day pipeline impact receipts (--md for Markdown, --json for scripting)
291
- npx forgedock uninstall # remove commands, the hook, and tracked copies
292
- npx forgedock help # show everything
73
+ gh api -X GET search/issues -f q="repo:RapierCraftStudios/ForgeDock is:pr is:merged merged:2026-09-24..2026-10-23" --jq .total_count
293
74
  ```
294
75
 
295
- > Running `npx forgedock` from *inside* this repo uses the local working tree. From your own project, use `npx forgedock@latest` to pin the published release.
296
-
297
- </details>
76
+ **Runs you can open and read end to end:**
298
77
 
299
- <details>
300
- <summary><strong>A note on install location</strong></summary>
301
-
302
- ForgeDock briefly experimented with a project-scoped-by-default install mode. It was backed out after causing a "split-brain" bug (`detect` assumed project-scoped while the installer still wrote globally — [#1589](https://github.com/RapierCraftStudios/ForgeDock/issues/1589)), so every version you'd realistically install today only ever writes to `~/.claude/commands/`. `--global` is still accepted as a flag for old scripts/muscle memory, but it changes nothing.
303
-
304
- If you're carrying an older `--global` habit in scripts or CI, it's harmless to leave it — `npx forgedock --global` and `npx forgedock` do exactly the same thing.
305
-
306
- </details>
307
-
308
- **After upgrading**: run `npx forgedock labels setup` once per repo. Repos created before the `workflow:remediating` state (forge#3541) lack that label; the pipeline now creates it on demand (best-effort), but the setup command is the supported way to sync all labels.
309
-
310
- ---
311
-
312
- ## For companies
78
+ - [#1230](https://github.com/RapierCraftStudios/ForgeDock/issues/1230): the staging review found dead code in a feature shipped three hours earlier, then review caught a bug in the fix itself. 30 minutes from issue to merge.
79
+ - [#1172](https://github.com/RapierCraftStudios/ForgeDock/issues/1172): review found an `ANTHROPIC_API_KEY` exfiltration path in the headless runner; fixed in 18 minutes with regression tests. A later review found a bypass of that fix ([#1243](https://github.com/RapierCraftStudios/ForgeDock/issues/1243)).
80
+ - [#952](https://github.com/RapierCraftStudios/ForgeDock/issues/952): the pipeline closed its own proposal as invalid, with receipts: the work had shipped weeks earlier. No code written.
81
+ - [#4442](https://github.com/RapierCraftStudios/ForgeDock/issues/4442): a large feature split into six dependent sub-issues ([#4448](https://github.com/RapierCraftStudios/ForgeDock/issues/4448)–[#4453](https://github.com/RapierCraftStudios/ForgeDock/issues/4453)) that the batch runner built in dependency order.
313
82
 
314
- The core is AGPL-3.0 and stays that way: engineers run the full pipeline on their own Claude account, forever free.
83
+ ### What the gates caught
315
84
 
316
- Two things are for sale:
85
+ The staging review runs before every release. The releases of 2026-10-22 and 2026-10-23 alone stopped these defects before they shipped. Each was found by a reviewer, filed, fixed by a lane and re-verified:
317
86
 
318
- - **A [commercial license](COMMERCIAL-LICENSE.md)** — for organizations that need ForgeDock inside proprietary workflows or products without AGPL copyleft obligations. Contact [support@rapiercraftstudios.com](mailto:support@rapiercraftstudios.com).
319
- - **The fleet layer** *(in development)* — org-wide observability over every pipeline run: the receipts on this page, live, across all your repos, plus policy controls and audit-grade provenance for autonomous merges. We're onboarding a small group of design partners — see [ForgeDock for Companies](docs/site/for-companies.md) for details and intake.
320
-
321
- ---
322
-
323
- ## Where it's going
324
-
325
- Month one built the execution layer. The open roadmap — tracked in the [five-foundations epic (#1320)](https://github.com/RapierCraftStudios/ForgeDock/issues/1320) — is about earning trust while unattended:
87
+ | Caught | What would have shipped |
88
+ |---|---|
89
+ | [#4465](https://github.com/RapierCraftStudios/ForgeDock/issues/4465) (HIGH) | Merge-conflict resolution silently dropped a lane's edits to any file named like `404-page.tsx`, then skipped tests and re-review |
90
+ | [#4468](https://github.com/RapierCraftStudios/ForgeDock/issues/4468) (HIGH) | The acceptance probe could run a command quoted inside a bot-authored issue on the operator's host |
91
+ | [#4470](https://github.com/RapierCraftStudios/ForgeDock/issues/4470) | The open-findings release gate passed when every GitHub read failed |
92
+ | [#4501](https://github.com/RapierCraftStudios/ForgeDock/pull/4501) (HIGH) | Issues reopened after a merge (e.g. by a failed production probe) were skipped forever |
93
+ | [#4516](https://github.com/RapierCraftStudios/ForgeDock/pull/4516) | A dependency-parser fix turned prose like "see #99" into blocking edges |
326
94
 
327
- 1. **Durability** — engine-owned state instead of prose-owned state. Headless core shipped ([PR #1326](https://github.com/RapierCraftStudios/ForgeDock/pull/1326)); interactive wiring in progress.
328
- 2. **Verification** — an outcome-based acceptance gate and a graded eval corpus, so "done" is machine-checkable before anything claims success. Per-release pipeline scorecards are published in [`docs/eval/`](docs/eval/README.md); model upgrades follow the [model-release playbook](docs/articles/model-release-playbook.md).
329
- 3. **Learning** — per-codebase memory that compounds across runs.
330
- 4. **Economics** — per-run cost accounting and risk×cost dispatch decisions.
331
- 5. **Provenance** — signed, replayable records of every autonomous change.
95
+ ### What still goes wrong
332
96
 
333
- Marketing is held to the same standard: [#1264](https://github.com/RapierCraftStudios/ForgeDock/issues/1264) gates our own launch on measured cost-per-issue benchmarks — no estimated claims.
97
+ Lanes fail. What matters is how they fail. A lane that cannot finish ends with a typed outcome (`ci.red`, `base.conflict`, `budget.exceeded`, `needs-human`…). Mechanical ones are retried automatically, and the rest wait for a person with the evidence attached. Bugs are tracked in public, for example a lane whose checkpoint push was rejected ([#4505](https://github.com/RapierCraftStudios/ForgeDock/issues/4505)) and a dependency-line regex that backtracked on long whitespace ([#4517](https://github.com/RapierCraftStudios/ForgeDock/issues/4517)), both since fixed. Outcome codes are documented in [OUTCOME-CODES](docs/OUTCOME-CODES.md).
334
98
 
335
- ---
99
+ ## How it works
336
100
 
337
- ## Show your support
101
+ **A lane** takes one issue through a fixed sequence. The engine, not the model, decides the next step:
338
102
 
339
- Using ForgeDock in your pipeline? Add the badge — each one is a backlink and a signal to other developers:
103
+ 1. **Validate:** is the issue real and still open work? Already fixed or invalid issues are closed with evidence and no code.
104
+ 2. **Plan:** the builder proposes requirements, and the engine freezes them as a contract.
105
+ 3. **Implement:** one builder session in an isolated worktree, which checks itself with the repo's own commands.
106
+ 4. **Review:** a separate reviewer checks the diff against the contract and looks for regressions. Fix rounds run in a fresh, narrow session.
107
+ 5. **PR, CI, merge:** the lane waits for the required checks, syncs with the base branch if it moved, and merges. Deferred items become tracked follow-up issues instead of silent gaps.
340
108
 
341
- ```markdown
342
- [![Built with ForgeDock](https://raw.githubusercontent.com/RapierCraftStudios/ForgeDock/main/assets/built-with-forgedock.svg)](https://github.com/RapierCraftStudios/ForgeDock)
343
- ```
109
+ **A batch** (`forgedock orchestrate`) is a scheduler over lanes. It reads `Depends on #N` edges, keeps K lanes busy, shares slots across repos on the host, holds admissions when an account hits its usage limit, and survives restarts: lanes are detached processes and a daemon re-adopts them.
344
110
 
345
- [![Built with ForgeDock](assets/built-with-forgedock.svg)](https://github.com/RapierCraftStudios/ForgeDock)
111
+ **A release** promotes staging to your default branch only after the staging review posts a `FORGE:GATE_PASS` marker that CI checks.
346
112
 
347
- ---
113
+ Deeper: [How it works](docs/site/how-it-works.md) · [GitHub is your agents' memory](docs/site/github-is-the-memory.md) · [FORGE annotation protocol](docs/spec/forge-protocol-v1.md) · [Architecture](docs/site/architecture.md)
348
114
 
349
- ## Star History
115
+ ## What works today
350
116
 
351
- <div align="center">
352
-
353
- <a href="https://star-history.com/#RapierCraftStudios/ForgeDock&Date">
354
- <picture>
355
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=RapierCraftStudios/ForgeDock&type=Date&theme=dark" />
356
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=RapierCraftStudios/ForgeDock&type=Date" width="600" />
357
- </picture>
358
- </a>
117
+ | | Status |
118
+ |---|---|
119
+ | Runtime | Claude Code (CLI or subscription). OpenCode is supported with [documented parity limits](docs/OPENCODE.md). |
120
+ | Forge | GitHub only (issues, PRs, labels, Actions). |
121
+ | Branching | Lanes merge into a staging branch (or `milestone/*`); a reviewed release promotes staging to the default branch. |
122
+ | Runtime test gate | Runs your configured integration tests before a release; it reports SKIP until you configure `verification.integration_tests`. |
123
+ | Light lane (one-session mode for small issues) | Ships in `shadow` mode: it records what it would do. The gaps found before enabling it ([#4502](https://github.com/RapierCraftStudios/ForgeDock/issues/4502)) are closed; `light.mode: on` is opt-in. |
124
+ | Human decisions | Product direction, spend, credentials, customer-facing actions and releases are always escalated, never decided by an agent. |
125
+ | Cost | Runs on your Claude account. `forgedock stats --efficiency` reports $/merge, turns/merge and retries by cause. |
359
126
 
360
- </div>
127
+ ## Docs
361
128
 
362
- ---
129
+ - [Getting started](docs/site/getting-started.md) · [Install](docs/site/install.md) · [Configuration](docs/CONFIG.md) · [Command reference](docs/site/command-reference.md)
130
+ - [Troubleshooting & recovery](docs/site/troubleshooting.md) · [Outcome codes](docs/OUTCOME-CODES.md) · [Stats](docs/STATS.md)
131
+ - [Start a new project](docs/site/start-a-new-project.md) · [Comparison with other approaches](docs/comparison.md) · [Release eval scorecards](docs/eval/README.md)
363
132
 
364
- ## Docs & community
133
+ ## For companies
365
134
 
366
- - [GitHub Is Already Your Agents' Memory](docs/site/github-is-the-memory.md) — the canonical argument: why GitHub is the right place for agent memory, how FORGE annotations make it machine-readable, and how to adopt the protocol without ForgeDock
367
- - [Getting Started in 5 Minutes](docs/site/getting-started.md)
368
- - [Start a New Project with ForgeDock](docs/site/start-a-new-project.md) — idea → `/bootstrap` → backlog → `/orchestrate`, with a worked example
369
- - [How the Knowledge Graph Works](docs/site/how-it-works.md)
370
- - [What Are Those FORGE Comments?](docs/site/annotations-explained.md) — 2-minute explainer for annotations you meet in the wild
371
- - [FORGE Annotation Protocol](docs/spec/forge-protocol-v1.md) — the open standard for AI context passing (CC-BY-4.0)
372
- - [ForgeDock vs. Manual Claude Code Workflows](docs/site/vs-manual-workflows.md)
373
- - [ForgeDock vs. DeepWiki, AGENTS.md, and Cursor Memories](docs/comparison.md)
374
- - [Command Learning Path](docs/site/command-learning-path.md) — which commands to learn first
375
- - [Complete Command Reference](docs/site/command-reference.md)
376
- - [Troubleshooting & Recovery](docs/site/troubleshooting.md)
377
- - [Pipeline Eval Scorecards](docs/eval/README.md) — per-release published results for every model/Claude Code upgrade
378
- - [Model-Release Upgrade Playbook](docs/articles/model-release-playbook.md) — how to validate a new model before adopting it
135
+ The core is AGPL-3.0 and stays that way. A [commercial license](COMMERCIAL-LICENSE.md) is available for proprietary use, and an org-wide fleet layer is in development with design partners. See [ForgeDock for companies](docs/site/for-companies.md) or write to [support@rapiercraftstudios.com](mailto:support@rapiercraftstudios.com).
379
136
 
380
- **Contributing:** PRs welcome — every change goes through a PR, tested against 3+ scenarios, using conventional commits (`fix(command):`, `feat(command):`). **License:** [AGPL-3.0](LICENSE) — free to use, modify, and distribute; network use of modifications must be open-sourced under the same license. Commercial licenses are available for proprietary use — see [COMMERCIAL-LICENSE.md](COMMERCIAL-LICENSE.md).
137
+ **Contributing:** PRs welcome, with conventional commits (`fix(scope):`, `feat(scope):`). **License:** [AGPL-3.0](LICENSE).
381
138
 
382
- <div align="center">
383
- <br />
384
- <p>Built and dogfooded in production by <a href="https://github.com/RapierCraftStudios">RapierCraft Studios</a>.</p>
385
- </div>
139
+ <sub>ForgeDock is unrelated to ForgeRock's identity platform. Using it? <a href="https://github.com/RapierCraftStudios/ForgeDock/stargazers">A star</a> is the whole marketing budget.</sub>
@@ -0,0 +1,26 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /** #4662: bot token lifetime from the stamp scripts/refresh-bot-token.sh writes (~/.forge/bot-token.json). Pure; `doctor` renders it. */
4
+ import { readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { homedir } from "node:os";
7
+
8
+ export const MIN_REMAINING_MS = 10 * 60 * 1000;
9
+ export const MAX_AGE_MS = 50 * 60 * 1000;
10
+
11
+ export const stampPath = (env = process.env) => join(env.FORGE_HOME_DIR || join(homedir(), ".forge"), "bot-token.json");
12
+
13
+ /** @returns {{configured:boolean, ok:boolean, remainingMs?:number, ageMs?:number, refreshedAt?:string, reason?:string}} */
14
+ export function botTokenStatus({ now = Date.now(), env = process.env, read = (p) => readFileSync(p, "utf8") } = {}) {
15
+ let raw;
16
+ try { raw = read(stampPath(env)); } catch { return { configured: false, ok: true }; }
17
+ let s;
18
+ try { s = JSON.parse(raw); } catch { return { configured: true, ok: false, reason: "bot-token.json is not valid JSON" }; }
19
+ const refreshed = Date.parse(s?.refreshedAt), expires = Date.parse(s?.expiresAt);
20
+ if (!Number.isFinite(refreshed) || !Number.isFinite(expires)) return { configured: true, ok: false, reason: "bot-token.json has no refreshedAt/expiresAt" };
21
+ const remainingMs = expires - now, ageMs = now - refreshed;
22
+ const out = { configured: true, remainingMs, ageMs, refreshedAt: s.refreshedAt };
23
+ if (remainingMs < MIN_REMAINING_MS) return { ...out, ok: false, reason: remainingMs <= 0 ? "token expired" : "less than 10 min of token lifetime remain" };
24
+ if (ageMs > MAX_AGE_MS) return { ...out, ok: false, reason: "no refresh in the last 50 min" };
25
+ return { ...out, ok: true };
26
+ }