Task: Finish the Session
Overview
Closes a working session in one invocation: it proves that the session's goals are met, puts the work on the remote, and archives the session.
- Goals Phase — every goal of the session checked against evidence gathered now, with one verdict line.
- Commit Phase — targeted documentation sync + Conventional Commits + task-status auto-flip.
- Push Phase — safe
git push with upstream and divergence gates.
- Reflect Phase — audit the session, apply the corrective edits to the instruction files and the project's own skills, commit them, and ask whether to push that commit.
- Archive Phase — final report, then the session is archived with the host's own means.
Four explicit gates between phases:
- Goals → Commit — the verdict MUST be
Goals: all met. A goal that is not met or not verified → STOP. The per-goal report reaches the user in the final report, or in the STOP message.
- Commit → Push — every change of this session MUST be committed.
- Push → Reflect — the push report does NOT end the run; the work MUST be on the remote before the reflection starts.
- Reflect → Archive — the reflection's push question MUST be answered by the user before the session is archived.
Context
Finishing a session by hand is four separate acts, and the first one — checking that what was asked for exists — is the one that gets skipped. This composite makes it the entrance: nothing is committed for a session whose goals do not hold. There is no review phase; a user who wants the diff reviewed before the commit asks for that workflow instead. The reflection runs here because archiving is the last act of a session: a lesson that has not reached the instruction files by then is lost with the conversation. Archiving is the only step that depends on the host: some hosts give the agent a tool that archives its own session and may remove the session's working copy with it, others give nothing. Each phase is FULLY INLINED below. Maintainer note (NOT for runtime): generated by `scripts/generate-skill-composites.ts` from `framework/composites.yaml`. Source-of-truth bookkeeping only.
Rules & Constraints
1. **No skill re-entry**: All five phases are FULLY INLINED below. Execute the steps directly. Do NOT invoke any goal-check, commit, push or reflection skill via the Skill tool — it would re-enter without the composite's gate logic and the workflow would silently exit between phases.
2. **Five Phases, Strict Order**: Goals, then Commit, then Push, then Reflect, then Archive. Never interleave; never skip a gate.
3. **The user sees the goal report in full**: the verdict line and every goal with its status and evidence. On a STOP at the Goals Gate it is the last thing you write. On a run that goes on, the final report of the Archive Phase carries it in full — a bare `Goals: all met` there is not the report.
4. **Goals Gate**: only `Goals: all met` proceeds. Any goal `not met` or `not verified` → STOP. Do NOT repair an unmet goal inside this run to get past the gate: finishing work is a new request, and the user decides whether to make it.
5. **A STOP ends the run**: after a STOP no later phase runs — no commit, no push, no reflection, no archive. Report which gate stopped you and why, then hand control back to the user and wait.
6. **Nothing to commit is not a failure**: when the session changed no file, the Commit Phase reports "Nothing to commit". Treat that report as a completed Commit Phase and continue with the gate after it.
7. **Archive is the last act**: nothing is written, run or edited after the session is archived. Never imitate archiving by deleting or moving transcripts, branches, worktrees or project files.
8. **Session Scope**: compare current `git status` with the git status snapshot from session start (available in system context). Files already modified/untracked at session start are outside the commit scope — note them but do not commit them. If unsure which changes are yours, ask the user before staging.
9. **Planning**: use a task management tool (e.g. `todo_write`, `todowrite`, `Task`) to track all five phases as a single plan.
Instructions
Goals Phase
<step_by_step>
-
List the goals of the session
- Go through the user's messages in this session in order, the invocation message included. Each thing the user asked for is one goal. Write it in the user's own words, shortened only where nothing is lost.
- A later instruction replaces an earlier one it contradicts. A goal the user cancelled is kept in the list with the status
withdrawn and is not checked.
- A message that only answers your question, approves a step or picks an option adds no goal of its own; it shapes the goal it belongs to.
- If the session worked on a task file (the
tasks role from the project instructions), every item of its Definition of Done is a goal as well. Merge an item with the user's request it restates.
- If you kept a task list in this session, an entry the user asked for and you never finished is a goal.
- No goal found — the session held only questions and answers, or the conversation is not available to you → say so in one line and skip to the last step. Do NOT ask the user to dictate the goals.
-
Gather evidence for each goal — now
- Choose the cheapest observation that would fail if the goal were not met:
- a Definition-of-Done item with an evidence command → run that command;
- a change in behaviour → run the test that covers it, or the project's check command once for all goals it covers;
- a file, section or setting that must exist → read it or
grep for it;
- an answer, an explanation or a report the user asked for → find the message that delivered it;
- something outside this machine (a deploy, a sent message, a CI run) → query it if a command for that exists.
- Reuse a result from earlier in this session only when no file it depends on changed afterwards. Otherwise run it again.
- Run independent read-only commands together where the tool allows it.
- Do not stop at the first unmet goal: check all of them.
-
Give each goal one status
met — the observation from step 2 confirms it. Name the observation: the command and its result, or the file and line.
not met — the observation contradicts it, or part of the goal is missing. Say exactly what is missing. A partly delivered goal is not met.
not verified — nothing available here can confirm or refute it. Say what the user can run or look at to settle it.
withdrawn — the user cancelled it in this session.
- A ticked checkbox whose evidence command fails is
not met, and the report says that the box is ticked.
-
List the loose ends — apart from the goals
- Run
git status --porcelain and, if the branch has an upstream, git rev-list --count @{u}..HEAD.
- Report, each in one line and only when present: uncommitted changes made in this session; commits not pushed; background processes or sessions this session started that still run; a question of the user you never answered; a follow-up you promised and did not do.
- A loose end does not change the status of a goal. Uncommitted work is not an unmet goal unless the user asked for a commit.
-
Compose the report
- First line, exactly one of:
Goals: all met (<N> of <N>)
Goals: NOT all met — <K> not met, <U> not verified, of <N>
Goals: none found in this session
- Withdrawn goals are not counted in
<N>.
- Then one entry per goal: the goal in the user's words, its status, and the evidence. Put
not met first, then not verified, then met, then withdrawn.
- Then the loose ends from step 4, or
Loose ends: none.
- Do not soften the verdict: no "essentially done", no "all met except". One unmet goal makes the first line
NOT all met.
-
Hand off to the next phase
- Keep the report from step 5 whole: the verdict line and every goal with its status and evidence. The run's final report must carry it in full — a bare verdict line there is not the report.
- You may also send it now as a progress message; whether you do or not, it still goes into the final report.
- Do not end the turn here and do not start on an unmet goal: the gate that follows this phase reads the verdict line and decides whether the run continues.
</step_by_step>
Goals → Commit Gate
Read the verdict line of the goal report from the Goals Phase:
Goals: all met → continue in this same turn with the Commit Phase below. Keep the report: the Archive Phase sends it in full.
Goals: none found in this session → there is nothing to verify. Say so in one line and continue with the Commit Phase below.
Goals: NOT all met → write the full goal report to the user and STOP. Do NOT commit, push or archive, and do NOT start fixing the unmet goal. End with one line: which goals block the finish, and that the user can ask to finish them or to close the session as it is.
- The user replies that the session should be closed as it is → that is a new instruction from the user and it opens the gate: continue with the Commit Phase and name the unmet goals again in the final report.
Commit Phase
<step_by_step>
- Gather Changes
- Collect all git state in a single command:
git status -s && echo '---DIFF---' && git diff && echo '---CACHED---' && git diff --cached && echo '---LOG---' && git log --oneline -5
- If working directory is clean (no changes at all), report "Nothing to commit" and STOP.
- Documentation Sync (mandatory — do NOT skip)
- Determine scope: look at the file paths from step 1. Classify the change:
- Infra-only: ALL changed files are tests (
*_test.*, *.test.*), CI (.github/), acceptance tests (acceptance-tests/), formatting, or dev-environment (.devcontainer/). → Skip doc sync. Output: Documentation sync: skipped — infra-only changes (tests/CI/acceptance-tests).
- Product changes: anything else → proceed with doc sync below.
- Resolve the documents first:
SRS, SDS, and index are ROLES, not filenames. Read ./AGENTS.md and take the path each role is bound to — a project may put its SDS at architecture/system.md or its SRS at specs/product.md, and the mapping below then means those files. Never go looking for design.md / requirements.md by name, and never create a file at the conventional path when the role already points somewhere else: that leaves the real document stale and adds a second one nobody reads. Take the WHOLE list the project declares, not just the three named roles — a documentation hierarchy that also binds, say, an API reference or an operations runbook is naming documents this step must keep in sync, and a change belonging to one of them does not become the SDS's problem because the SDS is the familiar name. A role you cannot resolve → say so in one line and sync only what you can. The same holds for a role whose bound path does not exist on disk: output Documentation sync: <role> → <path> is missing — not created, then continue — nothing in this workflow creates a project document, and a missing document is not a missing input.
- Find the mapping: check if
./AGENTS.md has a ## Documentation Map section. If yes → use the path→document mapping from there. If no → use the default mapping:
- New/changed exported functions, classes, types → SDS (component section)
- New feature, CLI command, skill, agent → SRS (new FR) + SDS (new component section)
- Removed feature/component → remove from SRS + SDS
- Changed behavior (fix that alters documented contract) → SDS (update description)
- Renamed/moved modules → SDS (update paths and structure)
- Config/build changes → SDS only if architecture section references them
- Renamed or removed name that documents mention → EVERY document that still prints the old one. A CLI flag, subcommand, option, environment variable, or exported symbol that changed its name is not covered by the "new feature" row, and this is the row that catches it. Do not infer the affected set from the kind of change:
grep the OLD string across the resolved documents and README, and take the set from the hits. Searching for the NEW name instead returns nothing, which reads as "docs are fine" — that is how a rename passes this step with every document left stale.
- README.md → update only for user-facing changes (new install steps, new features, changed API). A rename on the user-facing surface IS a changed API — a CLI flag, subcommand, option, or environment variable that changed its name belongs here.
- Sync each affected document:
- For each changed file, identify which document section describes its component (using the mapping).
- READ that specific section from the document.
- COMPARE the section text with the actual code after your changes. Ask: "Does this section accurately describe the code as it is NOW?"
- If inaccurate → update the section. If accurate → no change needed.
- For new functionality with no corresponding section → add a new section.
- For removed functionality → remove the section.
- Renamed or removed identifiers — search by the OLD name, across every resolved document. A flag, command, option, environment variable, function, or path that changed its name leaves the old one printed wherever it was documented, and grepping for the NEW name comes back empty, which reads as "docs are fine" and is how a rename passes this step untouched. Grep the old string verbatim in each resolved document plus README, and fix every hit. One document updated is not the step finished: the same name usually sits in several of them, and stopping at the first is the usual way the rest go stale.
- Gather change context for commit message and doc updates:
- Active task file: If the user referenced a task file in this session, resolve
tasks from AGENTS.md and read that file there. Do NOT scan all task files.
- Session context: User messages explaining intent, decisions, requirements.
- Apply Compression Rules to any doc updates:
- Use combined extractive + abstractive summarization (preserve all facts, minimize words).
- Compact formats: lists, YAML, Mermaid diagrams.
- Concise language, abbreviations after first mention.
- Execute Updates: Edit documents BEFORE proceeding to grouping.
- Report the sync, one line per document: after the edits, print a
Documentation sync: block with one line for EVERY document resolved
above — <path>: updated (<section or what changed>) or
<path>: no change — <reason>. The block is the step's output, not a
courtesy: a closing sentence such as "updated the SRS, SDS and README"
does not say which document was checked and why one was left alone, and
the user cannot tell a skipped document from an unaffected one.
(2026-09-02 and 2026-09-06: commit-doc-sync-gate synced all three
documents correctly in both runs and failed the same item both times
because the result was reported only as a summary sentence.)
- Commit Grouping
- Review the diff from step 1. Determine the primary business purpose.
- Default: ALL changes → 1 commit. Only split if:
a. Changes serve genuinely different, unrelated purposes (no causal link), OR
b. The user explicitly requested a split.
- Documentation describing a code change → same commit as that code.
- Tests for a feature → same commit as that feature.
- If splitting: use appropriate Conventional Commits types for each group.
- Hunk-level splitting (within a single file) — ONLY when user explicitly requests it.
- Commit Execution Loop
- Iterate through the planned groups:
- Stage specific files for the group.
- Verify the staged content matches the group's intent — check WHICH files are staged with
git status --short. When step 1 reused a diff from a prior phase rather than reading one, that is the whole check: staging moves files, it cannot change content you have already read, so do NOT run git diff in any form (--cached, --stat, per-file) to re-confirm it.
- Task Status Lifecycle (FR-DOC-TASK-LIFECYCLE) — for each staged task file under the resolved
tasks role with date: frontmatter (skip legacy flat-path), first check frontmatter status:. If it is superseded, require/keep superseded_by: and skip DoD derivation because the stale original DoD no longer maps to current reality. Otherwise count top-level - [ ]/- [x] items in ## Definition of Done. Derive status: K=0→"to do", 0<K<N→"in progress", K=N→"done" (warn if no DoD). Rewrite frontmatter and git add if it differs. Idempotent. Never downgrade done. Warn-only on parse errors.
- Commit with a Conventional Commits message (including any task-status frontmatter edit).
- Task files are never deleted (only if a task file was used in step 2) — task files of ANY shape (new-shape
date: frontmatter or legacy flat-path) are persistent canonical records; commit MUST NOT delete them, regardless of DoD completion. The only lifecycle action is the status derivation in step 4.3; status: superseded records are preserved.
- Verify Clean State
- Run
git status to confirm all changes are committed.
- If uncommitted changes remain, investigate and report to the user.
</step_by_step>
Commit → Push Gate
- Run
git status --porcelain. Every file this session created or modified MUST be committed. One of them still listed → STOP and name it.
- Files that were already modified or untracked at session start (rule 8) do not stop the push: they are not this session's work. List them — the Archive Phase asks about them.
- The branch has no upstream and nothing to push to (
git remote prints nothing) → skip the Push Phase, say so in one line, and continue with the Archive Phase.
- Otherwise → enter the Push Phase. If the user declines the push at its first-push or divergence gate, STOP — the commits stay local, and a session with unpushed work is not archived.
Push Phase
<step_by_step>
-
Identify Target Branch
- Run
git rev-parse --abbrev-ref HEAD to identify the current branch as <CURRENT>.
- If the user typed a branch name as argument, compare to
<CURRENT>. If different, STOP and ask "You typed <typed> but the current branch is <CURRENT>. Push <CURRENT> or check out <typed> first?". Wait for an answer.
- Otherwise, the push target is
<CURRENT>.
-
Resolve Upstream
- Run
git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null to find the upstream of <CURRENT>.
- If the command exits non-zero (no upstream), ASK the user: "
<CURRENT> has no upstream. Should I run git push --set-upstream origin <CURRENT>?". Wait for an answer.
- Affirmative → proceed to step 3 with
--set-upstream origin <CURRENT>.
- Negative → STOP. Report "No upstream and user declined to set one — nothing to do."
-
Safety Checks
- Protected-branch divergence (HARD REFUSAL — see Rule 4): if the upstream is
origin/main or origin/master, run git fetch origin <CURRENT> then git rev-list --left-right --count HEAD...@{u}. If the right count (commits the remote has and local does not) is > 0, ASK the user with EXACTLY two options: "Remote <CURRENT> is ahead by N commit(s) the local branch does not have. Force is REFUSED on protected branches even with explicit authorization. Pull and rebase first, or abort?". --force / --force-with-lease are NOT options — never present them, never run them, even if the user volunteers "force", "overwrite", or "yes I want to overwrite the remote". If the user pushes back, restate the refusal and re-offer pull-rebase / abort.
- Non-protected branch divergence: if the right count > 0, surface the divergence but proceed with a regular
git push (which will fail safely if non-fast-forward). DO NOT proactively suggest force.
--force request: if the user has explicitly asked for --force, decline. Explain --force-with-lease and proceed only with per-push user authorization (see Rule 2).
-
Push
- Run
GIT_PAGER=cat git push [--set-upstream origin <CURRENT>]. Stream stdout + stderr to the user. Do NOT silence error output.
- On a non-fast-forward error: do NOT retry with
--force or --force-with-lease. Surface the failure and STOP.
-
Post-Push Verification
- Run
git rev-parse @{u} and git rev-parse HEAD. Compare.
- Equal → push succeeded. Report the remote ref and the pushed SHA.
- Different → push reported success but upstream did not advance. STOP with "Post-push verification FAILED: @{u} =
<remote>, HEAD = <local>. Investigate before retrying."
-
Await CI (FR-ATOM-PUSH.CI-AWAIT)
- Read AGENTS.md
## CI/CD section.
- Absent: output
No CI declared in AGENTS.md — skipping CI await. and continue to step 7 (`7. Hand off to the next phase
- Final report: target branch, upstream, pushed SHA, post-push verification result, CI await result (
skipped, green, or not reached — stopped earlier).
- Announce: "Push complete; entering the next phase of the composite workflow."
- Do NOT issue a TOTAL STOP, and do NOT wait for the user to tell you to carry on. The push report reads like the end of the work — in
ship and ship-task the Reflect Phase follows it, in this same turn.`).
- Malformed (missing either
Provider: or Status command:): STOP with ## CI/CD section is malformed — required keys: Provider, Status command. Found: <list of present keys>. Do NOT silently fall back. Do NOT continue to step 7.
- Well-formed: continue.
- Resolve tunables (optional keys in
## CI/CD):
Poll interval: — seconds between status polls. Default 60. Accept integer seconds; a value <5 is treated as malformed and STOPs the atom.
Wall-clock budget: — soft cap on total await time. Default 1800 (30 min). Accept integer seconds.
- Compute
ITER_CAP = max(1, ceil(<budget> / <poll interval>)). The iteration count — NOT wall-clock — bounds the cap so it stays deterministic across IDE-harness latencies. With defaults, ITER_CAP = 30; a project that sets Poll interval: 10 and Wall-clock budget: 60 gets ITER_CAP = 6.
- Export the pushed SHA into the environment:
export SHA=$(git rev-parse HEAD). All CI commands below inherit $SHA from the agent's shell.
- Detect run trigger (≤60 s window; sized at ~2× the slowest realistic provider lag, observed ~30 s for GitLab pipelines registering after push): invoke the
Status command. Treat:
- exit 0 or 1 (terminal on first call) → proceed straight to the poll loop branch.
- exit 2 (in-progress — a run exists) → proceed to the poll loop.
- any other exit → sleep 5 s and retry. After 12 retries (60 s) with no run detected, STOP with
CI declared but no run was triggered by $SHA within 60 s — verify the workflow trigger configuration. Do NOT continue to step 7.
- Poll loop (max
ITER_CAP iterations × <poll interval> s sleep ≈ <wall-clock budget> wall-clock):
- Invoke the
Status command.
- exit 0 → CI green. Continue to step 7.
- exit 1 → CI red (terminal failure). Go to Investigate Handoff below.
- exit 2 → still running. Sleep
<poll interval> s. Re-invoke. Increment iteration counter.
- any other exit → treat as a malformed Status command, STOP with the raw exit code and stderr.
- Iteration cap (anomaly): if
ITER_CAP iterations completed without a terminal status (exit 0 or 1), STOP with a loud single-line message: CI ANOMALY: <ITER_CAP> iterations × <poll interval>s = <budget>s elapsed without a terminal verdict. Run URL: <result of Run URL command if defined, otherwise "not available">. Last status exit: 2 (in-progress). Treat as an incident (hanging job, queue starvation, runner outage) — do NOT continue silently. Do NOT invoke investigate (no failed-job logs to feed it yet — the build is still running, not red). Do NOT continue to step 7. The user owns the next action: extend the budget by re-running the atom after raising Wall-clock budget, cancel the CI run, or investigate the runner.
- Investigate Handoff (CI red):
- If the
Logs command is defined in AGENTS.md, execute it. Capture stdout. Truncate to 12 KB (investigate can fetch more via the run URL if it needs to drill deeper).
- If the
Run URL command is defined, execute it. Capture stdout as the run URL.
- Do NOT assume the working tree is clean:
@{u} == HEAD (step 5) proves only that the commit reached the remote, and a push leaves uncommitted work in place. The investigation therefore runs in a temporary worktree of the pushed commit, which is clean by construction; the handoff prompt below says so. Do NOT stash, reset, restore or commit the developer's uncommitted files to make the tree clean.
- Invoke the
investigate skill via the host IDE's skill-invocation primitive (Skill tool / /flowai:investigate slash command / inline expansion of its SKILL.md) with this prompt:
CI failed for commit $SHA on branch <CURRENT>. Run URL: <URL or "not available">. Failed-job logs (truncated to 12 KB):\n<LOGS or "not available">\nDiagnose the root cause in a temporary git worktree of $SHA (git worktree add <scratch dir> $SHA), not in the current working tree, and remove that worktree when done. Do not apply a fix; report findings.
- After
investigate returns its report, STOP. Do NOT continue to step 7 — the push succeeded but the build is broken; the user owns the remediation decision.
-
**7. Hand off to the next phase
- Final report: target branch, upstream, pushed SHA, post-push verification result, CI await result (
skipped, green, or not reached — stopped earlier).
- Announce: "Push complete; entering the next phase of the composite workflow."
- Do NOT issue a TOTAL STOP, and do NOT wait for the user to tell you to carry on. The push report reads like the end of the work — in
ship and ship-task the Reflect Phase follows it, in this same turn.**
</step_by_step>
Push → Reflect Gate
- The push report is not the end of the run. The next phase here is the Reflect Phase below; it runs in this same turn, without waiting for the user to ask for it.
- You are only here if the push succeeded and
git rev-parse @{u} equals HEAD, or the Push Phase was skipped because the repository has no remote. A failed push, a CI failure handed to an investigation, or a CI anomaly is a STOP (rule 5) and never arrives here.
Reflect Phase
<step_by_step>
-
Decide whether this session earned a reflection
- Scan the conversation and the invocation message for complexity signals:
- Errors or failed attempts (test failures, lint errors, build errors).
- The same action retried more than once.
- The user correcting your approach or output.
- Workarounds or non-obvious solutions.
- Explicit descriptors in the invocation message — "rough session", "had to retry", "wrong approach", "failed", "had to correct you". These count on their own.
- A project skill that failed, misled you, or that the user told you to deviate from.
- The user spelling out a procedure and saying they repeat it — "every time", "again", "each release". A procedure of three commands counts: the signal is that they had to say it.
- A choice between two or more alternatives made in this session, by you or stated by the user.
- The last three are not trouble. A session that ran clean and carries one of them still earns the reflection: read the user's messages for them before you write "none detected".
- Say the verdict aloud either way — one line:
Session complexity: none detected — skipping reflection, or Detected retries and a user correction — reflecting. A silent skip is indistinguishable from a forgotten step.
- No signals → skip to the final step. Signals → continue.
- Do NOT ask whether to reflect. That is not the user's call here; the one question in this atom comes at step 6, and it is about pushing.
-
Audit the session
- Execution flow: where did the work go wrong, and what did it cost — failed commands, wrong assumptions, rework.
- Logic patterns: looping (retrying without changing strategy), blindness (ignoring a "file not found" or a linter error), stubbornness (forcing a solution that does not fit).
- Technical decisions: proportionality, conformance to existing project patterns, abstraction fit, explicit error handling, robustness, obvious inefficiency, input validation, dependency justification, and fallbacks nobody asked for.
- Context gaps: project docs never opened, related source never read, relevant skills or rules never consulted, verification skipped, ambiguities resolved by guessing instead of asking.
- Context waste: files read but never used, whole files read for one fragment, the same unchanged file read twice, verbose tool output that added noise.
- Undocumented discoveries: knowledge gained here that changes how the project is built, run, tested or deployed. Keep what generalises; discard the one-off.
- Stale instructions: anything the project instructions told you that the repository contradicted — a command or task that does not exist, a path that moved, a convention the code does not follow. Compare the commands the instructions name with the ones the project's manifest defines.
- Project skills: for each project skill you used or read in this session — a command or path in it that failed or does not exist, a missing step, a statement the repository or another instruction file contradicts, a rule the user told you to break (→ repair that step). Every step of it dead, or another skill doing the same job (→ remove it; a skill that an instruction file, a hook or the CI config names is repaired instead).
- Recurring work: a multi-step, project-specific procedure this session had to be told or had to find, with a sign that it returns — the user said so, or it is routine by nature: a release, a report, a sync (→ a new project skill, not a bullet in an instruction file: ordered steps the agent performs are a skill, however few). A convention is a single fact about how the project is written, with no steps to perform (→ a rule); an invariant you checked by hand (→ a hook).
- Unrecorded decisions: every choice between two or more alternatives made in this session, with its reason. Look for each one in the session's task file and in the requirement and design documents. Recorded nowhere → it is a finding.
-
Criticise your own findings — before you touch a file
- Validity: is each finding backed by something you can quote from this session, or is it inference? Drop or downgrade the inferred.
- False positives: reading a neighbouring file to learn the pattern is not wasted context; updating a test after a deliberate behaviour change is not test-fitting.
- Proportionality: a one-off annoyance does not earn a new rule. Simplify anything disproportionate. This limits NEW rules only. A line in an existing instruction file that this session proved wrong is corrected on its first sighting, however rarely it bites: fixing a fact is not adding a rule. A "read-only" marker on
AGENTS.md keeps task notes out of it; it does not protect a wrong fact in it.
- A skill earns its place: no new skill when another PROJECT skill covers the work even partly (extend that one — a packaged workflow such as the one you are running does not count, it is not yours to extend), when the steps were already written in the instruction files before this session, or when the work did not succeed. A skill this session proved wrong is corrected on its first sighting, like any wrong fact.
- Blind spots: which whole categories did you not look at — security, performance, documentation?
- Severity: a pattern seen twice with different root causes is not recurring.
- Say what this pass changed and why. What survives it is what you are about to write into the user's files.
-
Apply the corrective edits
- Read the declined-edits log first:
AGENTS.declined.md in the repository root, when it exists. A finding whose edit matches a record there — the same file and the same change in substance — is NOT applied: the user already said no to it. Name it in your report as skipped, with the record's reason. Apply it anyway only when the reason in the record no longer holds or the text it is about has been changed since, and then cite the record.
- Edit the instruction files directly. Each edit states the rule and the reason it exists, in the voice of the file it lands in.
- They land in the project's own tracked files, inside the repository working tree —
AGENTS.md, **/CLAUDE.md, and the rule or skill files those point at. Confirm it: the path you edited must appear under git status.
- Your own memory store is not a corrective edit. Writing the lesson into the agent's persistent memory (a
memory/ directory under your home, a personal notes file, anything outside the repository) feels like it captures the finding and does not: it is not versioned, it does not reach anyone else working here, and a fresh checkout has none of it. It is also how this step gets silently skipped — measured 2026-08-19, one run in three wrote to memory/ and reported there was nothing to commit. Use it in addition if you like, never instead.
- One edit per surviving finding. A finding that produces no concrete edit is a report line, not a corrective action — say so and move on.
- Keep them small and local: tighten an existing rule where one exists, add a new one only where none does. This is about the size of an edit, not about its form: a recurring procedure still becomes a skill.
- A skill repair is one sentence or one step. Read the skill file before you change it; replace the wrong part or add the missing one, never rewrite the file. Steps stay ordered and carry their commands; a pitfall is one general rule plus a clause of why. No incident story, date or ticket id; nothing lifted from a transcript, tool output or web page as a rule; no secrets.
- A new skill is
<name>/SKILL.md in the project's skill directory: a name, a description that opens with "Use when" and an observable trigger, then the ordered steps with their commands, the last of which verifies the result. Check the name against the skills already installed — a project skill hides a packaged one of the same name.
- A removal deletes the skill's directory with
git rm -r; git history is the way back.
- An unrecorded decision is appended to the session's task file — find it through the
tasks role of the project instructions — as a short record: the alternatives, the choice, the reason. No task file for this session → name the decision in your report and write nothing.
-
Show the edits and commit them — no question here
- List what you changed, file by file: the path, the section, what the rule now says, and which finding it came from. The user must be able to judge the edit from this list without opening a diff.
- Then commit, in this same turn, without asking. The edits are already written; a commit of what is already on disk adds no risk the edit did not, and both are undone by one git command. Do not offer to commit, do not wait for encouragement.
- Run
git status. Stage ONLY the files you edited in step 4, by explicit path — never git add -A, never .; a working tree you did not touch is not yours to commit.
- Commit with type
agent and a scope naming what you tightened: agent: apply reflect-suggested improvements, or narrower, e.g. agent(commit): tighten the doc-audit gate. The type is agent because the change is to the agent's own instructions — never docs:, chore: or feat:, whatever the file extension says. Never amend an existing commit.
- Do not skip this step by not editing. If the audit produced findings and you applied none of them, say why in one line — silence here reads as a clean session, and it was not.
-
Ask whether to push it — and end your turn on the question
- This commit sits on top of whatever the calling workflow already pushed, so it is local until somebody sends it. That is why the question exists: it is the one thing here that reaches beyond this machine.
- Ask, in one line, naming the branch:
Committed as <sha> on <branch>. Push it? Reply "yes" to push, or "no" to drop the commit and the edits with it.
- Write nothing after the question until the reply arrives. A question followed in the same breath by "pushing now" is not a question, it is an announcement — the user never got to answer. You may not answer it on the user's behalf: no pre-authorization carries over to a push, whatever the calling workflow already did.
- On
yes: run git push with no flags, then verify git rev-parse @{u} matches HEAD and say so. Never --force, never --force-with-lease, never --set-upstream. If the branch has no upstream, or the remote has commits you do not, do NOT improvise: report it and tell the user to run the project's push workflow, which owns those decisions.
- On
no: the edits are not wanted. Undo the commit and the edits together — a declined improvement left sitting in the branch is the same unwanted change, one git log further away.
- Check two things first, then it is one command. (a)
git rev-parse HEAD still equals the sha you reported — nothing landed on top of your commit. (b) git status --porcelain prints nothing — the tree carries no other work. Both hold by construction here: the earlier phases committed and pushed everything, and you committed your own edits in step 5.
- Both true →
git reset --hard HEAD~1. That is the whole undo: the commit and the file contents go together, and there is nothing to restore by hand.
- Either check fails → STOP and change nothing. A
--hard reset discards uncommitted work outright, and whatever made those checks fail is work you did not put there. Report what you found, leave your commit in place, and let the user decide.
- Then confirm with
git log -1 that your commit is gone, and say in one line what you removed.
- Record what was declined, so the next session does not make the same edit. Append one line per undone edit to
AGENTS.declined.md in the repository root — create it with the heading # Declined instruction edits when it is missing: - <YYYY-MM-DD> | <file> | <what the edit did, in one line> | reason: <the user's words, or "not given">. Then git add AGENTS.declined.md and commit that file alone: git commit AGENTS.declined.md -m "agent: record declined instruction edits". Do not ask about pushing this commit; it travels with the next push.
-
Hand off to the next phase
- Report in one line whether the reflection ran, what it changed, under which commit, and whether that commit was pushed.
- Announce: "Reflection complete; entering the next phase of the composite workflow."
- Do NOT issue a TOTAL STOP, and do NOT wait for the user to tell you to carry on. Continue immediately into the next phase, in this same turn.
- This is the step this atom exists to protect. A reflection closes with a report, and a report reads like an ending — that is exactly how the phase after this one gets lost. Measured 2026-08-17: the calling workflow's Push Phase never ran, the commit stayed local, and the last thing written was the reflection report.
- A declined push does not stop the hand-off either. You undo the commit and the edits, and the next phase runs anyway.
</step_by_step>
Reflect → Archive Gate
- The Reflect Phase said "none detected" and changed nothing → continue with the Archive Phase below in this same turn.
- The Reflect Phase committed edits → its push question ends your turn. The Archive Phase starts with the turn in which the user answers it: on
yes after the push is verified, on no after the undo and the record of the declined edits.
- A commit the Reflect Phase left local — the record of declined edits, or its own commit when the push could not be made — does not stop the archive. Name it in the final report: it leaves with the next push.
Archive Phase
-
Send the final report first
- Archiving can end the conversation, so the report goes out before it:
- Goals: the goal report from the Goals Phase in full — the verdict line, then one entry per goal with its status and the evidence you observed (the command and its result, or the file). A verdict line alone is not enough: this is where the user sees what was checked. Name any goal the user chose to leave unmet.
- Commit: the commits made, or "nothing to commit".
- Push: branch, upstream, pushed SHA, or why there was no push.
- Reflection: what it changed and under which commit, whether that commit was pushed, or "none detected".
-
Check what would be lost
- Run
git status --porcelain. On some hosts archiving a session also removes its working copy, and uncommitted files go with it.
- The output is empty → continue with step 3.
- Files are listed → name them and ask once: "These files are not committed and may be removed together with the session. Archive anyway?" Wait for the reply. A refusal → say that the session stays open and STOP.
-
Archive the session with the host's own means
- Look at the tools you have in this session for one that archives or closes the CURRENT session (e.g. a session-archive tool in the Claude desktop app). Decide from the tool list alone; do not search the file system for a way.
- Such a tool exists → call it for the current session. The invocation of this workflow is the user's request to archive; if the host asks the user for its own approval, that is the host's step, not yours. This call is the last action of the run — write nothing after it. If the host refuses or the user declines the approval, say so in one line and stop.
- No such tool → say in one line that this host gives you no way to archive the session from inside it, and that the user can archive or close it in the host's interface. Then stop.
- Never substitute something else for it: do NOT delete or move session transcripts, do NOT remove branches or worktrees, do NOT clear the conversation.
Verification
[ ] Evidence for every goal was gathered BEFORE the first Commit Phase command.
[ ] The user received the goal report in full — verdict line, then every goal with status and evidence — in the STOP message or in the final report.
[ ] Goals gate enforced: only `Goals: all met` proceeded; no unmet goal was repaired inside the run.
[ ] Documentation sync performed: affected sections updated or justified skip.
[ ] Commits used Conventional Commits format; task status auto-flipped from the Definition of Done.
[ ] Commit → Push gate enforced: no change of this session left uncommitted.
[ ] Push Phase: no `--force` used; first-push gate satisfied; protected-branch divergence handled before the push attempt.
[ ] Post-push verification: `git rev-parse @{u}` matches `HEAD`.
[ ] Push → Reflect gate enforced: the Reflect Phase ran after the push report, and its push question was answered by the user.
[ ] Reflect → Archive gate enforced: the Archive Phase ran after the reply, whether the answer was yes or no.
[ ] Final report sent BEFORE the archive action.
[ ] Archive Phase: the session was archived with the host's own means as the last action, or the user was told in one line that the host offers none; nothing was deleted to imitate it.
[ ] No phase ran after a STOP.