From 65beb1dbebef7628217c4078063445c5304179be Mon Sep 17 00:00:00 2001 From: jtaroreh Date: Sun, 22 Nov 2026 14:43:30 -0800 Subject: [PATCH] Feat(skills): merge upstream workflow rigor across seven shared skills Port upstream pstack improvements into skills/correct, skills/typescript-best-practices, skills/arena, skills/ketchup, skills/cloud-swarm, and skills/poteto-mode/references/antigravity-tools.md while keeping Antigravity runtime invariants, Brain Artifacts, reactive subagent coordination, and Cloud Run GCS patch harvesting intact. --- skills/arena/SKILL.md | 45 ++++++----- skills/cloud-swarm/SKILL.md | 12 ++- skills/correct/SKILL.md | 56 ++++++++------ skills/ketchup/SKILL.md | 74 +++++++++---------- .../references/antigravity-tools.md | 9 ++- skills/typescript-best-practices/SKILL.md | 5 +- .../references/patterns.md | 62 ++++++++++++---- 7 files changed, 162 insertions(+), 101 deletions(-) diff --git a/skills/arena/SKILL.md b/skills/arena/SKILL.md index f71c68a..8bc1d12 100644 --- a/skills/arena/SKILL.md +++ b/skills/arena/SKILL.md @@ -19,45 +19,56 @@ Open a todolist tracking the operational phases: ## Phase A: Frame -1. **Artifact.** Define the target output each candidate must produce. -2. **Rubric.** Formulate 3-6 concrete, gradeable criteria (e.g. `Adds a --dry-run flag that skips writes`). -3. **Runners.** Use `arena runners` from `~/.gemini/config/plugins/agystack/agystack-models.md` if configured, or default across available tiers: `pro`, `flash`, `inherit`. +Every candidate receives the same prompt, so the prompt is the contract. + +1. **Artifact.** Define the target output each candidate produces. +2. **Rubric.** Formulate 3 to 6 concrete, gradeable criteria for this task, such as `Adds a --dry-run flag that skips writes`. Candidates see only the task. The picker uses the rubric in Phase D. +3. **Runners.** Read `arena runners` from `~/.gemini/config/plugins/agystack/agystack-models.md` (or `.agents/plugins/agystack/agystack-models.md`), defaulting across `inherit`, `flash`, and `pro`. An `inherit` or `auto` entry runs on the parent session's model (`Model: "inherit"`). If `invoke_subagent` rejects a tier or slot, use the nearest valid tier or drop the seat, keep at least two runners, and note the fallback. Repeat one model tier when the work is generation-bound rather than judgment-sensitive. 4. **Workspaces.** Assign isolated workspaces via `Workspace: "branch"` or scratch paths (`/brain//scratch/arena-/candidate-/`) per **principle-separate-before-serializing-shared-state**. ## Phase B: Fan out -Spawn all N subagents in one turn via `invoke_subagent` with `Workspace: "branch"` (never simulate in-context), `TypeName: "self"` (or `"poteto-agent"`), the task, grounding, output path, and instructions for producing the artifact and rationale. +Spawn all N subagents in one turn via `invoke_subagent` with `Workspace: "branch"` (never simulate in-context), `TypeName: "self"` (or `"poteto-agent"`), the task, grounding path, output path, and instructions to produce the artifact plus a short rationale naming alternatives considered and rejected. If a candidate produces no output or drops out, proceed with `N-1` and record the dropout. Provide `{PARENT_CONVERSATION_ID}` in each prompt. Candidates MUST invoke `send_message` with `Recipient: "{PARENT_CONVERSATION_ID}"` upon completion to wake the coordinator reactively. ### Reactive Dispatch & Watchdog Protocol -1. **Turn 1 (Dispatch & Arm):** Launch candidate subagents via `invoke_subagent` and arm a single watchdog deadline: +1. **Turn 1 (Dispatch and Arm).** Launch candidate subagents via `invoke_subagent` and arm a single watchdog deadline: `schedule(DurationSeconds: 300..600, Prompt="Watchdog: arena candidates timed out", TimerCondition: "never")` -2. **Turn 2 (Mechanical Yield):** Output an update message with ZERO tool calls (`tool_calls: []`). Busy polling via `manage_subagents(list)` is prohibited. -3. **Partial Arrivals:** When a candidate reports via `send_message`, record its artifact and yield immediately with ZERO tool calls if others remain running. -4. **Full Arrival:** When all N candidates report, cancel the watchdog timer via `manage_task(Action: "kill", TaskId: )` and proceed to Phase C. -5. **Timeout Fallback:** If the watchdog fires, inspect worker statuses via `manage_subagents(Action: "list")`, terminate hanging candidates (`manage_subagents(Action: "kill", ConversationIds: [])`), and proceed with surviving outputs. +2. **Turn 2 (Mechanical Yield).** Output an update message with ZERO tool calls (`tool_calls: []`). Busy polling via `manage_subagents(list)` is prohibited. +3. **Partial Arrivals.** When a candidate reports via `send_message`, record its artifact and yield immediately with ZERO tool calls if others remain running. +4. **Full Arrival.** When all N candidates report, cancel the watchdog timer via `manage_task(Action: "kill", TaskId: )` and proceed to Phase C. +5. **Timeout Fallback.** If the watchdog fires, inspect worker statuses via `manage_subagents(Action: "list")`, terminate hanging candidates (`manage_subagents(Action: "kill", ConversationIds: [])`), and proceed with surviving outputs. ## Phase C: Cross-judge -Spawn one judge subagent via `invoke_subagent` (`TypeName: "research"`, `Role: "Arena Cross-Judge"`). The cross-judge must be selected from a different model family than the candidates. For Antigravity, assign the judge role to `Model: "pro"` (Gemini Pro) to ensure deep comparative judgment over Flash candidate drafts. The judge scores candidates against rubric criteria and recommends a base with rationale. +After Phase B finishes, spawn one judge subagent via `invoke_subagent` (`TypeName: "research"`, `Role: "Arena Cross-Judge"`). Read `arena cross-judge pool` from `~/.gemini/config/plugins/agystack/agystack-models.md` (default `inherit, flash, pro`). Enforce model-tier and family diversity. Select a model from a different family than the parent session when cross-family models are configured, and pick a distinct Antigravity tier (`pro`, `flash`, or `inherit`) from the candidate draft majority (for example, `Model: "pro"` when candidates drafted on `flash`). If the parent model is unknown or `invoke_subagent` rejects a pool entry, fall back to the next pool entry or skip Phase C, and record whether the tier and family diversity check ran or was skipped. + +Pass `{PARENT_CONVERSATION_ID}` so the judge wakes the coordinator via `send_message`, using the same `TimerCondition: "never"` watchdog and ZERO tool calls yield while waiting. While you read in Phase D, the judge scores each candidate by path label on every rubric criterion and recommends a base with rationale. ## Phase D: Pick a base -Read every candidate end to end. Score against the rubric, compare against the cross-judge, and select the base that is easiest to extend cleanly per the **principle-laziness-protocol**. Record the choice and rationale. +Read every candidate end to end before picking. Score each against the rubric criterion by criterion rather than on holistic feel, and compare with the cross-judge verdict when Phase C ran. Agreement confirms the pick. Disagreement means one of you is biased or the rubric was ambiguous, so read both rationales before deciding. + +Pick the base a future maintainer can extend most easily without breaking invariants. When two feel tied, prefer the cleaner boundary or smaller API per **principle-laziness-protocol**. ## Phase E: Graft -Port winning ideas from losing candidates sequentially (`principle-sequence-verifiable-units`) per **principle-redesign-from-first-principles**: -- Apply each candidate's minimal diff to the base and verify immediately against tests and rubric criteria. -- Accept verified grafts; revert immediately if regressions occur. -- Record accepted grafts and explicit rejection reasons. +First apply the convergence-vs-divergence gate: + +- **Convergence.** If candidates converge on one shape, that is strong agreement. Record the convergence and ship the consensus shape with no graft needed. +- **Divergence.** If candidates wildly diverge, Phase A was under-specified. Reframe the artifact and rubric and re-run Phase B instead of averaging the divergence. + +When candidates share a clear base with distinct wins elsewhere, walk each losing candidate once more for what is worth porting (usually one or two ideas per candidate, not most of it). Fold each graft into the base sequentially (**principle-sequence-verifiable-units**) and by hand per **principle-redesign-from-first-principles**: + +- Apply one minimal diff to the base, verify immediately against tests and rubric criteria, and revert on regression. +- Record accepted grafts, source candidates, and explicit rejection reasons. ## Phase F: Verify -Verify the synthesized artifact per **principle-prove-it-works**. If verification fails, re-frame the task or inspect missed candidate solutions. +Verify the synthesized artifact per **principle-prove-it-works**. If verification finds a problem the arena missed, either Phase A was wrong (reframe and re-run) or a candidate caught it and you missed the graft (return to Phase E). Do not paper over it. ## Outputs -Publish the final synthesis package to `/brain//arena_synthesis.md` with `ArtifactMetadata: { Summary: "...", UserFacing: true, RequestFeedback: false }` and link to it in chat. Candidate drafts remain under `/brain//scratch/arena-/`. +Publish the final synthesis package to `/brain//arena_synthesis.md` with `ArtifactMetadata: { Summary: "...", UserFacing: true, RequestFeedback: false }` and link to it in chat. Record the base choice and rationale, cross-judge verdict (or why Phase C skipped it, plus tier and family diversity status), convergence or divergence outcomes, any dropouts, each graft with its source candidate, rejected ideas with reasons, and the verification result. Candidate drafts remain under `/brain//scratch/arena-/`. diff --git a/skills/cloud-swarm/SKILL.md b/skills/cloud-swarm/SKILL.md index ae11eb9..9bbde11 100644 --- a/skills/cloud-swarm/SKILL.md +++ b/skills/cloud-swarm/SKILL.md @@ -25,6 +25,7 @@ Open a todolist with one entry per phase before launching anything. 5. Execution routing: - For 8 or fewer workers (and unless `agystack-runtime.json` specifies `"runtime": "cloud-run"`), use local `invoke_subagent` fan-out (see `skills/poteto-mode/references/antigravity-tools.md`). - For more than 8 workers or when `agystack-runtime.json` specifies `"runtime": "cloud-run"`, use Cloud Run dispatch. +6. **Exact SHAs and measurement method.** When workers verify or measure commits, name the exact SHAs in each brief. When a worker measures performance or counts, also name the method (sample count, what one sample is, and execution order). Require every worker to echo both in its result. ## Phase B: Fan out (Cloud Run Dispatch) @@ -125,14 +126,17 @@ Before launching cloud swarms, match the model to the project's Model Garden ena - *Dashboard Reflection:* `SwarmDashboardWriter` captures steering dispatches to display `STEER_PENDING: ` under `Active Phase / Tool` and clears the pending status once `STEER_APPLIED` is acknowledged. - **Subprocess Timeout Guards:** Shell command execution and verification scripts are bounded by explicit environment timeouts (`COMMAND_TIMEOUT`, `VERIFY_TIMEOUT`), preventing hanging processes from stalling container lifecycle. -Every brief stands alone. Include goal, scope, exact slice, verification command, and expected report format (`[STATUS: PASS]`, `[STATUS: ISSUES]`, or `[STATUS: BLOCKED]` with evidence). +Every brief stands alone. Include goal, scope, exact slice or race arm, exact SHAs and measurement method when applicable, verification command, and expected report format (`[STATUS: PASS]`, `[STATUS: ISSUES]`, or `[STATUS: BLOCKED]` with evidence). A worker that can prove a defect reports `[STATUS: ISSUES]` and lists every issue it can prove, not only the first. + +If a worker drops out or fails to report, proceed with `N-1` and note the dropout explicitly. ## Phase C: Aggregate & Early Harvest 1. `cloud_dispatch.py` automatically harvests candidate patches from GCS into `.slices//task-/` and displays candidate patch file locations in the execution summary. -2. Apply selection rule (first pass, rank all, best-of): rank candidates by score delta descending. -3. **Candidate Integration Protocol:** Apply the winning `patch.diff` to a local worktree (`git apply .slices//task-/patch.diff`), run local verification, and commit. If verified, re-baseline and evaluate subsequent candidates sequentially. Never merge or compose multiple candidate patches simultaneously without intermediate verification (`principle-sequence-verifiable-units`). -4. Build a compact result table, one-line evidenced issues, and explicit dropouts. +2. **SHA and measurement-method echo gate.** Inspect terminal results and drop any result that omits the exact SHAs or measurement method named in its brief. Respawn or re-dispatch that slice once. After a second miss, record a gap. A gap never counts as a pass. For coverage sweeps, every required slice needs a result. +3. Apply the selection rule declared up front (`first pass`, `rank all`, or `best-of`): rank candidates by score delta descending. Do not paste raw worker dumps. +4. **Candidate Integration Protocol:** Apply the winning `patch.diff` to a local worktree (`git apply .slices//task-/patch.diff`), run local verification, and commit. If verified, re-baseline and evaluate subsequent candidates sequentially. Never merge or compose multiple candidate patches simultaneously without intermediate verification (`principle-sequence-verifiable-units`). +5. Build a compact result table, one-line evidenced issues, and explicit gaps or `N-1` dropouts. ## Phase D: Report diff --git a/skills/correct/SKILL.md b/skills/correct/SKILL.md index 2e7d9d2..73fd368 100644 --- a/skills/correct/SKILL.md +++ b/skills/correct/SKILL.md @@ -1,39 +1,47 @@ --- name: correct -description: Structured repository hardening against agent mistakes. Classifies recurring defects and enforces the fix hierarchy where architecture and structural checks precede rules and prompts. +description: "Find the mistakes agents keep repeating in this repo and make each one impossible. Try architecture first, then types, then a lint or hook whose error names the fix, then behavioral tests, and write docs last. Prove each check fails on a real past mistake. Use for /correct." --- # Correct -Harden repositories against recurring agent mistakes and systemic defects. -When an agent makes an error, do not simply patch the immediate failure or add an ad-hoc instruction. -Classify the defect and enforce structural defenses at the highest level of the fix hierarchy. +The operator keeps correcting agents in this repo for the same mistakes. Change the repo so the next agent cannot make them. -## Mistake Classification +Assume every contributor is an agent that sees only the files it opened, copies the nearest example, and takes the shortest path that compiles. Design the repo so a change that looks right from one file is right for the whole repo. -Group mistakes into distinct classes to identify appropriate structural countermeasures: +## Find the mistake classes -- **Constraint misunderstanding.** The agent ignores instructions, misinterprets bounds, or violates system constraints. -- **Hallucinated APIs.** The agent invents parameters, functions, flags, or tools that do not exist in the platform or runtime. -- **Fragile patterns.** The agent uses brittle regex parsing, race-prone file operations, unstructured text extraction, or unvalidated assumptions. -- **Regressions.** The agent breaks previously working tests, overwrites unrelated code, or reverts recent fixes. +Read recent commits, reverts, review comments, `rules/AGENTS.md`, and comments that explain workarounds. Group mistakes into classes (`Constraint misunderstanding`, `Hallucinated APIs`, `Fragile patterns`, `Regressions`). -## Fix Hierarchy +**A class counts once it has happened twice.** -When remediating an agent defect, apply solutions at the highest possible layer in the fix hierarchy. -Architecture and structural checks precede rules and prompt instructions: +## Fix each class at the highest level that works -1. **Architecture.** Make illegal states unrepresentable. Enforce structural boundaries, capability restrictions, and invariants by construction. -2. **Type checks.** Statically typed schemas, discriminated unions, and compiler gates that fail immediately on invalid invocations. -3. **Linter and automated tests.** Deterministic static analysis, linters, pre-commit hooks, and behavioral unit tests that catch errors in automated loops. -4. **Instructions and prompts.** Guidelines and prompt instructions are the last line of defense, never the first. +1. **Eliminate it with architecture.** Make illegal states unrepresentable. Give each piece of state one owner and each task one supported way. Hide internals so the wrong import fails, replace hand-synced lists with one source of truth, and delete dead ways an agent would copy. +2. **Enforce it with types and static checks.** Make invalid invocations fail compilation. If bad code still compiles, add a lint or CI check whose error names the file, type, or function to use instead. If the pattern is already common, fail only when a change adds more. +3. **Add hooks, linters, and behavioral tests.** Enforce tool boundaries with Antigravity lifecycle hooks (`hooks.json.example`) and test observable behavior (`tests/`). Fix or delete any test that still passes when the behavior breaks, or fails when only internals change. +4. **Write docs or agent rules last, only for judgment calls.** Nothing fails automatically when an agent skips `rules/AGENTS.md` or skill prose. -## Hardening Process +## Fix and prove -Follow these steps to remediate mistakes: +1. Reproduce and fix the most frequent mistake classes now, one commit each. +2. **Prove each new check fails on a real past mistake.** +3. Run the same verification command locally and in CI (`make ci`). +4. **Exception expiry rule.** Exceptions go on the offending line with a reason, an expiry date, and a human's approval. -1. Reproduce the mistake with an automated test or deterministic reproduction script. -2. Classify the mistake into its category. -3. Determine the highest applicable layer in the fix hierarchy. -4. Implement the structural guard such as a typed interface, lint rule, or architectural boundary. -5. Verify that the failure is blocked before falling back to prompt prose. +## Keep the rule-to-enforcer table + +Pair each recurring rule with what enforces it automatically. When the operator corrects you, fix the mistake and add the rule. If the rule already existed without enforcement, that is a repeat, so enforce it at the highest level in the same change. Drop a rule once its mistake cannot happen. + +| Rule or Invariant | Automated Enforcer | Verification | +| --- | --- | --- | +| Coordinator delegates code writes `> 50` lines to `poteto-agent` | `hooks.json.example` (`agystack-delegation` -> `pre_tool_delegation.py`) | `tests/test_hooks.py`, `tests/test_reactive_coordination_rules.py` | +| Destructive CLI commands (`rm`, trunk force-push, `drop database`) gated | `hooks.json.example` (`agystack-safety` -> `pre_tool_safety.py`) | `tests/test_hooks.py` | +| Deterministic post-write formatting on `.py`, `.ts`, `.tsx`, `.js`, and `.jsx` | `hooks.json.example` (`agystack-formatter` -> `post_tool_lint.py`) | `tests/test_hooks.py` | +| Zero Cursor leaks and `agystack-models.md` role key parity | Static scanner in `tests/test_antigravity_invariants.py` | `pytest -v tests/test_antigravity_invariants.py` | +| Reactive wakeup (`TimerCondition: "never"`, `ZERO tool calls`, `send_message`) | Contract assertions in `tests/test_reactive_coordination_rules.py` | `pytest -v tests/test_reactive_coordination_rules.py` | +| Skill catalog, principle count, and `/swarm` non-collision (`cloud-swarm`) | Catalog checks in `tests/test_skill_catalog.py` | `pytest -v tests/test_skill_catalog.py` | +| Agent `inheritCustomizations: false` and registered tool list | Frontmatter checks in `tests/test_agent_definitions.py` | `pytest -v tests/test_agent_definitions.py` | +| Manifest semver parity, hook paths, and zip hygiene | `tests/test_plugin_manifest.py` and `scripts/package-plugin.sh --test` | `make package-check` | + +**Reply:** list each mistake class with its evidence, the hierarchy level you picked, and why a higher level did not work. diff --git a/skills/ketchup/SKILL.md b/skills/ketchup/SKILL.md index a29bbb2..cfef7fd 100644 --- a/skills/ketchup/SKILL.md +++ b/skills/ketchup/SKILL.md @@ -1,60 +1,60 @@ --- name: ketchup -description: Catch up on autonomous runs, background tasks, and unread transcripts. Generates concise summaries under 100 words with native Antigravity Artifact links, visual receipts, and selectable action items. +description: "Catch the user up on what changed in this chat or autonomous run since their last message, in plain words and small visuals. List every item waiting on them with what they need to decide it from the reply alone. Use for /ketchup." --- # Ketchup -Catch up on autonomous runs, unattended tasks, and background execution without reading lengthy transcripts. +Catch the user up on what changed in this chat or autonomous run since the last message they wrote before `/ketchup`, and help them understand each change rather than only where it stands. Then lay out every call waiting on them so they can decide from your reply alone. Notifications and subagent results are not user messages. Assume the user remembers their last message and nothing after it. -## Strict Concise Summary Format +Use [`/bro`](../bro/SKILL.md)'s voice, in plain words and short sentences without jargon. State what changed for the user rather than how you did it. Say "the tests pass", not "CI is green". Omit commit hashes, file paths, commands, build numbers, and test counts unless the user needs one to act. Call each PR, branch, or agent by a name the user knows. If a fact needs context to make sense, give the context or leave the fact out. -Executive summaries must remain strictly under 100 words. -Deliver the core status in plain declarative sentences. -Name the current goal, the completed phase, any active blockers, and the next step. -Avoid narrative filler and conversational preamble. -Detailed logs belong in companion artifacts rather than the chat summary. +## Gather what changed -## Action Items and Decisions Formatting +- **Read-only turn enforcement.** Keep this turn strictly read-only. Build visuals only from state and artifacts you already have. Do not change code, start an app or job, or post anything. +- **Collect state.** Gather your work since the user's last message, subagent reports, messages from others in this chat, and the current state of each PR, CI run, or agent touched. +- **Verify numbers against source facts.** Check every number you plan to show against the source facts it comes from, including `decisions.tsv`, test logs, and PR metrics. Say so explicitly when you correct one. +- **Action-item qualification.** An action item is a call or step only the user can take, such as a product choice, approval, irreversible action, or missing access, including any still waiting from earlier. Work you can still do yourself is not an action item. Never invent a call to fill the reply. A step the user did not ask for and the work does not need is not an action item unless it is irreversible and waiting on them. Give that one line and no visual. +- **Per-action-item schema.** One call can cover many items, such as PRs awaiting merge. For each action item, collect: + 1. Link or identifier, if available. + 2. What it changes for users. + 3. Your pick and the evidence behind it, placing prerequisite or irreversible steps first. + 4. Risk, even when low, such as `"Low risk. Only the colors change."`. State waiting cost only when worse than a delay, such as a deadline or lost data. + Write `"unknown"` for any needed fact you do not know. -Format pending decisions and open questions so the user can easily select options or picks. -Present choices as structured options labeled with clear tags: +## Write the reply -- **Option A.** Description of the first choice and its immediate tradeoff. -- **Option B.** Description of the alternative choice and its immediate tradeoff. +Spend words on the calls, not the story. Keep what happened under **100 words**, excluding visuals, and shorter when less happened. Omit work that changed nothing for the user. -The user can respond with a single token or pick such as Option A. -Do not ask open-ended questions when a structured pick settles the fork. -When an action is blocked on external input, state the exact input required and the default fallback. +- **Scaling word budget (`~30 words per item`).** Give each action item about 30 words (`~30 words per item`). Total length grows with item count. Two items stay well under 150 words excluding visuals, and thirty items take proportionally more. Never cut items or shrink them behind counts or links to stay under a cap. The reply alone must be enough to decide. +- **Opening.** Open with one short sentence naming what waits on the user, or stating that nothing does. If nothing happened and nothing waits, say so and stop. +- **What happened.** Show visuals first, then one short plain bullet per requested item naming outcome and state (`done`, `still running`, `failed`, or `not checked`) plus any bug found and fixed. Never mark work waiting on the user as done. Follow with up to three short lines that change what the user knows or must do, and one line for remaining work you can do yourself. +- **Action items.** Fit the shape to the call: + - **Single-item call.** One bullet with the call, your pick, user-facing change, evidence, and risk. + - **Shared call.** State the call and your pick once, then list one bullet per item ordered riskiest first: link and name, user-facing change, evidence, risk, and any item-specific pick override. + - **Option choice.** Present structured picks so the user can respond with a single token such as `Option A`: + - **Option A.** Description, user gain, cost, and current state. + - **Option B.** Alternative, user gain, cost, and current state. + Costs serve as the risk line. When blocked on external input, state the exact input needed and the default fallback. -## Native Antigravity Artifacts & Visual Progress +## Native Antigravity Artifacts & Visual Layer -Deliver comprehensive context through native Antigravity Artifacts in `/brain//`. -Point to artifacts using clickable file links. -Do not dump artifact bodies into chat responses. -Key companion artifacts include: +Store detailed context in native Antigravity Brain Artifacts under `/brain//` and point with clickable `file://` links instead of dumping artifact bodies into chat: -- `walkthrough.md` for verified changes and test receipts. -- `decision_trail.md` for sequential forks, rationales, and results. +- `walkthrough.md` for verified changes, test receipts, and visual proof. +- `decisions.tsv` paired with `decision_trail.md` for sequential forks, evidence pointers, and results. - `implementation_plan.md` for roadmap progress and checked boxes. -### Visual Progress Carousels and Generative UI -Use native markdown carousels (````carousel ... ````) with `` comments for sequential visual walkthroughs and before/after progressions. -Embed `generative_ui` HTML/SVG timeline widgets for visual progress rendering directly in artifacts without external video compilation dependencies like ffmpeg MP4s. +### Primary Visual Layer (`carousel` and `generative_ui`) -## Visual Media Embedding +Use native markdown `carousel` blocks (````carousel ... ```` with `` comments) for sequential walkthroughs and before and after progressions, and use `generative_ui` HTML and SVG timeline widgets as the primary visual layer directly in artifacts without external video dependencies such as ffmpeg MP4s. -Link or embed visual media directly to provide immediate visual receipts. -Always copy screenshots and recordings to `/brain//` before referencing them. -Screenshots are linked or embedded using standard Markdown syntax: +### Visual Discipline and Media Embedding -`![Verification Receipt](file:///path/to/screenshot.png)` - -Provide direct file links alongside embeds so the user can open them in external viewers. -Every visual receipt must prove a concrete assertion such as passing gates or rendered UI states. +- Copy screenshots and recordings to `/brain//` before referencing them, then embed inline alongside a direct link (`![Verification Receipt](file:///path/to/screenshot.png)`). Every receipt must prove a concrete assertion. +- Embed screenshots inline when a change is visible, or mark the summary line `"No screenshot yet"` and describe the on-screen change. +- Keep diagrams and charts factual and small. Use at most six boxes and at most eight words per box. A Markdown table is not a visual. Never invent numbers, draw fake UI screens, or repeat the same fact across visuals and text. ## Periodic Audit Reporting -Use `/ketchup` at the conclusion of periodic audit ticks during autonomous playbooks. -An audit tick evaluates progress across subagents, verifies side effects, and outputs a concise ketchup report. -This practice keeps the operator informed without context overload. +Use `/ketchup` at the conclusion of periodic audit ticks during autonomous playbooks. An audit tick evaluates progress across subagents, verifies side effects, and outputs a concise ketchup report without context overload. diff --git a/skills/poteto-mode/references/antigravity-tools.md b/skills/poteto-mode/references/antigravity-tools.md index 2286f0e..e259a7d 100644 --- a/skills/poteto-mode/references/antigravity-tools.md +++ b/skills/poteto-mode/references/antigravity-tools.md @@ -73,13 +73,18 @@ For 8 or fewer independent parallel workers, verification lanes, or candidate ra ### Recipe 1. **Batch Spawn:** Dispatch all workers in a single `invoke_subagent` call with `TypeName: "poteto-agent"` (or `"self"`), `Role: "Worker ()"`, `Workspace: "branch"`, and the model resolved from `swarm workers` in `~/.gemini/config/plugins/agystack/agystack-models.md` (default: `flash`). -2. **Mandatory Reporting Contract:** In each worker's prompt, provide `{PARENT_CONVERSATION_ID}` and mandate that upon completing work and verification, the worker MUST invoke `send_message` with `Recipient: "{PARENT_CONVERSATION_ID}"` and its findings/status. -3. **Reactive Watchdog Protocol:** +2. **Standalone Brief, SHAs, and Measurement Method:** Give each writing worker its own writable workspace (`Workspace: "branch"`). Every brief stands alone with goal, scope, exact slice or race arm, verification command, and report format (`PASS`, `ISSUES`, or `BLOCKED` with evidence). A worker proving a defect lists every provable issue, not only the first. When workers verify or measure commits, name the exact SHAs in each brief, and for measurements also name the method, including sample count, what one sample is, and execution order. Require every worker to echo both in its `send_message` result. +3. **Mandatory Reporting Contract:** In each worker's prompt, provide `{PARENT_CONVERSATION_ID}` and mandate that upon completing work and verification, the worker MUST invoke `send_message` with `Recipient: "{PARENT_CONVERSATION_ID}"` and its findings and status. +4. **Reactive Watchdog Protocol:** - Arm a single unconditional watchdog deadline: `schedule(DurationSeconds: 300..600, Prompt="Watchdog: local fan-out timed out", TimerCondition: "never")`. - Yield the coordinator turn immediately with ZERO tool calls (`tool_calls: []`). - On each `send_message` arrival, process results and yield immediately with ZERO tool calls while workers remain active. - When all workers complete, cancel the watchdog timer via `manage_task(Action: "kill", TaskId: )`. - See Rule 4 in `rules/AGENTS.md` for full reactive wakeup and watchdog requirements. +5. **Aggregation, `N-1` Dropout Rule, and Echo Gate:** + - If a worker drops out or fails to report before the watchdog deadline (`manage_subagents(Action: "list")`), proceed with `N-1` and record the dropout explicitly. + - Drop any result that omits the exact SHAs or measurement method named in its brief, and respawn that worker once. After a second miss, record a gap. A gap never counts as a pass. + - For coverage sweeps, every required slice needs a result. For races, apply the selection rule declared up front (`first pass`, `rank all`, or `best-of`), verify winning candidates sequentially, and never paste raw worker dumps or bulk-merge candidate diffs. ## Parallel Cloud Agent Execution (Cloud Run Runtime) diff --git a/skills/typescript-best-practices/SKILL.md b/skills/typescript-best-practices/SKILL.md index 9c4e3cb..61672b5 100644 --- a/skills/typescript-best-practices/SKILL.md +++ b/skills/typescript-best-practices/SKILL.md @@ -10,11 +10,12 @@ Apply the **type-system-discipline** principle skill first; this skill grounds i | Rule | Summary | |------|---------| | Discriminated unions | Model variants with a `kind` literal discriminant so impossible states can't be represented. No optional-field bags. | -| Branded types | Brand primitives with `& { readonly __brand: "X" }` so they can't be mixed up. Validate once at creation. | +| Branded types | Brand primitives with `& { readonly __brand: "X" }` so they can't be mixed up. Validate once at the boundary and create brands only via verifying type guards (`input is AgentId`), never via `as`. | | Constructive modeling | Build the shape so the illegal value can't be constructed. `[T, ...T[]]` for non-empty, `[T, T][]` for even length, `start` plus `duration` for a range. Not a runtime guard, not a wish for refinement types. | | Simplest total type | Keep `T[]` while every operation on it stays total. Strengthen to `NonEmpty` only where the loose type forces `!`, a cast, or a "should never happen" throw. | | `unknown` over `any` | External data is `unknown`. `any` disables type checking everywhere it touches. | -| No `as` casts | Every `as` is a runtime crash waiting. Cast only after validation. | +| Schemas before guards | Before hand-writing a property-by-property type guard, use the repository's existing runtime schema library and infer the type from the schema, such as `z.infer`. | +| No `as` casts | Every `as` is a runtime crash waiting. Narrow with schemas, verifying guards, or `satisfies` instead. | | Narrowing hierarchy | Discriminant switch > `in` operator > `typeof`/`instanceof` > user-defined type guard > `as`. | | Type guards | Must verify the claim. A lying guard is worse than `as` because the bug hides behind a name that says it's safe. Name them `isX` or `hasX`. | | Exhaustiveness | Inline `const _exhaustive: never = x;` in default arms so the compiler errors when a new variant is added. | diff --git a/skills/typescript-best-practices/references/patterns.md b/skills/typescript-best-practices/references/patterns.md index 853b1cc..02f2546 100644 --- a/skills/typescript-best-practices/references/patterns.md +++ b/skills/typescript-best-practices/references/patterns.md @@ -4,7 +4,7 @@ Code examples for each rule in `SKILL.md`. The underlying principles are languag ## Branded types -Brand primitives so they can't be mixed up. Validate once at creation; downstream code trusts the type. +Brand primitives so they can't be mixed up. Validate once at the boundary, and create branded types only via verifying type guards (`input is AgentId`) instead of raw `as` casts. Downstream code trusts the type. ```ts type AgentId = string & { readonly __brand: "AgentId" }; @@ -131,33 +131,65 @@ function handle(input: unknown) { External sources include RPC payloads, `JSON.parse`, `postMessage`, IPC, file contents, environment variables, database results. +## Schemas before hand-rolled guards + +Before writing a property-by-property type guard for external data, look for the repository's existing runtime schema library and schemas. Let one schema own validation and derive the TypeScript type from it instead of keeping a schema, a duplicate interface, and a guard that can drift apart. + +```ts +import { z } from "zod"; + +const UserSchema = z.object({ + id: z.string().uuid(), + role: z.enum(["admin", "member"]), +}); + +type User = z.infer; + +function parseUser(input: unknown): User { + return UserSchema.parse(input); +} +``` + +Use `safeParse` when failure is an expected branch, or the equivalent inference helper when the repository uses another schema library, such as TypeBox, ArkType, or Valibot. Never add a new runtime schema dependency unprompted for one guard. Prefer the schema system the codebase already trusts. + ## No `as` casts -Every `as` is a potential runtime crash. Cast only after the type system has verified the claim. +Every `as` is a potential runtime crash. Narrow with schemas, verifying type guards, or `satisfies` instead. ```ts +import { z } from "zod"; + // Don't const user = data as User; -// Do. Earn the cast at the boundary. +// Don't. Half-checked guard that leaves fields unverified. +function isUser(data: unknown): data is User { + return typeof data === "object" && data !== null && "id" in data; +} + +// Do. Validate with the repo schema and infer the type. +const userSchema = z.object({ id: z.string(), name: z.string() }); +type User = z.infer; + function parseUser(data: unknown): User { - if (typeof data !== "object" || data === null) { - throw new Error("expected object"); - } - if (!("id" in data) || typeof (data as Record).id !== "string") { - throw new Error("expected id"); - } - // ... validate all fields - return data as User; // OK, earned cast after full validation + return userSchema.parse(data); } ``` -When refactoring an `as` out of existing code, identify why TypeScript can't infer: +When the type comes first, annotate the validator with the type it proves so the compiler rejects a validator that proves less than the type: + +```ts +type User = { id: string; name: string }; + +const userSchema: z.ZodType = z.object({ id: z.string(), name: z.string() }); +``` + +When refactoring an `as` out of existing code, identify why TypeScript cannot infer: - Missing discriminant: add one, switch to a discriminated union. - Overly wide source type (e.g. `Record`): narrow it. -- Untyped boundary: add a parse function or schema. -- Genuinely inexpressible: use a branded type or `satisfies`. +- Untyped boundary: parse with the schema that owns the shape. Add a schema only where none exists. +- Genuinely inexpressible: use a branded type guard or `satisfies`. ## Narrowing hierarchy @@ -249,7 +281,7 @@ Validate once where data crosses in; trust types inside. See the **boundary-disc ## Schema-derived types -When a `.proto`, OpenAPI spec, GraphQL schema, or database migration already defines a shape, derive from the generated types instead of duplicating them. Recommend an existing schema library (such as Zod, TypeBox, ArkType, or Valibot) only when the target project already uses one; never introduce a new runtime schema dependency unprompted. +When a `.proto`, OpenAPI spec, GraphQL schema, or database migration already defines a shape, derive from the generated types instead of duplicating them. ```ts // Don't. Duplicate shape, drifts when the schema changes.