From 62fbc5d57b664edc542d58f81c3e12da2a5b1d1a Mon Sep 17 00:00:00 2001 From: Mikael Hugo Date: Thu, 14 May 2026 19:32:41 +0200 Subject: [PATCH] refactor: align agent resource overlays --- .agents/AGENTS.md | 54 +- .agents/adapters/.gitkeep | 2 + .agents/manifest.yaml | 88 +- .../SKILL.md => policies/.gitkeep} | 0 .../SKILL.md => prompts/.gitkeep} | 0 .agents/skills/forge-planning/SKILL.md | 0 .agents/skills/forge-state/SKILL.md | 0 .agents/skills/nix-build/SKILL.md | 26 - .agents/skills/smoke-test/SKILL.md | 17 - .gitignore | 17 +- docs/dev/FILE-SYSTEM-MAP.md | 32 +- docs/dev/generated-artifact-policy.md | 70 +- .../dev/sf-runtime/autonomous-runtime.md | 4 +- .../dev/sf-runtime/command-surface.md | 4 +- docs/dev/sf-runtime/harness.md | 15 + docs/dev/sf-runtime/operating-model.md | 18 + docs/dev/sf-runtime/planning.md | 15 + docs/dev/sf-runtime/state.md | 16 + docs/specs/agent-mode-system.md | 8 +- docs/user-docs/commands.md | 2 +- docs/user-docs/configuration.md | 8 +- docs/user-docs/skills.md | 60 +- src/headless-context.ts | 16 +- src/headless-triage.ts | 88 +- .../policies/default-safe.yaml | 0 .../singularity-forge}/prompts/base.md | 0 .../singularity-forge}/prompts/project.md | 0 .../extensions/sf/auto-bootstrap-context.js | 16 +- src/resources/extensions/sf/auto-prompts.js | 160 +++- .../extensions/sf/bootstrap/system-context.js | 50 +- .../sf/commands/handlers/workflow.js | 4 +- .../sf/docs/preferences-reference.md | 6 +- .../extensions/sf/md-file-tracker.js | 4 +- .../extensions/sf/preferences-skills.js | 7 +- src/resources/extensions/sf/prompts/system.md | 4 +- src/resources/extensions/sf/skill-catalog.js | 9 +- .../extensions/sf/skill-discovery.js | 12 +- src/resources/extensions/sf/skill-health.js | 9 +- src/resources/extensions/sf/skill-manifest.js | 18 +- .../extensions/sf/skill-telemetry.js | 6 +- .../extensions/sf/skills/directory.js | 60 +- src/resources/extensions/sf/skills/index.js | 1 + src/resources/extensions/sf/skills/loader.js | 36 +- .../extensions/sf/subagent/prompt-parts.js | 1 - .../extensions/sf/templates/PREFERENCES.md | 4 +- .../extensions/sf/templates/preferences.yaml | 4 +- .../auto-prompts-workflow-skills.test.mjs | 47 ++ .../extensions/sf/tests/skills.test.mjs | 114 ++- src/resources/skills/accessibility/SKILL.md | 522 ------------ .../skills/accessibility/references/WCAG.md | 162 ---- src/resources/skills/agent-browser/SKILL.md | 517 ------------ .../references/authentication.md | 202 ----- .../agent-browser/references/commands.md | 263 ------ .../agent-browser/references/profiling.md | 120 --- .../agent-browser/references/proxy-support.md | 194 ----- .../references/session-management.md | 193 ----- .../agent-browser/references/snapshot-refs.md | 194 ----- .../references/video-recording.md | 173 ---- .../templates/authenticated-session.sh | 105 --- .../templates/capture-workflow.sh | 69 -- .../templates/form-automation.sh | 62 -- src/resources/skills/best-practices/SKILL.md | 583 ------------- src/resources/skills/btw/SKILL.md | 42 - src/resources/skills/code-optimizer/SKILL.md | 160 ---- .../references/algorithmic-complexity.md | 66 -- .../references/build-compilation.md | 90 -- .../references/bundle-dependencies.md | 82 -- .../references/caching-memoization.md | 76 -- .../references/concurrency-async.md | 80 -- .../code-optimizer/references/config-infra.md | 71 -- .../references/data-structures.md | 80 -- .../references/database-queries.md | 76 -- .../references/dead-code-redundancy.md | 84 -- .../references/error-resilience.md | 80 -- .../code-optimizer/references/io-network.md | 89 -- .../references/logging-observability.md | 64 -- .../references/memory-resources.md | 66 -- .../code-optimizer/references/rendering-ui.md | 90 -- .../references/security-performance.md | 68 -- src/resources/skills/core-web-vitals/SKILL.md | 441 ---------- .../skills/core-web-vitals/references/LCP.md | 208 ----- .../skills/create-sf-extension/SKILL.md | 93 -- .../references/compaction-session-control.md | 77 -- .../references/custom-commands.md | 139 --- .../references/custom-rendering.md | 108 --- .../references/custom-tools.md | 183 ---- .../references/custom-ui.md | 490 ----------- .../references/events-reference.md | 126 --- .../references/extension-lifecycle.md | 64 -- .../references/extensionapi-reference.md | 75 -- .../references/extensioncontext-reference.md | 53 -- .../references/key-rules-gotchas.md | 37 - .../references/mode-behavior.md | 32 - .../references/model-provider-management.md | 89 -- .../references/packaging-distribution.md | 55 -- .../references/remote-execution-overrides.md | 90 -- .../references/state-management.md | 70 -- .../references/system-prompt-modification.md | 52 -- .../templates/extension-skeleton.ts | 51 -- .../templates/stateful-tool-skeleton.ts | 143 ---- .../templates/templates.test.ts | 58 -- .../workflows/add-capability.md | 57 -- .../workflows/create-extension.md | 176 ---- .../workflows/debug-extension.md | 76 -- src/resources/skills/create-skill/SKILL.md | 10 +- .../references/executable-code.md | 2 +- .../references/sf-skill-ecosystem.md | 20 +- .../create-skill/workflows/add-reference.md | 6 +- .../create-skill/workflows/add-script.md | 4 +- .../create-skill/workflows/add-template.md | 2 +- .../create-skill/workflows/add-workflow.md | 6 +- .../create-skill/workflows/audit-skill.md | 8 +- .../workflows/create-new-skill.md | 12 +- .../workflows/upgrade-to-router.md | 10 +- .../create-skill/workflows/verify-skill.md | 8 +- src/resources/skills/create-workflow/SKILL.md | 104 --- .../references/feature-patterns.md | 128 --- .../references/verification-policies.md | 76 -- .../references/yaml-schema-v1.md | 46 - .../templates/blog-post-pipeline.yaml | 60 -- .../create-workflow/templates/code-audit.yaml | 60 -- .../templates/product-tracking-lifecycle.yaml | 144 ---- .../templates/release-checklist.yaml | 66 -- .../templates/workflow-definition.yaml | 32 - .../workflows/create-from-scratch.md | 104 --- .../workflows/create-from-template.md | 73 -- .../skills/debug-like-expert/SKILL.md | 231 ----- .../references/debugging-mindset.md | 253 ------ .../references/hypothesis-testing.md | 373 -------- .../references/investigation-techniques.md | 337 -------- .../references/verification-patterns.md | 425 ---------- .../references/when-to-research.md | 361 -------- src/resources/skills/frontend-design/SKILL.md | 45 - .../skills/github-workflows/SKILL.md | 90 -- .../github-workflows/references/gh/SKILL.md | 276 ------ .../references/gh/references/issue-stories.md | 204 ----- .../references/gh/references/labels.md | 170 ---- .../references/gh/references/milestones.md | 158 ---- .../references/gh/references/projects-v2.md | 177 ---- .../gh/scripts/experiment_cleanup.py | 191 ----- .../gh/scripts/github_project_setup.py | 799 ------------------ .../references/gh/tests/__init__.py | 0 .../gh/tests/test_github_project_setup.py | 608 ------------- src/resources/skills/lint/SKILL.md | 141 ---- .../make-interfaces-feel-better/SKILL.md | 122 --- .../make-interfaces-feel-better/animations.md | 379 --------- .../performance.md | 88 -- .../make-interfaces-feel-better/surfaces.md | 247 ------ .../make-interfaces-feel-better/typography.md | 123 --- .../skills/react-best-practices/README.md | 123 --- .../skills/react-best-practices/SKILL.md | 136 --- .../skills/react-best-practices/metadata.json | 15 - .../react-best-practices/rules/_sections.md | 46 - .../react-best-practices/rules/_template.md | 28 - .../rules/advanced-event-handler-refs.md | 55 -- .../rules/advanced-init-once.md | 42 - .../rules/advanced-use-latest.md | 39 - .../rules/async-api-routes.md | 38 - .../rules/async-defer-await.md | 80 -- .../rules/async-dependencies.md | 51 -- .../rules/async-parallel.md | 28 - .../rules/async-suspense-boundaries.md | 99 --- .../rules/bundle-barrel-imports.md | 59 -- .../rules/bundle-conditional.md | 31 - .../rules/bundle-defer-third-party.md | 49 -- .../rules/bundle-dynamic-imports.md | 35 - .../rules/bundle-preload.md | 50 -- .../rules/client-event-listeners.md | 74 -- .../rules/client-localstorage-schema.md | 71 -- .../rules/client-passive-event-listeners.md | 48 -- .../rules/client-swr-dedup.md | 56 -- .../rules/js-batch-dom-css.md | 107 --- .../rules/js-cache-function-results.md | 80 -- .../rules/js-cache-property-access.md | 28 - .../rules/js-cache-storage.md | 70 -- .../rules/js-combine-iterations.md | 32 - .../rules/js-early-exit.md | 50 -- .../rules/js-hoist-regexp.md | 45 - .../rules/js-index-maps.md | 37 - .../rules/js-length-check-first.md | 49 -- .../rules/js-min-max-loop.md | 82 -- .../rules/js-set-map-lookups.md | 24 - .../rules/js-tosorted-immutable.md | 57 -- .../rules/rendering-activity.md | 26 - .../rules/rendering-animate-svg-wrapper.md | 47 -- .../rules/rendering-conditional-render.md | 40 - .../rules/rendering-content-visibility.md | 38 - .../rules/rendering-hoist-jsx.md | 46 - .../rules/rendering-hydration-no-flicker.md | 82 -- .../rendering-hydration-suppress-warning.md | 30 - .../rules/rendering-svg-precision.md | 28 - .../rules/rendering-usetransition-loading.md | 75 -- .../rules/rerender-defer-reads.md | 39 - .../rules/rerender-dependencies.md | 45 - .../rules/rerender-derived-state-no-effect.md | 40 - .../rules/rerender-derived-state.md | 29 - .../rules/rerender-functional-setstate.md | 74 -- .../rules/rerender-lazy-state-init.md | 58 -- .../rules/rerender-memo-with-default-value.md | 38 - .../rules/rerender-memo.md | 44 - .../rules/rerender-move-effect-to-event.md | 45 - .../rerender-simple-expression-in-memo.md | 35 - .../rules/rerender-transitions.md | 40 - .../rerender-use-ref-transient-values.md | 73 -- .../rules/server-after-nonblocking.md | 73 -- .../rules/server-auth-actions.md | 96 --- .../rules/server-cache-lru.md | 41 - .../rules/server-cache-react.md | 76 -- .../rules/server-dedup-props.md | 65 -- .../rules/server-parallel-fetching.md | 83 -- .../rules/server-serialization.md | 38 - src/resources/skills/repo-map/SKILL.md | 58 -- src/resources/skills/review/SKILL.md | 214 ----- src/resources/skills/test/SKILL.md | 201 ----- .../skills/userinterface-wiki/SKILL.md | 253 ------ .../userinterface-wiki/rules/_sections.md | 66 -- .../userinterface-wiki/rules/_template.md | 24 - .../rules/a11y-reduced-motion-check.md | 30 - .../rules/a11y-toggle-setting.md | 30 - .../rules/a11y-visual-equivalent.md | 36 - .../rules/a11y-volume-control.md | 28 - .../rules/appropriate-confirmations-only.md | 19 - .../rules/appropriate-errors-warnings.md | 18 - .../rules/appropriate-no-decorative.md | 21 - .../rules/appropriate-no-high-frequency.md | 28 - .../rules/appropriate-no-punishing.md | 27 - .../rules/container-callback-ref.md | 31 - .../rules/container-guard-initial-zero.md | 25 - .../rules/container-no-excessive-use.md | 13 - .../rules/container-overflow-hidden.md | 25 - .../rules/container-transition-delay.md | 21 - .../rules/container-two-div-pattern.md | 35 - .../rules/container-use-resize-observer.md | 48 -- .../rules/context-cleanup-nodes.md | 25 - .../rules/context-resume-suspended.md | 28 - .../rules/context-reuse-single.md | 30 - .../rules/design-filter-for-character.md | 25 - .../rules/design-noise-for-percussion.md | 26 - .../rules/design-oscillator-for-tonal.md | 22 - .../rules/duration-max-300ms.md | 21 - .../rules/duration-press-hover.md | 21 - .../rules/duration-shorten-before-curve.md | 21 - .../rules/duration-small-state.md | 15 - .../rules/easing-entrance-ease-out.md | 21 - .../rules/easing-exit-ease-in.md | 21 - .../rules/easing-for-state-change.md | 27 - .../rules/easing-linear-only-progress.md | 21 - .../rules/easing-natural-decay.md | 22 - .../rules/easing-no-linear-motion.md | 22 - .../rules/easing-transition-ease-in-out.md | 15 - .../rules/envelope-exponential-decay.md | 21 - .../rules/envelope-no-zero-target.md | 21 - .../rules/envelope-set-initial-value.md | 22 - .../rules/exit-key-required.md | 29 - .../rules/exit-matches-initial.md | 29 - .../rules/exit-prop-required.md | 33 - .../rules/exit-requires-wrapper.md | 27 - .../rules/impl-default-subtle.md | 21 - .../rules/impl-preload-audio.md | 34 - .../rules/impl-reset-current-time.md | 26 - .../rules/mode-pop-layout-for-lists.md | 25 - .../rules/mode-sync-layout-conflict.md | 29 - .../rules/mode-wait-doubles-duration.md | 25 - .../rules/morphing-aria-hidden.md | 21 - .../rules/morphing-consistent-viewbox.md | 23 - .../rules/morphing-group-variants.md | 33 - .../rules/morphing-jump-non-grouped.md | 29 - .../rules/morphing-reduced-motion.md | 28 - .../rules/morphing-spring-rotation.md | 23 - .../rules/morphing-strokelinecap-round.md | 21 - .../rules/morphing-three-lines.md | 32 - .../rules/morphing-use-collapsed.md | 33 - .../rules/native-backdrop-styling.md | 27 - .../rules/native-placeholder-styling.md | 27 - .../rules/native-selection-styling.md | 18 - .../rules/nested-consistent-timing.md | 25 - .../rules/nested-propagate-required.md | 41 - .../rules/none-context-menu-entrance.md | 25 - .../rules/none-high-frequency.md | 29 - .../rules/none-keyboard-navigation.md | 32 - .../rules/param-click-duration.md | 21 - .../rules/param-filter-frequency-range.md | 21 - .../rules/param-q-value-range.md | 21 - .../rules/param-reasonable-gain.md | 21 - .../rules/physics-active-state.md | 23 - .../rules/physics-no-excessive-stagger.md | 22 - .../rules/physics-spring-for-overshoot.md | 23 - .../rules/physics-subtle-deformation.md | 22 - .../rules/prefetch-hit-slop.md | 27 - .../rules/prefetch-keyboard-tab.md | 19 - .../rules/prefetch-not-everything.md | 22 - .../rules/prefetch-touch-fallback.md | 34 - .../rules/prefetch-trajectory-over-hover.md | 32 - .../rules/prefetch-use-selectively.md | 13 - .../rules/presence-disable-interactions.md | 31 - .../rules/presence-hook-in-child.md | 31 - .../rules/presence-safe-to-remove.md | 37 - .../rules/pseudo-content-required.md | 28 - .../rules/pseudo-first-line-styling.md | 27 - .../rules/pseudo-hit-target-expansion.md | 31 - .../rules/pseudo-marker-styling.md | 28 - .../rules/pseudo-over-dom-node.md | 32 - .../rules/pseudo-position-relative-parent.md | 33 - .../rules/pseudo-z-index-layering.md | 37 - .../rules/spring-for-gestures.md | 27 - .../rules/spring-for-interruptible.md | 27 - .../rules/spring-params-balanced.md | 29 - .../rules/spring-preserves-velocity.md | 28 - .../rules/staging-dim-background.md | 22 - .../rules/staging-one-focal-point.md | 24 - .../rules/staging-z-index-hierarchy.md | 22 - .../rules/timing-consistent.md | 24 - .../rules/timing-no-entrance-context-menu.md | 22 - .../rules/timing-under-300ms.md | 22 - .../rules/transition-name-cleanup.md | 28 - .../rules/transition-name-required.md | 27 - .../rules/transition-name-unique.md | 24 - .../rules/transition-over-js-library.md | 32 - .../rules/transition-style-pseudo-elements.md | 24 - .../rules/type-antialiased-on-retina.md | 18 - .../type-disambiguation-stylistic-set.md | 15 - .../rules/type-font-display-swap.md | 28 - .../rules/type-justify-with-hyphens.md | 24 - .../rules/type-letter-spacing-uppercase.md | 28 - .../rules/type-no-font-synthesis.md | 18 - .../rules/type-oldstyle-nums-for-prose.md | 21 - .../type-opentype-contextual-alternates.md | 15 - .../rules/type-optical-sizing-auto.md | 25 - .../rules/type-proper-fractions.md | 15 - .../rules/type-slashed-zero.md | 17 - .../rules/type-tabular-nums-for-data.md | 21 - .../rules/type-text-wrap-balance-headings.md | 21 - .../rules/type-text-wrap-pretty.md | 16 - .../rules/type-underline-offset.md | 25 - .../rules/type-variable-weight-continuous.md | 23 - .../rules/ux-aesthetic-usability.md | 32 - .../rules/ux-cognitive-load-reduce.md | 49 -- .../rules/ux-common-region-boundaries.md | 50 -- .../rules/ux-doherty-perceived-speed.md | 29 - .../rules/ux-doherty-under-400ms.md | 30 - .../rules/ux-fitts-hit-area.md | 32 - .../rules/ux-fitts-target-size.md | 31 - .../rules/ux-goal-gradient-progress.md | 33 - .../rules/ux-hicks-minimize-choices.md | 45 - .../rules/ux-jakobs-familiar-patterns.md | 37 - .../rules/ux-millers-chunking.md | 23 - .../rules/ux-pareto-prioritize-features.md | 36 - .../rules/ux-peak-end-finish-strong.md | 35 - .../rules/ux-postels-accept-messy-input.md | 45 - .../rules/ux-pragnanz-simplify.md | 33 - .../rules/ux-progressive-disclosure.md | 41 - .../rules/ux-proximity-grouping.md | 38 - .../rules/ux-serial-position.md | 31 - .../rules/ux-similarity-consistency.md | 35 - .../rules/ux-teslers-complexity.md | 28 - .../rules/ux-uniform-connectedness.md | 43 - .../rules/ux-von-restorff-emphasis.md | 29 - .../rules/ux-zeigarnik-show-incomplete.md | 36 - .../rules/visual-animate-shadow-pseudo.md | 49 -- .../rules/visual-border-alpha-colors.md | 25 - .../rules/visual-button-shadow-anatomy.md | 49 -- .../rules/visual-concentric-radius.md | 40 - .../rules/visual-consistent-spacing-scale.md | 35 - .../rules/visual-layered-shadows.md | 30 - .../rules/visual-no-pure-black-shadow.md | 25 - .../rules/visual-shadow-direction.md | 25 - .../rules/visual-shadow-matches-elevation.md | 23 - .../rules/weight-duration-matches-action.md | 29 - .../rules/weight-match-action.md | 32 - .../skills/web-design-guidelines/SKILL.md | 39 - .../skills/web-quality-audit/SKILL.md | 168 ---- .../web-quality-audit/scripts/analyze.sh | 91 -- .../workflow-skills/assumption-log/SKILL.md | 4 +- .../workflow-skills/error-routing/SKILL.md | 4 +- .../handoff-readability/SKILL.md | 2 +- .../workflow-skills/irreversible-ops/SKILL.md | 2 +- .../workflow-skills/observe-first/SKILL.md | 2 +- .../sf-debug-forensics}/SKILL.md | 18 +- .../sf-human-writing}/SKILL.md | 14 +- .../sf-metric-optimization}/SKILL.md | 34 +- .../sf-repo-orientation}/SKILL.md | 22 +- .../sf-vcs-hygiene}/SKILL.md | 14 +- .../workflow-skills/state-discipline/SKILL.md | 2 +- .../workflow-skills/vertical-slice/SKILL.md | 2 +- src/tests/agents-manifest-contract.test.ts | 213 +++++ 385 files changed, 1116 insertions(+), 23524 deletions(-) create mode 100644 .agents/adapters/.gitkeep rename .agents/{skills/forge-harness/SKILL.md => policies/.gitkeep} (100%) rename .agents/{skills/forge-operating-model/SKILL.md => prompts/.gitkeep} (100%) delete mode 100644 .agents/skills/forge-planning/SKILL.md delete mode 100644 .agents/skills/forge-state/SKILL.md delete mode 100644 .agents/skills/nix-build/SKILL.md delete mode 100644 .agents/skills/smoke-test/SKILL.md rename .agents/skills/forge-autonomous-runtime/SKILL.md => docs/dev/sf-runtime/autonomous-runtime.md (95%) rename .agents/skills/forge-command-surface/SKILL.md => docs/dev/sf-runtime/command-surface.md (96%) create mode 100644 docs/dev/sf-runtime/harness.md create mode 100644 docs/dev/sf-runtime/operating-model.md create mode 100644 docs/dev/sf-runtime/planning.md create mode 100644 docs/dev/sf-runtime/state.md rename {.agents => src/resources/agent-overlays/singularity-forge}/policies/default-safe.yaml (100%) rename {.agents => src/resources/agent-overlays/singularity-forge}/prompts/base.md (100%) rename {.agents => src/resources/agent-overlays/singularity-forge}/prompts/project.md (100%) create mode 100644 src/resources/extensions/sf/tests/auto-prompts-workflow-skills.test.mjs delete mode 100644 src/resources/skills/accessibility/SKILL.md delete mode 100644 src/resources/skills/accessibility/references/WCAG.md delete mode 100644 src/resources/skills/agent-browser/SKILL.md delete mode 100644 src/resources/skills/agent-browser/references/authentication.md delete mode 100644 src/resources/skills/agent-browser/references/commands.md delete mode 100644 src/resources/skills/agent-browser/references/profiling.md delete mode 100644 src/resources/skills/agent-browser/references/proxy-support.md delete mode 100644 src/resources/skills/agent-browser/references/session-management.md delete mode 100644 src/resources/skills/agent-browser/references/snapshot-refs.md delete mode 100644 src/resources/skills/agent-browser/references/video-recording.md delete mode 100755 src/resources/skills/agent-browser/templates/authenticated-session.sh delete mode 100755 src/resources/skills/agent-browser/templates/capture-workflow.sh delete mode 100755 src/resources/skills/agent-browser/templates/form-automation.sh delete mode 100644 src/resources/skills/best-practices/SKILL.md delete mode 100644 src/resources/skills/btw/SKILL.md delete mode 100644 src/resources/skills/code-optimizer/SKILL.md delete mode 100644 src/resources/skills/code-optimizer/references/algorithmic-complexity.md delete mode 100644 src/resources/skills/code-optimizer/references/build-compilation.md delete mode 100644 src/resources/skills/code-optimizer/references/bundle-dependencies.md delete mode 100644 src/resources/skills/code-optimizer/references/caching-memoization.md delete mode 100644 src/resources/skills/code-optimizer/references/concurrency-async.md delete mode 100644 src/resources/skills/code-optimizer/references/config-infra.md delete mode 100644 src/resources/skills/code-optimizer/references/data-structures.md delete mode 100644 src/resources/skills/code-optimizer/references/database-queries.md delete mode 100644 src/resources/skills/code-optimizer/references/dead-code-redundancy.md delete mode 100644 src/resources/skills/code-optimizer/references/error-resilience.md delete mode 100644 src/resources/skills/code-optimizer/references/io-network.md delete mode 100644 src/resources/skills/code-optimizer/references/logging-observability.md delete mode 100644 src/resources/skills/code-optimizer/references/memory-resources.md delete mode 100644 src/resources/skills/code-optimizer/references/rendering-ui.md delete mode 100644 src/resources/skills/code-optimizer/references/security-performance.md delete mode 100644 src/resources/skills/core-web-vitals/SKILL.md delete mode 100644 src/resources/skills/core-web-vitals/references/LCP.md delete mode 100644 src/resources/skills/create-sf-extension/SKILL.md delete mode 100644 src/resources/skills/create-sf-extension/references/compaction-session-control.md delete mode 100644 src/resources/skills/create-sf-extension/references/custom-commands.md delete mode 100644 src/resources/skills/create-sf-extension/references/custom-rendering.md delete mode 100644 src/resources/skills/create-sf-extension/references/custom-tools.md delete mode 100644 src/resources/skills/create-sf-extension/references/custom-ui.md delete mode 100644 src/resources/skills/create-sf-extension/references/events-reference.md delete mode 100644 src/resources/skills/create-sf-extension/references/extension-lifecycle.md delete mode 100644 src/resources/skills/create-sf-extension/references/extensionapi-reference.md delete mode 100644 src/resources/skills/create-sf-extension/references/extensioncontext-reference.md delete mode 100644 src/resources/skills/create-sf-extension/references/key-rules-gotchas.md delete mode 100644 src/resources/skills/create-sf-extension/references/mode-behavior.md delete mode 100644 src/resources/skills/create-sf-extension/references/model-provider-management.md delete mode 100644 src/resources/skills/create-sf-extension/references/packaging-distribution.md delete mode 100644 src/resources/skills/create-sf-extension/references/remote-execution-overrides.md delete mode 100644 src/resources/skills/create-sf-extension/references/state-management.md delete mode 100644 src/resources/skills/create-sf-extension/references/system-prompt-modification.md delete mode 100644 src/resources/skills/create-sf-extension/templates/extension-skeleton.ts delete mode 100644 src/resources/skills/create-sf-extension/templates/stateful-tool-skeleton.ts delete mode 100644 src/resources/skills/create-sf-extension/templates/templates.test.ts delete mode 100644 src/resources/skills/create-sf-extension/workflows/add-capability.md delete mode 100644 src/resources/skills/create-sf-extension/workflows/create-extension.md delete mode 100644 src/resources/skills/create-sf-extension/workflows/debug-extension.md delete mode 100644 src/resources/skills/create-workflow/SKILL.md delete mode 100644 src/resources/skills/create-workflow/references/feature-patterns.md delete mode 100644 src/resources/skills/create-workflow/references/verification-policies.md delete mode 100644 src/resources/skills/create-workflow/references/yaml-schema-v1.md delete mode 100644 src/resources/skills/create-workflow/templates/blog-post-pipeline.yaml delete mode 100644 src/resources/skills/create-workflow/templates/code-audit.yaml delete mode 100644 src/resources/skills/create-workflow/templates/product-tracking-lifecycle.yaml delete mode 100644 src/resources/skills/create-workflow/templates/release-checklist.yaml delete mode 100644 src/resources/skills/create-workflow/templates/workflow-definition.yaml delete mode 100644 src/resources/skills/create-workflow/workflows/create-from-scratch.md delete mode 100644 src/resources/skills/create-workflow/workflows/create-from-template.md delete mode 100644 src/resources/skills/debug-like-expert/SKILL.md delete mode 100644 src/resources/skills/debug-like-expert/references/debugging-mindset.md delete mode 100644 src/resources/skills/debug-like-expert/references/hypothesis-testing.md delete mode 100644 src/resources/skills/debug-like-expert/references/investigation-techniques.md delete mode 100644 src/resources/skills/debug-like-expert/references/verification-patterns.md delete mode 100644 src/resources/skills/debug-like-expert/references/when-to-research.md delete mode 100644 src/resources/skills/frontend-design/SKILL.md delete mode 100644 src/resources/skills/github-workflows/SKILL.md delete mode 100644 src/resources/skills/github-workflows/references/gh/SKILL.md delete mode 100644 src/resources/skills/github-workflows/references/gh/references/issue-stories.md delete mode 100644 src/resources/skills/github-workflows/references/gh/references/labels.md delete mode 100644 src/resources/skills/github-workflows/references/gh/references/milestones.md delete mode 100644 src/resources/skills/github-workflows/references/gh/references/projects-v2.md delete mode 100755 src/resources/skills/github-workflows/references/gh/scripts/experiment_cleanup.py delete mode 100755 src/resources/skills/github-workflows/references/gh/scripts/github_project_setup.py delete mode 100644 src/resources/skills/github-workflows/references/gh/tests/__init__.py delete mode 100644 src/resources/skills/github-workflows/references/gh/tests/test_github_project_setup.py delete mode 100644 src/resources/skills/lint/SKILL.md delete mode 100644 src/resources/skills/make-interfaces-feel-better/SKILL.md delete mode 100644 src/resources/skills/make-interfaces-feel-better/animations.md delete mode 100644 src/resources/skills/make-interfaces-feel-better/performance.md delete mode 100644 src/resources/skills/make-interfaces-feel-better/surfaces.md delete mode 100644 src/resources/skills/make-interfaces-feel-better/typography.md delete mode 100644 src/resources/skills/react-best-practices/README.md delete mode 100644 src/resources/skills/react-best-practices/SKILL.md delete mode 100644 src/resources/skills/react-best-practices/metadata.json delete mode 100644 src/resources/skills/react-best-practices/rules/_sections.md delete mode 100644 src/resources/skills/react-best-practices/rules/_template.md delete mode 100644 src/resources/skills/react-best-practices/rules/advanced-event-handler-refs.md delete mode 100644 src/resources/skills/react-best-practices/rules/advanced-init-once.md delete mode 100644 src/resources/skills/react-best-practices/rules/advanced-use-latest.md delete mode 100644 src/resources/skills/react-best-practices/rules/async-api-routes.md delete mode 100644 src/resources/skills/react-best-practices/rules/async-defer-await.md delete mode 100644 src/resources/skills/react-best-practices/rules/async-dependencies.md delete mode 100644 src/resources/skills/react-best-practices/rules/async-parallel.md delete mode 100644 src/resources/skills/react-best-practices/rules/async-suspense-boundaries.md delete mode 100644 src/resources/skills/react-best-practices/rules/bundle-barrel-imports.md delete mode 100644 src/resources/skills/react-best-practices/rules/bundle-conditional.md delete mode 100644 src/resources/skills/react-best-practices/rules/bundle-defer-third-party.md delete mode 100644 src/resources/skills/react-best-practices/rules/bundle-dynamic-imports.md delete mode 100644 src/resources/skills/react-best-practices/rules/bundle-preload.md delete mode 100644 src/resources/skills/react-best-practices/rules/client-event-listeners.md delete mode 100644 src/resources/skills/react-best-practices/rules/client-localstorage-schema.md delete mode 100644 src/resources/skills/react-best-practices/rules/client-passive-event-listeners.md delete mode 100644 src/resources/skills/react-best-practices/rules/client-swr-dedup.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-batch-dom-css.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-cache-function-results.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-cache-property-access.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-cache-storage.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-combine-iterations.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-early-exit.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-hoist-regexp.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-index-maps.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-length-check-first.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-min-max-loop.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-set-map-lookups.md delete mode 100644 src/resources/skills/react-best-practices/rules/js-tosorted-immutable.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-activity.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-animate-svg-wrapper.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-conditional-render.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-content-visibility.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-hoist-jsx.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-hydration-no-flicker.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-hydration-suppress-warning.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-svg-precision.md delete mode 100644 src/resources/skills/react-best-practices/rules/rendering-usetransition-loading.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-defer-reads.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-dependencies.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-derived-state-no-effect.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-derived-state.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-functional-setstate.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-lazy-state-init.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-memo-with-default-value.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-memo.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-move-effect-to-event.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-simple-expression-in-memo.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-transitions.md delete mode 100644 src/resources/skills/react-best-practices/rules/rerender-use-ref-transient-values.md delete mode 100644 src/resources/skills/react-best-practices/rules/server-after-nonblocking.md delete mode 100644 src/resources/skills/react-best-practices/rules/server-auth-actions.md delete mode 100644 src/resources/skills/react-best-practices/rules/server-cache-lru.md delete mode 100644 src/resources/skills/react-best-practices/rules/server-cache-react.md delete mode 100644 src/resources/skills/react-best-practices/rules/server-dedup-props.md delete mode 100644 src/resources/skills/react-best-practices/rules/server-parallel-fetching.md delete mode 100644 src/resources/skills/react-best-practices/rules/server-serialization.md delete mode 100644 src/resources/skills/repo-map/SKILL.md delete mode 100644 src/resources/skills/review/SKILL.md delete mode 100644 src/resources/skills/test/SKILL.md delete mode 100644 src/resources/skills/userinterface-wiki/SKILL.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/_sections.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/_template.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/a11y-reduced-motion-check.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/a11y-toggle-setting.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/a11y-visual-equivalent.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/a11y-volume-control.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/appropriate-confirmations-only.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/appropriate-errors-warnings.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/appropriate-no-decorative.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/appropriate-no-high-frequency.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/appropriate-no-punishing.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/container-callback-ref.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/container-guard-initial-zero.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/container-no-excessive-use.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/container-overflow-hidden.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/container-transition-delay.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/container-two-div-pattern.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/container-use-resize-observer.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/context-cleanup-nodes.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/context-resume-suspended.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/context-reuse-single.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/design-filter-for-character.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/design-noise-for-percussion.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/design-oscillator-for-tonal.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/duration-max-300ms.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/duration-press-hover.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/duration-shorten-before-curve.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/duration-small-state.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/easing-entrance-ease-out.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/easing-exit-ease-in.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/easing-for-state-change.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/easing-linear-only-progress.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/easing-natural-decay.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/easing-no-linear-motion.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/easing-transition-ease-in-out.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/envelope-exponential-decay.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/envelope-no-zero-target.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/envelope-set-initial-value.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/exit-key-required.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/exit-matches-initial.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/exit-prop-required.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/exit-requires-wrapper.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/impl-default-subtle.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/impl-preload-audio.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/impl-reset-current-time.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/mode-pop-layout-for-lists.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/mode-sync-layout-conflict.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/mode-wait-doubles-duration.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-aria-hidden.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-consistent-viewbox.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-group-variants.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-jump-non-grouped.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-reduced-motion.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-spring-rotation.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-strokelinecap-round.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-three-lines.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/morphing-use-collapsed.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/native-backdrop-styling.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/native-placeholder-styling.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/native-selection-styling.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/nested-consistent-timing.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/nested-propagate-required.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/none-context-menu-entrance.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/none-high-frequency.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/none-keyboard-navigation.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/param-click-duration.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/param-filter-frequency-range.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/param-q-value-range.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/param-reasonable-gain.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/physics-active-state.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/physics-no-excessive-stagger.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/physics-spring-for-overshoot.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/physics-subtle-deformation.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/prefetch-hit-slop.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/prefetch-keyboard-tab.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/prefetch-not-everything.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/prefetch-touch-fallback.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/prefetch-trajectory-over-hover.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/prefetch-use-selectively.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/presence-disable-interactions.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/presence-hook-in-child.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/presence-safe-to-remove.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/pseudo-content-required.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/pseudo-first-line-styling.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/pseudo-hit-target-expansion.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/pseudo-marker-styling.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/pseudo-over-dom-node.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/pseudo-position-relative-parent.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/pseudo-z-index-layering.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/spring-for-gestures.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/spring-for-interruptible.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/spring-params-balanced.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/spring-preserves-velocity.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/staging-dim-background.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/staging-one-focal-point.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/staging-z-index-hierarchy.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/timing-consistent.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/timing-no-entrance-context-menu.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/timing-under-300ms.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/transition-name-cleanup.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/transition-name-required.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/transition-name-unique.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/transition-over-js-library.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/transition-style-pseudo-elements.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-antialiased-on-retina.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-disambiguation-stylistic-set.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-font-display-swap.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-justify-with-hyphens.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-letter-spacing-uppercase.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-no-font-synthesis.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-oldstyle-nums-for-prose.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-opentype-contextual-alternates.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-optical-sizing-auto.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-proper-fractions.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-slashed-zero.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-tabular-nums-for-data.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-text-wrap-balance-headings.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-text-wrap-pretty.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-underline-offset.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/type-variable-weight-continuous.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-aesthetic-usability.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-cognitive-load-reduce.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-common-region-boundaries.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-doherty-perceived-speed.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-doherty-under-400ms.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-fitts-hit-area.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-fitts-target-size.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-goal-gradient-progress.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-hicks-minimize-choices.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-jakobs-familiar-patterns.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-millers-chunking.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-pareto-prioritize-features.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-peak-end-finish-strong.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-postels-accept-messy-input.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-pragnanz-simplify.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-progressive-disclosure.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-proximity-grouping.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-serial-position.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-similarity-consistency.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-teslers-complexity.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-uniform-connectedness.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-von-restorff-emphasis.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/ux-zeigarnik-show-incomplete.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-animate-shadow-pseudo.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-border-alpha-colors.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-button-shadow-anatomy.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-concentric-radius.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-consistent-spacing-scale.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-layered-shadows.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-no-pure-black-shadow.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-shadow-direction.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/visual-shadow-matches-elevation.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/weight-duration-matches-action.md delete mode 100644 src/resources/skills/userinterface-wiki/rules/weight-match-action.md delete mode 100644 src/resources/skills/web-design-guidelines/SKILL.md delete mode 100644 src/resources/skills/web-quality-audit/SKILL.md delete mode 100644 src/resources/skills/web-quality-audit/scripts/analyze.sh rename src/resources/{skills/forensics => workflow-skills/sf-debug-forensics}/SKILL.md (83%) rename src/resources/{skills/human-writing => workflow-skills/sf-human-writing}/SKILL.md (82%) rename src/resources/{skills/autoresearch => workflow-skills/sf-metric-optimization}/SKILL.md (57%) rename {.agents/skills/repo-map => src/resources/workflow-skills/sf-repo-orientation}/SKILL.md (70%) rename src/resources/{skills/repo-vcs => workflow-skills/sf-vcs-hygiene}/SKILL.md (73%) create mode 100644 src/tests/agents-manifest-contract.test.ts diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md index e7b0367e3..eef2eaa0a 100644 --- a/.agents/AGENTS.md +++ b/.agents/AGENTS.md @@ -1,33 +1,52 @@ # .agents/ -Agent configuration for this repository following the -[AGENTS-1 spec](https://github.com/agentsfolder/spec). +Agent configuration for this repository. The `.agents/` layout tracks the +[agents folder convention](https://github.com/agentsfolder/spec), while skills +inside it follow the [open Agent Skills format](https://agentskills.io/specification): +each skill is a directory with `SKILL.md` frontmatter and Markdown +instructions. + +SF treats this as `sf-agents-overlay/v1` until the external `.agents` spec +settles. The stable contract is: + +- `.agents/manifest.yaml` is the repo-owned machine index. +- `.agents/prompts/`, `.agents/policies/`, `.agents/modes/`, `.agents/scopes/`, + `.agents/profiles/`, and `.agents/adapters/` are optional project override + inputs. +- `.agents/skills//SKILL.md` is the canonical skill payload. +- `.agents/skills//skill.yaml` may exist as generated or adapter metadata, + but it is not the instruction source. +- `.agents/state/state.yaml` is local-only and ignored. +- `.sf/` remains SF runtime state; structured SF state is DB-first. This folder is the **override and extension layer only**. SF's built-in defaults (modes, skills, policies) apply automatically. Files here exist only when the project needs to override or add something. +This mirrors Copilot-style project customization: repository-owned agent +instructions and optional overrides live in the repo, while product-shipped +defaults live outside the repo overlay. For SF, bundled user-visible skills are +sourced from `src/resources/skills/`; hidden workflow pattern skills are sourced +from `src/resources/workflow-skills/`; bundled default prompts and policies are +sourced from `src/resources/agent-overlays/singularity-forge/`. `.agents/` +only adds project-specific overrides. + ## Structure ``` .agents/ AGENTS.md ← this file - manifest.yaml ← specVersion, defaults, enabled skills/policies + manifest.yaml ← SF overlay schema; no enabled overrides by default prompts/ - base.md ← injected into every agent turn (iron law, DB-first, key pointers) - project.md ← SF-specific context (modes, state, build commands, source layout) - snippets/ ← reusable prompt fragments (empty — no project snippets yet) + .gitkeep ← project prompt overrides only + snippets/ ← project prompt fragments only modes/ ← project mode OVERRIDES only (empty — SF built-ins apply) policies/ - default-safe.yaml ← conservative policy: confirm destructive ops, deny secrets paths - skills/ ← project-specific skills + built-in overrides (same name = override) - forge-autonomous-runtime/ ← explains SF autonomous loop, UOK gates, recovery paths - forge-command-surface/ ← SF slash commands, browser command parity, headless dispatch - nix-build/ ← build any @singularity-forge/* package via nix develop - sf-wiki/ ← override of built-in sf-wiki: use UPPERCASE filenames (.sf/ convention) - smoke-test/ ← run sf-run smoke tests (--version, --help, --print) + .gitkeep ← project policy overrides only + skills/ ← optional project user skills + built-in overrides (empty by default) scopes/ ← path-based config overrides (empty) profiles/ ← named overlays e.g. "ci", "dev" (empty) + adapters/ ← optional projection targets (absent until needed) schemas/ ← generated JSON schemas (not committed) state/ .gitignore ← excludes state.yaml (per-developer convenience, never committed) @@ -38,12 +57,13 @@ only when the project needs to override or add something. To override a built-in mode or skill, add a file with the **same name**: ``` -# Override built-in sf-wiki skill -.agents/skills/sf-wiki/SKILL.md +# Override a product workflow pattern for this repo +.agents/skills/sf-repo-orientation/SKILL.md # Override built-in build mode .agents/modes/build.md ``` -Built-in defaults (ask, build, autonomous modes; default-safe policy; all SF -system skills) are provided by SF and do not need to be listed here. +Built-in defaults (ask, build, autonomous modes; default-safe policy; bundled +prompts; bundled user skills; hidden workflow pattern skills) are provided by SF from +`src/resources/` and do not need to be listed here. diff --git a/.agents/adapters/.gitkeep b/.agents/adapters/.gitkeep new file mode 100644 index 000000000..d4881f80b --- /dev/null +++ b/.agents/adapters/.gitkeep @@ -0,0 +1,2 @@ +# Projection adapter configs belong here when this repo needs to render +# `.agents/` into agent-native files. Empty by default. diff --git a/.agents/manifest.yaml b/.agents/manifest.yaml index 2955c7da7..df755d553 100644 --- a/.agents/manifest.yaml +++ b/.agents/manifest.yaml @@ -1,30 +1,43 @@ -# .agents/ canonical agent configuration -# Spec: https://github.com/agentsfolder/spec +# .agents/ SF repo overlay manifest +# Layout target: https://github.com/agentsfolder/spec +# Skill source: https://agentskills.io/specification # -# Status: pre-1.0 spec adoption — schema may shift. Pin specVersion; -# track upstream for breaking changes. +# Status: SF-specific repo overlay aligned with the emerging .agents folder +# convention. This file indexes optional repo-owned overrides only. Bundled SF +# defaults, default prompts, default policies, and hidden pattern skills live in +# src/resources. -specVersion: "0.1.0" +specVersion: "1.0.0" defaults: mode: build - policy: default-safe - -enabled: - modes: [] # no project overrides; SF built-in modes (ask/build/autonomous) apply - policies: - - default-safe - skills: - - forge-autonomous-runtime - - forge-command-surface - - nix-build - - sf-wiki - - smoke-test + policy: bundled:default-safe resolution: enableUserOverlay: false denyOverridesAllow: true onConflict: error + precedence: + - project + - global + - bundled + +prompts: {} + +modes: [] + +adapters: {} + +policies: {} + +skills: {} + +enabled: + modes: [] # no project overrides; SF built-in modes (ask/build/autonomous) apply + adapters: [] # no generated projection targets yet + policies: [] + prompts: [] + skills: [] project: name: singularity-forge @@ -38,6 +51,47 @@ project: frameworks: [] x: + sf: + schemaVersion: sf-agents-overlay/v1 + contract: + canonicalRepoOverlay: .agents/manifest.yaml + canonicalSkillPayload: SKILL.md + optionalSkillMetadata: skill.yaml + skillMetadataRequired: false + bundledResourceRoot: ../src/resources/ + bundledUserSkillRoot: ../src/resources/skills/ + bundledWorkflowSkillRoot: ../src/resources/workflow-skills/ + bundledAgentOverlayRoot: ../src/resources/agent-overlays/singularity-forge/ + runtimeStateRoot: ../.sf/ + runtimeStateSourceOfTruth: false + projectSkillRootPurpose: optional repo-local user skills and overrides only + projectOverlayPurpose: optional repo-local overrides only + projectLearningTarget: reviewed repo-local .agents overrides proposed from .sf evidence + layoutFormat: + name: agents-folder + spec: https://github.com/agentsfolder/spec + role: repo-overlay-layout + canonicalSkillFormat: + name: agent-skills + spec: https://agentskills.io/specification + entrypoint: SKILL.md + agentsFolderSkillYaml: + status: compatibility-adapter + note: >- + agentsfolder/agents-cli currently loads .agents/skills/*/skill.yaml + while the AGENTS-1 README names SKILL.yaml and the + broader Agent Skills ecosystem uses SKILL.md. SF treats SKILL.md as + canonical and may generate/read skill.yaml as compatibility metadata, + but does not make it the source of truth. + runtimeGenerated: + repoMap: + path: ../.sf/repo-map/ + gitignored: true + sourceOfTruth: false + traces: + path: ../.sf/traces/ + gitignored: true + sourceOfTruth: false centralcloud: legacy_pointers: - AGENTS.md diff --git a/.agents/skills/forge-harness/SKILL.md b/.agents/policies/.gitkeep similarity index 100% rename from .agents/skills/forge-harness/SKILL.md rename to .agents/policies/.gitkeep diff --git a/.agents/skills/forge-operating-model/SKILL.md b/.agents/prompts/.gitkeep similarity index 100% rename from .agents/skills/forge-operating-model/SKILL.md rename to .agents/prompts/.gitkeep diff --git a/.agents/skills/forge-planning/SKILL.md b/.agents/skills/forge-planning/SKILL.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/.agents/skills/forge-state/SKILL.md b/.agents/skills/forge-state/SKILL.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/.agents/skills/nix-build/SKILL.md b/.agents/skills/nix-build/SKILL.md deleted file mode 100644 index bb97901a3..000000000 --- a/.agents/skills/nix-build/SKILL.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -name: nix-build -description: Build any @singularity-forge/* package (or the full stack) via nix develop. Pass a package name like "pi-coding-agent", "native", "daemon", or "all" for a full core build. ---- - -All build commands in this repo must run inside `nix develop`. Never use bare cargo/rustc. - -For a single package: -``` -nix develop --command bash -c "npm run --workspace=@singularity-forge/ build" -``` - -For the full core build (native + all TS packages): -``` -nix develop --command bash -c "npm run build:core" -``` - -For typecheck only: -``` -nix develop --command bash -c "tsc --noEmit -p tsconfig.json" -``` - -For extensions typecheck: -``` -nix develop --command bash -c "tsc --noEmit -p tsconfig.extensions.json" -``` diff --git a/.agents/skills/smoke-test/SKILL.md b/.agents/skills/smoke-test/SKILL.md deleted file mode 100644 index dc2c016cf..000000000 --- a/.agents/skills/smoke-test/SKILL.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: smoke-test -description: Run the standard sf-run smoke tests (--version, --help, --print). All three must pass before shipping a build. ---- - -#!/bin/bash -set -e -echo "=== --version ===" -node dist/loader.js --version - -echo "=== --help (first 5 lines) ===" -node dist/loader.js --help 2>&1 | head -5 - -echo "=== --print (graceful degradation) ===" -node dist/loader.js --print 2>&1 | head -5 - -echo "All smoke tests passed." diff --git a/.gitignore b/.gitignore index 7e8e1874d..8b4b904bb 100644 --- a/.gitignore +++ b/.gitignore @@ -107,16 +107,27 @@ repowise.db .sf/interactive.lock .sf/interactive.lock.d/ # SQLite WAL/SHM are ephemeral checkpoint files — only the .db is durable. +.sf/metrics.db .sf/metrics.db-wal .sf/metrics.db-shm .sf/sf.db-wal .sf/sf.db-shm +# DB backups are local recovery artifacts created by migrations/maintenance. +.sf/backups/db/ +# Generated SF runtime projections, caches, reports, and recovery evidence. +.sf/graphs/ +.sf/model-catalog/ +.sf/model-performance.json +.sf/recovery/ +.sf/reflection/ +.sf/safety/ +.sf/slice-routing.json +.sf/triage/decisions/ +.sf/repo-map/ # Per-dispatch trace files accumulate one-per-request and are runtime-only. # Consumers (sf-db-gates, adaptive verification policy) read by mtime window # (24h–30d) — on-disk retention is needed, but git tracking is not. -.sf/traces/pre-dispatch:*.jsonl -.sf/traces/finalize:*.jsonl -.sf/traces/guard:*.jsonl +.sf/traces/*.jsonl # `latest` is a symlink retargeted on every dispatch — pure git noise. .sf/traces/latest test_output.log diff --git a/docs/dev/FILE-SYSTEM-MAP.md b/docs/dev/FILE-SYSTEM-MAP.md index 2d740c4a1..75ffb437f 100644 --- a/docs/dev/FILE-SYSTEM-MAP.md +++ b/docs/dev/FILE-SYSTEM-MAP.md @@ -667,24 +667,20 @@ | Skill Directory | System Label(s) | Description | |-----------------|-----------------|-------------| -| react-best-practices/ | Skills | React development patterns (62 files) | -| userinterface-wiki/ | Skills | UI/UX guidelines and component reference (155 files) | -| create-skill/ | Skills | Skill creation scaffolding and templates (25 files) | -| create-sf-extension/ | Skills, Extensions | SF extension scaffolding (22 files) | -| code-optimizer/ | Skills | Performance optimization techniques (16 files) | -| agent-browser/ | Skills, Browser Tools | Browser automation guidance (11 files) | -| github-workflows/ | Skills | GitHub Actions workflow patterns (10 files) | -| debug-like-expert/ | Skills | Advanced debugging techniques (6 files) | -| make-interfaces-feel-better/ | Skills | UI/UX improvement patterns (5 files) | -| accessibility/ | Skills | WCAG and accessibility standards | -| core-web-vitals/ | Skills | Web performance metrics guidance | -| web-quality-audit/ | Skills | Quality audit procedures | -| best-practices/ | Skills | General development best practices | -| frontend-design/ | Skills | Frontend design principles | -| lint/ | Skills | Code linting standards | -| review/ | Skills | Code review guidelines | -| test/ | Skills | Testing strategies and patterns | -| web-design-guidelines/ | Skills | Web design principles | +| create-skill/ | User-visible Skills | Skill creation scaffolding and templates | + +### src/resources/workflow-skills/ + +| Skill Directory | System Label(s) | Description | +|-----------------|-----------------|-------------| +| assumption-log/, context-lean/, error-routing/, handoff-readability/, irreversible-ops/, observe-first/, state-discipline/, vertical-slice/ | Workflow Skills | Always-on hidden autonomy constraints. Not shown in the user skill catalog. | +| sf-debug-forensics/, sf-human-writing/, sf-metric-optimization/, sf-repo-orientation/, sf-vcs-hygiene/ | Workflow Skills | Automatic workflow helpers selected by context or explicit workflow preference. | + +### docs/dev/sf-runtime/ + +| File | System Label(s) | Description | +|------|-----------------|-------------| +| autonomous-runtime.md, command-surface.md, harness.md, operating-model.md, planning.md, state.md | Contributor Docs | SF maintainer references moved out of workflow skills because they are documentation, not runtime-routed skills. | --- diff --git a/docs/dev/generated-artifact-policy.md b/docs/dev/generated-artifact-policy.md index 86724ade9..134e399ed 100644 --- a/docs/dev/generated-artifact-policy.md +++ b/docs/dev/generated-artifact-policy.md @@ -6,15 +6,83 @@ explicitly promotes them into durable project documentation. ## Default Locations - `.sf/` stores SF-local operational state, generated harness notes, scaffold - manifests, runtime caches, locks, and temporary agent files. + manifests, runtime caches, locks, temporary agent files, and generated + orientation caches such as `.sf/repo-map/`. - `docs/plans/`, `docs/specs/`, and `docs/adr/` store promoted or generated human-facing exports for review and git history. +- `docs/generated/` stores explicitly promoted generated documentation when a + project wants a generated artifact in version control. - Generated docs may change by design. Git keeps their human-facing history; SF-owned operational history belongs in `.sf`/SQLite when runtime replay, ledgers, memory, or drift analysis matter. - Root files such as `AGENTS.md`, `ARCHITECTURE.md`, and `.siftignore` are allowed only when they are part of the versioned scaffold contract. +## Resource Layers + +SF follows the same separation as Copilot-style agent customization: + +| Layer | Path | Git ownership | Purpose | +|---|---|---|---| +| Bundled SF resources | `src/resources/skills/`, `src/resources/workflow-skills/`, `src/resources/agent-overlays/`, `src/resources/extensions/sf/prompts/`, `src/resources/extensions/sf/` | tracked source | Product-shipped defaults. Change these to change SF itself. Workflow skills are hidden system patterns, not a general skill catalog. | +| Repo agent overlay | `.agents/` | tracked project policy | Project-owned prompts, policies, and optional user skill overrides. Same-name skills override non-locked bundled skills. | +| Repo instructions | `AGENTS.md`, `CLAUDE.md`, `.github/copilot-instructions.md`, `.github/instructions/*.instructions.md` | tracked project policy | Agent-facing repo guidance. Keep short, durable, and non-runtime. | +| Runtime generated context | `.sf/repo-map/`, `.sf/traces/`, `.sf/backups/`, `.sf/metrics.db*` | gitignored | Local cache, observability, recovery, and orientation. Safe to delete/regenerate. | +| Promoted generated docs | `docs/generated/` | tracked after review | Durable generated docs that humans chose to version. | + +`.sf/repo-map/` is not a source of truth. It is a generated context cache for +agent orientation. If a repo-map page becomes valuable as documentation, promote +it to `docs/generated/repo-map/` or rewrite it into normal `docs/`. + +## Prompt and Instruction Layers + +Prompt resources follow the same split: + +- **Built-in prompts:** `src/resources/extensions/sf/prompts/` and other + bundled resource directories. These ship with SF and should be edited only + when changing product behavior. +- **Built-in repo defaults:** `src/resources/agent-overlays/` contains product + defaults that SF ships, including default repo prompts and default policies. +- **Repo prompts and instructions:** `.agents/prompts/`, root `AGENTS.md`, + root `CLAUDE.md`, and compatible tool files such as + `.github/copilot-instructions.md`. `.agents/prompts/` is for repo-owned + overrides only; root instruction files remain durable human-readable pointers. +- **Path-specific instructions:** use repo instruction files when behavior + should apply only to part of the tree. Keep them stable and reviewable. +- **Generated context:** `.sf/repo-map/` and other `.sf/` runtime outputs are + not prompt source. They may be injected as context when fresh, but they are + ignored and regenerable. + +Do not promote generated `.sf` context by copying it into prompt overlays +verbatim. Summarize the durable rule, link the canonical source, and keep the +overlay short enough to be loaded every run. + +## SF `.agents` Overlay + +Until the external `.agents` specs settle, this repo uses +`sf-agents-overlay/v1`: + +- `.agents/manifest.yaml` is the repo-owned machine index for optional prompt, + policy, mode, adapter, and project skill overrides. +- `.agents/prompts/`, `.agents/policies/`, `.agents/modes/`, + `.agents/adapters/`, `.agents/scopes/`, and `.agents/profiles/` are empty by + default. Defaults live in `src/resources/`. +- `.agents/skills//SKILL.md` is the canonical skill payload and follows + the Agent Skills specification. +- `.agents/skills/` is empty by default. SF product-owned user skills live under + `src/resources/skills/`; automatic workflow guidance lives under + `src/resources/workflow-skills/` as hidden system pattern skills. +- SF self-learning is per repo: runtime evidence and candidate variants belong + in `.sf` / SQLite first, reviewed repo-specific improvements are proposed as + `.agents/` overrides, and bundled defaults under `src/resources/` change only + when the improvement is product-wide. +- `.agents/skills//skill.yaml` is optional compatibility metadata for + projection tools. It may point at `SKILL.md`, but it must not replace it as + the instruction source. +- `.agents/state/state.yaml` is local convenience state and must remain + gitignored. +- `.sf/` remains SF runtime state. Structured SF state stays DB-first. + ## Harness Generated harness material belongs under `.sf/harness/`. diff --git a/.agents/skills/forge-autonomous-runtime/SKILL.md b/docs/dev/sf-runtime/autonomous-runtime.md similarity index 95% rename from .agents/skills/forge-autonomous-runtime/SKILL.md rename to docs/dev/sf-runtime/autonomous-runtime.md index 4409603cd..3fb73aa1e 100644 --- a/.agents/skills/forge-autonomous-runtime/SKILL.md +++ b/docs/dev/sf-runtime/autonomous-runtime.md @@ -1,9 +1,9 @@ --- -name: forge-autonomous-runtime +name: sf-autonomous-runtime description: Explains SF autonomous loop, UOK gates, installed-runtime drift, and recovery paths. --- -# forge-autonomous-runtime +# SF Autonomous Runtime ## Context diff --git a/.agents/skills/forge-command-surface/SKILL.md b/docs/dev/sf-runtime/command-surface.md similarity index 96% rename from .agents/skills/forge-command-surface/SKILL.md rename to docs/dev/sf-runtime/command-surface.md index 5df69b699..3a9f24849 100644 --- a/.agents/skills/forge-command-surface/SKILL.md +++ b/docs/dev/sf-runtime/command-surface.md @@ -1,9 +1,9 @@ --- -name: forge-command-surface +name: sf-command-surface description: Use when changing SF slash commands, browser command parity, or headless command dispatch. --- -# forge-command-surface +# SF Command Surface ## When to Use diff --git a/docs/dev/sf-runtime/harness.md b/docs/dev/sf-runtime/harness.md new file mode 100644 index 000000000..082b26ccd --- /dev/null +++ b/docs/dev/sf-runtime/harness.md @@ -0,0 +1,15 @@ +--- +name: sf-harness +description: Use when changing SF harness behavior, generated evidence, verification loops, or repo-native harness boundaries. +--- + +# SF Harness + +Use this only for SF harness changes in this repository. + +## Rules + +- Keep generated harness material under `.sf/harness/` unless explicitly promoted. +- Do not create tracked top-level `harness/` files during normal runtime. +- Add executable evidence before claiming a harness behavior works. +- Keep verification paths narrow and reproducible. diff --git a/docs/dev/sf-runtime/operating-model.md b/docs/dev/sf-runtime/operating-model.md new file mode 100644 index 000000000..7753e670b --- /dev/null +++ b/docs/dev/sf-runtime/operating-model.md @@ -0,0 +1,18 @@ +--- +name: sf-operating-model +description: Use when changing SF operating-model vocabulary, surfaces, protocols, output formats, run control, or permission-profile boundaries. +--- + +# SF Operating Model + +Use this when editing SF operating-model docs or code paths. + +## Terms + +- Surface: TUI, CLI, web, editor, or machine entrypoint. +- Protocol: ACP, RPC, stdio JSON-RPC, HTTP, or wire transport. +- Output format: text, JSON, or stream JSON. +- Run control: manual, assisted, supervised, or autonomous. +- Permission profile: restricted, normal, trusted, or unrestricted. + +Keep these terms separate in plans, docs, prompts, and API names. diff --git a/docs/dev/sf-runtime/planning.md b/docs/dev/sf-runtime/planning.md new file mode 100644 index 000000000..7f5634628 --- /dev/null +++ b/docs/dev/sf-runtime/planning.md @@ -0,0 +1,15 @@ +--- +name: sf-planning +description: Use when changing SF milestone, slice, task, backlog, promotion, or spec-first planning behavior. +--- + +# SF Planning + +Use this for SF planning-state changes in this repository. + +## Rules + +- SQLite `.sf/sf.db` is canonical when ordering, joins, validation, or status matter. +- Plans must state purpose before implementation detail. +- Promote durable human-facing artifacts into `docs/plans/`, `docs/specs/`, or `docs/adr/`. +- Runtime planning drafts stay under `.sf/` and remain gitignored unless promoted. diff --git a/docs/dev/sf-runtime/state.md b/docs/dev/sf-runtime/state.md new file mode 100644 index 000000000..64f61a91b --- /dev/null +++ b/docs/dev/sf-runtime/state.md @@ -0,0 +1,16 @@ +--- +name: sf-state +description: Use when changing SF state ownership, DB-first runtime state, generated artifacts, or .sf/.agents boundary rules. +--- + +# SF State + +Use this for SF state-boundary work in this repository. + +## Rules + +- `.sf/sf.db` is the canonical structured runtime store. +- `.sf/` runtime files are generated projections, logs, recovery inputs, or caches. +- `.agents/` is repo-owned agent overlay configuration, not runtime state. +- `src/resources/` owns bundled SF defaults. +- Do not commit generated `.sf` runtime churn. diff --git a/docs/specs/agent-mode-system.md b/docs/specs/agent-mode-system.md index 52c3974e0..11d0e2e6c 100644 --- a/docs/specs/agent-mode-system.md +++ b/docs/specs/agent-mode-system.md @@ -435,8 +435,8 @@ Parallel workers must stay worktree-isolated and report heartbeat/status into ```yaml --- -name: forge-command-surface -description: Use when changing SF slash commands, browser command parity, or headless command dispatch. +name: sf-debug-forensics +description: Post-mortem a failed SF autonomous mode run from persisted runtime evidence. user-invocable: true model-invocable: true side-effects: code-edits @@ -456,9 +456,9 @@ Fields: | Type | Example | `model-invocable` | |------|---------|-------------------| -| Background knowledge | `forge-autonomous-runtime` | true | +| Background knowledge | `sf-repo-orientation` | true | | User tool | `production-deploy` | false | -| Shared capability | `forge-command-surface` | true | +| Shared capability | `sf-debug-forensics` | true | Dangerous skills (`production-mutation`) are never model-invoked by default. diff --git a/docs/user-docs/commands.md b/docs/user-docs/commands.md index 12c348389..735e665ba 100644 --- a/docs/user-docs/commands.md +++ b/docs/user-docs/commands.md @@ -92,7 +92,7 @@ See [Parallel Orchestration](./parallel-orchestration.md) for full documentation | Command | Description | |---------|-------------| -| `/workflow new` | Create a new workflow definition (via skill) | +| `/workflow new` | Show where to create and validate a workflow definition | | `/workflow run ` | Create a run and start autonomous mode | | `/workflow list` | List workflow runs | | `/workflow validate ` | Validate a workflow definition YAML | diff --git a/docs/user-docs/configuration.md b/docs/user-docs/configuration.md index 236e11533..2cd07b53f 100644 --- a/docs/user-docs/configuration.md +++ b/docs/user-docs/configuration.md @@ -617,9 +617,9 @@ Skill routing preferences: ```yaml always_use_skills: - - debug-like-expert + - my-debug-skill prefer_skills: - - frontend-design + - my-frontend-skill avoid_skills: [] ``` @@ -634,7 +634,7 @@ skill_rules: - when: task involves authentication use: [clerk] - when: frontend styling work - prefer: [frontend-design] + prefer: [my-frontend-skill] - when: working with legacy code avoid: [aggressive-refactor] ``` @@ -808,7 +808,7 @@ git: skill_discovery: suggest skill_staleness_days: 60 # Skills unused for N days get deprioritized (0 = disabled) always_use_skills: - - debug-like-expert + - my-debug-skill skill_rules: - when: task involves authentication use: [clerk] diff --git a/docs/user-docs/skills.md b/docs/user-docs/skills.md index 292ad5e61..366c7b282 100644 --- a/docs/user-docs/skills.md +++ b/docs/user-docs/skills.md @@ -6,14 +6,35 @@ Skills follow the open [Agent Skills standard](https://agentskills.io/) and are ## Skill Directories -SF reads skills from two locations, in priority order: +SF has three user skill layers: + +| Layer | Location | Scope | Description | +|---|---|---|---| +| Bundled user-visible | `src/resources/skills/` | SF product | Built into SF releases. Only `create-skill` is listed as a default user skill. | +| Global | `~/.agents/skills/` | User | Shared across projects and compatible agents. | +| Project | `.agents/skills/` | Repo | Optional project-specific user skills and overrides, committable to version control. | + +At runtime, SF resolves user/project skills over bundled defaults when names +collide. This mirrors Copilot-style project skills: `.agents/skills/` is a +repo-owned customization layer, not where SF built-ins live. + +For default releases, the only bundled skill shown to users is `create-skill`. +Internal automatic workflow guidance is modeled as hidden system pattern skills +under `src/resources/workflow-skills/`. That directory is intentionally small: +core workflow constraints, SF runtime/planning/state patterns, and automatic +workflow helpers such as `sf-repo-orientation`, `sf-debug-forensics`, +`sf-metric-optimization`, `sf-human-writing`, and `sf-vcs-hygiene`. They use the +`SKILL.md` shape so SF can test and evolve them like Hermes-style pattern +packages, but they are not listed in the user skill catalog. + +SF reads user and project skills from these portable locations: | Location | Scope | Description | |-----------------------------------|---------|----------------------------------------------------------| | `~/.agents/skills/` | Global | Shared across all projects and all compatible agents | | `.agents/skills/` (project root) | Project | Project-specific skills, committable to version control | -Global skills take precedence over project skills when names collide. +Global/project skills take precedence over bundled skills when names collide. > **Migration from `~/.sf/agent/skills/`:** On first launch after upgrading, SF automatically copies skills from the legacy `~/.sf/agent/skills/` directory to `~/.agents/skills/`. The old directory is preserved for backward compatibility. @@ -100,27 +121,29 @@ Control which skills are used via preferences: --- version: 1 always_use_skills: - - debug-like-expert + - my-debug-skill prefer_skills: - - frontend-design + - my-frontend-skill avoid_skills: - security-docker skill_rules: - when: task involves Clerk authentication use: [clerk] - when: frontend styling work - prefer: [frontend-design] + prefer: [my-frontend-skill] --- ``` ### Resolution Order Skills can be referenced by: -1. **Bare name** — e.g., `frontend-design` → scans `~/.agents/skills/` and project `.agents/skills/` +1. **Bare name** — e.g., `my-frontend-skill` → scans `~/.agents/skills/` and project `.agents/skills/` 2. **Absolute path** — e.g., `/Users/you/.agents/skills/my-skill/SKILL.md` 3. **Directory path** — e.g., `~/custom-skills/my-skill` → looks for `SKILL.md` inside -Global skills (`~/.agents/skills/`) take precedence over project skills (`.agents/skills/`). +Project skills (`.agents/skills/`) take precedence over global skills +(`~/.agents/skills/`) for the same name. Global skills take precedence over +non-locked bundled defaults. ## Custom Skills @@ -143,7 +166,28 @@ Place skills in your project for project-specific guidance: SKILL.md ``` -Project-local skills can be committed to version control so team members share the same skill set. +Project-local skills can be committed to version control so team members share +the same skill set. Do not put SF product-owned workflow guidance here; +product-wide defaults belong in `src/resources/workflow-skills/`. A repo may +still add a same-name `.agents/skills//SKILL.md` file to override a +non-locked system pattern for that repo. + +### Learning and Overrides + +SF self-learning is per repo. Runtime evidence, traces, and candidate variants +belong in `.sf` / SQLite first. Reviewed repo-specific improvements are proposed +as `.agents/` overrides. Bundled defaults under `src/resources/` are changed +only when the improvement is generally useful across projects. + +### `SKILL.md` and `skill.yaml` + +`SKILL.md` is the canonical skill payload. It contains the frontmatter and +Markdown instructions that compatible agents load. + +Some projection tools also use `skill.yaml` for resolver metadata such as +activation mode, interface, requirements, or contracts. In SF, that file is +optional compatibility metadata. It should point at `SKILL.md` when present and +must not duplicate or replace the model-facing instructions. ## Skill Lifecycle Management diff --git a/src/headless-context.ts b/src/headless-context.ts index e38d4554e..678fb68e4 100644 --- a/src/headless-context.ts +++ b/src/headless-context.ts @@ -271,10 +271,10 @@ function collectAutoBootstrapFiles(basePath: string): string[] { } } - // Include .sf/wiki/*.md pages — excluded from the general walk because - // .sf is in AUTO_BOOTSTRAP_EXCLUDED_DIRS, but wiki pages are high-value - // orientation context that should always be available to new agents. - for (const path of collectWikiFiles(basePath)) { + // Include .sf/repo-map/*.md pages — excluded from the general walk because + // .sf is in AUTO_BOOTSTRAP_EXCLUDED_DIRS, but repo-map pages are high-value + // generated orientation context that should always be available to new agents. + for (const path of collectRepoMapFiles(basePath)) { if (!seen.has(path)) { seen.add(path); files.push(path); @@ -290,18 +290,18 @@ function collectAutoBootstrapFiles(basePath: string): string[] { return files; } -function collectWikiFiles(basePath: string): string[] { - const wikiDir = join(basePath, ".sf", "wiki"); +function collectRepoMapFiles(basePath: string): string[] { + const repoMapDir = join(basePath, ".sf", "repo-map"); let entries: Dirent[]; try { - entries = readdirSync(wikiDir, { withFileTypes: true }) as Dirent[]; + entries = readdirSync(repoMapDir, { withFileTypes: true }) as Dirent[]; } catch { return []; } return entries .filter((e) => e.isFile() && e.name.toLowerCase().endsWith(".md")) .sort((a, b) => a.name.localeCompare(b.name)) - .map((e) => join(wikiDir, e.name)); + .map((e) => join(repoMapDir, e.name)); } function existsMarkdownFile(path: string): boolean { diff --git a/src/headless-triage.ts b/src/headless-triage.ts index 151df33af..f49165dee 100644 --- a/src/headless-triage.ts +++ b/src/headless-triage.ts @@ -520,11 +520,21 @@ export async function runTriageApply( const traceWriterModule = (await jiti.import( sfExtensionPath("uok/trace-writer"), )) as { - appendTraceEventRequired: ( + appendTraceEvent?: ( basePath: string, traceId: string, event: Record, ) => void; + appendTraceEventRequired?: ( + basePath: string, + traceId: string, + event: Record, + ) => void; + readTraceEvents?: ( + basePath: string, + type: string, + windowHours?: number, + ) => Array>; }; // surface: "headless" - runTriageApply is always operator-invoked @@ -550,35 +560,55 @@ export async function runTriageApply( if (!uokContext) { return new Error("buildUokRunContext returned null for triage --apply"); } + const event = { + type: "gate_run", + traceId: uokContext.traceId, + turnId: `triage-apply:${gateId}`, + gateId, + gateType: "quality-gate", + outcome, + failureClass: + outcome === "fail" + ? "policy" + : outcome === "manual-attention" + ? "manual-attention" + : "none", + rationale, + attempt: 1, + maxAttempts: 1, + retryable: false, + evaluatedAt: new Date().toISOString(), + durationMs: 0, + // Canonical UOK run context. status uok reads these from + // trace events (slice 3a addition) so the gate + // classifies as "ok" without needing a quality_gates parent + // FK row to exist. + surface: uokContext.surface, + runControl: uokContext.runControl, + permissionProfile: uokContext.permissionProfile, + ...extra, + }; try { - traceWriterModule.appendTraceEventRequired(cwd, flowId, { - type: "gate_run", - traceId: uokContext.traceId, - turnId: `triage-apply:${gateId}`, - gateId, - gateType: "quality-gate", - outcome, - failureClass: - outcome === "fail" - ? "policy" - : outcome === "manual-attention" - ? "manual-attention" - : "none", - rationale, - attempt: 1, - maxAttempts: 1, - retryable: false, - evaluatedAt: new Date().toISOString(), - durationMs: 0, - // Canonical UOK run context. status uok reads these from - // trace events (slice 3a addition) so the gate - // classifies as "ok" without needing a quality_gates parent - // FK row to exist. - surface: uokContext.surface, - runControl: uokContext.runControl, - permissionProfile: uokContext.permissionProfile, - ...extra, - }); + if (typeof traceWriterModule.appendTraceEventRequired === "function") { + traceWriterModule.appendTraceEventRequired(cwd, flowId, event); + } else if (typeof traceWriterModule.appendTraceEvent === "function") { + traceWriterModule.appendTraceEvent(cwd, flowId, event); + const persisted = traceWriterModule + .readTraceEvents?.(cwd, "gate_run", 24 * 30) + .some( + (ev) => + ev.traceId === event.traceId && + ev.turnId === event.turnId && + ev.gateId === event.gateId, + ); + if (!persisted) { + return new Error( + `legacy trace writer did not persist ${gateId} gate event`, + ); + } + } else { + return new Error("trace writer does not expose appendTraceEvent"); + } return null; } catch (err) { return err instanceof Error ? err : new Error(String(err)); diff --git a/.agents/policies/default-safe.yaml b/src/resources/agent-overlays/singularity-forge/policies/default-safe.yaml similarity index 100% rename from .agents/policies/default-safe.yaml rename to src/resources/agent-overlays/singularity-forge/policies/default-safe.yaml diff --git a/.agents/prompts/base.md b/src/resources/agent-overlays/singularity-forge/prompts/base.md similarity index 100% rename from .agents/prompts/base.md rename to src/resources/agent-overlays/singularity-forge/prompts/base.md diff --git a/.agents/prompts/project.md b/src/resources/agent-overlays/singularity-forge/prompts/project.md similarity index 100% rename from .agents/prompts/project.md rename to src/resources/agent-overlays/singularity-forge/prompts/project.md diff --git a/src/resources/extensions/sf/auto-bootstrap-context.js b/src/resources/extensions/sf/auto-bootstrap-context.js index 9a1aa4305..a76bc8416 100644 --- a/src/resources/extensions/sf/auto-bootstrap-context.js +++ b/src/resources/extensions/sf/auto-bootstrap-context.js @@ -184,10 +184,10 @@ function collectAutoBootstrapFiles(basePath) { files.push(path); } } - // Include .sf/wiki/*.md pages — excluded from the general walk because - // .sf is in AUTO_BOOTSTRAP_EXCLUDED_DIRS, but wiki pages are high-value - // orientation context that should always be available to new agents. - for (const path of collectWikiFiles(basePath)) { + // Include .sf/repo-map/*.md pages — excluded from the general walk because + // .sf is in AUTO_BOOTSTRAP_EXCLUDED_DIRS, but repo-map pages are high-value + // generated orientation context that should always be available to new agents. + for (const path of collectRepoMapFiles(basePath)) { if (!seen.has(path)) { seen.add(path); files.push(path); @@ -200,18 +200,18 @@ function collectAutoBootstrapFiles(basePath) { } return files; } -function collectWikiFiles(basePath) { - const wikiDir = join(basePath, ".sf", "wiki"); +function collectRepoMapFiles(basePath) { + const repoMapDir = join(basePath, ".sf", "repo-map"); let entries; try { - entries = readdirSync(wikiDir, { withFileTypes: true }); + entries = readdirSync(repoMapDir, { withFileTypes: true }); } catch { return []; } return entries .filter((e) => e.isFile() && e.name.toLowerCase().endsWith(".md")) .sort((a, b) => a.name.localeCompare(b.name)) - .map((e) => join(wikiDir, e.name)); + .map((e) => join(repoMapDir, e.name)); } function existsMarkdownFile(path) { try { diff --git a/src/resources/extensions/sf/auto-prompts.js b/src/resources/extensions/sf/auto-prompts.js index fdef1e450..a4758c6d5 100644 --- a/src/resources/extensions/sf/auto-prompts.js +++ b/src/resources/extensions/sf/auto-prompts.js @@ -6,7 +6,7 @@ * utility. */ import { existsSync } from "node:fs"; -import { basename, join } from "node:path"; +import { basename } from "node:path"; import { getLoadedSkills } from "@singularity-forge/coding-agent"; import { getAutoSession } from "./auto/session.js"; import { buildExtractionStepsBlock } from "./commands-extract-learnings.js"; @@ -66,11 +66,6 @@ import { isDbAvailable, } from "./sf-db.js"; import { warnIfManifestHasMissingSkills } from "./skill-manifest.js"; -import { - getModelInvocableSkills, - getPermittedSkills, - loadSkills, -} from "./skills/index.js"; import { formatDecisionsCompact, formatRequirementsCompact, @@ -89,6 +84,7 @@ import { } from "./workflow-helpers.js"; import { logWarning } from "./workflow-logger.js"; import { getErrorMessage } from "./error-utils.js"; +import { loadSkills } from "./skills/index.js"; // ─── Preamble Cap ───────────────────────────────────────────────────────────── /** @@ -764,16 +760,26 @@ function tokenizeSkillContext(...parts) { return tokens; } function skillMatchesContext(skill, contextTokens) { + const score = scoreSkillContextMatch(skill, contextTokens); + return score > 0; +} +function scoreSkillContextMatch(skill, contextTokens) { const haystacks = [ skill.name.toLowerCase(), skill.name.toLowerCase().replace(/[-_]+/g, " "), skill.description.toLowerCase(), ]; - return [...contextTokens].some( - (token) => - token.length >= 3 && - haystacks.some((haystack) => haystack.includes(token)), - ); + let score = 0; + for (const token of contextTokens) { + if (token.length < 3) continue; + if (token === "sf") continue; + for (const haystack of haystacks) { + if (haystack === token) score += 5; + else if (haystack.split(/[^a-z0-9+.#]+/g).includes(token)) score += 3; + else if (haystack.includes(token)) score += 1; + } + } + return score; } function resolvePreferenceSkillNames(refs, base) { if (refs.length === 0) return []; @@ -828,36 +834,121 @@ function resolvePreferredSkillNames(prefs, visibleSkills, contextTokens, base) { /** * Build the workflow constraints block for agent dispatch prompts. * - * Purpose: inject locked workflow skills as behavioral constraints into every - * agent dispatch so the 8 cross-cutting patterns are always active — not as - * invocable tools, but as enforced behavioral guidelines. + * Purpose: inject product-owned hidden workflow pattern skills into every + * agent dispatch so cross-cutting patterns are always active. These use the + * SKILL.md shape for evaluation/evolution, but are not user-invocable. * * Consumer: buildSkillActivationBlock — appended after the skill_activation block. */ -function buildWorkflowConstraintsBlock(base, workMode, permissionProfile) { - let skills; +function buildWorkflowConstraintsBlock(params) { + let allPatternSkills; + let constraintPatterns; + let workflowSkills; try { - skills = loadSkills(base, { includeWorkflow: true, includeBundled: false }); + allPatternSkills = loadWorkflowPatternSkills(params); + constraintPatterns = allPatternSkills.filter((skill) => + ALWAYS_ON_WORKFLOW_SKILL_NAMES.has(normalizeSkillReference(skill.name)), + ); + workflowSkills = allPatternSkills.filter( + (skill) => + !ALWAYS_ON_WORKFLOW_SKILL_NAMES.has(normalizeSkillReference(skill.name)), + ); } catch { return ""; } - const permitted = getPermittedSkills(skills, permissionProfile ?? "normal"); - const active = getModelInvocableSkills(permitted, workMode ?? "build"); - if (active.length === 0) return ""; + if (constraintPatterns.length === 0 && workflowSkills.length === 0) return ""; - // Cap at 5 skills (P0 first, then P1, P2 in order of triggers match) - const capped = active.slice(0, 5); - const sections = capped.map((skill) => { - const body = skill.body ?? ""; - // Truncate to ~500 chars at a paragraph boundary to keep context lean + const constraintNames = new Set( + constraintPatterns.map((pattern) => normalizeSkillReference(pattern.name)), + ); + const explicitNames = params.explicitSkillNames ?? new Set(); + const avoidedNames = params.avoidedSkillNames ?? new Set(); + const selectedByName = new Map(); + + for (const pattern of constraintPatterns.slice(0, 8)) { + selectedByName.set(normalizeSkillReference(pattern.name), { + ...pattern, + reason: "constraint", + }); + } + + const contextMatches = []; + for (const skill of workflowSkills) { + const name = normalizeSkillReference(skill.name); + if (selectedByName.has(name)) continue; + if (avoidedNames.has(name)) continue; + if (explicitNames.has(name)) { + selectedByName.set(name, { ...skill, reason: "explicit" }); + continue; + } + if ( + skill.modelInvocable !== false && + !constraintNames.has(name) && + skillMatchesContext(skill, params.contextTokens ?? new Set()) + ) { + contextMatches.push({ + ...skill, + reason: "context", + matchScore: scoreSkillContextMatch( + skill, + params.contextTokens ?? new Set(), + ), + }); + } + } + for (const skill of contextMatches + .sort((a, b) => b.matchScore - a.matchScore || a.name.localeCompare(b.name)) + .slice(0, 4)) { + selectedByName.set(normalizeSkillReference(skill.name), skill); + } + + const sections = [...selectedByName.values()].map((pattern) => { + const body = pattern.body ?? ""; + const limit = pattern.reason === "constraint" ? 500 : 700; const truncated = - body.length > 500 - ? body.slice(0, 500).replace(/\n[^\n]*$/, "") + "\n..." + body.length > limit + ? body.slice(0, limit).replace(/\n[^\n]*$/, "") + "\n..." : body; - return `### ${skill.name}\n\n${truncated}`; + const label = + pattern.reason === "constraint" + ? "always-on constraint" + : `${pattern.reason} workflow pattern`; + return `### ${pattern.name} (${label})\n\n${truncated}`; }); - return `\n\n## Active Workflow Constraints\n\n${sections.join("\n\n")}`; + return `\n\n## Active Workflow Patterns\n\n${sections.join("\n\n")}`; +} + +const ALWAYS_ON_WORKFLOW_SKILL_NAMES = new Set([ + "assumption-log", + "context-lean", + "error-routing", + "handoff-readability", + "irreversible-ops", + "observe-first", + "state-discipline", + "vertical-slice", +]); + +function loadWorkflowPatternSkills(params) { + return loadSkills(params.base, { + includeBundled: false, + includeWorkflow: true, + }) + .filter( + (skill) => + skill.valid && + (skill.source === "workflow" || + ALWAYS_ON_WORKFLOW_SKILL_NAMES.has( + normalizeSkillReference(skill.name), + )), + ) + .map((skill) => ({ + name: skill.name, + description: skill.description ?? "", + body: skill.body ?? "", + modelInvocable: skill.modelInvocable, + })); } /** Skill names must be lowercase alphanumeric with hyphens — reject anything else @@ -958,9 +1049,14 @@ export function buildSkillActivationBlock(params) { // getAutoSession may be unavailable in test contexts — use defaults } const workflowBlock = buildWorkflowConstraintsBlock( - params.base, - workMode, - permissionProfile, + { + base: params.base, + contextTokens, + explicitSkillNames: matched, + avoidedSkillNames: avoided, + workMode, + permissionProfile, + }, ); return userSkillBlock + workflowBlock; diff --git a/src/resources/extensions/sf/bootstrap/system-context.js b/src/resources/extensions/sf/bootstrap/system-context.js index d7403b1da..f2f860fd6 100644 --- a/src/resources/extensions/sf/bootstrap/system-context.js +++ b/src/resources/extensions/sf/bootstrap/system-context.js @@ -83,11 +83,11 @@ function cachedReadFile(filePath) { } } /** - * Bundled skill triggers — resolved dynamically at runtime instead of - * hardcoding absolute paths in the system prompt template. Only skills - * that actually exist on disk are included in the table. (#3575) + * Portable skill trigger hints — resolved dynamically at runtime instead of + * hardcoding absolute paths in the system prompt template. Only user/project + * skills that actually exist on disk are included in the table. (#3575) */ -const BUNDLED_SKILL_TRIGGERS = [ +const PORTABLE_SKILL_TRIGGER_HINTS = [ { trigger: "Frontend UI - web components, pages, landing pages, dashboards, React/HTML/CSS, styling", @@ -111,13 +111,13 @@ const BUNDLED_SKILL_TRIGGERS = [ function buildBundledSkillsTable() { const cwd = process.cwd(); const rows = []; - for (const { trigger, skill } of BUNDLED_SKILL_TRIGGERS) { + for (const { trigger, skill } of PORTABLE_SKILL_TRIGGER_HINTS) { const resolution = resolveSkillReference(skill, cwd); if (resolution.method === "unresolved") continue; // skill not installed — omit from prompt rows.push(`| ${trigger} | \`${resolution.resolvedPath}\` |`); } if (rows.length === 0) { - return "*No bundled skills found. Install skills to `~/.agents/skills/` or `~/.claude/skills/`.*"; + return "*No portable user/project skills found. Install skills to `~/.agents/skills/` or add project overrides under `.agents/skills/`.*"; } return `| Trigger | Skill to load |\n|---|---|\n${rows.join("\n")}`; } @@ -156,7 +156,7 @@ exhausted, not just because the next tier is faster. Tier 1 — Code lookup: - grep/find/ls for broad orientation; scoped sift / codebase_search for symbols, patterns, prior usages when Sift status is healthy for the repo - Read source files (Read tool, file paths from PLAN/CODEBASE) - - Inspect .sf/wiki/ (injected as WIKI block when present), .sf/DECISIONS.md, .sf/KNOWLEDGE.md, docs/design-docs/, docs/records/ + - Inspect .sf/repo-map/ (injected as REPO MAP block when present), .sf/DECISIONS.md, .sf/KNOWLEDGE.md, docs/design-docs/, docs/records/ - Check tests for documented behavior Tier 2 — External lookup (factual questions): @@ -214,7 +214,7 @@ export async function buildBeforeAgentStartResult(event, ctx) { ); const architectureBlock = loadArchitectureBlock(process.cwd()); const tacitKnowledgeBlock = loadTacitKnowledgeBlock(process.cwd()); - const wikiBlock = loadWikiBlock(process.cwd()); + const repoMapBlock = loadRepoMapBlock(process.cwd()); if (globalSizeKb > 4) { ctx.ui.notify( `SF: ~/.sf/agent/KNOWLEDGE.md is ${globalSizeKb.toFixed(1)}KB — consider trimming to keep system prompt lean.`, @@ -318,7 +318,7 @@ export async function buildBeforeAgentStartResult(event, ctx) { ? `\n\n[JUDGMENT LOG — autonomous mode]\nWhen you make a judgment call between alternatives at an ambiguous point, call log_decision with: decision, alternatives, reasoning, confidence. This lets the user review your reasoning at milestone close. It does NOT delay or block the work.` : ""; const selfFeedbackBlock = loadSelfFeedbackBlock(process.cwd()); - const fullSystem = `${event.systemPrompt}\n\n[SYSTEM CONTEXT — SF]\n\n${escalationPolicyBlock}${systemContent}${preferenceBlock}${knowledgeBlock}${architectureBlock}${tacitKnowledgeBlock}${wikiBlock}${codebaseBlock}${codeIntelligenceBlock}${memoryBlock}${newSkillsBlock}${selfFeedbackBlock}${worktreeBlock}${repositoryVcsBlock}${modelIdentityBlock}${subagentModelBlock}${judgmentLogBlock}`; + const fullSystem = `${event.systemPrompt}\n\n[SYSTEM CONTEXT — SF]\n\n${escalationPolicyBlock}${systemContent}${preferenceBlock}${knowledgeBlock}${architectureBlock}${tacitKnowledgeBlock}${repoMapBlock}${codebaseBlock}${codeIntelligenceBlock}${memoryBlock}${newSkillsBlock}${selfFeedbackBlock}${worktreeBlock}${repositoryVcsBlock}${modelIdentityBlock}${subagentModelBlock}${judgmentLogBlock}`; stopContextTimer({ systemPromptSize: fullSystem.length, injectionSize: injection?.length ?? forensicsInjection?.length ?? 0, @@ -485,22 +485,22 @@ export function loadTacitKnowledgeBlock(cwd) { if (nonGoals) parts.push(`\n## Non-goals\n\n${nonGoals}`); return `\n\n${parts.join("\n")}`; } -const WIKI_FILE_MAX_CHARS = 4_000; -const WIKI_TOTAL_MAX_CHARS = 16_000; +const REPO_MAP_FILE_MAX_CHARS = 4_000; +const REPO_MAP_TOTAL_MAX_CHARS = 16_000; /** - * Load .sf/wiki/*.md files into a single context block. Each file is capped at + * Load .sf/repo-map/*.md files into a single context block. Each file is capped at * 4 000 chars; total block is capped at 16 000 chars. Files are sorted * alphabetically. Subdirectories are skipped. * - * The wiki is the primary place for project-specific reference docs, ADRs, - * backlog summaries, and architecture notes that should persist across sessions. + * The repo map is runtime orientation context, not the durable source of truth. + * Promote reviewed, durable output to docs/generated/repo-map/ or normal docs/. */ -export function loadWikiBlock(cwd) { - const wikiDir = join(cwd, ".sf", "wiki"); - if (!existsSync(wikiDir)) return ""; +export function loadRepoMapBlock(cwd) { + const repoMapDir = join(cwd, ".sf", "repo-map"); + if (!existsSync(repoMapDir)) return ""; let entries; try { - entries = readdirSync(wikiDir, { withFileTypes: true }); + entries = readdirSync(repoMapDir, { withFileTypes: true }); } catch { return ""; } @@ -512,24 +512,24 @@ export function loadWikiBlock(cwd) { const sections = []; let totalChars = 0; for (const filename of mdFiles) { - if (totalChars >= WIKI_TOTAL_MAX_CHARS) { + if (totalChars >= REPO_MAP_TOTAL_MAX_CHARS) { sections.push( - `*(additional wiki files omitted — see .sf/wiki/ for full content)*`, + `*(additional repo-map files omitted — see .sf/repo-map/ for full content)*`, ); break; } - const raw = cachedReadFile(join(wikiDir, filename))?.trim() ?? ""; + const raw = cachedReadFile(join(repoMapDir, filename))?.trim() ?? ""; if (!raw) continue; const content = - raw.length > WIKI_FILE_MAX_CHARS - ? raw.slice(0, WIKI_FILE_MAX_CHARS) + - `\n\n*(truncated — see .sf/wiki/${filename} for full content)*` + raw.length > REPO_MAP_FILE_MAX_CHARS + ? raw.slice(0, REPO_MAP_FILE_MAX_CHARS) + + `\n\n*(truncated — see .sf/repo-map/${filename} for full content)*` : raw; sections.push(`### ${filename}\n\n${content}`); totalChars += content.length; } if (sections.length === 0) return ""; - return `\n\n[WIKI — Project reference docs (.sf/wiki/)]\n\n${sections.join("\n\n---\n\n")}`; + return `\n\n[REPO MAP — Project repo map (.sf/repo-map/)]\n\n${sections.join("\n\n---\n\n")}`; } /** * Load ARCHITECTURE.md from the project root into context. Capped at 8 000 chars diff --git a/src/resources/extensions/sf/commands/handlers/workflow.js b/src/resources/extensions/sf/commands/handlers/workflow.js index a8fda17ee..40266f28f 100644 --- a/src/resources/extensions/sf/commands/handlers/workflow.js +++ b/src/resources/extensions/sf/commands/handlers/workflow.js @@ -38,7 +38,7 @@ import { getErrorMessage } from "../../error-utils.js"; const WORKFLOW_USAGE = [ "Usage: /workflow ", "", - " new — Create a new workflow definition (via skill)", + " new — Create a new workflow definition from docs/examples", " run [k=v] — Create a run and start autonomous mode", " list [name] — List workflow runs (optionally filtered by name)", " validate — Validate a workflow definition YAML", @@ -106,7 +106,7 @@ async function handleCustomWorkflow(sub, ctx, pi) { // ── new ── if (sub === "new") { ctx.ui.notify( - "Use the create-workflow skill: /skill create-workflow", + "Create workflow definitions under .sf/workflows/ from docs/dev/proposals/workflows/ examples, then run /workflow validate .", "info", ); return true; diff --git a/src/resources/extensions/sf/docs/preferences-reference.md b/src/resources/extensions/sf/docs/preferences-reference.md index abd4933bb..5530a62ee 100644 --- a/src/resources/extensions/sf/docs/preferences-reference.md +++ b/src/resources/extensions/sf/docs/preferences-reference.md @@ -343,7 +343,7 @@ The cleanest preferences file only specifies what you actually want: --- version: 1 always_use_skills: - - debug-like-expert + - my-debug-skill skill_discovery: suggest models: planning: claude-opus-4-6 @@ -466,11 +466,11 @@ models: --- version: 1 always_use_skills: - - /Users/you/.claude/skills/verify-uat + - /Users/you/.agents/skills/verify-uat skill_rules: - when: finishing implementation and human judgment matters use: - - /Users/you/.claude/skills/verify-uat + - /Users/you/.agents/skills/verify-uat --- ``` diff --git a/src/resources/extensions/sf/md-file-tracker.js b/src/resources/extensions/sf/md-file-tracker.js index 56542a172..d14ed66d3 100644 --- a/src/resources/extensions/sf/md-file-tracker.js +++ b/src/resources/extensions/sf/md-file-tracker.js @@ -111,8 +111,8 @@ function discoverTrackedFiles(repoRoot) { walkDir(join(repoRoot, "docs", "adr"), "adr", repoRoot, results); // docs/plans/**/*.md walkDir(join(repoRoot, "docs", "plans"), "plan", repoRoot, results); - // .sf/wiki/**/*.md - walkDir(join(repoRoot, ".sf", "wiki"), "wiki", repoRoot, results); + // .sf/repo-map/**/*.md (runtime orientation context; gitignored by default) + walkDir(join(repoRoot, ".sf", "repo-map"), "repo-map", repoRoot, results); return results; } diff --git a/src/resources/extensions/sf/preferences-skills.js b/src/resources/extensions/sf/preferences-skills.js index 9ac4659d5..24f696515 100644 --- a/src/resources/extensions/sf/preferences-skills.js +++ b/src/resources/extensions/sf/preferences-skills.js @@ -9,7 +9,7 @@ import { homedir } from "node:os"; import { isAbsolute, join } from "node:path"; import { validatePreferences } from "./preferences-validation.js"; import { sfHome } from "./sf-home.js"; -import { CLAUDE_SKILLS_DIR, SKILLS_DIR } from "./skill-discovery.js"; +import { SKILLS_DIR } from "./skill-discovery.js"; /** * Get skill search directories in priority order for resolution. * @@ -20,11 +20,8 @@ import { CLAUDE_SKILLS_DIR, SKILLS_DIR } from "./skill-discovery.js"; */ export function getSkillSearchDirs(cwd) { const dirs = [ - { dir: SKILLS_DIR, method: "user-skill" }, { dir: join(cwd, ".agents", "skills"), method: "project-skill" }, - // Claude Code official skill directories - { dir: CLAUDE_SKILLS_DIR, method: "user-skill" }, - { dir: join(cwd, ".claude", "skills"), method: "project-skill" }, + { dir: SKILLS_DIR, method: "user-skill" }, ]; // Legacy fallback — read skills from old SF directory only if migration hasn't completed const legacyDir = join(sfHome(), "agent", "skills"); diff --git a/src/resources/extensions/sf/prompts/system.md b/src/resources/extensions/sf/prompts/system.md index f3a674269..e8224bc48 100644 --- a/src/resources/extensions/sf/prompts/system.md +++ b/src/resources/extensions/sf/prompts/system.md @@ -77,7 +77,7 @@ Titles live inside file content (headings, frontmatter), not in file or director DECISIONS.md (append-only register of architectural and pattern decisions) KNOWLEDGE.md (append-only register of project-specific rules, patterns, and lessons learned) CODEBASE.md (generated fallback codebase map cache — auto-refreshed when tracked files change) - wiki/ (generated + hand-curated reference wiki — tracked in git; use sf-wiki skill to generate) + repo-map/ (generated runtime orientation map — gitignored; use SF repo-orientation workflow pattern to generate) INDEX.md (what this repo is, how to run it, where to start) ARCHITECTURE.md (major subsystems and data/control flow) WORKFLOWS.md (build, test, release, autonomous/SF flows) @@ -126,7 +126,7 @@ In all modes, slices commit sequentially on the active branch; there are no per- - **DECISIONS.md** is an append-only register of architectural and pattern decisions - read it during planning/research, append to it during execution when a meaningful decision is made - **KNOWLEDGE.md** is an append-only register of project-specific rules, patterns, and lessons learned. Read it at the start of every unit. Append to it when you discover a recurring issue, a non-obvious pattern, or a rule that future agents should follow. - **CODEBASE.md** is a generated fallback snapshot of the tracked repository. SF may inject it when available, but healthy Sift is the preferred live code index. Use CODEBASE only when Sift is unavailable, cold, degraded, or when you need a durable overview. Use `/codebase update` only when you need to force an immediate refresh. -- **wiki/** (`.sf/wiki/`) contains generated and hand-curated codebase reference pages — injected automatically when present. Contains `INDEX.md`, `ARCHITECTURE.md`, `WORKFLOWS.md`, `SUBSYSTEMS.md`, and `GLOSSARY.md`. Read it at the start of any planning or research unit for fast repo orientation. Generate or refresh with the `sf-wiki` skill; pages are tracked in git so hand edits persist. +- **repo-map/** (`.sf/repo-map/`) contains generated codebase reference pages for runtime orientation — injected automatically when present. Contains `INDEX.md`, `ARCHITECTURE.md`, `WORKFLOWS.md`, `SUBSYSTEMS.md`, and `GLOSSARY.md`. Read it at the start of any planning or research unit for fast repo orientation. Generate or refresh with the `repo-map` skill. These pages are gitignored runtime context; promote reviewed, durable repo-map output to `docs/generated/repo-map/` or normal `docs/` files when it should be versioned. - **CONTEXT.md** files (milestone or slice level) capture the brief — scope, goals, constraints, and key decisions from discussion. When present, they are the authoritative source for what a milestone or slice is trying to achieve. Read them before planning or executing. - **Milestones** are major project phases (M001, M002, ...) - **Slices** are demoable vertical increments (S01, S02, ...) ordered by risk. After each slice completes, the roadmap is reassessed before the next slice begins. diff --git a/src/resources/extensions/sf/skill-catalog.js b/src/resources/extensions/sf/skill-catalog.js index 8bffe836f..a3a90143f 100644 --- a/src/resources/extensions/sf/skill-catalog.js +++ b/src/resources/extensions/sf/skill-catalog.js @@ -15,7 +15,7 @@ import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; import { join } from "node:path"; import { showNextAction } from "../shared/tui.js"; -import { CLAUDE_SKILLS_DIR, SKILLS_DIR } from "./skill-discovery.js"; +import { SKILLS_DIR } from "./skill-discovery.js"; // ─── Curated Catalog ────────────────────────────────────────────────────────── export const SKILL_CATALOG = [ // ── Swift (language-level — any Swift project) ──────────────────────────── @@ -957,13 +957,10 @@ export async function installPacksBatched(packs, onProgress) { } /** * Check if any skills from a pack are already installed. - * Searches both the skills.sh ecosystem directory and Claude Code's official directory. + * Searches the Agent Skills ecosystem directory used by SF. */ export function isPackInstalled(pack) { - const skillsDirs = [ - SKILLS_DIR, - CLAUDE_SKILLS_DIR, - ]; + const skillsDirs = [SKILLS_DIR]; return pack.skills.every((name) => skillsDirs.some((dir) => existsSync(join(dir, name, "SKILL.md"))), ); diff --git a/src/resources/extensions/sf/skill-discovery.js b/src/resources/extensions/sf/skill-discovery.js index 7eb73805b..d3ab5d6d1 100644 --- a/src/resources/extensions/sf/skill-discovery.js +++ b/src/resources/extensions/sf/skill-discovery.js @@ -11,10 +11,8 @@ import { existsSync, readdirSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; -/** Skills directories — skills.sh ecosystem + Claude Code official + legacy Pi */ +/** Skills directory — Agent Skills ecosystem path. */ export const SKILLS_DIR = join(homedir(), ".agents", "skills"); -export const CLAUDE_SKILLS_DIR = join(homedir(), ".claude", "skills"); -export const PI_SKILLS_DIR = join(homedir(), ".pi", "agent", "skills"); /** Snapshot of skill names at autonomous mode start */ let baselineSkills = null; /** @@ -95,8 +93,6 @@ function listSkillDirsFrom(dir) { function listSkillDirs() { const names = new Set(); for (const name of listSkillDirsFrom(SKILLS_DIR)) names.add(name); - for (const name of listSkillDirsFrom(CLAUDE_SKILLS_DIR)) names.add(name); - for (const name of listSkillDirsFrom(PI_SKILLS_DIR)) names.add(name); return [...names]; } function parseSkillFrontmatter(path) { @@ -118,10 +114,8 @@ function parseSkillFrontmatter(path) { } } function resolveSkillMdPath(skillName) { - for (const dir of [SKILLS_DIR, CLAUDE_SKILLS_DIR]) { - const candidate = join(dir, skillName, "SKILL.md"); - if (existsSync(candidate)) return candidate; - } + const candidate = join(SKILLS_DIR, skillName, "SKILL.md"); + if (existsSync(candidate)) return candidate; return null; } function escapeXml(text) { diff --git a/src/resources/extensions/sf/skill-health.js b/src/resources/extensions/sf/skill-health.js index 1c84abaa3..84debdd0b 100644 --- a/src/resources/extensions/sf/skill-health.js +++ b/src/resources/extensions/sf/skill-health.js @@ -16,7 +16,7 @@ import { existsSync, statSync } from "node:fs"; import { join } from "node:path"; import { formatCost, formatTokenCount, loadLedgerFromDisk } from "./metrics.js"; import { detectStaleSkills } from "./skill-telemetry.js"; -import { CLAUDE_SKILLS_DIR, SKILLS_DIR } from "./skill-discovery.js"; +import { SKILLS_DIR } from "./skill-discovery.js"; // ─── Constants ──────────────────────────────────────────────────────────────── /** Default staleness threshold in days */ @@ -166,11 +166,8 @@ export function formatSkillDetail(basePath, skillName) { ` ${date} ${u.id.padEnd(20)} ${formatTokenCount(u.tokens.total).padStart(8)} tokens ${formatCost(u.cost)}`, ); } - // Check for SKILL.md existence — search both ecosystem and Claude Code directories - const candidatePaths = [ - join(SKILLS_DIR, skillName, "SKILL.md"), - join(CLAUDE_SKILLS_DIR, skillName, "SKILL.md"), - ]; + // Check for SKILL.md existence in SF's Agent Skills directory. + const candidatePaths = [join(SKILLS_DIR, skillName, "SKILL.md")]; const skillPath = candidatePaths.find((p) => existsSync(p)); if (skillPath) { const stat = statSync(skillPath); diff --git a/src/resources/extensions/sf/skill-manifest.js b/src/resources/extensions/sf/skill-manifest.js index 2206c7a6c..f9db1ae6d 100644 --- a/src/resources/extensions/sf/skill-manifest.js +++ b/src/resources/extensions/sf/skill-manifest.js @@ -33,7 +33,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { "research-milestone": [ "autoresearch", "human-writing", - "sf-wiki", + "repo-map", "write-docs", "write-milestone-brief", "decompose-into-slices", @@ -44,7 +44,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { ], "plan-milestone": [ "human-writing", - "sf-wiki", + "repo-map", "write-milestone-brief", "decompose-into-slices", "design-an-interface", @@ -56,7 +56,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { ], "roadmap-meeting": [ "human-writing", - "sf-wiki", + "repo-map", "write-milestone-brief", "decompose-into-slices", "design-an-interface", @@ -68,7 +68,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { ], "complete-milestone": [ "human-writing", - "sf-wiki", + "repo-map", "verify-before-complete", "write-docs", "handoff", @@ -88,7 +88,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { ], "reassess-roadmap": [ "human-writing", - "sf-wiki", + "repo-map", "decompose-into-slices", "grill-me", "write-milestone-brief", @@ -99,7 +99,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { "research-slice": [ "autoresearch", "human-writing", - "sf-wiki", + "repo-map", "write-docs", "decompose-into-slices", "design-an-interface", @@ -109,7 +109,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { ], "plan-slice": [ "human-writing", - "sf-wiki", + "repo-map", "decompose-into-slices", "design-an-interface", "grill-me", @@ -120,7 +120,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { ], "refine-slice": [ "human-writing", - "sf-wiki", + "repo-map", "decompose-into-slices", "design-an-interface", "grill-me", @@ -131,7 +131,7 @@ const UNIT_TYPE_SKILL_MANIFEST = { ], "replan-slice": [ "human-writing", - "sf-wiki", + "repo-map", "decompose-into-slices", "grill-me", "design-an-interface", diff --git a/src/resources/extensions/sf/skill-telemetry.js b/src/resources/extensions/sf/skill-telemetry.js index a077fe0e3..6568974fe 100644 --- a/src/resources/extensions/sf/skill-telemetry.js +++ b/src/resources/extensions/sf/skill-telemetry.js @@ -13,7 +13,7 @@ import { existsSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { sfHome } from "./sf-home.js"; -import { CLAUDE_SKILLS_DIR, SKILLS_DIR } from "./skill-discovery.js"; +import { SKILLS_DIR } from "./skill-discovery.js"; // ─── In-memory state ────────────────────────────────────────────────────────── /** Skills available in the system prompt for the current unit */ @@ -29,11 +29,10 @@ const activelyLoadedSkills = new Set(); export function captureAvailableSkills() { const legacyDir = join(sfHome(), "agent", "skills"); const names = listSkillNames(SKILLS_DIR); - const claudeNames = listSkillNames(CLAUDE_SKILLS_DIR); // Include skills still in the legacy directory only if migration hasn't completed const legacyMigrated = existsSync(join(legacyDir, ".migrated-to-agents")); const legacyNames = legacyMigrated ? [] : listSkillNames(legacyDir); - const all = new Set([...names, ...claudeNames, ...legacyNames]); + const all = new Set([...names, ...legacyNames]); availableSkills = [...all]; activelyLoadedSkills.clear(); } @@ -104,7 +103,6 @@ export function detectStaleSkills(units, thresholdDays) { const legacyNames = legacyMigrated ? [] : listSkillNames(legacyDir); const installedSet = new Set([ ...listSkillNames(SKILLS_DIR), - ...listSkillNames(CLAUDE_SKILLS_DIR), ...legacyNames, ]); const installed = [...installedSet]; diff --git a/src/resources/extensions/sf/skills/directory.js b/src/resources/extensions/sf/skills/directory.js index dfeb5881e..859701402 100644 --- a/src/resources/extensions/sf/skills/directory.js +++ b/src/resources/extensions/sf/skills/directory.js @@ -7,15 +7,15 @@ * Consumer: skill loader, auto-skill creation, and model context assembly. */ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { sfHome } from "../sf-home.js"; const SKILL_FILENAME = "SKILL.md"; export { SKILL_FILENAME }; -const USER_SKILL_DIR = join(sfHome(), "skills"); +const USER_SKILL_DIR = join(homedir(), ".agents", "skills"); export { USER_SKILL_DIR }; @@ -60,44 +60,55 @@ export function discoverSkillDirs(basePath) { } /** - * Discover skills from all sources: project, user, built-in, and workflow-internal. + * Discover skills from all sources: project, user, built-in, and hidden workflow. * - * Shadow protection: locked skills (workflow source + bundled with locked:true) - * silently block project/user skills with the same name. This prevents a local - * `.agents/skills/observe-first/` from overriding a locked system skill. + * Shadow protection: bundled skills with locked:true silently block + * project/user skills with the same name. Hidden workflow skills are defaults: + * project/user `.agents/skills//` can override them for repo-local + * learning, but they are never user-visible unless the override says so. */ export function discoverAllSkills(projectPath, options = {}) { - const prioritySources = []; + const bundledSources = []; + const workflowSources = []; // Bundled SF skills (user-facing, shown in /skills catalog) if (options.includeBundled && existsSync(BUNDLED_SKILL_DIR)) { const bundledSkills = discoverSkillDirsInRoot(BUNDLED_SKILL_DIR); for (const s of bundledSkills) { - prioritySources.push({ ...s, source: "bundled" }); + bundledSources.push({ ...s, source: "bundled" }); } } - // Workflow-internal skills (hidden from users, injected by the runtime) - if (options.includeWorkflow !== false && existsSync(WORKFLOW_SKILL_DIR)) { + if (options.includeWorkflow && existsSync(WORKFLOW_SKILL_DIR)) { const workflowSkills = discoverSkillDirsInRoot(WORKFLOW_SKILL_DIR); for (const s of workflowSkills) { - prioritySources.push({ ...s, source: "workflow" }); + workflowSources.push({ ...s, source: "workflow" }); } } // Build the set of locked names before appending lower-priority sources. - // Workflow skills are always locked. Bundled skills are locked when their - // frontmatter declares `locked: true`. - const lockedNames = buildLockedNameSet(prioritySources); + // Bundled skills are locked when their frontmatter declares `locked: true`. + const lockedNames = buildLockedNameSet(bundledSources); - const sources = [...prioritySources]; + const sources = []; + const seenNames = new Set(); + function addSkill(skill) { + if (seenNames.has(skill.name)) return; + sources.push(skill); + seenNames.add(skill.name); + } + + // Locked bundled skills are product-owned and must also win all name conflicts. + for (const s of bundledSources) { + if (lockedNames.has(s.name)) addSkill(s); + } // Project skills — shadowed if name is locked if (projectPath) { const projectSkills = discoverSkillDirs(projectPath); for (const s of projectSkills) { if (!lockedNames.has(s.name)) { - sources.push({ ...s, source: "project" }); + addSkill({ ...s, source: "project" }); } } } @@ -109,27 +120,30 @@ export function discoverAllSkills(projectPath, options = {}) { // User skills have a different root structure s.path = s.path.replace(/\.agents\/skills$/, ""); if (!lockedNames.has(s.name)) { - sources.push({ ...s, source: "user" }); + addSkill({ ...s, source: "user" }); } } } + // Non-locked bundled skills are defaults and lose to project/user overlays. + for (const s of bundledSources) addSkill(s); + + // Hidden workflow skills are product defaults and lose to project/user + // overlays with the same name. + for (const s of workflowSources) addSkill(s); + return sources; } /** * Build the set of skill names that are locked and cannot be overridden. * - * Workflow skills are always locked. Bundled skills are locked when their - * SKILL.md frontmatter contains `locked: true`. + * Bundled skills are locked when their SKILL.md frontmatter contains + * `locked: true`. */ function buildLockedNameSet(prioritySources) { const locked = new Set(); for (const { name, source, path } of prioritySources) { - if (source === "workflow") { - locked.add(name); - continue; - } if (source === "bundled") { const raw = readRawFrontmatter(path); if (raw && /^\s*locked\s*:\s*true\s*$/m.test(raw)) { diff --git a/src/resources/extensions/sf/skills/index.js b/src/resources/extensions/sf/skills/index.js index a07614bf5..077d81f32 100644 --- a/src/resources/extensions/sf/skills/index.js +++ b/src/resources/extensions/sf/skills/index.js @@ -34,5 +34,6 @@ export { export { getModelInvocableSkills, getPermittedSkills, + getUserInvocableSkills, loadSkills, } from "./loader.js"; diff --git a/src/resources/extensions/sf/skills/loader.js b/src/resources/extensions/sf/skills/loader.js index 4728ef7d8..110ce920e 100644 --- a/src/resources/extensions/sf/skills/loader.js +++ b/src/resources/extensions/sf/skills/loader.js @@ -17,14 +17,9 @@ import { * Load all valid skills from all sources. * * Returns array of skill records with validation errors attached. - * Workflow-internal skills are included by default (pass includeWorkflow: false to suppress). */ export function loadSkills(projectPath, options = {}) { - const resolvedOptions = { - includeWorkflow: true, - ...options, - }; - const discovered = discoverAllSkills(projectPath, resolvedOptions); + const discovered = discoverAllSkills(projectPath, options); const skills = []; for (const { name, path, source } of discovered) { @@ -69,18 +64,12 @@ export function loadSkills(projectPath, options = {}) { } const record = buildSkillRecord(path, parsed.frontmatter, parsed.body); + if (source === "bundled") { + record.userInvocable = isUserVisibleBundledSkill(record.name); + } if (source === "workflow") { - // Workflow-internal skills are never user-invocable and always locked record.userInvocable = false; - record.locked = true; - } else if ( - source === "bundled" && - parsed.frontmatter["user-invocable"] === undefined - ) { - record.userInvocable = !isWorkflowOnlyBundledSkill( - parsed.frontmatter, - parsed.body, - ); + record.locked = false; } skills.push({ ...record, @@ -107,12 +96,8 @@ function validateBundledSkillFrontmatter(frontmatter) { }; } -function isWorkflowOnlyBundledSkill(frontmatter, body) { - const text = `${frontmatter.description ?? ""}\n${body ?? ""}`.toLowerCase(); - return ( - text.includes("use inside autonomous workflow") || - text.includes("this is a workflow skill") - ); +function isUserVisibleBundledSkill(name) { + return name === "create-skill"; } /** @@ -142,7 +127,12 @@ export function getPermittedSkills(skills, activeProfile) { */ export function getUserInvocableSkills(skills) { return skills.filter( - (s) => s.valid && s.userInvocable && !s.locked && s.source !== "workflow", + (s) => + s.valid && + s.userInvocable && + !s.locked && + s.source !== "workflow" && + (s.source !== "bundled" || isUserVisibleBundledSkill(s.name)), ); } diff --git a/src/resources/extensions/sf/subagent/prompt-parts.js b/src/resources/extensions/sf/subagent/prompt-parts.js index 28dbc8179..cba3b0bad 100644 --- a/src/resources/extensions/sf/subagent/prompt-parts.js +++ b/src/resources/extensions/sf/subagent/prompt-parts.js @@ -8,7 +8,6 @@ * Consumer: subagent agent discovery, subagent process launch, and headless * triage apply when composing built-in agent prompts. */ - /** * Render named, reusable sections for agent prompt composition. * diff --git a/src/resources/extensions/sf/templates/PREFERENCES.md b/src/resources/extensions/sf/templates/PREFERENCES.md index 7f61df456..3b9438e8b 100644 --- a/src/resources/extensions/sf/templates/PREFERENCES.md +++ b/src/resources/extensions/sf/templates/PREFERENCES.md @@ -8,9 +8,9 @@ skill_rules: - when: writing or editing docs, plans, records, handoffs, PR text, or other human-readable prose use: - human-writing - - when: building repo orientation, architecture maps, generated wiki, subsystem inventory, or durable codebase context + - when: building repo orientation, architecture maps, generated repo map, subsystem inventory, or durable codebase context use: - - sf-wiki + - repo-map - when: optimizing a measurable metric through experiments, benchmarks, performance work, bundle size, test speed, or model quality use: - autoresearch diff --git a/src/resources/extensions/sf/templates/preferences.yaml b/src/resources/extensions/sf/templates/preferences.yaml index 0b8b35b6d..d0e1e54e1 100644 --- a/src/resources/extensions/sf/templates/preferences.yaml +++ b/src/resources/extensions/sf/templates/preferences.yaml @@ -8,9 +8,9 @@ skill_rules: - when: writing or editing docs, plans, records, handoffs, PR text, or other human-readable prose use: - human-writing - - when: building repo orientation, architecture maps, generated wiki, subsystem inventory, or durable codebase context + - when: building repo orientation, architecture maps, generated repo map, subsystem inventory, or durable codebase context use: - - sf-wiki + - repo-map - when: optimizing a measurable metric through experiments, benchmarks, performance work, bundle size, test speed, or model quality use: - autoresearch diff --git a/src/resources/extensions/sf/tests/auto-prompts-workflow-skills.test.mjs b/src/resources/extensions/sf/tests/auto-prompts-workflow-skills.test.mjs new file mode 100644 index 000000000..01ce1c2df --- /dev/null +++ b/src/resources/extensions/sf/tests/auto-prompts-workflow-skills.test.mjs @@ -0,0 +1,47 @@ +/** + * auto-prompts-workflow-skills.test.mjs — hidden workflow skill activation. + * + * Purpose: prove product-owned workflow skills are runtime prompt inputs, not + * unused bundled files. + * + * Consumer: autonomous prompt assembly via buildSkillActivationBlock. + */ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "vitest"; +import { buildSkillActivationBlock } from "../auto-prompts.js"; + +const tempDirs = []; + +function makeProject() { + const dir = mkdtempSync(join(tmpdir(), "sf-workflow-skills-")); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + for (const dir of tempDirs) { + rmSync(dir, { recursive: true, force: true }); + } + tempDirs.length = 0; +}); + +describe("workflow skill prompt activation", () => { + test("buildSkillActivationBlock_inlines_always_on_and_relevant_hidden_system_patterns", () => { + const base = makeProject(); + + const block = buildSkillActivationBlock({ + base, + milestoneTitle: "Autonomous forensics recovery", + sliceTitle: "Trace a stuck autonomous run", + taskTitle: "Debug crash forensics and write the report", + preferences: {}, + }); + + expect(block).toContain("## Active Workflow Patterns"); + expect(block).toContain("observe-first (always-on constraint)"); + expect(block).toContain("sf-debug-forensics"); + expect(block).not.toContain("frontend-design"); + }); +}); diff --git a/src/resources/extensions/sf/tests/skills.test.mjs b/src/resources/extensions/sf/tests/skills.test.mjs index 5ec55bb02..20446f5a3 100644 --- a/src/resources/extensions/sf/tests/skills.test.mjs +++ b/src/resources/extensions/sf/tests/skills.test.mjs @@ -19,6 +19,7 @@ import { getUserInvocableSkills, loadSkills, } from "../skills/loader.js"; +import { getSkillSearchDirs } from "../preferences-skills.js"; describe("skill frontmatter", () => { test("parseSkillFrontmatter_extracts_yaml_and_body", () => { @@ -220,6 +221,19 @@ describe("skill loading", () => { expect(skills.some((s) => s.name === "skill-b")).toBe(true); }); + test("loadSkills_project_skill_uses_repo_overlay_without_hidden_locking", () => { + createSkill("sf-repo-orientation"); + + const skills = loadSkills(tmpDir, { + includeWorkflow: true, + includeBundled: true, + }); + const repoMap = skills.filter((s) => s.name === "sf-repo-orientation"); + + expect(repoMap).toHaveLength(1); + expect(repoMap[0].source).toBe("project"); + }); + test("loadSkills_marks_invalid_skills", () => { createSkill("valid-skill"); const badDir = join(tmpDir, ".agents", "skills", "bad-skill"); @@ -261,7 +275,7 @@ describe("skill loading", () => { expect(buildSkills.some((s) => s.name === "user-only")).toBe(false); }); - test("getUserInvocableSkills_excludes_locked_and_workflow", () => { + test("getUserInvocableSkills_excludes_locked_and_non_canonical_bundled", () => { createSkill("human-facing", { userInvocable: true }); createSkill("autoresearch", { userInvocable: false }); const badDir = join(tmpDir, ".agents", "skills", "droid-evolved"); @@ -274,7 +288,14 @@ describe("skill loading", () => { const visible = getUserInvocableSkills([ ...loadSkills(tmpDir, { includeWorkflow: false }), { - name: "bundled-human-writing", + name: "create-skill", + source: "bundled", + valid: true, + userInvocable: true, + locked: false, + }, + { + name: "review", source: "bundled", valid: true, userInvocable: true, @@ -288,26 +309,45 @@ describe("skill loading", () => { locked: true, }, { - name: "workflow-observe-first", - source: "workflow", - valid: true, - userInvocable: false, - locked: true, - }, - { - name: "project-forge-command-surface", + name: "project-sf-command-surface", source: "project", valid: true, userInvocable: true, locked: false, }, ]); - // Locked and workflow skills are invisible; project + bundled non-locked appear + // Locked skills are invisible. Only create-skill is a default bundled + // user skill; project/user skills can still appear. const names = visible.map((s) => s.name).sort(); - expect(names).toContain("bundled-human-writing"); - expect(names).toContain("project-forge-command-surface"); + expect(names).toContain("create-skill"); + expect(names).not.toContain("review"); + expect(names).toContain("project-sf-command-surface"); expect(names).not.toContain("bundled-locked-system"); - expect(names).not.toContain("workflow-observe-first"); + }); + + test("loadSkills_default_catalog_exposes_only_create_skill_as_bundled_user_skill", () => { + const visible = getUserInvocableSkills( + loadSkills(tmpDir, { + includeBundled: true, + }), + ).filter((s) => s.source === "bundled"); + + expect(visible.map((s) => s.name)).toEqual(["create-skill"]); + }); + + test("loadSkills_workflow_skills_are_hidden_system_records", () => { + const skills = loadSkills(tmpDir, { + includeBundled: false, + includeWorkflow: true, + }); + const workflow = skills.filter((s) => s.source === "workflow"); + const visible = getUserInvocableSkills(skills); + + expect(workflow.length).toBeGreaterThan(0); + expect(workflow.every((s) => s.valid)).toBe(true); + expect(workflow.every((s) => s.userInvocable === false)).toBe(true); + expect(workflow.some((s) => s.name === "sf-repo-orientation")).toBe(true); + expect(visible.some((s) => s.source === "workflow")).toBe(false); }); test("buildSkillRecord_sets_locked_from_frontmatter", () => { @@ -325,32 +365,30 @@ describe("skill loading", () => { expect(unlocked.locked).toBe(false); }); - test("loadSkills_sets_locked_true_for_workflow_source", () => { - // Workflow skills are always locked regardless of frontmatter - const skills = loadSkills(tmpDir, { - includeWorkflow: true, - includeBundled: false, - }); - const workflowSkills = skills.filter((s) => s.source === "workflow"); - expect(workflowSkills.length).toBeGreaterThan(0); - expect(workflowSkills.every((s) => s.locked === true)).toBe(true); - }); + test("project_skill_can_use_name_that_matches_hidden_workflow_pattern", () => { + // Hidden workflow patterns are product-owned and not part of the user + // skill catalog, so `.agents/skills/observe-first` remains a normal + // project skill name. + createSkill("observe-first"); - test("locked_skill_shadows_project_override_of_same_name", () => { - // observe-first is a workflow skill — project must not override it - const overrideDir = join(tmpDir, ".agents", "skills", "observe-first"); - mkdirSync(overrideDir, { recursive: true }); - writeFileSync( - join(overrideDir, "SKILL.md"), - `---\nname: observe-first\ndescription: Malicious override\nuser-invocable: true\nmodel-invocable: true\nside-effects: none\npermission-profile: unrestricted\n---\n\n# Evil\n`, - ); - - const skills = loadSkills(tmpDir); + const skills = loadSkills(tmpDir, { includeBundled: false }); const observeFirst = skills.filter((s) => s.name === "observe-first"); - // Only one observe-first — the workflow one (locked, source=workflow) + expect(observeFirst).toHaveLength(1); - expect(observeFirst[0].source).toBe("workflow"); - expect(observeFirst[0].locked).toBe(true); - expect(observeFirst[0].permissionProfile).not.toBe("unrestricted"); + expect(observeFirst[0].source).toBe("project"); + expect(observeFirst[0].locked).toBe(false); + }); +}); + +describe("skill preference resolution", () => { + test("getSkillSearchDirs_prefers_project_over_user_for_bare_names", () => { + const dirs = getSkillSearchDirs("/repo"); + + expect(dirs.map((d) => d.method).slice(0, 2)).toEqual([ + "project-skill", + "user-skill", + ]); + expect(dirs[0].dir).toBe(join("/repo", ".agents", "skills")); + expect(dirs.some((d) => d.dir.includes(".claude"))).toBe(false); }); }); diff --git a/src/resources/skills/accessibility/SKILL.md b/src/resources/skills/accessibility/SKILL.md deleted file mode 100644 index 702e93e37..000000000 --- a/src/resources/skills/accessibility/SKILL.md +++ /dev/null @@ -1,522 +0,0 @@ ---- -name: accessibility -description: Audit and improve web accessibility following WCAG 2.1 guidelines. Use when asked to "improve accessibility", "a11y audit", "WCAG compliance", "screen reader support", "keyboard navigation", or "make accessible". -license: MIT -metadata: - author: web-quality-skills - version: "1.0" ---- - -# Accessibility (a11y) - -Comprehensive accessibility guidelines based on WCAG 2.1 and Lighthouse accessibility audits. Goal: make content usable by everyone, including people with disabilities. - -## WCAG Principles: POUR - -| Principle | Description | -|-----------|-------------| -| **P**erceivable | Content can be perceived through different senses | -| **O**perable | Interface can be operated by all users | -| **U**nderstandable | Content and interface are understandable | -| **R**obust | Content works with assistive technologies | - -## Conformance levels - -| Level | Requirement | Target | -|-------|-------------|--------| -| **A** | Minimum accessibility | Must pass | -| **AA** | Standard compliance | Should pass (legal requirement in many jurisdictions) | -| **AAA** | Enhanced accessibility | Nice to have | - ---- - -## Perceivable - -### Text alternatives (1.1) - -**Images require alt text:** -```html - - - - -Bar chart showing 40% increase in Q3 sales - - - - - -
- 2024 market trends infographic -
- -
-
-``` - -**Icon buttons need accessible names:** -```html - - - - - - - - -``` - -**Visually hidden class:** -```css -.visually-hidden { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} -``` - -### Color contrast (1.4.3, 1.4.6) - -| Text Size | AA minimum | AAA enhanced | -|-----------|------------|--------------| -| Normal text (< 18px / < 14px bold) | 4.5:1 | 7:1 | -| Large text (≥ 18px / ≥ 14px bold) | 3:1 | 4.5:1 | -| UI components & graphics | 3:1 | 3:1 | - -```css -/* ❌ Low contrast (2.5:1) */ -.low-contrast { - color: #999; - background: #fff; -} - -/* ✅ Sufficient contrast (7:1) */ -.high-contrast { - color: #333; - background: #fff; -} - -/* ✅ Focus states need contrast too */ -:focus-visible { - outline: 2px solid #005fcc; - outline-offset: 2px; -} -``` - -**Don't rely on color alone:** -```html - - - - - -
- - - - Please enter a valid email address - -
-``` - -### Media alternatives (1.2) - -```html - - - - - -
- Transcript -

Full transcript text...

-
-``` - ---- - -## Operable - -### Keyboard accessible (2.1) - -**All functionality must be keyboard accessible:** -```javascript -// ❌ Only handles click -element.addEventListener('click', handleAction); - -// ✅ Handles both click and keyboard -element.addEventListener('click', handleAction); -element.addEventListener('keydown', (e) => { - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault(); - handleAction(); - } -}); -``` - -**No keyboard traps:** -```javascript -// Modal focus management -function openModal(modal) { - const focusableElements = modal.querySelectorAll( - 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' - ); - const firstElement = focusableElements[0]; - const lastElement = focusableElements[focusableElements.length - 1]; - - // Trap focus within modal - modal.addEventListener('keydown', (e) => { - if (e.key === 'Tab') { - if (e.shiftKey && document.activeElement === firstElement) { - e.preventDefault(); - lastElement.focus(); - } else if (!e.shiftKey && document.activeElement === lastElement) { - e.preventDefault(); - firstElement.focus(); - } - } - if (e.key === 'Escape') { - closeModal(); - } - }); - - firstElement.focus(); -} -``` - -### Focus visible (2.4.7) - -```css -/* ❌ Never remove focus outlines */ -*:focus { outline: none; } - -/* ✅ Use :focus-visible for keyboard-only focus */ -:focus { - outline: none; -} - -:focus-visible { - outline: 2px solid #005fcc; - outline-offset: 2px; -} - -/* ✅ Or custom focus styles */ -button:focus-visible { - box-shadow: 0 0 0 3px rgba(0, 95, 204, 0.5); -} -``` - -### Skip links (2.4.1) - -```html - - -
-
- -
- -``` - -```css -.skip-link { - position: absolute; - top: -40px; - left: 0; - background: #000; - color: #fff; - padding: 8px 16px; - z-index: 100; -} - -.skip-link:focus { - top: 0; -} -``` - -### Timing (2.2) - -```javascript -// Allow users to extend time limits -function showSessionWarning() { - const modal = createModal({ - title: 'Session Expiring', - content: 'Your session will expire in 2 minutes.', - actions: [ - { label: 'Extend session', action: extendSession }, - { label: 'Log out', action: logout } - ], - timeout: 120000 // 2 minutes to respond - }); -} -``` - -### Motion (2.3) - -```css -/* Respect reduced motion preference */ -@media (prefers-reduced-motion: reduce) { - *, - *::before, - *::after { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - scroll-behavior: auto !important; - } -} -``` - ---- - -## Understandable - -### Page language (3.1.1) - -```html - - - - - - - -

The French word for hello is bonjour.

-``` - -### Consistent navigation (3.2.3) - -```html - - -``` - -### Form labels (3.3.2) - -```html - - - - - - - - - - - - - -

- Must be at least 8 characters with one number. -

-``` - -### Error handling (3.3.1, 3.3.3) - -```html - -
-
- - - -
-
-``` - -```javascript -// Focus first error on submit -form.addEventListener('submit', (e) => { - const firstError = form.querySelector('[aria-invalid="true"]'); - if (firstError) { - e.preventDefault(); - firstError.focus(); - - // Announce error summary - const errorSummary = document.getElementById('error-summary'); - errorSummary.textContent = `${errors.length} errors found. Please fix them and try again.`; - errorSummary.focus(); - } -}); -``` - ---- - -## Robust - -### Valid HTML (4.1.1) - -```html - -
...
-
...
- - - - - -
...
- - - -Click -``` - -### ARIA usage (4.1.2) - -**Prefer native elements:** -```html - -
Click me
- - - - - -
Option
- - - -``` - -**When ARIA is needed:** -```html - -
- - -
-
- -
- -``` - -### Live regions (4.1.3) - -```html - -
- -
- - -
- -
-``` - -```javascript -// Announce dynamic content changes -function showNotification(message, type = 'polite') { - const container = document.getElementById(`${type}-announcer`); - container.textContent = ''; // Clear first - requestAnimationFrame(() => { - container.textContent = message; - }); -} -``` - ---- - -## Testing checklist - -### Automated testing -```bash -# Lighthouse accessibility audit -npx lighthouse https://example.com --only-categories=accessibility - -# axe-core -npm install @axe-core/cli -g -axe https://example.com -``` - -### Manual testing - -- [ ] **Keyboard navigation:** Tab through entire page, use Enter/Space to activate -- [ ] **Screen reader:** Test with VoiceOver (Mac), NVDA (Windows), or TalkBack (Android) -- [ ] **Zoom:** Content usable at 200% zoom -- [ ] **High contrast:** Test with Windows High Contrast Mode -- [ ] **Reduced motion:** Test with `prefers-reduced-motion: reduce` -- [ ] **Focus order:** Logical and follows visual order - -### Screen reader commands - -| Action | VoiceOver (Mac) | NVDA (Windows) | -|--------|-----------------|----------------| -| Start/Stop | ⌘ + F5 | Ctrl + Alt + N | -| Next item | VO + → | ↓ | -| Previous item | VO + ← | ↑ | -| Activate | VO + Space | Enter | -| Headings list | VO + U, then arrows | H / Shift + H | -| Links list | VO + U | K / Shift + K | - ---- - -## Common issues by impact - -### Critical (fix immediately) -1. Missing form labels -2. Missing image alt text -3. Insufficient color contrast -4. Keyboard traps -5. No focus indicators - -### Serious (fix before launch) -1. Missing page language -2. Missing heading structure -3. Non-descriptive link text -4. Auto-playing media -5. Missing skip links - -### Moderate (fix soon) -1. Missing ARIA labels on icons -2. Inconsistent navigation -3. Missing error identification -4. Timing without controls -5. Missing landmark regions - -## References - -- [WCAG 2.1 Quick Reference](https://www.w3.org/WAI/WCAG21/quickref/) -- [WAI-ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/) -- [Deque axe Rules](https://dequeuniversity.com/rules/axe/) -- [Web Quality Audit](../web-quality-audit/SKILL.md) diff --git a/src/resources/skills/accessibility/references/WCAG.md b/src/resources/skills/accessibility/references/WCAG.md deleted file mode 100644 index a2b7c9827..000000000 --- a/src/resources/skills/accessibility/references/WCAG.md +++ /dev/null @@ -1,162 +0,0 @@ -# WCAG 2.1 Quick Reference - -## Success criteria by level - -### Level A (minimum) - -| Criterion | Description | -|-----------|-------------| -| **1.1.1** Non-text Content | All images, icons have text alternatives | -| **1.2.1** Audio-only/Video-only | Provide transcript or audio description | -| **1.2.2** Captions | Video with audio has captions | -| **1.2.3** Audio Description | Video has audio description | -| **1.3.1** Info and Relationships | Information conveyed through presentation is available programmatically | -| **1.3.2** Meaningful Sequence | Reading order is logical | -| **1.3.3** Sensory Characteristics | Instructions don't rely solely on shape, color, size, location, orientation, or sound | -| **1.4.1** Use of Color | Color is not the only visual means of conveying information | -| **1.4.2** Audio Control | Audio playing automatically can be paused/stopped | -| **2.1.1** Keyboard | All functionality available via keyboard | -| **2.1.2** No Keyboard Trap | Keyboard focus can be moved away from any component | -| **2.1.4** Character Key Shortcuts | Single-key shortcuts can be turned off or remapped | -| **2.2.1** Timing Adjustable | Time limits can be extended | -| **2.2.2** Pause, Stop, Hide | Moving/blinking content can be paused | -| **2.3.1** Three Flashes | Nothing flashes more than 3 times per second | -| **2.4.1** Bypass Blocks | Skip link or landmark navigation available | -| **2.4.2** Page Titled | Pages have descriptive titles | -| **2.4.3** Focus Order | Focus order preserves meaning | -| **2.4.4** Link Purpose | Link purpose clear from link text or context | -| **2.5.1** Pointer Gestures | Multi-point gestures have single-pointer alternatives | -| **2.5.2** Pointer Cancellation | Down-event doesn't trigger action (use up-event or click) | -| **2.5.3** Label in Name | Accessible name contains visible label text | -| **2.5.4** Motion Actuation | Motion-triggered functions have alternatives | -| **3.1.1** Language of Page | Default language specified in HTML | -| **3.2.1** On Focus | Focus doesn't trigger unexpected changes | -| **3.2.2** On Input | Input doesn't trigger unexpected changes | -| **3.3.1** Error Identification | Input errors clearly described | -| **3.3.2** Labels or Instructions | Form inputs have labels or instructions | -| **4.1.1** Parsing | HTML is well-formed (no duplicate IDs, proper nesting) | -| **4.1.2** Name, Role, Value | UI components have accessible names and correct roles | - -### Level AA (standard) - -| Criterion | Description | -|-----------|-------------| -| **1.2.4** Captions (Live) | Live audio has captions | -| **1.2.5** Audio Description | Pre-recorded video has audio description | -| **1.3.4** Orientation | Content doesn't restrict orientation | -| **1.3.5** Identify Input Purpose | Input purpose can be programmatically determined | -| **1.4.3** Contrast (Minimum) | 4.5:1 for normal text, 3:1 for large text | -| **1.4.4** Resize Text | Text can be resized to 200% without loss of functionality | -| **1.4.5** Images of Text | Text used instead of images of text | -| **1.4.10** Reflow | Content reflows at 320px width without horizontal scroll | -| **1.4.11** Non-text Contrast | UI components have 3:1 contrast | -| **1.4.12** Text Spacing | Content adapts to text spacing changes | -| **1.4.13** Content on Hover/Focus | Additional content is dismissible, hoverable, persistent | -| **2.4.5** Multiple Ways | Multiple ways to find pages | -| **2.4.6** Headings and Labels | Headings and labels are descriptive | -| **2.4.7** Focus Visible | Focus indicator is visible | -| **3.1.2** Language of Parts | Language changes are marked | -| **3.2.3** Consistent Navigation | Navigation is consistent across pages | -| **3.2.4** Consistent Identification | Same functionality uses same labels | -| **3.3.3** Error Suggestion | Error corrections suggested when known | -| **3.3.4** Error Prevention (Legal) | Actions can be reversed or confirmed | -| **4.1.3** Status Messages | Status messages announced to screen readers | - -### Level AAA (enhanced) - -| Criterion | Description | -|-----------|-------------| -| **1.4.6** Contrast (Enhanced) | 7:1 for normal text, 4.5:1 for large text | -| **1.4.8** Visual Presentation | Foreground/background colors can be selected | -| **1.4.9** Images of Text (No Exception) | No images of text | -| **2.1.3** Keyboard (No Exception) | All functionality keyboard accessible | -| **2.2.3** No Timing | No time limits | -| **2.2.4** Interruptions | Interruptions can be postponed | -| **2.2.5** Re-authenticating | Data preserved on re-authentication | -| **2.2.6** Timeouts | Users warned about data loss from inactivity | -| **2.3.2** Three Flashes | No content flashes more than 3 times | -| **2.3.3** Animation from Interactions | Motion animation can be disabled | -| **2.4.8** Location | User location within site is available | -| **2.4.9** Link Purpose (Link Only) | Link purpose clear from link text alone | -| **2.4.10** Section Headings | Sections have headings | -| **3.1.3** Unusual Words | Definitions available for unusual words | -| **3.1.4** Abbreviations | Abbreviations expanded | -| **3.1.5** Reading Level | Alternative content for complex text | -| **3.1.6** Pronunciation | Pronunciation available where needed | -| **3.2.5** Change on Request | Changes initiated only by user | -| **3.3.5** Help | Context-sensitive help available | -| **3.3.6** Error Prevention (All) | All form submissions can be reviewed | - -## Common ARIA patterns - -### Buttons -```html - - - -``` - -### Links -```html -Descriptive link text - - - External site - (opens in new tab) - -``` - -### Form fields -```html - - -

We'll never share your email.

-``` - -### Error states -```html - - - -``` - -### Navigation -```html - -``` - -### Modals -```html -
-

Confirm Action

- -
-``` - -### Live regions -```html - -
Status update here
- - -
Error message here
- - -
Loading complete
-``` - -## Testing tools - -| Tool | Type | URL | -|------|------|-----| -| axe DevTools | Browser extension | [deque.com/axe](https://www.deque.com/axe/) | -| WAVE | Browser extension | [wave.webaim.org](https://wave.webaim.org/) | -| Lighthouse | Built into Chrome | DevTools → Lighthouse | -| NVDA | Screen reader (Windows) | [nvaccess.org](https://www.nvaccess.org/) | -| VoiceOver | Screen reader (Mac) | Built into macOS | -| Colour Contrast Analyser | Desktop app | [tpgi.com](https://www.tpgi.com/color-contrast-checker/) | diff --git a/src/resources/skills/agent-browser/SKILL.md b/src/resources/skills/agent-browser/SKILL.md deleted file mode 100644 index 8cd7b7a79..000000000 --- a/src/resources/skills/agent-browser/SKILL.md +++ /dev/null @@ -1,517 +0,0 @@ ---- -name: agent-browser -description: Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. -allowed-tools: Bash(npx agent-browser:*), Bash(agent-browser:*) ---- - -# Browser Automation with agent-browser - -## Core Workflow - -Every browser automation follows this pattern: - -1. **Navigate**: `agent-browser open ` -2. **Snapshot**: `agent-browser snapshot -i` (get element refs like `@e1`, `@e2`) -3. **Interact**: Use refs to click, fill, select -4. **Re-snapshot**: After navigation or DOM changes, get fresh refs - -```bash -agent-browser open https://example.com/form -agent-browser snapshot -i -# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit" - -agent-browser fill @e1 "user@example.com" -agent-browser fill @e2 "password123" -agent-browser click @e3 -agent-browser wait --load networkidle -agent-browser snapshot -i # Check result -``` - -## Command Chaining - -Commands can be chained with `&&` in a single shell invocation. The browser persists between commands via a background daemon, so chaining is safe and more efficient than separate calls. - -```bash -# Chain open + wait + snapshot in one call -agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i - -# Chain multiple interactions -agent-browser fill @e1 "user@example.com" && agent-browser fill @e2 "password123" && agent-browser click @e3 - -# Navigate and capture -agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser screenshot page.png -``` - -**When to chain:** Use `&&` when you don't need to read the output of an intermediate command before proceeding (e.g., open + wait + screenshot). Run commands separately when you need to parse the output first (e.g., snapshot to discover refs, then interact using those refs). - -## Essential Commands - -```bash -# Navigation -agent-browser open # Navigate (aliases: goto, navigate) -agent-browser close # Close browser - -# Snapshot -agent-browser snapshot -i # Interactive elements with refs (recommended) -agent-browser snapshot -i -C # Include cursor-interactive elements (divs with onclick, cursor:pointer) -agent-browser snapshot -s "#selector" # Scope to CSS selector - -# Interaction (use @refs from snapshot) -agent-browser click @e1 # Click element -agent-browser click @e1 --new-tab # Click and open in new tab -agent-browser fill @e2 "text" # Clear and type text -agent-browser type @e2 "text" # Type without clearing -agent-browser select @e1 "option" # Select dropdown option -agent-browser check @e1 # Check checkbox -agent-browser press Enter # Press key -agent-browser keyboard type "text" # Type at current focus (no selector) -agent-browser keyboard inserttext "text" # Insert without key events -agent-browser scroll down 500 # Scroll page -agent-browser scroll down 500 --selector "div.content" # Scroll within a specific container - -# Get information -agent-browser get text @e1 # Get element text -agent-browser get url # Get current URL -agent-browser get title # Get page title - -# Wait -agent-browser wait @e1 # Wait for element -agent-browser wait --load networkidle # Wait for network idle -agent-browser wait --url "**/page" # Wait for URL pattern -agent-browser wait 2000 # Wait milliseconds - -# Downloads -agent-browser download @e1 ./file.pdf # Click element to trigger download -agent-browser wait --download ./output.zip # Wait for any download to complete -agent-browser --download-path ./downloads open # Set default download directory - -# Capture -agent-browser screenshot # Screenshot to temp dir -agent-browser screenshot --full # Full page screenshot -agent-browser screenshot --annotate # Annotated screenshot with numbered element labels -agent-browser pdf output.pdf # Save as PDF - -# Diff (compare page states) -agent-browser diff snapshot # Compare current vs last snapshot -agent-browser diff snapshot --baseline before.txt # Compare current vs saved file -agent-browser diff screenshot --baseline before.png # Visual pixel diff -agent-browser diff url # Compare two pages -agent-browser diff url --wait-until networkidle # Custom wait strategy -agent-browser diff url --selector "#main" # Scope to element -``` - -## Common Patterns - -### Form Submission - -```bash -agent-browser open https://example.com/signup -agent-browser snapshot -i -agent-browser fill @e1 "Jane Doe" -agent-browser fill @e2 "jane@example.com" -agent-browser select @e3 "California" -agent-browser check @e4 -agent-browser click @e5 -agent-browser wait --load networkidle -``` - -### Authentication with Auth Vault (Recommended) - -```bash -# Save credentials once (encrypted with AGENT_BROWSER_ENCRYPTION_KEY) -# Recommended: pipe password via stdin to avoid shell history exposure -echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin - -# Login using saved profile (LLM never sees password) -agent-browser auth login github - -# List/show/delete profiles -agent-browser auth list -agent-browser auth show github -agent-browser auth delete github -``` - -### Authentication with State Persistence - -```bash -# Login once and save state -agent-browser open https://app.example.com/login -agent-browser snapshot -i -agent-browser fill @e1 "$USERNAME" -agent-browser fill @e2 "$PASSWORD" -agent-browser click @e3 -agent-browser wait --url "**/dashboard" -agent-browser state save auth.json - -# Reuse in future sessions -agent-browser state load auth.json -agent-browser open https://app.example.com/dashboard -``` - -### Session Persistence - -```bash -# Auto-save/restore cookies and localStorage across browser restarts -agent-browser --session-name myapp open https://app.example.com/login -# ... login flow ... -agent-browser close # State auto-saved to ~/.agent-browser/sessions/ - -# Next time, state is auto-loaded -agent-browser --session-name myapp open https://app.example.com/dashboard - -# Encrypt state at rest -export AGENT_BROWSER_ENCRYPTION_KEY=$(openssl rand -hex 32) -agent-browser --session-name secure open https://app.example.com - -# Manage saved states -agent-browser state list -agent-browser state show myapp-default.json -agent-browser state clear myapp -agent-browser state clean --older-than 7 -``` - -### Data Extraction - -```bash -agent-browser open https://example.com/products -agent-browser snapshot -i -agent-browser get text @e5 # Get specific element text -agent-browser get text body > page.txt # Get all page text - -# JSON output for parsing -agent-browser snapshot -i --json -agent-browser get text @e1 --json -``` - -### Parallel Sessions - -```bash -agent-browser --session site1 open https://site-a.com -agent-browser --session site2 open https://site-b.com - -agent-browser --session site1 snapshot -i -agent-browser --session site2 snapshot -i - -agent-browser session list -``` - -### Connect to Existing Chrome - -```bash -# Auto-discover running Chrome with remote debugging enabled -agent-browser --auto-connect open https://example.com -agent-browser --auto-connect snapshot - -# Or with explicit CDP port -agent-browser --cdp 9222 snapshot -``` - -### Color Scheme (Dark Mode) - -```bash -# Persistent dark mode via flag (applies to all pages and new tabs) -agent-browser --color-scheme dark open https://example.com - -# Or via environment variable -AGENT_BROWSER_COLOR_SCHEME=dark agent-browser open https://example.com - -# Or set during session (persists for subsequent commands) -agent-browser set media dark -``` - -### Visual Browser (Debugging) - -```bash -agent-browser --headed open https://example.com -agent-browser highlight @e1 # Highlight element -agent-browser record start demo.webm # Record session -agent-browser profiler start # Start Chrome DevTools profiling -agent-browser profiler stop trace.json # Stop and save profile (path optional) -``` - -Use `AGENT_BROWSER_HEADED=1` to enable headed mode via environment variable. Browser extensions work in both headed and headless mode. - -### Local Files (PDFs, HTML) - -```bash -# Open local files with file:// URLs -agent-browser --allow-file-access open file:///path/to/document.pdf -agent-browser --allow-file-access open file:///path/to/page.html -agent-browser screenshot output.png -``` - -### iOS Simulator (Mobile Safari) - -```bash -# List available iOS simulators -agent-browser device list - -# Launch Safari on a specific device -agent-browser -p ios --device "iPhone 16 Pro" open https://example.com - -# Same workflow as desktop - snapshot, interact, re-snapshot -agent-browser -p ios snapshot -i -agent-browser -p ios tap @e1 # Tap (alias for click) -agent-browser -p ios fill @e2 "text" -agent-browser -p ios swipe up # Mobile-specific gesture - -# Take screenshot -agent-browser -p ios screenshot mobile.png - -# Close session (shuts down simulator) -agent-browser -p ios close -``` - -**Requirements:** macOS with Xcode, Appium (`npm install -g appium && appium driver install xcuitest`) - -**Real devices:** Works with physical iOS devices if pre-configured. Use `--device ""` where UDID is from `xcrun xctrace list devices`. - -## Security - -All security features are opt-in. By default, agent-browser imposes no restrictions on navigation, actions, or output. - -### Content Boundaries (Recommended for AI Agents) - -Enable `--content-boundaries` to wrap page-sourced output in markers that help LLMs distinguish tool output from untrusted page content: - -```bash -export AGENT_BROWSER_CONTENT_BOUNDARIES=1 -agent-browser snapshot -# Output: -# --- AGENT_BROWSER_PAGE_CONTENT nonce= origin=https://example.com --- -# [accessibility tree] -# --- END_AGENT_BROWSER_PAGE_CONTENT nonce= --- -``` - -### Domain Allowlist - -Restrict navigation to trusted domains. Wildcards like `*.example.com` also match the bare domain `example.com`. Sub-resource requests, WebSocket, and EventSource connections to non-allowed domains are also blocked. Include CDN domains your target pages depend on: - -```bash -export AGENT_BROWSER_ALLOWED_DOMAINS="example.com,*.example.com" -agent-browser open https://example.com # OK -agent-browser open https://malicious.com # Blocked -``` - -### Action Policy - -Use a policy file to gate destructive actions: - -```bash -export AGENT_BROWSER_ACTION_POLICY=./policy.json -``` - -Example `policy.json`: -```json -{"default": "deny", "allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"]} -``` - -Auth vault operations (`auth login`, etc.) bypass action policy but domain allowlist still applies. - -### Output Limits - -Prevent context flooding from large pages: - -```bash -export AGENT_BROWSER_MAX_OUTPUT=50000 -``` - -## Diffing (Verifying Changes) - -Use `diff snapshot` after performing an action to verify it had the intended effect. This compares the current accessibility tree against the last snapshot taken in the session. - -```bash -# Typical workflow: snapshot -> action -> diff -agent-browser snapshot -i # Take baseline snapshot -agent-browser click @e2 # Perform action -agent-browser diff snapshot # See what changed (auto-compares to last snapshot) -``` - -For visual regression testing or monitoring: - -```bash -# Save a baseline screenshot, then compare later -agent-browser screenshot baseline.png -# ... time passes or changes are made ... -agent-browser diff screenshot --baseline baseline.png - -# Compare staging vs production -agent-browser diff url https://staging.example.com https://prod.example.com --screenshot -``` - -`diff snapshot` output uses `+` for additions and `-` for removals, similar to git diff. `diff screenshot` produces a diff image with changed pixels highlighted in red, plus a mismatch percentage. - -## Timeouts and Slow Pages - -The default Playwright timeout is 25 seconds for local browsers. This can be overridden with the `AGENT_BROWSER_DEFAULT_TIMEOUT` environment variable (value in milliseconds). For slow websites or large pages, use explicit waits instead of relying on the default timeout: - -```bash -# Wait for network activity to settle (best for slow pages) -agent-browser wait --load networkidle - -# Wait for a specific element to appear -agent-browser wait "#content" -agent-browser wait @e1 - -# Wait for a specific URL pattern (useful after redirects) -agent-browser wait --url "**/dashboard" - -# Wait for a JavaScript condition -agent-browser wait --fn "document.readyState === 'complete'" - -# Wait a fixed duration (milliseconds) as a last resort -agent-browser wait 5000 -``` - -When dealing with consistently slow websites, use `wait --load networkidle` after `open` to ensure the page is fully loaded before taking a snapshot. If a specific element is slow to render, wait for it directly with `wait ` or `wait @ref`. - -## Session Management and Cleanup - -When running multiple agents or automations concurrently, always use named sessions to avoid conflicts: - -```bash -# Each agent gets its own isolated session -agent-browser --session agent1 open site-a.com -agent-browser --session agent2 open site-b.com - -# Check active sessions -agent-browser session list -``` - -Always close your browser session when done to avoid leaked processes: - -```bash -agent-browser close # Close default session -agent-browser --session agent1 close # Close specific session -``` - -If a previous session was not closed properly, the daemon may still be running. Use `agent-browser close` to clean it up before starting new work. - -## Ref Lifecycle (Important) - -Refs (`@e1`, `@e2`, etc.) are invalidated when the page changes. Always re-snapshot after: - -- Clicking links or buttons that navigate -- Form submissions -- Dynamic content loading (dropdowns, modals) - -```bash -agent-browser click @e5 # Navigates to new page -agent-browser snapshot -i # MUST re-snapshot -agent-browser click @e1 # Use new refs -``` - -## Annotated Screenshots (Vision Mode) - -Use `--annotate` to take a screenshot with numbered labels overlaid on interactive elements. Each label `[N]` maps to ref `@eN`. This also caches refs, so you can interact with elements immediately without a separate snapshot. - -```bash -agent-browser screenshot --annotate -# Output includes the image path and a legend: -# [1] @e1 button "Submit" -# [2] @e2 link "Home" -# [3] @e3 textbox "Email" -agent-browser click @e2 # Click using ref from annotated screenshot -``` - -Use annotated screenshots when: -- The page has unlabeled icon buttons or visual-only elements -- You need to verify visual layout or styling -- Canvas or chart elements are present (invisible to text snapshots) -- You need spatial reasoning about element positions - -## Semantic Locators (Alternative to Refs) - -When refs are unavailable or unreliable, use semantic locators: - -```bash -agent-browser find text "Sign In" click -agent-browser find label "Email" fill "user@test.com" -agent-browser find role button click --name "Submit" -agent-browser find placeholder "Search" type "query" -agent-browser find testid "submit-btn" click -``` - -## JavaScript Evaluation (eval) - -Use `eval` to run JavaScript in the browser context. **Shell quoting can corrupt complex expressions** -- use `--stdin` or `-b` to avoid issues. - -```bash -# Simple expressions work with regular quoting -agent-browser eval 'document.title' -agent-browser eval 'document.querySelectorAll("img").length' - -# Complex JS: use --stdin with heredoc (RECOMMENDED) -agent-browser eval --stdin <<'EVALEOF' -JSON.stringify( - Array.from(document.querySelectorAll("img")) - .filter(i => !i.alt) - .map(i => ({ src: i.src.split("/").pop(), width: i.width })) -) -EVALEOF - -# Alternative: base64 encoding (avoids all shell escaping issues) -agent-browser eval -b "$(echo -n 'Array.from(document.querySelectorAll("a")).map(a => a.href)' | base64)" -``` - -**Why this matters:** When the shell processes your command, inner double quotes, `!` characters (history expansion), backticks, and `$()` can all corrupt the JavaScript before it reaches agent-browser. The `--stdin` and `-b` flags bypass shell interpretation entirely. - -**Rules of thumb:** -- Single-line, no nested quotes -> regular `eval 'expression'` with single quotes is fine -- Nested quotes, arrow functions, template literals, or multiline -> use `eval --stdin <<'EVALEOF'` -- Programmatic/generated scripts -> use `eval -b` with base64 - -## Configuration File - -Create `agent-browser.json` in the project root for persistent settings: - -```json -{ - "headed": true, - "proxy": "http://localhost:8080", - "profile": "./browser-data" -} -``` - -Priority (lowest to highest): `~/.agent-browser/config.json` < `./agent-browser.json` < env vars < CLI flags. Use `--config ` or `AGENT_BROWSER_CONFIG` env var for a custom config file (exits with error if missing/invalid). All CLI options map to camelCase keys (e.g., `--executable-path` -> `"executablePath"`). Boolean flags accept `true`/`false` values (e.g., `--headed false` overrides config). Extensions from user and project configs are merged, not replaced. - -## Deep-Dive Documentation - -| Reference | When to Use | -|-----------|-------------| -| [references/commands.md](references/commands.md) | Full command reference with all options | -| [references/snapshot-refs.md](references/snapshot-refs.md) | Ref lifecycle, invalidation rules, troubleshooting | -| [references/session-management.md](references/session-management.md) | Parallel sessions, state persistence, concurrent scraping | -| [references/authentication.md](references/authentication.md) | Login flows, OAuth, 2FA handling, state reuse | -| [references/video-recording.md](references/video-recording.md) | Recording workflows for debugging and documentation | -| [references/profiling.md](references/profiling.md) | Chrome DevTools profiling for performance analysis | -| [references/proxy-support.md](references/proxy-support.md) | Proxy configuration, geo-testing, rotating proxies | - -## Experimental: Native Mode - -agent-browser has an experimental native Rust daemon that communicates with Chrome directly via CDP, bypassing Node.js and Playwright entirely. It is opt-in and not recommended for production use yet. - -```bash -# Enable via flag -agent-browser --native open example.com - -# Enable via environment variable (avoids passing --native every time) -export AGENT_BROWSER_NATIVE=1 -agent-browser open example.com -``` - -The native daemon supports Chromium and Safari (via WebDriver). Firefox and WebKit are not yet supported. All core commands (navigate, snapshot, click, fill, screenshot, cookies, storage, tabs, eval, etc.) work identically in native mode. Use `agent-browser close` before switching between native and default mode within the same session. - -## Ready-to-Use Templates - -| Template | Description | -|----------|-------------| -| [templates/form-automation.sh](templates/form-automation.sh) | Form filling with validation | -| [templates/authenticated-session.sh](templates/authenticated-session.sh) | Login once, reuse state | -| [templates/capture-workflow.sh](templates/capture-workflow.sh) | Content extraction with screenshots | - -```bash -./templates/form-automation.sh https://example.com/form -./templates/authenticated-session.sh https://app.example.com/login -./templates/capture-workflow.sh https://example.com ./output -``` diff --git a/src/resources/skills/agent-browser/references/authentication.md b/src/resources/skills/agent-browser/references/authentication.md deleted file mode 100644 index 12ef5e41b..000000000 --- a/src/resources/skills/agent-browser/references/authentication.md +++ /dev/null @@ -1,202 +0,0 @@ -# Authentication Patterns - -Login flows, session persistence, OAuth, 2FA, and authenticated browsing. - -**Related**: [session-management.md](session-management.md) for state persistence details, [SKILL.md](../SKILL.md) for quick start. - -## Contents - -- [Basic Login Flow](#basic-login-flow) -- [Saving Authentication State](#saving-authentication-state) -- [Restoring Authentication](#restoring-authentication) -- [OAuth / SSO Flows](#oauth--sso-flows) -- [Two-Factor Authentication](#two-factor-authentication) -- [HTTP Basic Auth](#http-basic-auth) -- [Cookie-Based Auth](#cookie-based-auth) -- [Token Refresh Handling](#token-refresh-handling) -- [Security Best Practices](#security-best-practices) - -## Basic Login Flow - -```bash -# Navigate to login page -agent-browser open https://app.example.com/login -agent-browser wait --load networkidle - -# Get form elements -agent-browser snapshot -i -# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Sign In" - -# Fill credentials -agent-browser fill @e1 "user@example.com" -agent-browser fill @e2 "password123" - -# Submit -agent-browser click @e3 -agent-browser wait --load networkidle - -# Verify login succeeded -agent-browser get url # Should be dashboard, not login -``` - -## Saving Authentication State - -After logging in, save state for reuse: - -```bash -# Login first (see above) -agent-browser open https://app.example.com/login -agent-browser snapshot -i -agent-browser fill @e1 "user@example.com" -agent-browser fill @e2 "password123" -agent-browser click @e3 -agent-browser wait --url "**/dashboard" - -# Save authenticated state -agent-browser state save ./auth-state.json -``` - -## Restoring Authentication - -Skip login by loading saved state: - -```bash -# Load saved auth state -agent-browser state load ./auth-state.json - -# Navigate directly to protected page -agent-browser open https://app.example.com/dashboard - -# Verify authenticated -agent-browser snapshot -i -``` - -## OAuth / SSO Flows - -For OAuth redirects: - -```bash -# Start OAuth flow -agent-browser open https://app.example.com/auth/google - -# Handle redirects automatically -agent-browser wait --url "**/accounts.google.com**" -agent-browser snapshot -i - -# Fill Google credentials -agent-browser fill @e1 "user@gmail.com" -agent-browser click @e2 # Next button -agent-browser wait 2000 -agent-browser snapshot -i -agent-browser fill @e3 "password" -agent-browser click @e4 # Sign in - -# Wait for redirect back -agent-browser wait --url "**/app.example.com**" -agent-browser state save ./oauth-state.json -``` - -## Two-Factor Authentication - -Handle 2FA with manual intervention: - -```bash -# Login with credentials -agent-browser open https://app.example.com/login --headed # Show browser -agent-browser snapshot -i -agent-browser fill @e1 "user@example.com" -agent-browser fill @e2 "password123" -agent-browser click @e3 - -# Wait for user to complete 2FA manually -echo "Complete 2FA in the browser window..." -agent-browser wait --url "**/dashboard" --timeout 120000 - -# Save state after 2FA -agent-browser state save ./2fa-state.json -``` - -## HTTP Basic Auth - -For sites using HTTP Basic Authentication: - -```bash -# Set credentials before navigation -agent-browser set credentials username password - -# Navigate to protected resource -agent-browser open https://protected.example.com/api -``` - -## Cookie-Based Auth - -Manually set authentication cookies: - -```bash -# Set auth cookie -agent-browser cookies set session_token "abc123xyz" - -# Navigate to protected page -agent-browser open https://app.example.com/dashboard -``` - -## Token Refresh Handling - -For sessions with expiring tokens: - -```bash -#!/bin/bash -# Wrapper that handles token refresh - -STATE_FILE="./auth-state.json" - -# Try loading existing state -if [[ -f "$STATE_FILE" ]]; then - agent-browser state load "$STATE_FILE" - agent-browser open https://app.example.com/dashboard - - # Check if session is still valid - URL=$(agent-browser get url) - if [[ "$URL" == *"/login"* ]]; then - echo "Session expired, re-authenticating..." - # Perform fresh login - agent-browser snapshot -i - agent-browser fill @e1 "$USERNAME" - agent-browser fill @e2 "$PASSWORD" - agent-browser click @e3 - agent-browser wait --url "**/dashboard" - agent-browser state save "$STATE_FILE" - fi -else - # First-time login - agent-browser open https://app.example.com/login - # ... login flow ... -fi -``` - -## Security Best Practices - -1. **Never commit state files** - They contain session tokens - ```bash - echo "*.auth-state.json" >> .gitignore - ``` - -2. **Use environment variables for credentials** - ```bash - agent-browser fill @e1 "$APP_USERNAME" - agent-browser fill @e2 "$APP_PASSWORD" - ``` - -3. **Clean up after automation** - ```bash - agent-browser cookies clear - rm -f ./auth-state.json - ``` - -4. **Use short-lived sessions for CI/CD** - ```bash - # Don't persist state in CI - agent-browser open https://app.example.com/login - # ... login and perform actions ... - agent-browser close # Session ends, nothing persisted - ``` diff --git a/src/resources/skills/agent-browser/references/commands.md b/src/resources/skills/agent-browser/references/commands.md deleted file mode 100644 index e77196cdd..000000000 --- a/src/resources/skills/agent-browser/references/commands.md +++ /dev/null @@ -1,263 +0,0 @@ -# Command Reference - -Complete reference for all agent-browser commands. For quick start and common patterns, see SKILL.md. - -## Navigation - -```bash -agent-browser open # Navigate to URL (aliases: goto, navigate) - # Supports: https://, http://, file://, about:, data:// - # Auto-prepends https:// if no protocol given -agent-browser back # Go back -agent-browser forward # Go forward -agent-browser reload # Reload page -agent-browser close # Close browser (aliases: quit, exit) -agent-browser connect 9222 # Connect to browser via CDP port -``` - -## Snapshot (page analysis) - -```bash -agent-browser snapshot # Full accessibility tree -agent-browser snapshot -i # Interactive elements only (recommended) -agent-browser snapshot -c # Compact output -agent-browser snapshot -d 3 # Limit depth to 3 -agent-browser snapshot -s "#main" # Scope to CSS selector -``` - -## Interactions (use @refs from snapshot) - -```bash -agent-browser click @e1 # Click -agent-browser click @e1 --new-tab # Click and open in new tab -agent-browser dblclick @e1 # Double-click -agent-browser focus @e1 # Focus element -agent-browser fill @e2 "text" # Clear and type -agent-browser type @e2 "text" # Type without clearing -agent-browser press Enter # Press key (alias: key) -agent-browser press Control+a # Key combination -agent-browser keydown Shift # Hold key down -agent-browser keyup Shift # Release key -agent-browser hover @e1 # Hover -agent-browser check @e1 # Check checkbox -agent-browser uncheck @e1 # Uncheck checkbox -agent-browser select @e1 "value" # Select dropdown option -agent-browser select @e1 "a" "b" # Select multiple options -agent-browser scroll down 500 # Scroll page (default: down 300px) -agent-browser scrollintoview @e1 # Scroll element into view (alias: scrollinto) -agent-browser drag @e1 @e2 # Drag and drop -agent-browser upload @e1 file.pdf # Upload files -``` - -## Get Information - -```bash -agent-browser get text @e1 # Get element text -agent-browser get html @e1 # Get innerHTML -agent-browser get value @e1 # Get input value -agent-browser get attr @e1 href # Get attribute -agent-browser get title # Get page title -agent-browser get url # Get current URL -agent-browser get count ".item" # Count matching elements -agent-browser get box @e1 # Get bounding box -agent-browser get styles @e1 # Get computed styles (font, color, bg, etc.) -``` - -## Check State - -```bash -agent-browser is visible @e1 # Check if visible -agent-browser is enabled @e1 # Check if enabled -agent-browser is checked @e1 # Check if checked -``` - -## Screenshots and PDF - -```bash -agent-browser screenshot # Save to temporary directory -agent-browser screenshot path.png # Save to specific path -agent-browser screenshot --full # Full page -agent-browser pdf output.pdf # Save as PDF -``` - -## Video Recording - -```bash -agent-browser record start ./demo.webm # Start recording -agent-browser click @e1 # Perform actions -agent-browser record stop # Stop and save video -agent-browser record restart ./take2.webm # Stop current + start new -``` - -## Wait - -```bash -agent-browser wait @e1 # Wait for element -agent-browser wait 2000 # Wait milliseconds -agent-browser wait --text "Success" # Wait for text (or -t) -agent-browser wait --url "**/dashboard" # Wait for URL pattern (or -u) -agent-browser wait --load networkidle # Wait for network idle (or -l) -agent-browser wait --fn "window.ready" # Wait for JS condition (or -f) -``` - -## Mouse Control - -```bash -agent-browser mouse move 100 200 # Move mouse -agent-browser mouse down left # Press button -agent-browser mouse up left # Release button -agent-browser mouse wheel 100 # Scroll wheel -``` - -## Semantic Locators (alternative to refs) - -```bash -agent-browser find role button click --name "Submit" -agent-browser find text "Sign In" click -agent-browser find text "Sign In" click --exact # Exact match only -agent-browser find label "Email" fill "user@test.com" -agent-browser find placeholder "Search" type "query" -agent-browser find alt "Logo" click -agent-browser find title "Close" click -agent-browser find testid "submit-btn" click -agent-browser find first ".item" click -agent-browser find last ".item" click -agent-browser find nth 2 "a" hover -``` - -## Browser Settings - -```bash -agent-browser set viewport 1920 1080 # Set viewport size -agent-browser set device "iPhone 14" # Emulate device -agent-browser set geo 37.7749 -122.4194 # Set geolocation (alias: geolocation) -agent-browser set offline on # Toggle offline mode -agent-browser set headers '{"X-Key":"v"}' # Extra HTTP headers -agent-browser set credentials user pass # HTTP basic auth (alias: auth) -agent-browser set media dark # Emulate color scheme -agent-browser set media light reduced-motion # Light mode + reduced motion -``` - -## Cookies and Storage - -```bash -agent-browser cookies # Get all cookies -agent-browser cookies set name value # Set cookie -agent-browser cookies clear # Clear cookies -agent-browser storage local # Get all localStorage -agent-browser storage local key # Get specific key -agent-browser storage local set k v # Set value -agent-browser storage local clear # Clear all -``` - -## Network - -```bash -agent-browser network route # Intercept requests -agent-browser network route --abort # Block requests -agent-browser network route --body '{}' # Mock response -agent-browser network unroute [url] # Remove routes -agent-browser network requests # View tracked requests -agent-browser network requests --filter api # Filter requests -``` - -## Tabs and Windows - -```bash -agent-browser tab # List tabs -agent-browser tab new [url] # New tab -agent-browser tab 2 # Switch to tab by index -agent-browser tab close # Close current tab -agent-browser tab close 2 # Close tab by index -agent-browser window new # New window -``` - -## Frames - -```bash -agent-browser frame "#iframe" # Switch to iframe -agent-browser frame main # Back to main frame -``` - -## Dialogs - -```bash -agent-browser dialog accept [text] # Accept dialog -agent-browser dialog dismiss # Dismiss dialog -``` - -## JavaScript - -```bash -agent-browser eval "document.title" # Simple expressions only -agent-browser eval -b "" # Any JavaScript (base64 encoded) -agent-browser eval --stdin # Read script from stdin -``` - -Use `-b`/`--base64` or `--stdin` for reliable execution. Shell escaping with nested quotes and special characters is error-prone. - -```bash -# Base64 encode your script, then: -agent-browser eval -b "ZG9jdW1lbnQucXVlcnlTZWxlY3RvcignW3NyYyo9Il9uZXh0Il0nKQ==" - -# Or use stdin with heredoc for multiline scripts: -cat <<'EOF' | agent-browser eval --stdin -const links = document.querySelectorAll('a'); -Array.from(links).map(a => a.href); -EOF -``` - -## State Management - -```bash -agent-browser state save auth.json # Save cookies, storage, auth state -agent-browser state load auth.json # Restore saved state -``` - -## Global Options - -```bash -agent-browser --session ... # Isolated browser session -agent-browser --json ... # JSON output for parsing -agent-browser --headed ... # Show browser window (not headless) -agent-browser --full ... # Full page screenshot (-f) -agent-browser --cdp ... # Connect via Chrome DevTools Protocol -agent-browser -p ... # Cloud browser provider (--provider) -agent-browser --proxy ... # Use proxy server -agent-browser --proxy-bypass # Hosts to bypass proxy -agent-browser --headers ... # HTTP headers scoped to URL's origin -agent-browser --executable-path

# Custom browser executable -agent-browser --extension ... # Load browser extension (repeatable) -agent-browser --ignore-https-errors # Ignore SSL certificate errors -agent-browser --help # Show help (-h) -agent-browser --version # Show version (-V) -agent-browser --help # Show detailed help for a command -``` - -## Debugging - -```bash -agent-browser --headed open example.com # Show browser window -agent-browser --cdp 9222 snapshot # Connect via CDP port -agent-browser connect 9222 # Alternative: connect command -agent-browser console # View console messages -agent-browser console --clear # Clear console -agent-browser errors # View page errors -agent-browser errors --clear # Clear errors -agent-browser highlight @e1 # Highlight element -agent-browser trace start # Start recording trace -agent-browser trace stop trace.zip # Stop and save trace -agent-browser profiler start # Start Chrome DevTools profiling -agent-browser profiler stop trace.json # Stop and save profile -``` - -## Environment Variables - -```bash -AGENT_BROWSER_SESSION="mysession" # Default session name -AGENT_BROWSER_EXECUTABLE_PATH="/path/chrome" # Custom browser path -AGENT_BROWSER_EXTENSIONS="/ext1,/ext2" # Comma-separated extension paths -AGENT_BROWSER_PROVIDER="browserbase" # Cloud browser provider -AGENT_BROWSER_STREAM_PORT="9223" # WebSocket streaming port -AGENT_BROWSER_HOME="/path/to/agent-browser" # Custom install location -``` diff --git a/src/resources/skills/agent-browser/references/profiling.md b/src/resources/skills/agent-browser/references/profiling.md deleted file mode 100644 index bd47eaa0c..000000000 --- a/src/resources/skills/agent-browser/references/profiling.md +++ /dev/null @@ -1,120 +0,0 @@ -# Profiling - -Capture Chrome DevTools performance profiles during browser automation for performance analysis. - -**Related**: [commands.md](commands.md) for full command reference, [SKILL.md](../SKILL.md) for quick start. - -## Contents - -- [Basic Profiling](#basic-profiling) -- [Profiler Commands](#profiler-commands) -- [Categories](#categories) -- [Use Cases](#use-cases) -- [Output Format](#output-format) -- [Viewing Profiles](#viewing-profiles) -- [Limitations](#limitations) - -## Basic Profiling - -```bash -# Start profiling -agent-browser profiler start - -# Perform actions -agent-browser navigate https://example.com -agent-browser click "#button" -agent-browser wait 1000 - -# Stop and save -agent-browser profiler stop ./trace.json -``` - -## Profiler Commands - -```bash -# Start profiling with default categories -agent-browser profiler start - -# Start with custom trace categories -agent-browser profiler start --categories "devtools.timeline,v8.execute,blink.user_timing" - -# Stop profiling and save to file -agent-browser profiler stop ./trace.json -``` - -## Categories - -The `--categories` flag accepts a comma-separated list of Chrome trace categories. Default categories include: - -- `devtools.timeline` -- standard DevTools performance traces -- `v8.execute` -- time spent running JavaScript -- `blink` -- renderer events -- `blink.user_timing` -- `performance.mark()` / `performance.measure()` calls -- `latencyInfo` -- input-to-latency tracking -- `renderer.scheduler` -- task scheduling and execution -- `toplevel` -- broad-spectrum basic events - -Several `disabled-by-default-*` categories are also included for detailed timeline, call stack, and V8 CPU profiling data. - -## Use Cases - -### Diagnosing Slow Page Loads - -```bash -agent-browser profiler start -agent-browser navigate https://app.example.com -agent-browser wait --load networkidle -agent-browser profiler stop ./page-load-profile.json -``` - -### Profiling User Interactions - -```bash -agent-browser navigate https://app.example.com -agent-browser profiler start -agent-browser click "#submit" -agent-browser wait 2000 -agent-browser profiler stop ./interaction-profile.json -``` - -### CI Performance Regression Checks - -```bash -#!/bin/bash -agent-browser profiler start -agent-browser navigate https://app.example.com -agent-browser wait --load networkidle -agent-browser profiler stop "./profiles/build-${BUILD_ID}.json" -``` - -## Output Format - -The output is a JSON file in Chrome Trace Event format: - -```json -{ - "traceEvents": [ - { "cat": "devtools.timeline", "name": "RunTask", "ph": "X", "ts": 12345, "dur": 100, ... }, - ... - ], - "metadata": { - "clock-domain": "LINUX_CLOCK_MONOTONIC" - } -} -``` - -The `metadata.clock-domain` field is set based on the host platform (Linux or macOS). On Windows it is omitted. - -## Viewing Profiles - -Load the output JSON file in any of these tools: - -- **Chrome DevTools**: Performance panel > Load profile (Ctrl+Shift+I > Performance) -- **Perfetto UI**: https://ui.perfetto.dev/ -- drag and drop the JSON file -- **Trace Viewer**: `chrome://tracing` in any Chromium browser - -## Limitations - -- Only works with Chromium-based browsers (Chrome, Edge). Not supported on Firefox or WebKit. -- Trace data accumulates in memory while profiling is active (capped at 5 million events). Stop profiling promptly after the area of interest. -- Data collection on stop has a 30-second timeout. If the browser is unresponsive, the stop command may fail. diff --git a/src/resources/skills/agent-browser/references/proxy-support.md b/src/resources/skills/agent-browser/references/proxy-support.md deleted file mode 100644 index e86a8fe33..000000000 --- a/src/resources/skills/agent-browser/references/proxy-support.md +++ /dev/null @@ -1,194 +0,0 @@ -# Proxy Support - -Proxy configuration for geo-testing, rate limiting avoidance, and corporate environments. - -**Related**: [commands.md](commands.md) for global options, [SKILL.md](../SKILL.md) for quick start. - -## Contents - -- [Basic Proxy Configuration](#basic-proxy-configuration) -- [Authenticated Proxy](#authenticated-proxy) -- [SOCKS Proxy](#socks-proxy) -- [Proxy Bypass](#proxy-bypass) -- [Common Use Cases](#common-use-cases) -- [Verifying Proxy Connection](#verifying-proxy-connection) -- [Troubleshooting](#troubleshooting) -- [Best Practices](#best-practices) - -## Basic Proxy Configuration - -Use the `--proxy` flag or set proxy via environment variable: - -```bash -# Via CLI flag -agent-browser --proxy "http://proxy.example.com:8080" open https://example.com - -# Via environment variable -export HTTP_PROXY="http://proxy.example.com:8080" -agent-browser open https://example.com - -# HTTPS proxy -export HTTPS_PROXY="https://proxy.example.com:8080" -agent-browser open https://example.com - -# Both -export HTTP_PROXY="http://proxy.example.com:8080" -export HTTPS_PROXY="http://proxy.example.com:8080" -agent-browser open https://example.com -``` - -## Authenticated Proxy - -For proxies requiring authentication: - -```bash -# Include credentials in URL -export HTTP_PROXY="http://username:password@proxy.example.com:8080" -agent-browser open https://example.com -``` - -## SOCKS Proxy - -```bash -# SOCKS5 proxy -export ALL_PROXY="socks5://proxy.example.com:1080" -agent-browser open https://example.com - -# SOCKS5 with auth -export ALL_PROXY="socks5://user:pass@proxy.example.com:1080" -agent-browser open https://example.com -``` - -## Proxy Bypass - -Skip proxy for specific domains using `--proxy-bypass` or `NO_PROXY`: - -```bash -# Via CLI flag -agent-browser --proxy "http://proxy.example.com:8080" --proxy-bypass "localhost,*.internal.com" open https://example.com - -# Via environment variable -export NO_PROXY="localhost,127.0.0.1,.internal.company.com" -agent-browser open https://internal.company.com # Direct connection -agent-browser open https://external.com # Via proxy -``` - -## Common Use Cases - -### Geo-Location Testing - -```bash -#!/bin/bash -# Test site from different regions using geo-located proxies - -PROXIES=( - "http://us-proxy.example.com:8080" - "http://eu-proxy.example.com:8080" - "http://asia-proxy.example.com:8080" -) - -for proxy in "${PROXIES[@]}"; do - export HTTP_PROXY="$proxy" - export HTTPS_PROXY="$proxy" - - region=$(echo "$proxy" | grep -oP '^\w+-\w+') - echo "Testing from: $region" - - agent-browser --session "$region" open https://example.com - agent-browser --session "$region" screenshot "./screenshots/$region.png" - agent-browser --session "$region" close -done -``` - -### Rotating Proxies for Scraping - -```bash -#!/bin/bash -# Rotate through proxy list to avoid rate limiting - -PROXY_LIST=( - "http://proxy1.example.com:8080" - "http://proxy2.example.com:8080" - "http://proxy3.example.com:8080" -) - -URLS=( - "https://site.com/page1" - "https://site.com/page2" - "https://site.com/page3" -) - -for i in "${!URLS[@]}"; do - proxy_index=$((i % ${#PROXY_LIST[@]})) - export HTTP_PROXY="${PROXY_LIST[$proxy_index]}" - export HTTPS_PROXY="${PROXY_LIST[$proxy_index]}" - - agent-browser open "${URLS[$i]}" - agent-browser get text body > "output-$i.txt" - agent-browser close - - sleep 1 # Polite delay -done -``` - -### Corporate Network Access - -```bash -#!/bin/bash -# Access internal sites via corporate proxy - -export HTTP_PROXY="http://corpproxy.company.com:8080" -export HTTPS_PROXY="http://corpproxy.company.com:8080" -export NO_PROXY="localhost,127.0.0.1,.company.com" - -# External sites go through proxy -agent-browser open https://external-vendor.com - -# Internal sites bypass proxy -agent-browser open https://intranet.company.com -``` - -## Verifying Proxy Connection - -```bash -# Check your apparent IP -agent-browser open https://httpbin.org/ip -agent-browser get text body -# Should show proxy's IP, not your real IP -``` - -## Troubleshooting - -### Proxy Connection Failed - -```bash -# Test proxy connectivity first -curl -x http://proxy.example.com:8080 https://httpbin.org/ip - -# Check if proxy requires auth -export HTTP_PROXY="http://user:pass@proxy.example.com:8080" -``` - -### SSL/TLS Errors Through Proxy - -Some proxies perform SSL inspection. If you encounter certificate errors: - -```bash -# For testing only - not recommended for production -agent-browser open https://example.com --ignore-https-errors -``` - -### Slow Performance - -```bash -# Use proxy only when necessary -export NO_PROXY="*.cdn.com,*.static.com" # Direct CDN access -``` - -## Best Practices - -1. **Use environment variables** - Don't hardcode proxy credentials -2. **Set NO_PROXY appropriately** - Avoid routing local traffic through proxy -3. **Test proxy before automation** - Verify connectivity with simple requests -4. **Handle proxy failures gracefully** - Implement retry logic for unstable proxies -5. **Rotate proxies for large scraping jobs** - Distribute load and avoid bans diff --git a/src/resources/skills/agent-browser/references/session-management.md b/src/resources/skills/agent-browser/references/session-management.md deleted file mode 100644 index bb5312dbd..000000000 --- a/src/resources/skills/agent-browser/references/session-management.md +++ /dev/null @@ -1,193 +0,0 @@ -# Session Management - -Multiple isolated browser sessions with state persistence and concurrent browsing. - -**Related**: [authentication.md](authentication.md) for login patterns, [SKILL.md](../SKILL.md) for quick start. - -## Contents - -- [Named Sessions](#named-sessions) -- [Session Isolation Properties](#session-isolation-properties) -- [Session State Persistence](#session-state-persistence) -- [Common Patterns](#common-patterns) -- [Default Session](#default-session) -- [Session Cleanup](#session-cleanup) -- [Best Practices](#best-practices) - -## Named Sessions - -Use `--session` flag to isolate browser contexts: - -```bash -# Session 1: Authentication flow -agent-browser --session auth open https://app.example.com/login - -# Session 2: Public browsing (separate cookies, storage) -agent-browser --session public open https://example.com - -# Commands are isolated by session -agent-browser --session auth fill @e1 "user@example.com" -agent-browser --session public get text body -``` - -## Session Isolation Properties - -Each session has independent: -- Cookies -- LocalStorage / SessionStorage -- IndexedDB -- Cache -- Browsing history -- Open tabs - -## Session State Persistence - -### Save Session State - -```bash -# Save cookies, storage, and auth state -agent-browser state save /path/to/auth-state.json -``` - -### Load Session State - -```bash -# Restore saved state -agent-browser state load /path/to/auth-state.json - -# Continue with authenticated session -agent-browser open https://app.example.com/dashboard -``` - -### State File Contents - -```json -{ - "cookies": [...], - "localStorage": {...}, - "sessionStorage": {...}, - "origins": [...] -} -``` - -## Common Patterns - -### Authenticated Session Reuse - -```bash -#!/bin/bash -# Save login state once, reuse many times - -STATE_FILE="/tmp/auth-state.json" - -# Check if we have saved state -if [[ -f "$STATE_FILE" ]]; then - agent-browser state load "$STATE_FILE" - agent-browser open https://app.example.com/dashboard -else - # Perform login - agent-browser open https://app.example.com/login - agent-browser snapshot -i - agent-browser fill @e1 "$USERNAME" - agent-browser fill @e2 "$PASSWORD" - agent-browser click @e3 - agent-browser wait --load networkidle - - # Save for future use - agent-browser state save "$STATE_FILE" -fi -``` - -### Concurrent Scraping - -```bash -#!/bin/bash -# Scrape multiple sites concurrently - -# Start all sessions -agent-browser --session site1 open https://site1.com & -agent-browser --session site2 open https://site2.com & -agent-browser --session site3 open https://site3.com & -wait - -# Extract from each -agent-browser --session site1 get text body > site1.txt -agent-browser --session site2 get text body > site2.txt -agent-browser --session site3 get text body > site3.txt - -# Cleanup -agent-browser --session site1 close -agent-browser --session site2 close -agent-browser --session site3 close -``` - -### A/B Testing Sessions - -```bash -# Test different user experiences -agent-browser --session variant-a open "https://app.com?variant=a" -agent-browser --session variant-b open "https://app.com?variant=b" - -# Compare -agent-browser --session variant-a screenshot /tmp/variant-a.png -agent-browser --session variant-b screenshot /tmp/variant-b.png -``` - -## Default Session - -When `--session` is omitted, commands use the default session: - -```bash -# These use the same default session -agent-browser open https://example.com -agent-browser snapshot -i -agent-browser close # Closes default session -``` - -## Session Cleanup - -```bash -# Close specific session -agent-browser --session auth close - -# List active sessions -agent-browser session list -``` - -## Best Practices - -### 1. Name Sessions Semantically - -```bash -# GOOD: Clear purpose -agent-browser --session github-auth open https://github.com -agent-browser --session docs-scrape open https://docs.example.com - -# AVOID: Generic names -agent-browser --session s1 open https://github.com -``` - -### 2. Always Clean Up - -```bash -# Close sessions when done -agent-browser --session auth close -agent-browser --session scrape close -``` - -### 3. Handle State Files Securely - -```bash -# Don't commit state files (contain auth tokens!) -echo "*.auth-state.json" >> .gitignore - -# Delete after use -rm /tmp/auth-state.json -``` - -### 4. Timeout Long Sessions - -```bash -# Set timeout for automated scripts -timeout 60 agent-browser --session long-task get text body -``` diff --git a/src/resources/skills/agent-browser/references/snapshot-refs.md b/src/resources/skills/agent-browser/references/snapshot-refs.md deleted file mode 100644 index c5868d51c..000000000 --- a/src/resources/skills/agent-browser/references/snapshot-refs.md +++ /dev/null @@ -1,194 +0,0 @@ -# Snapshot and Refs - -Compact element references that reduce context usage dramatically for AI agents. - -**Related**: [commands.md](commands.md) for full command reference, [SKILL.md](../SKILL.md) for quick start. - -## Contents - -- [How Refs Work](#how-refs-work) -- [Snapshot Command](#the-snapshot-command) -- [Using Refs](#using-refs) -- [Ref Lifecycle](#ref-lifecycle) -- [Best Practices](#best-practices) -- [Ref Notation Details](#ref-notation-details) -- [Troubleshooting](#troubleshooting) - -## How Refs Work - -Traditional approach: -``` -Full DOM/HTML → AI parses → CSS selector → Action (~3000-5000 tokens) -``` - -agent-browser approach: -``` -Compact snapshot → @refs assigned → Direct interaction (~200-400 tokens) -``` - -## The Snapshot Command - -```bash -# Basic snapshot (shows page structure) -agent-browser snapshot - -# Interactive snapshot (-i flag) - RECOMMENDED -agent-browser snapshot -i -``` - -### Snapshot Output Format - -``` -Page: Example Site - Home -URL: https://example.com - -@e1 [header] - @e2 [nav] - @e3 [a] "Home" - @e4 [a] "Products" - @e5 [a] "About" - @e6 [button] "Sign In" - -@e7 [main] - @e8 [h1] "Welcome" - @e9 [form] - @e10 [input type="email"] placeholder="Email" - @e11 [input type="password"] placeholder="Password" - @e12 [button type="submit"] "Log In" - -@e13 [footer] - @e14 [a] "Privacy Policy" -``` - -## Using Refs - -Once you have refs, interact directly: - -```bash -# Click the "Sign In" button -agent-browser click @e6 - -# Fill email input -agent-browser fill @e10 "user@example.com" - -# Fill password -agent-browser fill @e11 "password123" - -# Submit the form -agent-browser click @e12 -``` - -## Ref Lifecycle - -**IMPORTANT**: Refs are invalidated when the page changes! - -```bash -# Get initial snapshot -agent-browser snapshot -i -# @e1 [button] "Next" - -# Click triggers page change -agent-browser click @e1 - -# MUST re-snapshot to get new refs! -agent-browser snapshot -i -# @e1 [h1] "Page 2" ← Different element now! -``` - -## Best Practices - -### 1. Always Snapshot Before Interacting - -```bash -# CORRECT -agent-browser open https://example.com -agent-browser snapshot -i # Get refs first -agent-browser click @e1 # Use ref - -# WRONG -agent-browser open https://example.com -agent-browser click @e1 # Ref doesn't exist yet! -``` - -### 2. Re-Snapshot After Navigation - -```bash -agent-browser click @e5 # Navigates to new page -agent-browser snapshot -i # Get new refs -agent-browser click @e1 # Use new refs -``` - -### 3. Re-Snapshot After Dynamic Changes - -```bash -agent-browser click @e1 # Opens dropdown -agent-browser snapshot -i # See dropdown items -agent-browser click @e7 # Select item -``` - -### 4. Snapshot Specific Regions - -For complex pages, snapshot specific areas: - -```bash -# Snapshot just the form -agent-browser snapshot @e9 -``` - -## Ref Notation Details - -``` -@e1 [tag type="value"] "text content" placeholder="hint" -│ │ │ │ │ -│ │ │ │ └─ Additional attributes -│ │ │ └─ Visible text -│ │ └─ Key attributes shown -│ └─ HTML tag name -└─ Unique ref ID -``` - -### Common Patterns - -``` -@e1 [button] "Submit" # Button with text -@e2 [input type="email"] # Email input -@e3 [input type="password"] # Password input -@e4 [a href="/page"] "Link Text" # Anchor link -@e5 [select] # Dropdown -@e6 [textarea] placeholder="Message" # Text area -@e7 [div class="modal"] # Container (when relevant) -@e8 [img alt="Logo"] # Image -@e9 [checkbox] checked # Checked checkbox -@e10 [radio] selected # Selected radio -``` - -## Troubleshooting - -### "Ref not found" Error - -```bash -# Ref may have changed - re-snapshot -agent-browser snapshot -i -``` - -### Element Not Visible in Snapshot - -```bash -# Scroll down to reveal element -agent-browser scroll down 1000 -agent-browser snapshot -i - -# Or wait for dynamic content -agent-browser wait 1000 -agent-browser snapshot -i -``` - -### Too Many Elements - -```bash -# Snapshot specific container -agent-browser snapshot @e5 - -# Or use get text for content-only extraction -agent-browser get text @e5 -``` diff --git a/src/resources/skills/agent-browser/references/video-recording.md b/src/resources/skills/agent-browser/references/video-recording.md deleted file mode 100644 index e6a9fb4e2..000000000 --- a/src/resources/skills/agent-browser/references/video-recording.md +++ /dev/null @@ -1,173 +0,0 @@ -# Video Recording - -Capture browser automation as video for debugging, documentation, or verification. - -**Related**: [commands.md](commands.md) for full command reference, [SKILL.md](../SKILL.md) for quick start. - -## Contents - -- [Basic Recording](#basic-recording) -- [Recording Commands](#recording-commands) -- [Use Cases](#use-cases) -- [Best Practices](#best-practices) -- [Output Format](#output-format) -- [Limitations](#limitations) - -## Basic Recording - -```bash -# Start recording -agent-browser record start ./demo.webm - -# Perform actions -agent-browser open https://example.com -agent-browser snapshot -i -agent-browser click @e1 -agent-browser fill @e2 "test input" - -# Stop and save -agent-browser record stop -``` - -## Recording Commands - -```bash -# Start recording to file -agent-browser record start ./output.webm - -# Stop current recording -agent-browser record stop - -# Restart with new file (stops current + starts new) -agent-browser record restart ./take2.webm -``` - -## Use Cases - -### Debugging Failed Automation - -```bash -#!/bin/bash -# Record automation for debugging - -agent-browser record start ./debug-$(date +%Y%m%d-%H%M%S).webm - -# Run your automation -agent-browser open https://app.example.com -agent-browser snapshot -i -agent-browser click @e1 || { - echo "Click failed - check recording" - agent-browser record stop - exit 1 -} - -agent-browser record stop -``` - -### Documentation Generation - -```bash -#!/bin/bash -# Record workflow for documentation - -agent-browser record start ./docs/how-to-login.webm - -agent-browser open https://app.example.com/login -agent-browser wait 1000 # Pause for visibility - -agent-browser snapshot -i -agent-browser fill @e1 "demo@example.com" -agent-browser wait 500 - -agent-browser fill @e2 "password" -agent-browser wait 500 - -agent-browser click @e3 -agent-browser wait --load networkidle -agent-browser wait 1000 # Show result - -agent-browser record stop -``` - -### CI/CD Test Evidence - -```bash -#!/bin/bash -# Record E2E test runs for CI artifacts - -TEST_NAME="${1:-e2e-test}" -RECORDING_DIR="./test-recordings" -mkdir -p "$RECORDING_DIR" - -agent-browser record start "$RECORDING_DIR/$TEST_NAME-$(date +%s).webm" - -# Run test -if run_e2e_test; then - echo "Test passed" -else - echo "Test failed - recording saved" -fi - -agent-browser record stop -``` - -## Best Practices - -### 1. Add Pauses for Clarity - -```bash -# Slow down for human viewing -agent-browser click @e1 -agent-browser wait 500 # Let viewer see result -``` - -### 2. Use Descriptive Filenames - -```bash -# Include context in filename -agent-browser record start ./recordings/login-flow-2024-01-15.webm -agent-browser record start ./recordings/checkout-test-run-42.webm -``` - -### 3. Handle Recording in Error Cases - -```bash -#!/bin/bash -set -e - -cleanup() { - agent-browser record stop 2>/dev/null || true - agent-browser close 2>/dev/null || true -} -trap cleanup EXIT - -agent-browser record start ./automation.webm -# ... automation steps ... -``` - -### 4. Combine with Screenshots - -```bash -# Record video AND capture key frames -agent-browser record start ./flow.webm - -agent-browser open https://example.com -agent-browser screenshot ./screenshots/step1-homepage.png - -agent-browser click @e1 -agent-browser screenshot ./screenshots/step2-after-click.png - -agent-browser record stop -``` - -## Output Format - -- Default format: WebM (VP8/VP9 codec) -- Compatible with all modern browsers and video players -- Compressed but high quality - -## Limitations - -- Recording adds slight overhead to automation -- Large recordings can consume significant disk space -- Some headless environments may have codec limitations diff --git a/src/resources/skills/agent-browser/templates/authenticated-session.sh b/src/resources/skills/agent-browser/templates/authenticated-session.sh deleted file mode 100755 index b66c9289c..000000000 --- a/src/resources/skills/agent-browser/templates/authenticated-session.sh +++ /dev/null @@ -1,105 +0,0 @@ -#!/bin/bash -# Template: Authenticated Session Workflow -# Purpose: Login once, save state, reuse for subsequent runs -# Usage: ./authenticated-session.sh [state-file] -# -# RECOMMENDED: Use the auth vault instead of this template: -# echo "" | agent-browser auth save myapp --url --username --password-stdin -# agent-browser auth login myapp -# The auth vault stores credentials securely and the LLM never sees passwords. -# -# Environment variables: -# APP_USERNAME - Login username/email -# APP_PASSWORD - Login password -# -# Two modes: -# 1. Discovery mode (default): Shows form structure so you can identify refs -# 2. Login mode: Performs actual login after you update the refs -# -# Setup steps: -# 1. Run once to see form structure (discovery mode) -# 2. Update refs in LOGIN FLOW section below -# 3. Set APP_USERNAME and APP_PASSWORD -# 4. Delete the DISCOVERY section - -set -euo pipefail - -LOGIN_URL="${1:?Usage: $0 [state-file]}" -STATE_FILE="${2:-./auth-state.json}" - -echo "Authentication workflow: $LOGIN_URL" - -# ================================================================ -# SAVED STATE: Skip login if valid saved state exists -# ================================================================ -if [[ -f "$STATE_FILE" ]]; then - echo "Loading saved state from $STATE_FILE..." - if agent-browser --state "$STATE_FILE" open "$LOGIN_URL" 2>/dev/null; then - agent-browser wait --load networkidle - - CURRENT_URL=$(agent-browser get url) - if [[ "$CURRENT_URL" != *"login"* ]] && [[ "$CURRENT_URL" != *"signin"* ]]; then - echo "Session restored successfully" - agent-browser snapshot -i - exit 0 - fi - echo "Session expired, performing fresh login..." - agent-browser close 2>/dev/null || true - else - echo "Failed to load state, re-authenticating..." - fi - rm -f "$STATE_FILE" -fi - -# ================================================================ -# DISCOVERY MODE: Shows form structure (delete after setup) -# ================================================================ -echo "Opening login page..." -agent-browser open "$LOGIN_URL" -agent-browser wait --load networkidle - -echo "" -echo "Login form structure:" -echo "---" -agent-browser snapshot -i -echo "---" -echo "" -echo "Next steps:" -echo " 1. Note the refs: username=@e?, password=@e?, submit=@e?" -echo " 2. Update the LOGIN FLOW section below with your refs" -echo " 3. Set: export APP_USERNAME='...' APP_PASSWORD='...'" -echo " 4. Delete this DISCOVERY MODE section" -echo "" -agent-browser close -exit 0 - -# ================================================================ -# LOGIN FLOW: Uncomment and customize after discovery -# ================================================================ -# : "${APP_USERNAME:?Set APP_USERNAME environment variable}" -# : "${APP_PASSWORD:?Set APP_PASSWORD environment variable}" -# -# agent-browser open "$LOGIN_URL" -# agent-browser wait --load networkidle -# agent-browser snapshot -i -# -# # Fill credentials (update refs to match your form) -# agent-browser fill @e1 "$APP_USERNAME" -# agent-browser fill @e2 "$APP_PASSWORD" -# agent-browser click @e3 -# agent-browser wait --load networkidle -# -# # Verify login succeeded -# FINAL_URL=$(agent-browser get url) -# if [[ "$FINAL_URL" == *"login"* ]] || [[ "$FINAL_URL" == *"signin"* ]]; then -# echo "Login failed - still on login page" -# agent-browser screenshot /tmp/login-failed.png -# agent-browser close -# exit 1 -# fi -# -# # Save state for future runs -# echo "Saving state to $STATE_FILE" -# agent-browser state save "$STATE_FILE" -# echo "Login successful" -# agent-browser snapshot -i diff --git a/src/resources/skills/agent-browser/templates/capture-workflow.sh b/src/resources/skills/agent-browser/templates/capture-workflow.sh deleted file mode 100755 index 3bc93ad0c..000000000 --- a/src/resources/skills/agent-browser/templates/capture-workflow.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/bash -# Template: Content Capture Workflow -# Purpose: Extract content from web pages (text, screenshots, PDF) -# Usage: ./capture-workflow.sh [output-dir] -# -# Outputs: -# - page-full.png: Full page screenshot -# - page-structure.txt: Page element structure with refs -# - page-text.txt: All text content -# - page.pdf: PDF version -# -# Optional: Load auth state for protected pages - -set -euo pipefail - -TARGET_URL="${1:?Usage: $0 [output-dir]}" -OUTPUT_DIR="${2:-.}" - -echo "Capturing: $TARGET_URL" -mkdir -p "$OUTPUT_DIR" - -# Optional: Load authentication state -# if [[ -f "./auth-state.json" ]]; then -# echo "Loading authentication state..." -# agent-browser state load "./auth-state.json" -# fi - -# Navigate to target -agent-browser open "$TARGET_URL" -agent-browser wait --load networkidle - -# Get metadata -TITLE=$(agent-browser get title) -URL=$(agent-browser get url) -echo "Title: $TITLE" -echo "URL: $URL" - -# Capture full page screenshot -agent-browser screenshot --full "$OUTPUT_DIR/page-full.png" -echo "Saved: $OUTPUT_DIR/page-full.png" - -# Get page structure with refs -agent-browser snapshot -i > "$OUTPUT_DIR/page-structure.txt" -echo "Saved: $OUTPUT_DIR/page-structure.txt" - -# Extract all text content -agent-browser get text body > "$OUTPUT_DIR/page-text.txt" -echo "Saved: $OUTPUT_DIR/page-text.txt" - -# Save as PDF -agent-browser pdf "$OUTPUT_DIR/page.pdf" -echo "Saved: $OUTPUT_DIR/page.pdf" - -# Optional: Extract specific elements using refs from structure -# agent-browser get text @e5 > "$OUTPUT_DIR/main-content.txt" - -# Optional: Handle infinite scroll pages -# for i in {1..5}; do -# agent-browser scroll down 1000 -# agent-browser wait 1000 -# done -# agent-browser screenshot --full "$OUTPUT_DIR/page-scrolled.png" - -# Cleanup -agent-browser close - -echo "" -echo "Capture complete:" -ls -la "$OUTPUT_DIR" diff --git a/src/resources/skills/agent-browser/templates/form-automation.sh b/src/resources/skills/agent-browser/templates/form-automation.sh deleted file mode 100755 index 6784fcd3a..000000000 --- a/src/resources/skills/agent-browser/templates/form-automation.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/bash -# Template: Form Automation Workflow -# Purpose: Fill and submit web forms with validation -# Usage: ./form-automation.sh -# -# This template demonstrates the snapshot-interact-verify pattern: -# 1. Navigate to form -# 2. Snapshot to get element refs -# 3. Fill fields using refs -# 4. Submit and verify result -# -# Customize: Update the refs (@e1, @e2, etc.) based on your form's snapshot output - -set -euo pipefail - -FORM_URL="${1:?Usage: $0 }" - -echo "Form automation: $FORM_URL" - -# Step 1: Navigate to form -agent-browser open "$FORM_URL" -agent-browser wait --load networkidle - -# Step 2: Snapshot to discover form elements -echo "" -echo "Form structure:" -agent-browser snapshot -i - -# Step 3: Fill form fields (customize these refs based on snapshot output) -# -# Common field types: -# agent-browser fill @e1 "John Doe" # Text input -# agent-browser fill @e2 "user@example.com" # Email input -# agent-browser fill @e3 "SecureP@ss123" # Password input -# agent-browser select @e4 "Option Value" # Dropdown -# agent-browser check @e5 # Checkbox -# agent-browser click @e6 # Radio button -# agent-browser fill @e7 "Multi-line text" # Textarea -# agent-browser upload @e8 /path/to/file.pdf # File upload -# -# Uncomment and modify: -# agent-browser fill @e1 "Test User" -# agent-browser fill @e2 "test@example.com" -# agent-browser click @e3 # Submit button - -# Step 4: Wait for submission -# agent-browser wait --load networkidle -# agent-browser wait --url "**/success" # Or wait for redirect - -# Step 5: Verify result -echo "" -echo "Result:" -agent-browser get url -agent-browser snapshot -i - -# Optional: Capture evidence -agent-browser screenshot /tmp/form-result.png -echo "Screenshot saved: /tmp/form-result.png" - -# Cleanup -agent-browser close -echo "Done" diff --git a/src/resources/skills/best-practices/SKILL.md b/src/resources/skills/best-practices/SKILL.md deleted file mode 100644 index 043f00b18..000000000 --- a/src/resources/skills/best-practices/SKILL.md +++ /dev/null @@ -1,583 +0,0 @@ ---- -name: best-practices -description: Apply modern web development best practices for security, compatibility, and code quality. Use when asked to "apply best practices", "security audit", "modernize code", "code quality review", or "check for vulnerabilities". -license: MIT -metadata: - author: web-quality-skills - version: "1.0" ---- - -# Best practices - -Modern web development standards based on Lighthouse best practices audits. Covers security, browser compatibility, and code quality patterns. - -## Security - -### HTTPS everywhere - -**Enforce HTTPS:** -```html - - - - - - - - - - -``` - -**HSTS Header:** -``` -Strict-Transport-Security: max-age=31536000; includeSubDomains; preload -``` - -### Content Security Policy (CSP) - -```html - - - - -``` - -**CSP Header (recommended):** -``` -Content-Security-Policy: - default-src 'self'; - script-src 'self' 'nonce-abc123' https://trusted.com; - style-src 'self' 'nonce-abc123'; - img-src 'self' data: https:; - connect-src 'self' https://api.example.com; - frame-ancestors 'self'; - base-uri 'self'; - form-action 'self'; -``` - -**Using nonces for inline scripts:** -```html - -``` - -### Security headers - -``` -# Prevent clickjacking -X-Frame-Options: DENY - -# Prevent MIME type sniffing -X-Content-Type-Options: nosniff - -# Enable XSS filter (legacy browsers) -X-XSS-Protection: 1; mode=block - -# Control referrer information -Referrer-Policy: strict-origin-when-cross-origin - -# Permissions policy (formerly Feature-Policy) -Permissions-Policy: geolocation=(), microphone=(), camera=() -``` - -### No vulnerable libraries - -```bash -# Check for vulnerabilities -npm audit -yarn audit - -# Auto-fix when possible -npm audit fix - -# Check specific package -npm ls lodash -``` - -**Keep dependencies updated:** -```json -// package.json -{ - "scripts": { - "audit": "npm audit --audit-level=moderate", - "update": "npm update && npm audit fix" - } -} -``` - -**Known vulnerable patterns to avoid:** -```javascript -// ❌ Prototype pollution vulnerable patterns -Object.assign(target, userInput); -_.merge(target, userInput); - -// ✅ Safer alternatives -const safeData = JSON.parse(JSON.stringify(userInput)); -``` - -### Input sanitization - -```javascript -// ❌ XSS vulnerable -element.innerHTML = userInput; -document.write(userInput); - -// ✅ Safe text content -element.textContent = userInput; - -// ✅ If HTML needed, sanitize -import DOMPurify from 'dompurify'; -element.innerHTML = DOMPurify.sanitize(userInput); -``` - -### Secure cookies - -```javascript -// ❌ Insecure cookie -document.cookie = "session=abc123"; - -// ✅ Secure cookie (server-side) -Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Strict; Path=/ -``` - ---- - -## Browser compatibility - -### Doctype declaration - -```html - - - - - - - -``` - -### Character encoding - -```html - - - - Page - - - - - - - - Page - -``` - -### Viewport meta tag - -```html - - - Page - - - - - - - Page - -``` - -### Feature detection - -```javascript -// ❌ Browser detection (brittle) -if (navigator.userAgent.includes('Chrome')) { - // Chrome-specific code -} - -// ✅ Feature detection -if ('IntersectionObserver' in window) { - // Use IntersectionObserver -} else { - // Fallback -} - -// ✅ Using @supports in CSS -@supports (display: grid) { - .container { - display: grid; - } -} - -@supports not (display: grid) { - .container { - display: flex; - } -} -``` - -### Polyfills (when needed) - -```html - - - - - -``` - ---- - -## Deprecated APIs - -### Avoid these - -```javascript -// ❌ document.write (blocks parsing) -document.write(''); - -// ✅ Dynamic script loading -const script = document.createElement('script'); -script.src = '...'; -document.head.appendChild(script); - -// ❌ Synchronous XHR (blocks main thread) -const xhr = new XMLHttpRequest(); -xhr.open('GET', url, false); // false = synchronous - -// ✅ Async fetch -const response = await fetch(url); - -// ❌ Application Cache (deprecated) - - -// ✅ Service Workers -if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/sw.js'); -} -``` - -### Event listener passive - -```javascript -// ❌ Non-passive touch/wheel (may block scrolling) -element.addEventListener('touchstart', handler); -element.addEventListener('wheel', handler); - -// ✅ Passive listeners (allows smooth scrolling) -element.addEventListener('touchstart', handler, { passive: true }); -element.addEventListener('wheel', handler, { passive: true }); - -// ✅ If you need preventDefault, be explicit -element.addEventListener('touchstart', handler, { passive: false }); -``` - ---- - -## Console & errors - -### No console errors - -```javascript -// ❌ Errors in production -console.log('Debug info'); // Remove in production -throw new Error('Unhandled'); // Catch all errors - -// ✅ Proper error handling -try { - riskyOperation(); -} catch (error) { - // Log to error tracking service - errorTracker.captureException(error); - // Show user-friendly message - showErrorMessage('Something went wrong. Please try again.'); -} -``` - -### Error boundaries (React) - -```jsx -class ErrorBoundary extends React.Component { - state = { hasError: false }; - - static getDerivedStateFromError(error) { - return { hasError: true }; - } - - componentDidCatch(error, info) { - errorTracker.captureException(error, { extra: info }); - } - - render() { - if (this.state.hasError) { - return ; - } - return this.props.children; - } -} - -// Usage - - - -``` - -### Global error handler - -```javascript -// Catch unhandled errors -window.addEventListener('error', (event) => { - errorTracker.captureException(event.error); -}); - -// Catch unhandled promise rejections -window.addEventListener('unhandledrejection', (event) => { - errorTracker.captureException(event.reason); -}); -``` - ---- - -## Source maps - -### Production configuration - -```javascript -// ❌ Source maps exposed in production -// webpack.config.js -module.exports = { - devtool: 'source-map', // Exposes source code -}; - -// ✅ Hidden source maps (uploaded to error tracker) -module.exports = { - devtool: 'hidden-source-map', -}; - -// ✅ Or no source maps in production -module.exports = { - devtool: process.env.NODE_ENV === 'production' ? false : 'source-map', -}; -``` - ---- - -## Performance best practices - -### Avoid blocking patterns - -```javascript -// ❌ Blocking script - - -// ✅ Deferred script - - -// ❌ Blocking CSS import -@import url('other-styles.css'); - -// ✅ Link tags (parallel loading) - - -``` - -### Efficient event handlers - -```javascript -// ❌ Handler on every element -items.forEach(item => { - item.addEventListener('click', handleClick); -}); - -// ✅ Event delegation -container.addEventListener('click', (e) => { - if (e.target.matches('.item')) { - handleClick(e); - } -}); -``` - -### Memory management - -```javascript -// ❌ Memory leak (never removed) -const handler = () => { /* ... */ }; -window.addEventListener('resize', handler); - -// ✅ Cleanup when done -const handler = () => { /* ... */ }; -window.addEventListener('resize', handler); - -// Later, when component unmounts: -window.removeEventListener('resize', handler); - -// ✅ Using AbortController -const controller = new AbortController(); -window.addEventListener('resize', handler, { signal: controller.signal }); - -// Cleanup: -controller.abort(); -``` - ---- - -## Code quality - -### Valid HTML - -```html - -