/session-orchestrator:discovery [all|code|infra|ui|arch|session|audit|vault|feature] [--since <git-ref>] [--full]from session-orchestrator
Runs systematic quality discovery and issue detection with modular probes adapted to the project's tech stack. Presents findings for interactive triage and creates VCS issues for confirmed problems.
Ships in session-orchestrator. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Plugin root:
${CLAUDE_PLUGIN_ROOT}. Claude Code replaces this with the plugin's absolute path when it loads this file. Where it appears unreplaced — in a file this skill reads with the Read tool, or on Codex, Cursor or Pi — the plugin root is the directory that contains this skill'sskills/folder (two levels above the folder of this SKILL.md). Write that absolute path literally into every command that starts a plugin script: the Bash tool has no plugin variable, and shell variables do not survive between tool calls.
The user invokes /discovery with scope: $ARGUMENTS (if empty, default to all).
Parse $ARGUMENTS before doing anything else. Extract the following flags and tokens in any order:
--since <git-ref> — restrict discovery to files changed since the given git ref (e.g. HEAD~5, main, a commit hash). Sets since_ref = <git-ref>, which is passed into Phase 3 plumbing.--full — explicit full-repo scan. Sets full_scan = true.Conflict check: If BOTH --since and --full are present, stop immediately and report:
Error: Cannot use --since with --full. Provide one, not both.
Do NOT proceed with discovery when this conflict is present.
Argument validation: Valid scopes: all, code, infra, ui, arch, session, audit, vault, feature (comma-separated for multiple). If any scope is invalid, inform the user: "Invalid scope '[token]'. Valid scopes: all, code, infra, ui, arch, session, audit, vault, feature." and default that token to all.
Scan the codebase for quality issues, technical debt, and improvement opportunities within the requested scope. Do NOT skip the interactive triage phase — every finding must be confirmed by the user before issue creation (a lead-guided run confirms by recorded decision, § Lead-guided runs). Evidence before assertions.
Two modes of operation:
/discovery [scope]): Full 6-phase flow with interactive triage (Phases 0-6)discovery-on-close: true): Phases 0-4 only, returns structured findings to session-endThe scope argument accepts: all (default), code, infra, ui, arch, session, audit, vault, feature, or comma-separated like code,session.
Read skills/_shared/bootstrap-gate.md and execute the gate check. If the gate is CLOSED, invoke skills/bootstrap/SKILL.md and wait for completion before proceeding. If the gate is OPEN, continue to Phase 1.
Read and parse Session Config per skills/_shared/config-reading.md. Store result as $CONFIG.
Discovery-relevant fields (parse these specifically):
discovery-on-close, discovery-probes, discovery-exclude-paths, discovery-severity-threshold, discovery-confidence-threshold, discovery-parallelismtest-command, typecheck-command, lint-commandpencil, vcs, cross-repos, stale-issue-daysDetect the project's tech stack via marker file checks. Use Glob and run checks in parallel:
| Marker File(s) | Activates |
|---|---|
package.json | JS/TS probes |
tsconfig.json | TypeScript probes |
requirements.txt / pyproject.toml | Python probes |
Dockerfile / docker-compose.yml | Container probes |
vercel.json / .vercel/ | Vercel probes |
.github/workflows/ | GitHub CI probes |
.gitlab-ci.yml | GitLab CI probes |
supabase/ | Supabase probes |
next.config.* / nuxt.config.* | SSR probes |
tailwind.config.* | Tailwind probes |
| Pencil in Session Config | design-drift probe |
.orchestrator/bootstrap.lock | harness-audit probe |
.vault.yaml OR Session Config vault-integration.enabled: true | vault probes |
package.json / requirements.txt / Cargo.toml AND Session Config slopcheck.enabled: true AND slopcheck.sources includes "discovery" | supply-chain probe (skills/discovery/probes-supply-chain.md) |
docs/ directory present AND Session Config docs-staleness.enabled: true | docs-staleness probe (skills/discovery/probes-docs.md) |
CLAUDE.md (or AGENTS.md on Codex CLI) or README.md present in repo root | ssot-code-diff probe (skills/discovery/probes-docs.md) — always active within the docs category, no Session Config gate |
discovery-probes is set in config, intersect with that listscope argument was passed, restrict to that categoryThe audit probe activates when bootstrap.lock is present OR when discovery-probes config explicitly lists audit.
The vault probe activates when .vault.yaml is present in the repo root OR when vault-integration.enabled: true in Session Config OR when discovery-probes config explicitly lists vault.
The feature probe activates ONLY when the scope argument includes feature OR when discovery-probes config explicitly lists feature. It never activates under bare all — feature discovery is an explicitly requested scan, and its interactive router (below) cannot run in embedded mode.
Default exclude paths (always apply):
node_modules/, .git/, dist/, build/, .next/, .nuxt/, coverage/Add any paths from discovery-exclude-paths in Session Config.
VCS Reference: Detect the VCS platform per the "VCS Auto-Detection" section of the gitlab-ops skill.
Report: "Discovery: [N] probes active across [categories]. Stack: [detected]. Threshold: [severity]."
Fires ONLY when the active scope set includes feature AND the skill is running standalone (coordinator context). In embedded mode (session-end dispatches discovery as an Explore subagent — AskUserQuestion is unavailable in subagents per .claude/rules/ask-via-tool.md AUQ-004), the router MUST NOT fire; proceed directly with the grounded scan as the non-interactive default.
Judgment-based PM work (opportunity framing, personas, market-sizing) deliberately stays OUT of the verified-findings pipeline (Epic #750) — this router is the fork point that keeps grounded, evidence-anchored discovery separate from open-ended product judgment.
When the gate above is satisfied, present exactly this AskUserQuestion (AUQ-003 shape) before proceeding to Phase 3:
AskUserQuestion({
questions: [{
question: "Scope `feature` was requested. How should this run handle it?",
header: "Scope",
options: [
{ label: "Grounded scan (Recommended)", description: "Every finding is tied to a file and line and is verified before it can become an issue. Cost: two extra probes (intent-drift, stubbed-dead-feature)." },
{ label: "Also judgment topics", description: "Same scan, plus open product questions (opportunity framing, personas) kept as notes. They never become issues; after Phase 5 you pick where they go." },
{ label: "Route out", description: "No scan at all. You get a pointer to /brainstorm (product ideation) or /grill (assumption stress-test) instead." },
{ label: "Skip", description: "Drops `feature` (the probes for half-built and drifted features) from this run; the other scopes still run." }
],
multiSelect: false
}]
})
On user selection (every branch is explicit — do not fall through):
feature in the active scope set and continue to Phase 3 unchanged.feature in the active scope set and continue to Phase 3 unchanged for the grounded probes. Collect any judgment-based product questions (opportunity framing, personas, market-sizing) encountered during the scan as plain notes — do not route them through Phase 4 (Verification) or Phase 6 (Issue-Creation) at any point. AFTER Phase 5 triage completes, present a SECOND AskUserQuestion that forks how the collected topics are handled:AskUserQuestion({
questions: [{
question: "Where should the collected judgment topics go?",
header: "Topics",
options: [
{ label: "Inline synthesis (Recommended)", description: "Sketches an outcome/persona pass into `### Judgment Topics (non-verified)` (a report section that never becomes issues). Cost: no second run." },
{ label: "Route to /brainstorm", description: "Hands the topics to /brainstorm as its opening context, for a full question-and-answer design dialogue." },
{ label: "Route to /plan feature", description: "Hands the topics to /plan feature as its opening context, for feature-PRD scoping." }
],
multiSelect: false
}]
})
### Judgment Topics (non-verified) section to the discovery report. For each collected topic, write a brief candidate outcome/opportunity sketch (Teresa Torres OST framing) and, where a persona angle is evident, a one-line persona note — every line explicitly labeled (non-verified sketch). This is prose synthesis, never a probe finding.### Judgment Topics (non-verified) section, but render each topic as a one-line pointer plus the recommendation to invoke /brainstorm with the collected topic context pre-filled as its initial prompt. Do not auto-invoke /brainstorm — surface the recommendation and let the operator trigger it./brainstorm branch above, pointing at /plan feature with the collected topic context pre-filled instead.Invariant (PRD §4 Non-Goals) — holds across all three sub-branches above: judgment items are report-appendix ONLY — they MUST NOT become findings, MUST NOT pass through Phase 4 verification, and MUST NOT produce issues in Phase 6.
feature from the active scope set. Do NOT run the feature probes. Recommend the operator invoke /brainstorm or /grill after this run (name whichever fits the operator's question), then continue to Phase 3 with the remaining scopes — or, if feature was the ONLY requested scope, stop after reporting: "Feature scope routed out — no probes to run. Invoke /brainstorm or /grill directly."feature from the active scope set before Phase 3. If feature was the only requested scope, stop with: "Feature scope skipped — nothing to run."since_ref is provided)When since_ref is set (passed from the /discovery --since <git-ref> invocation):
changedFilesSince(since_ref) from scripts/lib/discovery/helpers.mjs.[] (no files changed since the ref), emit:
No files changed since <since_ref>. Skipping discovery.
and exit with status 0. Do NOT fall back to a full-repo scan.changedFiles context to each probe agent below.Probe exemptions: The vault-staleness probe and the harness-audit probe are EXEMPT from --since filtering — they always scan the full repository because their analysis targets metadata (vault narrative staleness, bootstrap lock state) that is not file-diff-gated. This exemption is advisory: no code enforcement is applied in this wave. The probe agents will naturally read whole-repo state; the changedFiles context they receive from --since is informational and does not restrict their glob/grep scope.
Dispatch probe agents IN PARALLEL using the Agent tool. Group by category (max $CONFIG['discovery-parallelism'] agents, default 5):
Cursor IDE: No Agent() tool available. Run probes sequentially within the current session — one category at a time. Complete each category's analysis before moving to the next.
skills/discovery/probes/insecure-infra-defaults.mjs (invoked via node per probes-infra.md; runs the private baseline's pattern SSOT scripts/check-insecure-defaults.sh and returns {findings, metrics, duration_ms}; skips with no-baseline without it; discovery-only, never session-end Phase 2.4).skills/discovery/probes-vault.md): invokes skills/discovery/probes/vault-staleness.mjs and skills/discovery/probes/vault-narrative-staleness.mjs directly via node. Each probe returns {findings, metrics, duration_ms}. The runner reports FINDING: blocks per finding and appends summary records to .orchestrator/metrics/vault-staleness.jsonl and vault-narrative-staleness.jsonl.skills/discovery/probes-supply-chain.md): invokes skills/discovery/probes/supply-chain-slopcheck.mjs directly via node. Gated: only activates when slopcheck.enabled: true AND "discovery" is in slopcheck.sources (Session Config). The probe returns {findings, summary}. SLOP findings surface as critical, ASSUMED as medium, LEGITIMATE packages generate no finding. See probes-supply-chain.md for invocation details and classification reference.skills/discovery/probes-docs.md): invokes skills/discovery/probes/docs-staleness.mjs AND skills/discovery/probes/ssot-code-diff.mjs directly via node. docs-staleness.mjs is gated: only activates when a docs/ directory exists AND docs-staleness.enabled: true (Session Config); it scans docs/*.md (root level) and docs/examples/*.md for filesystem-mtime staleness against the docs-staleness.thresholds.living threshold (default 90d) — docs/adr/ and docs/prd/ are deliberately excluded. ssot-code-diff.mjs is ungated (no Session Config key) — it always runs when CLAUDE.md or README.md is present, diffing hardcoded doc "count" claims (e.g. "(13 rules)") against the live code/filesystem value they describe. Both probes return {findings, metrics, duration_ms}. See probes-docs.md for invocation details and severity escalation.skills/discovery/probes-feature.md): intent-drift + stubbed-dead-feature + feature-request-cluster probes. The first two MUST carry file_path:line_number anchors that survive the Phase 4.2 re-read (±3 lines); feature-request-cluster instead anchors on a VCS issue-ID set and MUST carry verification_method: vcs-issue — see Phase 4.2's dual verification path below.Each agent receives:
probes-intro.md (confidence scoring reference) AND the category-specific probes-<category>.md file for this agent's category (include the actual grep commands/patterns in the prompt)since_ref was provided and changedFiles is non-empty: the changedFiles array (informational context for per-probe filtering — per-probe filtering enforcement is deferred to W3)FINDING:
probe: <probe_name>
category: <category>
severity: <critical|high|medium|low>
file_path: <absolute path>
line_number: <number>
matched_text: <exact text from tool output>
title: <short title for the finding>
description: <1-2 sentence description>
recommended_fix: <concrete fix suggestion>
"If a probe's activation condition is not met, skip it with: SKIPPED: <probe_name> -- " "If a probe command fails, skip it with: FAILED: <probe_name> -- " "Do NOT fabricate findings. Only report what tool output confirms."
CRITICAL: run_in_background: false for all agents.
Skip categories with no activated probes (don't dispatch empty agents).
After all probe agents complete:
Collect all FINDING: blocks from agent outputs into a unified findings list.
For EACH finding, use the verification path matching how the finding is anchored:
Default path — file-anchored findings (no verification_method field, or verification_method: file-line):
file_path:line_number using the Read toolmatched_text appears at or near that line (+/-3 lines tolerance)VCS-issue-anchored findings (verification_method: vcs-issue) — e.g. feature-request-cluster, whose findings anchor on a set of issue IDs rather than a file location:
For each issue ID in the finding's Location set, verify it via the VCS CLI — syntax reference: skills/gitlab-ops/SKILL.md § "Common CLI Commands" (glab issue view <IID> / gh issue view <NUMBER>); do not duplicate the CLI syntax here
Confirm the issue exists and is still open (state != closed)
If an issue ID no longer resolves or was closed since detection, drop it from the Location set; if EVERY issue in the set is gone/closed, discard the finding entirely with note "false positive -- all referenced issues closed/removed since detection"
Report: "Verification: N confirmed, M discarded as false positives"
For each verified finding, assign a confidence score (0-100) based on three factors:
| Factor | Low (+0) | Medium (+10) | High (+20) |
|---|---|---|---|
| Pattern specificity | Generic match (URL, TODO) | Moderate (orphaned annotation, magic number) | Specific (API key regex, eval(), SQL injection) |
| File context | Test fixture, example, seed data, docs | Utility, config, scripts | Production source, API handler, middleware |
| Historical signal | Previously dismissed as false positive | No prior data (first occurrence) | Recurring issue (confirmed in learnings.jsonl) |
Scoring rules:
critical get a minimum confidence of 70 — they are NEVER auto-deferredThreshold: Read discovery-confidence-threshold from Session Config (default: 60). If not configured, use 60.
Annotate each finding with its confidence score for Phase 5 presentation.
Two findings are duplicates if:
file_path ANDKeep the higher severity finding. Merge descriptions.
discovery-severity-threshold from Session Config.discovery-confidence-threshold (default: 60). Log filtered-out findings: "Auto-dismissed N low-confidence findings (below threshold [T]). Use discovery-confidence-threshold: 0 to see all."Group remaining findings by category for Phase 5 presentation.
If in embedded mode (called from session-end): STOP HERE. Return structured findings to the caller using this schema:
Embedded mode return schema:
{
"findings": [
{"probe": "string", "category": "string", "severity": "critical|high|medium|low", "confidence": 0-100, "file": "string", "line": number, "description": "string", "recommendation": "string"}
],
"stats": {
"probes_run": number,
"findings_raw": number,
"findings_verified": number,
"false_positives": number,
"user_dismissed": 0,
"issues_created": 0,
"by_category": {"<category>": {"findings": number, "actioned": 0}}
}
}
Present both as structured data in your final output. Do not proceed to Phase 5.
Loads persistent triage state, partitions findings into auto-deferred/high-confidence buckets, and walks the user through Critical/High findings individually and Medium/Low findings in a batch before Phase 6 issue creation.
See references/discovery-interactive-triage.md.
Read WHEN: running in standalone mode (not embedded mode — see Phase 4.6 Embedded Mode Exit above), after Phase 4 scoring completes.
When a standalone run is lead-guided or headless (detection, duties, owner classes and the decision-line format: ../_shared/lead-guided-mode.md), nobody answers, so no AskUserQuestion is raised and the run never ends waiting. The decision the triage would ask for is taken, recorded and carried on:
Grounded scan (the recommended option). The judgment-topics fork does not arise.Create issue (<severity>); each Medium/Low category gets Accept all (its recommended option); the batch confirmation gets Create all. Auto-deferred findings stay deferred. Triage state is written as in an interactive run.issue-budget: (report the remainder). When the issue tracker is public (a public GitHub/GitLab project), no issue is filed at all: the whole batch is parked as one aussenwirkung owner question and the findings stay in the Final Report.### Autonome Entscheidungen; each created issue body ends with its own decision line, so the owner can find and close autonomously filed issues in bulk.VCS Reference: Detect the VCS platform per the "VCS Auto-Detection" section of the gitlab-ops skill. Use CLI commands per the "Common CLI Commands" section.
For each approved finding:
issue-templates.mdtype:discovery + priority::<level> + area:<inferred from category/filepath> + status:readyglab issue create --title "[Discovery] <title>" --label "type:discovery,priority::<level>,area:<area>,status:ready" --description "<body>"gh issue create --title "[Discovery] <title>" --label "type:discovery,priority::<level>,area:<area>,status:ready" --body "<body>"When the active scope included feature AND at least one verified feature finding was approved into an issue, insert an Opportunity Solution Tree (OST) section between ### Created Issues and ### Dismissed Findings (shown below). This section is feature-scope-only — every other category keeps the flat ### Created Issues table as its sole findings view, unchanged.
## Discovery Report
### Summary
- Probes run: [N] across [categories]
- Raw findings: [N]
- Verified: [N] (false positives discarded: [M])
- User approved: [N]
- Issues created: [N]
### Created Issues
| # | Title | Priority | Area | Probe |
|---|-------|----------|------|-------|
| <IID> | <title> | <priority> | <area> | <probe> |
### Opportunity Solution Tree (feature scope only)
> Present ONLY when the active scope included `feature` and at least one verified feature finding was approved. Group the approved feature findings under a Teresa Torres OST hierarchy: **outcome** (the user/business result the product is steering toward) -> **opportunity** (the observed gap or unmet need the finding surfaces) -> **solution** (the finding itself — the created issue). Infer outcome/opportunity from the finding's probe + description; never fabricate a hierarchy level with no evidentiary basis — when the outcome is genuinely unclear, write "Outcome: (unclassified)" rather than guessing.
Example:
Outcome: Reduce time-to-first-value for new users
Opportunity: Onboarding drops users before they reach the "aha" moment (intent-drift: docs claim auto-provisioning, code path is manual)
Solution: #182 -- Implement auto-provisioning of default workspace
Opportunity: Users repeatedly request the same missing capability without a tracked epic
Solution: #191, #204, #211 -- feature-request-cluster: "CSV export" cluster (3 issues, no epic)
### Dismissed Findings
- [N] dismissed as intentional
- [M] dismissed as false positive
### Recommendations
- [suggestions based on finding patterns]
discovery-severity-threshold -- filter before presenting to usernode_modules/, .git/, dist/, build/, .next/, .nuxt/, coverage/This phase runs only in standalone mode. Embedded mode returns findings to the caller.
After Phase 6 (Issue Creation) completes, prepare discovery statistics for session metrics:
Count totals from the triage results:
probes_run: number of probes that were activated and executedfindings_raw: total findings before verificationfindings_verified: findings that passed Phase 4.2 verificationfalse_positives: findings discarded during verificationuser_dismissed: findings the user declined during Phase 5 triageissues_created: issues created in Phase 6by_category: per-category breakdown of findings and actioned itemsReport stats summary:
Discovery stats: [probes_run] probes, [findings_raw] raw → [findings_verified] verified ([false_positives] false positives). User dismissed [user_dismissed]. Created [issues_created] issues.
These stats are available for session-end to include in sessions.jsonl under the discovery_stats field. The discovery skill does NOT write to sessions.jsonl directly — session-end handles that.
The JSONL schema (.orchestrator/metrics/discovery-triage.jsonl), fingerprint derivation, state enum (open/dismissed/accepted-as-known/reopened), re-run semantics, and the scripts/lib/discovery/triage-state.mjs module API that Phase 5 above reads and writes.
See references/discovery-triage-state.md.
Read WHEN: implementing or debugging Phase 5 triage persistence, or investigating why a finding was suppressed/re-shown across runs.
code scope, don't scan infrastructuresessions.jsonl directly — session-end handles metrics persistenceissue-templates.md (opens in a new tab)probes-arch.md (opens in a new tab)probes-audit.md (opens in a new tab)probes-code.md (opens in a new tab)probes-docs.md (opens in a new tab)probes-feature.md (opens in a new tab)probes-infra.md (opens in a new tab)probes-intro.md (opens in a new tab)probes-session.md (opens in a new tab)probes-supply-chain.md (opens in a new tab)probes-ui.md (opens in a new tab)probes-vault.md (opens in a new tab)probes/docs-staleness.mjs (opens in a new tab)probes/frontend-slop.mjs (opens in a new tab)probes/insecure-infra-defaults.mjs (opens in a new tab)probes/ssot-code-diff.mjs (opens in a new tab)probes/supply-chain-slopcheck.mjs (opens in a new tab)probes/vault-narrative-staleness.mjs (opens in a new tab)probes/vault-staleness.mjs (opens in a new tab)references/discovery-interactive-triage.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
sonnetnpx claudepluginhub kanevry/session-orchestrator --plugin session-orchestrator55 skills in this plugin
/architectureUse when the user asks to improve architecture, find refactoring opportunities, surface deepening opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable. Surfaces shallow modules and hypothetical seams using a precise vocabulary (Module / Interface / Implementation / Depth / Seam / Adapter / Leverage / Locality from LANGUAGE.md)./autopilotUse this skill when running an autonomous session-orchestration loop. Chains session-start → session-plan → wave-executor → session-end for N iterations with all 10 kill-switches (SPIRAL, FAILED wave, carryover > 50%, max-hours, max-sessions, resource-overload, token-budget, stall-timeout, sub-threshold confidence, user-abort). Reads Mode-Selector output (Phase B) to decide auto-execute vs. fallback. Writes one autopilot.jsonl record per loop run. Phase C scaffold (issue #277); implementation lives in scripts/lib/autopilot.mjs (Phase C-1 follow-up).
/backlogUse when a repository's issue backlog needs refinement so agents can start work without asking back. Measures the tracker with scripts/backlog-refine.mjs (labels, readiness of status:ready issues, size, dependencies, epics, closed-issue hygiene), then proposes splits, epics, merges, fills and closings for approval and applies them through gitlab-ops. Triggered by /backlog [repo], "refine the backlog", "is the backlog ready for agents", "Backlog aufräumen". Not for finding code defects (use discovery), not for cross-repo dashboards (use portfolio), and not for creating issues from scratch./bootstrapUse this skill when scaffolding the minimum repository structure required by session-orchestrator. Invoked automatically by the Bootstrap Gate when CLAUDE.md, Session Config, or bootstrap.lock is missing. Also available as /bootstrap for manual invocation. Three intensity tiers: fast (demos/spikes), standard (MVPs), deep (production/team).
/brainstormUse when you have a feature idea but the scope or UX is still ambiguous — runs a lightweight Socratic design dialogue (3-5 AUQ rounds) and writes a spec markdown file. Use BEFORE /plan feature when product intent needs validation; skip to /plan feature when scope is already clear. HARD-GATE prevents any code work until the design is user-approved./claude-md-drift-checkUse when detecting drift between CLAUDE.md (or AGENTS.md, the Codex CLI alias) / _meta narrative and live repository state. Ten checks: absolute-path resolution, 01-projects/ count claims, issue-reference freshness, session-file existence, command-count sync, session-config-parity (mandatory template keys = error, opt-in gaps = note, unknown local keys = warning), vault-dir-parity (CLAUDE.md vs AGENTS.md), generated-rule-staleness (WARN-only), rule-scoping (paths:/globs: frontmatter defects, dangling rule citations, zero-match globs), and docs-parity (docs/components.md count-claims vs on-disk counts, template-vs-reference config-key parity, stale .claude/metrics/ paths). Full per-check spec in the body table. Invoked as an opt-in session-end phase; mirrors vault-sync's lean JSON+exit-code contract.
Other plugins' skills for the same job