Learning Objectives
- Package the seven workbench surfaces into one drop-in directory.
- Pin the schemas, scripts, and templates so a new repo gets a known-good baseline.
- Add a single installer script that lays down the pack idempotently.
- Decide what stays in the pack and what stays out, defending the cut for each.
- Demonstrate one agent-assisted repository change with evidence a reviewer can reproduce.
The Problem
A workbench that lives in a Google Doc, a chat history, and three half-remembered scripts is a workbench that gets rebuilt every quarter. The cure is a versioned pack: a repo or directory with the surfaces, the schemas, the scripts, and a one-command installer.
You will end this lesson with outputs/agent-workbench-pack/ shipped on disk and a bin/install.sh that drops it into any target repo.
The Concept
flowchart TD
Pack[agent-workbench-pack/] --> Docs[AGENTS.md + docs/]
Pack --> Schemas[schemas/]
Pack --> Scripts[scripts/]
Pack --> Bin[bin/install.sh]
Bin --> Repo[target repo]
Repo --> Surfaces[all seven workbench surfaces wired]
The pack layout
outputs/agent-workbench-pack/
├── AGENTS.md
├── docs/
│ ├── agent-rules.md
│ ├── reliability-policy.md
│ ├── handoff-protocol.md
│ └── reviewer-rubric.md
├── schemas/
│ ├── agent_state.schema.json
│ ├── task_board.schema.json
│ └── scope_contract.schema.json
├── scripts/
│ ├── init_agent.py
│ ├── run_with_feedback.py
│ ├── verify_agent.py
│ └── generate_handoff.py
├── bin/
│ └── install.sh
└── README.md
What stays in, what stays out
In:
- Surface schemas. They are the contract.
- The four scripts above. They are the runtime.
- The four docs. They are the rules and the rubric.
Out:
- Project-specific tasks. Tasks belong on the target repo's board, not in the pack.
- Vendor SDK calls. The pack is framework-agnostic.
- Onboarding prose. The pack lives next to the team's existing onboarding, not inside it.
The installer
A short bin/install.sh (or bin/install.py):
- Refuses to install over an existing pack without
--force. - Copies the pack into the target repo.
- Wires up CI if a
.github/workflows/exists. - Prints next steps: fill in the board, set acceptance commands, run the init script.
Versioning
The pack carries a VERSION file. Schema bumps and script changes that require migrations bump the major. Doc-only changes bump the patch. The target repo's agent_state.json records which pack version it was initialized against.
Interactive figure coming later.
Build It
code/main.py assembles the pack into outputs/agent-workbench-pack/ next to the lesson, seeded with the schemas and scripts from the previous lessons in this mini-track and the docs you already wrote.
Run it:
python3 code/main.py
The script copies and pins the surfaces, writes the README, prints the pack tree, and exits zero. Re-running is idempotent.
Production patterns in the wild
A pack is only valuable if it survives forks, updates, and an unfriendly upstream. Four patterns make that work.
VERSION is the contract, not the marketing. Major bumps require a state migration. Minor bumps require a checker re-run. Patch bumps are doc-only. The installer writes .workbench-version into the target repo on every install; lint_pack.py refuses to ship if the target's lock disagrees with the pack's VERSION. This is how npm, Cargo, and pyproject.toml survive 10 years of churn; nothing about agents changes the rules.
Single source for cross-tool distribution. Nx ships one nx ai-setup that lays down AGENTS.md, CLAUDE.md, .cursor/rules/, .github/copilot-instructions.md, and an MCP server from a single config. The pack should do the same; the installer emits the symlinks (ln -s AGENTS.md CLAUDE.md) so a single source of truth fans out to every coding agent. Forking the pack to support one tool over another is a failure mode.
uninstall.sh that refuses on non-trivial state. Uninstalling the pack must not delete the user's agent_state.json, task_board.json, or outputs/. The uninstaller removes the schemas, scripts, docs, and AGENTS.md (with --keep-agents-md opt-out) and refuses to proceed if state files have any uncommitted changes. State belongs to the user; the pack does not own it.
Skill-as-publishable. SkillKit-style distribution. The pack ships as a SkillKit skill: skillkit install agent-workbench-pack lays it down across 32 AI agents from a single source. The pack repo is the source of truth; SkillKit is the distribution channel. Vendor lock-in collapses; the seven surfaces stay the same.
Use It
Three places the pack ships:
- As a directory you drop into a repo.
cp -r outputs/agent-workbench-pack /path/to/repo. - As a public template repo. Fork-and-customize, with
VERSIONcontrolling drift. - As a SkillKit skill. Wired into your agent product so a single command lays it down.
The pack is the recipe. Each install is a serving.
Ship It
outputs/skill-workbench-pack.md generates a project-tuned pack: rules sharpened to the team's history, scope globs matched to the repo, rubric dimensions extended with one domain-specific entry.
Exercises
- Decide which optional fifth doc deserves promotion into the canonical pack. Defend the cut.
- Rewrite the installer as Python with a
--dry-runflag. Compare ergonomics against bash. - Add a
bin/uninstall.shthat safely removes the pack and refuses if state files have non-trivial history. What counts as non-trivial? - Add a
lint_pack.pythat fails when the pack drifts fromVERSION. Wire it into CI for the pack's own repo. - Author the migration runbook from a hand-rolled workbench to this pack. What is the order of operations that minimizes downtime?
Career Practice: Prove One Repository Change
The packaging demo proves that the assembler runs and produces files. It does not prove that your agent can complete a new task, that the generated checks prove that task, or that a deployed system works. Keep those claims separate.
Choose a small real task in a repository you own or have permission to change. Use one coding agent you already have access to. A bug fix, a bounded feature, or an operational improvement is enough; installing several agents is not part of the exercise.
Budget a separate working session beyond the packaging lab. Copy the evidence template linked below into your own learning-artifacts/ directory. Preserve the checked-in template and pack as reference material.
1. Frame the task and choose the autonomy
Use the task frame from lesson 43 and the evidence plan from lesson 44. Record the starting revision, observable goal, non-goals, allowed paths, and acceptance evidence. Identify the real user or operator who needs the behavior.
Choose a working mode: guided steps, checkpointed implementation, or a bounded autonomous run. Explain why the uncertainty, consequences, and reversibility justify it. A small local refactor may need fewer checkpoints than a change to access control.
Set a wall-time budget and a token or cost limit if the agent exposes one. Record unavailable measurements honestly. Define a stop condition for repeated failure, new permissions, budget exhaustion, or an unresolved contract decision; name who can resolve it.
2. Prepare the smallest useful environment
Retrieve the relevant implementation, caller, test, and local instructions. Record why each source belongs in context and which current evidence would override a stale note. Do not load the whole repository by default.
Make one explicit choice for each relevant extension: a skill supplies a repeatable procedure; an MCP tool supplies access; a hook runs a deterministic check; a plugin packages capabilities. Keep an extension only when the task needs it, with the least permissions that let it work.
Record the context or maintenance cost of one proposed addition you reject. Recheck one stale memory or instruction, then retire or replace it in your learner-owned setup when the evidence supports that decision. Rerun the affected check to confirm the removal did not lose a needed constraint.
3. Capture the baseline and implement
Before editing, run the closest existing check and demonstrate the requested behavior's current state. Keep the command, revision, result, and evidence location. A feature that does not exist yet still has a baseline: record the observed response or unsupported operation.
Let the agent implement inside the contract. Keep an intervention log with the reason for each correction, permission change, or plan revision. Delegation is optional; if useful, apply lesson 45's ownership and integration contract before adding another worker.
4. Challenge the evidence
Choose proof that observes the changed surface. For a UI, rebuild and inspect the served journey at relevant widths. For an API, inspect the request and serialized response. For a CLI, run the built command and check its exit code and output. Select the checks your task needs and explain their limits.
Write an expected result from the task contract independently of the agent's implementation. In a disposable copy, introduce one specific incorrect result, such as accepting an invalid value or dropping a required response field. Run the same acceptance check: it must fail for that reason.
If it stays green, strengthen the assertion or observation before trusting it. Restore the correct implementation and rerun successfully. Keep both receipts. A syntax error or broken test setup does not count as detecting the regression.
Review the final diff, including changed tests, against the original goal and allowed paths. Ask a peer or a separate reviewer session to challenge the weakest proof without editing the implementation. You still own the final judgment; another agent's agreement is not execution evidence.
5. Rehearse operation and recovery
Run the changed artifact in a disposable local or staging environment. Label every observation local, staging, or live, with the exact revision or artifact identity. A local rehearsal supports a local claim; production deployment is not required for this exercise.
Choose one failure signal related to the task, a threshold, an observation window, and an owner. Explain the response when that threshold is crossed. Trigger the signal safely in the rehearsal and retain the observed log, metric, or response.
Rehearse rollback to a known-good artifact and check that the previous behavior is restored. Account for persistent data when applicable; replacing a binary alone may not reverse a data change. Record any recovery step you could not verify.
6. Improve the next run and hand it off
Compare the result with the baseline, including elapsed time, available usage data, and human interventions. One task shows what happened on that task; it does not establish that an agent is generally faster or more reliable.
Promote one observed correction into a test, a smaller permission boundary, an automation, or a clearer example using lesson 46. Rerun the affected check. Remove temporary mutations and leave the final branch, changed files, open risks, and next action explicit for the next session.
Manual review rubric
Have the reviewer inspect the evidence files and reproduce at least the weakest acceptance check. Use demonstrated, needs revision, or unverified for each row, with an evidence pointer and a reason. Filled fields and passing packaging scripts are not substitutes for these observations.
| Dimension | Evidence the reviewer should challenge |
|---|---|
| Task and autonomy | Starting behavior, bounded goal, justified permissions, budget, and a usable stop rule |
| Context and environment | Relevant sources, justified tool access, and a rechecked retirement decision |
| Verification | Actual before/after behavior and a deliberate incorrect result that the same check rejects |
| Review and operation | Inspected diff, independent challenge, labeled runtime observation, and rehearsed recovery |
| Iteration and handoff | One verified improvement, honest limits, clean final state, and a reproducible next action |
Resolve needs revision findings before claiming the task complete. Leave unavailable evidence unverified and narrow the claim accordingly. The portfolio demonstrates your engineering judgment on a bounded task; it is not a hiring or deployment guarantee.
Shipped Artifact
Keep the reusable pack and your completed copy of career-agent-evidence.md. The template connects the task frame, execution plan, runtime receipts, review, recovery rehearsal, and handoff into one reviewable case study.
Key Terms
| Term | What people say | What it actually means |
|---|---|---|
| Workbench pack | "The starter kit" | A versioned directory carrying all seven surfaces |
| Installer | "Setup script" | bin/install.sh that lays the pack down idempotently |
| Pack version | "VERSION" | Major bumps for schema/script changes, patch for doc-only |
| Drop-in pack | "cp -r and go" | Pack works without per-repo customization on day one |
| Forkable template | "GitHub template" | Public repo that GitHub's "Use this template" can clone from |
Further Reading
- Phases 14 · 31 to 14 · 41 — every surface this pack bundles
- SkillKit — install this skill across 32 AI agents
- Nx Blog, Teach Your AI Agent How to Work in a Monorepo — single-source generator across six tools
- agents.md — the open spec — what your pack's router must implement
- HKUDS/OpenHarness — reference implementation of a pack-equivalent
- Augment Code, A good AGENTS.md is a model upgrade — pack docs quality bar
- Anthropic, Effective harnesses for long-running agents
- Anthropic, Harness design for long-running application development
- Phase 14 · 30 — eval-driven agent development that consumes the pack's verification gate
- Phase 14 · 41 — the before/after benchmark this pack improves on
Code
Take-away files
agent-workbench-pack/AGENTS.md
# AGENTS.md You are working inside a repository that runs with an agent workbench. Read these before acting: 1. `agent_state.json` — where the last session stopped. 2. `task_board.json` — what is in flight, what is next. 3. `docs/agent-rules.md` — startup, forbidden, done, uncertainty, approval. 4. `docs/reliability-policy.md` — failure modes this workbench is designed to absorb. 5. `docs/handoff-protocol.md` — what session end must produce. 6. `docs/reviewer-rubric.md` — how completed work is judged. Verification command: see `acceptance_criteria` in the active task on the board. Pack version: 1.0.0
agent-workbench-pack/bin/install.sh
#!/usr/bin/env bash
set -euo pipefail
# Install the agent workbench pack into the current repo.
# Usage: bin/install.sh [--force]
FORCE="${1:-}"
TARGET="$(pwd)"
PACK_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
required=("AGENTS.md" "VERSION" "docs" "schemas" "scripts")
for path in "${required[@]}"; do
if [[ ! -e "$PACK_ROOT/$path" ]]; then
echo "missing pack source: $PACK_ROOT/$path" >&2
exit 1
fi
done
if [[ -e "$TARGET/AGENTS.md" && "$FORCE" != "--force" ]]; then
echo "AGENTS.md already exists. Pass --force to overwrite." >&2
exit 1
fi
cp "$PACK_ROOT/AGENTS.md" "$TARGET/AGENTS.md"
mkdir -p "$TARGET/docs" "$TARGET/schemas" "$TARGET/scripts"
cp -r "$PACK_ROOT/docs/." "$TARGET/docs/"
cp -r "$PACK_ROOT/schemas/." "$TARGET/schemas/"
cp -r "$PACK_ROOT/scripts/." "$TARGET/scripts/"
cat "$PACK_ROOT/VERSION" > "$TARGET/.workbench-version"
echo "pack installed at version $(cat "$PACK_ROOT/VERSION")"
echo "next: edit task_board.json, set acceptance commands, run scripts/init_agent.py"
agent-workbench-pack/docs/agent-rules.md
# Agent Rules ## startup/state-file-fresh - category: startup - check: state_file_fresh Agent must read agent_state.json before any tool call. ## forbidden/no-out-of-scope-writes - category: forbidden - check: no_out_of_scope_writes Never edit a file outside the active task's scope contract. ## done/tests-pass - category: definition_of_done - check: tests_pass A task is done only when every acceptance command exits zero. ## uncertainty/open-question-note - category: uncertainty - check: opened_question_when_unsure When confidence is below threshold, open a question note instead of guessing. ## approval/new-dependency - category: approval - check: new_dependency_approved Adding a runtime dependency requires explicit human approval.
agent-workbench-pack/docs/handoff-protocol.md
# Handoff Protocol Every session ends with a handoff packet containing: - summary - changed_files - commands_run - failed_attempts - open_risks (severity + detail) - next_action (one concrete step) - verdict_pointer (paths to verification + review reports) The packet ships as both handoff.md (humans) and handoff.json (next agent). Missing fields halt the session-end hook.
agent-workbench-pack/docs/reliability-policy.md
# Reliability Policy The workbench absorbs the five industry-recurring failure modes: 1. Hallucinated action — caught by the rule set + verification gate. 2. Scope creep — caught by the scope contract diff check. 3. Cascading errors — caught by feedback records + refuse-on-null-exit. 4. Context loss — absorbed by repo memory; chat is not the source of truth. 5. Tool misuse — caught by the reviewer rubric's verification dimension. The policy is enforced by the verification gate. The override path is signed and audited; agents cannot self-override.
agent-workbench-pack/docs/reviewer-rubric.md
# Reviewer Rubric Five dimensions, scored 0 to 2. 1. Problem fit — did the change solve the task as stated? 2. Scope discipline — were edits confined to the contract? 3. Assumptions — are hidden assumptions written down? 4. Verification quality — does acceptance actually prove the goal? 5. Handoff readiness — can the next session pick up cleanly? Total >= 7 with no zeros: pass. Total 5-6: soft fail. Below 5 or any zero: hard fail.
agent-workbench-pack/README.md
# Agent Workbench Pack Drop-in workbench for any repo that wants reliable agent work. ## What you get - `AGENTS.md` short router into the rest of the pack. - `docs/` rules, reliability policy, handoff protocol, reviewer rubric. - `schemas/` JSON Schemas for state, board, and scope contract. - `scripts/` init, feedback runner, verification gate, handoff generator. - `bin/install.sh` idempotent installer. ## Quickstart ``` bin/install.sh $EDITOR task_board.json python3 scripts/init_agent.py ``` ## Versioning The `VERSION` file is the contract. Major bumps require a state migration.
agent-workbench-pack/schemas/agent_state.schema.json
{
"$id": "agent_state.schema.json",
"type": "object",
"required": [
"schema_version",
"active_task_id",
"touched_files",
"next_action"
],
"properties": {
"schema_version": {
"type": "integer",
"enum": [
1
]
},
"active_task_id": {
"type": [
"string",
"null"
]
},
"touched_files": {
"type": "array",
"items": {
"type": "string"
}
},
"assumptions": {
"type": "array",
"items": {
"type": "string"
}
},
"blockers": {
"type": "array",
"items": {
"type": "string"
}
},
"next_action": {
"type": "string"
}
}
}
agent-workbench-pack/schemas/scope_contract.schema.json
{
"$id": "scope_contract.schema.json",
"type": "object",
"required": [
"task_id",
"goal",
"allowed_files",
"forbidden_files",
"acceptance_criteria",
"rollback_plan"
],
"properties": {
"task_id": {
"type": "string"
},
"goal": {
"type": "string"
},
"allowed_files": {
"type": "array",
"items": {
"type": "string"
}
},
"forbidden_files": {
"type": "array",
"items": {
"type": "string"
}
},
"acceptance_criteria": {
"type": "array",
"items": {
"type": "string"
}
},
"rollback_plan": {
"type": "string"
},
"approvals_required": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
agent-workbench-pack/schemas/task_board.schema.json
{
"$id": "task_board.schema.json",
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"goal",
"owner",
"acceptance",
"status"
],
"properties": {
"id": {
"type": "string",
"pattern": "^T-\\d{3,}$"
},
"goal": {
"type": "string"
},
"owner": {
"type": "string",
"enum": [
"builder",
"reviewer",
"human"
]
},
"acceptance": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1
},
"status": {
"type": "string",
"enum": [
"todo",
"in_progress",
"done",
"blocked"
]
}
}
}
}
agent-workbench-pack/scripts/generate_handoff.py
#!/usr/bin/env python3
"""End-of-session handoff packet generator. See Phase 14 · 40."""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def _load_json(path: Path, default):
if not path.exists():
return default
return json.loads(path.read_text())
def _load_jsonl(path: Path) -> list[dict]:
if not path.exists():
return []
return [json.loads(ln) for ln in path.read_text().splitlines() if ln.strip()]
def derive_risks(verdict: dict, state: dict, review: dict) -> list[dict[str, str]]:
risks: list[dict[str, str]] = []
for f in verdict.get("findings", []) or []:
if isinstance(f, dict) and f.get("severity") in ("warn", "block"):
risks.append({"severity": str(f.get("severity")), "detail": str(f.get("detail"))})
for blocker in state.get("blockers") or []:
risks.append({"severity": "warn", "detail": f"open blocker: {blocker}"})
try:
total = int(review.get("total", 10))
except (TypeError, ValueError):
total = 10
if total < 7:
risks.append({"severity": "warn", "detail": f"review total {review.get('total')} below 7"})
return risks
def generate_handoff(task_id: str, session_id: str | None = None) -> dict[str, object]:
state = _load_json(ROOT / "agent_state.json", {})
verdict = _load_json(ROOT / "outputs" / "verification" / f"{task_id}.json", {})
review = _load_json(ROOT / "outputs" / "review" / f"{task_id}.json", {})
feedback = _load_jsonl(ROOT / "feedback_record.jsonl")
diff = _load_json(ROOT / "outputs" / "diff_summary.json", {})
payload = {
"session_id": session_id or str(int(time.time())),
"timestamp": time.time(),
"task_id": task_id,
"summary": f"task {task_id}: gate={verdict.get('passed')} review={review.get('verdict')}",
"changed_files": diff.get("touched", []),
"commands_run": [str(r.get("command")) for r in feedback],
"failed_attempts": [
f"{r.get('command')} -> exit {r.get('exit_code')}"
for r in feedback if r.get("exit_code") not in (0, None)
],
"open_risks": derive_risks(verdict, state, review),
"next_action": str(state.get("next_action") or "no next_action recorded; needs human"),
"verdict_pointer": {
"verdict": f"outputs/verification/{task_id}.json",
"review": f"outputs/review/{task_id}.json",
},
}
out = ROOT / "outputs" / "handoff" / payload["session_id"]
out.mkdir(parents=True, exist_ok=True)
(out / "handoff.json").write_text(json.dumps(payload, indent=2) + "\n")
(out / "handoff.md").write_text(_render_markdown(payload))
return payload
def _render_markdown(p: dict[str, object]) -> str:
def bullets(items):
return [f"- {x}" for x in items] or ["- none"]
lines = [
f"# Handoff: {p['task_id']}",
"",
f"**Summary.** {p['summary']}",
"",
"## Changed files",
*bullets(p["changed_files"]),
"",
"## Commands run",
*bullets(p["commands_run"]),
"",
"## Failed attempts",
*bullets(p["failed_attempts"]),
"",
"## Open risks",
*bullets([f"[{r['severity']}] {r['detail']}" for r in p["open_risks"]]),
"",
"## Next action",
str(p["next_action"]),
"",
"## Receipts",
f"- verdict: `{p['verdict_pointer']['verdict']}`",
f"- review: `{p['verdict_pointer']['review']}`",
]
return "\n".join(lines) + "\n"
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("task_id")
ap.add_argument("--session-id", default=None)
args = ap.parse_args()
try:
payload = generate_handoff(args.task_id, args.session_id)
except Exception as exc:
print(f"handoff failed: {exc}", file=sys.stderr)
return 1
print(f"wrote outputs/handoff/{payload['session_id']}/{{handoff.json,handoff.md}}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
agent-workbench-pack/scripts/init_agent.py
#!/usr/bin/env python3
"""Workbench init script. See Phase 14 · 35 for the from-scratch build."""
from __future__ import annotations
import importlib.util
import json
import os
import shutil
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
REPORT_PATH = ROOT / "init_report.json"
STATE_PATH = ROOT / "agent_state.json"
REQUIRED_PYTHON = (3, 10)
REQUIRED_DEPS: list[str] = []
TEST_COMMAND = os.environ.get("WORKBENCH_TEST_COMMAND", "python3")
REQUIRED_ENV: list[str] = []
FRESH_SECONDS = 24 * 60 * 60
def _probe_runtime() -> tuple[str, str, str]:
major, minor = sys.version_info[:2]
ok = (major, minor) >= REQUIRED_PYTHON
return ("runtime", "pass" if ok else "fail", f"python {major}.{minor}")
def _probe_deps() -> tuple[str, str, str]:
missing = [d for d in REQUIRED_DEPS if importlib.util.find_spec(d) is None]
return ("dependencies", "fail" if missing else "pass", f"missing: {missing}" if missing else "all importable")
def _probe_test_command() -> tuple[str, str, str]:
return ("test_command", "pass" if shutil.which(TEST_COMMAND) else "fail", f"{TEST_COMMAND} on PATH")
def _probe_env() -> tuple[str, str, str]:
missing = [k for k in REQUIRED_ENV if not os.environ.get(k)]
return ("env", "fail" if missing else "pass", f"missing: {missing}" if missing else "all present")
def _probe_state() -> tuple[str, str, str]:
if not STATE_PATH.exists():
return ("state_freshness", "warn", "no state file yet")
age = time.time() - STATE_PATH.stat().st_mtime
if age > FRESH_SECONDS:
return ("state_freshness", "warn", f"state is {int(age // 3600)}h old")
return ("state_freshness", "pass", f"state is {int(age)}s old")
def main() -> int:
probes = [_probe_runtime(), _probe_deps(), _probe_test_command(), _probe_env(), _probe_state()]
REPORT_PATH.write_text(
json.dumps(
{"timestamp": time.time(), "probes": [{"name": n, "status": s, "detail": d} for n, s, d in probes]},
indent=2,
)
+ "\n"
)
width = max(len(n) for n, _, _ in probes)
for name, status, detail in probes:
print(f" {name:<{width}} {status:>4} {detail}")
failed = [n for n, s, _ in probes if s == "fail"]
if failed:
print(f"\ninit failed: {failed}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
agent-workbench-pack/scripts/run_with_feedback.py
#!/usr/bin/env python3
"""Structured shell-command runner. See Phase 14 · 37."""
from __future__ import annotations
import argparse
import json
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RECORD = ROOT / "feedback_record.jsonl"
HEAD_LINES = 5
TAIL_LINES = 30
def deterministic_tail(text: str) -> tuple[str, int]:
lines = text.splitlines()
if len(lines) <= HEAD_LINES + TAIL_LINES:
return text, 0
cut = len(lines) - HEAD_LINES - TAIL_LINES
return "\n".join(lines[:HEAD_LINES] + [f"...truncated {cut} lines..."] + lines[-TAIL_LINES:]), cut
def run_with_feedback(command: list[str], agent_note: str = "", timeout_s: float = 30.0) -> dict[str, object]:
started = time.time()
record: dict[str, object] = {"command": command, "agent_note": agent_note, "started_at": started}
try:
completed = subprocess.run(command, capture_output=True, text=True, timeout=timeout_s)
out, cut_out = deterministic_tail(completed.stdout)
err, cut_err = deterministic_tail(completed.stderr)
record.update(
stdout_tail=out, stderr_tail=err, exit_code=completed.returncode,
duration_ms=int((time.time() - started) * 1000),
truncations={"stdout": cut_out, "stderr": cut_err},
)
except subprocess.TimeoutExpired as exc:
partial_out = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
partial_err = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
out, cut_out = deterministic_tail(partial_out)
err, cut_err = deterministic_tail(partial_err)
record.update(
stdout_tail=out, stderr_tail=err, exit_code=None,
duration_ms=int((time.time() - started) * 1000),
error=f"timeout after {timeout_s}s",
truncations={"stdout": cut_out, "stderr": cut_err},
)
except FileNotFoundError as exc:
record.update(stdout_tail="", stderr_tail="", exit_code=None,
duration_ms=int((time.time() - started) * 1000), error=str(exc))
with RECORD.open("a") as fh:
fh.write(json.dumps(record) + "\n")
return record
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("command", nargs="+")
ap.add_argument("--note", default="")
ap.add_argument("--timeout", type=float, default=30.0)
args = ap.parse_args()
rec = run_with_feedback(args.command, agent_note=args.note, timeout_s=args.timeout)
print(json.dumps(rec, indent=2))
return 0 if rec.get("exit_code") == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
agent-workbench-pack/scripts/verify_agent.py
#!/usr/bin/env python3
"""Deterministic verification gate. See Phase 14 · 38."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def _load_json(path: Path, default):
if not path.exists():
return default
return json.loads(path.read_text())
def _load_jsonl(path: Path) -> list[dict]:
if not path.exists():
return []
return [json.loads(ln) for ln in path.read_text().splitlines() if ln.strip()]
def _normalize_command(cmd) -> str:
if isinstance(cmd, list):
return " ".join(str(part) for part in cmd)
return str(cmd)
def check_acceptance(accept: list[str], feedback: list[dict]) -> list[dict]:
findings: list[dict] = []
commands_run = [_normalize_command(r.get("command")) for r in feedback]
accept_set = set(accept)
for cmd in accept:
if cmd not in commands_run:
findings.append({"code": "acceptance.missing", "severity": "block", "detail": f"never ran: {cmd}"})
for r in feedback:
cmd_str = _normalize_command(r.get("command"))
if r.get("exit_code") is None:
findings.append({"code": "feedback.null_exit", "severity": "block", "detail": f"missing exit for {cmd_str}"})
elif r.get("exit_code") != 0 and cmd_str in accept_set:
findings.append({"code": "acceptance.failed", "severity": "block",
"detail": f"exit {r.get('exit_code')} on {cmd_str}"})
return findings
def check_scope(scope_report: dict) -> list[dict]:
findings: list[dict] = []
if scope_report.get("forbidden_writes"):
findings.append({"code": "scope.forbidden", "severity": "block",
"detail": f"forbidden writes: {scope_report['forbidden_writes']}"})
if scope_report.get("off_scope_writes"):
findings.append({"code": "scope.off_scope", "severity": "warn",
"detail": f"off-scope writes: {scope_report['off_scope_writes']}"})
return findings
def check_rules(rule_report: list[dict]) -> list[dict]:
return [{"code": "rule.failed", "severity": "block", "detail": f"rule failed: {row.get('slug')}"}
for row in rule_report if not row.get("passed")]
def run_checks(task_id: str) -> dict[str, object]:
accept = list(_load_json(ROOT / f"outputs/scope/closed/{task_id}.json", {}).get("acceptance_criteria", []))
feedback = _load_jsonl(ROOT / "feedback_record.jsonl")
scope_report = _load_json(ROOT / f"outputs/scope/closed/{task_id}.report.json", {})
rule_report = _load_json(ROOT / "outputs/rule_report.json", [])
findings = check_acceptance(accept, feedback) + check_scope(scope_report) + check_rules(rule_report)
return {"task_id": task_id, "passed": not any(f["severity"] == "block" for f in findings), "findings": findings}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("task_id")
args = ap.parse_args()
report = run_checks(args.task_id)
out = ROOT / "outputs" / "verification" / f"{args.task_id}.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
if not report["passed"]:
print("verification failed", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
agent-workbench-pack/VERSION
1.0.0
career-agent-evidence.md
# Agent-Assisted Engineering: Task Evidence Copy this template into your own repository under `learning-artifacts/`. Replace the prompts with actual observations and relative evidence paths. Keep private data and secrets out of the evidence. Mark missing evidence `unverified`; never replace it with an invented result. ## Task contract - Repository and starting revision: - Learner and intended user or operator: - Coding agent and relevant configuration: - Observable goal and non-goals: - Allowed paths and actions requiring approval: - Task frame and dependency-aware plan: - Acceptance claim and independently defined expected result: ## Autonomy and environment - Working mode and reason, considering uncertainty, consequences, and reversibility: - Wall-time budget; token or cost limit if available: - Stop or escalation conditions, next action, and decision owner: - Selected implementation, caller, tests, and instructions, with reasons: - Tool or extension retained, task need, permissions, and context cost: - Proposed skill, MCP tool, hook, or plugin rejected, with reason: - Stale memory or instruction rechecked, current source, and retirement or replacement decision: - Check rerun after that decision and its evidence: Use only extensions this task needs. Record unavailable usage measurements as unavailable. A decision to retain a revalidated instruction is valid when removing it would lose a necessary constraint. ## Baseline and implementation | Run | Revision or artifact | Exact command or observed journey | Actual result | Evidence path | |---|---|---|---|---| | Before the change | | | | | | After the change | | | | | - Why the selected proof observes the changed UI, wire response, CLI, or other surface: - What that proof does not establish: - Agent interventions, failed attempts, or contract changes, with reasons: - Final changed-file list and diff: ## Test the acceptance check Use a disposable copy. Introduce one wrong behavior from the task contract without breaking the test runner. Keep the acceptance check unchanged for the first challenge. - Deliberately incorrect result: - Expected assertion or observation that should reject it: - Actual failure, exact command, revision, and evidence path: - If the incorrect result passed, what made the check too weak and how it was improved: - Restored correct result, passing rerun, and evidence path: - Confirmation the deliberate mutation is absent from the final diff: A syntax error, missing dependency, or failing setup is not evidence that the check detects the behavioral defect. ## Independent review - Peer or separate reviewer session: - Evidence and diff inspected, including test changes: - Weakest acceptance check challenged or reproduced: - Findings, changes made, and remaining disagreements: ## Operation and recovery - Environment: `local`, `staging`, or `live`: - Running revision or artifact identity and observation time: - Failure signal, threshold, observation window, owner, and response: - Safe failure injection and observed evidence: - Known-good rollback target and recovery procedure: - Rollback rehearsal, restored behavior, and evidence: - Persistent-data implications, if any: - Unverified operational behavior and limits on the claim: Local rehearsal is sufficient for this exercise. Label it accurately and do not imply that it proves production behavior. ## Iteration and handoff - Baseline versus final outcome: - Actual elapsed time, available usage data, and human interventions: - One correction promoted to a durable control: - Rerun proving the control works: - Final branch and revision, deliberate uncommitted work, and artifact locations: - Temporary changes removed, open risks, and remaining blockers: - Next action and the command or evidence the next session should start with: ## Reviewer decision Inspect the referenced artifacts and reproduce the weakest acceptance check. Use `demonstrated`, `needs revision`, or `unverified`, with a reason. This is a manual evidence review, not a score for completing prose fields. | Dimension | Status | Evidence inspected and reason | |---|---|---| | Task contract and justified autonomy | | | | Context, tools, and retirement decision | | | | Before/after proof and rejected incorrect result | | | | Diff review and operational recovery | | | | Verified improvement and clean handoff | | | - Defensible completion claim: - Required revisions or unverified limits:
skill-workbench-pack.md
--- name: workbench-pack description: Generate a project-tuned drop-in agent workbench pack — rules sharpened to the team's history, scope globs matched to the repo, rubric dimensions extended with one domain-specific entry. version: 1.0.0 phase: 14 lesson: 42 tags: [capstone, workbench-pack, installer, schemas, drop-in] --- Given a repo, the team's incident history, and the agent product running inside it, emit a tuned agent-workbench-pack and an installer. Produce: 1. `agent-workbench-pack/` directory matching the canonical layout: AGENTS.md, docs/, schemas/, scripts/, bin/, README.md, VERSION. 2. A `bin/install.sh` that refuses to clobber an existing pack without `--force` and writes `.workbench-version` into the target repo. 3. Project-tuned versions of `agent-rules.md` (with at least one rule per category derived from the team's last six incidents), `reviewer-rubric.md` (with a sixth domain dimension), and `scope_contract.schema.json` (with project-specific globs). 4. A `lint_pack.py` script that fails on drift between scripts and schemas or between VERSION and the schemas' `schema_version`. 5. Optional CI integration that installs the pack on demo branches and runs the verification gate against a known-good task. Hard rejects: - A pack containing project-specific tasks. Tasks live on the target repo's board. - A pack tied to a single vendor SDK. Framework-agnostic only; SDK wiring is the target repo's job. - An installer that mutates state files. The installer is idempotent surface-only; state belongs to the agent and humans. - Rules without a corresponding check function. Aspirational rules belong in onboarding, not in the pack. Refusal rules: - If incident history is empty, refuse to ship a tuned `agent-rules.md`. Use the canonical default and surface the gap. - If the target repo's CI is incompatible with the install (no `.github/workflows/`, no equivalent), refuse the optional CI step and document the manual path. - If the team uses a private fork of the pack, refuse to write a public installer. Private installers carry private invariants. Output structure: ``` agent-workbench-pack/ ├── AGENTS.md ├── docs/ ├── schemas/ ├── scripts/ ├── bin/install.sh ├── lint_pack.py ├── VERSION └── README.md ``` End with "what to read next" pointing to: - Lesson 41 for the before/after benchmark this pack improves on. - Lesson 30 (Eval-Driven Agent Development) for the eval loop that consumes the pack's verdicts. - SkillKit for distributing the pack across 32 AI agents.