Pikku software archaeology

From pikkujs/pikku · View interactive version

Pikku software archaeology is an AI agent skill from the GitHub repository pikkujs/pikku. Reverse-engineer a repo into a `.knowledge/` Product Blueprint for a rebuild, and explain it plainly to a non-technical owner. Not `knowledge/` notes (pikku-knowledge) or code review.

How to use this skill

Skill file

Software Archaeology

Overview

Extract intent over implementation. A repository is a fossil record of product decisions; your job is to recover the product — domains, entities, commands, queries, events, policies, workflows, invariants — not to describe the code. The output is a .knowledge/ directory of schema-validated JSON plus a human-readable blueprint.md, consumable by a generator (Pikku) to rebuild the application cleanly.

You are the parser. Do not build or rely on regex/AST scanners — read the code with your own tools (Grep, Read, subagents). This is what makes the skill language-agnostic: an Express app, a Rails app, and a Django app all yield the same blueprint shape.

Two layers, never merged silently:

Never present a guess as a fact. confidence: "high" requires file:line evidence of the behavior itself.

Output Contract

Everything goes in <repo>/.knowledge/ (or a caller-specified directory):

.knowledge/
├── product.json        # purpose, virtualUsers, capabilities, terminology
├── domains.json        # business domains (NEVER folder names)
├── entities.json       # domain entities: attributes, relationships, states, transitions
├── commands.json       # state-changing actions (SendInvoice, not POST /invoices/:id/send)
├── queries.json        # read operations and views
├── events.json         # business facts, past tense (InvoicePaid) — no technical events
├── policies.json       # authorization, validation, state, business-constraint rules
├── workflows.json      # user + admin + system workflows, with test-derived scenarios
├── api.json            # every surface, each mapped to a command/query/event-ingress
├── integrations.json   # external services: purpose, direction, replaceability
├── architecture.json   # components, datastores, deployment constraints worth keeping
├── invariants.json     # what must ALWAYS be true, and what enforces it today
├── gaps.json           # TODOs, hacks, duplication, dead code, open product decisions
├── migration.json      # current files -> future concepts, drops, decisions needed
├── blueprint.md        # human synthesis of all of the above
│
│   # OPTIONAL — the consumer-surface layer. Emit these when the repo has a
│   # frontend and/or non-HTTP consumer channels. A backend-only repo omits them
│   # and the validator does not complain.
├── interfaces.json         # every way the product is consumed: web-ui, cli, mcp, openapi-rest, sdk, realtime, webhooks
├── frontend.json           # web-UI app shape: framework, router, styling, data layer, auth (e.g. TanStack Start + better-auth + Tailwind)
├── frontend-routes.json    # the page/route tree — what a user navigates to, its data + components
└── frontend-components.json# component inventory; `rebuild` splits trivial-library from custom-logic-to-port

The exact field shapes live in references/blueprint.schema.json (in this skill's directory — read it before writing any output file). After writing, ALWAYS run:

node <skill-dir>/scripts/validate.mjs <repo>/.knowledge

and fix every ERROR (WARNs are prompts to double-check, not necessarily wrong). Do not declare the extraction done with validation errors outstanding.

The Pipeline

Work in phases. For small repos (< ~50 source files) do them inline; for larger repos, fan out subagents per phase-3 lens and merge (see "Scaling up").

Phase 1 — Survey (facts only)

Build an inventory before interpreting anything:

Framework guides. Once you know the framework, read its guide before extracting. Each lists where intent hides, how its idioms map to blueprint concepts, the traps, and a grep checklist. Read only the ones that apply:

Other ecosystems fall back to this table. Where intent hides, per ecosystem (read these first):

| Ecosystem | Highest-yield locations |

| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| Rails | config/routes.rb, model validations + callbacks + aasm/state machines, app/policies (Pundit) / ability.rb (CanCan), Sidekiq/ActiveJob workers, db/schema.rb, specs (esp. request + model specs) |

| Express/Node | route registration files, middleware chains (auth!), inline if guards in handlers, SQL/ORM models, jobs/+crontab refs, webhook handlers |

| Django | urls.py, model Meta/constraints/clean(), DRF serializers + permissions classes, celery tasks, admin.py (reveals internal workflows) |

| Laravel | routes/, FormRequests (validation), Policies/Gates, Jobs + scheduler in Kernel.php, migrations |

| Go | mux/router setup, middleware, struct tags, cmd/ binaries (each is a component) |

| Frontend (React/Vue/etc.) | router config / file-based routes (pages a user reaches), the component tree, the design-system import (@mui/*, Tailwind config, shadcn components.json) to judge consistency, the data layer (react-query/tRPC/fetch wrappers) to tie UI back to backend queries, charts/tables/editors (the custom-logic port risk), auth wiring |

Phase 2 — Test excavation (do not skip)

Tests are the closest thing to an executable product spec. For every test file:

A rule attested by both an implementation guard AND a test is your strongest possible evidence — cite both.

Phase 3 — Extraction lenses

Run each lens over the surveyed material. Rules that counter the classic failure modes:

Domains — infer from data ownership, workflows, and vocabulary; NEVER from folder names. controllers/ is not a domain; "Billing" is. A domain owns entities and the commands that mutate them.

Entities — domain concepts, not tables. Include: attributes (from schema + serializers + fixtures), relationships, lifecycle states and transitions (grep status/state columns, then find every write to them — each write site is a transition with a trigger), ownership (which virtual user's rows), constraints.

Commands — every way state changes: routes, jobs, webhooks, CLI, admin consoles, DB triggers. Name them imperative VerbNoun in domain language: POST /api/users/:id/status → ActivateUser. For each: virtual user, preconditions (every if (...) return 4xx guard is a precondition or policy), effects, events produced. Convention: authentication/token issuance is a command (LogInUser, effect: "issues a session/JWT") even though it writes no rows — it changes the caller's security state.

Queries — reads and views, GetX/ListX/SearchX. Record the tenancy scoping each applies (a missing WHERE user_id= that exists elsewhere is a gaps.json security entry).

Events — meaningful business facts, past tense. Most legacy apps have implicit events: an email send, a status flip, and a counter bump inside one handler are the event's consumers — reconstruct InvoicePaid from them and set explicit: false. Exclude technical noise (ButtonClicked, FunctionCalled). Inclusion threshold for implicit events: at least one observed consumer beyond the row write itself (an email, a downstream job, a webhook out, a derived-state flip). Plain CRUD facts with no reaction (ClientCreated that nothing listens to) do not become events.

Policies — authorization, validation, state rules, business constraints. Record every location enforcing each rule in enforcedAt; the same rule enforced in 3 places (or worse, 2 slightly different versions) is a gaps.json duplication entry.

Workflows — ALL of them: user journeys, admin/support operations, and system workflows (cron jobs, queue consumers, webhook reactions, syncs, notification sweeps). A crontab line in a comment is a workflow. Attach Phase-2 scenarios.

API — list every surface but map each to its concept (mapsTo: {type: command, name: SendInvoice}). The route is evidence; the command is the deliverable. Auth per surface (including "none" and capability-URLs like tokened public links). A webhook whose handler changes state maps to a command (RecordInvoicePayment); reserve event-ingress for pure relay surfaces, where name must be an events.json event.

Integrations — from deps + config + calls: purpose, data exchanged, direction, importance, replacement difficulty, env vars.

Architecture — components as they actually run (API process, worker, cron job, SPA), datastores, and deployment constraints that must survive the rewrite (hardcoded ports with upstream expectations, raw-body middleware ordering, webhook retry semantics).

Invariants — what must always hold, and enforcedBy: db-constraint, code-guard, convention, or nothing (an unenforced invariant is a gap). Include atRiskBecause when enforcement is fragile (e.g. read-then-insert sequence numbering races).

Gaps — incomplete features, TODOs, hacks (hardcoded admin emails), duplicated logic that drifted, dead code, unclear ownership, and open product decisions the code never resolved (a FIXME asking "should deleting a client void invoices?" is a product decision, record it in both gaps.json and migration.json decisionsNeeded).

Migration — map current file clusters → future domain + concepts; list files to drop with reasons; list decisions a human must make before rebuild.

Interfaces (interfaces.json, optional) — every way the product is CONSUMED, one entry per channel, not per route. A product is usually driven through several: a web UI (humans), a CLI (developers/operators), an MCP server (AI agents — in a Pikku app each MCP tool IS a pikkuFunc), an OpenAPI/REST surface (developers/external systems, often _generated_ from the routes), a generated SDK, realtime (websocket/SSE), and webhooks (in/out). For each: kind, audience, purpose, roughly how many ops it exposes, whether it's generated vs hand-written, which domains it serves, and status (complete/partial/stub — an MCP server with two tools is stub). This layer answers "who can drive this, and how" — it is the map the second-opinion skill needs to explain that the app is usable by people, developers, and agents.

Frontend (frontend.json + frontend-routes.json + frontend-components.json, optional) — the web UI, which needs its own treatment because frontends vary wildly (framework, router, styling, state, data, auth) and the rebuild target is opinionated: everything in one component system (shadcn), one data layer, one auth.

Phase 4 — Cross-check, validate, synthesize

  1. Cross-checks before writing: every command has a virtual user and at least one precondition or policy (or you explain why it is genuinely unguarded); every state transition appears in some command/workflow — if a state is only reachable by manual/DB intervention, record the transition with trigger "none (manual/DB-only)" AND add a gaps.json entry; every event has a producer; every api surface maps to a defined concept; every integration is used by some command/workflow.
  2. Write all 14 JSON files, sorting unordered identity collections by name (or path) — on first extraction too, not just re-runs. Arrays whose order carries meaning (workflows[].steps, and any other observed sequence) stay in their observed order: sorting them would rewrite the behavior you extracted. Run the validator: done means 0 error(s) and exit 0, and every WARN explicitly reviewed and either fixed or justified in your summary.
  3. Write blueprint.md: product summary → domain map → per-domain narrative (entities/commands/events with the interesting rules) → workflows → integrations/architecture → invariants → gaps and open decisions → rebuild recommendation. Write it for the engineer who will rebuild the product and has never seen the legacy code.

Evidence & Confidence Discipline

Scaling up (large repos)

Red Flags — you are about to produce a worthless blueprint

| Thought | Reality |

| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| "I'll write it up as markdown docs" | Only blueprint.md is prose. The 14 JSON files ARE the deliverable; a generator consumes them. |

| "The routes are the API contract" | Routes are evidence. Lift each to a command/query or you've documented plumbing, not product. |

| "This is obvious, no citation needed" | Uncited claims are indistinguishable from hallucinations. Evidence on everything. |

| "The folder structure tells me the domains" | Folders are how it grew, not what it is. Derive domains from ownership + vocabulary. |

| "Tests are just tests, skip them" | Tests are the spec. Some rules exist ONLY in tests. Phase 2 is mandatory. |

| "No events are emitted, so events: []" | Reconstruct implicit events from side-effect clusters; mark explicit: false. |

| "Cron jobs aren't workflows" | System workflows are workflows. Include schedules, queue consumers, webhook reactions. |

| "The frontend is just the web routes" | The web UI is ONE interface. Inventory the CLI, MCP server, OpenAPI/SDK, realtime, webhooks in interfaces.json too — the product is driven by people, developers, AND agents. |

| "A component list is enough" | Without the rebuild split, you've hidden the frontend's real cost. Flag every custom-logic component (chart/table/canvas/editor) and say what the logic is — that's the port work. |

| "I'll skip the validator, the JSON looks right" | Run it. Missing domains refs, dangling event names, and undescribed custom-logic components are exactly what it catches. |

Reference files

The second phase — a report the owner can act on

Extraction produces a blueprint for a machine to rebuild from. The same

.knowledge/ directory is also the input to a second opinion for the person who

holds the app: what works, what is holding them back, and what you would build

instead, argued in business outcomes rather than architecture.

That phase has its own voice rules, structure and red flags — read

references/second-opinion.md, fill in

references/second-opinion-report-template.md, and match the tone of

example/second-opinion-sample-report.md. It consumes the blueprint; it never

re-derives facts from the code, so run the extraction first.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.