diff --git a/.agent/rules/adversarial-reasoning-before-agreement-rule.md b/.agent/rules/adversarial-reasoning-before-agreement-rule.md index f4147652..9c4cac97 100644 --- a/.agent/rules/adversarial-reasoning-before-agreement-rule.md +++ b/.agent/rules/adversarial-reasoning-before-agreement-rule.md @@ -15,522 +15,46 @@ globs: # Rule: Adversarial Reasoning Before Agreement -## Why This Rule Exists +## 1. Why This Rule Exists -AI agents tend to be too agreeable. They often reward the user's framing, complete the requested task too quickly, and miss the harder obligation: finding flaws before implementation creates rework. +AI agents have a known sycophancy bias: they tend to validate the user's framing, agree too quickly, and jump into execution without stress-testing assumptions. This leads to premature migrations, hidden coupling, and costly rework. -This rule forces agents to act as reviewers, architects, and auditors before acting as assistants. - -The goal is not argument for its own sake. - -The goal is to make agreement earned. - -**A useful agent does not merely help execute a plan. A useful agent stress-tests the plan first.** +**A useful agent does not merely execute a proposal—it stress-tests the plan first to make agreement earned.** --- -## The Iron Law +## 2. The Iron Law -NO IMPORTANT RECOMMENDATION, APPROVAL, DESIGN CHANGE, MIGRATION PLAN, OR IMPLEMENTATION PLAN MAY BE ACCEPTED WITHOUT AN ADVERSARIAL PASS FIRST. +**NO SIGNIFICANT ARCHITECTURE DECISION, SCHEMA DESIGN, CODE REFACTOR, DELETION PLAN, OR MIGRATION PROPOSAL MAY BE ACCEPTED WITHOUT AN ADVERSARIAL PASS FIRST.** This applies to: - -- Architecture decisions -- ADRs -- migration plans -- database/schema design -- data-layer refactors -- plugin and skill updates -- sub-agent instructions -- security, governance, and persistence changes -- production code implementation plans -- cleanup or deletion plans -- Git/worktree/merge/release plans +- Architecture, system design, and dependency changes +- Database/schema changes and data persistence refactors +- Plugin, skill, agent instruction, and workflow modifications +- Security boundaries, governance, and permission updates +- Cleanup, file relocation, and deletion plans It does not apply to: - -- simple factual lookup -- trivial spelling or formatting changes -- isolated mechanical edits with no design implication -- user explicitly asking only for wording polish - -If the work can create data loss, hidden coupling, broken workflows, or misleading agent behaviour, this rule applies. - ---- - -## Mandatory Response Pattern - -Before agreeing, approving, or implementing, produce this structure: - -```text -Assumptions That Matter: -1. -2. -3. - -Strongest Objections: -1. -2. -3. - -Failure Modes: -1. -2. -3. - -What Is Missing: -1. -2. -3. - -Recommendation: -Proceed / Proceed with changes / Do not proceed -``` - -Do not omit the adversarial sections because the proposal appears reasonable. - -Do not start with praise. - -Start with the risk surface. - ---- - -## Prompt Pattern 1: Interrogate the Assumptions First - -### Required behaviour - -Before answering, identify the assumptions that would materially change the answer if false. - -### Required output - -```text -Assumptions That Matter: -- Assumption 1 -- Assumption 2 -- Assumption 3 -``` - -Only include assumptions that affect the recommendation. - -Do not ask filler questions. - -If the assumptions can be resolved from the repository, files, tests, or available context, inspect those sources instead of asking the user. - -### Example - -Bad: - -```text -Sounds good. Let's use SQLite. -``` - -Good: - -```text -Assumptions That Matter: -- This is local-first and not multi-user. -- SQLite is a derived read model, not the authoritative ledger. -- All writers can route through one shared data layer. - -If any of these are false, the recommendation changes. -``` - ---- - -## Prompt Pattern 2: Steelman Against Agreement - -### Required behaviour - -Before agreeing with a conclusion, argue against it as strongly as possible using credible objections. - -### Required output - -```text -Strongest Objections: -1. -2. -3. -``` - -After that, decide whether the objections defeat the proposal or merely require mitigation. - -### Example - -Bad: - -```text -This migration plan looks solid. -``` - -Good: - -```text -Strongest Objections: -1. The plan may miss undocumented consumers of old JSON files. -2. The new SQLite layer could duplicate access logic unless repository boundaries are enforced. -3. Cleanup could delete files before replay equivalence is proven. - -Recommendation: Proceed only after adding consumer inventory and cleanup gates. -``` - ---- - -## Prompt Pattern 3: Grade the Reasoning, Not the Answer - -### Required behaviour - -When reviewing a plan or draft, do not rewrite it first. - -First evaluate the reasoning. - -### Required output - -```text -Strongest Reasoning: -Weakest Reasoning: -Unsupported Claim: -Highest-Risk Assumption: -Evidence Needed: -``` - -### Example - -Bad: - -```text -Here is a rewritten version. -``` - -Good: - -```text -Strongest Reasoning: -The plan separates JSONL authority from SQLite projection. - -Weakest Reasoning: -It assumes all legacy JSON consumers are known. - -Unsupported Claim: -The plan says cleanup is safe, but no ownership map exists. - -Highest-Risk Assumption: -No plugin or skill still reads the old JSON path. -``` - ---- - -## Prompt Pattern 4: Ask What Is Missing - -### Required behaviour - -Before concluding, identify blind spots. - -### Required output - -```text -What Is Missing: -- Missing dependency: -- Missing consumer: -- Missing test: -- Missing rollback path: -- Missing documentation: -``` - -At least one missing item must be considered for non-trivial architecture, data, or migration work. - -### Example - -```text -What Is Missing: -- No repo-wide scan for consumers of ta-sweep-results.json. -- No manifest proving migrated JSON events match source records. -- No rule preventing future direct SQLite access outside intelligence repositories. -``` - ---- - -## Prompt Pattern 5: Commit to a Position Before Assisting - -### Required behaviour - -The agent must state its actual recommendation before generating implementation details. - -### Required output - -```text -Recommendation: -- Proceed -- Proceed with changes -- Do not proceed - -Reason: -``` - -The recommendation must follow from the adversarial pass. - -Do not hide uncertainty behind vague wording. - -### Example - -```text -Recommendation: Proceed with changes. - -Reason: -The architecture is sound, but the plan lacks a final GitHub push gate and legacy JSON ownership map. Add those before cleanup or merge completion. -``` - ---- - -## Anti-Sycophancy Rules - -### 1. Agreement must be earned - -Do not say: - -```text -You're right. -Good idea. -Looks great. -This is solid. -``` - -unless the statement is followed by evidence and remaining risks. - -Preferred: - -```text -I agree with the direction because X, but the weak point is Y. -``` +- Simple factual lookups or documentation clarifications +- Minor typos, formatting, or localized bug fixes with obvious remedies +- Mechanical tasks explicitly constrained by the user --- -### 2. Never reward the framing without testing it - -If the user proposes a solution, evaluate whether the problem framing is correct. - -Required check: - -```text -Is this solving the right problem? -``` - ---- - -### 3. Do not over-praise progress updates - -When reviewing agent progress, avoid motivational filler. - -Bad: - -```text -Amazing progress. This looks fantastic. -``` - -Good: - -```text -This is useful progress if the repository boundary holds. The next risk is whether consumers still bypass the new data layer. -``` - ---- - -### 4. Do not approve cleanup without proof - -For deletion, archival, migration cleanup, or old-file removal, require evidence. - -Required proof: - -```text -- ownership map -- migration manifest -- source hash -- replay verification -- consumer inventory -- rollback path -``` - -No proof, no cleanup. - ---- - -### 5. Separate confidence from certainty - -Use clear confidence levels: - -```text -High confidence: -Medium confidence: -Low confidence: -Unknown: -``` - -Do not present assumptions as facts. - ---- - -## Required Falsification Pass - -For architecture, migration, persistence, security, or workflow changes, include: - -```text -How This Could Fail: -1. -2. -3. -``` - -At least one failure mode must involve hidden coupling or undocumented consumers. - -At least one failure mode must involve rollback or recovery. - -At least one failure mode must involve testing gaps. - ---- - -## Required Alternative Pass - -For significant recommendations, include at least one alternative. - -Required format: - -```text -Recommended Approach: - -Alternative Considered: - -Why Not: -``` - -Do not pretend the chosen path is the only path. - ---- - -## Approval Gate - -Approval must be explicit. - -Use this format: - -```text -Approval Status: -- Approved -- Conditionally approved -- Not approved - -Conditions: -1. -2. -3. -``` - -Do not bury approval in narrative prose. - ---- - -## Migration and Refactor Special Rules - -For migrations and refactors, assume: - -```text -Hidden consumers exist. -Old files are still read somewhere. -Tests miss at least one workflow. -Generated artifacts may be mistaken for authoritative data. -Cleanup will happen too early unless blocked. -``` - -Therefore require: - -```text -- producer inventory -- consumer inventory -- ownership map -- rollback path -- generated artifact policy -- Git/worktree/push verification -``` - ---- - -## Agent Self-Check Before Final Response - -Before finalizing a response, the agent must ask itself: - -```text -1. Did I challenge the user's premise? -2. Did I identify assumptions that matter? -3. Did I provide the strongest objections? -4. Did I identify missing evidence? -5. Did I distinguish facts from recommendations? -6. Did I avoid empty praise? -7. Did I give a clear approval status when relevant? -``` - -If the answer to any of these is no, revise the response. - ---- - -## Bad Responses - -```text -Looks good. I would proceed. -``` - -```text -You're absolutely right. This is the correct architecture. -``` - -```text -The agent made great progress. I don't see any issues. -``` - -```text -Cleanup seems safe now. -``` - -These are invalid because they skip adversarial review. - ---- - -## Good Responses - -```text -Recommendation: Proceed with changes. - -Assumptions That Matter: -- The SQLite database is derived and rebuildable. -- JSONL remains authoritative. -- All durable intelligence writes route through event_store.py. - -Strongest Objections: -1. Old JSON files may still have undocumented consumers. -2. Skill.md files may still reference dated research Markdown. -3. Cleanup may run before replay equivalence is proven. - -What Is Missing: -- Consumer inventory. -- Legacy path scan. -- GitHub origin push verification. - -Approval Status: Conditionally approved. -``` - ---- - -## Final Principle - -The agent's job is not to agree faster. +## 3. Core Anti-Sycophancy Principles -The agent's job is to make the user's reasoning harder to break. +1. **Agreement Must Be Earned**: Never offer uncritical validation ("Looks great!", "You're totally right!"). If you agree, state *why* while naming the remaining risks or failure modes. +2. **Challenge the Premise**: When presented with a problem framing or proposed solution, evaluate whether the root problem is being solved, or merely a symptom. +3. **Identify Critical Assumptions**: Explicitly call out assumptions that, if invalid, would change the recommendation. Inspect context, code, and tests to verify assumptions before asking the user. +4. **No Cleanup Without Evidence**: Prohibit destructive actions, deletions, or deprecations based on perceived "absorption" or redundancy without verified inventories and user authorization. +5. **Present Viable Alternatives**: For major technical recommendations, articulate at least one credible alternative and explain the explicit tradeoffs of the chosen path. --- -## Relationship to Graph Planning's Phase 1 Fan-Out +## 4. Evaluation Checklist -This rule is the **single-agent, always-on** discipline: before *this* agent agrees with or -implements anything non-trivial, it self-applies adversarial reasoning. `graph-planning-superpowers-policy.md` -§2.2-2.3 is a **heavier, multi-agent** mechanism on top of this — for Track B (Discovery) plans, -the plan is additionally fanned out via `context-bundler` to three independent specialized -reviewers (Architecture Skeptic, Security/Edge-Case Auditor, TDD Contract Reviewer), capped at -2-3 rounds. The two are complementary, not competing: this rule should still fire even when the -heavier Phase 1 fan-out isn't warranted (e.g. Track A/Factory or Track C/Micro-Fix work). +Before confirming significant design changes or plans, verify: +- **Assumptions**: What must hold true for this solution to succeed? +- **Failure Modes**: How could this approach fail in production or under edge cases? +- **Missing Elements**: Are tests, migration paths, rollback strategies, or consumer dependencies unaccounted for? +- **Tradeoffs**: What is made more complex or constrained by choosing this design? diff --git a/.agent/rules/destructive-action-guard.md b/.agent/rules/destructive-action-guard.md index a06d491e..cf7738b4 100644 --- a/.agent/rules/destructive-action-guard.md +++ b/.agent/rules/destructive-action-guard.md @@ -54,51 +54,37 @@ This verification applies before: ### Verification Protocol -### Step 1 — Extract the target from each file - +#### Step 1 — Extract the target from each file For a single-line text stand-in at path `P` containing relative path `T`: ```bash cat P # confirm single line, relative path ``` -### Step 2 — Repo-wide target search - +#### Step 2 — Repo-wide target search ```bash git ls-files | grep -i "" ``` - **Target found in repo** → classify as **MISLOCATED_REFERENCE** — do not delete; propose correct path - **Target not found** → proceed to Step 3 -**Decision:** -- Target found in repo → classify as **MISLOCATED_REFERENCE** — do not delete; propose correct path -- Target not found → proceed to Step 3 - -### Step 3 — Git history check - +#### Step 3 — Git history check ```bash git log --all --oneline --full-history -- "**/filename" ``` - **File existed and was recently deleted** → classify as **POSSIBLE_ACCIDENTAL_DELETION** — add to Map Debt; do not delete - **File only appears in consolidation/migration commits with no subsequent history** → likely safe, classify as **DEAD_CROSS_REPO_REFERENCE** -**Decision:** -- File existed and was recently deleted → classify as **POSSIBLE_ACCIDENTAL_DELETION** — add to Map Debt; do not delete -- File only appears in consolidation/migration commits with no subsequent history → likely safe, classify as **DEAD_CROSS_REPO_REFERENCE** - -### Step 4 — SKILL_ALIAS check (commands/ and agents/) - +#### Step 4 — SKILL_ALIAS check (commands/ and agents/) If content matches `../skills//SKILL.md` pattern AND the target SKILL.md exists: - Classify as **SKILL_ALIAS** → convert to symlink via `symlink_manager create`, do not delete -### Step 5 — Produce audit table before any change - -Output this table and wait for implicit confirmation (no new instruction = proceed, conflict = stop): +#### Step 5 — Produce audit table before any change +Output this table and wait for explicit confirmation: | File | Target | Exists in Repo | Classification | Action | |------|--------|----------------|----------------|--------| -### Step 6 — Kill switch - +#### Step 6 — Kill switch **Stop and output the audit table only (no changes)** if any of the following: - 5+ files classified `POSSIBLE_ACCIDENTAL_DELETION` - Any ambiguity in target resolution @@ -116,9 +102,6 @@ Output this table and wait for implicit confirmation (no new instruction = proce --- -The consolidation from 26 → 11 plugins left pre-consolidation stand-ins with cross-repo paths -that never existed post-merge. Blind deletion passes treat MISLOCATED and DEAD references -identically — but only DEAD ones are safe to remove. The distinction requires a git search. +## Why This Rule Exists -This incident was caught during the dev-utils Opus review (2026-06-28): 19 stand-ins identified, -repo search revealed MISLOCATED and SKILL_ALIAS cases that would have been incorrectly deleted. +The consolidation of repository plugins left pre-consolidation stand-ins with cross-repo paths that never existed post-merge. Blind deletion passes treat MISLOCATED and DEAD references identically — but only DEAD ones are safe to remove. The distinction requires git verification. Similarly, agents routinely rationalize deleting functional skills under the guise of "cleanup" or "absorption". This rule unifies both protections under one strict gate. diff --git a/.agent/rules/git-operations.md b/.agent/rules/git-operations.md index 3624bc26..a2474589 100644 --- a/.agent/rules/git-operations.md +++ b/.agent/rules/git-operations.md @@ -110,30 +110,21 @@ Never skip hooks with `--no-verify` unless the user explicitly requests it. - Auto-modified files like `.DS_Store` or `uv.lock` should not be committed unless relevant. - When `skills-lock.json` or `symlinks.json` changes as a direct result of adding/modifying skills or plugins, commit them together with the changes. -### 8. Mandatory Pre-Branch Fetch & Pull Gate -Before executing `git worktree add` or `git checkout -b` for ANY feature or chore: -1. Switch to `main`: `git checkout main` -2. Fetch and pull latest remote: `git fetch origin main && git pull origin main` -3. Verify local matches remote: `git rev-parse HEAD` equals `git rev-parse origin/main`. -Branching from an un-pulled local state is strictly prohibited. - -### 9. Strict Working-Directory Confinement & Cross-Repo Protocol -All commands, tool executions, and file edits MUST remain strictly within the current repository tree (`InvestmentToolkit`). Never pass `-C ../`, never reference files outside the workspace root, and never inspect or touch parallel repositories (such as `agent-plugins-skills`) unless explicitly reviewed, approved, or authorized by the user. - -When cross-repository ecosystem work in `agent-plugins-skills` is authorized: -1. **Pre-Flight Baseline**: Run `git status --short` in target repo. If uncommitted changes exist, STOP immediately and consult user. -2. **Remote Synchronization**: Run `git checkout main && git fetch origin main && git pull origin main`. Verify `HEAD == origin/main`. -3. **Scope Approval & Worktree Isolation**: Confirm exact change approval, then create isolated worktree: `git worktree add -b .worktrees/ main`. -4. **Implement, Test & PR**: Execute strictly within worktree, run tests, commit, push, open PR. Never self-merge. -5. **Post-Merge Hygiene**: After user merges, `git fetch origin main`, verify ancestor (`git merge-base --is-ancestor`), fast-forward `main`, remove worktree (`git worktree remove --force`), delete local and remote feature branch, verify clean state (`git branch --list`, `git worktree list`). -6. **Downstream Resync**: In `InvestmentToolkit`, run `sync_with_inventory.py` and `plugin_add.py plugins/ -y` to propagate updates. - -### 10. Git Worktree Hard Invariants -- **Path Standard**: Always use `.worktrees/` inside repository root; never `/tmp/`, home directories, or arbitrary locations. -- **Main Checkout Cleanliness**: The main checkout remains untouched on `main` while a worktree is active. -- **Never Raw `rm -rf`**: Always remove worktrees with `git worktree remove --force .worktrees/`. Using raw `rm -rf` leaves stale administrative refs in `.git/worktrees/`. -- **Data Isolation**: Gitignored data files (e.g. `domain_model.sqlite`) do not carry over to worktrees; always verify final database writes landed on the main checkout. -- **Leak Verification**: Before opening a PR from a worktree, run `git status --short` on the main checkout to ensure no edits leaked outside the worktree. +### 10. Evolution Integrity Gate — update map-debt BEFORE committing core logic +Any commit that touches files under `plugins/`, `src/`, or `py_services/` **must** do one of the following before `git commit`: +- Stage an update to `references/map-debt.md` recording the debt entry (RESOLVED or OPEN) for the change, **OR** +- Stage an update to `references/evolution-log.md` if one exists, **OR** +- Include `Evolution-Check: none` in the commit message body with a one-line justification. + +**Failure mode this prevents:** committing core logic changes and only discovering the missing map-debt entry when CI fails on the PR — forcing a follow-up commit and a broken CI run. + +**Correct sequence:** +1. Make code changes +2. Update `references/map-debt.md` (add or resolve the relevant DEBT entry) +3. `git add references/map-debt.md` +4. `git commit` + +The CI gate (`Verify Evolution & Map Debt Compliance`) enforces this post-hoc. The rule enforces it pre-emptively. Both must be respected. ## Approval Required diff --git a/.agent/rules/graph-planning-superpowers-policy.md b/.agent/rules/graph-planning-superpowers-policy.md index 81852e02..af6ca04f 100644 --- a/.agent/rules/graph-planning-superpowers-policy.md +++ b/.agent/rules/graph-planning-superpowers-policy.md @@ -33,10 +33,7 @@ Phase 3: Deterministic Exit Gates & Asymmetric Persistence (6-State Vocabulary + ## 2. Phase 0: Pre-Planning Intake Bookend & Socratic Gate -### 2.1. Native Read-Only Plan Sandboxing -- Before generating code, you MUST enter host-native Plan Mode (Claude Code `/plan` / `Shift+Tab` or Copilot `@plan`). -- While in Plan Mode, filesystem mutations and write operations are **strictly prohibited**. Use only read-only search and AST analysis tools. -- The output must be written to an immutable spec/plan contract (e.g., `docs/plans/.md` or `~/.claude/plans/`). +Before Plan Mode can ever be entered, the task must be bounded: 1. **Read-Only Exploration Cycle:** - Execute read-only codebase discovery via `exploration-cycle-plugin` (`technical_diagnostic_engine.py`). @@ -56,17 +53,14 @@ Phase 3: Deterministic Exit Gates & Asymmetric Persistence (6-State Vocabulary + ## 3. Phase 1: Native Plan Mode & Adversarial Review -### 3.1. Worktree State Isolation & Graph Execution -- Execute implementation subagents strictly within dedicated `git worktree` branches (`../worktree-`). -- Subagents must not execute in shared or dirty working trees. -- High-assurance, multi-step tasks must execute as a deterministic Directed Acyclic Graph (DAG) state machine via [`agent-orchestration:graph-execution`](../plugins/agent-orchestration/skills/graph-execution/SKILL.md), enforcing Proposal Mode, Verifier Sovereignty, and Asymmetric Persistence. -- Delegation between director and worker agents follows the [`agent-orchestration:dual-loop`](../plugins/agent-orchestration/skills/dual-loop/SKILL.md) pattern (or [`agent-orchestration:co-pilot-loop`](../plugins/agent-orchestration/skills/co-pilot-loop/SKILL.md) for fast-tier models). - -### 3.2. Strict Red-Green-Refactor Enforcement -- Invoke `superpowers/test-driven-development` protocols: - 1. **Red:** Author concrete unit/integration test cases against the contract. Verify they FAIL. - 2. **Green:** Implement minimum functional code to make tests pass. - 3. **Refactor:** Clean up code while maintaining green test status. +1. **Native Plan Sandboxing:** + - Enforce host-native Plan Mode (Claude `/plan`, Copilot `@plan`, Antigravity plan mode) where available. Defer to Superpowers graph planning *only* when native host planning is absent or when executing complex multi-agent DAGs. + - While in Plan Mode, filesystem mutations outside plan artifacts are strictly prohibited. +2. **Pre-Execution Critic Review:** + - Run clean-context adversarial review via `critical-auditor` (max 2–3 rounds) probing failure domains and cross-plugin boundaries before human presentation. +3. **The Supreme Law Human Gate:** + - Present plan and require explicit user approval ("Proceed", "Go", "Execute"). + - On approval, transition task to `APPROVED` in `context/control_plane.db`. --- @@ -102,22 +96,7 @@ Phase 3: Deterministic Exit Gates & Asymmetric Persistence (6-State Vocabulary + ## 6. Git & Environment Invariants -- **NEVER** commit directly to `main`. **ALWAYS** use a feature branch. -- **NEVER** run `git push` without explicit, fresh approval. -- **NEVER** "auto-fix" via git operations. -- **HALT** immediately on any user "Stop/Wait" command. -- Write descriptive commit messages in the imperative mood. -- **NEVER** commit agent directories (`.agents/`, `.claude/`, `.gemini/`, `.codex/`) to version control. They contain session data and secrets. -- Any planning artifacts created inside an isolated git worktree will be deleted when the worktree is removed. Sync these to the main checkout directory before merging. - ---- - -## 7. Context Management - -- **Build context, then maintain it.** Do not redundantly re-read unchanged artifacts in a single session. -- **Never** use blind full-repo sweeps (`grep`, `find`, or `ls -R`); use targeted native `rg` / exact scoped file matches or structured directories. Zero background daemons required. - ---- -**Renamed**: 2026-08-27 (from `spec-driven-development-policy.md` — dropped "Spec-Kit" branding; this repo does not use the spec-kitty tool) -**Refactored**: 2026-08-27 — replaced with the three-phase Graph Planning, Superpowers, and Execution Discipline lifecycle (native Plan Mode sandboxing, context-bundler adversarial convergence capped at 2-3 rounds, worktree-isolated TDD, multi-stage verification) -**Ratified**: 2026-05-22 | **Replaces**: `constitution.md`, `AGENTS.md`, legacy `spec_driven_development_policy.md` +- **NEVER** commit directly to `main`. Always use isolated branches. +- **NEVER** run `git push` without explicit approval. +- **NEVER** commit transient agent directories (`.agents/`, `.claude/`, `.gemini/`, `.codex/`). +- UTF-8 encoding only. No smart quotes or non-ASCII characters in manifests and rules. diff --git a/.agent/rules/local-worktree-and-dual-repo-edit-protocol.md b/.agent/rules/local-worktree-and-dual-repo-edit-protocol.md new file mode 100644 index 00000000..e0487c63 --- /dev/null +++ b/.agent/rules/local-worktree-and-dual-repo-edit-protocol.md @@ -0,0 +1,153 @@ +--- +description: Mandatory end-to-end protocol and checklist for authoring edits, worktrees, commits, PRs, user merge, branch cleanup, cross-repo plugin sync, and post-sync health checks. +globs: ["**/*"] +--- + +# Dual-Repo & Worktree Edit Lifecycle Protocol + +## Purpose +This rule formalizes the end-to-end execution protocol when modifying plugins, skills, or platform code—whether upstream in `agent-plugins-skills` or downstream in consumer repositories like `InvestmentToolkit`. + +It eliminates conversational friction and guessing by establishing an explicit, deterministic checklist: from branch creation to PR review, user merge, branch deletion, two-repo plugin reinstall, and final health check verification. + +--- + +## The End-to-End Lifecycle Protocol + +```mermaid +flowchart TD + A[Phase 0: Socratic Intake & Spec] --> B[Phase 1: Worktree / Feature Branch] + B --> C[Phase 2: TDD / Implementation] + C --> D[Phase 3: Pre-Push Quality Gates] + D --> E[Phase 4: Commit & Push to Feature Branch] + E --> F[Phase 5: Open PR & Notify User] + F --> G[Phase 6: User Merges PR on GitHub] + G --> H[Phase 7: Fetch & Fast-Forward Local Main] + H --> I[Phase 8: Branch & Worktree Cleanup] + I --> J[Phase 9: Dual-Repo Reinstall & Resync] + J --> K[Phase 10: Mandatory Post-Sync Health Check] +``` + +--- + +## 10-Phase Lifecycle Checklist + +### Phase 0: Intake, Control Plane & Planning Gate +- [ ] Task registered in `context/control_plane.db` (`python3 scripts/agent_control.py init` or kernel event). +- [ ] Read-only discovery conducted; 1–3 Socratic scoping questions presented with `[Recommended]` answers. +- [ ] Implementation plan approved by the user before creating branches or modifying code. + +### Phase 1: Worktree / Branch Creation +- [ ] In downstream repo (`InvestmentToolkit`), use a git worktree: + ```bash + git worktree add -b feat/ ../InvestmentToolkit- main + ``` +- [ ] In upstream repo (`agent-plugins-skills`), checkout a dedicated feature branch: + ```bash + git checkout -b feat/ + ``` +- [ ] Ensure gitignored files / dependencies required for tests are initialized or linked. + +### Phase 2: TDD & Implementation +- [ ] Follow Test-Driven Development (failing test or verification contract first). +- [ ] Implement required changes; refactor at 50+ lines or 3+ nesting levels. +- [ ] Adhere to coding conventions and standard file headers. + +### Phase 3: Pre-Push Quality & Regression Gates +- [ ] Run test suite: + - Upstream (`agent-plugins-skills`): `pytest plugins/agent-agentic-os/tests/` + - Downstream (`InvestmentToolkit`): `python3 run_tests.py` +- [ ] Run compliance & convention audits: + ```bash + python3 plugins/dev-utils/scripts/workspace_conventions_auditor.py # if present + python3 .agents/skills/symlink-manager/scripts/symlink_manager.py diagnose + ``` +- [ ] Confirm clean working state without stray diffs (`git status --short`). + +### Phase 4: Commit & Push +- [ ] Stage required files explicitly (`git add `). +- [ ] Commit with conventional commit message (`feat(...)`, `fix(...)`, `refactor(...)`). +- [ ] Push directly to remote feature branch: + ```bash + git push -u origin feat/ + ``` + +### Phase 5: Open PR & Hand Off to User (DO NOT AUTO-MERGE) +- [ ] Open Pull Request via GitHub CLI: + ```bash + gh pr create --repo --title "feat: ..." --body "## Summary..." + ``` +- [ ] Report PR link and state to user ("Pushed to origin, PR link below, awaiting user merge"). +- [ ] **STOP AND WAIT**: The user MUST review and merge the PR on GitHub. Never merge the PR autonomously. + +### Phase 6: User Merge Signal +- [ ] The user reviews and merges the PR on GitHub, then informs the agent ("merged", "PR merged", etc.). + +### Phase 7: Fetch & Fast-Forward Local Main +- [ ] Switch to root repository on `main`: + ```bash + git checkout main + git fetch origin + git pull origin main + ``` +- [ ] Verify the merge commit is an ancestor of `main`: + ```bash + git merge-base --is-ancestor main + ``` + +### Phase 8: Branch & Worktree Cleanup (Mandatory Loop Closure) +- [ ] In downstream repo (`InvestmentToolkit`), remove the merged worktree: + ```bash + git worktree remove ../InvestmentToolkit- + ``` +- [ ] Delete local feature branch: + ```bash + git branch -d feat/ + ``` +- [ ] Delete remote feature branch: + ```bash + git push origin --delete feat/ + ``` +- [ ] Confirm clean worktree list and branch list: + ```bash + git worktree list + git branch --list + ``` + +### Phase 9: Dual-Repo Reinstall & Resync +- [ ] **Step 9A: Upstream (`agent-plugins-skills`)**: + - Re-run OS initialization/retrofit: + ```bash + python3 plugins/agent-agentic-os/scripts/init_agentic_os.py --target . --retrofit + ``` + - Reinstall universal plugin copies: + ```bash + python3 plugins/plugin-manager/scripts/plugin_add.py --all -y + ``` +- [ ] **Step 9B: Downstream (`InvestmentToolkit`)**: + - Resync plugins from inventory: + ```bash + python3 .agents/skills/plugin-syncer/scripts/sync_with_inventory.py + ``` + - Re-run OS initialization/retrofit to align instruction mirrors (`CLAUDE.md`, `GEMINI.md`, `AGENTS.md`) and rules: + ```bash + python3 .agents/skills/os-init/scripts/init_agentic_os.py --target . --retrofit + ``` + +### Phase 10: Mandatory Post-Sync Health Check +- [ ] Deterministically verify all OS substrates are active: + ```bash + test -f context/control_plane.db && echo "OK control_plane.db" || echo "MISSING control_plane.db" + test -f .claude/hooks/hooks.json && echo "OK hooks.json" || echo "MISSING hooks.json" + test -f .git/hooks/pre-commit-evolution-guard && echo "OK pre-commit-guard" || echo "MISSING pre-commit-guard" + test -f .github/workflows/verify-evolution-integrity.yml && echo "OK verify-evolution-integrity.yml" || echo "MISSING verify-evolution-integrity.yml" + ``` +- [ ] Run canonical tests in downstream repo: + ```bash + python3 run_tests.py + ``` +- [ ] Verify symlink integrity: + ```bash + python3 .agents/skills/symlink-manager/scripts/symlink_manager.py diagnose + ``` +- [ ] Present final health check summary to user. diff --git a/.agent/rules/self-evolution-policy.md b/.agent/rules/self-evolution-policy.md index 0eea4a46..941c439d 100644 --- a/.agent/rules/self-evolution-policy.md +++ b/.agent/rules/self-evolution-policy.md @@ -40,22 +40,8 @@ Before triggering an autonomous self-evolution cycle, all 4 criteria must be sat ### Proposal Mode & Verifier Sovereignty Invariants -1. **Verify Boundaries First**: Escalate immediately if repairs require modifying files outside permitted boundaries. -2. **Three-Attempt Maximum**: Max 3 attempts per failure. If 3rd fails, stop and present formal Escalation Template. -3. **Update The Map, Not Just the Diary**: Every fix must update domain playbooks/rules (`wiki/` or `references/`). Log a `Status: RESOLVED` entry in `map-debt.md` for every Tier 0-3 friction event even when patched immediately. Dual-log to `references/evolution-log.md`. -4. **Autonomy Gates**: Auto-approve: new functions/selectors. Gated: file renames/moves. **Hard Gated (Human Permission Required)**: deletions of any file, function, rule, or skill. -5. **Absorption Fallacy**: Never delete a file/skill assuming it is 'redundant' or 'consolidated'. -6. **One Fix at a Time**: Apply one clean logical fix per execution pass. -7. **Fix Forward**: Never skip failures, add blind retries, or leave workarounds unaddressed. -8. **Sync Templates & Generators**: Update templates/generators immediately when core rules, schemas, or strategies change. -9. **Refine Prompt Templates**: Evaluate external model outputs and update prompt templates to guard against observed gaps. -10. **Sync Manifests on Decommission**: Remove entries from `symlinks.json` and reinstall via `plugin_add.py`. -11. **Pre-Deletion Git Check**: Always run `git log --follow -- ` before proposing deletions. -12. **Hub First, Spoke Second**: New skill assets must land in plugin root and symlink into skill folders via `symlink_manager.py`. -13. **Asymmetric Worktree Transfer**: Export Layer 2 failure insights to main checkout before tearing down failed worktrees. -14. **Integrity Receipts**: Autonomous evolution commits require `EVO-INTEGRITY--`. -15. **Single Source of Truth**: Verify live state against canonical DB/ledger before classifying entity status (e.g. holding vs watchlist). -16. **In-Situ Evolution (Flywheel)**: Resolve friction at shared tool/skill layer immediately during normal user tasks. +- **Proposal Mode:** During Stage 1 (`PLAN`), workspace files and configs are strictly read-only. No repo files modified or branches/worktrees spawned until explicit human authorization (`evolution_state.py authorize`). +- **Verifier Sovereignty:** Mutation subject cannot modify the acceptance gate. Immutable base protection set (`evaluate.py`, `eval_runner.py`, tests, holdout sets, baselines, policies) and declared verifiers cannot be targeted for mutation. Pre-execution SHA256 hashes are locked; modifications abort cycle with exit code 2. Verifier command must run directly in isolated worktree. --- @@ -97,8 +83,7 @@ A self-evolution event is required when a script/eval/tool fails, an existing ca ### Pre-Completion Self-Evolution Gate -> [!IMPORTANT] -> **Turn-by-Turn Mandatory Protocol**: On EVERY turn modifying code, running tests, or presenting findings, the agent MUST proactively output this block verbatim before yielding control: +Before claiming a task is complete, output this block verbatim: ``` PRE-COMPLETION GATE: diff --git a/.agent/rules/test-driven-development.md b/.agent/rules/test-driven-development.md index 5f941109..c09372d9 100644 --- a/.agent/rules/test-driven-development.md +++ b/.agent/rules/test-driven-development.md @@ -45,10 +45,7 @@ It does NOT apply to: 1. **For Code**: Write a failing unit or integration test first. 2. **For Orchestration**: Write a mock evaluation scenario, an assertions list, or an expected output schema validator first. -3. **Skill Tooling**: If the workspace contains a custom test-driven development skill or test runner (such as `superpowers:test-driven-development`), invoke it: - ``` - Skill: superpowers:test-driven-development (if available) - ``` +3. **Skill / Test Tooling**: If the workspace contains a test runner or TDD skill, invoke it before touching code. This enforces the Red-Green-Refactor cycle and blocks the rationalization patterns ("too simple to test", "I'll do it after") that lead to broken systems. If you start the work before writing the contract, it is invalid. Delete it and start over. @@ -212,9 +209,6 @@ For coordinator scripts, workflow engines, master orchestrators, agent prompts, ## Related Rules and References -- `/.agent/rules/no-inline-python.md` (or local script extraction policy) — extraction policy for scripts -- `/.agent/rules/coding-conventions.md` (or local style guides) — coding conventions and documentation standards -- `/docs/architecture/` (or project design docs) — system architecture details and design specifications +- `.agent/rules/coding-conventions.md` — coding conventions and documentation standards - `superpowers:test-driven-development` skill (if available) — invoke BEFORE writing any implementation -- `graph-planning-superpowers-policy.md` §3.2 (Phase 2: Strict Red-Green-Refactor Enforcement) — this Iron Law - is the concrete implementation of that phase; the two are the same requirement, not competing rules \ No newline at end of file +- `graph-planning-superpowers-policy.md` — test-driven execution and verification discipline \ No newline at end of file diff --git a/.agent/rules/worktree-lifecycle-management.md b/.agent/rules/worktree-lifecycle-management.md index c16c2d05..6c77ae0d 100644 --- a/.agent/rules/worktree-lifecycle-management.md +++ b/.agent/rules/worktree-lifecycle-management.md @@ -7,31 +7,7 @@ globs: ["**/*"] ## The Problem This Rule Solves -**2026-08-18 incident:** a session created two worktrees to execute SharePoint plugin -work, and repeatedly reported progress as "done"/"merged"/"pushed" without distinguishing -which of five genuinely different states a change was actually in. This caused the user to -ask "where are the CRUD scripts" and "is the worktree gone" many times over, each time -receiving an answer that was locally true but did not match what the user could actually -see on their own disk. Concretely: - -1. A subagent-driven-development round finished, the branch was pushed, and the session - reported "final review complete" without stating that nothing was merged yet. -2. A second worktree's work (file moves + new scripts) sat fully uncommitted for many - turns while the session narrated architecture debates instead of stating the plain - fact: "nothing is saved anywhere except the worktree's working directory." -3. After the user merged a PR on GitHub, the session ran `git fetch origin main:main` - (updating the **local branch ref**) and reported the plugin as present -- without - checking that the user's actual working directory was checked out on a **different - branch**, so the files were invisible on disk. The user had to ask "i don't see it are - you sure?" before this was caught. -4. Within one of the worktrees, symlinks were created with raw `ln -s` and a hand-edited - `symlinks.json` instead of this repo's mandated `.agents/skills/symlink-manager/ - scripts/symlink_manager.py` (per `.agent/rules/symlink-cross-platform.md`), discovered - only when the user separately flagged it. - -None of these were lies -- each statement was true in isolation. The failure was treating -"local worktree state", "committed", "pushed to origin", "merged on GitHub", "local branch -ref updated", and "checked out on disk" as one undifferentiated bucket called "done". +Worktree-related changes frequently suffer from ambiguity when multiple git states (uncommitted local work, committed on a branch, pushed to remote, merged to main, local ref updated, and checked out on disk) are collapsed into the vague word "done". This leads to confusion about where files actually reside and whether PRs or branches are safely integrated. ## The Law @@ -77,9 +53,8 @@ ref updated", and "checked out on disk" as one undifferentiated bucket called "d Updating a local branch ref is not the same as changing the working directory. If the current checkout is on a different branch than the one just updated, say so before the user has to ask why they can't see anything. -4. **State exact absolute paths for every file/plugin/worktree you reference.** "It's in - the new plugin" is not an answer; `C:\...\plugins\sharepoint-provisioning-execution\ - scripts\spo-update-list.ps1` is. +4. **State exact full paths for every file/plugin/worktree you reference.** "It's in + the new plugin" is not an answer; state the exact path (e.g. `/full/path/to/plugins//scripts/script.py`). 5. **Before deleting any worktree, verify state 4 (merged into origin/main) first**, via `git fetch` + `git log origin/main`, not by assuming a prior push means the PR was merged. Only after that verification, delete via the native worktree-removal tool (or @@ -97,12 +72,6 @@ ref updated", and "checked out on disk" as one undifferentiated bucket called "d ## Where This Applies -- Every `superpowers:using-git-worktrees` / `EnterWorktree` session in this repo. -- Every report to the user about progress on worktree-based work, from creation through - final deletion. -- Applies in addition to, not instead of, - `.agent/rules/worktree-subagent-leak-detection.md` (renamed 2026-08-18, formerly - `worktree-subagent-isolation.md`) — that file covers a narrower, different failure mode - (a dispatched subagent's writes leaking into the wrong checkout); this file covers the - full lifecycle around the worktree itself. Both apply simultaneously in any - subagent-driven-development session run inside a worktree. +- Every worktree session in the repository. +- Every report to the user about progress on worktree-based work, from creation through final deletion. +- Applies in addition to, not instead of, `worktree-subagent-leak-detection.md` (which covers subagents writing outside assigned worktrees). Both apply simultaneously in any subagent session run inside a worktree. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9924a77d..8ae9fb78 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,4 +1,4 @@ -# Copilot Instructions for InvestmentToolkit +# Copilot Instructions for CLAUDE.md — InvestmentToolkit > Authoritative repository instructions for GitHub Copilot. Mirrors CLAUDE.md. @@ -2002,3 +2002,20 @@ Zero `? regular file` or `✗ broken symlink` entries must remain before committ Read the full skill before any symlink work: `.agents/skills/symlink-manager/SKILL.md` + + +## Phase 0 Intake & Socratic Gate (Mandatory) +> Every non-trivial engineering task, feature request, or architectural refactor MUST trigger `interview-spec` first. +- Register the task in `context/control_plane.db` via `python3 scripts/agent_control.py init`. +- Enforce host-native Plan Mode (strictly read-only discovery). +- Present 1–3 Socratic questions with explicit `[Recommended]` defaults to align on scope. +- Compile the immutable 4-Pillar Specification (`TASK_SPEC.md`). +- Obtain explicit human authorization ("Proceed", "Go", or "Execute") before creating a worktree or modifying code. + + +## Plugin & Skill Maintenance Policy +- Check `context/plugin-config.json` for this repository's configured contribution mode: + 1. `fork-and-pr`: Test fix locally, commit to feature branch in cloned upstream repo, and submit PR to `richfrem/agent-plugins-skills`. + 2. `local-patch-and-issue`: Apply immediate fix directly in `.agents/skills/` and log an issue in `richfrem/agent-plugins-skills` with reproduction details. + 3. `domain-override`: Keep upstream shared skills unmodified; put project customizations in `.agent/rules/local-*` or local `plugins/`. +- Never make silent undocumented edits to shared skills without either opening an upstream PR or logging an issue. diff --git a/AGENTS.md b/AGENTS.md index 4a37aa75..5a1db309 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,5 @@ # AGENTS.md - ## Overview High-end investment analysis suite: React 19 dashboard (port 5173), Node.js/Express backend (port 3001), Python yfinance bridge, TradingView CDP automation. @@ -2001,3 +2000,20 @@ Zero `? regular file` or `✗ broken symlink` entries must remain before committ Read the full skill before any symlink work: `.agents/skills/symlink-manager/SKILL.md` + + +## Phase 0 Intake & Socratic Gate (Mandatory) +> Every non-trivial engineering task, feature request, or architectural refactor MUST trigger `interview-spec` first. +- Register the task in `context/control_plane.db` via `python3 scripts/agent_control.py init`. +- Enforce host-native Plan Mode (strictly read-only discovery). +- Present 1–3 Socratic questions with explicit `[Recommended]` defaults to align on scope. +- Compile the immutable 4-Pillar Specification (`TASK_SPEC.md`). +- Obtain explicit human authorization ("Proceed", "Go", or "Execute") before creating a worktree or modifying code. + + +## Plugin & Skill Maintenance Policy +- Check `context/plugin-config.json` for this repository's configured contribution mode: + 1. `fork-and-pr`: Test fix locally, commit to feature branch in cloned upstream repo, and submit PR to `richfrem/agent-plugins-skills`. + 2. `local-patch-and-issue`: Apply immediate fix directly in `.agents/skills/` and log an issue in `richfrem/agent-plugins-skills` with reproduction details. + 3. `domain-override`: Keep upstream shared skills unmodified; put project customizations in `.agent/rules/local-*` or local `plugins/`. +- Never make silent undocumented edits to shared skills without either opening an upstream PR or logging an issue. diff --git a/CLAUDE.md b/CLAUDE.md index 9036af9c..2e849dfd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2001,3 +2001,20 @@ Zero `? regular file` or `✗ broken symlink` entries must remain before committ Read the full skill before any symlink work: `.agents/skills/symlink-manager/SKILL.md` + + +## Phase 0 Intake & Socratic Gate (Mandatory) +> Every non-trivial engineering task, feature request, or architectural refactor MUST trigger `interview-spec` first. +- Register the task in `context/control_plane.db` via `python3 scripts/agent_control.py init`. +- Enforce host-native Plan Mode (strictly read-only discovery). +- Present 1–3 Socratic questions with explicit `[Recommended]` defaults to align on scope. +- Compile the immutable 4-Pillar Specification (`TASK_SPEC.md`). +- Obtain explicit human authorization ("Proceed", "Go", or "Execute") before creating a worktree or modifying code. + + +## Plugin & Skill Maintenance Policy +- Check `context/plugin-config.json` for this repository's configured contribution mode: + 1. `fork-and-pr`: Test fix locally, commit to feature branch in cloned upstream repo, and submit PR to `richfrem/agent-plugins-skills`. + 2. `local-patch-and-issue`: Apply immediate fix directly in `.agents/skills/` and log an issue in `richfrem/agent-plugins-skills` with reproduction details. + 3. `domain-override`: Keep upstream shared skills unmodified; put project customizations in `.agent/rules/local-*` or local `plugins/`. +- Never make silent undocumented edits to shared skills without either opening an upstream PR or logging an issue. diff --git a/GEMINI.md b/GEMINI.md index 89714dc2..583d7a58 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -1,6 +1,5 @@ # GEMINI.md - ## Overview High-end investment analysis suite: React 19 dashboard (port 5173), Node.js/Express backend (port 3001), Python yfinance bridge, TradingView CDP automation. @@ -2001,6 +2000,24 @@ Zero `? regular file` or `✗ broken symlink` entries must remain before committ Read the full skill before any symlink work: `.agents/skills/symlink-manager/SKILL.md` + + +## Phase 0 Intake & Socratic Gate (Mandatory) +> Every non-trivial engineering task, feature request, or architectural refactor MUST trigger `interview-spec` first. +- Register the task in `context/control_plane.db` via `python3 scripts/agent_control.py init`. +- Enforce host-native Plan Mode (strictly read-only discovery). +- Present 1–3 Socratic questions with explicit `[Recommended]` defaults to align on scope. +- Compile the immutable 4-Pillar Specification (`TASK_SPEC.md`). +- Obtain explicit human authorization ("Proceed", "Go", or "Execute") before creating a worktree or modifying code. + + +## Plugin & Skill Maintenance Policy +- Check `context/plugin-config.json` for this repository's configured contribution mode: + 1. `fork-and-pr`: Test fix locally, commit to feature branch in cloned upstream repo, and submit PR to `richfrem/agent-plugins-skills`. + 2. `local-patch-and-issue`: Apply immediate fix directly in `.agents/skills/` and log an issue in `richfrem/agent-plugins-skills` with reproduction details. + 3. `domain-override`: Keep upstream shared skills unmodified; put project customizations in `.agent/rules/local-*` or local `plugins/`. +- Never make silent undocumented edits to shared skills without either opening an upstream PR or logging an issue. + ## Gemini CLI Tool Mapping | Claude Code Tool | Gemini CLI Equivalent | |---|---| diff --git a/INIT_AGENTS.md b/INIT_AGENTS.md new file mode 100644 index 00000000..348c01a4 --- /dev/null +++ b/INIT_AGENTS.md @@ -0,0 +1,111 @@ +# Agent Onboarding & Environment Initialization Guide (`INIT_AGENTS.md`) + +Welcome to **InvestmentToolkit**. This guide is designed for both human engineers and AI coding assistants (Claude Code, Gemini CLI, Cursor, Antigravity, Copilot) when dropping into a fresh repository clone. + +Follow this sequential protocol to configure your **Agentic OS Substrate**, align your **Plugin Contribution Policy**, and execute the **Master Onboarding Coordinator**. + +--- + +## ⚡ Quickstart: One Prompt Bootstrap + +If working with an AI assistant in chat, paste this directive: + +```text +Please read INIT_AGENTS.md, run the initial substrate setup, ask me which plugin contribution mode I prefer (fork-and-pr, local-patch-and-issue, or domain-override), and then execute /toolkit-onboarding. +``` + +--- + +## Phase 1: Interactive Agentic OS & Dependency Alignment + +InvestmentToolkit relies on shared ecosystem skills and plugins (from `agent-plugins-skills`) alongside domain-specific investment tools. + +### 1. Choose Your Plugin Maintenance & Contribution Mode + +When an agent encounters a bug, deprecated selector, or friction in an upstream skill during daily operations, how should it handle changes? + +| Mode | Identifier | When to Choose | Agent Workflow | +| :--- | :--- | :--- | :--- | +| **Fork & PR** *(Recommended)* | `fork-and-pr` | You want to contribute improvements back to the ecosystem or maintain an active fork. | Clones/links `agent-plugins-skills`. Edits are made in a worktree, validated with `pytest`, and pushed as a Pull Request upstream. | +| **Local Patch & Issue** | `local-patch-and-issue` | You want rapid local resolution without maintaining a full git clone of the plugin repo. | Patches installed files directly in `.agents/skills/`. Generates an issue reproduction report to submit to upstream maintainers. | +| **Domain Override** | `domain-override` | Strict production consumer. Upstream plugins remain 100% vanilla. | Never alters upstream skills. Overrides logic using `.agent/rules/local-*` or dedicated `plugins/` in this repository. | + +### 2. Download / Clone Upstream Dependency (If using `fork-and-pr`) + +If opting for **`fork-and-pr`**, clone the upstream plugin source adjacent to this repository or into your development directory: + +```bash +# Clone adjacent to InvestmentToolkit (recommended structure) +cd .. +git clone https://github.com/richfrem/agent-plugins-skills.git +cd agent-plugins-skills +# Verify upstream status +python3 run_tests.py +cd ../InvestmentToolkit +``` + +### 3. Run Agentic OS Initialization & Retrofit + +Run the initialization script targeting this workspace. This scaffolds `.claude/hooks`, Git evolution guards, control plane SQLite DB, and configures `context/plugin-config.json`: + +```bash +# From InvestmentToolkit repository root: +python3 .agents/skills/os-init/scripts/init_agentic_os.py \ + --target . \ + --retrofit \ + --contribution-mode fork-and-pr +``` +*(Replace `fork-and-pr` with `local-patch-and-issue` or `domain-override` based on your choice).* + +> [!IMPORTANT] +> **Preserving Domain Rules & Handling `.bak` Files**: +> `init_agentic_os.py` creates `.bak` files when updating existing guidelines (`CLAUDE.md`, `GEMINI.md`, `AGENTS.md`). +> **Agents MUST NOT blindly delete `.bak` files.** First review the diffs (`git diff`), reconcile any custom domain rules, and only remove `.bak` files once domain integrity is verified. + +--- + +## Phase 2: Core Substrate Health Check + +Confirm that the local agentic runtime substrate is operational: + +```bash +# 1. Control plane and hooks +test -f context/control_plane.db && echo "✅ control_plane.db active" || echo "❌ Missing control_plane.db" +test -f .claude/hooks/hooks.json && echo "✅ Claude hooks active" || echo "❌ Missing hooks.json" + +# 2. Symlink integrity +python3 .agents/skills/symlink-manager/scripts/symlink_manager.py diagnose + +# 3. Comprehensive Agentic OS audit +python3 -c " +# Trigger os-health-check or run substrate audit +import subprocess +subprocess.run(['python3', 'run_tests.py', '-m', 'not slow']) +" +``` + +--- + +## Phase 3: Launch Master Toolkit Onboarding (`/toolkit-onboarding`) + +Once the Agentic OS substrate is confirmed, trigger the master investment coordinator: + +```text +/toolkit-onboarding +``` + +The master wizard interactively guides you through: +1. **Engine Compilation**: Node.js dependencies, Python virtualenv, and TradingView CDP engine (`tradingview-cdp/`). +2. **Private Data Initialization**: Automatically creates `cash_flows.json` and `portfolio-config.json` from `.example` templates. +3. **Strategy Pillars & Accounts**: Configures account architecture (e.g. TFSA Primary + RRSP Mirror) and allocates target weights (Power, Compute, Data Infra, Cash). +4. **Broker / TradingView Sync**: Connects to TradingView Desktop (CDP port 9222) to ingest real-time positions, shares, and cash balances into `domain_model.sqlite`. +5. **DCF Valuation Baselines**: Generates institutional 5-year multi-scenario DCF baselines across your holdings. +6. **Live Chart Sync & Dashboard Launch**: Injects dynamic Fair Value / Entry overlays onto TradingView charts and boots the React/Express suite on port 5173 / 3001. + +--- + +## Phase 4: Routine Maintenance & Dual-Repo Protocol + +When editing code across repositories: +- **Strict Worktree Discipline**: Always work in a dedicated git worktree (`.agent/rules/local-worktree-and-dual-repo-edit-protocol.md`). +- **Pre-Completion Gate**: Before concluding any agent turn, run `python3 run_tests.py` and inspect `.agent/rules/test-driven-development.md`. diff --git a/README.md b/README.md index 66fb304e..3cd1356f 100644 --- a/README.md +++ b/README.md @@ -41,11 +41,15 @@ An institutional-grade portfolio management and automated research suite built n ## 🚀 First Things First: Getting Started with Agents -The true power of this repository is not just the frontend UI—it is the **Agentic Operating System** behind it. +The true power of this repository is not just the frontend UI—it is the **Agentic Operating System** behind it. + +> [!TIP] +> ### 📖 Fresh Clone Setup Guide +> For a detailed walkthrough on initializing the Agentic OS substrate, choosing your plugin contribution policy, and handling upstream dependencies, consult [`INIT_AGENTS.md`](INIT_AGENTS.md). ### 💬 Just Cloned the Repo? Paste This Prompt to Your AI Agent: -> **"Please run `/toolkit-onboarding` to bootstrap my investment environment from scratch, initialize my accounts, and guide me through connecting TradingView and setting up my portfolio."** +> **"Please read INIT_AGENTS.md and run `/toolkit-onboarding` to bootstrap my investment environment, align plugin contribution preferences, initialize accounts, and connect TradingView."** --- diff --git a/plugins/toolkit-manager/skills/toolkit-onboarding/SKILL.md b/plugins/toolkit-manager/skills/toolkit-onboarding/SKILL.md index 378adf96..28e07200 100644 --- a/plugins/toolkit-manager/skills/toolkit-onboarding/SKILL.md +++ b/plugins/toolkit-manager/skills/toolkit-onboarding/SKILL.md @@ -20,11 +20,40 @@ allowed-tools: Bash, Read, Write This master coordinator takes an investor from a clean repository clone directly to an institutional-grade, fully operating investment operating system: ``` -[1. Pre-Flight Engine Check] ➔ [2. Accounts & Strategy Pillars] ➔ [3. Broker/TV Ingestion] ➔ [4. Automated DCF Baseline] ➔ [5. Live Chart Overlay & Launch] +[0. Agentic OS & Contribution Mode] ➔ [1. Pre-Flight Engine Check] ➔ [2. Accounts & Strategy Pillars] ➔ [3. Broker/TV Ingestion] ➔ [4. Automated DCF Baseline] ➔ [5. Live Chart Overlay & Launch] ``` --- +## 🛠️ Step 0 — Agentic OS Foundation & Plugin Contribution Setup + +Before setting up investment pipelines, establish the repository's Agentic OS substrate and align plugin contribution preferences: + +1. **Interactive Plugin Contribution Choice**: + Ask the user / guide the agent on how they prefer to handle bug fixes and updates to shared skills: + - **Option A [Recommended] (Fork & PR / `fork-and-pr`)**: + Clone or link `richfrem/agent-plugins-skills`. When an agent fixes an issue in an installed skill, test with `pytest`, commit to a branch, and open an upstream PR. + - **Option B (Local Patch & Issue / `local-patch-and-issue`)**: + Apply hotfixes directly to `.agents/skills/` and log an issue upstream with reproduction details. + - **Option C (Domain Overrides / `domain-override`)**: + Keep upstream plugins vanilla; house all repo-specific customizations in `.agent/rules/local-*` or `plugins/`. + +2. **Run OS Initialization & Retrofit**: + ```bash + python3 .agents/skills/os-init/scripts/init_agentic_os.py --target . --retrofit --contribution-mode + ``` + +3. **Mandatory Post-Init OS Substrate Health Check**: + Deterministically verify core substrates are active before proceeding: + ```bash + test -f context/control_plane.db && echo "OK control_plane.db" || echo "MISSING control_plane.db" + test -f .claude/hooks/hooks.json && echo "OK hooks.json" || echo "MISSING hooks.json" + test -f .git/hooks/pre-commit-evolution-guard && echo "OK pre-commit-guard" || echo "MISSING pre-commit-guard" + test -f .github/workflows/verify-evolution-integrity.yml && echo "OK verify-evolution-integrity.yml" || echo "MISSING verify-evolution-integrity.yml" + ``` + +--- + ## 🛠️ Step 1 — Zero-Config Engine & Plugin Installation 1. **Verify Runtime Prerequisites**: @@ -55,6 +84,11 @@ This master coordinator takes an investor from a clean repository clone directly print(f'Initialized: {f}') " ``` +5. **Verify Symlinks & System Baseline**: + ```bash + python3 .agents/skills/symlink-manager/scripts/symlink_manager.py diagnose + python3 run_tests.py + ``` --- diff --git a/references/map-debt.md b/references/map-debt.md index fb3051ed..8f862f12 100644 --- a/references/map-debt.md +++ b/references/map-debt.md @@ -21,3 +21,4 @@ Persistent tracking of architectural friction, structural anomalies, and unclose | DEBT-20260903-03 | Stale references to legacy skill names evaluate-stock / perform-stock-valuation across plugins | RESOLVED | Tier 0 | 1 | 2026-09-03 | 28 markdown/python/JSON files still contained legacy references to /evaluate-stock and perform-stock-valuation instead of the canonical update-stock-analysis. | Performed repository-wide global replacement across plugins/ to update all references to update-stock-analysis. | | DEBT-20260903-04 | Single-model news sweep blind spots on GAAP accounting, debt leverage, and M&A dilution | RESOLVED | Tier 1 | 1 | 2026-09-03 | Relying solely on Grok for news sweeps created narrative bias (e.g. overemphasizing CoreWeave $104B backlog while overlooking $35B debt/-$5.7B FCF, or accepting Riot AI leases without checking $90k/BTC all-in mining depreciation). | Upgraded `/pre-trade-analysis` and `/x-news-sweep` (Gate 9) to mandate Triangulated Multi-Model Verification: pairing Grok (breaking news/X sentiment) with ChatGPT/Claude (10-Q/SEC forensic accounting, debt burn, and GAAP vs non-GAAP reconciliation). | | DEBT-20260903-05 | Cross-repo contamination, unpulled branching, and dangerous unapproved actions | RESOLVED | Tier 0 | 1 | 2026-09-03 | Agent breached repository boundaries by attempting to push investment skills into the separate agent-plugins-skills repository, branched off an unpulled local state, and executed unapproved destructive branch deletions. | Added Rule 22 and Pitfall 31 to AGENTS.md/GEMINI.md; added Rules 8 and 9 to git-operations.md enforcing strict Single-Repo Confinement, mandatory pre-branch pull gates, and absolute prior authorization before state-changing actions. | +| DEBT-20260906-02 | Unaligned fresh clone setup and lack of interactive plugin contribution guidance in consuming repo | RESOLVED | Tier 1 | 1 | 2026-09-06 | Consuming repository lacked INIT_AGENTS.md onboarding documentation, and toolkit-onboarding did not guide agents through choosing their plugin contribution mode (fork-and-pr vs local-patch-and-issue vs domain-override) or running OS substrate health checks before setting up accounts and financial baselines. | Created INIT_AGENTS.md guide; updated README.md with onboarding link; upgraded toolkit-onboarding SKILL.md Step 0 with interactive contribution mode selection and Phase 3.5 OS substrate health checks. |