@homericintelligence/athena-opencode 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +29 -0
  2. package/NOTICE +22 -0
  3. package/README.md +45 -0
  4. package/package.json +29 -0
  5. package/plugin.js +54 -0
  6. package/skills/THIRD_PARTY_LICENSES.md +50 -0
  7. package/skills/_cli.py +152 -0
  8. package/skills/advise/SKILL.md +62 -0
  9. package/skills/advise/scripts/list_retrievable_skills.py +49 -0
  10. package/skills/brainstorm/SKILL.md +110 -0
  11. package/skills/change-review/SKILL.md +68 -0
  12. package/skills/change-review/references/scope-resolution.md +52 -0
  13. package/skills/change-review/scripts/resolve_scope.py +1219 -0
  14. package/skills/finalize-plan/SKILL.md +129 -0
  15. package/skills/git-worktrees/SKILL.md +113 -0
  16. package/skills/git-worktrees/scripts/prepare_worktree.py +153 -0
  17. package/skills/issue-review/SKILL.md +67 -0
  18. package/skills/learn/SKILL.md +208 -0
  19. package/skills/myrmidon-swarm/SKILL.md +93 -0
  20. package/skills/plan-issue/SKILL.md +70 -0
  21. package/skills/pr-review/SKILL.md +114 -0
  22. package/skills/pr-review/references/criteria.md +26 -0
  23. package/skills/pr-review/references/delivery.md +135 -0
  24. package/skills/pr-review/references/evidence.md +233 -0
  25. package/skills/pr-review/references/prevalidated.md +155 -0
  26. package/skills/pr-review/scripts/collect_evidence.py +1478 -0
  27. package/skills/pr-review/scripts/diff_context.py +74 -0
  28. package/skills/pr-review/scripts/materialize_snapshot.py +731 -0
  29. package/skills/pr-review/scripts/pr_identity.py +80 -0
  30. package/skills/pr-review/scripts/resolve_pr.py +258 -0
  31. package/skills/repo-review/SKILL.md +119 -0
  32. package/skills/systematic-debugging/SKILL.md +199 -0
  33. package/skills/systematic-debugging/scripts/repository_evidence.py +77 -0
  34. package/skills/test-driven-development/SKILL.md +75 -0
  35. package/skills/tidy/SKILL.md +71 -0
  36. package/skills/tidy/scripts/run_tidy.py +43 -0
@@ -0,0 +1,129 @@
1
+ ---
2
+ name: finalize-plan
3
+ license: BSD-3-Clause
4
+ description: Materialize one exact, actor-owned, GO-reviewed issue-planning epoch into its implementation-facing issue body. Use after plan-issue and issue-review approve a plan; `--draft` is read-only and every missing, foreign, stale, ambiguous, or unverifiable input fails closed.
5
+ argument-hint: "[--draft] ISSUE_NUMBER_OR_URL"
6
+ allowed-tools: [Read, Bash, Grep, Glob]
7
+ ---
8
+
9
+ # Finalize an approved issue plan
10
+
11
+ Why: an approved plan should be the readable implementation entry point without
12
+ turning review history, suggestions, or a generated body into new requirements.
13
+
14
+ Use the shared [issue-planning contract](../../docs/review/issue-planning.md),
15
+ [review contract](../../docs/review/common.md),
16
+ [design-document structure](../../docs/review/design-docs.md),
17
+ [language routing](../../docs/review/language-routing.md), and
18
+ [behavior-first testing](../../docs/review/behavior-first-testing.md).
19
+
20
+ ## Scope and delivery
21
+
22
+ `--draft` is read-only. Without it, this skill may replace the resolved issue
23
+ body once and, only after exact body readback, delete the two sealed,
24
+ actor-owned plan and review comments. It must not update the title, labels,
25
+ assignment, milestone, project fields, state, branches, pull requests, or
26
+ repository files. The finalized body retains the required provenance after
27
+ those intermediate comments are removed.
28
+
29
+ Use the forge's native issue-body mechanism. If the host cannot authenticate the
30
+ actor, enumerate and delete exact comments, read the issue body, compare
31
+ identities, or make and read back one exact body update, return a
32
+ ready-to-publish draft and identify the capability gap. Never create, adopt,
33
+ edit, or replace plan or review comments to make finalization possible.
34
+
35
+ ## Finalized planning epoch
36
+
37
+ An epoch has these sealed source identities:
38
+
39
+ - `R`: the canonical digest of the original issue requirements: exact issue ID,
40
+ title, body, and acceptance criteria before finalization;
41
+ - `P`: one actor-owned `<!-- athena:plan-issue -->` comment ID and canonical
42
+ plan-content digest; and
43
+ - `V`: one actor-owned `<!-- athena:issue-review -->` comment ID and
44
+ review-content digest.
45
+
46
+ The review must embed and exactly match the same issue, `R`, plan-comment ID,
47
+ and `P`. It must have an exact `GO` disposition with no unresolved `critical`,
48
+ `major`, or other `required` finding. A conditional, partial, malformed, stale,
49
+ foreign, duplicated, absent, or unverifiable artifact is not authorization.
50
+
51
+ The rendered body records exactly one marker:
52
+ `<!-- athena:finalize-plan R=<R> P=<P> V=<V> F=<F> -->`. Define `F` by hashing
53
+ the final body after replacing that marker's `F` value with the literal
54
+ `<F>` placeholder; do not hash a marker containing its own digest. The marker
55
+ lets a host distinguish sealed source identities from the generated body and
56
+ verify later readback without recursion.
57
+
58
+ ## Finalize
59
+
60
+ 1. Resolve one exact issue, including node or URL, title, body, state, and
61
+ authenticated actor. Enumerate every current comment before interpreting a
62
+ marker.
63
+ 2. Resolve exactly one actor-owned plan marker and one actor-owned review marker.
64
+ Compute `R`, `P`, and `V`, then verify the review's embedded bindings and
65
+ clean GO result. Any ownership, multiplicity, binding, disposition, or
66
+ required-finding failure returns no write.
67
+ 3. Build a compact, lossless synthesis. Lead with **Why** (the preserved
68
+ original problem, outcome, and non-negotiable requirements), then include a
69
+ compact system-shape diagram only when it makes at least three relationships,
70
+ boundaries, or state transitions materially clearer. Follow with architecture
71
+ breakdown, implementation plan, operations, and provenance.
72
+ 4. Preserve every acceptance criterion, implementation boundary, validation,
73
+ migration or cutover step, rollback condition, dependency, residual risk, and
74
+ out-of-scope decision. Record review suggestions as optional residual context
75
+ unless the reviewed canonical plan already adopted them. Do not invent files,
76
+ commands, requirements, architecture, implementation results, or validation
77
+ evidence; do not copy historical revision transcripts or duplicate the plan
78
+ and review verbatim when a smaller lossless synthesis suffices.
79
+ 5. Add the finalized marker and compute `F` over its non-self-referential
80
+ canonical representation. In `--draft`, return the complete body, `R/P/V/F`,
81
+ source links, and all withheld-write reasons without invoking a forge write.
82
+ 6. Immediately before publication, resolve the issue, actor, every comment and
83
+ marker, `R/P/V`, review disposition, and target body again. If any input
84
+ drifted, return the ready-to-publish body as stale; do not write.
85
+ 7. Publish exactly one issue-body replacement. Read the issue back immediately
86
+ and verify the exact body, marker, `R/P/V`, and `F`. A timeout, indeterminate
87
+ response, or mismatched readback is an unknown outcome: do not retry or make
88
+ another mutation.
89
+ 8. After successful body readback, re-read each sealed comment by its exact ID,
90
+ actor, marker, and digest, then delete the plan comment and review comment.
91
+ Delete no foreign, replacement, or drifted comment. A failed, timed-out, or
92
+ indeterminate deletion is a partial-cleanup unknown outcome: do not retry,
93
+ compensate, or remove the finalized body; report the surviving identities.
94
+
95
+ ## Re-finalization and restart
96
+
97
+ If the live body exactly verifies its finalized marker and both sealed comments
98
+ are absent, re-running for that epoch returns a documented no-change result. A
99
+ surviving sealed comment is partial cleanup, not authorization to retry a prior
100
+ deletion. If the marker is absent, malformed, foreign, or its canonical `F` does
101
+ not match, the epoch is not valid evidence. A later material human edit is a new
102
+ requirements state and must pass a fresh `plan-issue` plus `issue-review` cycle
103
+ before another finalization. Do not treat generated plan text or provenance
104
+ fields as newly authored requirements.
105
+
106
+ ## Behavior-first verification
107
+
108
+ Use controlled issue, comment, actor, and forge fixtures to demonstrate:
109
+
110
+ - one clean GO plan/review epoch preserves requirements and operational details;
111
+ - `--draft` returns the body without a forge mutation;
112
+ - publish performs one body update, verifies its exact readback, then deletes
113
+ only the two sealed actor-owned comments;
114
+ - an unchanged sealed epoch is idempotent; and
115
+ - every absent, foreign, duplicate, mismatched, stale, NO-GO, required-finding,
116
+ drift, unsupported-write, timeout, readback-mismatch, or deletion-uncertainty
117
+ case fails before an unsafe mutation or retry.
118
+
119
+ Assert identities, ordering classes, preservation, mutation count and scope, and
120
+ failure-before-write behavior. Do not freeze editorial wording, headings,
121
+ paragraph counts, or an example issue body.
122
+
123
+ ## Result
124
+
125
+ Return the issue and actor identities; `R/P/V/F`; GO decision and finding
126
+ summary; requirement-preservation map; draft, no-change, published, stale,
127
+ partial-cleanup, or unknown-outcome status; body-update receipt, readback
128
+ evidence, deleted-comment receipts when present; and every unresolved capability
129
+ or residual risk.
@@ -0,0 +1,113 @@
1
+ ---
2
+ name: git-worktrees
3
+ license: BSD-3-Clause
4
+ description: Use when starting feature work that needs isolation from current workspace — creates isolated git worktrees with safety verification
5
+ argument-hint: <branch-name or feature description>
6
+ allowed-tools: [Bash, Read]
7
+ ---
8
+
9
+ # Using Git Worktrees
10
+
11
+ ## Overview
12
+
13
+ Git worktrees create isolated workspaces sharing the same repository, allowing work on multiple branches simultaneously without switching.
14
+
15
+ **Core principle:** Systematic directory selection + safety verification = reliable isolation.
16
+
17
+ **When NOT to use this skill manually:** The `myrmidon-swarm` skill owns worktree creation for its
18
+ background subagents. Use this skill for manual development work, not to duplicate swarm setup.
19
+
20
+ ## Directory Selection
21
+
22
+ Follow this priority order:
23
+
24
+ ### 1. Check Existing Directories
25
+
26
+ The tested `scripts/prepare_worktree.py` helper checks `.worktrees` and then `worktrees`. If both
27
+ exist, `.worktrees` wins.
28
+
29
+ ### 2. Check repository guidance
30
+
31
+ Read `AGENTS.md` and its referenced repository guidance. If a preference is specified, pass it to
32
+ the helper with `--directory DIRECTORY`.
33
+
34
+ ### 3. Portable default
35
+
36
+ When no repository preference exists, use the host's temporary directory from
37
+ `tempfile.gettempdir()` with `<project>-<branch>`. This is commonly `/tmp` on Unix-like hosts and
38
+ avoids polluting the project directory.
39
+
40
+ The helper computes the project name from the repository root.
41
+
42
+ ## Safety Verification
43
+
44
+ ### For Project-Local Directories (.worktrees or worktrees)
45
+
46
+ **MUST verify directory is ignored before creating worktree.** The helper fails closed when its
47
+ project-local directory is not ignored.
48
+
49
+ **If NOT ignored:**
50
+
51
+ 1. Add `.worktrees/` to `.gitignore`
52
+ 2. Commit the change
53
+ 3. Then proceed with worktree creation
54
+
55
+ **Why critical:** Prevents accidentally committing worktree contents to repository.
56
+
57
+ ### For /tmp Locations
58
+
59
+ No `.gitignore` verification needed — outside the project entirely.
60
+
61
+ ## Creation Steps
62
+
63
+ 1. Resolve and record the intended base commit SHA.
64
+ 2. Keep the target repository as the current working directory. Resolve `scripts/prepare_worktree.py`
65
+ against this installed skill directory and invoke that absolute helper path with
66
+ `BRANCH_NAME --start-point BASE_SHA --dry-run`. For a contract requiring a distinct branch and
67
+ path, also pass exact `--path` and `--path-root` values.
68
+ 3. Create it with the same arguments without `--dry-run`, optionally supplying the documented
69
+ repository preference through `--directory`. Never replace the recorded SHA with ambient HEAD.
70
+ 4. Change to the returned path and run the repository-defined bootstrap when one exists.
71
+ 5. Verify a clean baseline with the repository-defined tests and report the path, start SHA, and result.
72
+
73
+ **If tests fail:** Report failures, ask whether to proceed or investigate.
74
+
75
+ **If tests pass:** Report ready.
76
+
77
+ ## Cleanup
78
+
79
+ When work is done, invoke `tidy` for branch and worktree cleanup. It prepares the trusted
80
+ Hephaestus dependency and delegates directly to `hephaestus-tidy`, whose interactive workflow owns
81
+ discovery, preservation rules, deletion prompts, rebases, and cleanup safeguards. Do not duplicate
82
+ that policy or improvise deletion commands in this skill.
83
+
84
+ Preserve the worktree by default. Delivery, merge, abandonment, or a general cleanup request does
85
+ not itself authorize this skill to remove it; route any cleanup through `tidy` and leave the
86
+ decision to the Hephaestus workflow and the user's answers to its prompts.
87
+
88
+ ## Quick Reference
89
+
90
+ | Situation | Action |
91
+ | ----------- | -------- |
92
+ | `.worktrees/` exists + ignored | Use it |
93
+ | Neither exists | Use the host temporary directory with `<project>-<branch>` |
94
+ | Directory not ignored | Add to `.gitignore` + commit first |
95
+ | Tests fail at baseline | Report failures + ask before proceeding |
96
+
97
+ ## Common Mistakes
98
+
99
+ - **Skipping ignore verification** for project-local worktrees → contents get tracked
100
+ - **Proceeding with failing baseline** → can't distinguish new bugs from pre-existing
101
+ - **Not cleaning up** → stale worktrees accumulate
102
+
103
+ ## Integration
104
+
105
+ **Pairs with:**
106
+
107
+ - Invoke `tidy` for dependency-locked delegation to Hephaestus branch and worktree cleanup.
108
+ - Verify with fresh runnable evidence per the evidence-integrity policy before finishing and
109
+ cleaning up.
110
+
111
+ ---
112
+
113
+ _Adapted from [obra/superpowers](https://github.com/obra/superpowers) under the [MIT License](https://github.com/obra/superpowers/blob/main/LICENSE). Copyright (c) 2025 Jesse Vincent._
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env python3
2
+ """Select, validate, and optionally create an isolated Git worktree."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ if __package__ in {None, ""}:
13
+ sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
14
+
15
+ from skills._cli import argument_parser, run_command
16
+
17
+
18
+ def git(
19
+ cwd: Path, *arguments: str, check: bool = True
20
+ ) -> subprocess.CompletedProcess[str]:
21
+ result = run_command(
22
+ ["git", *arguments], cwd=cwd, capture_output=True, text=True, check=False
23
+ )
24
+ if check and result.returncode != 0:
25
+ raise RuntimeError(result.stderr.strip() or f"git {' '.join(arguments)} failed")
26
+ return result
27
+
28
+
29
+ def reject_symlinks_below(trust_root: Path, target: Path) -> None:
30
+ """Reject symlinks in the caller-controlled path below a trusted root."""
31
+ lexical_root = trust_root.absolute()
32
+ lexical_target = target.absolute()
33
+ try:
34
+ lexical_target.relative_to(lexical_root)
35
+ except ValueError as error:
36
+ raise RuntimeError(
37
+ f"worktree path escapes trusted root {lexical_root}"
38
+ ) from error
39
+ for component in (*reversed(lexical_target.parents), lexical_target):
40
+ if component.is_symlink():
41
+ raise RuntimeError(f"worktree path component is a symlink: {component}")
42
+
43
+
44
+ def select_path(
45
+ root: Path,
46
+ branch: str,
47
+ requested: Path | None,
48
+ exact_path: Path | None,
49
+ path_root: Path | None,
50
+ ) -> tuple[Path, bool]:
51
+ if exact_path is not None:
52
+ path = exact_path if exact_path.is_absolute() else root / exact_path
53
+ trust_root = path_root if path_root is not None else path.parent
54
+ if not trust_root.is_absolute():
55
+ trust_root = root / trust_root
56
+ reject_symlinks_below(trust_root, path)
57
+ resolved_path = path.resolve()
58
+ return resolved_path, resolved_path.is_relative_to(root)
59
+ if requested is not None:
60
+ base = requested if requested.is_absolute() else root / requested
61
+ path = base / branch
62
+ reject_symlinks_below(base, path)
63
+ return path.resolve(), path.resolve().is_relative_to(root)
64
+ for directory_name in (".worktrees", "worktrees"):
65
+ directory = root / directory_name
66
+ if directory.is_dir():
67
+ if directory.is_symlink():
68
+ raise RuntimeError(
69
+ f"project-local worktree directory is a symlink: {directory}"
70
+ )
71
+ return (directory / branch).resolve(), True
72
+ project = root.name
73
+ return Path(tempfile.gettempdir()) / f"{project}-{branch}", False
74
+
75
+
76
+ def verify_ignored(root: Path, path: Path) -> None:
77
+ try:
78
+ relative = path.relative_to(root)
79
+ except ValueError:
80
+ return
81
+ probe = relative.parent / ".athena-ignore-probe"
82
+ result = git(root, "check-ignore", "-q", "--", str(probe), check=False)
83
+ if result.returncode != 0:
84
+ raise RuntimeError(
85
+ f"project-local worktree directory {relative.parent} is not ignored"
86
+ )
87
+
88
+
89
+ def main() -> int:
90
+ parser = argument_parser(description=__doc__)
91
+ parser.add_argument("branch")
92
+ path_selection = parser.add_mutually_exclusive_group()
93
+ path_selection.add_argument("--directory", type=Path)
94
+ path_selection.add_argument("--path", type=Path)
95
+ parser.add_argument("--path-root", type=Path)
96
+ parser.add_argument("--start-point", required=True)
97
+ parser.add_argument("--dry-run", action="store_true")
98
+ arguments = parser.parse_args()
99
+ try:
100
+ root = Path(git(Path.cwd(), "rev-parse", "--show-toplevel").stdout.strip())
101
+ branch_check = git(
102
+ root, "check-ref-format", "--branch", arguments.branch, check=False
103
+ )
104
+ if branch_check.returncode != 0:
105
+ raise RuntimeError(f"invalid branch name: {arguments.branch}")
106
+ if (arguments.path is None) != (arguments.path_root is None):
107
+ raise RuntimeError("--path and --path-root must be provided together")
108
+ path, project_local = select_path(
109
+ root,
110
+ arguments.branch,
111
+ arguments.directory,
112
+ arguments.path,
113
+ arguments.path_root,
114
+ )
115
+ start_sha = git(
116
+ root,
117
+ "rev-parse",
118
+ "--verify",
119
+ f"{arguments.start_point}^{{commit}}",
120
+ ).stdout.strip()
121
+ if project_local:
122
+ verify_ignored(root, path)
123
+ if path.exists():
124
+ raise RuntimeError(f"worktree path already exists: {path}")
125
+ if not arguments.dry_run:
126
+ git(
127
+ root,
128
+ "worktree",
129
+ "add",
130
+ str(path),
131
+ "-b",
132
+ arguments.branch,
133
+ start_sha,
134
+ )
135
+ except RuntimeError as error:
136
+ print(error, file=sys.stderr)
137
+ return 1
138
+ print(
139
+ json.dumps(
140
+ {
141
+ "branch": arguments.branch,
142
+ "created": not arguments.dry_run,
143
+ "path": str(path),
144
+ "start_sha": start_sha,
145
+ },
146
+ sort_keys=True,
147
+ )
148
+ )
149
+ return 0
150
+
151
+
152
+ if __name__ == "__main__":
153
+ raise SystemExit(main())
@@ -0,0 +1,67 @@
1
+ ---
2
+ name: issue-review
3
+ license: BSD-3-Clause
4
+ description: Review a GitHub or GitLab issue and its current plan-issue artifact for architecture alignment, scope, risks, and behavior-first verification. Use before implementation; `--report-only` is read-only.
5
+ argument-hint: "[--report-only] ISSUE_NUMBER_OR_URL"
6
+ allowed-tools: [Read, Bash, Grep, Glob, Agent, WebFetch]
7
+ ---
8
+
9
+ # Review an issue and plan
10
+
11
+ Why: find architecture, scope, and verification gaps while changing the plan is
12
+ still cheaper than changing code.
13
+
14
+ Use the shared [issue-planning contract](../../docs/review/issue-planning.md),
15
+ [review contract](../../docs/review/common.md),
16
+ [language routing](../../docs/review/language-routing.md), and
17
+ [behavior-first testing](../../docs/review/behavior-first-testing.md).
18
+
19
+ ## Scope and delivery
20
+
21
+ The issue is the requirements source; review only its current canonical plan.
22
+ Resolve plan ownership, marker, absence, and identity under the issue-planning
23
+ contract. Historical plans and reviews are bounded context, not the artifact
24
+ under review.
25
+
26
+ `--report-only` is read-only. A requested review without it may publish exactly
27
+ one actor-owned structured review comment after the required identity comparison
28
+ and forge-capability check. It does not expand scope to labels, assignment,
29
+ implementation, commit, push, pull request, merge, or issue closure.
30
+
31
+ ## Review
32
+
33
+ 1. Read the issue, linked work, canonical plan, repository guidance, ADRs,
34
+ relevant code, tests, and public contracts.
35
+ 2. Decide architecture first: aligned, intentional and justified change, or an
36
+ unexplained violation. A material violation blocks a positive assessment.
37
+ 3. Map every acceptance criterion to a concrete plan step, affected boundary,
38
+ and behavior-first validation step. For a material architecture change,
39
+ verify that the plan includes or cites a
40
+ [design record](../../docs/review/design-docs.md).
41
+ 4. Verify cited paths, symbols, commands, dependencies, assumptions, risks,
42
+ migration, and rollback claims against current repository evidence.
43
+ 5. Apply only activated language and change-surface checks, recording N/A
44
+ sections and reasons. Confirm that relevant prior findings are resolved,
45
+ rather than merely acknowledged.
46
+
47
+ Prioritize architecture violations, missing requirements, unsafe scope,
48
+ unresolved dependencies, untestable outcomes, invalid references,
49
+ non-deterministic tests, empty selections, and unsupported claims.
50
+
51
+ When reviewing after a finalized epoch, do not reinterpret generated plan text
52
+ or sealed provenance as new requirements. Review only a later material issue
53
+ change and its current canonical plan; an unchanged finalized epoch is not a
54
+ new review target.
55
+
56
+ Immediately before a requested publication, re-resolve the canonical planning
57
+ identity. On drift, foreign or multiple markers, verified absence changes, or
58
+ missing safe forge capability, withhold the comment and return the review as
59
+ stale. Otherwise publish exactly one actor-owned structured comment, including
60
+ a clean result or verified absent-plan coverage gap.
61
+
62
+ ## Result
63
+
64
+ Return issue and plan identities, architecture decision first, requirement
65
+ mapping, severity-ranked findings, test-quality coverage, N/A sections,
66
+ residual risks, and whether the comment was published or withheld. A review
67
+ never expands scope to implementation or merge.
@@ -0,0 +1,208 @@
1
+ ---
2
+ name: learn
3
+ license: BSD-3-Clause
4
+ description: Preserve a verified, non-duplicate Mnemosyne lesson as a bounded generalized skill, with prior versions in .history and supporting evidence in .notes.md, through an isolated-worktree pull request when requested; otherwise report without mutation. A usable knowledge checkout is required before discovery or writing; read-only discovery may use its current contents without upstream synchronization, while new-PR delivery requires a fresh synchronized default-branch base.
5
+ argument-hint: <lesson or session summary>
6
+ allowed-tools: [Read, Write, Edit, Bash, Grep, Glob, Agent]
7
+ ---
8
+
9
+ # Learn
10
+
11
+ Why: one concise, general rule is more discoverable and safer than many session-specific copies.
12
+ First decide whether a durable delta exists; then partition it into retrievable guidance, history, and
13
+ supporting notes before writing through a reviewable PR.
14
+
15
+ ## Prepare the knowledge repository
16
+
17
+ Prepare Mnemosyne at `$HOME/.agent_brain/knowledge` under the canonical
18
+ [`dependency-resolution` contract](../../docs/dependency-resolution.md). Report the resolved
19
+ repository, commit SHA, and trust basis. A usable knowledge checkout is required before discovery
20
+ or writing. Normal preparation may create it under the dependency-resolution contract. Any checkout
21
+ or inspection failure blocks `learn`; upstream resolution, authentication, update, and revalidation
22
+ may be deferred during read-only discovery but are required at the delivery boundary.
23
+
24
+ **Read-only discovery:** require the existing checkout, but do not require upstream resolution,
25
+ fetch, fast-forward, or automatic-fork revalidation. Bind discovery to its current `HEAD`, report
26
+ its repository, revision, origin/trust status, and freshness or verification limitation, and use the
27
+ checked-out content as best effort. If no usable checkout exists or inspection fails, report
28
+ `blocked` and stop; do not substitute another repository or continue into duplicate analysis.
29
+
30
+ Before creating a new PR, complete the normal dependency-resolution update and revalidation against
31
+ the canonical default branch. Bind the delivery worktree to that exact fresh SHA. Planning and
32
+ read-only discovery may use a stale checkout; PR delivery may not.
33
+
34
+ ## Decide before writing
35
+
36
+ This phase is read-only.
37
+
38
+ The steps below require the existing checkout described above. In read-only discovery, do not derive
39
+ a durable write disposition or continue after the required checkout is unavailable.
40
+
41
+ 1. Run `advise` with the proposed lesson, using its planning-mode best-effort behavior for this
42
+ read-only discovery phase.
43
+ 2. Define retrieval intent as the trigger/context, desired outcome, constraints, and failure mode;
44
+ never use title, issue number, or session wording as identity.
45
+ 3. Resolve the installed `advise/scripts/list_retrievable_skills.py` helper and run it by absolute
46
+ path against the knowledge checkout. Group only its returned main-skill paths by intent; then
47
+ inspect each selected candidate, its `.history`, its relevant `.notes.md`, and Git history for
48
+ provenance and prior consolidation. A missing or failed selector is blocking because an ad hoc
49
+ glob could silently change the retrieval boundary.
50
+ 4. Inspect every open PR in the resolved Mnemosyne repository: enumerate its changed flat
51
+ `skills/*.md` artifacts and derive intent from their changed content. A title or path only finds a
52
+ candidate; it is never sufficient duplicate evidence.
53
+ 5. Record exactly one disposition before mutation:
54
+
55
+ | Disposition | Use when | Action |
56
+ | --- | --- | --- |
57
+ | `amend` | One canonical entry has a material verified delta. | Update that canonical artifact set only. |
58
+ | `consolidate` | Two or more current entries share intent. | Select one canonical artifact set, merge non-superseded rules, and retire duplicates in the same PR. |
59
+ | `create` | Intent is materially distinct. | Add one precisely named artifact set. |
60
+ | `reject` | No durable, verified delta exists. | Report `no learnable change`; leave Mnemosyne unchanged. |
61
+ | `blocked` | Provenance is uncertain, more than one open PR targets the selected canonical entry, the selected PR is not safely writable, or retirement is unsafe. | Leave Mnemosyne unchanged and request direction. |
62
+
63
+ Never evade a blocked consolidation by creating a near-duplicate. When exactly one open PR changes
64
+ the selected canonical entry, it is the delivery target: enter Existing-PR mode and incorporate the
65
+ verified delta there. Never create a competing PR. Stop rather than guessing when multiple open PRs
66
+ target that entry. Do not report `learn` complete after `reject` or `blocked`.
67
+
68
+ Repository audits belong in `repo-review`; PR audits belong in `pr-review`; review depth is a mode.
69
+
70
+ ## Keep retrieval bounded
71
+
72
+ Treat each lesson as three different information classes. Do not use the main skill as an append-only
73
+ record.
74
+
75
+ | Artifact | Contains | Excludes |
76
+ | --- | --- | --- |
77
+ | `skills/<name>.md` | Current generalized triggers, decision rules, workflow, failures, parameters, and zero to three concise examples that materially change a decision | Prior versions, changelog narrative, session chronology, transcripts, and repeated project cases |
78
+ | `skills/<name>.history` | Superseded main-skill versions plus append-only version, change, and provenance records | Active instructions that exist only here |
79
+ | `skills/<name>.notes.md` | Privacy-cleared source detail, long examples, commands, measurements, verification reports, and other supporting evidence worth retaining | Rules required for the skill to work |
80
+
81
+ For every amendment, rewrite the main entry around the smallest reusable delta instead of appending
82
+ the session. Merge overlapping rules, remove superseded guidance, and retain at most three examples;
83
+ each example must cover a materially different decision branch and be shorter than the rule it
84
+ illustrates. A repository name, issue narrative, transcript, or another instance of an established
85
+ pattern is evidence, not a new main-skill example.
86
+
87
+ Before replacing a main entry, archive its complete prior retrievable content in `.history` unless
88
+ that version is already present. Append the new version and provenance record there. Put detailed
89
+ evidence that remains useful for the current rule in `.notes.md`. Never move prohibited sensitive
90
+ content merely to preserve it.
91
+
92
+ Keep only a schema-required current version identifier in main-file frontmatter. Put all prior
93
+ versions, change summaries, provenance, and other version-control narrative in `.history`. Obey the
94
+ resolved repository's main-skill size budget; for Mnemosyne, a new or changed retrievable main file
95
+ must not exceed 30,000 bytes. Notes and history must remain outside normal retrieval.
96
+
97
+ ## Privacy and proprietary-information gate
98
+
99
+ Treat the session, its repositories, and all discovery output as sensitive source material. A
100
+ durable lesson must capture only the general pattern, decision rule, and safely shareable evidence;
101
+ it must never store any of the following in a main skill, notes, history, filename, frontmatter,
102
+ example, commit, or PR description:
103
+
104
+ - PII or identifiers that can identify a person, account, customer, or organization;
105
+ - product, project, customer, vendor, or organization names and other non-public identifiers;
106
+ - internal paths, hostnames, URLs, repository names, issue IDs, environment names, or infrastructure
107
+ details;
108
+ - proprietary source, configuration, prompts, logs, data, metrics, or operational details; or
109
+ - secrets, credentials, tokens, or other access material.
110
+
111
+ Replace sensitive specifics with a faithful general pattern (for example, "an isolated checkout"
112
+ instead of a local path). When public information provides an equivalent, cite or describe that
113
+ public equivalent rather than copying internal evidence. Never invent a public analogue, a result,
114
+ or verification evidence. If the lesson cannot be made useful without disclosing sensitive or
115
+ proprietary information, select `reject`, leave Mnemosyne unchanged, and report that no safe
116
+ learnable change exists.
117
+
118
+ If a lesson requires Athena implementation, complete that normal development first. Follow
119
+ [`development.md`](../../docs/policies/development.md): keep helpers in `skills/<name>/scripts/`,
120
+ add behavior-based executable tests under `tests/unit/`, and do not add inline executable Markdown,
121
+ wording tests, or non-consumed artifacts merely to support a lesson.
122
+
123
+ ## Scope
124
+
125
+ Read-only discovery does not expand the requested scope. When the task requests durable learning,
126
+ the resolved repository and full delivery path are constructive work that may proceed through either
127
+ a new PR or the single Existing-PR target selected during discovery. A recommendation or indirect
128
+ invocation remains read-only; return the proposed repository, base, branch, files, and PR target.
129
+
130
+ ## Existing-PR mode
131
+
132
+ Use this mode when discovery identifies exactly one open PR that changes the selected canonical
133
+ entry. Re-fetch and bind its canonical repository, URL/number, `OPEN` state, source repository/ref,
134
+ and head OID before editing. Create an isolated worktree on that source ref at the bound head OID,
135
+ verify its `HEAD`, and never modify the shared checkout or default branch.
136
+
137
+ Immediately before publishing, re-fetch the same identity and head. Push only to the bound PR source
138
+ ref, using the provider's safe expected-head/lease protection. If the ref moves, the source repository
139
+ is not safely writable, or any binding differs, preserve the worktree and stop. Do not create a
140
+ branch, open another PR, or retarget the change. Use the disposition-specific write allowlist below.
141
+
142
+ ## Coordinate safely
143
+
144
+ When available, partition independent discovery, overlap analysis, drafting, and verification into
145
+ bounded work items; otherwise perform them sequentially without weakening evidence. New-PR writers
146
+ use isolated worktrees from the same resolved default-branch SHA; Existing-PR writers use only the
147
+ bound PR head. Give writers non-overlapping ownership; read-only work items never edit. The
148
+ coordinator owns each canonical entry or assigns one integration owner, rejects unrelated edits, runs
149
+ focused validation after each integration and complete relevant validation after the combined result,
150
+ and alone commits, pushes, and opens a new PR when applicable. Stop on ownership overlap, base drift,
151
+ or unexpected scope.
152
+
153
+ Without native isolation, use the installed `../git-worktrees/scripts/prepare_worktree.py` by absolute
154
+ path only for new-PR work: retain the resolved checkout as the current directory; use branch
155
+ `skill/<slug>`, `--path $HOME/.agent_brain/worktrees/knowledge-<slug>`,
156
+ `--path-root $HOME/.agent_brain/worktrees`, and `--start-point <resolved-default-SHA>`. Never use
157
+ this fallback to reconstruct an Existing-PR worktree.
158
+
159
+ ## Deliver a requested change
160
+
161
+ 1. Never modify the shared checkout. Before creating a new-PR worktree, complete the deferred
162
+ dependency-resolution update and bind it to the exact current default-branch SHA. Then derive
163
+ `slug` and `name` from lowercase ASCII
164
+ letters, digits, and single hyphens using `[a-z0-9][a-z0-9-]*`; reject empty, control, `/`, `..`,
165
+ and leading `-` values. Add a collision-resistant suffix when needed. Create `skill/<slug>` at
166
+ `$HOME/.agent_brain/worktrees/knowledge-<slug>` from the resolved default-branch SHA; resolve the
167
+ path first, require it directly below `$HOME/.agent_brain/worktrees`, and reject symlinked parents
168
+ or destinations. This is the new-PR path for `create` and `consolidate`, not Existing-PR mode.
169
+ 2. Before editing, resolve a closed, disposition-specific write allowlist of exact repository-relative
170
+ paths. Include only companions required by the artifact partition:
171
+
172
+ | Disposition | Allowed paths |
173
+ | --- | --- |
174
+ | `amend` | The canonical `.md`, its `.history`, and its `.notes.md` when supporting detail exists. |
175
+ | `create` | One new `.md`, its initial `.history`, and `.notes.md` only when supporting detail exists. |
176
+ | `consolidate` | The canonical three artifacts, each named duplicate to retire, and each verified active consumer that must migrate. |
177
+
178
+ Name every companion and retirement explicitly. Do not discover new write paths while editing.
179
+ 3. For `create`, read the resolved Mnemosyne template, schema, and validation rules before drafting.
180
+ Use every required frontmatter field, including `name`, `description`, `category`, `date`, and
181
+ the current `version`, plus the required section structure. Keep searchable intent, generalized
182
+ use and workflow, relevant failed approaches, and parameters in the main entry. Create the initial
183
+ version/provenance record in `.history`; route useful supporting detail to `.notes.md`.
184
+ 4. Apply the selected disposition inside its allowlist. For `amend` or `consolidate`, archive each
185
+ superseded canonical version before rewriting the main entry. Apart from that required historical
186
+ snapshot, partition rather than copy: current rules, history records, and notes evidence each have
187
+ one owner. During consolidation, migrate verified active consumers before retiring every named
188
+ duplicate.
189
+ 5. Before committing, review every proposed artifact and delivery text against the privacy and
190
+ proprietary-information gate. Remove or generalize sensitive specifics; use a faithful public
191
+ equivalent only when one exists. If safe generalization is not possible, reject the lesson.
192
+ 6. Run Mnemosyne's relevant complete validation. Verify exactly one active entry remains for the
193
+ intent; its main file is within the configured size budget; notes and history are excluded from
194
+ normal retrieval; and no duplicate intent, embedded version history, or stale consolidated name
195
+ was introduced.
196
+ 7. Sign and DCO-attest the commit. For a new PR, push the feature branch and open a PR against the
197
+ resolved default branch. For Existing-PR mode, push only to the already bound source ref and do
198
+ not open another PR. Never auto-merge.
199
+ 8. Report the disposition, bound or new PR URL, main-file byte size, archived version, companion
200
+ files, any retired entries, and exact validation evidence.
201
+
202
+ A write disposition succeeds only with its PR URL. If validation, push, or PR creation fails, preserve
203
+ the isolated worktree and report the blocker; never fall back to Athena, a default branch, or another
204
+ repository. Preserve delegated and delivery worktrees until their unique work is integrated or
205
+ explicitly rejected. Cleanup is separate: remove only worktrees created by this invocation, only with
206
+ user authority, only after confirming no uncommitted or unintegrated state remains. Otherwise report
207
+ each worktree's path, owner, revision, cleanliness, and integration state and leave it intact. Never
208
+ delete branches, discard changes, force removal, or touch a pre-existing worktree.