Skip to content
Back to search

claude-code-harness-marketplace

SkillWorks with Claude CodeGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Chachamaru127/claude-code-harness with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Chachamaru127/claude-code-harness'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/chachamaru127--claude-code-harness/badge.svg)](/listings/chachamaru127--claude-code-harness)

HTML

<a href="/listings/chachamaru127--claude-code-harness"><img src="/api/listings/chachamaru127--claude-code-harness/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

You need an installed, signed-in coding assistant and a project folder you can write to. For an existing Harness setup, read the [migration guide](docs/onboarding/migration.md) before reinstalling or cleaning up files.

For Claude Code, open a terminal (the app where you type system commands) and run:

claude

Then enter these commands **inside Claude Code**, one at a time:

/plugin marketplace add Chachamaru127/claude-code-harness
/plugin install harness@claude-code-harness-marketplace
/harness-setup

`/harness-setup` prepares the project's instructions and checks. Review any proposed project changes before accepting them. Installation time depends on your existing setup and connection.

The Claude plugin ID is now `harness`; the repository and marketplace names stay the same. If you installed the old `claude-code-harness` plugin, follow [Switch an existing Claude installation](docs/onboarding/plugin-rename.md). Updating the old ID alone does not rename it. The tool table describes verified paths, not every future assistant version.

For other tools, choose the route in [Install by tool](#install-by-tool). The [onboarding guide](docs/onboarding/index.md) covers the same starting point with more detail.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 37 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "claude-code-harness-marketplace",
  3. "metadata": {
  4. "version": "5.16.0",
  5. "description": "Marketplace entry for distributing and installing Harness as a single plugin."
  6. },
  7. "owner": {
  8. "name": "Chachamaru"
  9. },
  10. "plugins": [
  11. {
  12. "name": "harness",
  13. "version": "5.16.0",
  14. "source": "./",
  15. "description": "A harness for solo developers (Vibecoders) to handle full-cycle contract development.",
  16. "author": {
  17. "name": "Chachamaru",
  18. "url": "https://github.com/Chachamaru127"
  19. },
  20. "homepage": "https://github.com/Chachamaru127/claude-code-harness",
  21. "repository": "https://github.com/Chachamaru127/claude-code-harness",
  22. "license": "MIT",
  23. "keywords": [
  24. "claude-code",
  25. "plugin",
  26. "vibecoder",
  27. "workflow",
  28. "plan-work-review"
  29. ],
  30. "category": "productivity",
  31. "strict": true
  32. }
  33. ],
  34. "renames": {
  35. "claude-code-harness": "harness"
  36. }
  37. }
README.md · README · 295 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center"><img src="docs/images/claude-harness-logo-with-text.png" alt="Claude Harness" width="220"></p>
  2. <h1 align="center">The AI writes the code.<br>You still manage the work.</h1>
  3. <p align="center"><a href="docs/images/readme/hero-motion-en.svg"><picture><source media="(prefers-reduced-motion: reduce)" srcset="docs/images/readme/hero-motion-en-poster.svg"><img src="docs/images/readme/hero-motion-en.gif" alt="Scattered work becomes a plan, implementation and tests, and a separate review before your final decision" width="880"></picture></a></p>
  4. <p align="center"><strong>Delegate the plan, checks, and review.<br>Judge the result.</strong></p>
  5. Use your existing Claude Code, Codex CLI, Cursor, or Grok account.
  6. [Choose your tool](#install-by-tool) · [Try one small request](#your-first-request)
  7. English | [日本語](README_ja.md)
  8. [![Latest release](https://img.shields.io/github/v/release/Chachamaru127/claude-code-harness?display_name=tag&sort=semver)](https://github.com/Chachamaru127/claude-code-harness/releases/latest)
  9. ## Install and start
  10. You need an installed, signed-in coding assistant and a project folder you can
  11. write to. For an existing Harness setup, read the [migration guide](docs/onboarding/migration.md)
  12. before reinstalling or cleaning up files.
  13. For Claude Code, open a terminal (the app where you type system commands) and run:
  14. ```bash
  15. claude
  16. ```
  17. Then enter these commands **inside Claude Code**, one at a time:
  18. ```text
  19. /plugin marketplace add Chachamaru127/claude-code-harness
  20. /plugin install harness@claude-code-harness-marketplace
  21. /harness-setup
  22. ```
  23. `/harness-setup` prepares the project's instructions and checks. Review any
  24. proposed project changes before accepting them. Installation time depends on
  25. your existing setup and connection.
  26. The Claude plugin ID is now `harness`; the repository and marketplace names
  27. stay the same. If you installed the old `claude-code-harness` plugin, follow
  28. [Switch an existing Claude installation](docs/onboarding/plugin-rename.md).
  29. Updating the old ID alone does not rename it.
  30. The tool table describes verified paths, not every future assistant version.
  31. For other tools, choose the route in [Install by tool](#install-by-tool).
  32. The [onboarding guide](docs/onboarding/index.md) covers the same starting point
  33. with more detail.
  34. ## Your first request
  35. You decide the outcome, the completion criteria, and the actions you authorize.
  36. Review means checking the change separately from its implementation.
  37. Start with one small change whose result you can check:
  38. ```text
  39. /harness-plan Stop the contact form from sending twice. When I click Send twice quickly, only one message should be created. Keep the existing fields and appearance.
  40. ```
  41. Harness drafts `spec.md` and `Plans.md` for you. Read the proposed behavior,
  42. what it will change, how it will test the result, and anything still unknown.
  43. Approve the plan or correct it before work starts.
  44. Then run:
  45. ```text
  46. /harness-work all
  47. /harness-review
  48. ```
  49. The first command works through the approved tasks. The second requests a
  50. separate review. On Codex, use `$harness-plan`, `$harness-work all`, and
  51. `$harness-review` instead of the slash form.
  52. At the end, check the actual result: try the form, read which tests passed,
  53. and look for unresolved problems. A review-ready change can still need a
  54. real service connection or your acceptance before it is ready to publish.
  55. ## What you can delegate
  56. | Re-explaining the work | Tracking what is done | Checking “it works” |
  57. |---|---|---|
  58. | Keep the specification and plan in files | See task status and pending decisions | Get actual test results and a separate review |
  59. ## The work steps
  60. <p align="center"><img src="docs/images/readme/loop-en.svg" alt="Plan, work, review, and release" width="880"></p>
  61. Harness keeps the specification in `spec.md` and tasks in `Plans.md`.
  62. Think of them as a shared job sheet and checklist. In practice, the assistant
  63. writes the drafts and updates the records; you approve the intended result.
  64. A **skill** is a reusable set of instructions for the assistant. The 5 verb skills
  65. cover planning, work, review, checking status, and release. Setup is separate.
  66. | Request or command | What you receive | Your decision |
  67. |---|---|---|
  68. | `/harness-plan` | A specification, tasks, completion criteria, unknowns, and operations that need permission | Approve or correct the scope and criteria |
  69. | `/harness-work 3` | Changes and required checks for task 3 | Resolve a new permission or product decision if one is needed |
  70. | `/harness-work all` | Work on all approved tasks, with checks and corrections | Judge the result against the criteria |
  71. | `/harness-review` | Findings from a reviewer separate from the implementation | Serious findings block completion; minor suggestions can remain |
  72. | `/harness-sync` | Differences between the recorded plan and observed project state | Decide what to correct when they disagree |
  73. | `/harness-release` | A release plan, version changes, and publication checks | Approve the complete publication plan before it runs |
  74. When a task requires test-first development, the assistant demonstrates a
  75. failing test before implementing the fix, then runs it again. Other tasks use
  76. the checks their plan requires. A wording change need not use the same tests
  77. as a payment feature.
  78. The assistant continues reversible work inside the approved scope. It stops
  79. the affected operation when a new authorization or material product decision
  80. is needed. Failed checks and exhausted correction limits are reported as
  81. unfinished work, with evidence and a next step.
  82. ## What you can see during work
  83. | View | When to use it | What it tells you |
  84. |---|---|---|
  85. | Plan Brief | Before approving a plan | Intended result, choices, risks, and completion criteria |
  86. | Progress (`/harness-progress`) | During work | Task status and pending decisions recorded in `Plans.md` |
  87. | Acceptance | Before publication | Which completion criteria passed, failed, or remain unverified |
  88. The progress percentage counts recorded tasks. It is not the percentage of
  89. features proven to work. For example, “8 of 10 tasks complete” can coexist
  90. with a failed end-to-end test. Claude Code refreshes the progress page after
  91. edits or commands, at most once every 60 seconds; other tools have different
  92. update behavior.
  93. To continue after an interruption, use:
  94. ```text
  95. /harness-work --resume latest
  96. ```
  97. This recovers the recorded plan, changes, check results, and remaining work.
  98. Ask the assistant to show what was recovered before relying on it. Optional
  99. [harness-mem](https://github.com/Chachamaru127/harness-mem) adds memory and search
  100. across sessions; the basic workflow does not require it.
  101. ## Permissions and limits
  102. Harness checks operations connected to its execution hooks (checks run before
  103. or after an assistant action). The **Go-native guardrail engine** is the bundled
  104. program that applies those rules; it does not require Node.js to run.
  105. | Check layer | What it checks | What you control |
  106. |---|---|---|
  107. | Runtime floor | Billing, external sends, secret reads, production deployment, and destruction outside the task's working copy | Named permissions under the category's rules; there is no global off switch |
  108. | Guardrails | Protected files, direct pushes to the shared main branch, forced pushes, and changes to recorded history | Some rules are configurable for the project |
  109. Known permissions can be scoped and collected with the plan where the
  110. operation supports it. The permission details depend on the operation and its configured rules. The assistant must not rewrite protected settings to pass its own check.
  111. Stop reasons identify the rule and action so you can inspect the cause.
  112. These checks do not guarantee every command is contained. Coverage depends
  113. on the tool and how the operation is launched. Cursor has no traditional
  114. filesystem isolation; its restrictions are applied by Harness. Native Codex
  115. child agents can inherit their parent's permissions. A reviewer role alone
  116. is not read-only isolation; the companion review route explicitly requests
  117. read-only execution. Read the [differences between tools](docs/hardening-parity.md)
  118. and [Cursor limits](docs/CURSOR_INTEGRATION.md) before delegating sensitive work.
  119. ## Cost and project data
  120. Harness is free to use and modify under the MIT license. Your coding assistant, model
  121. provider, and any connected services have their own fees and terms. More
  122. workers, reviews, and repeated attempts can use more of those services.
  123. Harness does not provide an account or a universal spending cap.
  124. Project plans and task records are files in your project. Execution state is
  125. kept under `.claude/state/`. Setup also adds project guidance and check files. Content read by the
  126. coding assistant is still subject to that assistant's data handling. Installing
  127. Harness does not make model requests local or prevent the assistant from
  128. sending project content to its provider. Optional memory and external
  129. connections have their own configuration and data boundaries.
  130. ## Install by tool
  131. The tier describes the checked Harness integration path. `supported` means a
  132. verified path; `internal-compatible` means limited integration; `candidate`
  133. means experimental work; `future/unsupported` means no current user route.
  134. These labels do not promise identical permissions or features across tools.
  135. | Tool | Tier | How to start or what is missing |
  136. |---|---|---|
  137. | Claude Code | `supported` | Use the marketplace commands above, then `/harness-setup` |
  138. | Codex CLI | `supported` | [Run `scripts/setup-codex.sh --user`](codex/README.md#option-1-script-recommended-user-based), then restart Codex |
  139. | Cursor | `supported` | Run `scripts/setup-cursor.sh`, then reload Cursor; read its permission limits above |
  140. | Grok | `supported` | Run `scripts/setup-grok.sh`, then start a new session |
  141. | OpenCode | `internal-compatible` | Run `scripts/setup-opencode.sh` for instructions and skills; the full execution behavior is not verified as equivalent |
  142. | Codex app | `candidate` | The Codex CLI installation does not establish an app installation path |
  143. | Hermes Agent | `candidate` | Experimental manual skill loading; automatic guardrail enforcement is not connected |
  144. | GitHub Copilot CLI | `candidate` | Experimental manual instructions; no verified Harness installation route |
  145. | Antigravity CLI | `future/unsupported` | No end-user installation route |
  146. For setup scripts, first download this repository with Git (the program that
  147. manages project versions):
  148. ```bash
  149. git clone https://github.com/Chachamaru127/claude-code-harness.git
  150. cd claude-code-harness
  151. ```
  152. Then run the script for your tool. The Codex `--user` route writes user-level
  153. skills, rules, and managed profiles, so it applies across projects. Existing
  154. `worker.toml` and `reviewer.toml` are backed up and replaced, even if you created
  155. them yourself. Read the [installation details](docs/onboarding/install.md) for
  156. project-local alternatives, update steps, and removal.
  157. ## Larger jobs and model choices
  158. `/breezing` divides larger approved work between agents. `/harness-loop`
  159. repeats work within a limit and can ask an advisor for help. It defaults to
  160. eight cycles. Reaching the limit is not completion. Use `/harness-loop status`
  161. to inspect it and `/harness-loop stop` to stop further execution.
  162. Your explicit model and reasoning-effort choices take priority in their
  163. execution path. Reasoning effort is the amount of processing a model uses to
  164. think. Changing the main conversation does not change every child agent's
  165. settings. See [model choices](docs/model-routing-policy.md) and
  166. [Codex Breezing role routing](codex/README.md#codex-breezing-role-routing) before
  167. changing defaults.
  168. The experimental `HARNESS_AUTO_APPROVE=on` option only records an eligibility
  169. check. It is off by default and does not skip approval prompts.
  170. ## Update or troubleshoot
  171. For Claude Code, run these inside the assistant:
  172. ```text
  173. /plugin update harness
  174. /harness-setup
  175. ```
  176. For a script installation, update your repository copy with `git pull --ff-only`,
  177. rerun the same setup script, and restart or reload the assistant.
  178. Check the [English changelog](CHANGELOG.md) or [Japanese changelog](CHANGELOG_ja.md)
  179. for behavior changes and required action before updating.
  180. If commands are missing, check that installation targeted the tool you are
  181. using and that you restarted it. The [installation check](docs/onboarding/skill-trigger-acceptance.md)
  182. shows what a successful first invocation looks like.
  183. From your Harness repository copy, `bin/harness doctor --migration-report`
  184. inspects old setup files and memory state without deleting them.
  185. If a check blocks work, keep the exact error and ask the assistant to explain
  186. the rule, target, and required permission. Do not treat a failed check as a
  187. completed task. Report reproducible installation or execution problems in
  188. [GitHub Issues](https://github.com/Chachamaru127/claude-code-harness/issues).
  189. ## Requirements
  190. CLI means the edition you run from a terminal. A repository is a project folder
  191. whose changes are tracked with Git.
  192. - An installed coding assistant and access to its account or model provider.
  193. - Claude Code v2.1+ for the Claude path; check [compatibility notes](docs/CLAUDE_CODE_COMPATIBILITY.md) for dated observations and platform limits.
  194. - A project repository with write access. Setup scripts require Git and a shell that can run them.
  195. - No Go installation is needed for bundled binaries. Building the current source requires Go 1.26.0 or later; optional skills can have additional requirements.
  196. ## Documentation
  197. - [Start with your tool](docs/onboarding/index.md), [installation and removal](docs/onboarding/install.md), and [existing-user migration](docs/onboarding/migration.md).
  198. - [Language settings](docs/i18n.md): English is the default. Ask “Please respond in Japanese” to switch the conversation; project settings and environment variables are also available.
  199. - [What gets installed](docs/distribution-scope.md) and [checks for a whole plan](docs/evidence/work-all.md).
  200. - [Product guide in Japanese](docs/reports/2026-09-06-cch-product-guide-v5.15.0.html).
  201. For a project without a pinned language setting, you can also choose Japanese
  202. when starting Claude Code:
  203. ```bash
  204. CLAUDE_CODE_HARNESS_LANG=ja claude
  205. ```
  206. A project language setting takes priority over this environment variable.
  207. An explicit instruction in the conversation takes priority over both.
  208. ## Contributing
  209. Describe what you expected, what happened, and how to reproduce it in an Issue.
  210. For changes, see [CONTRIBUTING.md](CONTRIBUTING.md).
  211. ## Acknowledgments
  212. [AI Masao](https://note.com/masa_wunder) contributed ideas on organizing skills;
  213. [Beagle](https://github.com/beagleworks) contributed test integrity patterns.
  214. ## License
  215. [MIT](LICENSE.md).
scripts/codex-loop.sh · Bundled script · 3,497 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. #
  3. # codex-loop.sh
  4. #
  5. # Real background runner for `harness codex-loop`.
  6. # Stores state under .claude/state/codex-loop/ and delegates each cycle to the
  7. # Codex companion background task runner.
  8. set -euo pipefail
  9. SOURCE_PATH="${BASH_SOURCE[0]}"
  10. while [ -h "${SOURCE_PATH}" ]; do
  11. SOURCE_DIR="$(cd -P "$(dirname "${SOURCE_PATH}")" && pwd)"
  12. SOURCE_TARGET="$(readlink "${SOURCE_PATH}")"
  13. case "${SOURCE_TARGET}" in
  14. /*) SOURCE_PATH="${SOURCE_TARGET}" ;;
  15. *) SOURCE_PATH="${SOURCE_DIR}/${SOURCE_TARGET}" ;;
  16. esac
  17. done
  18. SCRIPT_DIR="$(cd -P "$(dirname "${SOURCE_PATH}")" && pwd)"
  19. SELF_SCRIPT="${SCRIPT_DIR}/$(basename "${SOURCE_PATH}")"
  20. DEFAULT_INSTALL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
  21. HARNESS_INSTALL_ROOT="${HARNESS_INSTALL_ROOT:-${DEFAULT_INSTALL_ROOT}}"
  22. DEFAULT_PROJECT_ROOT="${HARNESS_INSTALL_ROOT}"
  23. PROJECT_ROOT="${PROJECT_ROOT:-${DEFAULT_PROJECT_ROOT}}"
  24. STATE_ROOT="${PROJECT_ROOT}/.claude/state"
  25. LOOP_STATE_DIR="${STATE_ROOT}/codex-loop"
  26. LOCKS_DIR="${STATE_ROOT}/locks"
  27. LOCK_DIR="${LOCKS_DIR}/codex-loop.lock.d"
  28. RUN_JSON="${LOOP_STATE_DIR}/run.json"
  29. CYCLES_JSONL="${LOOP_STATE_DIR}/cycles.jsonl"
  30. RUNNER_LOG="${LOOP_STATE_DIR}/runner.log"
  31. CURRENT_JOB_JSON="${LOOP_STATE_DIR}/current-job.json"
  32. PROMPTS_DIR="${LOOP_STATE_DIR}/prompts"
  33. RESULTS_DIR="${LOOP_STATE_DIR}/results"
  34. TASK_JOBS_DIR="${LOOP_STATE_DIR}/jobs"
  35. CONFIG_UTILS="${HARNESS_INSTALL_ROOT}/scripts/config-utils.sh"
  36. COMPANION="${CODEX_LOOP_COMPANION:-${HARNESS_INSTALL_ROOT}/scripts/codex-companion.sh}"
  37. VALIDATE_SCRIPT="${CODEX_LOOP_VALIDATE_SCRIPT:-${PROJECT_ROOT}/tests/validate-plugin.sh}"
  38. ENRICH_CONTRACT_SCRIPT="${CODEX_LOOP_ENRICH_CONTRACT_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/enrich-sprint-contract.sh}"
  39. ENSURE_CONTRACT_SCRIPT="${CODEX_LOOP_ENSURE_CONTRACT_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/ensure-sprint-contract-ready.sh}"
  40. RUNTIME_REVIEW_SCRIPT="${CODEX_LOOP_RUNTIME_REVIEW_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/run-contract-review-checks.sh}"
  41. WRITE_REVIEW_RESULT_SCRIPT="${CODEX_LOOP_WRITE_REVIEW_RESULT_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/write-review-result.sh}"
  42. PLATEAU_SCRIPT="${CODEX_LOOP_PLATEAU_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/detect-review-plateau.sh}"
  43. CHECKPOINT_SCRIPT="${CODEX_LOOP_CHECKPOINT_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/auto-checkpoint.sh}"
  44. # Phase 60 (v2.20.10) 以降、scripts/harness-mem-client.sh は claude-harness
  45. # 配布から除外された (managed-companion 移行)。env 指定がない既定では空文字とし、
  46. # resume-pack 呼び出しを log 付きで skip する (line 1392-1397 の graceful path)。
  47. # CODEX_LOOP_MEM_CLIENT=/abs/path で test fixture 等を指定可能。
  48. MEM_CLIENT="${CODEX_LOOP_MEM_CLIENT:-}"
  49. NODE_BIN="${NODE_BIN:-node}"
  50. GENERATE_CONTRACT_SCRIPT="${CODEX_LOOP_GENERATE_CONTRACT_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/generate-sprint-contract.js}"
  51. POLL_INTERVAL_SEC="${CODEX_LOOP_POLL_INTERVAL_SEC:-5}"
  52. RUNNER_FINALIZED=0
  53. if [ -f "${CONFIG_UTILS}" ]; then
  54. # shellcheck source=scripts/config-utils.sh
  55. CONFIG_FILE="${PROJECT_ROOT}/.claude-code-harness.config.yaml"
  56. source "${CONFIG_UTILS}"
  57. fi
  58. usage() {
  59. cat <<'EOF'
  60. Usage:
  61. scripts/codex-loop.sh start <all|N|N-M> [--plan NAME] [--max-cycles N] [--pacing worker|ci|plateau|night] [--executor breezing|task] [--max-workers N|max]
  62. scripts/codex-loop.sh status [--json]
  63. scripts/codex-loop.sh stop
  64. scripts/codex-loop.sh run --run-id <id>
  65. scripts/codex-loop.sh run-cycle --run-id <id> --task-id <id> --cycle <n>
  66. scripts/codex-loop.sh local-task-worker --job-id <id>
  67. EOF
  68. }
  69. timestamp_utc() {
  70. date -u +"%Y-%m-%dT%H:%M:%SZ"
  71. }
  72. ensure_dirs() {
  73. mkdir -p "${LOOP_STATE_DIR}" "${LOCKS_DIR}" "${PROMPTS_DIR}" "${RESULTS_DIR}"
  74. mkdir -p "${TASK_JOBS_DIR}"
  75. if declare -F ensure_advisor_state_files >/dev/null 2>&1; then
  76. ensure_advisor_state_files
  77. fi
  78. }
  79. log_line() {
  80. ensure_dirs
  81. printf '[%s] %s\n' "$(timestamp_utc)" "$*" >> "${RUNNER_LOG}"
  82. }
  83. json_escape() {
  84. python3 - "$1" <<'PY'
  85. import json, sys
  86. print(json.dumps(sys.argv[1]))
  87. PY
  88. }
  89. python_json() {
  90. python3 - "$@"
  91. }
  92. run_state_patch() {
  93. local patch_json="$1"
  94. ensure_dirs
  95. python_json "${RUN_JSON}" "${patch_json}" <<'PY'
  96. import json
  97. import os
  98. import sys
  99. import tempfile
  100. path = sys.argv[1]
  101. patch = json.loads(sys.argv[2])
  102. data = {}
  103. if os.path.exists(path):
  104. with open(path, "r", encoding="utf-8") as fh:
  105. data = json.load(fh)
  106. def merge(left, right):
  107. for key, value in right.items():
  108. if isinstance(value, dict) and isinstance(left.get(key), dict):
  109. merge(left[key], value)
  110. else:
  111. left[key] = value
  112. merge(data, patch)
  113. parent = os.path.dirname(path) or "."
  114. fd, tmp_path = tempfile.mkstemp(prefix=".run-json-", suffix=".tmp", dir=parent)
  115. with os.fdopen(fd, "w", encoding="utf-8") as fh:
  116. json.dump(data, fh, ensure_ascii=False, indent=2)
  117. fh.write("\n")
  118. os.replace(tmp_path, path)
  119. PY
  120. }
  121. set_run_field() {
  122. local key="$1"
  123. local value_json="$2"
  124. run_state_patch "{\"${key}\": ${value_json}}"
  125. }
  126. json_get_file() {
  127. local file="$1"
  128. local path_expr="$2"
  129. local default_value="${3:-}"
  130. python_json "${file}" "${path_expr}" "${default_value}" <<'PY'
  131. import json
  132. import os
  133. import sys
  134. path = sys.argv[1]
  135. expr = sys.argv[2]
  136. default = sys.argv[3]
  137. if not os.path.exists(path):
  138. print(default)
  139. raise SystemExit(0)
  140. with open(path, "r", encoding="utf-8") as fh:
  141. data = json.load(fh)
  142. value = data
  143. for part in expr.split("."):
  144. if not part:
  145. continue
  146. if isinstance(value, dict) and part in value:
  147. value = value[part]
  148. else:
  149. print(default)
  150. raise SystemExit(0)
  151. if value is None:
  152. print(default)
  153. elif isinstance(value, bool):
  154. print("true" if value else "false")
  155. elif isinstance(value, (dict, list)):
  156. print(json.dumps(value, ensure_ascii=False))
  157. else:
  158. print(value)
  159. PY
  160. }
  161. append_jsonl() {
  162. local file="$1"
  163. local json_line="$2"
  164. ensure_dirs
  165. printf '%s\n' "${json_line}" >> "${file}"
  166. }
  167. plans_file_path() {
  168. if [ -n "${HARNESS_PLAN_FILE:-}" ]; then
  169. case "${HARNESS_PLAN_FILE}" in
  170. /*) printf '%s\n' "${HARNESS_PLAN_FILE}" ;;
  171. *) printf '%s\n' "${PROJECT_ROOT}/${HARNESS_PLAN_FILE}" ;;
  172. esac
  173. return 0
  174. fi
  175. local plans_file=""
  176. if [ -f "${CONFIG_UTILS}" ]; then
  177. plans_file="$(
  178. cd "${PROJECT_ROOT}" && \
  179. CONFIG_FILE="${PROJECT_ROOT}/.claude-code-harness.config.yaml" \
  180. source "${CONFIG_UTILS}" && \
  181. get_plans_file_path 2>/dev/null
  182. )" || plans_file=""
  183. if [ -n "${plans_file}" ] && [ ! -f "${plans_file}" ] && [ -f "${PROJECT_ROOT}/${plans_file}" ]; then
  184. plans_file="${PROJECT_ROOT}/${plans_file}"
  185. fi
  186. fi
  187. if [ -z "${plans_file}" ]; then
  188. if [ -f "${PROJECT_ROOT}/Plans.md" ]; then
  189. plans_file="${PROJECT_ROOT}/Plans.md"
  190. fi
  191. fi
  192. if [ -n "${plans_file}" ]; then
  193. case "${plans_file}" in
  194. /*) ;;
  195. *) plans_file="${PROJECT_ROOT}/${plans_file}" ;;
  196. esac
  197. fi
  198. printf '%s\n' "${plans_file}"
  199. }
  200. is_pid_alive() {
  201. local pid="${1:-}"
  202. [ -n "${pid}" ] || return 1
  203. kill -0 "${pid}" 2>/dev/null
  204. }
  205. terminate_process_tree() {
  206. local root_pid="${1:-}"
  207. local grace_sec="${CODEX_LOOP_CANCEL_GRACE_SEC:-1}"
  208. [ -n "${root_pid}" ] || return 1
  209. # macOS does not provide setsid by default, so cancel direct descendants too.
  210. python_json "${root_pid}" "${grace_sec}" <<'PY'
  211. import os
  212. import signal
  213. import subprocess
  214. import sys
  215. import time
  216. try:
  217. root = int(sys.argv[1])
  218. except (TypeError, ValueError):
  219. raise SystemExit(1)
  220. try:
  221. grace = float(sys.argv[2])
  222. except (TypeError, ValueError):
  223. grace = 1.0
  224. def pid_alive(pid):
  225. try:
  226. os.kill(pid, 0)
  227. return True
  228. except OSError:
  229. return False
  230. def process_tree(root_pid):
  231. try:
  232. output = subprocess.check_output(["ps", "-axo", "pid=,ppid="], text=True)
  233. except Exception:
  234. return []
  235. children = {}
  236. for raw_line in output.splitlines():
  237. parts = raw_line.split()
  238. if len(parts) < 2:
  239. continue
  240. try:
  241. pid, ppid = int(parts[0]), int(parts[1])
  242. except ValueError:
  243. continue
  244. children.setdefault(ppid, []).append(pid)
  245. result = []
  246. def visit(pid):
  247. for child in children.get(pid, []):
  248. visit(child)
  249. result.append(child)
  250. visit(root_pid)
  251. return result
  252. targets = process_tree(root) + [root]
  253. sent = False
  254. for pid in targets:
  255. try:
  256. os.kill(pid, signal.SIGTERM)
  257. sent = True
  258. except OSError:
  259. pass
  260. if sent and grace > 0:
  261. time.sleep(grace)
  262. for pid in targets:
  263. if not pid_alive(pid):
  264. continue
  265. try:
  266. os.kill(pid, signal.SIGKILL)
  267. except OSError:
  268. pass
  269. raise SystemExit(0 if sent else 1)
  270. PY
  271. }
  272. cleanup_stale_lock_if_needed() {
  273. if [ ! -d "${LOCK_DIR}" ]; then
  274. return 0
  275. fi
  276. local pid_file="${LOCK_DIR}/pid"
  277. local locked_pid=""
  278. if [ -f "${pid_file}" ]; then
  279. locked_pid="$(cat "${pid_file}" 2>/dev/null || true)"
  280. fi
  281. if [ -n "${locked_pid}" ] && is_pid_alive "${locked_pid}"; then
  282. return 1
  283. fi
  284. rm -rf "${LOCK_DIR}"
  285. return 0
  286. }
  287. acquire_lock() {
  288. ensure_dirs
  289. if mkdir "${LOCK_DIR}" 2>/dev/null; then
  290. printf '%s\n' "$$" > "${LOCK_DIR}/pid"
  291. return 0
  292. fi
  293. if cleanup_stale_lock_if_needed; then
  294. mkdir "${LOCK_DIR}"
  295. printf '%s\n' "$$" > "${LOCK_DIR}/pid"
  296. return 0
  297. fi
  298. return 1
  299. }
  300. release_lock() {
  301. rm -rf "${LOCK_DIR}" 2>/dev/null || true
  302. }
  303. runner_log_tail_one_line() {
  304. local max_lines="${1:-20}"
  305. if [ ! -f "${RUNNER_LOG}" ]; then
  306. return 0
  307. fi
  308. tail -n "${max_lines}" "${RUNNER_LOG}" 2>/dev/null \
  309. | tr '\n' ' ' \
  310. | sed 's/[[:space:]][[:space:]]*/ /g; s/^[[:space:]]*//; s/[[:space:]]*$//'
  311. }
  312. wait_for_runner_startup() {
  313. local runner_pid="$1"
  314. local checks="${CODEX_LOOP_STARTUP_CHECKS:-10}"
  315. local interval="${CODEX_LOOP_STARTUP_INTERVAL_SEC:-0.2}"
  316. local i=0
  317. while [ "${i}" -lt "${checks}" ]; do
  318. sleep "${interval}"
  319. if ! is_pid_alive "${runner_pid}"; then
  320. local status exit_reason
  321. status="$(json_get_file "${RUN_JSON}" "status" "")"
  322. exit_reason="$(json_get_file "${RUN_JSON}" "exit_reason" "")"
  323. if [ -s "${CYCLES_JSONL}" ] || [ -f "${CURRENT_JOB_JSON}" ]; then
  324. return 0
  325. fi
  326. case "${status}" in
  327. completed|stopped)
  328. return 0
  329. ;;
  330. failed)
  331. case "${exit_reason}" in
  332. task_blocked|pivot_required)
  333. return 0
  334. ;;
  335. esac
  336. ;;
  337. esac
  338. return 1
  339. fi
  340. i=$((i + 1))
  341. done
  342. return 0
  343. }
  344. delay_for_pacing() {
  345. local pacing="$1"
  346. case "${pacing}" in
  347. worker|ci) printf '270\n' ;;
  348. plateau) printf '1200\n' ;;
  349. night) printf '3600\n' ;;
  350. *) printf '270\n' ;;
  351. esac
  352. }
  353. normalize_selection() {
  354. local plans_file="$1"
  355. local selection="$2"
  356. python_json "${plans_file}" "${selection}" <<'PY'
  357. import pathlib
  358. import re
  359. import sys
  360. plans_path = sys.argv[1]
  361. selection = sys.argv[2].strip()
  362. HEADING_RE = re.compile(r"^\s{0,3}#{2,6}\s+(.+?)\s*$")
  363. TASK_ID_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9_.-]*)(?=\s|:|:|$)")
  364. LINE_REF_RE = re.compile(r"^(?P<path>.+):(?P<line>[0-9]+)$")
  365. def status_from_text(value):
  366. markers = (
  367. "cc:TODO",
  368. "cc:WIP",
  369. "cc:todo",
  370. "cc:wip",
  371. "cc:完了",
  372. "pm:確認済",
  373. "pm:依頼中",
  374. "cursor:依頼中",
  375. "cursor:確認済",
  376. "cc:done",
  377. "pm:approved",
  378. "pm:requested",
  379. "cc:blocked",
  380. "blocked",
  381. )
  382. for marker in markers:
  383. if marker == "blocked":
  384. if re.search(r"(?<![A-Za-z0-9_:.-])blocked(?![A-Za-z0-9_:.-])", value):
  385. return marker
  386. elif marker in value:
  387. return marker
  388. return ""
  389. def load_task_entries():
  390. entries = []
  391. lines = []
  392. with open(plans_path, "r", encoding="utf-8") as fh:
  393. for line_no, raw_line in enumerate(fh, start=1):
  394. lines.append(raw_line.rstrip("\n"))
  395. stripped = raw_line.strip()
  396. if stripped.startswith("|"):
  397. cells = [cell.strip() for cell in stripped.strip("|").split("|")]
  398. if len(cells) >= 2:
  399. task_id = cells[0]
  400. if task_id and task_id.lower() != "task" and not set(task_id) <= {"-"}:
  401. entries.append({"id": task_id, "line": line_no, "status": cells[-1] if cells else ""})
  402. continue
  403. heading = HEADING_RE.match(raw_line)
  404. if not heading:
  405. continue
  406. title = heading.group(1).strip()
  407. match = TASK_ID_RE.match(title)
  408. if not match:
  409. continue
  410. entries.append({"id": match.group(1), "line": line_no, "status": status_from_text(title)})
  411. return entries, lines
  412. def resolve_line_ref(entries, lines, token):
  413. match = LINE_REF_RE.match(token)
  414. if not match:
  415. return None
  416. ref_path = pathlib.Path(match.group("path"))
  417. plans = pathlib.Path(plans_path)
  418. if ref_path.name != plans.name:
  419. return None
  420. target_line = int(match.group("line"))
  421. exact = [entry for entry in entries if entry["line"] == target_line]
  422. if exact:
  423. return exact[0]["id"]
  424. following = [entry for entry in entries if entry["line"] >= target_line]
  425. previous = [entry for entry in entries if entry["line"] <= target_line]
  426. line_text = lines[target_line - 1].strip() if 1 <= target_line <= len(lines) else ""
  427. # Human line references are often copied from the blank line immediately
  428. # above a task heading. Treat that as selecting the following task.
  429. if not line_text and following and following[0]["line"] - target_line <= 3:
  430. return following[0]["id"]
  431. if previous:
  432. return previous[-1]["id"]
  433. if following:
  434. return following[0]["id"]
  435. return None
  436. def to_tuple(value):
  437. parts = []
  438. for item in value.split("."):
  439. try:
  440. parts.append(int(item))
  441. except ValueError:
  442. parts.append(item)
  443. return tuple(parts)
  444. def resolve_token(task_ids, token):
  445. if token in task_ids:
  446. return token
  447. lowered = token.lower()
  448. matches = [task_id for task_id in task_ids if task_id.lower() == lowered]
  449. if len(matches) == 1:
  450. return matches[0]
  451. raise ValueError(f"selection token not found in Plans.md: {token}")
  452. def resolve_range_endpoint(task_ids, token, side):
  453. """Resolve a range endpoint, accepting phase prefixes like 41.1 to mean
  454. 'first/last task whose ID starts with 41.1.'. Restores main-branch behavior
  455. where harness codex-loop start 41.1-41.4 traversed all 41.1.x..41.4.x tasks.
  456. """
  457. try:
  458. return resolve_token(task_ids, token)
  459. except ValueError:
  460. pass
  461. token_tuple = to_tuple(token)
  462. matching = [tid for tid in task_ids if to_tuple(tid)[: len(token_tuple)] == token_tuple]
  463. if not matching:
  464. raise ValueError(f"selection token not found in Plans.md: {token}")
  465. return matching[0] if side == "start" else matching[-1]
  466. entries, lines = load_task_entries()
  467. task_ids = [entry["id"] for entry in entries]
  468. if not task_ids:
  469. raise SystemExit("no task ids found in Plans.md")
  470. if selection == "all":
  471. print("all")
  472. raise SystemExit(0)
  473. line_ref = resolve_line_ref(entries, lines, selection)
  474. if line_ref:
  475. print(line_ref)
  476. raise SystemExit(0)
  477. try:
  478. print(resolve_token(task_ids, selection))
  479. raise SystemExit(0)
  480. except ValueError:
  481. pass
  482. range_parts = None
  483. if ".." in selection:
  484. range_parts = selection.split("..", 1)
  485. elif "-" in selection:
  486. range_parts = selection.split("-", 1)
  487. if range_parts is None:
  488. print(resolve_token(task_ids, selection))
  489. raise SystemExit(0)
  490. start_raw, end_raw = [part.strip() for part in range_parts]
  491. if not start_raw or not end_raw:
  492. raise SystemExit(f"invalid selection range: {selection}")
  493. start_id = resolve_range_endpoint(task_ids, start_raw, "start")
  494. end_id = resolve_range_endpoint(task_ids, end_raw, "end")
  495. start_index = task_ids.index(start_id)
  496. end_index = task_ids.index(end_id)
  497. if start_index > end_index:
  498. raise SystemExit(
  499. f"selection range is reversed in Plans.md order: {start_id}..{end_id}"
  500. )
  501. print(f"{start_id}..{end_id}")
  502. PY
  503. }
  504. selection_contains() {
  505. local selection="$1"
  506. local task_id="$2"
  507. python_json "${selection}" "${task_id}" <<'PY'
  508. import sys
  509. selection = sys.argv[1]
  510. task = sys.argv[2]
  511. def to_tuple(value):
  512. parts = []
  513. for item in value.split("."):
  514. try:
  515. parts.append(int(item))
  516. except ValueError:
  517. parts.append(item)
  518. return tuple(parts)
  519. if selection == "all":
  520. raise SystemExit(0)
  521. if selection == task:
  522. raise SystemExit(0)
  523. if ".." in selection:
  524. start, end = selection.split("..", 1)
  525. if to_tuple(start) <= to_tuple(task) <= to_tuple(end):
  526. raise SystemExit(0)
  527. raise SystemExit(1)
  528. if "-" in selection and selection != task:
  529. start, end = selection.split("-", 1)
  530. if to_tuple(start) <= to_tuple(task) <= to_tuple(end):
  531. raise SystemExit(0)
  532. raise SystemExit(1)
  533. raise SystemExit(0 if selection == task else 1)
  534. PY
  535. }
  536. next_task_id() {
  537. local selection="$1"
  538. local plans_file="$2"
  539. python_json "${plans_file}" "${selection}" <<'PY'
  540. import re
  541. import sys
  542. plans_path = sys.argv[1]
  543. selection = sys.argv[2]
  544. HEADING_RE = re.compile(r"^\s{0,3}#{2,6}\s+(.+?)\s*$")
  545. TASK_ID_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9_.-]*)(?=\s|:|:|$)")
  546. def status_from_text(value):
  547. markers = (
  548. "cc:TODO",
  549. "cc:WIP",
  550. "cc:todo",
  551. "cc:wip",
  552. "cc:完了",
  553. "pm:確認済",
  554. "pm:依頼中",
  555. "cursor:依頼中",
  556. "cursor:確認済",
  557. "cc:done",
  558. "pm:approved",
  559. "pm:requested",
  560. "cc:blocked",
  561. "blocked",
  562. )
  563. for marker in markers:
  564. if marker == "blocked":
  565. if re.search(r"(?<![A-Za-z0-9_:.-])blocked(?![A-Za-z0-9_:.-])", value):
  566. return marker
  567. elif marker in value:
  568. return marker
  569. return ""
  570. def has_any_status(value, markers):
  571. return any(marker in value for marker in markers)
  572. def parse_task_rows():
  573. rows = []
  574. with open(plans_path, "r", encoding="utf-8") as fh:
  575. for raw_line in fh:
  576. stripped = raw_line.strip()
  577. if stripped.startswith("|"):
  578. cells = [cell.strip() for cell in stripped.strip("|").split("|")]
  579. if len(cells) < 2:
  580. continue
  581. task_id = cells[0]
  582. if not task_id or task_id.lower() == "task" or set(task_id) <= {"-"}:
  583. continue
  584. rows.append((task_id, cells[-1]))
  585. continue
  586. heading = HEADING_RE.match(raw_line)
  587. if not heading:
  588. continue
  589. title = heading.group(1).strip()
  590. match = TASK_ID_RE.match(title)
  591. if match:
  592. rows.append((match.group(1), status_from_text(title)))
  593. return rows
  594. rows = parse_task_rows()
  595. ordered_ids = [task_id for task_id, _ in rows]
  596. if selection == "all":
  597. selected_ids = set(ordered_ids)
  598. elif ".." in selection:
  599. start, end = selection.split("..", 1)
  600. start = start.strip()
  601. end = end.strip()
  602. start_index = ordered_ids.index(start)
  603. end_index = ordered_ids.index(end)
  604. selected_ids = set(ordered_ids[start_index : end_index + 1])
  605. elif "-" in selection and selection not in ordered_ids:
  606. start, end = selection.split("-", 1)
  607. start = start.strip()
  608. end = end.strip()
  609. start_index = ordered_ids.index(start)
  610. end_index = ordered_ids.index(end)
  611. selected_ids = set(ordered_ids[start_index : end_index + 1])
  612. else:
  613. selected_ids = {selection}
  614. active_markers = ("cc:TODO", "cc:WIP", "cc:todo", "cc:wip", "pm:依頼中", "cursor:依頼中", "pm:requested")
  615. for task_id, status in rows:
  616. if task_id in selected_ids and has_any_status(status, active_markers):
  617. print(task_id)
  618. raise SystemExit(0)
  619. raise SystemExit(1)
  620. PY
  621. }
  622. next_ready_batch_ids() {
  623. local selection="$1"
  624. local plans_file="$2"
  625. local max_workers="${3:-max}"
  626. python_json "${plans_file}" "${selection}" "${max_workers}" <<'PY'
  627. import re
  628. import sys
  629. plans_path = sys.argv[1]
  630. selection = sys.argv[2]
  631. max_workers = sys.argv[3]
  632. HEADING_RE = re.compile(r"^\s{0,3}#{2,6}\s+(.+?)\s*$")
  633. TASK_ID_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9_.-]*)(?=\s|:|:|$)")
  634. def status_from_text(value):
  635. markers = (
  636. "cc:TODO",
  637. "cc:WIP",
  638. "cc:todo",
  639. "cc:wip",
  640. "cc:完了",
  641. "pm:確認済",
  642. "pm:依頼中",
  643. "cursor:依頼中",
  644. "cursor:確認済",
  645. "cc:done",
  646. "pm:approved",
  647. "pm:requested",
  648. "cc:blocked",
  649. "blocked",
  650. )
  651. for marker in markers:
  652. if marker == "blocked":
  653. if re.search(r"(?<![A-Za-z0-9_:.-])blocked(?![A-Za-z0-9_:.-])", value):
  654. return marker
  655. elif marker in value:
  656. return marker
  657. return ""
  658. def parse_rows():
  659. rows = []
  660. with open(plans_path, "r", encoding="utf-8") as fh:
  661. for raw_line in fh:
  662. stripped = raw_line.strip()
  663. if stripped.startswith("|"):
  664. cells = [cell.strip() for cell in stripped.strip("|").split("|")]
  665. if len(cells) < 2:
  666. continue
  667. task_id = cells[0]
  668. if not task_id or task_id.lower() == "task" or set(task_id) <= {"-"}:
  669. continue
  670. rows.append({
  671. "id": task_id,
  672. "depends": cells[-2] if len(cells) >= 5 else "-",
  673. "status": cells[-1],
  674. })
  675. continue
  676. heading = HEADING_RE.match(raw_line)
  677. if not heading:
  678. continue
  679. title = heading.group(1).strip()
  680. match = TASK_ID_RE.match(title)
  681. if match:
  682. rows.append({
  683. "id": match.group(1),
  684. "depends": "-",
  685. "status": status_from_text(title),
  686. })
  687. return rows
  688. def selected_ids(rows):
  689. ordered = [row["id"] for row in rows]
  690. if selection == "all":
  691. return set(ordered)
  692. if ".." in selection:
  693. start, end = [part.strip() for part in selection.split("..", 1)]
  694. return set(ordered[ordered.index(start): ordered.index(end) + 1])
  695. if "-" in selection and selection not in ordered:
  696. start, end = [part.strip() for part in selection.split("-", 1)]
  697. return set(ordered[ordered.index(start): ordered.index(end) + 1])
  698. return {selection}
  699. def is_complete(status):
  700. return any(marker in status for marker in ("cc:完了", "pm:確認済", "cursor:確認済", "cc:done", "pm:approved"))
  701. def is_active(status):
  702. return any(marker in status for marker in ("cc:TODO", "cc:WIP", "cc:todo", "cc:wip", "pm:依頼中", "cursor:依頼中", "pm:requested"))
  703. def depends_ready(depends, status_by_id):
  704. raw = (depends or "").strip()
  705. if not raw or raw == "-":
  706. return True
  707. for token in [part.strip() for part in raw.replace("、", ",").split(",") if part.strip()]:
  708. if token == "-":
  709. continue
  710. dep_status = status_by_id.get(token)
  711. if dep_status is None:
  712. # Phase-level or external dependency notation is not a concrete row.
  713. continue
  714. if not is_complete(dep_status):
  715. return False
  716. return True
  717. rows = parse_rows()
  718. selected = selected_ids(rows)
  719. status_by_id = {row["id"]: row["status"] for row in rows}
  720. ready = [
  721. row["id"]
  722. for row in rows
  723. if row["id"] in selected
  724. and is_active(row["status"])
  725. and depends_ready(row["depends"], status_by_id)
  726. ]
  727. if max_workers != "max":
  728. try:
  729. limit = int(max_workers)
  730. except ValueError:
  731. raise SystemExit(f"invalid --max-workers value: {max_workers}")
  732. if limit < 1:
  733. raise SystemExit("--max-workers must be >= 1 or max")
  734. ready = ready[:limit]
  735. if not ready:
  736. raise SystemExit(1)
  737. print(",".join(ready))
  738. PY
  739. }
  740. tasks_complete() {
  741. local plans_file="$1"
  742. local task_ids="$2"
  743. python_json "${plans_file}" "${task_ids}" <<'PY'
  744. import re
  745. import sys
  746. plans_path = sys.argv[1]
  747. targets = {item.strip() for item in sys.argv[2].split(",") if item.strip()}
  748. statuses = {}
  749. HEADING_RE = re.compile(r"^\s{0,3}#{2,6}\s+(.+?)\s*$")
  750. TASK_ID_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9_.-]*)(?=\s|:|:|$)")
  751. def status_from_text(value):
  752. markers = (
  753. "cc:TODO",
  754. "cc:WIP",
  755. "cc:todo",
  756. "cc:wip",
  757. "cc:完了",
  758. "pm:確認済",
  759. "pm:依頼中",
  760. "cursor:依頼中",
  761. "cursor:確認済",
  762. "cc:done",
  763. "pm:approved",
  764. "pm:requested",
  765. "cc:blocked",
  766. "blocked",
  767. )
  768. for marker in markers:
  769. if marker == "blocked":
  770. if re.search(r"(?<![A-Za-z0-9_:.-])blocked(?![A-Za-z0-9_:.-])", value):
  771. return marker
  772. elif marker in value:
  773. return marker
  774. return ""
  775. with open(plans_path, "r", encoding="utf-8") as fh:
  776. for raw_line in fh:
  777. stripped = raw_line.strip()
  778. if stripped.startswith("|"):
  779. cells = [cell.strip() for cell in stripped.strip("|").split("|")]
  780. if len(cells) < 2:
  781. continue
  782. task_id = cells[0]
  783. if task_id in targets:
  784. statuses[task_id] = cells[-1]
  785. continue
  786. heading = HEADING_RE.match(raw_line)
  787. if not heading:
  788. continue
  789. title = heading.group(1).strip()
  790. match = TASK_ID_RE.match(title)
  791. if match and match.group(1) in targets:
  792. statuses[match.group(1)] = status_from_text(title)
  793. missing = targets - statuses.keys()
  794. if missing:
  795. raise SystemExit(1)
  796. for task_id in targets:
  797. status = statuses.get(task_id, "")
  798. if not any(marker in status for marker in ("cc:完了", "pm:確認済", "cursor:確認済", "cc:done", "pm:approved")):
  799. raise SystemExit(1)
  800. raise SystemExit(0)
  801. PY
  802. }
  803. task_status_value() {
  804. local plans_file="$1"
  805. local task_id="$2"
  806. python_json "${plans_file}" "${task_id}" <<'PY'
  807. import re
  808. import sys
  809. plans_path = sys.argv[1]
  810. target = sys.argv[2]
  811. HEADING_RE = re.compile(r"^\s{0,3}#{2,6}\s+(.+?)\s*$")
  812. TASK_ID_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9_.-]*)(?=\s|:|:|$)")
  813. def status_from_text(value):
  814. markers = (
  815. "cc:TODO",
  816. "cc:WIP",
  817. "cc:todo",
  818. "cc:wip",
  819. "cc:完了",
  820. "pm:確認済",
  821. "pm:依頼中",
  822. "cursor:依頼中",
  823. "cursor:確認済",
  824. "cc:done",
  825. "pm:approved",
  826. "pm:requested",
  827. "cc:blocked",
  828. "blocked",
  829. )
  830. for marker in markers:
  831. if marker == "blocked":
  832. if re.search(r"(?<![A-Za-z0-9_:.-])blocked(?![A-Za-z0-9_:.-])", value):
  833. return marker
  834. elif marker in value:
  835. return marker
  836. return ""
  837. with open(plans_path, "r", encoding="utf-8") as fh:
  838. for raw_line in fh:
  839. stripped = raw_line.strip()
  840. if stripped.startswith("|"):
  841. cells = [cell.strip() for cell in stripped.strip("|").split("|")]
  842. if len(cells) < 2:
  843. continue
  844. task_id = cells[0]
  845. if not task_id or task_id.lower() == "task" or set(task_id) <= {"-"}:
  846. continue
  847. if task_id != target:
  848. continue
  849. print(cells[-1])
  850. raise SystemExit(0)
  851. heading = HEADING_RE.match(raw_line)
  852. if not heading:
  853. continue
  854. title = heading.group(1).strip()
  855. match = TASK_ID_RE.match(title)
  856. if match and match.group(1) == target:
  857. print(status_from_text(title))
  858. raise SystemExit(0)
  859. raise SystemExit(1)
  860. PY
  861. }
  862. task_title_from_contract() {
  863. local contract_file="$1"
  864. json_get_file "${contract_file}" "task.title" ""
  865. }
  866. stop_requested() {
  867. [ -f "${RUN_JSON}" ] || return 1
  868. local stop_at
  869. stop_at="$(json_get_file "${RUN_JSON}" "stop_requested_at" "")"
  870. [ -n "${stop_at}" ]
  871. }
  872. companion_status_json() {
  873. local job_id="$1"
  874. if [ "$(codex_loop_task_driver)" = "companion" ]; then
  875. bash "$(codex_loop_companion_path)" status "${job_id}" --json
  876. return $?
  877. fi
  878. local_task_status_json "${job_id}"
  879. }
  880. companion_result_json() {
  881. local job_id="$1"
  882. if [ "$(codex_loop_task_driver)" = "companion" ]; then
  883. bash "$(codex_loop_companion_path)" result "${job_id}" --json
  884. return $?
  885. fi
  886. local_task_result_json "${job_id}"
  887. }
  888. companion_cancel_json() {
  889. local job_id="$1"
  890. if [ "$(codex_loop_task_driver)" = "companion" ]; then
  891. bash "$(codex_loop_companion_path)" cancel "${job_id}" --json
  892. return $?
  893. fi
  894. local_task_cancel_json "${job_id}"
  895. }
  896. codex_loop_task_driver() {
  897. local driver="${CODEX_LOOP_TASK_DRIVER:-}"
  898. if [ -z "${driver}" ] && [ -f "${RUN_JSON}" ]; then
  899. driver="$(json_get_file "${RUN_JSON}" "task_driver" "" 2>/dev/null || true)"
  900. fi
  901. if [ -z "${driver}" ] && [ -f "${CURRENT_JOB_JSON}" ]; then
  902. driver="$(json_get_file "${CURRENT_JOB_JSON}" "task_driver" "" 2>/dev/null || true)"
  903. fi
  904. printf '%s\n' "${driver:-local}"
  905. }
  906. codex_loop_companion_path() {
  907. local companion_path="${CODEX_LOOP_COMPANION:-}"
  908. if [ -z "${companion_path}" ] && [ -f "${RUN_JSON}" ]; then
  909. companion_path="$(json_get_file "${RUN_JSON}" "companion_path" "" 2>/dev/null || true)"
  910. fi
  911. if [ -z "${companion_path}" ] && [ -f "${CURRENT_JOB_JSON}" ]; then
  912. companion_path="$(json_get_file "${CURRENT_JOB_JSON}" "companion_path" "" 2>/dev/null || true)"
  913. fi
  914. printf '%s\n' "${companion_path:-${COMPANION}}"
  915. }
  916. job_status_is_terminal() {
  917. case "${1:-}" in
  918. completed|done|failed|cancelled|missing) return 0 ;;
  919. *) return 1 ;;
  920. esac
  921. }
  922. current_job_id_from_state() {
  923. local job_id=""
  924. job_id="$(json_get_file "${RUN_JSON}" "current_job_id" "" 2>/dev/null || true)"
  925. if [ -z "${job_id}" ] && [ -f "${CURRENT_JOB_JSON}" ]; then
  926. job_id="$(json_get_file "${CURRENT_JOB_JSON}" "job_id" "" 2>/dev/null || true)"
  927. fi
  928. if [ -z "${job_id}" ] && [ -f "${CURRENT_JOB_JSON}" ]; then
  929. job_id="$(json_get_file "${CURRENT_JOB_JSON}" "id" "" 2>/dev/null || true)"
  930. fi
  931. printf '%s\n' "${job_id}"
  932. }
  933. current_job_status_from_state() {
  934. local job_status=""
  935. job_status="$(json_get_file "${RUN_JSON}" "current_job_status" "" 2>/dev/null || true)"
  936. if [ -z "${job_status}" ] && [ -f "${CURRENT_JOB_JSON}" ]; then
  937. job_status="$(json_get_file "${CURRENT_JOB_JSON}" "status" "" 2>/dev/null || true)"
  938. fi
  939. printf '%s\n' "${job_status}"
  940. }
  941. current_job_live_status() {
  942. local job_id="$1"
  943. local status_json status_payload status
  944. status_json="$(companion_status_json "${job_id}" 2>> "${RUNNER_LOG}" || true)"
  945. status_payload="${status_json}"
  946. [ -n "${status_payload}" ] || status_payload='{}'
  947. status="$(python_json 3<<<"${status_payload}" <<'PY'
  948. import json
  949. import sys
  950. try:
  951. with open(3, encoding="utf-8") as fh:
  952. payload = json.load(fh)
  953. except json.JSONDecodeError:
  954. payload = {}
  955. job = payload.get("job", {}) or {}
  956. print(job.get("status", ""))
  957. PY
  958. )"
  959. if [ -n "${status}" ]; then
  960. printf '%s\n' "${status}"
  961. return 0
  962. fi
  963. current_job_status_from_state
  964. }
  965. cancel_current_job_if_active() {
  966. local reason="${1:-runner_exit}"
  967. local job_id job_status cancel_status
  968. job_id="$(current_job_id_from_state)"
  969. [ -n "${job_id}" ] || return 0
  970. job_status="$(current_job_live_status "${job_id}")"
  971. if job_status_is_terminal "${job_status}"; then
  972. return 0
  973. fi
  974. log_line "cancelling active job ${job_id}: ${reason}"
  975. cancel_status=0
  976. companion_cancel_json "${job_id}" >> "${RUNNER_LOG}" 2>&1 || cancel_status=$?
  977. local recorded_status recorded_phase
  978. if [ "${cancel_status}" -eq 0 ]; then
  979. recorded_status="cancelled"
  980. recorded_phase="cancelled"
  981. else
  982. recorded_status="cancel_failed"
  983. recorded_phase="cancel_failed"
  984. fi
  985. run_state_patch "$(cat <<EOF
  986. {
  987. "updated_at": $(json_escape "$(timestamp_utc)"),
  988. "current_job_status": $(json_escape "${recorded_status}"),
  989. "current_job_phase": $(json_escape "${recorded_phase}"),
  990. "last_cancelled_job_id": $(json_escape "${job_id}"),
  991. "last_cancel_reason": $(json_escape "${reason}"),
  992. "last_cancel_exit_status": ${cancel_status}
  993. }
  994. EOF
  995. )"
  996. return "${cancel_status}"
  997. }
  998. runner_exit_trap() {
  999. local exit_code="${1:-0}"
  1000. local scope="${2:-runner}"
  1001. set +e
  1002. if [ "${exit_code}" -eq 0 ] || [ "${RUNNER_FINALIZED:-0}" = "1" ]; then
  1003. if [ "${scope}" = "run" ]; then
  1004. release_lock
  1005. fi
  1006. return 0
  1007. fi
  1008. local job_id error_message
  1009. job_id="$(current_job_id_from_state)"
  1010. if [ -n "${job_id}" ]; then
  1011. cancel_current_job_if_active "runner_exit:${scope}:exit_${exit_code}" || true
  1012. error_message="codex-loop ${scope} exited unexpectedly (exit=${exit_code}) while job ${job_id} was active; cancellation requested"
  1013. run_state_patch "$(cat <<EOF
  1014. {
  1015. "status": "failed",
  1016. "exit_reason": "runner_exit",
  1017. "pid": null,
  1018. "finished_at": $(json_escape "$(timestamp_utc)"),
  1019. "updated_at": $(json_escape "$(timestamp_utc)"),
  1020. "error_message": $(json_escape "${error_message}")
  1021. }
  1022. EOF
  1023. )"
  1024. log_line "${error_message}"
  1025. fi
  1026. if [ "${scope}" = "run" ]; then
  1027. release_lock
  1028. fi
  1029. return 0
  1030. }
  1031. start_background_task() {
  1032. local prompt_file="$1"
  1033. if [ "$(codex_loop_task_driver)" = "companion" ]; then
  1034. bash "$(codex_loop_companion_path)" task --background --write --json --prompt-file "${prompt_file}"
  1035. return $?
  1036. fi
  1037. local_task_start_json "${prompt_file}"
  1038. }
  1039. local_task_job_file() {
  1040. printf '%s\n' "${TASK_JOBS_DIR}/$1.json"
  1041. }
  1042. local_task_log_file() {
  1043. printf '%s\n' "${TASK_JOBS_DIR}/$1.log"
  1044. }
  1045. local_task_output_file() {
  1046. printf '%s\n' "${TASK_JOBS_DIR}/$1.out"
  1047. }
  1048. local_task_summary() {
  1049. local prompt_file="$1"
  1050. python_json "${prompt_file}" <<'PY'
  1051. import pathlib
  1052. import sys
  1053. path = pathlib.Path(sys.argv[1])
  1054. if not path.exists():
  1055. print("Codex loop task")
  1056. raise SystemExit(0)
  1057. for raw_line in path.read_text(encoding="utf-8").splitlines():
  1058. line = raw_line.strip()
  1059. if line:
  1060. print(line[:120])
  1061. raise SystemExit(0)
  1062. print("Codex loop task")
  1063. PY
  1064. }
  1065. local_task_write_record() {
  1066. local job_file="$1"
  1067. local payload_json="$2"
  1068. printf '%s\n' "${payload_json}" > "${job_file}"
  1069. }
  1070. local_task_mark_crashed_if_needed() {
  1071. local job_id="$1"
  1072. local job_file
  1073. job_file="$(local_task_job_file "${job_id}")"
  1074. [ -f "${job_file}" ] || return 0
  1075. python_json "${job_file}" <<'PY'
  1076. import json
  1077. import os
  1078. import signal
  1079. import sys
  1080. job_file = sys.argv[1]
  1081. with open(job_file, "r", encoding="utf-8") as fh:
  1082. job = json.load(fh)
  1083. if job.get("status") not in {"queued", "running"}:
  1084. raise SystemExit(0)
  1085. pid = job.get("pid")
  1086. child_pid = job.get("childPid")
  1087. if not pid:
  1088. job["status"] = "failed"
  1089. job["phase"] = "failed"
  1090. job["errorMessage"] = "Loop worker terminated before recording a pid."
  1091. else:
  1092. try:
  1093. os.kill(int(pid), 0)
  1094. raise SystemExit(0)
  1095. except OSError:
  1096. if child_pid:
  1097. try:
  1098. os.kill(int(child_pid), signal.SIGTERM)
  1099. except OSError:
  1100. pass
  1101. job["status"] = "failed"
  1102. job["phase"] = "failed"
  1103. job["pid"] = None
  1104. job["childPid"] = None
  1105. job["errorMessage"] = "Loop worker process exited unexpectedly."
  1106. with open(job_file, "w", encoding="utf-8") as fh:
  1107. json.dump(job, fh, ensure_ascii=False, indent=2)
  1108. fh.write("\n")
  1109. PY
  1110. }
  1111. local_task_start_json() {
  1112. local prompt_file="$1"
  1113. local job_id="task-$(date +%Y%m%d%H%M%S)-$$"
  1114. local job_file log_file output_file summary
  1115. job_file="$(local_task_job_file "${job_id}")"
  1116. log_file="$(local_task_log_file "${job_id}")"
  1117. output_file="$(local_task_output_file "${job_id}")"
  1118. summary="$(local_task_summary "${prompt_file}")"
  1119. : > "${log_file}"
  1120. : > "${output_file}"
  1121. append_jsonl "${log_file}" "[local-task] queued"
  1122. local_task_write_record "${job_file}" "$(cat <<EOF
  1123. {
  1124. "id": $(json_escape "${job_id}"),
  1125. "status": "queued",
  1126. "phase": "queued",
  1127. "title": "Codex Task",
  1128. "summary": $(json_escape "${summary}"),
  1129. "workspaceRoot": $(json_escape "${PROJECT_ROOT}"),
  1130. "jobClass": "task",
  1131. "write": true,
  1132. "logFile": $(json_escape "${log_file}"),
  1133. "request": {
  1134. "cwd": $(json_escape "${PROJECT_ROOT}"),
  1135. "promptFile": $(json_escape "${prompt_file}")
  1136. }
  1137. }
  1138. EOF
  1139. )"
  1140. nohup bash "${SELF_SCRIPT}" local-task-worker --job-id "${job_id}" >> "${log_file}" 2>&1 &
  1141. local worker_pid=$!
  1142. python_json "${job_file}" "${worker_pid}" <<'PY'
  1143. import json
  1144. import sys
  1145. job_file = sys.argv[1]
  1146. pid = int(sys.argv[2])
  1147. with open(job_file, "r", encoding="utf-8") as fh:
  1148. job = json.load(fh)
  1149. job["pid"] = pid
  1150. job["childPid"] = None
  1151. with open(job_file, "w", encoding="utf-8") as fh:
  1152. json.dump(job, fh, ensure_ascii=False, indent=2)
  1153. fh.write("\n")
  1154. PY
  1155. python_json "${job_id}" "${log_file}" "${summary}" <<'PY'
  1156. import json
  1157. import sys
  1158. job_id, log_file, summary = sys.argv[1:4]
  1159. print(json.dumps({
  1160. "jobId": job_id,
  1161. "status": "queued",
  1162. "title": "Codex Task",
  1163. "summary": summary,
  1164. "logFile": log_file,
  1165. }, ensure_ascii=False))
  1166. PY
  1167. }
  1168. local_task_status_json() {
  1169. local job_id="$1"
  1170. local job_file
  1171. job_file="$(local_task_job_file "${job_id}")"
  1172. [ -f "${job_file}" ] || {
  1173. printf '{"job":{"id":%s,"status":"missing","phase":"missing"}}\n' "$(json_escape "${job_id}")"
  1174. return 0
  1175. }
  1176. local_task_mark_crashed_if_needed "${job_id}"
  1177. python_json "${job_file}" <<'PY'
  1178. import json
  1179. import sys
  1180. with open(sys.argv[1], "r", encoding="utf-8") as fh:
  1181. job = json.load(fh)
  1182. print(json.dumps({"job": job}, ensure_ascii=False))
  1183. PY
  1184. }
  1185. local_task_result_json() {
  1186. local job_id="$1"
  1187. local job_file
  1188. job_file="$(local_task_job_file "${job_id}")"
  1189. [ -f "${job_file}" ] || {
  1190. printf '{"storedJob":{"id":%s,"status":"missing","phase":"missing"}}\n' "$(json_escape "${job_id}")"
  1191. return 0
  1192. }
  1193. local_task_mark_crashed_if_needed "${job_id}"
  1194. python_json "${job_file}" <<'PY'
  1195. import json
  1196. import sys
  1197. with open(sys.argv[1], "r", encoding="utf-8") as fh:
  1198. job = json.load(fh)
  1199. print(json.dumps({"storedJob": job}, ensure_ascii=False))
  1200. PY
  1201. }
  1202. local_task_cancel_json() {
  1203. local job_id="$1"
  1204. local job_file
  1205. job_file="$(local_task_job_file "${job_id}")"
  1206. [ -f "${job_file}" ] || {
  1207. printf '{"jobId":%s,"cancelled":false,"reason":"missing"}\n' "$(json_escape "${job_id}")"
  1208. return 0
  1209. }
  1210. local worker_pid child_pid cancelled reason
  1211. worker_pid="$(json_get_file "${job_file}" "pid" "")"
  1212. child_pid="$(json_get_file "${job_file}" "childPid" "")"
  1213. cancelled="false"
  1214. reason="not-running"
  1215. if [ -n "${child_pid}" ] && terminate_process_tree "${child_pid}"; then
  1216. cancelled="true"
  1217. reason="signal_sent"
  1218. fi
  1219. if [ -n "${worker_pid}" ]; then
  1220. if kill -TERM "${worker_pid}" 2>/dev/null; then
  1221. cancelled="true"
  1222. reason="signal_sent"
  1223. elif [ "${cancelled}" != "true" ]; then
  1224. reason="already-exited"
  1225. fi
  1226. fi
  1227. python_json "${job_file}" "${cancelled}" "${reason}" <<'PY'
  1228. import json
  1229. import sys
  1230. job_file = sys.argv[1]
  1231. cancelled = sys.argv[2] == "true"
  1232. reason = sys.argv[3]
  1233. with open(job_file, "r", encoding="utf-8") as fh:
  1234. job = json.load(fh)
  1235. job["status"] = "cancelled"
  1236. job["phase"] = "cancelled"
  1237. job["pid"] = None
  1238. job["childPid"] = None
  1239. with open(job_file, "w", encoding="utf-8") as fh:
  1240. json.dump(job, fh, ensure_ascii=False, indent=2)
  1241. fh.write("\n")
  1242. print(json.dumps({
  1243. "jobId": job.get("id"),
  1244. "cancelled": cancelled,
  1245. "reason": reason,
  1246. }, ensure_ascii=False))
  1247. PY
  1248. }
  1249. run_local_task_worker() {
  1250. local job_id=""
  1251. while [ $# -gt 0 ]; do
  1252. case "$1" in
  1253. --job-id)
  1254. job_id="${2:-}"
  1255. shift 2
  1256. ;;
  1257. *)
  1258. echo "Unknown option: $1" >&2
  1259. exit 2
  1260. ;;
  1261. esac
  1262. done
  1263. [ -n "${job_id}" ] || {
  1264. echo "local-task-worker requires --job-id" >&2
  1265. exit 2
  1266. }
  1267. local job_file log_file output_file
  1268. job_file="$(local_task_job_file "${job_id}")"
  1269. [ -f "${job_file}" ] || {
  1270. echo "job file not found: ${job_id}" >&2
  1271. exit 1
  1272. }
  1273. log_file="$(local_task_log_file "${job_id}")"
  1274. output_file="$(local_task_output_file "${job_id}")"
  1275. local prompt_file
  1276. prompt_file="$(json_get_file "${job_file}" "request.promptFile" "")"
  1277. [ -f "${prompt_file}" ] || {
  1278. local_task_write_record "${job_file}" "$(cat <<EOF
  1279. {
  1280. "id": $(json_escape "${job_id}"),
  1281. "status": "failed",
  1282. "phase": "failed",
  1283. "title": "Codex Task",
  1284. "summary": "Missing prompt file",
  1285. "workspaceRoot": $(json_escape "${PROJECT_ROOT}"),
  1286. "jobClass": "task",
  1287. "write": true,
  1288. "logFile": $(json_escape "${log_file}"),
  1289. "errorMessage": "Prompt file missing: ${prompt_file}"
  1290. }
  1291. EOF
  1292. )"
  1293. exit 1
  1294. }
  1295. python_json "${job_file}" "$$" <<'PY'
  1296. import json
  1297. import sys
  1298. from datetime import datetime, timezone
  1299. job_file = sys.argv[1]
  1300. pid = int(sys.argv[2])
  1301. with open(job_file, "r", encoding="utf-8") as fh:
  1302. job = json.load(fh)
  1303. job["status"] = "running"
  1304. job["phase"] = "running"
  1305. job["pid"] = pid
  1306. job["childPid"] = None
  1307. job["startedAt"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
  1308. with open(job_file, "w", encoding="utf-8") as fh:
  1309. json.dump(job, fh, ensure_ascii=False, indent=2)
  1310. fh.write("\n")
  1311. PY
  1312. printf '[%s] local task worker started: %s\n' "$(timestamp_utc)" "${job_id}" >> "${log_file}"
  1313. local exit_code=0
  1314. local child_pid=""
  1315. local worker_cancelled=0
  1316. terminate_child() {
  1317. worker_cancelled=1
  1318. if [ -n "${child_pid}" ]; then
  1319. printf '[%s] local task worker terminating child: %s\n' "$(timestamp_utc)" "${child_pid}" >> "${log_file}"
  1320. terminate_process_tree "${child_pid}" || true
  1321. fi
  1322. }
  1323. trap 'terminate_child' TERM INT
  1324. # Local mode inherits the invoking Codex profile's model and reasoning effort.
  1325. # Role defaults are selected by the companion driver, not by this local path.
  1326. codex exec - --dangerously-bypass-approvals-and-sandbox < "${prompt_file}" > "${output_file}" 2>> "${log_file}" &
  1327. child_pid=$!
  1328. python_json "${job_file}" "${child_pid}" <<'PY'
  1329. import json
  1330. import sys
  1331. job_file = sys.argv[1]
  1332. child_pid = int(sys.argv[2])
  1333. with open(job_file, "r", encoding="utf-8") as fh:
  1334. job = json.load(fh)
  1335. job["childPid"] = child_pid
  1336. with open(job_file, "w", encoding="utf-8") as fh:
  1337. json.dump(job, fh, ensure_ascii=False, indent=2)
  1338. fh.write("\n")
  1339. PY
  1340. set +e
  1341. wait "${child_pid}"
  1342. exit_code=$?
  1343. set -e
  1344. trap - TERM INT
  1345. child_pid=""
  1346. if [ "${worker_cancelled}" -eq 1 ] && [ "${exit_code}" -eq 0 ]; then
  1347. exit_code=143
  1348. fi
  1349. python_json "${job_file}" "${output_file}" "${exit_code}" <<'PY'
  1350. import json
  1351. import pathlib
  1352. import sys
  1353. from datetime import datetime, timezone
  1354. job_file = pathlib.Path(sys.argv[1])
  1355. output_file = pathlib.Path(sys.argv[2])
  1356. exit_code = int(sys.argv[3])
  1357. with job_file.open("r", encoding="utf-8") as fh:
  1358. job = json.load(fh)
  1359. raw_output = output_file.read_text(encoding="utf-8") if output_file.exists() else ""
  1360. was_cancelled = job.get("status") == "cancelled"
  1361. if was_cancelled:
  1362. job["status"] = "cancelled"
  1363. job["phase"] = "cancelled"
  1364. else:
  1365. job["status"] = "completed" if exit_code == 0 else "failed"
  1366. job["phase"] = "done" if exit_code == 0 else "failed"
  1367. job["pid"] = None
  1368. job["childPid"] = None
  1369. job["completedAt"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
  1370. job["result"] = {
  1371. "status": exit_code,
  1372. "rawOutput": raw_output,
  1373. "touchedFiles": [],
  1374. "reasoningSummary": [],
  1375. }
  1376. job["rendered"] = raw_output
  1377. if exit_code != 0 and not was_cancelled:
  1378. job["errorMessage"] = f"codex exec exited with status {exit_code}"
  1379. with job_file.open("w", encoding="utf-8") as fh:
  1380. json.dump(job, fh, ensure_ascii=False, indent=2)
  1381. fh.write("\n")
  1382. PY
  1383. printf '[%s] local task worker finished: %s (exit=%s)\n' "$(timestamp_utc)" "${job_id}" "${exit_code}" >> "${log_file}"
  1384. return "${exit_code}"
  1385. }
  1386. resume_pack_best_effort() {
  1387. RESUME_EVIDENCE_JSON='[]'
  1388. if [ ! -x "${MEM_CLIENT}" ]; then
  1389. log_line "resume-pack skipped: harness-mem client not executable"
  1390. return 0
  1391. fi
  1392. local output project_key request_json
  1393. project_key="$(basename "$(cd "${PROJECT_ROOT}" && pwd)")"
  1394. request_json="$(python_json "${project_key}" <<'PY'
  1395. import json, sys
  1396. print(json.dumps({"project": sys.argv[1], "limit": 5, "include_private": False,
  1397. "detail_level": "L0", "resume_pack_max_tokens": 1200}))
  1398. PY
  1399. )"
  1400. if output="$(printf '%s' "${request_json}" | "${MEM_CLIENT}" resume-pack 2>> "${RUNNER_LOG}")"; then
  1401. RESUME_EVIDENCE_JSON="$(python_json "${output}" "${project_key}" <<'PY'
  1402. import json, sys
  1403. try:
  1404. payload = json.loads(sys.argv[1])
  1405. except json.JSONDecodeError:
  1406. payload = {}
  1407. # Aggregate summaries do not identify the project of every source item.
  1408. items = payload.get("items", []) if isinstance(payload, dict) and payload.get("ok") is True else []
  1409. if not isinstance(items, list):
  1410. items = []
  1411. print(json.dumps([item for item in items if isinstance(item, dict)
  1412. and item.get("project") == sys.argv[2]][:5], ensure_ascii=False))
  1413. PY
  1414. )"
  1415. log_line "resume-pack refreshed for project=${project_key}"
  1416. else
  1417. log_line "resume-pack unavailable for project=${project_key}"
  1418. fi
  1419. }
  1420. execution_context_json() {
  1421. local task_ids="$1"
  1422. local contract_path="${2:-}"
  1423. python_json "${PROJECT_ROOT}" "$(plans_file_path)" "${task_ids}" "${contract_path}" "${RESUME_EVIDENCE_JSON:-[]}" <<'PY'
  1424. import json
  1425. import pathlib
  1426. import re
  1427. import sys
  1428. project = pathlib.Path(sys.argv[1]).resolve()
  1429. plans = pathlib.Path(sys.argv[2])
  1430. task_ids = [item.strip() for item in sys.argv[3].split(",") if item.strip()]
  1431. explicit_contract = sys.argv[4]
  1432. rows, background = [], []
  1433. sections = [(0, [])]
  1434. table_header = ""
  1435. if plans.is_file():
  1436. for number, line in enumerate(plans.read_text(encoding="utf-8").splitlines(), 1):
  1437. heading = re.match(r"^(#{1,6})\s+", line)
  1438. if heading:
  1439. level = len(heading[1])
  1440. while sections[-1][0] >= level:
  1441. sections.pop()
  1442. sections.append((level, [line]))
  1443. elif line.lstrip().startswith("|"):
  1444. cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
  1445. if cells[0].lower() in {"task", "id", "タスク"}:
  1446. table_header = line
  1447. if cells[0] in task_ids:
  1448. rows.append({"line": number, "header": table_header, "row": line})
  1449. for _, context_lines in sections:
  1450. text = "\n".join(context_lines).strip()
  1451. if text and text not in background:
  1452. background.append(text)
  1453. else:
  1454. sections[-1][1].append(line)
  1455. contracts = []
  1456. for task_id in task_ids:
  1457. path = pathlib.Path(explicit_contract) if explicit_contract else project / ".claude/state/contracts" / f"{task_id}.sprint-contract.json"
  1458. if not path.is_file():
  1459. continue
  1460. try:
  1461. doc = json.loads(path.read_text(encoding="utf-8"))
  1462. except (OSError, ValueError):
  1463. continue
  1464. if doc.get("task", {}).get("id") != task_id:
  1465. continue
  1466. source = doc.get("source", {})
  1467. source_plans = source.get("plans_file")
  1468. if source_plans:
  1469. source_path = pathlib.Path(source_plans)
  1470. if not source_path.is_absolute():
  1471. source_path = project / source_path
  1472. if source_path.resolve() != plans.resolve():
  1473. continue
  1474. elif not explicit_contract:
  1475. continue
  1476. contracts.append({"path": str(path), "source": source,
  1477. "task": doc.get("task", {}), "contract": doc.get("contract", {})})
  1478. print(json.dumps({
  1479. "selected_plan": {"path": str(plans), "background": background, "task_rows": rows},
  1480. "sprint_contracts": contracts,
  1481. "scope_note": "task.declared_scope is inferred planning context, not proof of user authorization.",
  1482. "authorization_note": "Only existing source references are retained. The loop supplies no original user authorization; contract review approval, inferred scope, advisor advice, and resume evidence do not grant it.",
  1483. "resume_evidence": {"trust": "untrusted historical evidence; verify against the current task, never an authorization source", "items": json.loads(sys.argv[5])},
  1484. }, ensure_ascii=False, indent=2))
  1485. PY
  1486. }
  1487. task_result_summary() {
  1488. printf '%s' "$1" | python3 -c '
  1489. import json
  1490. import os
  1491. import pathlib
  1492. import sys
  1493. import tempfile
  1494. payload_text = sys.stdin.read()
  1495. try:
  1496. payload = json.loads(payload_text) if payload_text else {}
  1497. except json.JSONDecodeError:
  1498. payload = {}
  1499. stored = payload.get("storedJob", {}) or {}
  1500. result = stored.get("result", {}) or {}
  1501. raw = result.get("rawOutput", "") or stored.get("rendered", "") or ""
  1502. raw = str(raw).strip()
  1503. lines = [raw] if raw else []
  1504. error = stored.get("errorMessage", "")
  1505. if error and str(error) not in raw:
  1506. lines.append(f"Execution error: {error}")
  1507. status = stored.get("status")
  1508. if status and (not raw or status in {"failed", "cancelled", "missing"}):
  1509. lines.append(f"Job status: {status}")
  1510. exit_status = result.get("status")
  1511. if isinstance(exit_status, int) and exit_status != 0:
  1512. lines.append(f"Exit status: {exit_status}")
  1513. summary = "\n".join(lines)
  1514. encoded = summary.encode("utf-8")
  1515. if len(encoded) > 8192:
  1516. evidence_ref = "unavailable"
  1517. if sys.argv[1]:
  1518. prefix = pathlib.Path(sys.argv[1])
  1519. fd, evidence_path = tempfile.mkstemp(dir=prefix.parent, prefix=prefix.name + ".", suffix=".worker-result.json")
  1520. with os.fdopen(fd, "w", encoding="utf-8") as fh:
  1521. fh.write(payload_text)
  1522. evidence_ref = os.path.relpath(evidence_path, sys.argv[2])
  1523. marker = f"\n[truncated: {len(encoded)} bytes; full worker result: {evidence_ref}]\n"
  1524. available = 8192 - len(marker.encode("utf-8"))
  1525. head_size = available // 2
  1526. tail_size = available - head_size
  1527. summary = (encoded[:head_size].decode("utf-8", errors="ignore") + marker
  1528. + encoded[-tail_size:].decode("utf-8", errors="ignore"))
  1529. print(summary)
  1530. ' "${2:-}" "${PROJECT_ROOT}"
  1531. }
  1532. builtin_validate_quick() {
  1533. echo "=========================================="
  1534. echo "Claude harness - クイック整合性チェック"
  1535. echo "=========================================="
  1536. echo ""
  1537. local quick_fail=0
  1538. if [ -d "${PROJECT_ROOT}/.claude/state" ]; then
  1539. echo "✓ .claude/state/ ディレクトリが存在します"
  1540. else
  1541. echo "✗ .claude/state/ ディレクトリが見つかりません"
  1542. quick_fail=$((quick_fail + 1))
  1543. fi
  1544. local plans_file=""
  1545. plans_file="$(plans_file_path)"
  1546. if [ -n "${plans_file}" ] && [ -f "${plans_file}" ]; then
  1547. echo "✓ Plans.md が存在します: ${plans_file}"
  1548. else
  1549. echo "✗ Plans.md が見つかりません"
  1550. quick_fail=$((quick_fail + 1))
  1551. fi
  1552. if [ -n "${plans_file}" ] && [ -f "${plans_file}" ]; then
  1553. if grep -q "DoD" "${plans_file}" && grep -q "Depends" "${plans_file}"; then
  1554. echo "✓ Plans.md は v2 フォーマットです(DoD / Depends カラムあり)"
  1555. else
  1556. echo "✗ Plans.md が v2 フォーマットではありません(DoD または Depends カラムがありません)"
  1557. quick_fail=$((quick_fail + 1))
  1558. fi
  1559. fi
  1560. local contract_dir="${PROJECT_ROOT}/.claude/state/contracts"
  1561. if [ -d "${contract_dir}" ]; then
  1562. local contract_error=0
  1563. while IFS= read -r contract_file; do
  1564. [ -f "${contract_file}" ] || continue
  1565. if command -v jq >/dev/null 2>&1; then
  1566. if ! jq empty "${contract_file}" >/dev/null 2>&1; then
  1567. echo "✗ 壊れた JSON: $(basename "${contract_file}")"
  1568. contract_error=$((contract_error + 1))
  1569. fi
  1570. elif command -v python3 >/dev/null 2>&1; then
  1571. if ! python3 -c "import json,sys; json.load(open(sys.argv[1], encoding='utf-8'))" "${contract_file}" >/dev/null 2>&1; then
  1572. echo "✗ 壊れた JSON: $(basename "${contract_file}")"
  1573. contract_error=$((contract_error + 1))
  1574. fi
  1575. fi
  1576. done < <(find "${contract_dir}" -name "*.sprint-contract.json" -type f 2>/dev/null)
  1577. if [ "${contract_error}" -eq 0 ]; then
  1578. echo "✓ sprint-contract の形式チェックは問題ありません"
  1579. else
  1580. quick_fail=$((quick_fail + contract_error))
  1581. fi
  1582. else
  1583. echo "✓ sprint-contract ディレクトリは未作成(初回実行)"
  1584. fi
  1585. echo ""
  1586. if [ "${quick_fail}" -eq 0 ]; then
  1587. echo "✓ クイック整合性チェック: OK"
  1588. return 0
  1589. fi
  1590. echo "✗ クイック整合性チェック: ${quick_fail} 件の問題があります"
  1591. return 1
  1592. }
  1593. validate_quick() {
  1594. if [ -n "${CODEX_LOOP_VALIDATE_SCRIPT:-}" ]; then
  1595. if [ ! -f "${VALIDATE_SCRIPT}" ]; then
  1596. echo "validate script not found: ${VALIDATE_SCRIPT}" >&2
  1597. return 1
  1598. fi
  1599. (cd "${PROJECT_ROOT}" && bash "${VALIDATE_SCRIPT}" --quick)
  1600. return 0
  1601. fi
  1602. if [ -f "${VALIDATE_SCRIPT}" ]; then
  1603. (cd "${PROJECT_ROOT}" && bash "${VALIDATE_SCRIPT}" --quick)
  1604. return 0
  1605. fi
  1606. builtin_validate_quick
  1607. }
  1608. generate_contract() {
  1609. if [[ "${GENERATE_CONTRACT_SCRIPT}" == *.js ]]; then
  1610. (cd "${PROJECT_ROOT}" && "${NODE_BIN}" "${GENERATE_CONTRACT_SCRIPT}" "$1")
  1611. else
  1612. (cd "${PROJECT_ROOT}" && "${GENERATE_CONTRACT_SCRIPT}" "$1")
  1613. fi
  1614. }
  1615. enrich_contract() {
  1616. (cd "${PROJECT_ROOT}" && "${ENRICH_CONTRACT_SCRIPT}" "$1" --check "Codex loop auto-approval for task $2" --approve)
  1617. }
  1618. ensure_contract_ready() {
  1619. (cd "${PROJECT_ROOT}" && "${ENSURE_CONTRACT_SCRIPT}" "$1")
  1620. }
  1621. run_runtime_review() {
  1622. (cd "${PROJECT_ROOT}" && "${RUNTIME_REVIEW_SCRIPT}" "$1" "$2")
  1623. }
  1624. write_review_result() {
  1625. (cd "${PROJECT_ROOT}" && "${WRITE_REVIEW_RESULT_SCRIPT}" "$1" "$2" "$3")
  1626. }
  1627. run_plateau_check() {
  1628. (cd "${PROJECT_ROOT}" && "${PLATEAU_SCRIPT}" "$1")
  1629. }
  1630. run_checkpoint() {
  1631. (cd "${PROJECT_ROOT}" && "${CHECKPOINT_SCRIPT}" "$1" "$2" "$3" "$4")
  1632. }
  1633. advisor_script_path() {
  1634. printf '%s\n' "${CODEX_LOOP_ADVISOR_SCRIPT:-${HARNESS_INSTALL_ROOT}/scripts/run-advisor-consultation.sh}"
  1635. }
  1636. advisor_enabled_globally() {
  1637. if [ ! -f "${CONFIG_UTILS}" ]; then
  1638. printf 'true\n'
  1639. return 0
  1640. fi
  1641. # shellcheck disable=SC1090
  1642. PROJECT_ROOT="${PROJECT_ROOT}" CONFIG_FILE="${PROJECT_ROOT}/.claude-code-harness.config.yaml" source "${CONFIG_UTILS}"
  1643. get_advisor_enabled
  1644. }
  1645. advisor_retry_threshold() {
  1646. if [ ! -f "${CONFIG_UTILS}" ]; then
  1647. printf '2\n'
  1648. return 0
  1649. fi
  1650. # shellcheck disable=SC1090
  1651. PROJECT_ROOT="${PROJECT_ROOT}" CONFIG_FILE="${PROJECT_ROOT}/.claude-code-harness.config.yaml" source "${CONFIG_UTILS}"
  1652. get_advisor_retry_threshold
  1653. }
  1654. advisor_max_consults_per_task() {
  1655. if [ ! -f "${CONFIG_UTILS}" ]; then
  1656. printf '3\n'
  1657. return 0
  1658. fi
  1659. # shellcheck disable=SC1090
  1660. PROJECT_ROOT="${PROJECT_ROOT}" CONFIG_FILE="${PROJECT_ROOT}/.claude-code-harness.config.yaml" source "${CONFIG_UTILS}"
  1661. get_advisor_max_consults_per_task
  1662. }
  1663. advisor_consult_before_user_escalation() {
  1664. if [ ! -f "${CONFIG_UTILS}" ]; then
  1665. printf 'true\n'
  1666. return 0
  1667. fi
  1668. # shellcheck disable=SC1090
  1669. PROJECT_ROOT="${PROJECT_ROOT}" CONFIG_FILE="${PROJECT_ROOT}/.claude-code-harness.config.yaml" source "${CONFIG_UTILS}"
  1670. get_advisor_consult_before_user_escalation
  1671. }
  1672. advisor_model_name() {
  1673. if [ -n "${CODEX_ADVISOR_MODEL:-}" ]; then
  1674. printf '%s\n' "${CODEX_ADVISOR_MODEL}"
  1675. return 0
  1676. fi
  1677. if [ ! -f "${CONFIG_UTILS}" ]; then
  1678. bash "${HARNESS_INSTALL_ROOT}/scripts/model-routing.sh" --host codex --tier advisor --field model
  1679. return $?
  1680. fi
  1681. # shellcheck disable=SC1090
  1682. PROJECT_ROOT="${PROJECT_ROOT}" CONFIG_FILE="${PROJECT_ROOT}/.claude-code-harness.config.yaml" source "${CONFIG_UTILS}"
  1683. get_advisor_codex_model
  1684. }
  1685. contract_advisor_enabled() {
  1686. local contract_path="$1"
  1687. local global_enabled
  1688. global_enabled="$(advisor_enabled_globally)"
  1689. if [ "${global_enabled}" != "true" ]; then
  1690. printf 'false\n'
  1691. return 0
  1692. fi
  1693. json_get_file "${contract_path}" "advisor.enabled" "false"
  1694. }
  1695. contract_high_risk_summary() {
  1696. local contract_path="$1"
  1697. python_json "${contract_path}" <<'PY'
  1698. import json
  1699. import sys
  1700. with open(sys.argv[1], "r", encoding="utf-8") as fh:
  1701. data = json.load(fh)
  1702. triggers = data.get("advisor", {}).get("triggers", []) or []
  1703. high_risk = [value for value in triggers if value in {"needs-spike", "security-sensitive", "state-migration"}]
  1704. print(",".join(high_risk))
  1705. PY
  1706. }
  1707. normalize_error_signature() {
  1708. local text="$1"
  1709. python_json "${text}" <<'PY'
  1710. import re
  1711. import sys
  1712. normalized = re.sub(r"[^a-z0-9]+", "-", sys.argv[1].lower()).strip("-")
  1713. print(normalized[:80] or "none")
  1714. PY
  1715. }
  1716. advisor_trigger_seen() {
  1717. local trigger_hash="$1"
  1718. python_json "${RUN_JSON}" "${trigger_hash}" <<'PY'
  1719. import json
  1720. import os
  1721. import sys
  1722. path = sys.argv[1]
  1723. target = sys.argv[2]
  1724. if not os.path.exists(path):
  1725. raise SystemExit(1)
  1726. with open(path, "r", encoding="utf-8") as fh:
  1727. data = json.load(fh)
  1728. hashes = data.get("consulted_trigger_hashes", []) or []
  1729. raise SystemExit(0 if target in hashes else 1)
  1730. PY
  1731. }
  1732. advisor_task_consult_count() {
  1733. local task_id="$1"
  1734. python_json "${RUN_JSON}" "${task_id}" <<'PY'
  1735. import json
  1736. import os
  1737. import sys
  1738. path = sys.argv[1]
  1739. task_id = sys.argv[2]
  1740. if not os.path.exists(path):
  1741. print(0)
  1742. raise SystemExit(0)
  1743. with open(path, "r", encoding="utf-8") as fh:
  1744. data = json.load(fh)
  1745. counts = data.get("task_consultations", {}) or {}
  1746. print(counts.get(task_id, 0))
  1747. PY
  1748. }
  1749. record_advisor_consultation() {
  1750. local task_id="$1"
  1751. local trigger_hash="$2"
  1752. local decision="$3"
  1753. local model="$4"
  1754. python_json "${RUN_JSON}" "${task_id}" "${trigger_hash}" "${decision}" "${model}" <<'PY'
  1755. import json
  1756. import os
  1757. import sys
  1758. import tempfile
  1759. path, task_id, trigger_hash, decision, model = sys.argv[1:6]
  1760. data = {}
  1761. if os.path.exists(path):
  1762. with open(path, "r", encoding="utf-8") as fh:
  1763. data = json.load(fh)
  1764. data["consultations"] = int(data.get("consultations", 0)) + 1
  1765. data["last_decision"] = decision
  1766. data["last_trigger"] = trigger_hash
  1767. data["last_model"] = model
  1768. hashes = data.setdefault("consulted_trigger_hashes", [])
  1769. if trigger_hash not in hashes:
  1770. hashes.append(trigger_hash)
  1771. task_counts = data.setdefault("task_consultations", {})
  1772. task_counts[task_id] = int(task_counts.get(task_id, 0)) + 1
  1773. parent = os.path.dirname(path) or "."
  1774. fd, tmp_path = tempfile.mkstemp(prefix=".run-json-", suffix=".tmp", dir=parent)
  1775. with os.fdopen(fd, "w", encoding="utf-8") as fh:
  1776. json.dump(data, fh, ensure_ascii=False, indent=2)
  1777. fh.write("\n")
  1778. os.replace(tmp_path, path)
  1779. PY
  1780. }
  1781. render_advisor_guidance() {
  1782. local response_file="$1"
  1783. python_json "${response_file}" <<'PY'
  1784. import json
  1785. import sys
  1786. with open(sys.argv[1], "r", encoding="utf-8") as fh:
  1787. payload = json.load(fh)
  1788. lines = []
  1789. summary = payload.get("summary")
  1790. if summary:
  1791. lines.append(f"Advisor summary: {summary}")
  1792. for item in payload.get("executor_instructions", []) or []:
  1793. lines.append(f"- {item}")
  1794. print("\n".join(lines))
  1795. PY
  1796. }
  1797. restore_advisor_response() {
  1798. python_json "${RUN_JSON}" "${RESULTS_DIR}" "$1" "$(plans_file_path)" "${PROJECT_ROOT}" <<'PY'
  1799. import json
  1800. import pathlib
  1801. import sys
  1802. run_path, results_dir, task_id, plans_file, project_root = sys.argv[1:]
  1803. if not pathlib.Path(run_path).is_file():
  1804. raise SystemExit(0)
  1805. run = json.loads(pathlib.Path(run_path).read_text(encoding="utf-8"))
  1806. for key, expected in [("project_root", project_root), ("plans_file", plans_file)]:
  1807. if run.get(key) and pathlib.Path(run[key]).resolve() != pathlib.Path(expected).resolve():
  1808. raise SystemExit(0)
  1809. hashes = run.get("consulted_trigger_hashes", []) or []
  1810. responses = {}
  1811. for request_path in pathlib.Path(results_dir).glob("*.advisor-request.json"):
  1812. response_path = request_path.with_name(request_path.name.replace(".advisor-request.json", ".advisor-response.json"))
  1813. try:
  1814. request = json.loads(request_path.read_text(encoding="utf-8"))
  1815. response = json.loads(response_path.read_text(encoding="utf-8"))
  1816. except (OSError, ValueError):
  1817. continue
  1818. if request.get("task_id") != task_id or request.get("trigger_hash") not in hashes:
  1819. continue
  1820. if request.get("run_id") != run.get("run_id"):
  1821. continue
  1822. prior_plan = request.get("execution_context", {}).get("selected_plan", {}).get("path")
  1823. if prior_plan and pathlib.Path(prior_plan).resolve() != pathlib.Path(plans_file).resolve():
  1824. continue
  1825. if response.get("schema_version") != "advisor-response.v1" or response.get("decision") not in {"PLAN", "CORRECTION", "STOP"}:
  1826. continue
  1827. responses[request["trigger_hash"]] = response_path
  1828. for trigger_hash in reversed(hashes):
  1829. if trigger_hash in responses:
  1830. print(responses[trigger_hash])
  1831. break
  1832. PY
  1833. }
  1834. consult_advisor() {
  1835. local task_id="$1"
  1836. local reason_code="$2"
  1837. local trigger_hash="$3"
  1838. local question="$4"
  1839. local attempt="$5"
  1840. local last_error="$6"
  1841. local context_summary="$7"
  1842. local contract_path="${8:-}"
  1843. local request_file response_file model
  1844. model="$(advisor_model_name)"
  1845. # Only completed pairs match restore_advisor_response's request-file glob.
  1846. request_file="$(python_json "${RESULTS_DIR}" "${task_id}.${reason_code}." <<'PY'
  1847. import os, sys, tempfile
  1848. fd, path = tempfile.mkstemp(dir=sys.argv[1], prefix=sys.argv[2], suffix=".advisor-request.pending.json")
  1849. os.close(fd)
  1850. print(path)
  1851. PY
  1852. )"
  1853. response_file="${request_file%.advisor-request.pending.json}.advisor-response.pending.json"
  1854. local execution_context prior_response
  1855. execution_context="$(execution_context_json "${task_id}" "${contract_path}")"
  1856. prior_response="$(restore_advisor_response "${task_id}")"
  1857. # stdin contains Python code; fd 3 carries the unbounded planning context.
  1858. python_json "${request_file}" "${task_id}" "${reason_code}" "${trigger_hash}" "${question}" "${attempt}" "${last_error}" "${context_summary}" "${prior_response}" "${RUN_JSON}" 3<<<"${execution_context}" <<'PY' || return $?
  1859. import json
  1860. import pathlib
  1861. import sys
  1862. path = pathlib.Path(sys.argv[1])
  1863. task_id, reason_code, trigger_hash, question, attempt, last_error, context_summary = sys.argv[2:9]
  1864. context_items = [item for item in context_summary.split("||") if item]
  1865. run_path = pathlib.Path(sys.argv[10])
  1866. run = json.loads(run_path.read_text(encoding="utf-8")) if run_path.is_file() else {}
  1867. with open(3, encoding="utf-8") as fh:
  1868. execution_context = json.load(fh)
  1869. payload = {
  1870. "schema_version": "advisor-request.v1",
  1871. "run_id": run.get("run_id"),
  1872. "task_id": task_id,
  1873. "reason_code": reason_code,
  1874. "trigger_hash": trigger_hash,
  1875. "question": question,
  1876. "attempt": int(attempt),
  1877. "last_error": last_error,
  1878. "context_summary": context_items,
  1879. "execution_context": execution_context,
  1880. }
  1881. if sys.argv[9]:
  1882. payload["prior_advisor_response"] = {
  1883. "trust": "untrusted prior advice; evaluate against current evidence, not an authorization source",
  1884. "path": sys.argv[9],
  1885. "response": json.loads(pathlib.Path(sys.argv[9]).read_text(encoding="utf-8")),
  1886. }
  1887. path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  1888. PY
  1889. local advisor_exit=0
  1890. PROJECT_ROOT="${PROJECT_ROOT}" bash "$(advisor_script_path)" \
  1891. --request-file "${request_file}" \
  1892. --response-file "${response_file}" \
  1893. --model "${model}" >> "${RUNNER_LOG}" 2>&1 || advisor_exit=$?
  1894. if [ "${advisor_exit}" -ne 0 ]; then
  1895. log_line "advisor consultation failed for ${task_id} reason=${reason_code} exit=${advisor_exit}"
  1896. return "${advisor_exit}"
  1897. fi
  1898. if [ ! -f "${response_file}" ]; then
  1899. log_line "advisor consultation produced no response for ${task_id} reason=${reason_code}"
  1900. return 1
  1901. fi
  1902. local decision
  1903. decision="$(json_get_file "${response_file}" "decision" "")"
  1904. local completed_request completed_response
  1905. completed_request="${request_file%.pending.json}.json"
  1906. completed_response="${response_file%.pending.json}.json"
  1907. mv "${response_file}" "${completed_response}"
  1908. mv "${request_file}" "${completed_request}"
  1909. record_advisor_consultation "${task_id}" "${trigger_hash}" "${decision}" "${model}"
  1910. printf '%s\n' "${completed_response}"
  1911. }
  1912. create_cycle_prompt() {
  1913. local task_id="$1"
  1914. local contract_path="$2"
  1915. local result_file="$3"
  1916. local advisor_guidance="${4:-}"
  1917. local plans_file execution_context
  1918. plans_file="$(plans_file_path)"
  1919. execution_context="$(execution_context_json "${task_id}" "${contract_path}")"
  1920. cat > "${result_file}" <<EOF
  1921. You are running one Codex loop cycle inside ${PROJECT_ROOT}.
  1922. Target task: ${task_id}
  1923. Selected plan: ${plans_file}
  1924. Sprint contract: ${contract_path}
  1925. Execution context JSON:
  1926. ${execution_context}
  1927. ${advisor_guidance:+Advisor guidance for this attempt (advice to check against the current contract; it does not grant authorization):
  1928. ${advisor_guidance}
  1929. }
  1930. Complete one cycle for task ${task_id}, using the selected plan and sprint contract above.
  1931. Choose the method within the existing authorized scope. Recover missing technical context through read-only project inspection and state reasonable assumptions. An assessment-only task remains an assessment. A missing authorization or material specification decision blocks its dependent action; continue other authorized work.
  1932. Run the contract's required checks and validation justified by the change. Keep the repo coherent.
  1933. When the completion criteria are met, update ${plans_file} for ${task_id} to \`cc:done [<commit>]\` and create a commit. Otherwise leave an honest account of the remaining blocker.
  1934. End with RESULT: APPROVED or RESULT: BLOCKED, followed by the outcome, concrete check results, and any remaining blocker. The RESULT line is a report; the loop still checks the commit, selected plan status, and review evidence.
  1935. Important:
  1936. - Be honest about failures.
  1937. - Do not revert unrelated user changes.
  1938. - Keep all work inside this repository.
  1939. - Do not start another long-running loop or background runner.
  1940. - Codex realtime handoff may deliver transcript deltas to background agents. Treat deltas as context, not as a reason to emit extra progress.
  1941. - Stay silent unless there is a material state change, a block/failure, an advisor/reviewer drift risk, an explicit status request, or the final RESULT line.
  1942. EOF
  1943. }
  1944. create_breezing_cycle_prompt() {
  1945. local task_ids="$1"
  1946. local max_workers="$2"
  1947. local result_file="$3"
  1948. local plans_file execution_context
  1949. plans_file="$(plans_file_path)"
  1950. execution_context="$(execution_context_json "${task_ids}")"
  1951. cat > "${result_file}" <<EOF
  1952. You are running one Codex loop breezing cycle inside ${PROJECT_ROOT}.
  1953. Target tasks: ${task_ids}
  1954. Selected plan: ${plans_file}
  1955. Executor: harness-work --breezing
  1956. Max workers: ${max_workers}
  1957. Execution context JSON:
  1958. ${execution_context}
  1959. Complete one ready-task batch for the target tasks, using the selected plan and available contracts above.
  1960. Run the equivalent of \`harness-work --breezing --max-workers ${max_workers} ${task_ids}\` inside this repository. Choose the method within the existing authorized scope; preserve assessment-only requests and recover missing technical context through read-only inspection.
  1961. Use parallel workers only for independent tasks with explicit ownership and completion criteria. Keep review and cherry-pick/integration serial.
  1962. When every target task meets its completion criteria, update ${plans_file} for each target task to \`cc:done [<commit>]\` and create a commit. If a task is blocked, preserve the specific blocker and continue independent authorized work.
  1963. End with RESULT: APPROVED or RESULT: BLOCKED, followed by completed work, check results, and remaining blockers. The RESULT line is a report; the loop still checks the commit and selected plan statuses.
  1964. Important:
  1965. - Be honest about failures.
  1966. - Do not revert unrelated user changes.
  1967. - Keep all work inside this repository.
  1968. - Do not start another long-running loop or background runner.
  1969. - Codex realtime handoff may deliver transcript deltas to background agents. Treat deltas as context, not as a reason to emit extra progress.
  1970. - Stay silent unless there is a material state change, a block/failure, an advisor/reviewer drift risk, an explicit status request, or the final RESULT line.
  1971. EOF
  1972. }
  1973. build_review_input() {
  1974. local output_file="$1"
  1975. local verdict="$2"
  1976. local reviewer_profile="$3"
  1977. local task_id="$4"
  1978. local task_title="$5"
  1979. local summary="$6"
  1980. python_json "${output_file}" "${verdict}" "${reviewer_profile}" "${task_id}" "${task_title}" "${summary}" <<'PY'
  1981. import json
  1982. import sys
  1983. path, verdict, reviewer_profile, task_id, task_title, summary = sys.argv[1:7]
  1984. payload = {
  1985. "schema_version": "codex-loop-review-input.v1",
  1986. "verdict": verdict,
  1987. "reviewer_profile": reviewer_profile,
  1988. "task": {
  1989. "id": task_id,
  1990. "title": task_title,
  1991. },
  1992. "recommendations": [] if verdict == "APPROVE" else [summary or "Task did not reach approval."],
  1993. }
  1994. with open(path, "w", encoding="utf-8") as fh:
  1995. json.dump(payload, fh, ensure_ascii=False, indent=2)
  1996. fh.write("\n")
  1997. PY
  1998. }
  1999. cleanup_current_job() {
  2000. rm -f "${CURRENT_JOB_JSON}" 2>/dev/null || true
  2001. run_state_patch '{
  2002. "current_task_id": null,
  2003. "current_batch_ids": null,
  2004. "current_cycle": null,
  2005. "current_job_id": null,
  2006. "current_job_status": null,
  2007. "current_job_phase": null,
  2008. "current_job_log": null,
  2009. "current_executor": null
  2010. }'
  2011. }
  2012. finalize_run() {
  2013. local status="$1"
  2014. local exit_reason="$2"
  2015. local error_message="${3:-}"
  2016. local runner_pid=""
  2017. runner_pid="$(json_get_file "${RUN_JSON}" "pid" "")"
  2018. local cancel_status=0
  2019. RUNNER_FINALIZED=1
  2020. if [ "${status}" != "completed" ]; then
  2021. cancel_current_job_if_active "finalize:${exit_reason}" || cancel_status=$?
  2022. fi
  2023. run_state_patch "$(cat <<EOF
  2024. {
  2025. "status": $(json_escape "${status}"),
  2026. "exit_reason": $(json_escape "${exit_reason}"),
  2027. "finished_at": $(json_escape "$(timestamp_utc)"),
  2028. "updated_at": $(json_escape "$(timestamp_utc)"),
  2029. "pid": null,
  2030. "error_message": $( [ -n "${error_message}" ] && json_escape "${error_message}" || printf 'null' )
  2031. }
  2032. EOF
  2033. )"
  2034. if [ "${cancel_status}" -eq 0 ]; then
  2035. cleanup_current_job
  2036. fi
  2037. release_lock
  2038. log_line "run finished: status=${status} reason=${exit_reason}"
  2039. [ -n "${runner_pid}" ] && true
  2040. }
  2041. write_current_job_state() {
  2042. local json_payload="$1"
  2043. local tmp_file
  2044. tmp_file="$(mktemp "${CURRENT_JOB_JSON}.tmp.XXXXXX")"
  2045. printf '%s\n' "${json_payload}" > "${tmp_file}"
  2046. mv "${tmp_file}" "${CURRENT_JOB_JSON}"
  2047. }
  2048. perform_cycle() {
  2049. local run_id="$1"
  2050. local task_id="$2"
  2051. local cycle_number="$3"
  2052. local cycle_started_at
  2053. cycle_started_at="$(timestamp_utc)"
  2054. log_line "cycle ${cycle_number} starting for task ${task_id}"
  2055. if ! validate_quick >> "${RUNNER_LOG}" 2>&1; then
  2056. log_line "cycle ${cycle_number} failed validation"
  2057. return 20
  2058. fi
  2059. resume_pack_best_effort
  2060. local contract_path
  2061. contract_path="$(generate_contract "${task_id}")"
  2062. contract_path="$(enrich_contract "${contract_path}" "${task_id}")"
  2063. ensure_contract_ready "${contract_path}" >> "${RUNNER_LOG}" 2>&1
  2064. local task_title reviewer_profile
  2065. task_title="$(task_title_from_contract "${contract_path}")"
  2066. reviewer_profile="$(json_get_file "${contract_path}" "review.reviewer_profile" "static")"
  2067. local prompt_file runtime_review_file review_input_file review_result_file
  2068. prompt_file="${PROMPTS_DIR}/${run_id}-cycle-${cycle_number}.md"
  2069. runtime_review_file="${RESULTS_DIR}/${run_id}-cycle-${cycle_number}.runtime.json"
  2070. review_input_file="${RESULTS_DIR}/${run_id}-cycle-${cycle_number}.review-input.json"
  2071. review_result_file="${RESULTS_DIR}/${run_id}-cycle-${cycle_number}.review-result.json"
  2072. local advisor_active advisor_guidance high_risk_summary
  2073. advisor_active="$(contract_advisor_enabled "${contract_path}")"
  2074. advisor_guidance=""
  2075. high_risk_summary="$(contract_high_risk_summary "${contract_path}")"
  2076. if [ "${advisor_active}" = "true" ]; then
  2077. local prior_response
  2078. prior_response="$(restore_advisor_response "${task_id}")"
  2079. if [ -n "${prior_response}" ]; then
  2080. if [ "$(json_get_file "${prior_response}" "decision" "")" = "STOP" ]; then
  2081. log_line "restored advisor stop before execution for ${task_id}"
  2082. return 21
  2083. fi
  2084. advisor_guidance="$(render_advisor_guidance "${prior_response}")"
  2085. fi
  2086. fi
  2087. if [ "${advisor_active}" = "true" ] && [ -n "${high_risk_summary}" ]; then
  2088. local preflight_hash preflight_response preflight_decision preflight_count preflight_exit
  2089. preflight_hash="${task_id}:high-risk-preflight:$(normalize_error_signature "${high_risk_summary}")"
  2090. preflight_count="$(advisor_task_consult_count "${task_id}")"
  2091. if ! advisor_trigger_seen "${preflight_hash}" && [ "${preflight_count}" -lt "$(advisor_max_consults_per_task)" ]; then
  2092. preflight_exit=0
  2093. preflight_response="$(consult_advisor "${task_id}" "high-risk-preflight" "${preflight_hash}" "高リスク task の初回実行前。どの観点を先に固めるべきか。" 1 "${high_risk_summary}" "task=${task_id}||risk_triggers=${high_risk_summary}||cycle=${cycle_number}" "${contract_path}")" || preflight_exit=$?
  2094. if [ "${preflight_exit}" -ne 0 ]; then
  2095. log_line "advisor preflight failed for ${task_id} (exit=${preflight_exit}); retaining any prior guidance"
  2096. else
  2097. preflight_decision="$(json_get_file "${preflight_response}" "decision" "")"
  2098. advisor_guidance="$(render_advisor_guidance "${preflight_response}")"
  2099. if [ "${preflight_decision}" = "STOP" ]; then
  2100. log_line "advisor stop before execution for ${task_id}"
  2101. return 21
  2102. fi
  2103. fi
  2104. fi
  2105. fi
  2106. local retry_threshold max_consults attempt_limit
  2107. retry_threshold="$(advisor_retry_threshold)"
  2108. max_consults="$(advisor_max_consults_per_task)"
  2109. attempt_limit=$((retry_threshold + 1))
  2110. local task_attempt=1 failure_count=0 failure_signature=""
  2111. local job_id="" job_log="" job_status="" job_phase="" summary=""
  2112. local post_head="" static_verdict="REQUEST_CHANGES" runtime_verdict="REQUEST_CHANGES" final_verdict="REQUEST_CHANGES"
  2113. local checkpoint_status="skipped" plateau_exit=1
  2114. while [ "${task_attempt}" -le "${attempt_limit}" ]; do
  2115. create_cycle_prompt "${task_id}" "${contract_path}" "${prompt_file}" "${advisor_guidance}"
  2116. local pre_head=""
  2117. pre_head="$(cd "${PROJECT_ROOT}" && git rev-parse --short HEAD 2>/dev/null || true)"
  2118. local task_launch_json
  2119. task_launch_json="$(start_background_task "${prompt_file}")"
  2120. job_id="$(python_json "${task_launch_json}" <<'PY'
  2121. import json, sys
  2122. print(json.loads(sys.argv[1]).get("jobId", ""))
  2123. PY
  2124. )"
  2125. job_log="$(python_json "${task_launch_json}" <<'PY'
  2126. import json, sys
  2127. print(json.loads(sys.argv[1]).get("logFile", ""))
  2128. PY
  2129. )"
  2130. [ -n "${job_id}" ] || {
  2131. log_line "cycle ${cycle_number} missing job id"
  2132. return 21
  2133. }
  2134. write_current_job_state "$(cat <<EOF
  2135. {
  2136. "run_id": $(json_escape "${run_id}"),
  2137. "cycle": ${cycle_number},
  2138. "attempt": ${task_attempt},
  2139. "task_id": $(json_escape "${task_id}"),
  2140. "job_id": $(json_escape "${job_id}"),
  2141. "log_file": $(json_escape "${job_log}"),
  2142. "task_driver": $(json_escape "$(codex_loop_task_driver)"),
  2143. "companion_path": $(json_escape "$(codex_loop_companion_path)"),
  2144. "contract_path": $(json_escape "${contract_path}"),
  2145. "reviewer_profile": $(json_escape "${reviewer_profile}"),
  2146. "started_at": $(json_escape "${cycle_started_at}")
  2147. }
  2148. EOF
  2149. )"
  2150. run_state_patch "$(cat <<EOF
  2151. {
  2152. "status": "running",
  2153. "updated_at": $(json_escape "$(timestamp_utc)"),
  2154. "current_task_id": $(json_escape "${task_id}"),
  2155. "current_cycle": ${cycle_number},
  2156. "current_job_id": $(json_escape "${job_id}"),
  2157. "current_job_status": "queued",
  2158. "current_job_phase": "queued",
  2159. "current_job_log": $(json_escape "${job_log}")
  2160. }
  2161. EOF
  2162. )"
  2163. local stop_cancelled=0
  2164. local status_json
  2165. while true; do
  2166. status_json="$(companion_status_json "${job_id}" 2>/dev/null || true)"
  2167. local status_payload="${status_json}"
  2168. [ -n "${status_payload}" ] || status_payload='{}'
  2169. job_status="$(python_json 3<<<"${status_payload}" <<'PY'
  2170. import json, sys
  2171. try:
  2172. with open(3, encoding="utf-8") as fh:
  2173. payload = json.load(fh)
  2174. except json.JSONDecodeError:
  2175. payload = {}
  2176. job = payload.get("job", {})
  2177. print(job.get("status", "unknown"))
  2178. PY
  2179. )"
  2180. job_phase="$(python_json 3<<<"${status_payload}" <<'PY'
  2181. import json, sys
  2182. try:
  2183. with open(3, encoding="utf-8") as fh:
  2184. payload = json.load(fh)
  2185. except json.JSONDecodeError:
  2186. payload = {}
  2187. job = payload.get("job", {})
  2188. print(job.get("phase", "unknown"))
  2189. PY
  2190. )"
  2191. run_state_patch "$(cat <<EOF
  2192. {
  2193. "updated_at": $(json_escape "$(timestamp_utc)"),
  2194. "current_job_status": $(json_escape "${job_status}"),
  2195. "current_job_phase": $(json_escape "${job_phase}")
  2196. }
  2197. EOF
  2198. )"
  2199. if stop_requested && [ "${stop_cancelled}" -eq 0 ] && { [ "${job_status}" = "queued" ] || [ "${job_status}" = "running" ]; }; then
  2200. log_line "stop requested: cancelling ${job_id}"
  2201. companion_cancel_json "${job_id}" >> "${RUNNER_LOG}" 2>&1 || true
  2202. stop_cancelled=1
  2203. fi
  2204. if [ "${job_status}" != "queued" ] && [ "${job_status}" != "running" ]; then
  2205. break
  2206. fi
  2207. sleep "${POLL_INTERVAL_SEC}"
  2208. done
  2209. local result_json result_payload
  2210. result_json="$(companion_result_json "${job_id}" 2>/dev/null || true)"
  2211. result_payload="${result_json}"
  2212. [ -n "${result_payload}" ] || result_payload='{}'
  2213. summary="$(task_result_summary "${result_payload}" "${RESULTS_DIR}/${run_id}-cycle-${cycle_number}-attempt-${task_attempt}")"
  2214. post_head="$(cd "${PROJECT_ROOT}" && git rev-parse --short HEAD 2>/dev/null || true)"
  2215. local task_status
  2216. task_status="$(task_status_value "$(plans_file_path)" "${task_id}" 2>/dev/null || true)"
  2217. static_verdict="REQUEST_CHANGES"
  2218. if [ -n "${post_head}" ] && [ "${post_head}" != "${pre_head}" ] && grep -Eq 'cc:完了|pm:確認済|cursor:確認済|cc:done|pm:approved' <<<"${task_status}"; then
  2219. static_verdict="APPROVE"
  2220. fi
  2221. runtime_verdict="${static_verdict}"
  2222. if run_runtime_review "${contract_path}" "${runtime_review_file}" >> "${RUNNER_LOG}" 2>&1; then
  2223. runtime_verdict="$(json_get_file "${runtime_review_file}" "verdict" "${static_verdict}")"
  2224. fi
  2225. final_verdict="${static_verdict}"
  2226. if [ "${runtime_verdict}" = "REQUEST_CHANGES" ]; then
  2227. final_verdict="REQUEST_CHANGES"
  2228. elif [ "${runtime_verdict}" = "APPROVE" ] && [ "${static_verdict}" = "APPROVE" ]; then
  2229. final_verdict="APPROVE"
  2230. fi
  2231. build_review_input "${review_input_file}" "${final_verdict}" "${reviewer_profile}" "${task_id}" "${task_title}" "${summary}"
  2232. write_review_result "${review_input_file}" "${post_head}" "${review_result_file}" >> "${RUNNER_LOG}" 2>&1 || true
  2233. if [ "${final_verdict}" = "APPROVE" ]; then
  2234. break
  2235. fi
  2236. local current_signature
  2237. current_signature="$(normalize_error_signature "${summary}")"
  2238. if [ "${current_signature}" = "${failure_signature}" ]; then
  2239. failure_count=$((failure_count + 1))
  2240. else
  2241. failure_signature="${current_signature}"
  2242. failure_count=1
  2243. fi
  2244. if [ "${task_attempt}" -lt "${retry_threshold}" ]; then
  2245. task_attempt=$((task_attempt + 1))
  2246. continue
  2247. fi
  2248. if [ "${advisor_active}" = "true" ] && [ "${failure_count}" -ge "${retry_threshold}" ]; then
  2249. local retry_hash retry_response retry_decision retry_count retry_exit
  2250. retry_hash="${task_id}:retry-threshold:${failure_signature}"
  2251. retry_count="$(advisor_task_consult_count "${task_id}")"
  2252. if ! advisor_trigger_seen "${retry_hash}" && [ "${retry_count}" -lt "${max_consults}" ]; then
  2253. retry_exit=0
  2254. retry_response="$(consult_advisor "${task_id}" "retry-threshold" "${retry_hash}" "同じ原因の失敗が繰り返された。次は何を変えるべきか。" "${task_attempt}" "${summary}" "task=${task_id}||attempt=${task_attempt}||signature=${failure_signature}" "${contract_path}")" || retry_exit=$?
  2255. if [ "${retry_exit}" -ne 0 ]; then
  2256. log_line "advisor retry-threshold failed for ${task_id} (exit=${retry_exit}); retaining any prior guidance"
  2257. if [ "${task_attempt}" -lt "${attempt_limit}" ]; then
  2258. task_attempt=$((task_attempt + 1))
  2259. continue
  2260. fi
  2261. else
  2262. retry_decision="$(json_get_file "${retry_response}" "decision" "")"
  2263. advisor_guidance="$(render_advisor_guidance "${retry_response}")"
  2264. if [ "${retry_decision}" = "STOP" ]; then
  2265. break
  2266. fi
  2267. if [ "${task_attempt}" -lt "${attempt_limit}" ]; then
  2268. task_attempt=$((task_attempt + 1))
  2269. continue
  2270. fi
  2271. fi
  2272. fi
  2273. fi
  2274. break
  2275. done
  2276. if [ -n "${post_head}" ] && [ "${final_verdict}" = "APPROVE" ] && [ -f "${review_result_file}" ]; then
  2277. if run_checkpoint "${task_id}" "${post_head}" "${contract_path}" "${review_result_file}" >> "${RUNNER_LOG}" 2>&1; then
  2278. checkpoint_status="ok"
  2279. else
  2280. checkpoint_status="failed"
  2281. fi
  2282. fi
  2283. if run_plateau_check "${task_id}" >> "${RUNNER_LOG}" 2>&1; then
  2284. plateau_exit=0
  2285. else
  2286. plateau_exit=$?
  2287. fi
  2288. if [ "${plateau_exit}" -eq 2 ] && [ "${advisor_active}" = "true" ] && [ "$(advisor_consult_before_user_escalation)" = "true" ]; then
  2289. local plateau_hash plateau_response plateau_decision plateau_count
  2290. plateau_hash="${task_id}:plateau-pre-escalation:$(normalize_error_signature "${summary}")"
  2291. plateau_count="$(advisor_task_consult_count "${task_id}")"
  2292. if ! advisor_trigger_seen "${plateau_hash}" && [ "${plateau_count}" -lt "${max_consults}" ]; then
  2293. plateau_response="$(consult_advisor "${task_id}" "plateau-pre-escalation" "${plateau_hash}" "plateau により停止候補。もう一度進めるべきか止めるべきか。" "${task_attempt}" "${summary}" "task=${task_id}||phase=plateau||verdict=${final_verdict}" "${contract_path}")" || return 22
  2294. plateau_decision="$(json_get_file "${plateau_response}" "decision" "")"
  2295. if [ "${plateau_decision}" != "STOP" ]; then
  2296. plateau_exit=0
  2297. fi
  2298. fi
  2299. fi
  2300. append_jsonl "${CYCLES_JSONL}" "$(cat <<EOF
  2301. {"run_id":$(json_escape "${run_id}"),"cycle":${cycle_number},"task_id":$(json_escape "${task_id}"),"job_id":$(json_escape "${job_id}"),"job_status":$(json_escape "${job_status}"),"reviewer_profile":$(json_escape "${reviewer_profile}"),"verdict":$(json_escape "${final_verdict}"),"static_verdict":$(json_escape "${static_verdict}"),"runtime_verdict":$(json_escape "${runtime_verdict}"),"commit_hash":$( [ -n "${post_head}" ] && json_escape "${post_head}" || printf 'null' ),"summary":$(json_escape "${summary}"),"checkpoint":$(json_escape "${checkpoint_status}"),"attempts":${task_attempt},"consultations":$(json_get_file "${RUN_JSON}" "consultations" "0"),"started_at":$(json_escape "${cycle_started_at}"),"finished_at":$(json_escape "$(timestamp_utc)")}
  2302. EOF
  2303. )"
  2304. run_state_patch "$(cat <<EOF
  2305. {
  2306. "cycle_count": ${cycle_number},
  2307. "last_task_id": $(json_escape "${task_id}"),
  2308. "last_job_id": $(json_escape "${job_id}"),
  2309. "last_verdict": $(json_escape "${final_verdict}"),
  2310. "updated_at": $(json_escape "$(timestamp_utc)")
  2311. }
  2312. EOF
  2313. )"
  2314. cleanup_current_job
  2315. if stop_requested; then
  2316. return 30
  2317. fi
  2318. if [ "${plateau_exit}" -eq 2 ]; then
  2319. return 22
  2320. fi
  2321. if [ "${final_verdict}" != "APPROVE" ]; then
  2322. return 21
  2323. fi
  2324. return 0
  2325. }
  2326. perform_breezing_cycle() {
  2327. local run_id="$1"
  2328. local task_ids="$2"
  2329. local cycle_number="$3"
  2330. local max_workers="$4"
  2331. local cycle_started_at
  2332. cycle_started_at="$(timestamp_utc)"
  2333. log_line "cycle ${cycle_number} starting executor=breezing batch=${task_ids} max_workers=${max_workers}"
  2334. if ! validate_quick >> "${RUNNER_LOG}" 2>&1; then
  2335. log_line "cycle ${cycle_number} failed validation"
  2336. return 20
  2337. fi
  2338. resume_pack_best_effort
  2339. local prompt_file review_input_file review_result_file
  2340. prompt_file="${PROMPTS_DIR}/${run_id}-cycle-${cycle_number}.breezing.md"
  2341. review_input_file="${RESULTS_DIR}/${run_id}-cycle-${cycle_number}.breezing.review-input.json"
  2342. review_result_file="${RESULTS_DIR}/${run_id}-cycle-${cycle_number}.breezing.review-result.json"
  2343. local pre_head post_head job_id job_log job_status job_phase summary
  2344. pre_head="$(cd "${PROJECT_ROOT}" && git rev-parse --short HEAD 2>/dev/null || true)"
  2345. create_breezing_cycle_prompt "${task_ids}" "${max_workers}" "${prompt_file}"
  2346. local task_launch_json
  2347. task_launch_json="$(start_background_task "${prompt_file}")"
  2348. job_id="$(python_json "${task_launch_json}" <<'PY'
  2349. import json, sys
  2350. print(json.loads(sys.argv[1]).get("jobId", ""))
  2351. PY
  2352. )"
  2353. job_log="$(python_json "${task_launch_json}" <<'PY'
  2354. import json, sys
  2355. print(json.loads(sys.argv[1]).get("logFile", ""))
  2356. PY
  2357. )"
  2358. [ -n "${job_id}" ] || {
  2359. log_line "cycle ${cycle_number} missing job id"
  2360. return 21
  2361. }
  2362. write_current_job_state "$(cat <<EOF
  2363. {
  2364. "run_id": $(json_escape "${run_id}"),
  2365. "cycle": ${cycle_number},
  2366. "executor": "breezing",
  2367. "task_ids": $(json_escape "${task_ids}"),
  2368. "job_id": $(json_escape "${job_id}"),
  2369. "log_file": $(json_escape "${job_log}"),
  2370. "task_driver": $(json_escape "$(codex_loop_task_driver)"),
  2371. "companion_path": $(json_escape "$(codex_loop_companion_path)"),
  2372. "started_at": $(json_escape "${cycle_started_at}")
  2373. }
  2374. EOF
  2375. )"
  2376. run_state_patch "$(cat <<EOF
  2377. {
  2378. "status": "running",
  2379. "updated_at": $(json_escape "$(timestamp_utc)"),
  2380. "current_task_id": $(json_escape "${task_ids}"),
  2381. "current_batch_ids": $(json_escape "${task_ids}"),
  2382. "current_cycle": ${cycle_number},
  2383. "current_job_id": $(json_escape "${job_id}"),
  2384. "current_job_status": "queued",
  2385. "current_job_phase": "queued",
  2386. "current_job_log": $(json_escape "${job_log}"),
  2387. "current_executor": "breezing"
  2388. }
  2389. EOF
  2390. )"
  2391. local stop_cancelled=0
  2392. local status_json
  2393. while true; do
  2394. status_json="$(companion_status_json "${job_id}" 2>/dev/null || true)"
  2395. local status_payload="${status_json}"
  2396. [ -n "${status_payload}" ] || status_payload='{}'
  2397. job_status="$(python_json 3<<<"${status_payload}" <<'PY'
  2398. import json, sys
  2399. try:
  2400. with open(3, encoding="utf-8") as fh:
  2401. payload = json.load(fh)
  2402. except json.JSONDecodeError:
  2403. payload = {}
  2404. job = payload.get("job", {})
  2405. print(job.get("status", "unknown"))
  2406. PY
  2407. )"
  2408. job_phase="$(python_json 3<<<"${status_payload}" <<'PY'
  2409. import json, sys
  2410. try:
  2411. with open(3, encoding="utf-8") as fh:
  2412. payload = json.load(fh)
  2413. except json.JSONDecodeError:
  2414. payload = {}
  2415. job = payload.get("job", {})
  2416. print(job.get("phase", "unknown"))
  2417. PY
  2418. )"
  2419. run_state_patch "$(cat <<EOF
  2420. {
  2421. "updated_at": $(json_escape "$(timestamp_utc)"),
  2422. "current_job_status": $(json_escape "${job_status}"),
  2423. "current_job_phase": $(json_escape "${job_phase}")
  2424. }
  2425. EOF
  2426. )"
  2427. if stop_requested && [ "${stop_cancelled}" -eq 0 ] && { [ "${job_status}" = "queued" ] || [ "${job_status}" = "running" ]; }; then
  2428. log_line "stop requested: cancelling ${job_id}"
  2429. companion_cancel_json "${job_id}" >> "${RUNNER_LOG}" 2>&1 || true
  2430. stop_cancelled=1
  2431. fi
  2432. if [ "${job_status}" != "queued" ] && [ "${job_status}" != "running" ]; then
  2433. break
  2434. fi
  2435. sleep "${POLL_INTERVAL_SEC}"
  2436. done
  2437. local result_json result_payload
  2438. result_json="$(companion_result_json "${job_id}" 2>/dev/null || true)"
  2439. result_payload="${result_json}"
  2440. [ -n "${result_payload}" ] || result_payload='{}'
  2441. summary="$(task_result_summary "${result_payload}" "${RESULTS_DIR}/${run_id}-cycle-${cycle_number}.breezing")"
  2442. post_head="$(cd "${PROJECT_ROOT}" && git rev-parse --short HEAD 2>/dev/null || true)"
  2443. local final_verdict="REQUEST_CHANGES"
  2444. if [ -n "${post_head}" ] && [ "${post_head}" != "${pre_head}" ] && tasks_complete "$(plans_file_path)" "${task_ids}"; then
  2445. final_verdict="APPROVE"
  2446. fi
  2447. build_review_input "${review_input_file}" "${final_verdict}" "static" "${task_ids}" "Breezing batch ${task_ids}" "${summary}"
  2448. write_review_result "${review_input_file}" "${post_head}" "${review_result_file}" >> "${RUNNER_LOG}" 2>&1 || true
  2449. local checkpoint_status="skipped"
  2450. if [ -n "${post_head}" ] && [ "${final_verdict}" = "APPROVE" ] && [ -f "${review_result_file}" ]; then
  2451. if run_checkpoint "${task_ids}" "${post_head}" "" "${review_result_file}" >> "${RUNNER_LOG}" 2>&1; then
  2452. checkpoint_status="ok"
  2453. else
  2454. checkpoint_status="failed"
  2455. fi
  2456. fi
  2457. append_jsonl "${CYCLES_JSONL}" "$(cat <<EOF
  2458. {"run_id":$(json_escape "${run_id}"),"cycle":${cycle_number},"executor":"breezing","task_ids":$(json_escape "${task_ids}"),"job_id":$(json_escape "${job_id}"),"job_status":$(json_escape "${job_status}"),"verdict":$(json_escape "${final_verdict}"),"commit_hash":$( [ -n "${post_head}" ] && json_escape "${post_head}" || printf 'null' ),"summary":$(json_escape "${summary}"),"checkpoint":$(json_escape "${checkpoint_status}"),"started_at":$(json_escape "${cycle_started_at}"),"finished_at":$(json_escape "$(timestamp_utc)")}
  2459. EOF
  2460. )"
  2461. run_state_patch "$(cat <<EOF
  2462. {
  2463. "cycle_count": ${cycle_number},
  2464. "last_task_id": $(json_escape "${task_ids}"),
  2465. "last_batch_ids": $(json_escape "${task_ids}"),
  2466. "last_job_id": $(json_escape "${job_id}"),
  2467. "last_verdict": $(json_escape "${final_verdict}"),
  2468. "updated_at": $(json_escape "$(timestamp_utc)")
  2469. }
  2470. EOF
  2471. )"
  2472. cleanup_current_job
  2473. if stop_requested; then
  2474. return 30
  2475. fi
  2476. if [ "${final_verdict}" != "APPROVE" ]; then
  2477. return 21
  2478. fi
  2479. return 0
  2480. }
  2481. cmd_start() {
  2482. local selection="${1:-}"
  2483. shift || true
  2484. [ -n "${selection}" ] || {
  2485. echo "codex-loop start requires a selection (all|TASK|START-END|START..END)" >&2
  2486. exit 2
  2487. }
  2488. local max_cycles="8"
  2489. local pacing="worker"
  2490. local executor="breezing"
  2491. local max_workers="max"
  2492. local plan_name=""
  2493. while [ $# -gt 0 ]; do
  2494. case "$1" in
  2495. --plan)
  2496. if [ $# -lt 2 ] || [[ "${2:-}" == --* ]]; then
  2497. echo "--plan requires a plan name" >&2
  2498. exit 2
  2499. fi
  2500. plan_name="${2:-}"
  2501. shift 2
  2502. ;;
  2503. --max-cycles)
  2504. max_cycles="${2:-}"
  2505. shift 2
  2506. ;;
  2507. --pacing)
  2508. pacing="${2:-}"
  2509. shift 2
  2510. ;;
  2511. --executor)
  2512. executor="${2:-}"
  2513. shift 2
  2514. ;;
  2515. --max-workers|--max-wokers)
  2516. if [ $# -lt 2 ] || [[ "${2:-}" == --* ]]; then
  2517. max_workers="max"
  2518. shift
  2519. else
  2520. max_workers="${2:-}"
  2521. shift 2
  2522. fi
  2523. ;;
  2524. *)
  2525. echo "Unknown option: $1" >&2
  2526. exit 2
  2527. ;;
  2528. esac
  2529. done
  2530. case "${executor}" in
  2531. breezing|task) ;;
  2532. *)
  2533. echo "--executor must be breezing or task" >&2
  2534. exit 2
  2535. ;;
  2536. esac
  2537. if [ -z "${max_workers}" ]; then
  2538. echo "--max-workers requires a value (N or max)" >&2
  2539. exit 2
  2540. fi
  2541. if [ "${max_workers}" != "max" ]; then
  2542. case "${max_workers}" in
  2543. ''|*[!0-9]*)
  2544. echo "--max-workers must be a positive integer or max" >&2
  2545. exit 2
  2546. ;;
  2547. 0)
  2548. echo "--max-workers must be >= 1 or max" >&2
  2549. exit 2
  2550. ;;
  2551. esac
  2552. fi
  2553. local plans_file
  2554. if [ -n "${plan_name}" ]; then
  2555. export HARNESS_PLAN_NAME="${plan_name}"
  2556. fi
  2557. plans_file="$(plans_file_path)"
  2558. [ -f "${plans_file}" ] || {
  2559. echo "Plans.md not found under ${PROJECT_ROOT}${plan_name:+ for plan ${plan_name}}" >&2
  2560. exit 1
  2561. }
  2562. local normalized_selection=""
  2563. if ! normalized_selection="$(normalize_selection "${plans_file}" "${selection}" 2>&1)"; then
  2564. echo "${normalized_selection}" >&2
  2565. exit 2
  2566. fi
  2567. selection="${normalized_selection}"
  2568. ensure_dirs
  2569. if ! acquire_lock; then
  2570. local existing_pid=""
  2571. existing_pid="$(cat "${LOCK_DIR}/pid" 2>/dev/null || true)"
  2572. echo "codex-loop is already running (pid=${existing_pid:-unknown})" >&2
  2573. exit 1
  2574. fi
  2575. local run_id delay_seconds
  2576. run_id="codex-loop-$(date +%Y%m%d%H%M%S)-$$"
  2577. delay_seconds="$(delay_for_pacing "${pacing}")"
  2578. rm -f "${CURRENT_JOB_JSON}"
  2579. local run_tmp
  2580. run_tmp="$(mktemp "${RUN_JSON}.tmp.XXXXXX")"
  2581. cat > "${run_tmp}" <<EOF
  2582. {
  2583. "schema_version": "codex-loop-run.v1",
  2584. "run_id": "$(printf '%s' "${run_id}")",
  2585. "selection": "$(printf '%s' "${selection}")",
  2586. "max_cycles": ${max_cycles},
  2587. "pacing": "$(printf '%s' "${pacing}")",
  2588. "executor": "$(printf '%s' "${executor}")",
  2589. "task_driver": "$(printf '%s' "${CODEX_LOOP_TASK_DRIVER:-local}")",
  2590. "companion_path": "$(printf '%s' "${CODEX_LOOP_COMPANION:-${COMPANION}}")",
  2591. "max_workers": "$(printf '%s' "${max_workers}")",
  2592. "delay_seconds": ${delay_seconds},
  2593. "cycle_count": 0,
  2594. "consultations": 0,
  2595. "last_decision": null,
  2596. "last_trigger": null,
  2597. "last_model": null,
  2598. "consulted_trigger_hashes": [],
  2599. "task_consultations": {},
  2600. "status": "starting",
  2601. "started_at": "$(timestamp_utc)",
  2602. "updated_at": "$(timestamp_utc)",
  2603. "project_root": "$(printf '%s' "${PROJECT_ROOT}")",
  2604. "plan_name": "$(printf '%s' "${plan_name:-default}")",
  2605. "plans_file": "$(printf '%s' "${plans_file}")"
  2606. }
  2607. EOF
  2608. mv "${run_tmp}" "${RUN_JSON}"
  2609. : > "${RUNNER_LOG}"
  2610. log_line "starting runner: script=${SELF_SCRIPT} run_id=${run_id}"
  2611. nohup env CODEX_LOOP_BOOTSTRAP_PID="$$" bash "${SELF_SCRIPT}" run --run-id "${run_id}" >> "${RUNNER_LOG}" 2>&1 &
  2612. local runner_pid=$!
  2613. printf '%s\n' "${runner_pid}" > "${LOCK_DIR}/pid"
  2614. run_state_patch "$(cat <<EOF
  2615. {
  2616. "pid": ${runner_pid},
  2617. "status": "running",
  2618. "updated_at": $(json_escape "$(timestamp_utc)")
  2619. }
  2620. EOF
  2621. )"
  2622. if ! wait_for_runner_startup "${runner_pid}"; then
  2623. local log_tail
  2624. log_tail="$(runner_log_tail_one_line 30)"
  2625. local error_message="loop runner exited during startup"
  2626. if [ -n "${log_tail}" ]; then
  2627. error_message="${error_message}; runner log tail: ${log_tail}"
  2628. fi
  2629. run_state_patch "$(cat <<EOF
  2630. {
  2631. "pid": null,
  2632. "status": "startup_failed",
  2633. "exit_reason": "startup_failed",
  2634. "finished_at": $(json_escape "$(timestamp_utc)"),
  2635. "updated_at": $(json_escape "$(timestamp_utc)"),
  2636. "error_message": $(json_escape "${error_message}"),
  2637. "startup_log_tail": $(json_escape "${log_tail}")
  2638. }
  2639. EOF
  2640. )"
  2641. release_lock
  2642. printf 'Failed to start codex-loop %s: %s\n' "${run_id}" "${error_message}" >&2
  2643. exit 1
  2644. fi
  2645. printf 'Started codex-loop %s in background (pid=%s)\n' "${run_id}" "${runner_pid}"
  2646. }
  2647. cmd_status() {
  2648. local as_json=0
  2649. while [ $# -gt 0 ]; do
  2650. case "$1" in
  2651. --json) as_json=1 ;;
  2652. *)
  2653. echo "Unknown option: $1" >&2
  2654. exit 2
  2655. ;;
  2656. esac
  2657. shift
  2658. done
  2659. ensure_dirs
  2660. if [ ! -f "${RUN_JSON}" ]; then
  2661. if [ "${as_json}" -eq 1 ]; then
  2662. printf '{"status":"idle","project_root":%s}\n' "$(json_escape "${PROJECT_ROOT}")"
  2663. else
  2664. echo "codex-loop: idle"
  2665. fi
  2666. return 0
  2667. fi
  2668. local payload
  2669. payload="$(python_json "${RUN_JSON}" "${CURRENT_JOB_JSON}" "${PROJECT_ROOT}" "${RUNNER_LOG}" <<'PY'
  2670. import json
  2671. import os
  2672. import sys
  2673. run_file, current_job_file, project_root, runner_log_file = sys.argv[1:5]
  2674. def pid_alive(pid):
  2675. if pid in (None, "", 0):
  2676. return False
  2677. try:
  2678. os.kill(int(pid), 0)
  2679. except (OSError, ValueError, TypeError):
  2680. return False
  2681. return True
  2682. try:
  2683. with open(run_file, "r", encoding="utf-8") as fh:
  2684. run = json.load(fh)
  2685. except Exception as exc:
  2686. print(json.dumps({
  2687. "status": "state_corrupt",
  2688. "project_root": project_root,
  2689. "run": None,
  2690. "current_job": None,
  2691. "error": str(exc),
  2692. }, ensure_ascii=False, indent=2))
  2693. raise SystemExit(0)
  2694. payload = {"run": run, "current_job": None}
  2695. if os.path.exists(current_job_file):
  2696. try:
  2697. with open(current_job_file, "r", encoding="utf-8") as fh:
  2698. payload["current_job"] = json.load(fh)
  2699. except Exception as exc:
  2700. payload["warning"] = f"current_job_corrupt: {exc}"
  2701. active_statuses = {"starting", "running", "waiting", "stopping"}
  2702. terminal_job_statuses = {"completed", "done", "failed", "cancelled", "missing"}
  2703. if run.get("status") in active_statuses and not pid_alive(run.get("pid")):
  2704. run = dict(run)
  2705. current_job = payload.get("current_job") or {}
  2706. job_id = run.get("current_job_id") or current_job.get("job_id") or current_job.get("id")
  2707. job_status = run.get("current_job_status") or current_job.get("status") or ""
  2708. active_job_lost = bool(job_id) and job_status not in terminal_job_statuses
  2709. if active_job_lost:
  2710. run["status"] = "runner_lost_job_running"
  2711. run["exit_reason"] = "runner_lost_active_job"
  2712. run["current_job_id"] = job_id
  2713. if job_status:
  2714. run["current_job_status"] = job_status
  2715. else:
  2716. run["status"] = "state_stale"
  2717. if not run.get("error_message"):
  2718. tail = ""
  2719. try:
  2720. with open(runner_log_file, "r", encoding="utf-8", errors="replace") as fh:
  2721. lines = fh.readlines()[-20:]
  2722. tail = " ".join(line.strip() for line in lines if line.strip())
  2723. except Exception:
  2724. tail = ""
  2725. if active_job_lost:
  2726. run["error_message"] = (
  2727. f"loop runner pid is not alive while active job {job_id} is still recorded"
  2728. + (f"; runner log tail: {tail}" if tail else "")
  2729. )
  2730. else:
  2731. run["error_message"] = "loop runner pid is not alive" + (f"; runner log tail: {tail}" if tail else "")
  2732. if tail:
  2733. run["startup_log_tail"] = tail
  2734. payload["run"] = run
  2735. print(json.dumps(payload, ensure_ascii=False, indent=2))
  2736. PY
  2737. )"
  2738. if [ "${as_json}" -eq 1 ]; then
  2739. printf '%s\n' "${payload}"
  2740. return 0
  2741. fi
  2742. python3 - "${payload}" <<'PY'
  2743. import json
  2744. import sys
  2745. payload = json.loads(sys.argv[1])
  2746. status = payload.get("status")
  2747. if status == "state_corrupt":
  2748. print("codex-loop: state_corrupt")
  2749. print(f" error: {payload.get('error', 'unknown error')}")
  2750. raise SystemExit(0)
  2751. run = payload.get("run") or {}
  2752. print(f"codex-loop: {run.get('status', 'unknown')}")
  2753. selection = run.get("selection")
  2754. if selection:
  2755. print(f" selection: {selection}")
  2756. executor = run.get("executor")
  2757. if executor:
  2758. print(f" executor: {executor}")
  2759. max_workers = run.get("max_workers")
  2760. if max_workers:
  2761. print(f" max workers: {max_workers}")
  2762. cycles = run.get("cycle_count")
  2763. max_cycles = run.get("max_cycles")
  2764. if cycles is not None and max_cycles is not None:
  2765. print(f" cycles: {cycles}/{max_cycles}")
  2766. batch_ids = run.get("current_batch_ids")
  2767. task_id = run.get("current_task_id")
  2768. if batch_ids:
  2769. print(f" current batch: {batch_ids}")
  2770. elif task_id:
  2771. print(f" current task: {task_id}")
  2772. job_state = run.get("current_job_status")
  2773. if job_state:
  2774. print(f" current job: {job_state}")
  2775. exit_reason = run.get("exit_reason")
  2776. if exit_reason:
  2777. print(f" exit reason: {exit_reason}")
  2778. error_message = run.get("error_message")
  2779. if error_message:
  2780. print(f" error: {error_message}")
  2781. warning = payload.get("warning")
  2782. if warning:
  2783. print(f" warning: {warning}")
  2784. PY
  2785. }
  2786. cmd_stop() {
  2787. ensure_dirs
  2788. [ -f "${RUN_JSON}" ] || {
  2789. echo "codex-loop is not running"
  2790. return 0
  2791. }
  2792. run_state_patch "$(cat <<EOF
  2793. {
  2794. "status": "stopping",
  2795. "stop_requested_at": $(json_escape "$(timestamp_utc)"),
  2796. "updated_at": $(json_escape "$(timestamp_utc)")
  2797. }
  2798. EOF
  2799. )"
  2800. local job_id
  2801. local cancel_status=0
  2802. job_id="$(current_job_id_from_state)"
  2803. if [ -n "${job_id}" ]; then
  2804. cancel_current_job_if_active "user_stop" || cancel_status=$?
  2805. fi
  2806. local runner_pid=""
  2807. runner_pid="$(json_get_file "${RUN_JSON}" "pid" "")"
  2808. if ! is_pid_alive "${runner_pid}"; then
  2809. if [ "${cancel_status}" -ne 0 ]; then
  2810. run_state_patch "$(cat <<EOF
  2811. {
  2812. "status": "runner_lost_job_running",
  2813. "exit_reason": "stop_cancel_failed",
  2814. "pid": null,
  2815. "updated_at": $(json_escape "$(timestamp_utc)"),
  2816. "error_message": $(json_escape "stop could not cancel active job ${job_id}; see runner log")
  2817. }
  2818. EOF
  2819. )"
  2820. release_lock
  2821. echo "stop requested but active job cancellation failed" >&2
  2822. return 1
  2823. fi
  2824. run_state_patch "$(cat <<EOF
  2825. {
  2826. "status": "stopped",
  2827. "exit_reason": "user_stop",
  2828. "pid": null,
  2829. "finished_at": $(json_escape "$(timestamp_utc)"),
  2830. "updated_at": $(json_escape "$(timestamp_utc)")
  2831. }
  2832. EOF
  2833. )"
  2834. cleanup_current_job
  2835. release_lock
  2836. fi
  2837. echo "stop requested"
  2838. }
  2839. prepare_run_lock() {
  2840. local bootstrap_pid="${CODEX_LOOP_BOOTSTRAP_PID:-}"
  2841. local lock_pid=""
  2842. if [ -d "${LOCK_DIR}" ]; then
  2843. lock_pid="$(cat "${LOCK_DIR}/pid" 2>/dev/null || true)"
  2844. if [ -n "${lock_pid}" ] && is_pid_alive "${lock_pid}"; then
  2845. if [ "${lock_pid}" != "$$" ] && [ -z "${bootstrap_pid}" -o "${lock_pid}" != "${bootstrap_pid}" ]; then
  2846. return 1
  2847. fi
  2848. else
  2849. rm -rf "${LOCK_DIR}" 2>/dev/null || true
  2850. fi
  2851. fi
  2852. if [ ! -d "${LOCK_DIR}" ]; then
  2853. if ! acquire_lock; then
  2854. return 1
  2855. fi
  2856. fi
  2857. printf '%s\n' "$$" > "${LOCK_DIR}/pid"
  2858. return 0
  2859. }
  2860. cmd_run() {
  2861. local run_id=""
  2862. while [ $# -gt 0 ]; do
  2863. case "$1" in
  2864. --run-id)
  2865. run_id="${2:-}"
  2866. shift 2
  2867. ;;
  2868. *)
  2869. echo "Unknown option: $1" >&2
  2870. exit 2
  2871. ;;
  2872. esac
  2873. done
  2874. [ -n "${run_id}" ] || {
  2875. echo "run requires --run-id" >&2
  2876. exit 2
  2877. }
  2878. ensure_dirs
  2879. [ -f "${RUN_JSON}" ] || {
  2880. echo "codex-loop run state not found for ${run_id}" >&2
  2881. exit 1
  2882. }
  2883. local state_run_id=""
  2884. state_run_id="$(json_get_file "${RUN_JSON}" "run_id" "")"
  2885. if [ -n "${state_run_id}" ] && [ "${state_run_id}" != "${run_id}" ]; then
  2886. echo "codex-loop run id mismatch: state has ${state_run_id}, requested ${run_id}" >&2
  2887. exit 1
  2888. fi
  2889. if ! prepare_run_lock; then
  2890. local existing_pid=""
  2891. existing_pid="$(cat "${LOCK_DIR}/pid" 2>/dev/null || true)"
  2892. log_line "runner refused to start: lock already held by pid=${existing_pid:-unknown}"
  2893. echo "codex-loop is already running (pid=${existing_pid:-unknown})" >&2
  2894. exit 1
  2895. fi
  2896. trap 'runner_exit_trap "$?" "run"' EXIT
  2897. local selection max_cycles pacing delay_seconds plans_file executor max_workers
  2898. selection="$(json_get_file "${RUN_JSON}" "selection" "all")"
  2899. max_cycles="$(json_get_file "${RUN_JSON}" "max_cycles" "8")"
  2900. pacing="$(json_get_file "${RUN_JSON}" "pacing" "worker")"
  2901. executor="$(json_get_file "${RUN_JSON}" "executor" "breezing")"
  2902. max_workers="$(json_get_file "${RUN_JSON}" "max_workers" "max")"
  2903. delay_seconds="$(json_get_file "${RUN_JSON}" "delay_seconds" "270")"
  2904. plans_file="$(json_get_file "${RUN_JSON}" "plans_file" "$(plans_file_path)")"
  2905. run_state_patch "$(cat <<EOF
  2906. {
  2907. "pid": $$,
  2908. "status": "running",
  2909. "updated_at": $(json_escape "$(timestamp_utc)"),
  2910. "exit_reason": null,
  2911. "finished_at": null,
  2912. "error_message": null,
  2913. "stop_requested_at": null
  2914. }
  2915. EOF
  2916. )"
  2917. while true; do
  2918. if stop_requested; then
  2919. finalize_run "stopped" "user_stop"
  2920. exit 0
  2921. fi
  2922. local cycle_count
  2923. cycle_count="$(json_get_file "${RUN_JSON}" "cycle_count" "0")"
  2924. if [ "${cycle_count}" -ge "${max_cycles}" ]; then
  2925. finalize_run "completed" "max_cycles"
  2926. exit 0
  2927. fi
  2928. local task_id="" batch_ids=""
  2929. if [ "${executor}" = "breezing" ]; then
  2930. batch_ids="$(next_ready_batch_ids "${selection}" "${plans_file}" "${max_workers}" 2>/dev/null || true)"
  2931. task_id="${batch_ids}"
  2932. else
  2933. task_id="$(next_task_id "${selection}" "${plans_file}" 2>/dev/null || true)"
  2934. fi
  2935. if [ -z "${task_id}" ]; then
  2936. finalize_run "completed" "no_remaining_tasks"
  2937. exit 0
  2938. fi
  2939. local next_cycle
  2940. next_cycle=$((cycle_count + 1))
  2941. local cycle_status=0
  2942. if [ "${executor}" = "breezing" ]; then
  2943. if [[ "${batch_ids}" == *,* ]]; then
  2944. HARNESS_PLAN_FILE="${plans_file}" bash "${SELF_SCRIPT}" run-cycle --run-id "${run_id}" --task-id "${batch_ids}" --cycle "${next_cycle}" --executor breezing --max-workers "${max_workers}" || cycle_status=$?
  2945. else
  2946. log_line "cycle ${next_cycle} starting executor=breezing batch=${batch_ids} max_workers=${max_workers}"
  2947. HARNESS_PLAN_FILE="${plans_file}" bash "${SELF_SCRIPT}" run-cycle --run-id "${run_id}" --task-id "${batch_ids}" --cycle "${next_cycle}" --executor task || cycle_status=$?
  2948. fi
  2949. else
  2950. HARNESS_PLAN_FILE="${plans_file}" bash "${SELF_SCRIPT}" run-cycle --run-id "${run_id}" --task-id "${task_id}" --cycle "${next_cycle}" --executor task || cycle_status=$?
  2951. fi
  2952. if [ "${cycle_status}" -ne 0 ]; then
  2953. local recorded_exit_reason
  2954. recorded_exit_reason="$(json_get_file "${RUN_JSON}" "exit_reason" "")"
  2955. if [ "${recorded_exit_reason}" = "runner_exit" ]; then
  2956. RUNNER_FINALIZED=1
  2957. release_lock
  2958. log_line "run finished: status=failed reason=runner_exit"
  2959. exit 1
  2960. fi
  2961. case "${cycle_status}" in
  2962. 21) finalize_run "failed" "task_blocked" "Task(s) ${task_id} did not reach approval" ;;
  2963. 22) finalize_run "failed" "pivot_required" "Plateau detected for task(s) ${task_id}" ;;
  2964. 30) finalize_run "stopped" "user_stop" ;;
  2965. *) finalize_run "failed" "cycle_error" "Cycle ${next_cycle} failed for task ${task_id}" ;;
  2966. esac
  2967. exit 1
  2968. fi
  2969. if stop_requested; then
  2970. finalize_run "stopped" "user_stop"
  2971. exit 0
  2972. fi
  2973. if [ "${next_cycle}" -ge "${max_cycles}" ]; then
  2974. finalize_run "completed" "max_cycles"
  2975. exit 0
  2976. fi
  2977. local remaining=""
  2978. if [ "${executor}" = "breezing" ]; then
  2979. remaining="$(next_ready_batch_ids "${selection}" "${plans_file}" "${max_workers}" 2>/dev/null || true)"
  2980. else
  2981. remaining="$(next_task_id "${selection}" "${plans_file}" 2>/dev/null || true)"
  2982. fi
  2983. if [ -z "${remaining}" ]; then
  2984. finalize_run "completed" "no_remaining_tasks"
  2985. exit 0
  2986. fi
  2987. run_state_patch "$(cat <<EOF
  2988. {
  2989. "status": "waiting",
  2990. "updated_at": $(json_escape "$(timestamp_utc)")
  2991. }
  2992. EOF
  2993. )"
  2994. log_line "cycle ${next_cycle} finished; sleeping ${delay_seconds}s before next ${executor} cycle"
  2995. local slept=0
  2996. while [ "${slept}" -lt "${delay_seconds}" ]; do
  2997. if stop_requested; then
  2998. finalize_run "stopped" "user_stop"
  2999. exit 0
  3000. fi
  3001. sleep 1
  3002. slept=$((slept + 1))
  3003. done
  3004. set_run_field "status" '"running"'
  3005. done
  3006. }
  3007. cmd_run_cycle() {
  3008. local run_id="" task_id="" cycle_number="" executor="task" max_workers="max"
  3009. while [ $# -gt 0 ]; do
  3010. case "$1" in
  3011. --run-id)
  3012. run_id="${2:-}"
  3013. shift 2
  3014. ;;
  3015. --task-id)
  3016. task_id="${2:-}"
  3017. shift 2
  3018. ;;
  3019. --cycle)
  3020. cycle_number="${2:-}"
  3021. shift 2
  3022. ;;
  3023. --executor)
  3024. executor="${2:-}"
  3025. shift 2
  3026. ;;
  3027. --max-workers|--max-wokers)
  3028. if [ $# -lt 2 ] || [[ "${2:-}" == --* ]]; then
  3029. max_workers="max"
  3030. shift
  3031. else
  3032. max_workers="${2:-}"
  3033. shift 2
  3034. fi
  3035. ;;
  3036. *)
  3037. echo "Unknown option: $1" >&2
  3038. exit 2
  3039. ;;
  3040. esac
  3041. done
  3042. [ -n "${run_id}" ] && [ -n "${task_id}" ] && [ -n "${cycle_number}" ] || {
  3043. echo "run-cycle requires --run-id, --task-id, and --cycle" >&2
  3044. exit 2
  3045. }
  3046. trap 'runner_exit_trap "$?" "run-cycle"' EXIT
  3047. case "${executor}" in
  3048. breezing) perform_breezing_cycle "${run_id}" "${task_id}" "${cycle_number}" "${max_workers}" ;;
  3049. task) perform_cycle "${run_id}" "${task_id}" "${cycle_number}" ;;
  3050. *)
  3051. echo "--executor must be breezing or task" >&2
  3052. exit 2
  3053. ;;
  3054. esac
  3055. }
  3056. subcommand="${1:-}"
  3057. if [ "${HARNESS_CODEX_LOOP_SOURCE_ONLY:-0}" = "1" ]; then
  3058. return 0 2>/dev/null || exit 0
  3059. fi
  3060. case "${subcommand}" in
  3061. start)
  3062. shift
  3063. cmd_start "$@"
  3064. ;;
  3065. status)
  3066. shift
  3067. cmd_status "$@"
  3068. ;;
  3069. stop)
  3070. shift
  3071. cmd_stop "$@"
  3072. ;;
  3073. run)
  3074. shift
  3075. cmd_run "$@"
  3076. ;;
  3077. run-cycle)
  3078. shift
  3079. cmd_run_cycle "$@"
  3080. ;;
  3081. local-task-worker)
  3082. shift
  3083. run_local_task_worker "$@"
  3084. ;;
  3085. ""|-h|--help|help)
  3086. usage
  3087. ;;
  3088. *)
  3089. echo "Unknown subcommand: ${subcommand}" >&2
  3090. usage >&2
  3091. exit 2
  3092. ;;
  3093. esac
scripts/evidence/common.sh · Bundled script · 179 lines · 3 findings marked
  1. #!/bin/bash
  2. set -euo pipefail
  3. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  4. HARNESS_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
  5. OUTPUT_ROOT="${HARNESS_EVIDENCE_OUT_DIR:-$HARNESS_ROOT/out/evidence/work-all}"
  6. resolve_timeout_cmd() {
  7. if command -v timeout >/dev/null 2>&1; then
  8. echo "timeout"
  9. elif command -v gtimeout >/dev/null 2>&1; then
  10. echo "gtimeout"
  11. else
  12. echo ""
  13. fi
  14. }
  15. prepare_case_dir() {
  16. local case_name="$1"
  17. local case_root="$OUTPUT_ROOT/$case_name"
  18. local timestamp
  19. timestamp="$(date +%Y%m%d-%H%M%S)"
  20. local case_dir
  21. mkdir -p "$case_root"
  22. if case_dir="$(mktemp -d "$case_root/$timestamp.XXXXXX" 2>/dev/null)"; then
  23. :
  24. else
  25. case_dir="$case_root/$timestamp.$$"
  26. mkdir -p "$case_dir"
  27. fi
  28. echo "$case_dir"
  29. }
  30. copy_fixture_to_case() {
  31. local fixture_name="$1"
  32. local case_dir="$2"
  33. local fixture_src="$HARNESS_ROOT/tests/fixtures/$fixture_name"
  34. local worktree_dir="$case_dir/worktree"
  35. mkdir -p "$worktree_dir"
  36. cp -R "$fixture_src"/. "$worktree_dir"/
  37. echo "$worktree_dir"
  38. }
  39. overlay_tree() {
  40. local src="$1"
  41. local dest="$2"
  42. if [ -d "$src" ]; then
  43. if command -v rsync >/dev/null 2>&1; then
  44. rsync -a "$src/" "$dest/"
  45. else
  46. cp -R "$src"/. "$dest"/
  47. fi
  48. fi
  49. }
  50. init_git_repo() {
  51. local worktree_dir="$1"
  52. git -C "$worktree_dir" init -q
  53. git -C "$worktree_dir" config user.name "Harness Evidence"
  54. git -C "$worktree_dir" config user.email "harness-evidence@example.com"
  55. git -C "$worktree_dir" add .
  56. git -C "$worktree_dir" commit -qm "chore: baseline fixture"
  57. }
  58. write_command_preview() {
  59. local case_dir="$1"
  60. local worktree_dir="$2"
  61. cat > "$case_dir/command-preview.txt" <<EOF
  62. cd "$worktree_dir"
  63. claude --plugin-dir "$HARNESS_ROOT" --dangerously-skip-permissions --output-format json --no-session-persistence -p "\$(cat PROMPT.md)"
  64. EOF
  65. }
  66. run_baseline_tests() {
  67. local worktree_dir="$1"
  68. local log_file="$2"
  69. set +e
  70. (cd "$worktree_dir" && npm test) >"$log_file" 2>&1
  71. local status=$?
  72. set -e
  73. return "$status"
  74. }
  75. run_claude_full() {
  76. local worktree_dir="$1"
  77. local stdout_file="$2"
  78. local stderr_file="$3"
  79. local elapsed_file="$4"
  80. local timeout_cmd
  81. timeout_cmd="$(resolve_timeout_cmd)"
  82. if ! command -v claude >/dev/null 2>&1; then
  83. echo "claude CLI is not installed" >"$stderr_file"
  84. return 127
  85. fi
  86. local start_ts end_ts duration status
  87. start_ts="$(date +%s)"
  88. set +e
  89. if [ -n "$timeout_cmd" ]; then
  90. (cd "$worktree_dir" && "$timeout_cmd" 900 claude --plugin-dir "$HARNESS_ROOT" --dangerously-skip-permissions --output-format json --no-session-persistence -p "$(cat PROMPT.md)") >"$stdout_file" 2>"$stderr_file"
  91. status=$?
  92. else
  93. (cd "$worktree_dir" && claude --plugin-dir "$HARNESS_ROOT" --dangerously-skip-permissions --output-format json --no-session-persistence -p "$(cat PROMPT.md)") >"$stdout_file" 2>"$stderr_file"
  94. status=$?
  95. fi
  96. set -e
  97. end_ts="$(date +%s)"
  98. duration="$((end_ts - start_ts))"
  99. printf '%s\n' "$duration" >"$elapsed_file"
  100. return "$status"
  101. }
  102. claude_hit_rate_limit() {
  103. local stderr_file="$1"
  104. local stdout_file="${2:-}"
  105. local pattern='hit your limit|rate limit|usage limit|quota'
  106. if [ -f "$stderr_file" ] && grep -Eqi "$pattern" "$stderr_file"; then
  107. return 0
  108. fi
  109. if [ -n "$stdout_file" ] && [ -f "$stdout_file" ] && grep -Eqi "$pattern" "$stdout_file"; then
  110. return 0
  111. fi
  112. return 1
  113. }
  114. apply_success_replay() {
  115. local worktree_dir="$1"
  116. local baseline_commit="$2"
  117. local replay_log="$3"
  118. local overlay_dir="$worktree_dir/.evidence-replay/success"
  119. local commit_message_file="$worktree_dir/.evidence-replay/COMMIT_MESSAGE.txt"
  120. local commit_message="test: replay success evidence artifact"
  121. if [ ! -d "$overlay_dir" ]; then
  122. echo "success replay overlay not found: $overlay_dir" >"$replay_log"
  123. return 1
  124. fi
  125. if [ -f "$commit_message_file" ]; then
  126. commit_message="$(cat "$commit_message_file")"
  127. fi
  128. git -C "$worktree_dir" reset --hard -q "$baseline_commit"
  129. git -C "$worktree_dir" clean -fdq
  130. overlay_tree "$overlay_dir" "$worktree_dir"
  131. git -C "$worktree_dir" add Plans.md src/math.js src/format.js
  132. git -C "$worktree_dir" commit -qm "$commit_message"
  133. {
  134. echo "replay_applied=yes"
  135. echo "baseline_commit=$baseline_commit"
  136. echo "overlay_dir=$overlay_dir"
  137. echo "commit_message=$commit_message"
  138. } >"$replay_log"
  139. }
  140. collect_git_artifacts() {
  141. local worktree_dir="$1"
  142. local case_dir="$2"
  143. git -C "$worktree_dir" status --short >"$case_dir/git-status.txt"
  144. git -C "$worktree_dir" diff --stat >"$case_dir/git-diff-stat.txt" || true
  145. git -C "$worktree_dir" diff >"$case_dir/git-diff.patch" || true
  146. git -C "$worktree_dir" log --oneline --decorate -5 >"$case_dir/git-log.txt"
  147. git -C "$worktree_dir" rev-list --count HEAD >"$case_dir/commit-count.txt"
  148. }
scripts/evidence/run-work-all-case.sh · Bundled script · 267 lines · 1 finding marked
  1. #!/bin/bash
  2. set -euo pipefail
  3. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  4. REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
  5. DEFAULT_OUTPUT_ROOT="$REPO_ROOT/out/evidence/work-all"
  6. usage() {
  7. cat <<'EOF'
  8. Usage:
  9. scripts/evidence/run-work-all-case.sh --case <work-all-success|work-all-failure> [--dry-run|--full] [--output-dir PATH]
  10. Modes:
  11. --dry-run Materialize fixture, prompt, and artifact layout only. Does not require claude CLI.
  12. --full Run baseline tests, execute /harness-work all through Claude CLI, then capture artifacts.
  13. If no mode is specified, --dry-run is used.
  14. EOF
  15. }
  16. log() {
  17. printf '[work-all-evidence] %s\n' "$*"
  18. }
  19. die() {
  20. printf '[work-all-evidence] ERROR: %s\n' "$*" >&2
  21. exit 1
  22. }
  23. copy_tree() {
  24. local src="$1"
  25. local dest="$2"
  26. if command -v rsync >/dev/null 2>&1; then
  27. rsync -a --delete "$src/" "$dest/"
  28. else
  29. rm -rf "$dest"
  30. mkdir -p "$dest"
  31. cp -R "$src/." "$dest/"
  32. fi
  33. }
  34. write_summary() {
  35. local summary_file="$1"
  36. local mode="$2"
  37. local observed_outcome="$3"
  38. local baseline_exit="$4"
  39. local final_exit="$5"
  40. local claude_exit="$6"
  41. local commit_delta="$7"
  42. local changed_ok="$8"
  43. local workspace_dir="$9"
  44. local artifacts_dir="${10}"
  45. local expectation="${11}"
  46. cat >"$summary_file" <<EOF
  47. # Work-All Evidence Summary
  48. - Case: $CASE_NAME
  49. - Mode: $mode
  50. - Expected outcome: $expectation
  51. - Observed outcome: $observed_outcome
  52. - Baseline test exit: $baseline_exit
  53. - Final test exit: $final_exit
  54. - Claude exit: $claude_exit
  55. - New commits: $commit_delta
  56. - Changed files within contract: $changed_ok
  57. - Workspace: $workspace_dir
  58. - Artifacts: $artifacts_dir
  59. EOF
  60. }
  61. compare_allowed_changes() {
  62. local changed_file_list="$1"
  63. local allowed_list="$2"
  64. local violation_file="$3"
  65. : >"$violation_file"
  66. while IFS= read -r changed; do
  67. [ -z "$changed" ] && continue
  68. local allowed=0
  69. for expected in $allowed_list; do
  70. if [ "$changed" = "$expected" ]; then
  71. allowed=1
  72. break
  73. fi
  74. done
  75. if [ "$allowed" -eq 0 ]; then
  76. echo "$changed" >>"$violation_file"
  77. fi
  78. done <"$changed_file_list"
  79. if [ -s "$violation_file" ]; then
  80. return 1
  81. fi
  82. return 0
  83. }
  84. CASE_NAME=""
  85. MODE="dry-run"
  86. OUTPUT_ROOT="$DEFAULT_OUTPUT_ROOT"
  87. while [ $# -gt 0 ]; do
  88. case "$1" in
  89. --case)
  90. CASE_NAME="${2:-}"
  91. shift 2
  92. ;;
  93. --dry-run)
  94. MODE="dry-run"
  95. shift
  96. ;;
  97. --full)
  98. MODE="full"
  99. shift
  100. ;;
  101. --output-dir)
  102. OUTPUT_ROOT="${2:-}"
  103. shift 2
  104. ;;
  105. -h|--help)
  106. usage
  107. exit 0
  108. ;;
  109. *)
  110. die "unknown argument: $1"
  111. ;;
  112. esac
  113. done
  114. [ -n "$CASE_NAME" ] || die "--case is required"
  115. CASE_DIR="$REPO_ROOT/tests/fixtures/$CASE_NAME"
  116. [ -d "$CASE_DIR" ] || die "fixture not found: $CASE_DIR"
  117. FIXTURE_ENV="$CASE_DIR/fixture.env"
  118. [ -f "$FIXTURE_ENV" ] || die "fixture metadata missing: $FIXTURE_ENV"
  119. # shellcheck disable=SC1090
  120. source "$FIXTURE_ENV"
  121. RUN_ID="$(date +"%Y%m%d-%H%M%S")"
  122. ARTIFACTS_DIR="$OUTPUT_ROOT/$CASE_NAME/$RUN_ID"
  123. WORKSPACE_DIR="$ARTIFACTS_DIR/workspace"
  124. mkdir -p "$ARTIFACTS_DIR"
  125. copy_tree "$CASE_DIR" "$WORKSPACE_DIR"
  126. PROMPT_PATH="$WORKSPACE_DIR/PROMPT.md"
  127. [ -f "$PROMPT_PATH" ] || die "PROMPT.md missing in workspace"
  128. git -C "$WORKSPACE_DIR" init -q
  129. git -C "$WORKSPACE_DIR" config user.name "Harness Evidence"
  130. git -C "$WORKSPACE_DIR" config user.email "evidence@local.invalid"
  131. git -C "$WORKSPACE_DIR" add .
  132. git -C "$WORKSPACE_DIR" commit -q -m "chore: evidence baseline"
  133. BASELINE_COMMIT="$(git -C "$WORKSPACE_DIR" rev-parse HEAD)"
  134. BASELINE_COMMIT_COUNT="$(git -C "$WORKSPACE_DIR" rev-list --count HEAD)"
  135. cp "$FIXTURE_ENV" "$ARTIFACTS_DIR/fixture.env"
  136. cp "$PROMPT_PATH" "$ARTIFACTS_DIR/prompt.txt"
  137. cat >"$ARTIFACTS_DIR/paths.txt" <<EOF
  138. output_root=$OUTPUT_ROOT
  139. artifacts_dir=$ARTIFACTS_DIR
  140. workspace_dir=$WORKSPACE_DIR
  141. baseline_commit=$BASELINE_COMMIT
  142. EOF
  143. if [ "$MODE" = "dry-run" ]; then
  144. write_summary \
  145. "$ARTIFACTS_DIR/summary.md" \
  146. "$MODE" \
  147. "fixture-inspection-only" \
  148. "not-run" \
  149. "not-run" \
  150. "not-run" \
  151. "0" \
  152. "not-checked" \
  153. "$WORKSPACE_DIR" \
  154. "$ARTIFACTS_DIR" \
  155. "$EXPECTED_OUTCOME"
  156. log "dry-run completed: $ARTIFACTS_DIR"
  157. exit 0
  158. fi
  159. command -v claude >/dev/null 2>&1 || die "claude CLI not found. Use --dry-run for fixture inspection."
  160. command -v npm >/dev/null 2>&1 || die "npm not found. Use --dry-run for fixture inspection."
  161. BASELINE_TEST_EXIT=0
  162. FINAL_TEST_EXIT=0
  163. CLAUDE_EXIT=0
  164. OBSERVED_OUTCOME="unknown"
  165. CHANGED_OK="yes"
  166. set +e
  167. (cd "$WORKSPACE_DIR" && npm test) >"$ARTIFACTS_DIR/test-before.log" 2>&1
  168. BASELINE_TEST_EXIT=$?
  169. set -e
  170. if [ "$BASELINE_TEST_EXIT" -ne "$EXPECT_BASELINE_TEST_EXIT" ]; then
  171. die "baseline test exit mismatch: expected $EXPECT_BASELINE_TEST_EXIT, got $BASELINE_TEST_EXIT"
  172. fi
  173. START_TS="$(date +%s)"
  174. set +e
  175. (cd "$WORKSPACE_DIR" && claude --plugin-dir "$REPO_ROOT" --dangerously-skip-permissions --output-format json --no-session-persistence -p "$(cat "$PROMPT_PATH")") \
  176. >"$ARTIFACTS_DIR/claude.stdout.log" 2>"$ARTIFACTS_DIR/claude.stderr.log"
  177. CLAUDE_EXIT=$?
  178. set -e
  179. END_TS="$(date +%s)"
  180. ELAPSED_SECONDS=$((END_TS - START_TS))
  181. echo "$ELAPSED_SECONDS" >"$ARTIFACTS_DIR/elapsed-seconds.txt"
  182. set +e
  183. (cd "$WORKSPACE_DIR" && npm test) >"$ARTIFACTS_DIR/test-after.log" 2>&1
  184. FINAL_TEST_EXIT=$?
  185. set -e
  186. FINAL_COMMIT_COUNT="$(git -C "$WORKSPACE_DIR" rev-list --count HEAD)"
  187. COMMIT_DELTA=$((FINAL_COMMIT_COUNT - BASELINE_COMMIT_COUNT))
  188. if [ "$COMMIT_DELTA" -gt 0 ]; then
  189. git -C "$WORKSPACE_DIR" diff --stat "$BASELINE_COMMIT"..HEAD >"$ARTIFACTS_DIR/git-diff-stat.txt"
  190. git -C "$WORKSPACE_DIR" diff "$BASELINE_COMMIT"..HEAD >"$ARTIFACTS_DIR/git-diff.patch"
  191. git -C "$WORKSPACE_DIR" diff --name-only "$BASELINE_COMMIT"..HEAD >"$ARTIFACTS_DIR/changed-files.txt"
  192. else
  193. git -C "$WORKSPACE_DIR" diff --stat "$BASELINE_COMMIT" >"$ARTIFACTS_DIR/git-diff-stat.txt" || true
  194. git -C "$WORKSPACE_DIR" diff "$BASELINE_COMMIT" >"$ARTIFACTS_DIR/git-diff.patch" || true
  195. git -C "$WORKSPACE_DIR" diff --name-only "$BASELINE_COMMIT" >"$ARTIFACTS_DIR/changed-files.txt" || true
  196. fi
  197. git -C "$WORKSPACE_DIR" status --short >"$ARTIFACTS_DIR/git-status.txt"
  198. git -C "$WORKSPACE_DIR" log --oneline --decorate -5 >"$ARTIFACTS_DIR/git-log.txt"
  199. if ! compare_allowed_changes "$ARTIFACTS_DIR/changed-files.txt" "$ALLOWED_CHANGED_FILES" "$ARTIFACTS_DIR/contract-violations.txt"; then
  200. CHANGED_OK="no"
  201. fi
  202. if [ "$EXPECTED_OUTCOME" = "success" ] && [ "$FINAL_TEST_EXIT" -eq 0 ] && [ "$CHANGED_OK" = "yes" ]; then
  203. OBSERVED_OUTCOME="success"
  204. elif [ "$EXPECTED_OUTCOME" = "failure" ] && [ "$FINAL_TEST_EXIT" -ne 0 ] && [ "$COMMIT_DELTA" -eq 0 ] && [ "$CHANGED_OK" = "yes" ]; then
  205. OBSERVED_OUTCOME="failure"
  206. else
  207. OBSERVED_OUTCOME="mismatch"
  208. fi
  209. write_summary \
  210. "$ARTIFACTS_DIR/summary.md" \
  211. "$MODE" \
  212. "$OBSERVED_OUTCOME" \
  213. "$BASELINE_TEST_EXIT" \
  214. "$FINAL_TEST_EXIT" \
  215. "$CLAUDE_EXIT" \
  216. "$COMMIT_DELTA" \
  217. "$CHANGED_OK" \
  218. "$WORKSPACE_DIR" \
  219. "$ARTIFACTS_DIR" \
  220. "$EXPECTED_OUTCOME"
  221. if [ "$OBSERVED_OUTCOME" = "mismatch" ]; then
  222. die "observed outcome did not match expectation. See $ARTIFACTS_DIR/summary.md"
  223. fi
  224. log "full run completed: $ARTIFACTS_DIR"

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.