opencode-agent-harness 0.0.0-stage → 0.3.14

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 (171) hide show
  1. package/CHANGELOG.md +217 -0
  2. package/LICENSE +21 -0
  3. package/README.md +636 -2
  4. package/bin/agent-harness.js +3182 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +86 -4
  8. package/templates/.agents/AGENTS.md +148 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1924 -0
  100. package/templates/scripts/board-service.sh +214 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +416 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +323 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +499 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +434 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +288 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +187 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/check-worktrees.js +93 -0
  124. package/templates/scripts/qa/ci-triage.js +346 -0
  125. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  126. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  127. package/templates/scripts/qa/command-classifier.js +552 -0
  128. package/templates/scripts/qa/context-guard-core.js +1618 -0
  129. package/templates/scripts/qa/diff.js +174 -0
  130. package/templates/scripts/qa/feature-scaffold.js +224 -0
  131. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  132. package/templates/scripts/qa/governance.js +174 -0
  133. package/templates/scripts/qa/hash-file.js +32 -0
  134. package/templates/scripts/qa/lease-lib.js +263 -0
  135. package/templates/scripts/qa/merge-backlog.js +324 -0
  136. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  137. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  138. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  139. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  140. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  141. package/templates/scripts/qa/mobile-e2e/check-flows.js +568 -0
  142. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  143. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  144. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  146. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  147. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  148. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  149. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  150. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  151. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  152. package/templates/scripts/qa/models.allowlist.txt +32 -0
  153. package/templates/scripts/qa/provider-stats.js +878 -0
  154. package/templates/scripts/qa/run-clean.js +83 -0
  155. package/templates/scripts/qa/run-gates.js +213 -0
  156. package/templates/scripts/qa/run-loop.js +220 -0
  157. package/templates/scripts/qa/session-recon.js +512 -0
  158. package/templates/scripts/qa/store-lib.js +324 -0
  159. package/templates/scripts/qa/tool-lib.js +134 -0
  160. package/templates/scripts/qa/where.js +214 -0
  161. package/templates/scripts/qa/worktree-hygiene.js +217 -0
  162. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  163. package/templates/scripts/serve.js +1328 -0
  164. package/templates/scripts/setup-nightly.sh +185 -0
  165. package/templates/scripts/setup-tmpfs.sh +374 -0
  166. package/templates/scripts/ship.js +586 -0
  167. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  168. package/templates/scripts/switch-reasoning-model.sh +104 -0
  169. package/templates/scripts/wait-for.js +342 -0
  170. package/templates/scripts/wsl-gpu.sh +180 -0
  171. package/templates/scripts/wsl-tune.sh +319 -0
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env bash
2
+ # board-service.sh — start/stop the shared external board service (ADR 0001).
3
+ #
4
+ # The board service is a single, shared Next.js + Prisma app that lives in the
5
+ # harness repo (`services/board/`), not in any project. This script manages its
6
+ # lifecycle and the connection config the clients read.
7
+ #
8
+ # board-service.sh up start it (idempotent); prints the URL
9
+ # board-service.sh down stop it
10
+ # board-service.sh status running? + health probe
11
+ # board-service.sh env print the client env exports
12
+ # board-service.sh install persist: systemd --user unit (+ bashrc fallback)
13
+ # board-service.sh uninstall stop + remove the unit
14
+ #
15
+ # Config resolution (first found wins):
16
+ # - $BOARD_SERVICE_DIR explicit service directory
17
+ # - $AGENT_HARNESS_HOME/services/board
18
+ # - ~/develop/agent-harness/services/board
19
+ #
20
+ # Client env (written to <config>/board.env, sourced by the shell hook):
21
+ # BACKLOG_API_URL, BACKLOG_API_TOKEN, BACKLOG_PROJECT
22
+ set -euo pipefail
23
+
24
+ HARNESS_HOME="${AGENT_HARNESS_HOME:-$HOME/develop/agent-harness}"
25
+ CONFIG_DIR="${BOARD_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/agent-harness}"
26
+ ENV_FILE="$CONFIG_DIR/board.env" # CLIENT config (BACKLOG_*)
27
+ SERVICE_ENV_FILE="$CONFIG_DIR/board-service.env" # SERVICE config (DATABASE_URL, BOARD_TOKENS)
28
+ UNIT_DIR="${BOARD_UNIT_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user}"
29
+ UNIT_NAME="agent-board.service"
30
+ BASHRC="${BOARD_BASHRC:-$HOME/.bashrc}"
31
+ BASHRC_MARKER="# >>> agent-harness board service >>>"
32
+ BASHRC_END="# <<< agent-harness board service <<<"
33
+ DEFAULT_PORT="${BOARD_PORT:-3021}"
34
+ LOG_DIR="${BOARD_LOG_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/agent-board}"
35
+ DRY_RUN=0
36
+
37
+ say() { printf 'board-service: %s\n' "$*"; }
38
+ run() {
39
+ if [ "$DRY_RUN" = "1" ]; then printf ' [dry-run] %s\n' "$*"; return 0; fi
40
+ "$@"
41
+ }
42
+ have() { command -v "$1" >/dev/null 2>&1; }
43
+
44
+ service_dir() {
45
+ for d in "${BOARD_SERVICE_DIR:-}" "$HARNESS_HOME/services/board" "$HOME/develop/agent-harness/services/board"; do
46
+ [ -n "$d" ] || continue
47
+ [ -f "$d/package.json" ] && { printf '%s' "$d"; return 0; }
48
+ done
49
+ return 1
50
+ }
51
+
52
+ url() { printf 'http://127.0.0.1:%s' "$DEFAULT_PORT"; }
53
+
54
+ is_up() {
55
+ have curl || return 1
56
+ curl -sf -o /dev/null --max-time 2 "$(url)/api/health" 2>/dev/null
57
+ }
58
+
59
+ cmd_up() {
60
+ local dir
61
+ dir="$(service_dir)" || { say "service code not found (set BOARD_SERVICE_DIR or AGENT_HARNESS_HOME)"; return 1; }
62
+ if is_up; then say "already running at $(url)"; return 0; fi
63
+ if have systemctl && systemctl --user list-unit-files "$UNIT_NAME" >/dev/null 2>&1 \
64
+ && systemctl --user cat "$UNIT_NAME" >/dev/null 2>&1; then
65
+ run systemctl --user start "$UNIT_NAME"
66
+ say "started via systemd ($UNIT_NAME)"
67
+ elif have systemd-run && systemd-run --user --version >/dev/null 2>&1; then
68
+ # Transient unit: fully detached from this shell/tool call and survives it.
69
+ run systemd-run --user --unit=agent-board-transient \
70
+ --working-directory="$dir" \
71
+ --setenv=NODE_ENV=production \
72
+ npx next start -p "$DEFAULT_PORT"
73
+ say "started via systemd-run (transient unit)"
74
+ else
75
+ mkdir -p "$LOG_DIR"
76
+ # Last resort: setsid + full stdio redirection in a subshell.
77
+ ( cd "$dir" && exec setsid npx next start -p "$DEFAULT_PORT" >"$LOG_DIR/service.log" 2>&1 </dev/null ) &
78
+ disown 2>/dev/null || true
79
+ say "started detached (port $DEFAULT_PORT; log $LOG_DIR/service.log)"
80
+ fi
81
+ for _ in $(seq 1 30); do is_up && { say "healthy at $(url)"; return 0; }; sleep 1; done
82
+ say "did not become healthy in 30s — check $LOG_DIR/service.log"; return 1
83
+ }
84
+
85
+ cmd_down() {
86
+ if have systemctl && systemctl --user cat "$UNIT_NAME" >/dev/null 2>&1; then
87
+ run systemctl --user stop "$UNIT_NAME" || true
88
+ fi
89
+ # Fallback: kill a detached next-server bound to our port.
90
+ if have pkill; then pkill -f "next start -p $DEFAULT_PORT" 2>/dev/null || true; fi
91
+ say "stopped"
92
+ }
93
+
94
+ cmd_status() {
95
+ if is_up; then say "running — $(curl -s --max-time 2 "$(url)/api/health")"
96
+ else say "not running ($(url))"; return 1; fi
97
+ }
98
+
99
+ cmd_env() {
100
+ local f="$ENV_FILE"
101
+ if [ -f "$f" ]; then cat "$f"; else
102
+ printf 'export BACKLOG_API_URL="%s"\n' "$(url)"
103
+ printf 'export BACKLOG_API_TOKEN="%s"\n' "${BOARD_TOKEN:-change-me}"
104
+ printf 'export BACKLOG_PROJECT="%s"\n' "${BOARD_PROJECT:-${PROJECT_NAME:-project}}"
105
+ fi
106
+ }
107
+
108
+ write_env() {
109
+ [ "$DRY_RUN" = "1" ] && { printf ' [dry-run] write %s\n' "$ENV_FILE"; return 0; }
110
+ mkdir -p "$CONFIG_DIR"
111
+ {
112
+ printf '# agent-harness board service client config (ADR 0001).\n'
113
+ printf 'export BACKLOG_API_URL="%s"\n' "$(url)"
114
+ printf 'export BACKLOG_API_TOKEN="%s"\n' "${BOARD_TOKEN:-}"
115
+ printf 'export BACKLOG_PROJECT="%s"\n' "${BOARD_PROJECT:-}"
116
+ } >"$ENV_FILE"
117
+ }
118
+
119
+ write_unit() {
120
+ local dir
121
+ dir="$(service_dir)" || { say "service code not found"; return 1; }
122
+ [ "$DRY_RUN" = "1" ] && { printf ' [dry-run] write %s/%s\n' "$UNIT_DIR" "$UNIT_NAME"; return 0; }
123
+ mkdir -p "$UNIT_DIR"
124
+ {
125
+ echo "[Unit]"
126
+ echo "Description=agent-harness shared board service (ADR 0001)"
127
+ echo "After=default.target"
128
+ # Auto-start across WSL restarts: the board DB is a Docker container, so wait
129
+ # for the engine and retry the boot until Postgres is actually accepting
130
+ # connections (Docker + the container come up asynchronously after boot).
131
+ echo "Wants=docker.service"
132
+ echo "After=docker.service"
133
+ echo
134
+ echo "[Service]"
135
+ echo "WorkingDirectory=$dir"
136
+ [ -f "$SERVICE_ENV_FILE" ] && echo "EnvironmentFile=$SERVICE_ENV_FILE"
137
+ echo "Environment=NODE_ENV=production"
138
+ # `next`'s shebang is `#!/usr/bin/env node`, and systemd --user's default
139
+ # PATH omits user-level Node installs (nvm/volta/~/.local/bin), so the unit
140
+ # restart-loops with `env: 'node': No such file or directory` (exit 127).
141
+ # Pin the directory of the node that generated this unit.
142
+ local node_dir
143
+ node_dir="$(dirname "$(command -v node 2>/dev/null || printf '%s' /usr/bin/node)")"
144
+ echo "Environment=PATH=$node_dir:/usr/local/bin:/usr/bin:/bin"
145
+ # Best-effort gate: wait (bounded, ~60s) for the DB port before the app
146
+ # boots. Uses bash (the `/dev/tcp` redirect is a bash feature).
147
+ echo "ExecStartPre=-/bin/bash -c 'for i in \$(seq 1 30); do (exec 3<>/dev/tcp/127.0.0.1/5432) 2>/dev/null && exit 0; sleep 2; done; exit 0'"
148
+ echo "ExecStart=$dir/node_modules/.bin/next start -p $DEFAULT_PORT"
149
+ echo "Restart=always"
150
+ echo "RestartSec=3"
151
+ echo
152
+ echo "[Install]"
153
+ echo "WantedBy=default.target"
154
+ } >"$UNIT_DIR/$UNIT_NAME"
155
+ }
156
+
157
+ install_bashrc_hook() {
158
+ [ "$DRY_RUN" = "1" ] && { printf ' [dry-run] bashrc hook in %s\n' "$BASHRC"; return 0; }
159
+ touch "$BASHRC"
160
+ awk -v b="$BASHRC_MARKER" -v e="$BASHRC_END" '$0==b{skip=1;next} skip&&$0==e{skip=0;next} !skip{print}' "$BASHRC" >"$BASHRC.tmp.$$" && mv "$BASHRC.tmp.$$" "$BASHRC"
161
+ {
162
+ printf '%s\n' "$BASHRC_MARKER"
163
+ printf '[ -f "%s" ] && . "%s"\n' "$ENV_FILE" "$ENV_FILE"
164
+ # Safety net: if systemd did not bring the service up (e.g. no linger, or a
165
+ # cold WSL boot racing Docker), nudge it once per shell — bounded and silent.
166
+ printf 'if command -v systemctl >/dev/null 2>&1 && ! systemctl --user is-active --quiet %s 2>/dev/null; then\n' "$UNIT_NAME"
167
+ printf ' systemctl --user start %s >/dev/null 2>&1 || true\n' "$UNIT_NAME"
168
+ printf 'fi\n'
169
+ printf '%s\n' "$BASHRC_END"
170
+ } >>"$BASHRC"
171
+ }
172
+
173
+ cmd_install() {
174
+ write_env
175
+ write_unit
176
+ install_bashrc_hook
177
+ if have systemctl && systemctl --user show-environment >/dev/null 2>&1; then
178
+ run systemctl --user daemon-reload
179
+ run systemctl --user enable --now "$UNIT_NAME"
180
+ say "systemd --user unit '$UNIT_NAME' enabled."
181
+ else
182
+ say "systemd --user unavailable — bashrc hook + detached start is the persistence path."
183
+ fi
184
+ cmd_up
185
+ say "persisted. Client env in $ENV_FILE (source your shell or open a new one)."
186
+ }
187
+
188
+ cmd_uninstall() {
189
+ cmd_down
190
+ if have systemctl; then run systemctl --user disable "$UNIT_NAME" 2>/dev/null || true; fi
191
+ [ "$DRY_RUN" != "1" ] && rm -f "$UNIT_DIR/$UNIT_NAME" "$ENV_FILE"
192
+ if [ "$DRY_RUN" != "1" ] && [ -f "$BASHRC" ]; then
193
+ awk -v b="$BASHRC_MARKER" -v e="$BASHRC_END" '$0==b{skip=1;next} skip&&$0==e{skip=0;next} !skip{print}' "$BASHRC" >"$BASHRC.tmp.$$" && mv "$BASHRC.tmp.$$" "$BASHRC"
194
+ fi
195
+ say "uninstalled"
196
+ }
197
+
198
+ usage() {
199
+ sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
200
+ }
201
+
202
+ ACTION="${1:-status}"
203
+ shift || true
204
+ case "$ACTION" in
205
+ up) cmd_up ;;
206
+ down) cmd_down ;;
207
+ restart) cmd_down; cmd_up ;;
208
+ status) cmd_status ;;
209
+ env) cmd_env ;;
210
+ install) cmd_install ;;
211
+ uninstall) cmd_uninstall ;;
212
+ help|-h|--help) usage ;;
213
+ *) usage; exit 2 ;;
214
+ esac
@@ -0,0 +1,290 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * checkpoint — deterministic bounded-state checkpoint for one session handoff.
5
+ *
6
+ * Writes the compact state block described in `.agents/rules/00-operating.md`
7
+ * §Context budget & lifecycle (objective/phase, completed + active dispatches,
8
+ * files changed, contracts, known facts, decisions, risks, next_action) into
9
+ * `.agents/handoffs/<feature>.md`, replacing only its own `## Checkpoint`
10
+ * section. `resume` prints that block alone — the bounded context a fresh
11
+ * session reads instead of replaying the transcript.
12
+ *
13
+ * Deterministic: no timestamps, stable ordering, `unknown` for anything not
14
+ * recorded (never invented). Writing identical state is a no-op; changing it
15
+ * increments `checkpoint_count`.
16
+ *
17
+ * Usage:
18
+ * node scripts/checkpoint.js write --feature F-001 [--objective ...] [--phase ...]
19
+ * [--completed item]... [--active item]... [--files-changed path]...
20
+ * [--contracts item]... [--facts item]... [--decisions item]... [--risks item]...
21
+ * [--next-action ...] [--session ses_...]
22
+ * node scripts/checkpoint.js resume --feature F-001 [--json]
23
+ */
24
+
25
+ const fs = require("fs");
26
+ const path = require("path");
27
+ const { spawnSync } = require("child_process");
28
+
29
+ /* The project root. Resolve from an explicit `--root <dir>` when given, else
30
+ * `process.cwd()` when it looks like a project root, and only fall back to
31
+ * `__dirname/..`. Under the harness dogfood the repo `scripts` dir is symlinked
32
+ * to `templates/scripts`; Node realpaths the script, so `__dirname/..` is
33
+ * `templates/` — writing a checkpoint into the tree `update` ships to every
34
+ * project (F-26/H-49). The tool wrappers spawn this CLI with `cwd` = session
35
+ * directory (see `scripts/qa/tool-lib.js` sessionRoot()), so cwd is the tree. */
36
+ function looksLikeRoot(dir) {
37
+ return fs.existsSync(path.join(dir, ".agents")) || fs.existsSync(path.join(dir, ".git"));
38
+ }
39
+
40
+ function resolveRoot(argv, cwd) {
41
+ const i = Array.isArray(argv) ? argv.indexOf("--root") : -1;
42
+ if (i !== -1 && argv[i + 1]) return path.resolve(argv[i + 1]);
43
+ const c = cwd || process.cwd();
44
+ if (looksLikeRoot(c)) return c;
45
+ return path.resolve(__dirname, "..");
46
+ }
47
+
48
+ let root = resolveRoot(process.argv.slice(2), process.cwd());
49
+ const SCHEMA = "checkpoint/1";
50
+ const HEADING_RE = /^#{1,6}\s*Checkpoint\b.*$/im;
51
+ const MARKER = "<!-- agent-harness checkpoint — machine-written; edit via scripts/checkpoint.js -->";
52
+
53
+ const SCALARS = [
54
+ ["feature", "feature"],
55
+ ["objective", "objective"],
56
+ ["phase", "phase"],
57
+ ["next_action", "next_action"],
58
+ ["session", "session"],
59
+ ];
60
+ const LISTS = [
61
+ ["completed", "completed"],
62
+ ["active", "active"],
63
+ ["files_changed", "filesChanged"],
64
+ ["contracts", "contracts"],
65
+ ["known_facts", "facts"],
66
+ ["decisions", "decisions"],
67
+ ["risks", "risks"],
68
+ ];
69
+
70
+ function parseArgs(argv) {
71
+ const out = { _: [], lists: {}, scalars: {} };
72
+ const listFlags = new Set(LISTS.map(([key]) => key));
73
+ const scalarFlags = new Set(["objective", "phase", "next-action", "session"]);
74
+ for (let i = 0; i < argv.length; i++) {
75
+ const a = argv[i];
76
+ if (a === "--feature") out.feature = argv[++i];
77
+ else if (a === "--root") out.root = argv[++i];
78
+ else if (a === "--json") out.json = true;
79
+ else if (a.startsWith("--") && listFlags.has(a.slice(2))) {
80
+ const key = a.slice(2);
81
+ if (!out.lists[key]) out.lists[key] = [];
82
+ for (const item of String(argv[++i] || "").split(/\s*;\s*/)) if (item.trim()) out.lists[key].push(item.trim());
83
+ } else if (a.startsWith("--") && scalarFlags.has(a.slice(2))) {
84
+ out.scalars[a.slice(2).replace(/-/g, "_")] = argv[++i];
85
+ } else out._.push(a);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /* Compare a feature id ("F-246") to a branch/dir name ("f-246", "F-246-...")
91
+ * ignoring case and separators. */
92
+ function normalizeId(s) {
93
+ return String(s || "").toLowerCase().replace(/[^a-z0-9]/g, "");
94
+ }
95
+
96
+ /* When the session root is the MAIN tree but the feature has its own linked
97
+ * worktree (the mid-session-reroot case that is missed when `backlog worktree`
98
+ * is invoked via bash and no session pointer is recorded), the handoff belongs
99
+ * in the tree the work actually lives in. Returns the worktree path or null. */
100
+ function featureWorktreeRoot(feature) {
101
+ const res = spawnSync("git", ["-C", root, "worktree", "list", "--porcelain"], { encoding: "utf8" });
102
+ if (res.status !== 0) return null;
103
+ const want = normalizeId(feature);
104
+ let cur = null;
105
+ for (const line of String(res.stdout || "").split(/\r?\n/)) {
106
+ if (line.startsWith("worktree ")) {
107
+ cur = { path: line.slice("worktree ".length).trim(), branch: "" };
108
+ } else if (cur && line.startsWith("branch ")) {
109
+ cur.branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim();
110
+ if (path.resolve(cur.path) === root) continue;
111
+ if (normalizeId(path.basename(cur.path)) === want || normalizeId(cur.branch) === want) {
112
+ return cur.path;
113
+ }
114
+ }
115
+ }
116
+ return null;
117
+ }
118
+
119
+ function handoffPath(feature) {
120
+ const base = featureWorktreeRoot(feature) || root;
121
+ return path.join(base, ".agents", "handoffs", feature + ".md");
122
+ }
123
+
124
+ /* A feature id must be a real slug. Reject the stringified sentinels a tool
125
+ * wrapper produces from an unset arg (`undefined`/`null`), which otherwise
126
+ * match the slug regex and silently write a `.agents/handoffs/undefined.md`
127
+ * (the H-14 stray-handoff defect: `.agents/handoffs/undefined.md` left on main
128
+ * by a `checkpoint_write` call that omitted `feature`). */
129
+ const RESERVED_FEATURE = new Set(["undefined", "null", "none", "nan", "nil"]);
130
+ function assertFeature(raw, verb) {
131
+ const feature = String(raw == null ? "" : raw).trim();
132
+ if (!feature || RESERVED_FEATURE.has(feature.toLowerCase()) || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(feature)) {
133
+ throw new Error(
134
+ `${verb} requires --feature <id or slug> (letters, digits, dot, dash, underscore); ` +
135
+ `refusing the value ${JSON.stringify(raw == null ? "" : raw)} — pass the BACKLOG row id (e.g. F-001)`
136
+ );
137
+ }
138
+ return feature;
139
+ }
140
+
141
+ /* Split the file into [before, checkpointBody, after] around the existing
142
+ * `## Checkpoint` section (until the next heading), any of which may be null. */
143
+ function splitCheckpoint(src) {
144
+ const m = src.match(HEADING_RE);
145
+ if (!m) return { before: src, body: null, after: "" };
146
+ const start = m.index;
147
+ const rest = src.slice(start + m[0].length);
148
+ const next = rest.match(/^#{1,6}\s/m);
149
+ const end = next ? start + m[0].length + next.index : src.length;
150
+ return { before: src.slice(0, start), body: src.slice(start, end), after: src.slice(end) };
151
+ }
152
+
153
+ function countOf(body) {
154
+ const m = body && body.match(/^- checkpoint_count:\s*(\d+)\s*$/m);
155
+ return m ? Number(m[1]) : 0;
156
+ }
157
+
158
+ function renderBlock(args, feature, count) {
159
+ const lines = ["## Checkpoint (resume)", "", MARKER, ""];
160
+ for (const [label, key] of SCALARS) {
161
+ lines.push(`- ${label}: ${args.scalars[key] || (key === "feature" ? feature : "unknown")}`);
162
+ }
163
+ for (const [label] of LISTS) {
164
+ lines.push(`- ${label}:`);
165
+ const items = args.lists[label] || [];
166
+ if (items.length === 0) lines.push(" - (none recorded)");
167
+ else for (const item of items) lines.push(` - ${item}`);
168
+ }
169
+ lines.push(`- checkpoint_count: ${count}`);
170
+ return lines.join("\n") + "\n";
171
+ }
172
+
173
+ function writeCheckpoint(args) {
174
+ const feature = assertFeature(args.feature, "write");
175
+ const hasState =
176
+ Object.values(args.scalars).some((v) => v != null && String(v).trim()) ||
177
+ Object.values(args.lists).some((v) => v && v.length);
178
+ if (!hasState) throw new Error("refusing to write an empty checkpoint — record at least one state field");
179
+
180
+ const file = handoffPath(feature);
181
+ const existed = fs.existsSync(file);
182
+ const src = existed ? fs.readFileSync(file, "utf8") : "";
183
+ const parts = splitCheckpoint(src);
184
+ const existingCount = countOf(parts.body);
185
+ const sameBlock = parts.body ? renderBlock(args, feature, existingCount) : null;
186
+ if (sameBlock && parts.body.trim() === sameBlock.trim()) {
187
+ return { feature, file, changed: false, count: existingCount, created: false };
188
+ }
189
+ const block = renderBlock(args, feature, existingCount + 1);
190
+ const nextCount = existingCount + 1;
191
+
192
+ const before = parts.before.replace(/\s*$/, "");
193
+ const after = parts.after.replace(/^\s*/, "");
194
+ // A checkpoint can create the handoff before the session wraps up, so the new
195
+ // file carries an honest placeholder dispatch-log line — `test:governance`
196
+ // never blocks on a mid-session checkpoint, and the handoff skill replaces
197
+ // the line with the real log at wrap-up.
198
+ const head = existed
199
+ ? before
200
+ : `# Where we stopped (handoff) — ${feature}\n\nDate: unknown\n\n## Dispatch log\n- (checkpoint only — dispatch log recorded at wrap-up)\n`;
201
+ const body = [head, "", block.trim(), after ? "\n" + after : ""].join("\n").replace(/\n{4,}/g, "\n\n\n");
202
+ fs.mkdirSync(path.dirname(file), { recursive: true });
203
+ fs.writeFileSync(file, body.endsWith("\n") ? body : body + "\n", "utf8");
204
+ return { feature, file, changed: true, count: nextCount, created: !existed };
205
+ }
206
+
207
+ function parseBlock(body) {
208
+ const state = {};
209
+ let current = null;
210
+ for (const raw of String(body || "").split(/\r?\n/)) {
211
+ const scalar = raw.match(/^- ([a-z_]+):\s*(.*)$/);
212
+ if (scalar) {
213
+ current = null;
214
+ if (scalar[2] === "") current = scalar[1];
215
+ else state[scalar[1]] = scalar[2];
216
+ continue;
217
+ }
218
+ const item = raw.match(/^\s{2,}- (.*)$/);
219
+ if (item && current) {
220
+ if (!Array.isArray(state[current])) state[current] = [];
221
+ if (item[1] !== "(none recorded)") state[current].push(item[1]);
222
+ }
223
+ }
224
+ if (Array.isArray(state.checkpoint_count)) state.checkpoint_count = Number(state.checkpoint_count[0] || 0);
225
+ else state.checkpoint_count = Number(state.checkpoint_count || 0);
226
+ return state;
227
+ }
228
+
229
+ function readCheckpoint(args) {
230
+ const feature = assertFeature(args.feature, "resume");
231
+ const worktree = featureWorktreeRoot(feature);
232
+ const file = handoffPath(feature);
233
+ if (!fs.existsSync(file)) throw new Error(`no handoff found for "${feature}" (${path.relative(root, file)})`);
234
+ const parts = splitCheckpoint(fs.readFileSync(file, "utf8"));
235
+ if (!parts.body) throw new Error(`"${feature}" has no ## Checkpoint block yet — run checkpoint write first`);
236
+ return { feature, file, root, worktree, body: parts.body.trim(), state: parseBlock(parts.body) };
237
+ }
238
+
239
+ function main() {
240
+ const argv = process.argv.slice(2);
241
+ const cmd = argv[0];
242
+ const args = parseArgs(argv.slice(1));
243
+ if (cmd === "write") {
244
+ const r = writeCheckpoint(args);
245
+ if (r.changed) {
246
+ console.log(
247
+ `checkpoint: ${r.created ? "created" : "updated"} ${path.relative(root, r.file).split(path.sep).join("/")} (checkpoint_count ${r.count})`
248
+ );
249
+ } else {
250
+ console.log(`checkpoint: ${path.relative(root, r.file).split(path.sep).join("/")} already matches — unchanged`);
251
+ }
252
+ return;
253
+ }
254
+ if (cmd === "resume") {
255
+ const r = readCheckpoint(args);
256
+ if (args.json) {
257
+ console.log(JSON.stringify({ schema: SCHEMA, feature: r.feature, state: r.state, root: r.root, worktree: r.worktree }, null, 2));
258
+ return;
259
+ }
260
+ // The handoff is resolved through the feature's linked worktree, so a session
261
+ // still rooted in the main checkout would otherwise read the right state and
262
+ // then run tsc/tests against the wrong tree. Say which root the state belongs to.
263
+ if (r.worktree && path.resolve(r.worktree) !== path.resolve(r.root)) {
264
+ console.log(
265
+ `> ROOT MISMATCH — ${r.feature}'s checkpoint lives in ${r.worktree}, but this session is rooted in ${r.root}.\n` +
266
+ "> Move the session to that worktree (session_move) before running tsc/tests; this root is a different tree.\n"
267
+ );
268
+ }
269
+ console.log(r.body);
270
+ return;
271
+ }
272
+ console.error(
273
+ "Usage: node scripts/checkpoint.js write --feature <id> [--objective ...] [--phase ...]\n" +
274
+ " [--completed item]... [--active item]... [--files-changed path]... [--contracts item]...\n" +
275
+ " [--facts item]... [--decisions item]... [--risks item]... [--next-action ...] [--session <ses_...>]\n" +
276
+ " node scripts/checkpoint.js resume --feature <id> [--json]"
277
+ );
278
+ process.exitCode = 1;
279
+ }
280
+
281
+ if (require.main === module) {
282
+ try {
283
+ main();
284
+ } catch (e) {
285
+ console.error("checkpoint: " + (e && e.message ? e.message : e));
286
+ process.exit(1);
287
+ }
288
+ }
289
+
290
+ module.exports = { SCHEMA, splitCheckpoint, renderBlock, parseBlock, writeCheckpoint, readCheckpoint, handoffPath, assertFeature };