From ec18ec7e70a2f018051d1f3b3f7cecbc9170b625 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 4 Oct 2026 17:08:50 +1100 Subject: [PATCH] feat(skills): skill packages project into a skills resource the gateway reads live --- examples/skills/archie-wf-frontend/SKILL.md | 43 -------- examples/skills/archie-wf-go-gate/SKILL.md | 78 -------------- examples/skills/archie-wf-node/SKILL.md | 91 ---------------- examples/skills/archie-wf-python/SKILL.md | 87 --------------- examples/skills/archie-wf-security/SKILL.md | 76 ------------- examples/skills/archie-wf-tdd/SKILL.md | 83 -------------- install.sh | 5 - internal/app/archiegateway/gateway.go | 1 + internal/app/archiegateway/skills.go | 95 ++++++++++++++++ internal/app/archiegateway/tools.go | 11 -- internal/app/controlplane/definitions.go | 2 +- .../app/controlplane/package_projection.go | 88 +++++++++++++++ internal/app/controlplane/playbooks.go | 93 +++------------- internal/app/controlplane/skills.go | 101 ++++++++++++++++++ internal/app/statestore/server.go | 7 +- internal/skill/skill.go | 19 ++++ internal/skill/tooldef.go | 5 + 17 files changed, 332 insertions(+), 553 deletions(-) delete mode 100644 examples/skills/archie-wf-frontend/SKILL.md delete mode 100644 examples/skills/archie-wf-go-gate/SKILL.md delete mode 100644 examples/skills/archie-wf-node/SKILL.md delete mode 100644 examples/skills/archie-wf-python/SKILL.md delete mode 100644 examples/skills/archie-wf-security/SKILL.md delete mode 100644 examples/skills/archie-wf-tdd/SKILL.md create mode 100644 internal/app/archiegateway/skills.go create mode 100644 internal/app/controlplane/skills.go diff --git a/examples/skills/archie-wf-frontend/SKILL.md b/examples/skills/archie-wf-frontend/SKILL.md deleted file mode 100644 index 31c8f7539..000000000 --- a/examples/skills/archie-wf-frontend/SKILL.md +++ /dev/null @@ -1,43 +0,0 @@ ---- - -name: archie-wf-frontend -description: > -Runs frontend quality checks: stylelint for CSS, htmlhint for HTML. -Gate stage runs these after Go vet/build/test. Use in any project -with web assets to catch syntax errors, broken selectors, and -structural issues before they reach a PR. -version: 1.1.0 -metadata: -archie: -workflow: frontend -tools: [stylelint, htmlhint] -engine: any - -# Frontend Quality Gate - -## When this runs - -This skill adds frontend linting to the gate stage. After Go checks pass, -the gate runs: - -1. `stylelint "**/*.css"` -- catches syntax errors, invalid properties, - duplicate selectors, calc() misuse, missing units -2. `htmlhint "**/*.html"` -- catches unclosed tags, mismatched pairs, - duplicate IDs, inline style abuse, missing viewport meta - -Both must exit 0. If either fails, the stage parks with the lint output. - -## How to use in your project - -1. Copy this skill directory into your skills directory -2. Add to your daemon config gate: - ```toml - gate = [ - ["go", "vet", "./..."], - ["go", "test", "./..."], - ["stylelint", "**/*.css"], - ["htmlhint", "**/*.html"], - ] - ``` -3. Or declare `workflow: frontend` in the skill frontmatter -- archie-core - loads the skill body and the agent knows to run these during build diff --git a/examples/skills/archie-wf-go-gate/SKILL.md b/examples/skills/archie-wf-go-gate/SKILL.md deleted file mode 100644 index 00a25d821..000000000 --- a/examples/skills/archie-wf-go-gate/SKILL.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -name: go-quality-gate -description: > - Run the full Go quality pipeline: gofumpt, go fix, golangci-lint, go test -race, - and task deadcode. Use before any commit in a Go project. Triggered automatically - by archie-core's implement and tdd workflows via the per-repo gate config. -version: 1.0.0 -metadata: - archie: - tools: [go, golangci-lint, gofumpt, task] - engine: any ---- - -# Go Quality Gate - -## When this runs - -arcie-core enforces this gate after every builder agent stage. The specific commands -come from the repository's `[[repos.gate]]` config, not this skill. This skill documents -what a correct gate looks like and how to diagnose failures. - -## Standard gate - -Run in this exact order. archie-core does NOT run these -- the `ai-sdk/agentloop` gate -does. This list is what you should configure in `config.toml`: - -```toml -[[repos.gate]] = ["gofumpt", "-w", "."] -[[repos.gate]] = ["go", "fix", "./..."] -[[repos.gate]] = ["golangci-lint", "run", "./..."] -[[repos.gate]] = ["go", "test", "-race", "-count=1", "./..."] -``` - -Or if the project uses Task: - -```toml -[[repos.gate]] = ["task", "check"] -``` - -The LAST command in the gate list is the test runner by convention. archie-core's -TDD workflow inverts only that last command during the repro stage. - -## Diagnosing gate failures - -### gofumpt / go fix - -These mutate files. If they change anything, the next `git diff` will catch it. -The agent should re-run them after making changes. - -### golangci-lint - -Common failures and fixes: - -- `unused` -- remove the unused function or add `//nolint:unused` -- `errcheck` -- handle the error or assign to `_` -- `gosec` -- review the security finding; never blindly suppress - -### go test -race - -Data races are non-deterministic. If `-race` fails: - -1. Identify the race with `go test -race -run=TestName` -2. Add a mutex or channel to protect the shared state -3. Re-run with `-count=5` to confirm it's gone - -### task deadcode - -Scoping rule: if deadcode fails on packages you didn't touch, scope it: - -```bash -golangci-lint run --tests=false --enable-only=unused,staticcheck ./changed/pkg/... -``` - -## When the TDD workflow runs - -During `repro-tests`, the test command's expectations are INVERTED -- it must FAIL. -During `fix`, the full gate runs normally and test files are write-protected. -The agent cannot modify tests in the fix stage; it must fix the code to make them pass. diff --git a/examples/skills/archie-wf-node/SKILL.md b/examples/skills/archie-wf-node/SKILL.md deleted file mode 100644 index 86de9479a..000000000 --- a/examples/skills/archie-wf-node/SKILL.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -name: ecosystem-node -description: > - Node.js/TypeScript project conventions for archie-core: npm/pnpm, eslint, - prettier, tsc, vitest. Use when working on Node repositories with archie-core. -version: 1.0.0 -metadata: - archie: - tools: [node, npm, pnpm, vitest, eslint, prettier] - engine: any ---- - -# Node.js / TypeScript Ecosystem Conventions - -## Preflight - -When archie-core's `[[repos]]` entry sets `ecosystem = "node"`, the daemon runs -`node --version` as the preflight check before any agent stage. - -## Recommended gate configuration - -```toml -[[repos]] -owner = "acme" -name = "my-node-project" -ecosystem = "node" - -[[repos.gate]] = ["pnpm", "run", "lint"] -[[repos.gate]] = ["pnpm", "run", "typecheck"] -[[repos.gate]] = ["pnpm", "run", "test"] -``` - -Or for npm projects: - -```toml -[[repos.gate]] = ["npm", "run", "lint"] -[[repos.gate]] = ["npm", "run", "build", "--", "--noEmit"] -[[repos.gate]] = ["npm", "test"] -``` - -## Test glob - -The default test glob for Node is `*.test.ts`. The TDD workflow's repro-tests -stage write-protects files matching this glob during the fix stage. - -Override with `test_glob = "**/*.spec.ts"` for projects using that convention, -or `test_glob = "__tests__/**/*.ts"` for Jest-style test directories. - -## Package management - -arcie-core detects the lockfile: - -- `pnpm-lock.yaml` → use `pnpm` -- `package-lock.json` → use `npm` -- `yarn.lock` → use `yarn` - -Install before gate: - -```bash -pnpm install --frozen-lockfile -``` - -## Common tools - -| Tool | Purpose | Config file | -| -------------- | ---------------- | ------------------- | -| `eslint` | Linting | `eslint.config.mjs` | -| `prettier` | Formatting | `.prettierrc` | -| `tsc --noEmit` | Type checking | `tsconfig.json` | -| `vitest` | Testing | `vitest.config.ts` | -| `jest` | Testing (legacy) | `jest.config.ts` | - -## Common gate failures - -### eslint - -- `no-unused-vars`: remove unused import/variable -- `@typescript-eslint/no-explicit-any`: add proper type -- Import order: let eslint fix it with `--fix` - -### tsc / typecheck - -- `TS2345`: type mismatch -- fix the argument or the signature -- `TS2339`: property doesn't exist -- check the type definition -- `Cannot find module`: check the import path or install the package - -### vitest / jest - -- Test timeout: the test is hanging -- check async/await, mocks, or network calls -- Snapshot mismatch: the output changed -- update the snapshot if the change is intentional -- Assertion failure: fix the code, not the test diff --git a/examples/skills/archie-wf-python/SKILL.md b/examples/skills/archie-wf-python/SKILL.md deleted file mode 100644 index 3fcb2d85b..000000000 --- a/examples/skills/archie-wf-python/SKILL.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -name: ecosystem-python -description: > - Python project conventions for archie-core: venv, pytest, ruff, mypy, pip-audit. - Use when working on Python repositories with archie-core. -version: 1.0.0 -metadata: - archie: - tools: [python, pytest, ruff, mypy, pip-audit] - engine: any ---- - -# Python Ecosystem Conventions - -## Preflight - -When archie-core's `[[repos]]` entry sets `ecosystem = "python"`, the daemon runs -`python --version` as the preflight check before any agent stage. - -## Recommended gate configuration - -```toml -[[repos]] -owner = "acme" -name = "my-python-project" -ecosystem = "python" - -[[repos.gate]] = ["ruff", "check", "."] -[[repos.gate]] = ["ruff", "format", "--check", "."] -[[repos.gate]] = ["mypy", "."] -[[repos.gate]] = ["pytest", "-x", "--tb=short"] -``` - -## Test glob - -The default test glob for Python is `test_*.py`. The TDD workflow's repro-tests -stage write-protects files matching this glob during the fix stage. - -Override with `test_glob = "tests/**/*.py"` in the repo config for projects -with test files outside the package root. - -## Package management - -arcie-core assumes: - -- `requirements.txt` or `pyproject.toml` at the repo root -- Tests run with `pytest` (the ecosystem default) -- Linting with `ruff` (recommended) or `flake8` -- Type checking with `mypy` -- Security auditing with `pip-audit` - -## Virtual environment - -Before the gate runs, ensure dependencies are installed: - -```bash -python -m venv .venv -. .venv/bin/activate -pip install -r requirements.txt -pip install pytest ruff mypy pip-audit -``` - -For `pyproject.toml` projects: - -```bash -pip install -e ".[dev]" -``` - -## Common gate failures - -### ruff - -- `F401`: unused import -- remove it -- `E501`: line too long -- break the line -- `I001`: import order -- let ruff fix it with `ruff check --fix` - -### mypy - -- Missing type annotation on public function -- add it -- `Cannot determine type` -- add explicit annotation -- Import errors -- check the package is installed in the venv - -### pytest - -- Test discovery failed -- check `__init__.py` files and test naming -- Import errors -- verify the package is installed (`pip install -e .`) -- Assertion failures -- fix the code, not the test diff --git a/examples/skills/archie-wf-security/SKILL.md b/examples/skills/archie-wf-security/SKILL.md deleted file mode 100644 index af992bd79..000000000 --- a/examples/skills/archie-wf-security/SKILL.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -name: security-audit -description: > - Scan code for security vulnerabilities: hardcoded secrets, injection vectors, - unsafe deserialization, missing auth checks, and path traversal. Use on PRs - touching auth, API endpoints, or data handling code. -version: 1.0.0 -metadata: - archie: - tools: [golangci-lint, trivy, gitleaks] - engine: any ---- - -# Security Audit - -## When to use - -Run this audit when: - -- A PR touches authentication, authorisation, or session code -- New API endpoints are added -- Database queries or file I/O paths change -- The issue mentions "security", "vulnerability", "CVE", or "auth" -- A dependency update changes major versions - -## What to check - -### 1. Hardcoded secrets - -Scan for: - -- API keys, tokens, passwords in source files -- `.env` files committed to the repo -- Credentials in test fixtures - -Use `gitleaks detect --no-git` for a fast scan. - -### 2. Injection vectors - -- **SQL:** any string concatenation in query building. Use parameterised queries. -- **Command:** any `os/exec` with user-controlled input. Use `exec.Command` with separate args, never `sh -c`. -- **Path:** any file path constructed from user input without validation. Use `filepath.Clean` and check the resolved path is within the expected directory. - -### 3. Unsafe deserialization - -- `json.Unmarshal` on untrusted input into `interface{}` or `map[string]any` without validation -- `yaml.Unmarshal` without `KnownFields` or strict mode -- `gob.Decode` on network input - -### 4. Missing auth checks - -- New endpoints without middleware -- Internal/admin endpoints exposed without auth -- Token validation that only checks signature, not expiry or revocation - -### 5. Dependency CVEs - -Run `trivy fs --severity HIGH,CRITICAL .` on the repository. -Report each finding with: - -- Package name and version -- CVE ID -- CVSS score -- Fixed version (if available) - -## Reporting - -For each finding, report: - -1. **Severity:** Critical / High / Medium / Low -2. **Location:** file, line, function -3. **Description:** what's wrong -4. **Fix:** specific code change needed -5. **Prevention:** how to catch this in future (lint rule, gate addition) - -If nothing is found, report clean. Never fabricate findings. diff --git a/examples/skills/archie-wf-tdd/SKILL.md b/examples/skills/archie-wf-tdd/SKILL.md deleted file mode 100644 index 37d15432f..000000000 --- a/examples/skills/archie-wf-tdd/SKILL.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -name: archie-wf-tdd -description: > - Fix bugs using test-driven development. Write a failing repro test first, prove - it captures the bug, then fix the code without touching the tests. archie-core - routes issues labelled "bug" through this workflow automatically. -version: 1.0.0 -metadata: - archie: - tools: [go, golangci-lint] - engine: any - workflow: tdd ---- - -# TDD Bugfix Workflow - -## When this runs - -arcie-core routes any GitHub issue labelled `bug` through the TDD workflow. -The workflow has five stages: analyse → repro-tests → capture-proof → fix → deliver. - -## Stage 1: Analyse (read-only planner) - -The planner agent explores the codebase read-only and produces: - -- Root cause: the exact file, function, and condition -- The expected vs actual behaviour -- Which test cases would prove the bug exists - -No code is written. The plan is stored but not posted -- the repro proof speaks louder. - -## Stage 2: Repro Tests (write failing tests only) - -The agent writes tests that PROVE the bug. Critical constraints: - -- **Do not touch non-test files.** Only `*_test.go` (or the ecosystem's test glob). -- **The gate is inverted.** The test command (last in `[[repos.gate]]`) must FAIL. - If it passes, the repro didn't capture the bug and the stage parks. -- **Make the failure explicit.** The test should assert the correct behaviour, - not just `panic()` or `t.FailNow()`. - -## Stage 3: Capture Proof (deterministic) - -arcie-core runs the test command directly (not through the agent loop) and captures -the output. This is deterministic proof that the tests fail before the fix. - -## Stage 4: Fix (code only) - -The agent fixes the bug. Critical constraints: - -- **Test files are write-protected.** The agent CANNOT modify `*_test.go`. - This is an environmental constraint, not a prompt rule. -- **The full gate runs normally.** All quality commands plus the test suite must pass. -- **Make the smallest fix.** Change only what's needed to make the repro tests pass. - -## Stage 5: Deliver - -arcie-core: - -1. Commits both the repro and the fix as separate commits (telling the PR story) -2. Pushes the branch -3. Opens a PR with the builder's summary -4. Posts the captured failure proof as a PR comment - -## Common pitfalls - -### The repro tests pass unexpectedly - -This means the test doesn't actually capture the bug. Check: - -- Is the test calling the right function with the right inputs? -- Is the assertion checking the correct behaviour (not the buggy behaviour)? -- Are there test setup issues (missing imports, wrong package)? - -### The fix stage modifies test files - -This shouldn't happen -- test files are write-protected. If it does, the agent is -bypassing the constraint. The worktree should be inspected. - -### The gate is misconfigured - -If the repo has no `[[repos.gate]]` entries, TDD cannot run -- it needs at least -one gate command, with the test runner last. diff --git a/install.sh b/install.sh index 950fdff40..7817342bf 100755 --- a/install.sh +++ b/install.sh @@ -401,11 +401,6 @@ fi # 6. Seed skills, personas, memories, and onboarding tasks echo "==> Seeding skills and templates..." -# Copy built-in skills from examples/skills -if [ -d "${SRC_DIR}/examples/skills" ]; then - cp -rn "${SRC_DIR}/examples/skills/"* "${ARCHIE_CONFIG_DIR}/skills/" 2>/dev/null || true -fi - # Seed example personas without overwriting existing files if [ -d "${SRC_DIR}/examples/persona" ]; then cp -rn "${SRC_DIR}/examples/persona/"* "${ARCHIE_CONFIG_DIR}/persona/" 2>/dev/null || true diff --git a/internal/app/archiegateway/gateway.go b/internal/app/archiegateway/gateway.go index bf9c6c3cd..8828b0897 100644 --- a/internal/app/archiegateway/gateway.go +++ b/internal/app/archiegateway/gateway.go @@ -49,6 +49,7 @@ func (b *server) startGatewayRuntime(ctx context.Context, actor gateway.ChatTask return nil, err } b.registerStandaloneTools() + b.serveSkills(ctx) b.addCleanup(shutdownCapabilityHost(ctx, b.capabilityHost, b.log)) if err := b.capabilityHost.Start(ctx); err != nil { return nil, fmt.Errorf("start gateway tool providers: %w", err) diff --git a/internal/app/archiegateway/skills.go b/internal/app/archiegateway/skills.go new file mode 100644 index 000000000..a7acfcedc --- /dev/null +++ b/internal/app/archiegateway/skills.go @@ -0,0 +1,95 @@ +package archiegateway + +import ( + "context" + "encoding/json" + "slices" + "strings" + "time" + + "github.com/samcharles93/archie-core/internal/app/controlplane" + "github.com/samcharles93/archie-core/internal/domain/applystatus" + "github.com/samcharles93/archie-core/internal/skill" +) + +// skillActivateTool is the registry name of the tool that loads a skill. +const skillActivateTool = "skill_activate" + +// serveSkills registers skill_activate over the skills on disk and in the +// skills resource, then keeps it in step: an installed or withdrawn skill +// package reaches the next chat turn within one restamp interval, no restart. +// A skill on disk wins a name the resource also holds. +func (b *server) serveSkills(ctx context.Context) { + var applied string + b.refreshSkills(ctx, &applied) + go func() { + ticker := time.NewTicker(applystatus.RestampInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + b.refreshSkills(ctx, &applied) + } + } + }() +} + +func (b *server) refreshSkills(ctx context.Context, applied *string) { + cfg, log := b.cfg, b.log + catalog, err := skill.CatalogRoots(skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir)...) + if err != nil { + log.Warn("skill catalog load failed", "err", err) + return + } + catalog = append(catalog, b.storedSkills(ctx, catalog)...) + signature := catalogSignature(catalog) + if signature == *applied { + return + } + b.toolReg.Unregister(skillActivateTool) + if entry := skill.ActivateTool(cfg.WorkDir, catalog); entry != nil { + if err := b.toolReg.Register(*entry); err != nil { + log.Warn("skill_activate registration failed", "err", err) + return + } + log.Info("skill catalog registered", "skills", len(catalog)) + } + *applied = signature +} + +// storedSkills reads the skills resource, leaving out any name already in +// have. An unreadable resource contributes nothing this round. +func (b *server) storedSkills(ctx context.Context, have []skill.CatalogEntry) []skill.CatalogEntry { + var out []skill.CatalogEntry + _, _, err := b.controlPlane.Query(ctx, controlplane.SkillsKind, func(value []byte) error { + var collection controlplane.SkillCollection + if err := json.Unmarshal(value, &collection); err != nil { + return err + } + for _, held := range collection.Skills { + entry, err := skill.EntryFromContent([]byte(held.Content)) + if err != nil { + b.log.Warn("stored skill skipped", "skill", held.Name, "err", err) + continue + } + if !slices.ContainsFunc(have, func(e skill.CatalogEntry) bool { return e.Name == entry.Name }) { + out = append(out, entry) + } + } + return nil + }) + if err != nil { + b.log.Warn("skills resource unavailable", "err", err) + } + return out +} + +func catalogSignature(catalog []skill.CatalogEntry) string { + var b strings.Builder + for _, e := range catalog { + b.WriteString(e.Name + "\x00" + e.Description + "\x00" + e.Body + "\x00" + e.Dir + "\x00") + } + return b.String() +} diff --git a/internal/app/archiegateway/tools.go b/internal/app/archiegateway/tools.go index f7b4c6483..c1c9f9e34 100644 --- a/internal/app/archiegateway/tools.go +++ b/internal/app/archiegateway/tools.go @@ -11,7 +11,6 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/plugin" - "github.com/samcharles93/archie-core/internal/skill" "github.com/samcharles93/archie-core/internal/tools/mcp" "github.com/samcharles93/archie-core/internal/tools/minimax" toolprovider "github.com/samcharles93/archie-core/internal/tools/provider" @@ -64,16 +63,6 @@ func (b *server) registerTools() error { func (b *server) registerStandaloneTools() { cfg, log := b.cfg, b.log - if catalog, err := skill.CatalogRoots(skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir)...); err != nil { - log.Warn("skill catalog load failed", "err", err) - } else if entry := skill.ActivateTool(cfg.WorkDir, catalog); entry != nil { - if err := b.toolReg.Register(*entry); err != nil { - log.Warn("skill_activate registration failed", "err", err) - } else { - log.Info("skill catalog registered", "skills", len(catalog)) - } - } - if spillDir := cfg.Tools.Policy.SpillDir; spillDir != "" { if err := toolLimits(cfg).EnsureSpillDir(); err != nil { log.Warn("tool spill directory unavailable; large results will be truncated instead", "err", err) diff --git a/internal/app/controlplane/definitions.go b/internal/app/controlplane/definitions.go index 261edb0e8..dcfef1442 100644 --- a/internal/app/controlplane/definitions.go +++ b/internal/app/controlplane/definitions.go @@ -8,7 +8,7 @@ import ( // Schemas are not declared here: each Definition names its document type, and // Definition.Descriptor derives the JSON Schema from it (internal/app/controlplane/schema.go). func builtinDefinitions(steps workflow.StepRegistry) []Definition { - definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), workflowEnablementDefinition(), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), playbooksDefinition(), credentialBindingsDefinition(), reviewSettingsDefinition()} + definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), workflowEnablementDefinition(), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), reviewSettingsDefinition()} definitions = append(definitions, modelDefinitions()...) definitions = append(definitions, operationalDefinitions()...) return definitions diff --git a/internal/app/controlplane/package_projection.go b/internal/app/controlplane/package_projection.go index 417442fe7..e0a568804 100644 --- a/internal/app/controlplane/package_projection.go +++ b/internal/app/controlplane/package_projection.go @@ -4,10 +4,12 @@ import ( "context" "errors" "fmt" + "slices" "strconv" "time" "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/storepkg" ) // projectDocument edits one org resource on behalf of an installed package. @@ -45,3 +47,89 @@ func projectDocument(ctx context.Context, store ResourceStore, orgID, kind, sour return nil } } + +// listFamily describes a family whose resource is a list of entries with +// stable ids, merged into by installed packages. +type listFamily[E any] struct { + kind, family string + decode func([]byte) ([]E, error) + // encode validates the merged list and returns the document. + encode func([]E) ([]byte, error) + id func(E) string + // parse reads one contributed file into an entry. + parse func(name string, content []byte) (E, error) +} + +// listProjector merges an installed package's entries into the org's list +// resource. Ids owned by an operator or another package are refused. +type listProjector[E any] struct { + store ResourceStore + ledger storepkg.ProjectionLedger + listFamily[E] +} + +func newListProjector[E any](resources ResourceStore, ledger storepkg.ProjectionLedger, family listFamily[E]) (*listProjector[E], error) { + if resources == nil || ledger == nil { + return nil, fmt.Errorf("control plane: %s projection needs a resource store and a contributions ledger", family.family) + } + return &listProjector[E]{store: resources, ledger: ledger, listFamily: family}, nil +} + +func (p *listProjector[E]) Apply(ctx context.Context, orgID, name, digest string, contents map[string][]byte) error { + incoming := make([]E, 0, len(contents)) + recorded := make([]storepkg.ProjectionEntry, 0, len(contents)) + for contentName, content := range contents { + entry, err := p.parse(contentName, content) + if err != nil { + return fmt.Errorf("contributed %s %q: %w", p.family, contentName, err) + } + incoming = append(incoming, entry) + recorded = append(recorded, storepkg.ProjectionEntry{Family: p.family, EntryID: p.id(entry)}) + } + err := projectDocument(ctx, p.store, orgID, p.kind, "package:"+name+"@"+digest, "package-project:"+digest, func(current []byte) ([]byte, error) { + entries, err := p.decode(current) + if err != nil { + return nil, err + } + for _, have := range entries { + if slices.ContainsFunc(incoming, func(in E) bool { return p.id(in) == p.id(have) }) { + return nil, fmt.Errorf("package %q: %w: %s %q", name, storepkg.ErrContributionCollision, p.family, p.id(have)) + } + } + return p.encode(append(entries, incoming...)) + }) + if err != nil { + return err + } + if err := p.ledger.Record(ctx, orgID, name, recorded); err != nil { + return fmt.Errorf("record contributions of %q: %w", name, err) + } + return nil +} + +func (p *listProjector[E]) Withdraw(ctx context.Context, orgID, name, digest string) error { + recorded, err := p.ledger.Entries(ctx, orgID, name) + if err != nil { + return fmt.Errorf("entries of package %q: %w", name, err) + } + var withdrawn []string + for _, entry := range recorded { + if entry.Family == p.family { + withdrawn = append(withdrawn, entry.EntryID) + } + } + if len(withdrawn) == 0 { + return nil + } + err = projectDocument(ctx, p.store, orgID, p.kind, "package-withdraw:"+name+"@"+digest, "package-withdraw:"+digest, func(current []byte) ([]byte, error) { + entries, err := p.decode(current) + if err != nil { + return nil, err + } + return p.encode(slices.DeleteFunc(entries, func(e E) bool { return slices.Contains(withdrawn, p.id(e)) })) + }) + if err != nil { + return err + } + return p.ledger.Forget(ctx, orgID, name, p.family) +} diff --git a/internal/app/controlplane/playbooks.go b/internal/app/controlplane/playbooks.go index 59106454f..5927081c1 100644 --- a/internal/app/controlplane/playbooks.go +++ b/internal/app/controlplane/playbooks.go @@ -1,13 +1,9 @@ package controlplane import ( - "context" "encoding/json" - "errors" "fmt" "path" - "slices" - "strings" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/eda/module" @@ -65,80 +61,23 @@ func CompilePlaybooks(c PlaybookCollection) (*playbook.Store, error) { return store, nil } -// PlaybookProjector merges an installed package's playbooks into the org's -// eda-playbooks resource. Ids owned by an operator or another package are -// refused. -type PlaybookProjector struct { - store ResourceStore - ledger storepkg.ProjectionLedger -} - -var _ storepkg.FamilyProjector = (*PlaybookProjector)(nil) - -func NewPlaybookPackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger) (*PlaybookProjector, error) { - if resources == nil || ledger == nil { - return nil, errors.New("control plane: playbook projection needs a resource store and a contributions ledger") - } - return &PlaybookProjector{store: resources, ledger: ledger}, nil -} - -func (p *PlaybookProjector) Apply(ctx context.Context, orgID, name, digest string, contents map[string][]byte) error { - incoming := make([]PlaybookEntry, 0, len(contents)) - recorded := make([]storepkg.ProjectionEntry, 0, len(contents)) - for contentName, content := range contents { - id := path.Base(contentName) - incoming = append(incoming, PlaybookEntry{ID: id, YAML: string(content)}) - recorded = append(recorded, storepkg.ProjectionEntry{Family: storepkg.FamilyPlaybooks, EntryID: id}) - } - slices.SortFunc(incoming, func(a, b PlaybookEntry) int { return strings.Compare(a.ID, b.ID) }) - err := projectDocument(ctx, p.store, orgID, PlaybooksKind, "package:"+name+"@"+digest, "package-project:"+digest, func(current []byte) ([]byte, error) { - collection, err := decodePlaybooks(current) - if err != nil { - return nil, err - } - for _, entry := range collection.Playbooks { - if slices.ContainsFunc(incoming, func(in PlaybookEntry) bool { return in.ID == entry.ID }) { - return nil, fmt.Errorf("package %q: %w: playbook %q", name, storepkg.ErrContributionCollision, entry.ID) - } - } - collection.Playbooks = append(collection.Playbooks, incoming...) - return encodePlaybooks(collection) +// NewPlaybookPackageProjector builds the projector for storepkg.FamilyPlaybooks. +func NewPlaybookPackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger) (storepkg.FamilyProjector, error) { + return newListProjector(resources, ledger, listFamily[PlaybookEntry]{ + kind: PlaybooksKind, + family: storepkg.FamilyPlaybooks, + decode: func(value []byte) ([]PlaybookEntry, error) { + c, err := decodePlaybooks(value) + return c.Playbooks, err + }, + encode: func(entries []PlaybookEntry) ([]byte, error) { + return encodePlaybooks(PlaybookCollection{Playbooks: entries}) + }, + id: func(e PlaybookEntry) string { return e.ID }, + parse: func(name string, content []byte) (PlaybookEntry, error) { + return PlaybookEntry{ID: path.Base(name), YAML: string(content)}, nil + }, }) - if err != nil { - return err - } - if err := p.ledger.Record(ctx, orgID, name, recorded); err != nil { - return fmt.Errorf("record contributions of %q: %w", name, err) - } - return nil -} - -func (p *PlaybookProjector) Withdraw(ctx context.Context, orgID, name, digest string) error { - entries, err := p.ledger.Entries(ctx, orgID, name) - if err != nil { - return fmt.Errorf("entries of package %q: %w", name, err) - } - var withdrawn []string - for _, entry := range entries { - if entry.Family == storepkg.FamilyPlaybooks { - withdrawn = append(withdrawn, entry.EntryID) - } - } - if len(withdrawn) == 0 { - return nil - } - err = projectDocument(ctx, p.store, orgID, PlaybooksKind, "package-withdraw:"+name+"@"+digest, "package-withdraw:"+digest, func(current []byte) ([]byte, error) { - collection, err := decodePlaybooks(current) - if err != nil { - return nil, err - } - collection.Playbooks = slices.DeleteFunc(collection.Playbooks, func(e PlaybookEntry) bool { return slices.Contains(withdrawn, e.ID) }) - return encodePlaybooks(collection) - }) - if err != nil { - return err - } - return p.ledger.Forget(ctx, orgID, name, storepkg.FamilyPlaybooks) } func decodePlaybooks(value []byte) (PlaybookCollection, error) { diff --git a/internal/app/controlplane/skills.go b/internal/app/controlplane/skills.go new file mode 100644 index 000000000..f27a35de1 --- /dev/null +++ b/internal/app/controlplane/skills.go @@ -0,0 +1,101 @@ +package controlplane + +import ( + "encoding/json" + "errors" + "fmt" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/storepkg" + "github.com/samcharles93/archie-core/internal/skill" +) + +// SkillsKind is the control-plane resource holding the org's skills: SKILL.md +// documents under their skill name. +const SkillsKind = "skills" + +// SkillCollection is the skills document. +type SkillCollection struct { + Skills []SkillEntry `json:"skills"` +} + +// SkillEntry is one skill. Content is its SKILL.md. +type SkillEntry struct { + Name string `json:"name"` + Content string `json:"content"` +} + +func skillsDefinition() Definition { + return Definition{ + Kind: SkillsKind, + Title: "Skills", + Document: SkillCollection{}, + ApplyMode: "live", + Seed: func(config.Config) any { return SkillCollection{Skills: []SkillEntry{}} }, + Validate: func(input []byte) error { + return validateAs(input, validateSkills) + }, + } +} + +func validateSkills(c SkillCollection) error { + seen := map[string]bool{} + for _, entry := range c.Skills { + if entry.Name == "" || seen[entry.Name] { + return fmt.Errorf("%w: skill name %q is empty or repeated", ErrValidation, entry.Name) + } + seen[entry.Name] = true + fm, _, err := skill.Parse([]byte(entry.Content)) + if err != nil { + return fmt.Errorf("%w: skill %q: %w", ErrValidation, entry.Name, err) + } + if fm.Name != entry.Name { + return fmt.Errorf("%w: skill %q: SKILL.md names it %q", ErrValidation, entry.Name, fm.Name) + } + } + return nil +} + +// NewSkillPackageProjector builds the projector for storepkg.FamilySkills. +func NewSkillPackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger) (storepkg.FamilyProjector, error) { + return newListProjector(resources, ledger, listFamily[SkillEntry]{ + kind: SkillsKind, + family: storepkg.FamilySkills, + decode: func(value []byte) ([]SkillEntry, error) { + c, err := decodeSkills(value) + return c.Skills, err + }, + encode: func(entries []SkillEntry) ([]byte, error) { + return encodeSkills(SkillCollection{Skills: entries}) + }, + id: func(e SkillEntry) string { return e.Name }, + parse: func(_ string, content []byte) (SkillEntry, error) { + fm, _, err := skill.Parse(content) + if err != nil { + return SkillEntry{}, err + } + if fm.Name == "" { + return SkillEntry{}, errors.New("no frontmatter name") + } + return SkillEntry{Name: fm.Name, Content: string(content)}, nil + }, + }) +} + +func decodeSkills(value []byte) (SkillCollection, error) { + collection := SkillCollection{Skills: []SkillEntry{}} + if value == nil { + return collection, nil + } + if err := json.Unmarshal(value, &collection); err != nil { + return SkillCollection{}, fmt.Errorf("decode %s: %w", SkillsKind, err) + } + return collection, nil +} + +func encodeSkills(collection SkillCollection) ([]byte, error) { + if err := validateSkills(collection); err != nil { + return nil, err + } + return json.Marshal(collection) +} diff --git a/internal/app/statestore/server.go b/internal/app/statestore/server.go index 15dd64934..f9b03b24f 100644 --- a/internal/app/statestore/server.go +++ b/internal/app/statestore/server.go @@ -510,7 +510,7 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants, cal } // newPackageProjections builds the family projectors an installed package's -// contributions apply through: workflows, playbooks and agent profiles become +// contributions apply through: workflows, playbooks, skills and agent profiles become // the org resources the runtime reads live. The step vocabulary // (stepVocabulary) is the same one this process's control plane validates // dashboard edits with, so a definition the projector admits is compilable @@ -534,8 +534,13 @@ func newPackageProjections(pool *pgxpool.Pool) (map[string]storepkg.FamilyProjec if err != nil { return nil, fmt.Errorf("build profile package projector: %w", err) } + skills, err := controlplane.NewSkillPackageProjector(resources, ledger) + if err != nil { + return nil, fmt.Errorf("build skill package projector: %w", err) + } return map[string]storepkg.FamilyProjector{ storepkg.FamilyWorkflows: workflows, + storepkg.FamilySkills: skills, storepkg.FamilyPlaybooks: playbooks, storepkg.FamilyProfiles: profiles, }, nil diff --git a/internal/skill/skill.go b/internal/skill/skill.go index eeb1ddf78..66e1705c5 100644 --- a/internal/skill/skill.go +++ b/internal/skill/skill.go @@ -37,6 +37,25 @@ type CatalogEntry struct { Workflow string // from metadata.archie.workflow -- which workflow this skill handles Dir string // skill directory name Root string // catalog root containing.agents/skills + // Body is the skill's instructions when they are held in memory rather + // than in Dir under Root. + Body string +} + +// EntryFromContent builds a catalog entry for a SKILL.md held in memory. +func EntryFromContent(content []byte) (CatalogEntry, error) { + fm, body, err := Parse(content) + if err != nil { + return CatalogEntry{}, err + } + if fm.Name == "" { + return CatalogEntry{}, fmt.Errorf("SKILL.md has no name") + } + entry := CatalogEntry{Name: fm.Name, Description: fm.Description, Body: body} + if fm.Metadata.Archie != nil { + entry.Workflow = fm.Metadata.Archie.Workflow + } + return entry, nil } // Only the frontmatter is parsed -- full bodies are not loaded. Missing diff --git a/internal/skill/tooldef.go b/internal/skill/tooldef.go index dec4e9c19..8a4d846ca 100644 --- a/internal/skill/tooldef.go +++ b/internal/skill/tooldef.go @@ -18,7 +18,9 @@ func ActivateTool(dir string, catalog []CatalogEntry) *tools.ToolEntry { descByName := make(map[string]string, len(catalog)) dirByName := make(map[string]string, len(catalog)) rootByName := make(map[string]string, len(catalog)) + bodyByName := make(map[string]string, len(catalog)) for i, e := range catalog { + bodyByName[e.Name] = e.Body names[i] = e.Name descByName[e.Name] = e.Description dirByName[e.Name] = e.Dir @@ -51,6 +53,9 @@ func ActivateTool(dir string, catalog []CatalogEntry) *tools.ToolEntry { if !ok { return nil, fmt.Errorf("skill_activate: unknown skill %q", name) } + if body := bodyByName[name]; body != "" { + return body, nil + } root := dir if catalogRoot := rootByName[name]; catalogRoot != "" { root = catalogRoot