initial import: @mikefreno/omp-pygenium (omp port)
This commit is contained in:
256
src/agent-runner.ts
Normal file
256
src/agent-runner.ts
Normal file
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* agent-runner.ts — spawn isolated sub-agents for analysis and fix phases.
|
||||
*
|
||||
* The production runner uses pi's `createAgentSession` SDK to spin up a fresh
|
||||
* in-memory agent session scoped to the target `cwd`, with the agent
|
||||
* definition's system prompt and tool allowlist applied. Because that path
|
||||
* needs live model credentials (unsuitable for CI), the runner is backed by an
|
||||
* injectable factory: tests swap it for a deterministic fake that executes a
|
||||
* tiny instruction protocol embedded in the task string.
|
||||
*
|
||||
* Instruction protocol (used by the fake runner, harmless to the real one):
|
||||
* task lines may begin with `!write <path> <text>` — the fake writes the file
|
||||
* and reports it as a finding. Real sub-agents receive the whole task verbatim.
|
||||
*
|
||||
* @module pygienium/agent-runner
|
||||
*/
|
||||
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, isAbsolute, join } from "node:path";
|
||||
import type { AgentSessionEvent } from "@oh-my-pi/pi-coding-agent";
|
||||
import { loadAgents, extensionRoot, type AgentDef } from "./agents.js";
|
||||
|
||||
export interface AgentTaskOptions {
|
||||
/** Absolute working directory for the sub-agent. */
|
||||
cwd: string;
|
||||
/** Agent name to look up in `agents/*.md`. */
|
||||
agentName: string;
|
||||
/** The task prompt handed to the sub-agent. */
|
||||
task: string;
|
||||
/** Optional tool allowlist override (else uses the agent's `allowedTools`). */
|
||||
allowedTools?: string[];
|
||||
/** Optional explicit agent definition (skips `loadAgents`). */
|
||||
agent?: AgentDef;
|
||||
/**
|
||||
* Live callback forwarding raw {@link AgentSessionEvent}s from the
|
||||
* sub-agent session. The `pygienium-stream` forwarder in `index.ts`
|
||||
* turns tool_execution_start/end + assistant turns into chat messages.
|
||||
*/
|
||||
onEvent?: (event: AgentSessionEvent) => void;
|
||||
}
|
||||
|
||||
export interface AgentRunResult {
|
||||
/** Whether the sub-agent completed without throwing. */
|
||||
ok: boolean;
|
||||
/** The final assistant text emitted by the sub-agent. */
|
||||
text: string;
|
||||
/** Error message when `ok` is false. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type AgentRunner = (opts: AgentTaskOptions) => Promise<AgentRunResult>;
|
||||
|
||||
/** Module-level runner (defaults to the SDK-backed runner; tests override it). */
|
||||
let currentRunner: AgentRunner = defaultAgentRunner;
|
||||
|
||||
/** Entry point used by the check-runner. */
|
||||
export function runAgentTask(opts: AgentTaskOptions): Promise<AgentRunResult> {
|
||||
return currentRunner(opts);
|
||||
}
|
||||
|
||||
/** Override the active agent runner (primarily for tests). */
|
||||
export function setAgentRunner(runner: AgentRunner): void {
|
||||
currentRunner = runner;
|
||||
}
|
||||
|
||||
/** Restore the default SDK-backed agent runner. */
|
||||
export function resetAgentRunner(): void {
|
||||
currentRunner = defaultAgentRunner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Real sub-agent runner: spins up an in-memory `AgentSession` scoped to `cwd`,
|
||||
* overrides the system prompt with the agent definition's body, restricts tools
|
||||
* to the agent's allowlist, and runs the task to completion.
|
||||
*/
|
||||
export async function defaultAgentRunner(
|
||||
opts: AgentTaskOptions,
|
||||
): Promise<AgentRunResult> {
|
||||
const agents = await loadAgents({ cwd: opts.cwd });
|
||||
const agent = opts.agent ?? agents.get(opts.agentName);
|
||||
if (!agent) {
|
||||
const names = [...agents.keys()];
|
||||
return {
|
||||
ok: false,
|
||||
text: "",
|
||||
error:
|
||||
`Unknown agent definition: "${opts.agentName}". ` +
|
||||
`Available agents: ${names.length > 0 ? names.join(", ") : "(none loaded — check agents/ directories exist)"}. ` +
|
||||
`Searched ${extensionRoot()}/agents/ (extension) and ${opts.cwd}/agents/ (project-local). ` +
|
||||
`Add agents/${opts.agentName}.md to either location.`,
|
||||
};
|
||||
}
|
||||
|
||||
// Lazily import the SDK so the rest of the module graph (and tests using the
|
||||
// fake runner) never resolve the heavy pi-coding-agent package. The specifier
|
||||
// is static by intent (dynamic-import exception: module is intentionally
|
||||
// excluded from the import-time graph to keep fake-runner tests SDK-free).
|
||||
const { createAgentSession, AgentRegistry, SessionManager } = await import(
|
||||
"@oh-my-pi/pi-coding-agent"
|
||||
);
|
||||
|
||||
const tools = opts.allowedTools ??
|
||||
agent.allowedTools ?? ["read", "bash", "grep", "glob"];
|
||||
|
||||
const { session } = await createAgentSession({
|
||||
cwd: opts.cwd,
|
||||
toolNames: tools,
|
||||
// `tools` is an allowlist, not a request list.
|
||||
restrictToolNames: true,
|
||||
sessionManager: SessionManager.inMemory(opts.cwd),
|
||||
// Replace the fully rendered default prompt with the agent body.
|
||||
systemPrompt: agent.systemPrompt,
|
||||
// Keep the sub-agent isolated: no nested extensions/skills/prompts/etc.
|
||||
disableExtensionDiscovery: true,
|
||||
skills: [],
|
||||
promptTemplates: [],
|
||||
rules: [],
|
||||
contextFiles: [],
|
||||
enableMCP: false,
|
||||
enableLsp: false,
|
||||
// Private registry: the host session owns the process-global "Main"
|
||||
// identity, so a per-run registry keeps these in-process workers
|
||||
// disjoint from the main agent.
|
||||
agentRegistry: new AgentRegistry(),
|
||||
});
|
||||
|
||||
try {
|
||||
let text = "";
|
||||
let stopReason: string | undefined;
|
||||
let errorMessage: string | undefined;
|
||||
const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
|
||||
if (
|
||||
event.type === "message_update" &&
|
||||
event.assistantMessageEvent.type === "text_delta"
|
||||
) {
|
||||
text += event.assistantMessageEvent.delta;
|
||||
}
|
||||
if (event.type === "message_end") {
|
||||
// Capture the full assistant text from the finalized message —
|
||||
// models that don't stream text_delta (or truncate) still surface
|
||||
// their output here. Prefer the streamed text when non-empty.
|
||||
const message = event.message as {
|
||||
role?: string;
|
||||
content?: unknown;
|
||||
stopReason?: string;
|
||||
errorMessage?: string;
|
||||
};
|
||||
if (message.stopReason) stopReason = message.stopReason;
|
||||
if (message.errorMessage) errorMessage = message.errorMessage;
|
||||
if (message.role === "assistant") {
|
||||
const full = extractAssistantText(message.content).trim();
|
||||
if (full && !text.trim()) text = full;
|
||||
}
|
||||
}
|
||||
// Forward the stream-driving events to the chat forwarder; it turns
|
||||
// each into its own `pygienium-stream` message (see index.ts).
|
||||
if (
|
||||
event.type === "tool_execution_start" ||
|
||||
event.type === "tool_execution_end" ||
|
||||
event.type === "message_end"
|
||||
) {
|
||||
opts.onEvent?.(event);
|
||||
}
|
||||
});
|
||||
await session.prompt(opts.task, { expandPromptTemplates: false });
|
||||
// Ensure the agent has fully settled (tool calls may still be in-flight
|
||||
// after prompt() resolves; piolium's runner calls this for the same
|
||||
// reason).
|
||||
await session.agent.waitForIdle();
|
||||
unsubscribe();
|
||||
// Surface session errors that didn't throw but left no useful output.
|
||||
// A session ending with stopReason "error" and no text means the model
|
||||
// call failed silently — treat that as a failed run, not ok:true.
|
||||
if (errorMessage) {
|
||||
return { ok: false, text, error: errorMessage };
|
||||
}
|
||||
if (!text.trim() && stopReason === "error") {
|
||||
return {
|
||||
ok: false,
|
||||
text,
|
||||
error: "sub-agent session ended in error with no output.",
|
||||
};
|
||||
}
|
||||
return { ok: true, text };
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
text: "",
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
};
|
||||
} finally {
|
||||
try {
|
||||
session.dispose();
|
||||
} catch {
|
||||
/* ignore dispose errors */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract joined text from an assistant message's content blocks.
|
||||
* Mirrors piolium's `extractAssistantText`.
|
||||
*/
|
||||
function extractAssistantText(content: unknown): string {
|
||||
if (typeof content === "string") return content;
|
||||
if (!Array.isArray(content)) return "";
|
||||
return content
|
||||
.flatMap((c) =>
|
||||
c && typeof c === "object" && (c as { type?: string }).type === "text"
|
||||
? [(c as { text?: string }).text ?? ""]
|
||||
: [],
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fake agent runner for tests: it understands a tiny instruction protocol
|
||||
* embedded in the task so a no-op check can produce deterministic findings
|
||||
* and write marker files without a model. Recognised instructions (one per
|
||||
* line, leading-whitespace tolerant):
|
||||
*
|
||||
* !write <path> <text...> — write text to path (relative to cwd); recorded
|
||||
* !echo <text...> — appended to findings
|
||||
*
|
||||
* The agent's emitted findings text is the collected `!echo`/`!write` lines.
|
||||
*/
|
||||
export const fakeAgentRunner: AgentRunner = async (opts) => {
|
||||
const lines = opts.task.split(/\r?\n/);
|
||||
const findings: string[] = [];
|
||||
try {
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
const write = /^!write\s+(\S+)\s*(.*)$/.exec(trimmed);
|
||||
if (write) {
|
||||
const rel = write[1] as string;
|
||||
const content = (write[2] ?? "").replace(/^["']|["']$/g, "");
|
||||
const full = isAbsolute(rel) ? rel : join(opts.cwd, rel);
|
||||
await mkdir(dirname(full), { recursive: true });
|
||||
await writeFile(full, content + "\n", "utf8");
|
||||
findings.push(`wrote ${rel}`);
|
||||
continue;
|
||||
}
|
||||
const echo = /^!echo\s+(.*)$/.exec(trimmed);
|
||||
if (echo) {
|
||||
findings.push((echo[1] ?? "").replace(/^["']|["']$/g, ""));
|
||||
}
|
||||
}
|
||||
return { ok: true, text: findings.join("\n") };
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
text: findings.join("\n"),
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
};
|
||||
}
|
||||
};
|
||||
193
src/agents.ts
Normal file
193
src/agents.ts
Normal file
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* agents.ts — markdown agent-definition loader.
|
||||
*
|
||||
* Reads agent definitions from `agents/*.md` shipped with the extension so the
|
||||
* analysis and fix roles are plain editable markdown — no TypeScript changes
|
||||
* needed to tune a sub-agent's behaviour. Each `.md` file uses a YAML
|
||||
* frontmatter block to declare its `name` and `allowedTools`; the body becomes
|
||||
* the agent's system prompt.
|
||||
*
|
||||
* File shape:
|
||||
*
|
||||
* ---
|
||||
* name: scanner
|
||||
* allowedTools:
|
||||
* - read
|
||||
* - grep
|
||||
* - glob
|
||||
* ---
|
||||
* You are a code-hygiene scanner …
|
||||
*
|
||||
* @module pygienium/agents
|
||||
*/
|
||||
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/** A loaded agent definition. */
|
||||
export interface AgentDef {
|
||||
/** Unique agent name (matches `agentName` on a `CheckDefinition`). */
|
||||
name: string;
|
||||
/** The markdown body, used verbatim as the sub-agent system prompt. */
|
||||
systemPrompt: string;
|
||||
/** Tool names the sub-agent may use (`read`, `bash`, …), or undefined to inherit defaults. */
|
||||
allowedTools?: string[];
|
||||
/** Absolute path to the source `.md` file. */
|
||||
sourcePath: string;
|
||||
}
|
||||
|
||||
/** Resolve the extension root (the directory holding `package.json` and `agents/`). */
|
||||
export function extensionRoot(): string {
|
||||
// src/agents.ts → ../ = extension root.
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
return resolve(here, "..");
|
||||
}
|
||||
|
||||
/** Parse a YAML-ish frontmatter block from markdown. Only the keys we use. */
|
||||
function parseFrontmatter(raw: string): {
|
||||
frontmatter: Record<string, unknown>;
|
||||
body: string;
|
||||
} {
|
||||
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/.exec(raw);
|
||||
if (!match) return { frontmatter: {}, body: raw };
|
||||
const fmText = match[1] ?? "";
|
||||
const body = match[2] ?? "";
|
||||
const frontmatter: Record<string, unknown> = {};
|
||||
const lines = fmText.split(/\r?\n/);
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i] ?? "";
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith("#")) continue;
|
||||
|
||||
// YAML block-list: a key with an empty value followed by "- item" lines.
|
||||
const blockList = /^([A-Za-z_][A-Za-z0-9_-]*):\s*$/.exec(trimmed);
|
||||
if (blockList) {
|
||||
const key = blockList[1] as string;
|
||||
const items: string[] = [];
|
||||
let j = i + 1;
|
||||
for (; j < lines.length; j++) {
|
||||
const item = /^\s+-\s+(.*)$/.exec(lines[j] ?? "");
|
||||
if (!item) break;
|
||||
items.push((item[1] ?? "").trim().replace(/^["']|["']$/g, ""));
|
||||
}
|
||||
if (items.length > 0) {
|
||||
frontmatter[key] = items;
|
||||
i = j - 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Inline key/value (also handles inline lists like key: [a, b]).
|
||||
const idx = trimmed.indexOf(":");
|
||||
if (idx === -1) continue;
|
||||
const key = trimmed.slice(0, idx).trim();
|
||||
const value = trimmed.slice(idx + 1).trim();
|
||||
if (value.startsWith("[") && value.endsWith("]")) {
|
||||
const inner = value.slice(1, -1);
|
||||
const valueList: string[] = [];
|
||||
for (const part of inner.split(",")) {
|
||||
const v = part.trim().replace(/^["']|["']$/g, "");
|
||||
if (v) valueList.push(v);
|
||||
}
|
||||
frontmatter[key] = valueList;
|
||||
} else {
|
||||
frontmatter[key] = value.replace(/^["']|["']$/g, "");
|
||||
}
|
||||
}
|
||||
return { frontmatter, body: body.trim() + "\n" };
|
||||
}
|
||||
|
||||
function asStringList(value: unknown): string[] | undefined {
|
||||
if (value == null) return undefined;
|
||||
if (Array.isArray(value)) return value.map((v) => String(v)).filter(Boolean);
|
||||
if (typeof value === "string") {
|
||||
return value
|
||||
.split(",")
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
if (value == null) return undefined;
|
||||
if (typeof value === "string") return value;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load agent definitions: the extension's `agents/*.md` baseline, plus any
|
||||
* repo-local `agents/*.md` at `<cwd>/agents/` (when `cwd` is given). Repo
|
||||
* agents override the extension's by name, so a project can tune a sub-agent's
|
||||
* prompt or tool allowlist without editing the extension. Missing dirs are
|
||||
* skipped silently; a dir with entries that all fail to parse logs each
|
||||
* failure and continues.
|
||||
*/
|
||||
export async function loadAgents(opts?: {
|
||||
cwd?: string;
|
||||
}): Promise<Map<string, AgentDef>> {
|
||||
const extRoot = extensionRoot();
|
||||
const result = new Map<string, AgentDef>();
|
||||
|
||||
// Extension-shipped agents are the baseline.
|
||||
await scanAgentDir(join(extRoot, "agents"), result);
|
||||
|
||||
// Repo-local overrides, applied last so they win on name collisions.
|
||||
if (opts?.cwd) {
|
||||
await scanAgentDir(join(opts.cwd, "agents"), result, true);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load every `agents/*.md` in `dir` into `result` (later dirs win on name
|
||||
* collisions). `repoDir` suppresses the missing-dir warning: `<cwd>/agents/`
|
||||
* legitimately doesn't exist in most scanned projects.
|
||||
*/
|
||||
async function scanAgentDir(
|
||||
dir: string,
|
||||
result: Map<string, AgentDef>,
|
||||
repoDir = false,
|
||||
): Promise<void> {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await readdir(dir);
|
||||
} catch (err) {
|
||||
if (!repoDir) {
|
||||
console.error(
|
||||
`[pygienium] agent loading: could not read agents dir at ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.endsWith(".md")) continue;
|
||||
const sourcePath = join(dir, entry);
|
||||
try {
|
||||
const raw = await readFile(sourcePath, "utf8");
|
||||
const { frontmatter, body } = parseFrontmatter(raw);
|
||||
const name = asString(frontmatter.name) ?? entry.slice(0, -".md".length);
|
||||
const allowedTools = asStringList(frontmatter.allowedTools);
|
||||
result.set(name, {
|
||||
name,
|
||||
systemPrompt: body,
|
||||
allowedTools,
|
||||
sourcePath,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[pygienium] agent loading: failed to load ${entry} from ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
// Continue loading other agents even if one fails.
|
||||
}
|
||||
}
|
||||
|
||||
if (!repoDir && result.size === 0 && entries.length > 0) {
|
||||
console.error(
|
||||
`[pygienium] agent loading: found ${entries.length} entries in ${dir} but loaded 0 agents`,
|
||||
);
|
||||
}
|
||||
}
|
||||
0
src/checks/.gitkeep
Normal file
0
src/checks/.gitkeep
Normal file
233
src/checks/comments.ts
Normal file
233
src/checks/comments.ts
Normal file
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* checks/comments.ts — comments hygiene check (first end-to-end reference).
|
||||
*
|
||||
* This is the canonical `CheckDefinition` that future checks (08+) copy. It
|
||||
* reuses the generic `scanner`/`fixer` agents shipped in `agents/*.md`; the
|
||||
* check-specific rubric is embedded in the task text handed to the sub-agent
|
||||
* (see {@link buildCommentsScanTask} / {@link buildCommentsFixTask}) so no
|
||||
* per-check agent `.md` file is required.
|
||||
*
|
||||
* Rubric (the user's spec — short + high value):
|
||||
* - comments that restate the code they sit on ("what" comments) → REMOVE
|
||||
* - verbose narration / long-winded explanations → TIGHTEN (shorten)
|
||||
* - "why" comments that explain intent, rationale, or gotchas → KEEP
|
||||
* - code self-explanatory with no comment → no comment needed (don't add one)
|
||||
*
|
||||
* Artifacts (under `<cwd>/.pygienium/checks/comments/`):
|
||||
* - `findings.md` — per-file line refs for each smell
|
||||
* - `changes.md` — summary of edits + human-review items
|
||||
*
|
||||
* @module pygienium/checks/comments
|
||||
*/
|
||||
|
||||
import type { CheckDefinition, CheckScope } from "./registry.js";
|
||||
import { scopeRulesMarkdown } from "./scope.js";
|
||||
|
||||
/** Phase-strip phase this check belongs to. */
|
||||
export const COMMENTS_PHASE_ID = "C1";
|
||||
|
||||
/**
|
||||
* Directory where this check writes its `findings.md` and `changes.md`
|
||||
* artifacts: `<cwd>/.pygienium/checks/comments/`. Based on `scope.cwd` (the
|
||||
* project root, always a directory) so the path is valid whether the scan
|
||||
* target is a single file or a directory. Matches the spec's
|
||||
* `.pygienium/checks/comments/findings.md` relative-path notation.
|
||||
*/
|
||||
export function commentsArtifactDir(scope: CheckScope): string {
|
||||
const base = scope.cwd.replace(/\/+$/, "");
|
||||
return `${base}/.pygienium/checks/comments`;
|
||||
}
|
||||
|
||||
/** Absolute path to the findings artifact for this check. */
|
||||
export function findingsPath(scope: CheckScope): string {
|
||||
return `${commentsArtifactDir(scope)}/findings.md`;
|
||||
}
|
||||
|
||||
/** Absolute path to the changes artifact for this check. */
|
||||
export function changesPath(scope: CheckScope): string {
|
||||
return `${commentsArtifactDir(scope)}/changes.md`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared rubric block, injected into both scan and fix task text so the analysis
|
||||
* and remediation sub-agents apply identical judgement.
|
||||
*/
|
||||
const RUBRIC = `# Comments hygiene rubric
|
||||
|
||||
Short + high value is the goal. Evaluate every comment in the target:
|
||||
|
||||
- **RESTATE → REMOVE.** A comment that paraphrases the line(s) it sits on adds
|
||||
no information. Examples: \`// increment i\` over \`i++\`, \`// return the
|
||||
result\` over \`return result\`. Delete it.
|
||||
- **VERBOSE → TIGHTEN.** A comment that is high-value but needlessly long.
|
||||
Rewrite it to one tight sentence preserving the key insight. Do not delete.
|
||||
- **"WHY" → KEEP.** A comment explaining intent, rationale, a non-obvious
|
||||
decision, a workaround, a gotcha, or a constraint the code cannot express.
|
||||
Leave it untouched (tighten only if it is also verbose).
|
||||
- **NO COMMENT NEEDED.** When the code is self-explanatory, do not add a comment.
|
||||
- Keep inline section headers/dividers that aid navigation only if they mark a
|
||||
real boundary; remove pure decoration.`;
|
||||
|
||||
/**
|
||||
* Build the analysis sub-agent task. Instructs the agent to read candidate
|
||||
* source files, identify comment smells per the rubric, and write per-file line
|
||||
* references to `.pygienium/comments/findings.md`.
|
||||
*/
|
||||
export function buildCommentsScanTask(_cwd: string, scope: CheckScope): string {
|
||||
const outDir = commentsArtifactDir(scope);
|
||||
const findingsFile = findingsPath(scope);
|
||||
return `# Task: comments hygiene scan
|
||||
|
||||
You are running the **comments** hygiene check.
|
||||
|
||||
## Target
|
||||
- Scan target: \`${scope.target}\`
|
||||
|
||||
${scopeRulesMarkdown()}
|
||||
## What to do
|
||||
1. Read the recon snapshot at \`${scope.cwd}/.pygienium/recon.json\` if it
|
||||
exists; otherwise enumerate source files directly under the target.
|
||||
2. For each source file, read it and locate every comment (inline \`//\`,
|
||||
block \`/* */\`, doc \`/** */\`, \`#\` for scripting languages, etc.).
|
||||
3. Apply the rubric below to each comment and classify it: RESTATE, VERBOSE,
|
||||
WHY, or OK.
|
||||
4. Write a findings report to \`${findingsFile}\` with per-file line refs.
|
||||
5. Return the findings report text as your final message (same content as the
|
||||
file). The host captures it as the analysis-phase findings.
|
||||
|
||||
${RUBRIC}
|
||||
|
||||
## findings.md format
|
||||
|
||||
\`\`\`markdown
|
||||
# comments — findings
|
||||
|
||||
<count> comment smell(s) across <files> file(s).
|
||||
|
||||
## <relative-file>
|
||||
- L<line>: <smell: RESTATE|VERBOSE> — <quote or paraphrase>
|
||||
- L<line>: KEEP (why) — <one-line reason> # listed for transparency
|
||||
\`\`\`
|
||||
|
||||
If no smells are found, write \`# comments — findings\n\n0 comment smell(s).\`
|
||||
and return that text. Always create findings.md so the run has an artifact.
|
||||
|
||||
Write the report under \`${outDir}\` (create directories as needed).
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the fix sub-agent task from the scan findings. Instructs the agent to
|
||||
* apply safe removals/tightenings, leave "why" comments, and write a summary
|
||||
* of edits plus anything needing human review to `.pygienium/comments/changes.md`.
|
||||
*/
|
||||
export function buildCommentsFixTask(
|
||||
_cwd: string,
|
||||
scope: CheckScope,
|
||||
findings: string,
|
||||
): string {
|
||||
const outDir = commentsArtifactDir(scope);
|
||||
const changesFile = changesPath(scope);
|
||||
return `# Task: comments hygiene fix
|
||||
|
||||
You are running the **comments** hygiene fix phase.
|
||||
|
||||
## Target
|
||||
- Fix target: \`${scope.target}\`
|
||||
|
||||
## Input: scan findings
|
||||
${findings.trim().length > 0 ? findings : "(no findings text provided)"}
|
||||
|
||||
## What to do
|
||||
1. For each RESTATE finding: remove the comment entirely.
|
||||
2. For each VERBOSE finding: replace the comment with a tightened one-sentence
|
||||
version that keeps the key insight.
|
||||
3. For every WHY comment: leave it untouched (tighten only if it is also
|
||||
verbose, preserving the rationale).
|
||||
4. Do not change any code logic, formatting, or ordering — only comments.
|
||||
5. Write a summary to \`${changesFile}\` and return it as your final message.
|
||||
|
||||
${RUBRIC}
|
||||
|
||||
## changes.md format
|
||||
|
||||
\`\`\`markdown
|
||||
# comments — changes
|
||||
|
||||
<applied> edit(s) applied; <deferred> deferred for human review.
|
||||
|
||||
## Applied
|
||||
- <relative-file>:<line> — <removed|tightened> comment (auto)
|
||||
|
||||
## Needs human review
|
||||
- <relative-file>:<line> — <reason> (manual)
|
||||
\`\`\`
|
||||
|
||||
If nothing needed changing, write
|
||||
\`# comments — changes\n\n0 edit(s) applied.\` and return that text. Always
|
||||
create changes.md so the run has an artifact. Write it under \`${outDir}\`.
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Precondition gate. Returns an error string when the comments check cannot
|
||||
* proceed (target path missing or not a real file/directory), else
|
||||
* `undefined`. Idempotent — passes identically before analysis and at verify.
|
||||
*/
|
||||
async function commentsGate(cwd: string): Promise<string | undefined> {
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const { resolve } = await import("node:path");
|
||||
const target = resolve(cwd);
|
||||
try {
|
||||
const s = await stat(target);
|
||||
if (s.isDirectory() || s.isFile()) return undefined;
|
||||
return `target is not a file or directory: ${target}`;
|
||||
} catch {
|
||||
return `target path does not exist: ${target}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify hook: confirms the check actually produced its artifacts. After the
|
||||
* scan phase `findings.md` must exist; after the fix phase `changes.md` must
|
||||
* exist too (the scan-phase-only run skips `changes.md` by design). Returns an
|
||||
* error string to fail verify, or `undefined` to pass. Replaces the historical
|
||||
* no-op verify (which only re-ran the existence gate) so the verify phase now
|
||||
* genuinely asserts the run produced its report.
|
||||
*/
|
||||
async function commentsVerify(scope: CheckScope): Promise<string | undefined> {
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const f = findingsPath(scope);
|
||||
try {
|
||||
await stat(f);
|
||||
} catch {
|
||||
return `comments verify: expected findings.md at ${f} after scan, none found.`;
|
||||
}
|
||||
if (scope.fix) {
|
||||
const c = changesPath(scope);
|
||||
try {
|
||||
await stat(c);
|
||||
} catch {
|
||||
return `comments verify: expected changes.md at ${c} after --fix, none found.`;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The comments hygiene check definition. */
|
||||
export const check = {
|
||||
name: "comments",
|
||||
label: "Comments",
|
||||
description:
|
||||
'Remove low-value/restating comments, tighten verbose ones, keep "why" comments.',
|
||||
agentName: "scanner",
|
||||
fixAgentName: "fixer",
|
||||
phaseId: COMMENTS_PHASE_ID,
|
||||
buildScanTask: buildCommentsScanTask,
|
||||
buildFixTask: buildCommentsFixTask,
|
||||
gate: commentsGate,
|
||||
verify: commentsVerify,
|
||||
} as const satisfies CheckDefinition;
|
||||
|
||||
// No self-registration here: `index.ts` auto-discovers every `checks/*.ts`
|
||||
// that exports `check` and registers it — a new check is still one file.
|
||||
317
src/checks/complexity.ts
Normal file
317
src/checks/complexity.ts
Normal file
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* checks/complexity.ts — excessive complexity check.
|
||||
*
|
||||
* Detects high cyclomatic complexity and structural complexity smells, then
|
||||
* refactors toward the simplest implementation that meets requirements.
|
||||
*
|
||||
* Cyclomatic complexity thresholds (MUST enforce, not advisory):
|
||||
* - 50+ → must refactor. No exceptions.
|
||||
* - 35–49 → heavy skepticism. Only keep if critical path + justified.
|
||||
* - <35 → not flagged on cyclomatic grounds (may still be flagged for other
|
||||
* structural smells).
|
||||
*
|
||||
* Structural smells detected:
|
||||
* - deep nesting (>3 levels)
|
||||
* - speculative abstractions
|
||||
* - premature config indirection
|
||||
* - non-idiomatic patterns
|
||||
* - over-engineered generics
|
||||
* - unnecessary wrappers
|
||||
*
|
||||
* @module pygienium/checks/complexity
|
||||
*/
|
||||
|
||||
import type { CheckDefinition, CheckScope } from "./registry.js";
|
||||
import { scopeRulesMarkdown } from "./scope.js";
|
||||
|
||||
/** Phase-strip phase this check belongs to. */
|
||||
export const COMPLEXITY_PHASE_ID = "C4";
|
||||
|
||||
/**
|
||||
* Artifact directory: `<cwd>/.pygienium/checks/complexity/`.
|
||||
*/
|
||||
export function complexityArtifactDir(scope: CheckScope): string {
|
||||
const base = scope.cwd.replace(/\/+$/, "");
|
||||
return `${base}/.pygienium/checks/complexity`;
|
||||
}
|
||||
|
||||
/** Absolute path to findings artifact. */
|
||||
export function findingsPath(scope: CheckScope): string {
|
||||
return `${complexityArtifactDir(scope)}/findings.md`;
|
||||
}
|
||||
|
||||
/** Absolute path to changes artifact. */
|
||||
export function changesPath(scope: CheckScope): string {
|
||||
return `${complexityArtifactDir(scope)}/changes.md`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared rubric for complexity analysis, injected into both scan and fix tasks.
|
||||
*/
|
||||
const RUBRIC = `# Complexity hygiene rubric
|
||||
|
||||
## Cyclomatic complexity thresholds
|
||||
|
||||
Cyclomatic complexity counts the number of independent paths through a function.
|
||||
Compute via language-native tools when available (lizard, radon, gocyclo), or
|
||||
count decision points (if/else if/for/while/case/&&/||/catch) per function.
|
||||
|
||||
| Score | Action |
|
||||
|-------|--------|
|
||||
| 50+ | **MUST refactor.** No exceptions. Break the function into smaller pieces. |
|
||||
| 35–49 | **Heavy skepticism.** Only keep if this is a massively critical point along the main path AND the complexity genuinely must be here. Document justification in findings.md; otherwise refactor. |
|
||||
| <35 | Not flagged on cyclomatic grounds (may still be flagged for other structural smells). |
|
||||
|
||||
## Structural complexity smells
|
||||
|
||||
- **Deep nesting (>3 levels).** Flatten with early returns, guard clauses, or extracting to named helpers.
|
||||
- **Speculative abstractions.** Remove abstractions created "just in case" — no concrete use case yet.
|
||||
- **Premature config indirection.** Remove configuration layers that add no value yet.
|
||||
- **Non-idiomatic patterns.** Replace with common conventions for the language.
|
||||
- **Over-engineered generics.** Simplify to concrete types when only one type is used.
|
||||
- **Unnecessary wrappers.** Inline trivial wrappers that add no logic.
|
||||
|
||||
## Refactoring principles
|
||||
|
||||
1. **Simplest implementation.** Choose the simplest implementation that fully meets current requirements.
|
||||
2. **No backward-compat baggage.** Remove obsolete paths rather than adding compatibility layers.
|
||||
3. **Grow in layers.** Build on a product that already works; don't trade a working product for unfinished complexity.
|
||||
4. **Use existing libraries.** Lean on well-maintained libraries when they reduce complexity or improve reliability.
|
||||
5. **Long-term decisions.** Make architectural decisions for the long term, not stopgaps meant to be replaced later.
|
||||
`;
|
||||
|
||||
/**
|
||||
* Build the analysis sub-agent task. Instructs the agent to:
|
||||
* 1. Compute cyclomatic complexity per function
|
||||
* 2. Identify structural complexity smells
|
||||
* 3. Write findings to .pygienium/checks/complexity/findings.md
|
||||
*/
|
||||
export function buildComplexityScanTask(
|
||||
_cwd: string,
|
||||
scope: CheckScope,
|
||||
): string {
|
||||
const findingsFile = findingsPath(scope);
|
||||
return `# Task: excessive complexity scan
|
||||
|
||||
You are running the **complexity** hygiene check.
|
||||
|
||||
## Target
|
||||
- Scan target: \`${scope.target}\`
|
||||
|
||||
${scopeRulesMarkdown()}
|
||||
## What to do
|
||||
|
||||
### 1. Compute cyclomatic complexity
|
||||
|
||||
For each source file in the target:
|
||||
|
||||
1. Read the recon snapshot at \`${scope.cwd}/.pygienium/recon.json\` if it
|
||||
exists; otherwise enumerate source files directly under the target.
|
||||
2. For each file, identify every function/method/class.
|
||||
3. Compute cyclomatic complexity:
|
||||
- Prefer language-native tools (lizard, radon, gocyclo, etc.) when available
|
||||
- Fall back to counting decision points: if/else if/for/while/case/&&/||/catch
|
||||
4. Classify each function into bands:
|
||||
- **50+** = MUST refactor (no exceptions)
|
||||
- **35–49** = heavy skepticism (must justify or refactor)
|
||||
- **<35** = not flagged on cyclomatic grounds
|
||||
|
||||
### 2. Identify structural complexity smells
|
||||
|
||||
For each file, identify:
|
||||
- Deep nesting (>3 levels)
|
||||
- Speculative abstractions
|
||||
- Premature config indirection
|
||||
- Non-idiomatic patterns
|
||||
- Over-engineered generics
|
||||
- Unnecessary wrappers
|
||||
|
||||
### 3. Write findings
|
||||
|
||||
Write a findings report to \`${findingsFile}\` with per-function scores and
|
||||
structural smell locations. Include a proposed simpler form for every flagged
|
||||
function.
|
||||
|
||||
${RUBRIC}
|
||||
|
||||
## findings.md format
|
||||
|
||||
\`\`\`markdown
|
||||
# complexity — findings
|
||||
|
||||
## Cyclomatic complexity
|
||||
|
||||
| File | Function | Score | Band | Action |
|
||||
|------|----------|-------|------|--------|
|
||||
| path/to/file:42 | myFunction | 65 | 50+ | MUST refactor |
|
||||
| path/to/file:100 | otherFunction | 42 | 35-49 | Skepticism — justify or refactor |
|
||||
| path/to/file:150 | simpleFunction | 8 | <35 | OK |
|
||||
|
||||
## Structural smells
|
||||
|
||||
- [severity] <file>:<line> — <smell type> — <description>
|
||||
- <proposed simplification>
|
||||
|
||||
## Justifications (35–49 band)
|
||||
|
||||
For each function kept at 35–49 complexity:
|
||||
- **Function:** <name> at <file>:<line>
|
||||
- **Score:** <score>
|
||||
- **Justification:** <why this is critical path and can't be simplified>
|
||||
\`\`\`
|
||||
|
||||
If no issues found, write:
|
||||
\`# complexity — findings\n\n0 complexity issues found.\`
|
||||
|
||||
Always create findings.md so the run has an artifact.
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the fix sub-agent task from the scan findings. Instructs the agent to:
|
||||
* 1. Split 50+ complexity functions
|
||||
* 2. Refactor or justify 35–49 functions
|
||||
* 3. Apply safe refactors for structural smells
|
||||
* 4. Write changes summary to .pygienium/checks/complexity/changes.md
|
||||
*/
|
||||
export function buildComplexityFixTask(
|
||||
_cwd: string,
|
||||
scope: CheckScope,
|
||||
findings: string,
|
||||
): string {
|
||||
const outDir = complexityArtifactDir(scope);
|
||||
const changesFile = changesPath(scope);
|
||||
return `# Task: excessive complexity fix
|
||||
|
||||
You are running the **complexity** hygiene fix phase.
|
||||
|
||||
## Target
|
||||
- Fix target: \`${scope.target}\`
|
||||
|
||||
## Input: scan findings
|
||||
${findings.trim().length > 0 ? findings : "(no findings text provided)"}
|
||||
|
||||
## What to do
|
||||
|
||||
### 1. Handle 50+ functions (MUST refactor)
|
||||
|
||||
For each function with cyclomatic complexity ≥ 50:
|
||||
- Split into smaller, focused functions
|
||||
- Extract complex conditional branches into named helper functions
|
||||
- Use early returns and guard clauses to reduce nesting
|
||||
- Preserve behavior after refactoring
|
||||
|
||||
### 2. Handle 35–49 functions
|
||||
|
||||
For each function in the 35–49 band:
|
||||
- If no justified critical-path reason exists, refactor
|
||||
- If kept, ensure justification is documented in findings.md
|
||||
- Prefer refactoring over keeping
|
||||
|
||||
### 3. Apply structural refactors
|
||||
|
||||
- Flatten deep nesting (>3 levels)
|
||||
- Remove speculative abstractions
|
||||
- Inline trivial wrappers
|
||||
- Replace non-idiomatic patterns with conventional ones
|
||||
- Simplify over-engineered generics to concrete types
|
||||
|
||||
### 4. Write changes summary
|
||||
|
||||
Write a summary to \`${changesFile}\` and return it as your final message.
|
||||
|
||||
${RUBRIC}
|
||||
|
||||
## changes.md format
|
||||
|
||||
\`\`\`markdown
|
||||
# complexity — changes
|
||||
|
||||
<applied> refactoring(s) applied; <deferred> deferred for human review.
|
||||
|
||||
## Applied
|
||||
|
||||
- <file>:<line> — <function> split (was <score>, now <scores>)
|
||||
- <file>:<line> — nested conditionals flattened
|
||||
- <file>:<line> — trivial wrapper inlined
|
||||
- <file>:<line> — speculative abstraction removed
|
||||
|
||||
## Deferred (needs human review)
|
||||
|
||||
- <file>:<line> — <function> — <reason> (manual)
|
||||
|
||||
## Justified (kept at 35–49)
|
||||
|
||||
- <file>:<line> — <function> (<score>) — <justification>
|
||||
\`\`\`
|
||||
|
||||
If nothing needed changing, write:
|
||||
\`# complexity — changes\n\n0 refactoring(s) applied.\`
|
||||
|
||||
Always create changes.md so the run has an artifact. Write it under \`${outDir}\`.
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Precondition gate. Returns an error string when the complexity check cannot
|
||||
* proceed (target path missing or not a real file/directory), else
|
||||
* `undefined`.
|
||||
*/
|
||||
async function complexityGate(cwd: string): Promise<string | undefined> {
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const { resolve } = await import("node:path");
|
||||
const target = resolve(cwd);
|
||||
try {
|
||||
const s = await stat(target);
|
||||
if (s.isDirectory() || s.isFile()) return undefined;
|
||||
return `target is not a file or directory: ${target}`;
|
||||
} catch {
|
||||
return `target path does not exist: ${target}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify hook: confirms the check actually produced its artifacts. After the
|
||||
* scan phase `findings.md` must exist; after the fix phase `changes.md` must
|
||||
* exist too. Without this, a sub-agent that returns empty/ok without writing
|
||||
* its report would be stamped `complete` — a false positive. Mirrors
|
||||
* {@link commentsVerify} / {@link todosVerify}.
|
||||
*/
|
||||
async function complexityVerify(
|
||||
scope: CheckScope,
|
||||
): Promise<string | undefined> {
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const f = findingsPath(scope);
|
||||
try {
|
||||
await stat(f);
|
||||
} catch {
|
||||
return `complexity verify: expected findings.md at ${f} after scan, none found.`;
|
||||
}
|
||||
if (scope.fix) {
|
||||
const c = changesPath(scope);
|
||||
try {
|
||||
await stat(c);
|
||||
} catch {
|
||||
return `complexity verify: expected changes.md at ${c} after --fix, none found.`;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The excessive complexity check definition. */
|
||||
export const check = {
|
||||
name: "complexity",
|
||||
label: "Complexity",
|
||||
description:
|
||||
"Detect and refactor excessive complexity: high cyclomatic complexity (50+ must refactor, 35-49 needs justification), deep nesting, and speculative abstractions.",
|
||||
agentName: "scanner",
|
||||
fixAgentName: "fixer",
|
||||
phaseId: COMPLEXITY_PHASE_ID,
|
||||
buildScanTask: buildComplexityScanTask,
|
||||
buildFixTask: buildComplexityFixTask,
|
||||
gate: complexityGate,
|
||||
verify: complexityVerify,
|
||||
} as const satisfies CheckDefinition;
|
||||
|
||||
// No self-registration here: `index.ts` auto-discovers every `checks/*.ts`
|
||||
// that exports `check` and registers it — a new check is still one file.
|
||||
1144
src/checks/dead-code.ts
Normal file
1144
src/checks/dead-code.ts
Normal file
File diff suppressed because it is too large
Load Diff
185
src/checks/deep-modules.ts
Normal file
185
src/checks/deep-modules.ts
Normal file
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* checks/deep-modules.ts — "deep modules, not shallow ones" check.
|
||||
*
|
||||
* Detects modules with shallow abstractions (thin pass-throughs, one-line
|
||||
* re-export barrels, trivial getter classes, unnecessary adapter layers) and
|
||||
* recommends/applies consolidation. The rubric encodes John Ousterhout's
|
||||
* "deep modules" definition from *A Philosophy of Software Design*: a module
|
||||
* is valuable when it hides a substantial implementation behind a small
|
||||
* interface; a shallow one exposes as much complexity as it hides, so its
|
||||
* indirection adds cost without abstraction payoff.
|
||||
*
|
||||
* Lifecycle:
|
||||
* gate (need source files) → recon (shared) → scan sub-agent writes
|
||||
* `<cwd>/.pygienium/checks/deep-modules/findings.md` → [with --fix] fix
|
||||
* sub-agent writes `changes.md`, inlines safe pass-throughs, and lists
|
||||
* risky consolidations (external importers / public API) for human review.
|
||||
*
|
||||
* Registering this file is the ONLY wiring needed: `index.ts` auto-discovers
|
||||
* `src/checks/*.ts`, so dropping this file exposes `/pygienium-deep-modules`.
|
||||
*
|
||||
* @module pygienium/checks/deep-modules
|
||||
*/
|
||||
|
||||
import { readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { CheckDefinition, CheckScope } from "./registry.js";
|
||||
import { isScopeSource, scopeRulesMarkdown } from "./scope.js";
|
||||
|
||||
/** Output directory for this check's persistent reports. */
|
||||
export function deepModulesOutputDir(cwd: string): string {
|
||||
return join(cwd, ".pygienium", "checks", "deep-modules");
|
||||
}
|
||||
|
||||
/** `findings.md` path for this check. */
|
||||
export function findingsPath(cwd: string): string {
|
||||
return join(deepModulesOutputDir(cwd), "findings.md");
|
||||
}
|
||||
|
||||
/** `changes.md` path for this check. */
|
||||
export function changesPath(cwd: string): string {
|
||||
return join(deepModulesOutputDir(cwd), "changes.md");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate: skip when the cwd has no inspectable source files at all. A workspace
|
||||
* with zero source files gives the scanner nothing to classify.
|
||||
*/
|
||||
function deepModulesGate(cwd: string): string | undefined {
|
||||
let found = false;
|
||||
try {
|
||||
const entries = readdirSync(cwd);
|
||||
for (const entry of entries) {
|
||||
if (isScopeSource(entry)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// unreadable cwd → let the agent decide; don't block.
|
||||
return undefined;
|
||||
}
|
||||
if (!found) {
|
||||
return "no source files found to inspect";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify hook: confirms the check actually produced its artifacts (mirrors
|
||||
* {@link commentsVerify} / {@link todosVerify}). After scan `findings.md` must
|
||||
* exist; after `--fix` `changes.md` must exist too. Catches a sub-agent that
|
||||
* returns ok with no output — which would otherwise be a false `complete`.
|
||||
*/
|
||||
async function deepModulesVerify(
|
||||
scope: CheckScope,
|
||||
): Promise<string | undefined> {
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const f = findingsPath(scope.cwd);
|
||||
try {
|
||||
await stat(f);
|
||||
} catch {
|
||||
return `deep-modules verify: expected findings.md at ${f} after scan, none found.`;
|
||||
}
|
||||
if (scope.fix) {
|
||||
const c = changesPath(scope.cwd);
|
||||
try {
|
||||
await stat(c);
|
||||
} catch {
|
||||
return `deep-modules verify: expected changes.md at ${c} after --fix, none found.`;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the scan task. The deep-modules scanner agent inspects the target,
|
||||
* classifies modules by abstraction depth against the rubric, and writes a
|
||||
* structured findings report to `findings.md`. The output path is passed into
|
||||
* the task so both the real agent (which uses its `write` tool) and the
|
||||
* deterministic fake runner (which understands `!write <path> <text>`) persist
|
||||
* the report to the same location.
|
||||
*
|
||||
* Note: the `!write`/`!echo` lines are the deterministic fallback the fake
|
||||
* runner executes for tests/smoke runs; a real model-driven agent receives the
|
||||
* whole prompt and writes a real analysis.
|
||||
*/
|
||||
function buildDeepScanTask(cwd: string, scope: CheckScope): string {
|
||||
const findings = findingsPath(cwd);
|
||||
const target = scope.target;
|
||||
// The expected findings document shape, shown to a real model-driven agent
|
||||
// as the format spec. The `!write`/`!echo` lines below are the deterministic
|
||||
// fallback the fake runner executes for tests/smoke runs.
|
||||
return [
|
||||
`Inspect the target "${target}" (cwd: ${cwd}) for shallow modules.`,
|
||||
`Classify every source module by abstraction depth (see your rubric).`,
|
||||
`Write your full findings report to: ${findings}.`,
|
||||
`findings.md must list each flagged module with: kind, evidence, importer`,
|
||||
`count, recommendation, and risk (low if no external importers, high else).`,
|
||||
`Then emit a one-line summary referencing the findings path.`,
|
||||
"",
|
||||
scopeRulesMarkdown(),
|
||||
"",
|
||||
`# Deterministic fallback (executed by the fake runner in tests):`,
|
||||
`!write ${findings} # Deep-modules findings | summary: 1 shallow module(s) flagged | ## 1. ${target}/wrapper.ts | kind: pass-through-wrapper | evidence: forwards every argument to a single library call with no added logic | importers: 0 | recommendation: inline-and-remove | risk: low`,
|
||||
`!echo deep-modules: 1 issue — see ${findings}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the fix task. The fixer consumes the scan findings and applies ONLY safe
|
||||
* consolidations: inline-and-remove pass-through wrappers that have **zero**
|
||||
* external importers. Risky consolidations (any importer, or unclear
|
||||
* ownership) are listed in `changes.md` as `review-manual` and NOT applied.
|
||||
* Every action — applied or deferred — is recorded in `changes.md`.
|
||||
*/
|
||||
function buildDeepFixTask(
|
||||
cwd: string,
|
||||
scope: CheckScope,
|
||||
findings: string,
|
||||
): string {
|
||||
const changes = changesPath(cwd);
|
||||
const findingsFile = findingsPath(cwd);
|
||||
const target = scope.target;
|
||||
return [
|
||||
`Consolidate shallow modules found in the scan.`,
|
||||
`cwd: ${cwd} target: ${target}`,
|
||||
`Findings report (also persisted at ${findingsFile}):`,
|
||||
`---`,
|
||||
findings,
|
||||
`---`,
|
||||
``,
|
||||
`Rules:`,
|
||||
`- Apply ONLY safe consolidations: a pass-through wrapper with zero external`,
|
||||
` importers may be inlined at its single use site and the wrapper removed.`,
|
||||
`- NEVER auto-delete or rewrite a module with any external importer — list it`,
|
||||
` for human review instead.`,
|
||||
`- Preserve public API boundaries; when in doubt, defer to manual review.`,
|
||||
`- Write changes.md to ${changes} describing every action (auto | manual) with`,
|
||||
` the file, the finding, and the disposition.`,
|
||||
``,
|
||||
`# Deterministic consolidation (executed by the fake runner in tests):`,
|
||||
`# Safe: zero-importer pass-through rewritten/removed (auto).`,
|
||||
`# Risky: external-importer adapter left in place (manual).`,
|
||||
`!write ${target}/wrapper.ts // Consolidated by pygienium-deep-modules: pass-through wrapper removed; callers now use the underlying implementation directly.`,
|
||||
`!write ${changes} # Deep-modules changes | 1. ${target}/wrapper.ts — pass-through-wrapper — consolidated: inlined the underlying call at the use site and removed the wrapper module (auto) | 2. ${target}/risky-adapter.ts — adapter-layer — 2 external importer(s): left in place; listed for review (manual)`,
|
||||
`!echo deep-modules: 1 auto-applied, 1 deferred to review — see ${changes}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** The check definition; registers itself on import. */
|
||||
export const check: CheckDefinition = {
|
||||
name: "deep-modules",
|
||||
label: "Deep modules",
|
||||
description:
|
||||
"Detect shallow modules (pass-throughs, trivial wrappers, re-export barrels) and consolidate the safe ones.",
|
||||
agentName: "deep-modules",
|
||||
phaseId: "analysis",
|
||||
buildScanTask: buildDeepScanTask,
|
||||
buildFixTask: buildDeepFixTask,
|
||||
gate: deepModulesGate,
|
||||
verify: deepModulesVerify,
|
||||
};
|
||||
|
||||
// No self-registration here: `index.ts` auto-discovers every `checks/*.ts`
|
||||
// that exports `check` and registers it.
|
||||
215
src/checks/defensive-guards.ts
Normal file
215
src/checks/defensive-guards.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* checks/defensive-guards.ts — "redundant defensive guarding" check.
|
||||
*
|
||||
* Detects defensive code that guards invariants the type system or an
|
||||
* upstream validation already guarantees, and removes the redundant guards
|
||||
* while preserving guards that protect genuine external boundaries (user
|
||||
* input, IO, parsing, untrusted data). The rubric encodes the engineering rule:
|
||||
* no compatibility layers or fallbacks meant to be "replaced later" — remove
|
||||
* them outright rather than layering over them.
|
||||
*
|
||||
* Flagged smells (non-exhaustive):
|
||||
* - redundant-null-check — null/undefined check on a value whose declared
|
||||
* type is already non-nullable.
|
||||
* - swallowing-try-catch — try/catch that silently discards the error
|
||||
* (empty catch, catch that only logs, or catch returning a fallback that
|
||||
* hides the failure).
|
||||
* - rethrow-only-try-catch — try/catch whose body only rethrows the exact
|
||||
* error, adding nothing.
|
||||
* - error-masking-fallback — `return defaultValue` / `|| fallback` in a
|
||||
* catch that masks a real failure with a plausible-but-wrong value.
|
||||
* - defensive-guard-on-validated-input — re-checking input that a caller or
|
||||
* parser already validated (e.g. asserting a parsed enum is in range).
|
||||
* - compatibility-fallback — a fallback branch kept "for now" / "to be
|
||||
* replaced later" (engineering rule: remove, don't layer).
|
||||
*
|
||||
* Kept (legitimate boundary guards):
|
||||
* - untrusted input (HTTP params, CLI args, env vars, files on disk).
|
||||
* - IO (network, filesystem, subprocess) where failures are expected.
|
||||
* - parsing (`JSON.parse`, `parseInt`, `Date.parse`, schema decoders).
|
||||
*
|
||||
* Lifecycle:
|
||||
* gate (need source files) → recon (shared) → scan sub-agent writes
|
||||
* `<cwd>/.pygienium/checks/defensive-guards/findings.md` separating redundant
|
||||
* guards from boundary guards → [with --fix] fix sub-agent removes redundant
|
||||
* guards, preserves boundary guards, and writes `changes.md` distinguishing
|
||||
* removed vs kept-with-reason.
|
||||
*
|
||||
* Registering this file is the ONLY wiring needed: `index.ts` auto-discovers
|
||||
* `src/checks/*.ts`, so dropping this file exposes `/pygienium-defensive-guards`.
|
||||
*
|
||||
* @module pygienium/checks/defensive-guards
|
||||
*/
|
||||
|
||||
import { readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { CheckDefinition, CheckScope } from "./registry.js";
|
||||
import { isScopeSource, scopeRulesMarkdown } from "./scope.js";
|
||||
|
||||
/** Output directory for this check's persistent reports. */
|
||||
export function defensiveGuardsOutputDir(cwd: string): string {
|
||||
return join(cwd, ".pygienium", "checks", "defensive-guards");
|
||||
}
|
||||
|
||||
/** `findings.md` path for this check. */
|
||||
export function findingsPath(cwd: string): string {
|
||||
return join(defensiveGuardsOutputDir(cwd), "findings.md");
|
||||
}
|
||||
|
||||
/** `changes.md` path for this check. */
|
||||
export function changesPath(cwd: string): string {
|
||||
return join(defensiveGuardsOutputDir(cwd), "changes.md");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate: skip when the cwd has no inspectable source files at all — a workspace
|
||||
* with zero source files gives the scanner nothing to analyse.
|
||||
*/
|
||||
function defensiveGuardsGate(cwd: string): string | undefined {
|
||||
let found = false;
|
||||
try {
|
||||
const entries = readdirSync(cwd);
|
||||
for (const entry of entries) {
|
||||
if (isScopeSource(entry)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// unreadable cwd → let the agent decide; don't block.
|
||||
return undefined;
|
||||
}
|
||||
if (!found) {
|
||||
return "no source files found to inspect";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify hook: confirms the check actually produced its artifacts (mirrors
|
||||
* {@link commentsVerify} / {@link todosVerify}). After scan `findings.md` must
|
||||
* exist; after `--fix` `changes.md` must exist too. Catches a sub-agent that
|
||||
* returns ok with no output — which would otherwise be a false `complete`.
|
||||
*/
|
||||
async function defensiveGuardsVerify(
|
||||
scope: CheckScope,
|
||||
): Promise<string | undefined> {
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const f = findingsPath(scope.cwd);
|
||||
try {
|
||||
await stat(f);
|
||||
} catch {
|
||||
return `defensive-guards verify: expected findings.md at ${f} after scan, none found.`;
|
||||
}
|
||||
if (scope.fix) {
|
||||
const c = changesPath(scope.cwd);
|
||||
try {
|
||||
await stat(c);
|
||||
} catch {
|
||||
return `defensive-guards verify: expected changes.md at ${c} after --fix, none found.`;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the scan task. The defensive-guards scanner agent inspects the target,
|
||||
* classifies each guard as redundant or a legitimate boundary guard against the
|
||||
* rubric, and writes a structured findings report to `findings.md`. The output
|
||||
* path is passed into the task so both the real agent (which uses its `write`
|
||||
* tool) and the deterministic fake runner (which understands `!write <path>
|
||||
* <text>`) persist the report to the same location.
|
||||
*
|
||||
* The `!write`/`!echo` lines are the deterministic fallback the fake runner
|
||||
* executes for tests/smoke runs; a real model-driven agent receives the whole
|
||||
* prompt and writes a real analysis.
|
||||
*/
|
||||
function buildDefensiveGuardsScanTask(cwd: string, scope: CheckScope): string {
|
||||
const findings = findingsPath(cwd);
|
||||
const target = scope.target;
|
||||
return [
|
||||
`Inspect the target "${target}" (cwd: ${cwd}) for redundant defensive guarding.`,
|
||||
`Classify every guard (null check, try/catch, fallback) against your rubric as`,
|
||||
`either REDUNDANT (remove) or BOUNDARY (keep). Boundary guards protect real`,
|
||||
`external boundaries: untrusted input, IO, and parsing. Redundant guards protect`,
|
||||
`invariants the type system or upstream validation already guarantees.`,
|
||||
`Write your full findings report to: ${findings}.`,
|
||||
`findings.md must separate redundant guards from legitimate boundary guards,`,
|
||||
`listing each with: kind, evidence, disposition (remove | keep-boundary), and`,
|
||||
`reason.`,
|
||||
`Then emit a one-line summary referencing the findings path.`,
|
||||
``,
|
||||
scopeRulesMarkdown(),
|
||||
``,
|
||||
`# Deterministic fallback (executed by the fake runner in tests):`,
|
||||
`!write ${findings} # Defensive-guards findings | summary: 2 redundant guard(s) flagged, 1 boundary guard kept | ## 1. ${target}/noise.ts:2 | kind: redundant-null-check | evidence: \`if (name === null)\` on \`name\` whose declared type is \`string\` (non-nullable) | disposition: remove | reason: type system already guarantees non-null | ## 2. ${target}/noise.ts:7 | kind: swallowing-try-catch | evidence: try/catch around doThing() discards the error silently (empty catch body) | disposition: remove | reason: masks bugs; no error mapping or recovery logic | ## 3. ${target}/boundary.ts:2 | kind: parsing-guard | evidence: try/catch around JSON.parse(input) | disposition: keep-boundary | reason: protects an external parsing boundary (JSON.parse of untrusted input)`,
|
||||
`!echo defensive-guards: 2 redundant, 1 boundary kept — see ${findings}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the fix task. The fixer consumes the scan findings and removes ONLY
|
||||
* redundant guards — those whose protected invariant is already guaranteed by
|
||||
* the type system or upstream validation. Boundary guards (IO, parsing,
|
||||
* untrusted input) are preserved untouched. Every action — removed or kept —
|
||||
* is recorded in `changes.md`, distinguishing removed (auto) from kept with a
|
||||
* reason (boundary).
|
||||
*
|
||||
* The fixer rewrites the affected source files with the redundant guards
|
||||
* excised; compatibility fallbacks are removed outright (engineering rule:
|
||||
* remove, don't layer), never left behind as a transitional shim.
|
||||
*/
|
||||
function buildDefensiveGuardsFixTask(
|
||||
cwd: string,
|
||||
scope: CheckScope,
|
||||
findings: string,
|
||||
): string {
|
||||
const changes = changesPath(cwd);
|
||||
const findingsFile = findingsPath(cwd);
|
||||
const target = scope.target;
|
||||
return [
|
||||
`Remove redundant defensive guards found in the scan.`,
|
||||
`cwd: ${cwd} target: ${target}`,
|
||||
`Findings report (also persisted at ${findingsFile}):`,
|
||||
`---`,
|
||||
findings,
|
||||
`---`,
|
||||
``,
|
||||
`Rules:`,
|
||||
`- Remove ONLY redundant guards: null/undefined checks on non-nullable types,`,
|
||||
` try/catch that only rethrows or swallows, fallback values that hide errors,`,
|
||||
` defensive guards on already-validated input, and compatibility fallbacks.`,
|
||||
`- PRESERVE boundary guards: anything protecting untrusted input, IO, or parsing`,
|
||||
` (e.g. JSON.parse, network, filesystem, subprocess errors). Do not touch them.`,
|
||||
`- No compatibility layers: remove fallbacks outright — never leave a shim meant`,
|
||||
` to be "replaced later".`,
|
||||
`- Apply the smallest diff that removes the guard without changing behaviour for`,
|
||||
` the happy path. Preserve tests and existing conventions.`,
|
||||
`- Write changes.md to ${changes} distinguishing removed (auto) from kept`,
|
||||
` (boundary — with reason) for every finding.`,
|
||||
``,
|
||||
`# Deterministic removal (executed by the fake runner in tests):`,
|
||||
`# Redundant null check + swallowing try/catch removed from noise.ts (auto).`,
|
||||
`# JSON.parse boundary guard in boundary.ts preserved (boundary).`,
|
||||
`!write ${target}/noise.ts // Cleaned by pygienium-defensive-guards: removed redundant null check on non-nullable \`name\` and the swallowing try/catch around doThing(). export function greet(name: string) { return \`hello \${name}\`; } export function swallow() { doThing(); } function doThing() {}`,
|
||||
`!write ${changes} # Defensive-guards changes | summary: 2 removed, 1 kept (boundary) | ## Removed (auto) | 1. ${target}/noise.ts:2 — redundant-null-check — removed \`if (name === null) return ""\`; type system guarantees non-null | 2. ${target}/noise.ts:7 — swallowing-try-catch — removed the try/catch around doThing(); the error is no longer silently swallowed | ## Kept (boundary — with reason) | 1. ${target}/boundary.ts:2 — parsing-guard — kept: try/catch around JSON.parse protects an external parsing boundary (untrusted input)`,
|
||||
`!echo defensive-guards: 2 removed, 1 kept (boundary) — see ${changes}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** The check definition; registers itself on import. */
|
||||
export const check: CheckDefinition = {
|
||||
name: "defensive-guards",
|
||||
label: "Defensive guards",
|
||||
description:
|
||||
"Remove redundant defensive guarding (null checks on non-nullable types, swallowing try/catch, masking fallbacks) while keeping boundary guards (IO, parsing, untrusted input).",
|
||||
agentName: "defensive-guards",
|
||||
phaseId: "analysis",
|
||||
buildScanTask: buildDefensiveGuardsScanTask,
|
||||
buildFixTask: buildDefensiveGuardsFixTask,
|
||||
gate: defensiveGuardsGate,
|
||||
verify: defensiveGuardsVerify,
|
||||
};
|
||||
|
||||
// No self-registration here: `index.ts` auto-discovers every `checks/*.ts`
|
||||
// that exports `check` and registers it.
|
||||
139
src/checks/registry.ts
Normal file
139
src/checks/registry.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* checks/registry.ts — pluggable check registry.
|
||||
*
|
||||
* A `CheckDefinition` describes one hygiene check (e.g. `comments`, `complexity`).
|
||||
* The registry is a module-level `Map` so that adding a check only requires a
|
||||
* new file in `src/checks/` plus one `registerCheck(def)` call — no changes to
|
||||
* `index.ts` command wiring. At startup, `index.ts` iterates the registry and
|
||||
* auto-registers a `/pygienium-<name>` command per definition.
|
||||
*
|
||||
* Lifecycle of a single check run (orchestrated by `src/modes/check-runner.ts`):
|
||||
* Q0 recon (shared) → analysis sub-agent (buildScanTask) →
|
||||
* fix sub-agent (buildFixTask, only with --fix) → verify gate → cleanup.
|
||||
*
|
||||
* @module pygienium/checks/registry
|
||||
*/
|
||||
|
||||
/**
|
||||
* Scope passed to scan/fix task builders. Resolved from the command args:
|
||||
* a positional path (absolute or relative to `cwd`) plus parsed flags.
|
||||
*/
|
||||
export interface CheckScope {
|
||||
/** Absolute working directory the check operates on. */
|
||||
cwd: string;
|
||||
/** Target path (absolute) the check scans; defaults to `cwd` when none given. */
|
||||
target: string;
|
||||
/** Whether fixes should be applied (the `--fix` flag). */
|
||||
fix: boolean;
|
||||
/** Remaining raw tokens after flag parsing, for check-specific use. */
|
||||
rest: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies preconditions before a check runs its analysis phase. Returns an
|
||||
* error string when the check cannot proceed (e.g. no source files match),
|
||||
* or `undefined` when the gate passes. Implemented per-check so generic
|
||||
* checks can bail early without spawning an agent.
|
||||
*/
|
||||
export type CheckGate = (
|
||||
cwd: string,
|
||||
) => Promise<string | undefined> | string | undefined;
|
||||
|
||||
/**
|
||||
* Optional post-analysis (+ optional fix) verify hook. Confirms the check
|
||||
* actually produced its artifacts (e.g. `findings.md`/`changes.md`). Returns an
|
||||
* error string to fail the verify phase, or `undefined` to pass. When omitted,
|
||||
* the verify phase falls back to re-running {@link CheckDefinition.gate},
|
||||
* preserving the historical behaviour for checks that have nothing to verify.
|
||||
*/
|
||||
export type CheckVerify = (
|
||||
scope: CheckScope,
|
||||
) => Promise<string | undefined> | string | undefined;
|
||||
|
||||
/**
|
||||
* The structured task string handed to a sub-agent. `buildScanTask` produces
|
||||
* the analysis prompt; `buildFixTask` consumes the findings text the scan
|
||||
* agent emitted and produces a fix prompt.
|
||||
*
|
||||
* Task builders may be async: a check can pre-compute deterministic candidates
|
||||
* (e.g. an import-graph scan) before assembling the prompt, so the sub-agent's
|
||||
* job is to verify/refine rather than re-derive everything from scratch.
|
||||
*/
|
||||
export type BuildScanTask = (
|
||||
cwd: string,
|
||||
scope: CheckScope,
|
||||
) => string | Promise<string>;
|
||||
export type BuildFixTask = (
|
||||
cwd: string,
|
||||
scope: CheckScope,
|
||||
findings: string,
|
||||
) => string | Promise<string>;
|
||||
|
||||
/**
|
||||
* Definition of a single pluggable hygiene check.
|
||||
*/
|
||||
export interface CheckDefinition {
|
||||
/** Lowercase kebab command suffix → `/pygienium-<name>`. Must be unique. */
|
||||
name: string;
|
||||
/** Human label shown in help and status strips. */
|
||||
label: string;
|
||||
/** One-line description for `/pygienium-help`. */
|
||||
description: string;
|
||||
/**
|
||||
* Name of the agent definition (from `agents/*.md`) used for the analysis
|
||||
* phase. The fix phase uses the `fixer` agent unless `fixAgentName`
|
||||
* overrides it.
|
||||
*/
|
||||
agentName: string;
|
||||
/** Optional override for the fix-phase agent (defaults to `fixer`). */
|
||||
fixAgentName?: string;
|
||||
/** Identifier of the phase-strip phase this check belongs to (task 05). */
|
||||
phaseId: string;
|
||||
/** Builds the analysis sub-agent task. */
|
||||
buildScanTask: BuildScanTask;
|
||||
/** Builds the fix sub-agent task from scan findings. */
|
||||
buildFixTask: BuildFixTask;
|
||||
/**
|
||||
* Precondition gate. Returning a string skips the check (recorded as
|
||||
* `skipped`); returning `undefined` proceeds normally.
|
||||
*/
|
||||
gate: CheckGate;
|
||||
/**
|
||||
* Optional verify hook confirming artifacts landed (see {@link CheckVerify}).
|
||||
* Falls back to re-running `gate` when omitted.
|
||||
*/
|
||||
verify?: CheckVerify;
|
||||
}
|
||||
|
||||
const registry = new Map<string, CheckDefinition>();
|
||||
|
||||
/**
|
||||
* Register a check. Throws on duplicate names so wiring mistakes surface
|
||||
* loudly at startup rather than silently shadowing a command.
|
||||
*/
|
||||
export function registerCheck(def: CheckDefinition): void {
|
||||
if (!def.name || !/^[a-z0-9][a-z0-9-]*$/.test(def.name)) {
|
||||
throw new Error(
|
||||
`Invalid check name "${def.name}": must be lowercase kebab (e.g. "comments").`,
|
||||
);
|
||||
}
|
||||
if (registry.has(def.name)) {
|
||||
throw new Error(`Duplicate pygienium check name: "${def.name}".`);
|
||||
}
|
||||
registry.set(def.name, def);
|
||||
}
|
||||
|
||||
/** Look up a registered check by name. */
|
||||
export function getCheck(name: string): CheckDefinition | undefined {
|
||||
return registry.get(name);
|
||||
}
|
||||
|
||||
/** All registered checks in insertion order. */
|
||||
export function getAllChecks(): CheckDefinition[] {
|
||||
return [...registry.values()];
|
||||
}
|
||||
|
||||
/** Test-only: reset the registry between tests. */
|
||||
export function clearChecks(): void {
|
||||
registry.clear();
|
||||
}
|
||||
145
src/checks/scope.ts
Normal file
145
src/checks/scope.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* scope.ts — canonical source-of-truth for what pygienium checks inspect.
|
||||
*
|
||||
* Every check (recon, dead-code, deep-modules, defensive-guards, complexity,
|
||||
* comments) and every scanner agent prompt shares these definitions so the
|
||||
* "only inspect implementation code" rule is stated once, not copy-pasted
|
||||
* across four files that drift apart.
|
||||
*
|
||||
* @module pygienium/checks/scope
|
||||
*/
|
||||
|
||||
/**
|
||||
* Implementation-code file extensions pygienium inspects.
|
||||
*
|
||||
* Deliberately excludes documentation (`.md`, `.txt`, `.rst`), config
|
||||
* (`.json`, `.yaml`, `.yml`, `.toml`, `.env`, `.ini`), type declarations
|
||||
* (`.d.ts`), styles (`.css`, `.scss`), markup (`.html`, `.svg`), and lock
|
||||
* files. These are not implementation code — a comments or complexity check
|
||||
* flagging prose in a `.md` or a key in `package.json` is noise.
|
||||
*/
|
||||
export const SCOPE_EXTENSIONS: ReadonlySet<string> = new Set([
|
||||
".ts",
|
||||
".tsx",
|
||||
".js",
|
||||
".jsx",
|
||||
".mjs",
|
||||
".cjs",
|
||||
".py",
|
||||
".rb",
|
||||
".go",
|
||||
".rs",
|
||||
".java",
|
||||
".kt",
|
||||
".swift",
|
||||
".php",
|
||||
".cs",
|
||||
".lua",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Directories pygienium never descends into — build output, dependency caches,
|
||||
* tooling state, and VCS metadata. When walking the tree with `glob`/`grep`/
|
||||
* `readdir`, skip these by name to avoid wasting tokens on vendored code and
|
||||
* generated artifacts the user can't act on.
|
||||
*/
|
||||
export const SCOPE_EXCLUDE_DIRS: ReadonlySet<string> = new Set([
|
||||
"node_modules",
|
||||
".git",
|
||||
".hg",
|
||||
".svn",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
"coverage",
|
||||
".next",
|
||||
".nuxt",
|
||||
".turbo",
|
||||
".svelte-kit",
|
||||
"__pycache__",
|
||||
".venv",
|
||||
"venv",
|
||||
"vendor",
|
||||
".cache",
|
||||
".pygienium",
|
||||
".ralpi",
|
||||
".idea",
|
||||
".vscode",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Compound extensions (checked after the simple extension lookup) that should
|
||||
* be treated as non-source even though their tail extension appears in
|
||||
* {@link SCOPE_EXTENSIONS}. The primary case: `.d.ts` type declarations are
|
||||
* generated contracts, not implementation code.
|
||||
*/
|
||||
export const SCOPE_EXCLUDE_SUFFIXES: ReadonlySet<string> = new Set([
|
||||
".d.ts",
|
||||
".d.mts",
|
||||
".d.cts",
|
||||
".min.js",
|
||||
".min.mjs",
|
||||
".min.cjs",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Test if a file path is implementation source pygienium should inspect.
|
||||
*
|
||||
* Returns `true` when the extension is in {@link SCOPE_EXTENSIONS} AND the
|
||||
* path does not end with a {@link SCOPE_EXCLUDE_SUFFIXES} pattern (e.g.
|
||||
* `.d.ts`).
|
||||
*/
|
||||
export function isScopeSource(path: string): boolean {
|
||||
const lower = path.toLowerCase();
|
||||
for (const suffix of SCOPE_EXCLUDE_SUFFIXES) {
|
||||
if (lower.endsWith(suffix)) return false;
|
||||
}
|
||||
const dot = lower.lastIndexOf(".");
|
||||
if (dot === -1) return false;
|
||||
return SCOPE_EXTENSIONS.has(lower.slice(dot));
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown section injected into every scan task string so the sub-agent knows
|
||||
* exactly what to inspect and what to skip — stated once here, not copy-pasted
|
||||
* into each task builder.
|
||||
*
|
||||
* Agents that use `glob`/`grep`/`readdir` for their own file discovery read
|
||||
* this before exploring, so the exclusion list governs their search too.
|
||||
*/
|
||||
export function scopeRulesMarkdown(): string {
|
||||
const extensions = [...SCOPE_EXTENSIONS]
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.join("`, `");
|
||||
const excludeDirs = [...SCOPE_EXCLUDE_DIRS]
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.join("`, `");
|
||||
return `## Scope of inspection
|
||||
|
||||
**Only inspect implementation source files.** Do not analyse documentation,
|
||||
config, type declarations, build output, or dependencies — flagging those is
|
||||
noise the user cannot act on.
|
||||
|
||||
### Inspect (extensions)
|
||||
\`${extensions}\`
|
||||
|
||||
### Skip (directory names — never descend into)
|
||||
\`${excludeDirs}\`
|
||||
|
||||
### Skip (file patterns)
|
||||
- Type declarations: \`*.d.ts\`, \`*.d.mts\`, \`*.d.cts\` — generated contracts, not impl
|
||||
- Minified bundles: \`*.min.js\`, \`*.min.mjs\`, \`*.min.cjs\` — generated, not editable
|
||||
- Docs: \`*.md\`, \`*.txt\`, \`*.rst\` — prose, not code
|
||||
- Config: \`*.json\`, \`*.yaml\`, \`*.yml\`, \`*.toml\`, \`*.ini\`, \`*.env\`
|
||||
- Styles/markup: \`*.css\`, \`*.scss\`, \`*.html\`, \`*.svg\`
|
||||
- Lock files: \`package-lock.json\`, \`*.lock\`, \`bun.lockb\`
|
||||
|
||||
### File discovery preference
|
||||
1. **Prefer the recon snapshot** at \`<cwd>/.pygienium/recon.json\` when it
|
||||
exists — it is the authoritative source inventory (git-tracked, extension-
|
||||
filtered, exclude-aware). Read its \`fileCounts\` for the quick picture.
|
||||
2. Otherwise enumerate files yourself, applying the rules above.
|
||||
3. When using \`glob\`/\`grep\`, add ignore patterns for the skip directories
|
||||
(e.g. exclude \`**/node_modules/**\` from your scans).
|
||||
`;
|
||||
}
|
||||
558
src/checks/todos.ts
Normal file
558
src/checks/todos.ts
Normal file
@@ -0,0 +1,558 @@
|
||||
/**
|
||||
* checks/todos.ts — "TODOs & stubs" check.
|
||||
*
|
||||
* Inventories unfinished work: TODO/FIXME/HACK markers and stub
|
||||
* implementations. The engineering rule encoded in the fix phase: pygienium
|
||||
* never *implements* a TODO and never deletes a marker — the fixer's only
|
||||
* action is to convert **silent stubs** (placeholder returns, empty bodies,
|
||||
* pass-only bodies) into loud failures, because a stub that silently returns
|
||||
* a plausible-but-wrong value ships the lie to every caller, while a stub
|
||||
* that throws is honest tracked debt.
|
||||
*
|
||||
* Classification (the scan agent applies judgment; a deterministic pre-scan
|
||||
* feeds it candidates):
|
||||
* - marker — `TODO` / `FIXME` / `HACK` / `XXX` / `@todo` in a comment.
|
||||
* - silent-stub — lone placeholder return / empty body / pass-only body;
|
||||
* the actionable, dangerous ones.
|
||||
* - loud-stub — explicit not-implemented failures (`throw new Error("Not
|
||||
* implemented")`, `todo!()`, `raise NotImplementedError`, `TODO("...")`);
|
||||
* already failing loudly → tracked debt, fixer never touches them.
|
||||
* - noise (dropped by the agent) — "TODO" inside a string literal, doc
|
||||
* examples, fixtures, abstract-method `NotImplementedError` (the correct
|
||||
* Python idiom), legit default returns (reducers, indexOf -1, catch
|
||||
* handlers returning null).
|
||||
*
|
||||
* Lifecycle:
|
||||
* gate (need source files) → recon (shared) → async scan task runs a
|
||||
* deterministic candidate pass over the scope tree, diffs the counts
|
||||
* against the previous run's findings (stored in run-state), hands the
|
||||
* candidates + delta to the `todos` agent, which verifies/drops noise and
|
||||
* writes `<cwd>/.pygienium/checks/todos/findings.md` → [with --fix] fixer
|
||||
* converts silent stubs to loud throws and writes `changes.md`.
|
||||
*
|
||||
* Registering this file is the ONLY wiring needed: `index.ts` auto-discovers
|
||||
* `src/checks/*.ts`, so dropping this file exposes `/pygienium-todos`.
|
||||
*
|
||||
* @module pygienium/checks/todos
|
||||
*/
|
||||
|
||||
import { readdirSync } from "node:fs";
|
||||
import { readFile, readdir, stat } from "node:fs/promises";
|
||||
import { join, relative } from "node:path";
|
||||
import { loadRunState } from "../run-state.js";
|
||||
import type { CheckDefinition, CheckScope } from "./registry.js";
|
||||
import {
|
||||
isScopeSource,
|
||||
SCOPE_EXCLUDE_DIRS,
|
||||
scopeRulesMarkdown,
|
||||
} from "./scope.js";
|
||||
|
||||
/** Output directory for this check's persistent reports. */
|
||||
export function todosOutputDir(cwd: string): string {
|
||||
return join(cwd, ".pygienium", "checks", "todos");
|
||||
}
|
||||
|
||||
/** `findings.md` path for this check. */
|
||||
export function findingsPath(cwd: string): string {
|
||||
return join(todosOutputDir(cwd), "findings.md");
|
||||
}
|
||||
|
||||
/** `changes.md` path for this check. */
|
||||
export function changesPath(cwd: string): string {
|
||||
return join(todosOutputDir(cwd), "changes.md");
|
||||
}
|
||||
|
||||
export type TodoKind = "marker" | "silent-stub" | "loud-stub";
|
||||
|
||||
/** One candidate line the deterministic pre-scan flagged. */
|
||||
export interface TodoCandidate {
|
||||
/** Absolute path of the file. */
|
||||
path: string;
|
||||
/** 1-based line number. */
|
||||
line: number;
|
||||
kind: TodoKind;
|
||||
/** Matched token (e.g. `TODO`, `Not implemented`, `empty-body`). */
|
||||
snippet: string;
|
||||
/** The trimmed line content. */
|
||||
code: string;
|
||||
/** Enclosing function name when one was seen, else the file path. */
|
||||
context: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marker tokens: an unfinished-work note in a comment. Case-insensitive;
|
||||
* `@todo\b` (not `@todos`) and `\bHACK\b` (not `hacking`).
|
||||
*/
|
||||
const MARKER_RE = /\b(?:TODO|FIXME|HACK)\b|\bXXX\b|@todo\b/i;
|
||||
|
||||
/**
|
||||
* Loud-stub tokens: explicit not-implemented failures. `not implemented`
|
||||
* covers `throw new Error("Not implemented")` and `panic!("not implemented")`;
|
||||
* the `NotImplementedError` branch also catches Python's `raise
|
||||
* NotImplementedError`, and the Rust/Kotlin idioms (`todo!()`, `TODO("...")`)
|
||||
* are matched explicitly.
|
||||
*/
|
||||
const LOUD_STUB_RE =
|
||||
/not\s+implemented|NotImplementedError|NotImplementedException|\btodo!\s*\(|unimplemented!\s*\(|\bTODO\s*\(/i;
|
||||
|
||||
/** A lone placeholder return (`return 0;` / `return "";` / `return null;` …). */
|
||||
const PLACEHOLDER_RETURN_RE =
|
||||
/^\s*return\s+(?:null|undefined|0(?:\.0)?|""|''|\[\]|\{\}|None|nil|false)\s*;?\s*(?:\/\/.*)?$/;
|
||||
|
||||
/** Function/arrow header lines worth inspecting for a stub body. */
|
||||
const FN_HEADER_RE =
|
||||
/\b(?:function|def|func|fun|fn)\s+\w+|(?:const|let|var)\s+\w+\s*=\s*(?:async\s*)?\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/;
|
||||
|
||||
/** Single-line placeholder body: `function x() { return 0; }`. */
|
||||
const SINGLE_PLACEHOLDER_BODY_RE =
|
||||
/\{\s*return\s+(?:null|undefined|0(?:\.0)?|""|''|\[\]|\{\}|None|nil|false)\s*;?\s*\}/;
|
||||
|
||||
/** Single-line arrow expression body: `const f = () => 0;`. */
|
||||
const ARROW_PLACEHOLDER_RE =
|
||||
/=>\s*(?:null|undefined|0(?:\.0)?|""|''|\[\]|\{\}|false)\s*;?\s*$/;
|
||||
|
||||
/** Empty single-line body: `function notify(): void {}`. */
|
||||
const EMPTY_BODY_RE = /\{\s*\}/;
|
||||
|
||||
/** Hard cap on candidates so a huge tree can't blow the task prompt. */
|
||||
const MAX_CANDIDATES = 500;
|
||||
/** Candidate sections are truncated at this many entries in the fallback. */
|
||||
const FALLBACK_CAP = 16;
|
||||
/** Candidate list embedded in the live prompt is truncated at this many. */
|
||||
const PROMPT_CAP = 40;
|
||||
|
||||
/** Extract the declared function name from a header line, when present. */
|
||||
function headerName(line: string): string | undefined {
|
||||
const decl =
|
||||
/(?:function|def|func|fun|fn|class)\s+([A-Za-z_$][\w$]*)/.exec(line) ??
|
||||
/(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/.exec(
|
||||
line,
|
||||
);
|
||||
return decl?.[1];
|
||||
}
|
||||
|
||||
/** Index of the next non-blank line at or after `start`, else `undefined`. */
|
||||
function nextNonBlank(lines: string[], start: number): number | undefined {
|
||||
for (let i = start; i < lines.length; i++) {
|
||||
if ((lines[i] as string).trim()) return i;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the target collecting implementation-source files, honouring
|
||||
* {@link SCOPE_EXCLUDE_DIRS} and {@link isScopeSource} (same rules as
|
||||
* dead-code's walker).
|
||||
*/
|
||||
async function walkScopeFiles(root: string): Promise<string[]> {
|
||||
const st = await stat(root).catch(() => undefined);
|
||||
if (!st) return [];
|
||||
if (st.isFile()) return isScopeSource(root) ? [root] : [];
|
||||
const out: string[] = [];
|
||||
const stack = [root];
|
||||
while (stack.length > 0) {
|
||||
const dir = stack.pop() as string;
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (SCOPE_EXCLUDE_DIRS.has(entry.name)) continue;
|
||||
stack.push(full);
|
||||
} else if (entry.isFile() && isScopeSource(entry.name)) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic pre-scan: flag marker/loud-stub/silent-stub candidates across
|
||||
* the target's scope tree. High recall by design — the scan agent verifies
|
||||
* each candidate and drops noise (in-string "TODO", doc examples, legit
|
||||
* default returns). Pure function of the tree: unit-testable without agents.
|
||||
*/
|
||||
export async function detectTodoStubs(
|
||||
target: string,
|
||||
): Promise<TodoCandidate[]> {
|
||||
const files = await walkScopeFiles(target);
|
||||
const out: TodoCandidate[] = [];
|
||||
for (const file of files) {
|
||||
const raw = await readFile(file, "utf8").catch(() => "");
|
||||
const lines = raw.split("\n");
|
||||
let lastFn = "";
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const code = lines[i] as string;
|
||||
const trimmed = code.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
const loud = LOUD_STUB_RE.exec(trimmed);
|
||||
if (loud) {
|
||||
out.push({
|
||||
path: file,
|
||||
line: i + 1,
|
||||
kind: "loud-stub",
|
||||
snippet: loud[0].slice(0, 40),
|
||||
code: trimmed,
|
||||
context: lastFn,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const marker = MARKER_RE.exec(trimmed);
|
||||
if (marker) {
|
||||
out.push({
|
||||
path: file,
|
||||
line: i + 1,
|
||||
kind: "marker",
|
||||
snippet: marker[0],
|
||||
code: trimmed,
|
||||
context: lastFn,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (FN_HEADER_RE.test(trimmed)) {
|
||||
const name = headerName(trimmed);
|
||||
if (name) lastFn = name;
|
||||
const ctx = name ?? lastFn;
|
||||
// Single-line stub forms.
|
||||
if (
|
||||
SINGLE_PLACEHOLDER_BODY_RE.test(trimmed) ||
|
||||
ARROW_PLACEHOLDER_RE.test(trimmed)
|
||||
) {
|
||||
out.push({
|
||||
path: file,
|
||||
line: i + 1,
|
||||
kind: "silent-stub",
|
||||
snippet: "placeholder-return",
|
||||
code: trimmed,
|
||||
context: ctx,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
EMPTY_BODY_RE.test(trimmed) &&
|
||||
!/\b(?:return|throw)\b/.test(trimmed)
|
||||
) {
|
||||
out.push({
|
||||
path: file,
|
||||
line: i + 1,
|
||||
kind: "silent-stub",
|
||||
snippet: "empty-body",
|
||||
code: trimmed,
|
||||
context: ctx,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// Multi-line forms: inspect the first non-blank body line.
|
||||
const bodyIdx = nextNonBlank(lines, i + 1);
|
||||
if (bodyIdx === undefined) continue;
|
||||
const body = (lines[bodyIdx] as string).trim();
|
||||
if (body === "}") {
|
||||
out.push({
|
||||
path: file,
|
||||
line: i + 1,
|
||||
kind: "silent-stub",
|
||||
snippet: "empty-body",
|
||||
code: trimmed,
|
||||
context: ctx,
|
||||
});
|
||||
} else if (body === "pass") {
|
||||
out.push({
|
||||
path: file,
|
||||
line: bodyIdx + 1,
|
||||
kind: "silent-stub",
|
||||
snippet: "pass-only",
|
||||
code: body,
|
||||
context: ctx,
|
||||
});
|
||||
} else if (PLACEHOLDER_RETURN_RE.test(body)) {
|
||||
// Lone placeholder return: the statement after it must be the
|
||||
// closing brace (a `try/catch { return null }` handler does not
|
||||
// match — its `return null` is followed by `}` inside `catch`).
|
||||
const after = nextNonBlank(lines, bodyIdx + 1);
|
||||
if (after !== undefined && (lines[after] as string).trim() === "}") {
|
||||
out.push({
|
||||
path: file,
|
||||
line: bodyIdx + 1,
|
||||
kind: "silent-stub",
|
||||
snippet: "placeholder-return",
|
||||
code: body,
|
||||
context: ctx,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (out.length >= MAX_CANDIDATES) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Counts by kind across a candidate list. */
|
||||
function countByKind(candidates: TodoCandidate[]): {
|
||||
silent: number;
|
||||
loud: number;
|
||||
marker: number;
|
||||
} {
|
||||
let silent = 0;
|
||||
let loud = 0;
|
||||
let marker = 0;
|
||||
for (const c of candidates) {
|
||||
if (c.kind === "silent-stub") silent++;
|
||||
else if (c.kind === "loud-stub") loud++;
|
||||
else marker++;
|
||||
}
|
||||
return { silent, loud, marker };
|
||||
}
|
||||
|
||||
/** Previous run's verified counts, parsed from run-state findings text. */
|
||||
const PRIOR_SUMMARY_RE =
|
||||
/todos:\s*(\d+)\s+silent\s+stub\(s\)?,\s*(\d+)\s+loud\s+stub\(s\)?,\s*(\d+)\s+marker\(s\)?/;
|
||||
|
||||
/**
|
||||
* Parse the previous run's per-kind counts out of run-state (the scan agent's
|
||||
* one-line summary is persisted there). `undefined` when there is no prior
|
||||
* run or the stored summary isn't parseable — the delta is then all-new.
|
||||
*/
|
||||
export async function todosPriorCounts(
|
||||
cwd: string,
|
||||
): Promise<{ silent: number; loud: number; marker: number } | undefined> {
|
||||
const state = await loadRunState(cwd).catch(() => undefined);
|
||||
const stored = state?.checks["todos"]?.findings;
|
||||
if (!stored) return undefined;
|
||||
const m = PRIOR_SUMMARY_RE.exec(stored);
|
||||
if (!m) return undefined;
|
||||
return {
|
||||
silent: Number(m[1]),
|
||||
loud: Number(m[2]),
|
||||
marker: Number(m[3]),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the deterministic report the fake runner writes (and the real agent
|
||||
* uses as a shape reference): one pipe-separated line, sections per kind.
|
||||
*/
|
||||
function renderFindings(
|
||||
cwd: string,
|
||||
candidates: TodoCandidate[],
|
||||
delta: { nw: number; resolved: number },
|
||||
): string {
|
||||
const { silent, loud, marker } = countByKind(candidates);
|
||||
const total = silent + loud + marker;
|
||||
const parts = [
|
||||
`# TODOs & stubs findings | summary: ${marker} marker(s), ${silent} silent stub(s), ${loud} loud stub(s) | new: ${delta.nw} | resolved: ${delta.resolved} | reviewed: ${candidates.length}`,
|
||||
];
|
||||
if (total === 0) {
|
||||
parts.push(
|
||||
"No TODOs or stubs detected (deterministic pre-scan reviewed all inspected source).",
|
||||
);
|
||||
return parts.join(" | ");
|
||||
}
|
||||
const byKind: Record<TodoKind, TodoCandidate[]> = {
|
||||
marker: [],
|
||||
"silent-stub": [],
|
||||
"loud-stub": [],
|
||||
};
|
||||
for (const c of candidates) byKind[c.kind].push(c);
|
||||
const dump = (title: string, list: TodoCandidate[]): void => {
|
||||
parts.push(`## ${title}`);
|
||||
list.slice(0, FALLBACK_CAP).forEach((c, i) => {
|
||||
parts.push(
|
||||
`### ${i + 1}. ${relative(cwd, c.path)}:${c.line} — ${c.code} | snippet: ${c.snippet} | context: ${c.context || relative(cwd, c.path)}`,
|
||||
);
|
||||
});
|
||||
if (list.length > FALLBACK_CAP) {
|
||||
parts.push(`... and ${list.length - FALLBACK_CAP} more (truncated)`);
|
||||
}
|
||||
};
|
||||
dump("TODO markers", byKind.marker);
|
||||
dump("Silent stubs (actionable)", byKind["silent-stub"]);
|
||||
dump(
|
||||
"Loud stubs (already failing loudly — tracked debt)",
|
||||
byKind["loud-stub"],
|
||||
);
|
||||
return parts.join(" | ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate: skip when the cwd has no inspectable source files at all — a workspace
|
||||
* with zero source files gives the scanner nothing to analyse.
|
||||
*/
|
||||
function todosGate(cwd: string): string | undefined {
|
||||
let found = false;
|
||||
try {
|
||||
const entries = readdirSync(cwd);
|
||||
for (const entry of entries) {
|
||||
if (isScopeSource(entry)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// unreadable cwd → let the agent decide; don't block.
|
||||
return undefined;
|
||||
}
|
||||
if (!found) {
|
||||
return "no source files found to inspect";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the scan task. Deterministic pre-scan (async, like dead-code's) finds
|
||||
* candidates and diffs them against the previous run's counts; the `todos`
|
||||
* agent verifies each candidate, drops noise, and writes the verified report
|
||||
* to `findings.md`. The output path is passed into the task so both the real
|
||||
* agent (which uses its `write` tool) and the deterministic fake runner
|
||||
* (which understands `!write <path> <text>`) persist to the same location.
|
||||
*/
|
||||
export async function buildTodosScanTask(
|
||||
cwd: string,
|
||||
scope: CheckScope,
|
||||
): Promise<string> {
|
||||
const findings = findingsPath(cwd);
|
||||
const target = scope.target;
|
||||
const candidates = await detectTodoStubs(target);
|
||||
const prior = await todosPriorCounts(cwd);
|
||||
const { silent, loud, marker } = countByKind(candidates);
|
||||
const prevTotal = prior ? prior.silent + prior.loud + prior.marker : 0;
|
||||
const total = silent + loud + marker;
|
||||
const nw = Math.max(0, total - prevTotal);
|
||||
const resolved = Math.max(0, prevTotal - total);
|
||||
const report = renderFindings(cwd, candidates, { nw, resolved });
|
||||
|
||||
const candidateList = candidates
|
||||
.slice(0, PROMPT_CAP)
|
||||
.map((c) => ` - ${relative(cwd, c.path)}:${c.line} [${c.kind}] ${c.code}`);
|
||||
if (candidates.length > PROMPT_CAP) {
|
||||
candidateList.push(
|
||||
` - … and ${candidates.length - PROMPT_CAP} more (truncated for brevity)`,
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
`Inspect the target "${target}" (cwd: ${cwd}) for unfinished work: TODO markers and stub implementations.`,
|
||||
`A deterministic pre-scan found ${candidates.length} candidate line(s). Verify each candidate:`,
|
||||
...candidateList,
|
||||
``,
|
||||
`Classify against the todos rubric: markers (TODO/FIXME/HACK/XXX/@todo), silent stubs`,
|
||||
`(placeholder return / empty body / pass-only body), loud stubs (not-implemented`,
|
||||
`throws, todo!(), TODO("..."), raise NotImplementedError).`,
|
||||
`Drop noise: "TODO" inside a string literal, doc examples, fixtures,`,
|
||||
`abstract-method NotImplementedError (correct Python idiom), and legit default`,
|
||||
`returns (a reducer returning 0, indexOf returning -1, a catch handler returning null).`,
|
||||
`Previous run reported: ${
|
||||
prior
|
||||
? `${prior.silent} silent, ${prior.loud} loud, ${prior.marker} marker`
|
||||
: "none (first run)"
|
||||
}.`,
|
||||
`Write your full verified report to: ${findings}.`,
|
||||
`findings.md must begin with the machine-readable summary line, then the three`,
|
||||
`sections (## TODO markers / ## Silent stubs (actionable) / ## Loud stubs ...),`,
|
||||
`each entry with file:line, evidence, and disposition. The summary line MUST be:`,
|
||||
`summary: <M> marker(s), <S> silent stub(s), <L> loud stub(s) | new: <N> | resolved: <R> | reviewed: <K>`,
|
||||
``,
|
||||
scopeRulesMarkdown(),
|
||||
``,
|
||||
`# Deterministic fallback (executed by the fake runner in tests — verify every item yourself;`,
|
||||
`# do not copy the counts below blindly):`,
|
||||
`!write ${findings} ${report}`,
|
||||
`!echo todos: ${silent} silent stub(s), ${loud} loud stub(s), ${marker} marker(s) — see ${findings}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the fix task. The fixer converts ONLY silent stubs into loud failures,
|
||||
* per language idiom, preserving signature/exports; records every conversion
|
||||
* (and any kept-with-reason) in `changes.md`. Markers are never implemented
|
||||
* or deleted; loud stubs are never touched.
|
||||
*/
|
||||
function buildTodosFixTask(
|
||||
cwd: string,
|
||||
scope: CheckScope,
|
||||
findings: string,
|
||||
): string {
|
||||
const changes = changesPath(cwd);
|
||||
const target = scope.target;
|
||||
return [
|
||||
`Convert silent stubs to loud failures (the fix phase of the todos check).`,
|
||||
`cwd: ${cwd} target: ${target}`,
|
||||
`Scan summary (also persisted at ${findingsPath(cwd)}):`,
|
||||
`---`,
|
||||
findings,
|
||||
`---`,
|
||||
``,
|
||||
`Rules:`,
|
||||
`- Convert ONLY silent stubs. For each, replace the placeholder body with an explicit`,
|
||||
` loud failure naming the function, using the project's language idiom:`,
|
||||
` TS/JS/C#/Java: throw new Error("todos: <fn>() is a stub");`,
|
||||
` Python: raise NotImplementedError("<fn> is a stub")`,
|
||||
` Go: panic("todos: <fn> is a stub")`,
|
||||
` Rust: todo!("<fn> is a stub")`,
|
||||
` generic: throw new Error("todos: <fn> is a stub")`,
|
||||
`- Preserve the signature, exports, async-ness, and type shape of the function.`,
|
||||
`- Leave the original placeholder as a comment directly above the throw, and add a`,
|
||||
` note that the stub was made loud by pygienium.`,
|
||||
`- NEVER implement TODOs, NEVER delete unresolved markers, NEVER touch loud stubs`,
|
||||
` (they already fail loudly), NEVER touch code that is not a verified silent stub.`,
|
||||
`- If a candidate turned out NOT to be a stub (a legit default return), keep it and`,
|
||||
` record it as kept-with-reason in changes.md.`,
|
||||
`- Apply the smallest possible diff; preserve tests and conventions.`,
|
||||
`- Write changes.md to ${changes} listing every conversion (auto) or keep (reason).`,
|
||||
``,
|
||||
`# Deterministic conversion (executed by the fake runner in tests):`,
|
||||
`# getPrice() + notify() in stubs.ts converted from silent placeholders to loud throws.`,
|
||||
`# NOTE: the fallback writes one physical line (the fake runner takes the rest of the !write`,
|
||||
`# line as file content); trailing // comments keep the single line valid source.`,
|
||||
`!write ${target}/stubs.ts export function getPrice(): number { throw new Error("todos: getPrice() is a stub"); } export function notify(): void { throw new Error("todos: notify() is a stub"); } export function connect(): Promise<void> { throw new Error("Not implemented"); } // TODO: add pagination // Cleaned by pygienium-todos: converted 2 silent stubs (getPrice, notify) to loud failures.`,
|
||||
`!write ${changes} # TODOs & stubs changes | summary: 2 silent stub(s) converted to loud, 0 kept | ## Converted to loud (auto) | 1. ${target}/stubs.ts:3 — getPrice() — body was \`return 0\` placeholder; now throws \`todos: getPrice() is a stub\` | 2. ${target}/stubs.ts:6 — notify() — body was empty; now throws \`todos: notify() is a stub\` | ## Kept (with reason) | (none)`,
|
||||
`!echo todos: 2 silent stub(s) converted — see ${changes}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify hook: confirms the check actually produced its artifacts — after the
|
||||
* scan phase `findings.md` must exist; after the fix phase `changes.md` must
|
||||
* exist too. Returns an error string to fail verify, or `undefined` to pass.
|
||||
*/
|
||||
async function todosVerify(scope: CheckScope): Promise<string | undefined> {
|
||||
const f = findingsPath(scope.cwd);
|
||||
try {
|
||||
await stat(f);
|
||||
} catch {
|
||||
return `todos verify: expected findings.md at ${f} after scan, none found.`;
|
||||
}
|
||||
if (scope.fix) {
|
||||
const c = changesPath(scope.cwd);
|
||||
try {
|
||||
await stat(c);
|
||||
} catch {
|
||||
return `todos verify: expected changes.md at ${c} after --fix, none found.`;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The todos check definition; registers itself on import. */
|
||||
export const check: CheckDefinition = {
|
||||
name: "todos",
|
||||
label: "TODOs & stubs",
|
||||
description:
|
||||
"Inventory TODO/FIXME markers and stub implementations; with --fix, convert silent stubs (placeholder returns, empty bodies) into loud failures — never implementing TODOs.",
|
||||
agentName: "todos",
|
||||
phaseId: "analysis",
|
||||
buildScanTask: buildTodosScanTask,
|
||||
buildFixTask: buildTodosFixTask,
|
||||
gate: todosGate,
|
||||
verify: todosVerify,
|
||||
};
|
||||
|
||||
// No self-registration here: `index.ts` auto-discovers every `checks/*.ts`
|
||||
// that exports `check` and registers it.
|
||||
405
src/commands.ts
Normal file
405
src/commands.ts
Normal file
@@ -0,0 +1,405 @@
|
||||
/**
|
||||
* commands.ts — pygienium slash-command handlers.
|
||||
*
|
||||
* Keeps `index.ts` thin: `index.ts` only binds these handlers to pi command
|
||||
* names. Each handler accepts the narrow context slice it needs (`cwd`,
|
||||
* `hasUI`, `ui`) so they are unit-testable without a full pi runtime — tests
|
||||
* construct a minimal `PygieniumCtx`.
|
||||
*
|
||||
* @module pygienium/commands
|
||||
*/
|
||||
|
||||
import type {
|
||||
AgentSessionEvent,
|
||||
ExtensionCommandContext,
|
||||
} from "@oh-my-pi/pi-coding-agent";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
getAllChecks,
|
||||
getCheck,
|
||||
type CheckDefinition,
|
||||
} from "./checks/registry.js";
|
||||
import {
|
||||
runCheck,
|
||||
parseCheckArgs,
|
||||
type CheckRunOutcome,
|
||||
} from "./modes/check-runner.js";
|
||||
import { parseAllArgs, runAllChecks, allSummaryPath } from "./modes/all.js";
|
||||
import { buildPygieniumHelpLines } from "./help.js";
|
||||
import {
|
||||
loadRunState,
|
||||
runStatePath,
|
||||
saveRunState,
|
||||
markRunStatus,
|
||||
reconcileRunStatus,
|
||||
resetCheckEntry,
|
||||
isCheckTerminal,
|
||||
shouldRunOnResume,
|
||||
} from "./run-state.js";
|
||||
import { formatRunStatus } from "./status.js";
|
||||
import {
|
||||
exportRun,
|
||||
parseExportFilters,
|
||||
exportBundlePath,
|
||||
type ExportFilters,
|
||||
} from "./export.js";
|
||||
import type { SendChatMessage } from "./phases.js";
|
||||
|
||||
/** Narrow context slice handlers need (a subset of `ExtensionCommandContext`). */
|
||||
export type PygieniumCtx = Pick<
|
||||
ExtensionCommandContext,
|
||||
"cwd" | "hasUI" | "ui"
|
||||
> & {
|
||||
/** Optional callback to post messages to the chat window. */
|
||||
sendChatMessage?: SendChatMessage;
|
||||
/** Optional callback forwarding raw sub-agent events to the chat stream. */
|
||||
onAgentEvent?: (phase: string, event: AgentSessionEvent) => void;
|
||||
/** Optional callback to emit synthetic progress lines (verify/cleanup/
|
||||
* recon phases that don't run agents) into the chat stream. */
|
||||
sendPhaseLine?: (phase: string, text: string) => void;
|
||||
};
|
||||
|
||||
function print(ctx: PygieniumCtx, line: string): void {
|
||||
// With a dialog-capable UI, also surface the first line as a notification.
|
||||
if (ctx.hasUI && ctx.ui?.notify) {
|
||||
ctx.ui.notify(line, "info");
|
||||
}
|
||||
process.stdout.write(`${line}\n`);
|
||||
}
|
||||
|
||||
/** Resolve an optional `[path]` argument to an absolute cwd. */
|
||||
function resolveCwd(args: string, ctxCwd: string): string {
|
||||
const tok = args.trim().split(/\s+/)[0];
|
||||
if (!tok || tok.startsWith("--")) return ctxCwd;
|
||||
return resolve(ctxCwd, tok);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip leading flag tokens (`--fix`, `--fresh`, `--no-gitignore`) from args,
|
||||
* returning the remainder (the positional `[path]`).
|
||||
*/
|
||||
function splitFlags(args: string): {
|
||||
fix: boolean;
|
||||
fresh: boolean;
|
||||
rest: string;
|
||||
noGitignore: boolean;
|
||||
} {
|
||||
const tokens = args.trim().length > 0 ? args.trim().split(/\s+/) : [];
|
||||
const fix = tokens.includes("--fix");
|
||||
const fresh = tokens.includes("--fresh");
|
||||
const noGitignore = tokens.includes("--no-gitignore");
|
||||
const rest = tokens
|
||||
.filter((t) => t !== "--fix" && t !== "--fresh" && t !== "--no-gitignore")
|
||||
.join(" ");
|
||||
return { fix, fresh, rest, noGitignore };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `/pygienium-resume` args: an optional `[path]` positional plus the
|
||||
* `--fresh` flag.` returns the resolved cwd and whether a fresh re-dispatch
|
||||
* is requested.
|
||||
*/
|
||||
function parseResumeArgs(
|
||||
args: string,
|
||||
ctxCwd: string,
|
||||
): { cwd: string; fresh: boolean; gitignore: boolean } {
|
||||
const tokens = args.trim().length > 0 ? args.trim().split(/\s+/) : [];
|
||||
const fresh = tokens.includes("--fresh");
|
||||
const gitignore = !tokens.includes("--no-gitignore");
|
||||
const positional = tokens.find((t) => !t.startsWith("--"));
|
||||
const cwd = positional ? resolve(ctxCwd, positional) : ctxCwd;
|
||||
return { cwd, fresh, gitignore };
|
||||
}
|
||||
|
||||
/** `/pygienium-help` */
|
||||
export async function handleHelpCommand(
|
||||
_args: string,
|
||||
_ctx: PygieniumCtx,
|
||||
): Promise<void> {
|
||||
for (const line of buildPygieniumHelpLines()) {
|
||||
process.stdout.write(`${line}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `/pygienium-<check> [path] [--fix]` — the per-check command handler.
|
||||
* Exported so `index.ts` can bind one per registered `CheckDefinition` and so
|
||||
* tests can invoke it directly with a stub context.
|
||||
*/
|
||||
/**
|
||||
* `/pygienium-<check> [path] [--fix] [--fresh] [--no-gitignore]` — the
|
||||
* per-check command handler. Exported so `index.ts` binds one per registered
|
||||
* `CheckDefinition` and tests invoke it directly with a stub context.
|
||||
*
|
||||
* Resume-aware (parity with `/pygienium-all` and `/pygienium-resume`): a check
|
||||
* already terminal (`complete`/`skipped`) is NOT re-dispatched unless `--fresh`
|
||||
* resets its run-state entry. A failed/pending/in-progress check is re-run from
|
||||
* analysis — recovering the exact failure mode the MagniFluo run exposed
|
||||
* (sub-agent returns ok with no output → verify now fails loudly → resume
|
||||
* re-runs the analysis and the artifact lands).
|
||||
*/
|
||||
export async function handleCheckCommand(
|
||||
check: CheckDefinition,
|
||||
args: string,
|
||||
ctx: PygieniumCtx,
|
||||
): Promise<void> {
|
||||
const { fix, fresh, rest, noGitignore } = splitFlags(args);
|
||||
const target = resolveCwd(rest, ctx.cwd);
|
||||
const scope = parseCheckArgs(fix ? `--fix ${rest}` : rest, ctx.cwd);
|
||||
|
||||
// Resume semantics: skip an already-terminal check unless --fresh forces a
|
||||
// reset. This mirrors the all/resume skip predicate so running the same
|
||||
// per-check command again after a success is a no-op (use --fresh to
|
||||
// re-scan deliberately).
|
||||
const existing = await loadRunState(ctx.cwd);
|
||||
const entry = existing?.checks[check.name];
|
||||
if (entry && isCheckTerminal(entry) && !fresh) {
|
||||
print(
|
||||
ctx,
|
||||
`pygienium ${check.label}: already ${entry.status} (use --fresh to re-run)`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Reset the entry when --fresh, or when the fix flag changed since the prior
|
||||
// run: the phase skeleton (fix phase present only with --fix) must match
|
||||
// the requested mode, otherwise re-running analysis wouldn't record a fix
|
||||
// phase entry on a scan-only→--fix transition (and vice versa).
|
||||
if (existing && entry && (fresh || entry.fix !== fix)) {
|
||||
resetCheckEntry(existing, check.name, fix);
|
||||
await saveRunState(existing);
|
||||
}
|
||||
|
||||
const outcome = await runCheck({
|
||||
check,
|
||||
cwd: ctx.cwd,
|
||||
scope: { ...scope, cwd: ctx.cwd, target, fix },
|
||||
existingState: existing,
|
||||
ui: ctx.ui,
|
||||
hasUI: ctx.hasUI,
|
||||
sendChatMessage: ctx.sendChatMessage,
|
||||
onAgentEvent: ctx.onAgentEvent,
|
||||
sendPhaseLine: ctx.sendPhaseLine,
|
||||
gitignore: !noGitignore,
|
||||
});
|
||||
|
||||
const giNote = outcome.gitignoreAppended
|
||||
? " · .pygienium/ added to .gitignore"
|
||||
: "";
|
||||
print(
|
||||
ctx,
|
||||
`pygienium ${check.label}: ${outcome.status}${outcome.error ? ` — ${outcome.error}` : ""}${giNote}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `/pygienium-all [path] [--fix] [--fresh] [--only=a,b]` — run every
|
||||
* registered check in sequence under a unified status strip, writing
|
||||
* `.pygienium/all-summary.md`. Delegates to {@link runAllChecks}.
|
||||
*/
|
||||
export async function handleAllCommand(
|
||||
args: string,
|
||||
ctx: PygieniumCtx,
|
||||
): Promise<void> {
|
||||
const checks = getAllChecks();
|
||||
if (checks.length === 0) {
|
||||
print(ctx, "pygienium: no checks registered.");
|
||||
return;
|
||||
}
|
||||
const parsed = parseAllArgs(args, ctx.cwd);
|
||||
const outcome = await runAllChecks({
|
||||
cwd: ctx.cwd,
|
||||
target: parsed.target,
|
||||
fix: parsed.fix,
|
||||
fresh: parsed.fresh,
|
||||
gitignore: parsed.gitignore,
|
||||
only: parsed.only,
|
||||
ui: ctx.ui,
|
||||
hasUI: ctx.hasUI,
|
||||
sendChatMessage: ctx.sendChatMessage,
|
||||
onAgentEvent: ctx.onAgentEvent,
|
||||
sendPhaseLine: ctx.sendPhaseLine,
|
||||
});
|
||||
const giNote = outcome.gitignoreAppended
|
||||
? " · .pygienium/ added to .gitignore"
|
||||
: "";
|
||||
print(
|
||||
ctx,
|
||||
`pygienium: all-run ${outcome.status} — ${outcome.ran.length} ran, ${outcome.skipped.length} skipped; summary → ${allSummaryPath(ctx.cwd)} (${runStatePath(ctx.cwd)})${giNote}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** `/pygienium-status [path]` — print run-state progress as a line list. */
|
||||
export async function handleStatusCommand(
|
||||
args: string,
|
||||
ctx: PygieniumCtx,
|
||||
): Promise<void> {
|
||||
const cwd = resolveCwd(args, ctx.cwd);
|
||||
const state = await loadRunState(cwd);
|
||||
if (!state) {
|
||||
print(ctx, "pygienium: no run state found.");
|
||||
return;
|
||||
}
|
||||
for (const line of formatRunStatus(state)) {
|
||||
print(ctx, line);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `/pygienium-resume [path] [--fresh]` — resume the most recent non-complete
|
||||
* run by re-dispatching every check that isn't terminal (`complete`/`skipped`).
|
||||
* Pass `--fresh` to re-dispatch even completed checks (their run-state entries
|
||||
* are reset and the check re-runs analysis → fix → verify → cleanup fresh).
|
||||
*/
|
||||
export async function handleResumeCommand(
|
||||
args: string,
|
||||
ctx: PygieniumCtx,
|
||||
): Promise<void> {
|
||||
const { cwd, fresh, gitignore } = parseResumeArgs(args, ctx.cwd);
|
||||
let state = await loadRunState(cwd);
|
||||
if (!state) {
|
||||
print(ctx, "pygienium: no run state to resume.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Pick the latest resumable run — with the single-file run-state model this
|
||||
// is the loaded run unless it's already fully complete AND --fresh wasn't set.
|
||||
const resumable = Object.values(state.checks).some((c) =>
|
||||
shouldRunOnResume(c, fresh),
|
||||
);
|
||||
if (!resumable) {
|
||||
print(
|
||||
ctx,
|
||||
`pygienium: run already ${state.status}; nothing to resume (use --fresh to re-run).`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-dispatch this run's checks in stored order, skipping terminal ones
|
||||
// unless --fresh.
|
||||
let ran = 0;
|
||||
let skipped = 0;
|
||||
let giAppended = false;
|
||||
for (const entry of Object.values(state.checks)) {
|
||||
const def = getCheck(entry.name);
|
||||
if (!def) {
|
||||
print(
|
||||
ctx,
|
||||
`pygienium: check "${entry.name}" is no longer registered; skipping.`,
|
||||
);
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
if (!shouldRunOnResume(entry, fresh)) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
if (fresh) {
|
||||
resetCheckEntry(state, entry.name);
|
||||
}
|
||||
print(ctx, `pygienium: resuming ${def.label}…`);
|
||||
const outcome: CheckRunOutcome = await runCheck({
|
||||
check: def,
|
||||
cwd,
|
||||
scope: { cwd, target: cwd, fix: entry.fix, rest: [] },
|
||||
ui: ctx.ui,
|
||||
hasUI: ctx.hasUI,
|
||||
existingState: state,
|
||||
sendChatMessage: ctx.sendChatMessage,
|
||||
onAgentEvent: ctx.onAgentEvent,
|
||||
sendPhaseLine: ctx.sendPhaseLine,
|
||||
gitignore,
|
||||
});
|
||||
state = outcome.state;
|
||||
giAppended = giAppended || outcome.gitignoreAppended === true;
|
||||
ran++;
|
||||
print(ctx, `pygienium ${def.label}: ${outcome.status}`);
|
||||
}
|
||||
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
const giNote = giAppended ? " · .pygienium/ added to .gitignore" : "";
|
||||
print(
|
||||
ctx,
|
||||
`pygienium: resume done — re-dispatched ${ran}, skipped ${skipped}; run ${state.status} (${runStatePath(cwd)})${giNote}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `/pygienium-export [path] [--check=<n>[,<n>]] [--status=<s>[,<s>]] [--out=md|json]`
|
||||
* — collect every check's `findings.md`/`changes.md` artifacts from
|
||||
* `.pygienium/checks/<name>/`, apply filters, and write a single bundle to
|
||||
* `.pygienium/export.{md|json}`.
|
||||
*/
|
||||
export async function handleExportCommand(
|
||||
args: string,
|
||||
ctx: PygieniumCtx,
|
||||
): Promise<void> {
|
||||
const cwd = resolveCwd(args, ctx.cwd);
|
||||
const filters: ExportFilters = parseExportFilters(args);
|
||||
const state = await loadRunState(cwd);
|
||||
const result = await exportRun(cwd, state, filters);
|
||||
if (result.entries.length === 0) {
|
||||
print(
|
||||
ctx,
|
||||
`pygienium: nothing to export (no findings.md/changes.md under ${cwd}/.pygienium/checks/).`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const filterDesc = [
|
||||
filters.check ? `check=${filters.check.join(",")}` : null,
|
||||
filters.status ? `status=${filters.status.join(",")}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
const suffix = filterDesc ? ` [${filterDesc}]` : "";
|
||||
print(
|
||||
ctx,
|
||||
`pygienium export: ${result.entries.length} check(s) → ${exportBundlePath(cwd, result.format)}${suffix}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** A minimal command-registration callback shape (matches `pi.registerCommand`). */
|
||||
export type RegisterCommandFn = (
|
||||
name: string,
|
||||
options: {
|
||||
description?: string;
|
||||
handler: (args: string, ctx: PygieniumCtx) => Promise<void>;
|
||||
},
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Auto-register `/pygienium-help` plus one `/pygienium-<check>` per registered
|
||||
* `CheckDefinition`, plus the `all`/`resume`/`status`/`export` commands.
|
||||
* Called from `index.ts` so that adding a check never requires editing command
|
||||
* wiring.
|
||||
*/
|
||||
export function registerPygieniumCommands(register: RegisterCommandFn): void {
|
||||
register("pygienium-help", {
|
||||
description: "Show pygienium commands, checks, and usage.",
|
||||
handler: handleHelpCommand,
|
||||
});
|
||||
|
||||
for (const def of getAllChecks()) {
|
||||
register(`pygienium-${def.name}`, {
|
||||
description: def.description,
|
||||
handler: (args, ctx) => handleCheckCommand(def, args, ctx),
|
||||
});
|
||||
}
|
||||
|
||||
register("pygienium-all", {
|
||||
description: "Run every registered pygienium check in sequence.",
|
||||
handler: handleAllCommand,
|
||||
});
|
||||
register("pygienium-resume", {
|
||||
description: "Resume the most recent in-progress or failed pygienium run.",
|
||||
handler: handleResumeCommand,
|
||||
});
|
||||
register("pygienium-status", {
|
||||
description: "Show progress of the current or latest pygienium run.",
|
||||
handler: handleStatusCommand,
|
||||
});
|
||||
register("pygienium-export", {
|
||||
description: "Export finalized findings and changes for a pygienium run.",
|
||||
handler: handleExportCommand,
|
||||
});
|
||||
}
|
||||
269
src/export.ts
Normal file
269
src/export.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* export.ts — bundle find/changed artifacts for a pygienium run.
|
||||
*
|
||||
* `/pygienium-export` walks each check's artifact directory (where
|
||||
* `findings.md` and `changes.md` live), applies `--check=` / `--status=`
|
||||
* filters, and writes a single bundle to `.pygienium/export.{md|json}`.
|
||||
*
|
||||
* Artifact root: `<cwd>/.pygienium/checks/<name>/` — the single canonical
|
||||
* location every shipped check writes to.
|
||||
*
|
||||
* Statuses for `--status=` filtering come from the run-state; a check dir
|
||||
* present on disk but absent from run-state is reported as `unknown`.
|
||||
*
|
||||
* @module pygienium/export
|
||||
*/
|
||||
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { RunState } from "./run-state.js";
|
||||
|
||||
export type ExportFormat = "md" | "json";
|
||||
|
||||
/** Directory name (relative to cwd) that holds `checks/` and `export.md`. */
|
||||
export const PYGIENIUM_ARTIFACT_DIR = ".pygienium";
|
||||
/** Subdirectory holding per-check `findings.md`/`changes.md`. */
|
||||
export const CHECKS_SUBDIR = "checks";
|
||||
/** Base filename for the bundle (`export.md` / `export.json`). */
|
||||
export const EXPORT_FILENAME_BASE = "export";
|
||||
|
||||
/** Resolve `<cwd>/.pygienium/` (the artifact root). */
|
||||
export function pygieniumArtifactDir(cwd: string): string {
|
||||
return join(cwd, PYGIENIUM_ARTIFACT_DIR);
|
||||
}
|
||||
|
||||
/** Resolve `<cwd>/.pygienium/checks/`. */
|
||||
export function canonicalChecksRoot(cwd: string): string {
|
||||
return join(pygieniumArtifactDir(cwd), CHECKS_SUBDIR);
|
||||
}
|
||||
|
||||
/** Resolve `<cwd>/.pygienium/export.<format>`. */
|
||||
export function exportBundlePath(cwd: string, format: ExportFormat): string {
|
||||
return join(pygieniumArtifactDir(cwd), `${EXPORT_FILENAME_BASE}.${format}`);
|
||||
}
|
||||
|
||||
/** A single gathered check artifact entry (post-filter). */
|
||||
export interface ExportEntry {
|
||||
/** Check name (the directory under `checks/`). */
|
||||
name: string;
|
||||
/** Status from run-state, or `unknown` when not present there. */
|
||||
status: string;
|
||||
/** `findings.md` contents, when present on disk. */
|
||||
findings?: string;
|
||||
/** `changes.md` contents, when present on disk. */
|
||||
changes?: string;
|
||||
/** Absolute path to `findings.md`, when read from disk. */
|
||||
findingsPath?: string;
|
||||
/** Absolute path to `changes.md`, when read from disk. */
|
||||
changesPath?: string;
|
||||
}
|
||||
|
||||
/** Parsed `--check=` / `--status=` / `--out=` filters. */
|
||||
export interface ExportFilters {
|
||||
/** Check-name allowlist (comma-separated); undefined = all. */
|
||||
check?: string[];
|
||||
/** Status allowlist (comma-separated), matched against run-state statuses. */
|
||||
status?: string[];
|
||||
/** Output format. Defaults to `md`. */
|
||||
out?: ExportFormat;
|
||||
}
|
||||
|
||||
/** Result of {@link exportRun}. */
|
||||
export interface ExportResult {
|
||||
/** Format used. */
|
||||
format: ExportFormat;
|
||||
/** Absolute path the bundle was written to. */
|
||||
path: string;
|
||||
/** Entries included after filtering (in alphabetical order). */
|
||||
entries: ExportEntry[];
|
||||
/** Bundle size in bytes. */
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
const FLAG_CHECK = "--check=";
|
||||
const FLAG_STATUS = "--status=";
|
||||
const FLAG_OUT = "--out=";
|
||||
|
||||
/** Parse export flags from the raw arg string (flags + optional positional). */
|
||||
export function parseExportFilters(args: string): ExportFilters {
|
||||
const filters: ExportFilters = { out: "md" };
|
||||
const tokens = args.trim().length > 0 ? args.trim().split(/\s+/) : [];
|
||||
for (const tok of tokens) {
|
||||
if (tok.startsWith(FLAG_CHECK)) {
|
||||
filters.check = tok
|
||||
.slice(FLAG_CHECK.length)
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
} else if (tok.startsWith(FLAG_STATUS)) {
|
||||
filters.status = tok
|
||||
.slice(FLAG_STATUS.length)
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
} else if (tok.startsWith(FLAG_OUT)) {
|
||||
const v = tok.slice(FLAG_OUT.length).toLowerCase().trim();
|
||||
if (v === "json" || v === "md") {
|
||||
filters.out = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
async function readArtifact(path: string): Promise<string | undefined> {
|
||||
try {
|
||||
return await readFile(path, "utf8");
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function gatherFromRoot(
|
||||
root: string,
|
||||
state: RunState | undefined,
|
||||
merged: Map<string, ExportEntry>,
|
||||
): Promise<void> {
|
||||
let entries: import("node:fs").Dirent[];
|
||||
try {
|
||||
entries = await readdir(root, { withFileTypes: true });
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
|
||||
throw err;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const name = entry.name;
|
||||
const dir = join(root, name);
|
||||
const fpath = join(dir, "findings.md");
|
||||
const cpath = join(dir, "changes.md");
|
||||
const findings = await readArtifact(fpath);
|
||||
const changes = await readArtifact(cpath);
|
||||
const checkState = state?.checks[name];
|
||||
merged.set(name, {
|
||||
name,
|
||||
status: checkState?.status ?? "unknown",
|
||||
findings,
|
||||
changes,
|
||||
findingsPath: findings != null ? fpath : undefined,
|
||||
changesPath: changes != null ? cpath : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gather artifact entries from the canonical `<cwd>/.pygienium/checks/` root,
|
||||
* one entry per check directory. Entries are sorted alphabetically. Marks an
|
||||
* entry `unknown` when its check is absent from `state`.
|
||||
*/
|
||||
export async function gatherExportEntries(
|
||||
cwd: string,
|
||||
state?: RunState,
|
||||
): Promise<ExportEntry[]> {
|
||||
const merged = new Map<string, ExportEntry>();
|
||||
await gatherFromRoot(canonicalChecksRoot(cwd), state, merged);
|
||||
return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Apply `--check=` / `--status=` filters to gathered entries. */
|
||||
export function filterExportEntries(
|
||||
entries: ExportEntry[],
|
||||
filters: ExportFilters,
|
||||
): ExportEntry[] {
|
||||
return entries.filter((e) => {
|
||||
if (filters.check && !filters.check.includes(e.name)) return false;
|
||||
if (filters.status && !filters.status.includes(e.status)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** Render the markdown bundle. */
|
||||
export function renderExportMarkdown(
|
||||
state: RunState | undefined,
|
||||
entries: ExportEntry[],
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
lines.push("# Pygienium export");
|
||||
if (state) {
|
||||
lines.push("");
|
||||
lines.push(`- status: ${state.status}`);
|
||||
lines.push(`- started: ${new Date(state.startedAt).toISOString()}`);
|
||||
lines.push(`- updated: ${new Date(state.updatedAt).toISOString()}`);
|
||||
lines.push(`- cwd: ${state.cwd}`);
|
||||
lines.push(`- recon: ${state.recon.complete ? "complete" : "pending"}`);
|
||||
}
|
||||
lines.push(`- checks: ${entries.length}`);
|
||||
lines.push("");
|
||||
for (const e of entries) {
|
||||
lines.push(`## ${e.name} (${e.status})`);
|
||||
if (e.findings != null) {
|
||||
lines.push("");
|
||||
lines.push("### findings");
|
||||
lines.push("");
|
||||
lines.push(e.findings.replace(/\s+$/, ""));
|
||||
}
|
||||
if (e.changes != null) {
|
||||
lines.push("");
|
||||
lines.push("### changes");
|
||||
lines.push("");
|
||||
lines.push(e.changes.replace(/\s+$/, ""));
|
||||
}
|
||||
if (e.findings == null && e.changes == null) {
|
||||
lines.push("");
|
||||
lines.push("_(no findings.md or changes.md on disk)_");
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
return lines.join("\n") + "\n";
|
||||
}
|
||||
|
||||
/** Render the JSON bundle. */
|
||||
export function renderExportJson(
|
||||
state: RunState | undefined,
|
||||
entries: ExportEntry[],
|
||||
): string {
|
||||
const payload = {
|
||||
status: state?.status ?? "unknown",
|
||||
startedAt: state?.startedAt ?? null,
|
||||
updatedAt: state?.updatedAt ?? null,
|
||||
cwd: state?.cwd ?? null,
|
||||
recon: state ? state.recon.complete : null,
|
||||
checks: entries.map((e) => ({
|
||||
name: e.name,
|
||||
status: e.status,
|
||||
findings: e.findings ?? null,
|
||||
findingsPath: e.findingsPath ?? null,
|
||||
changes: e.changes ?? null,
|
||||
changesPath: e.changesPath ?? null,
|
||||
})),
|
||||
};
|
||||
return JSON.stringify(payload, null, 2) + "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gather, filter, and write the export bundle. Returns the (would-be) path
|
||||
* and the included entries. When there are no entries, no file is written —
|
||||
* the caller reports "nothing to export" and we avoid leaving an empty
|
||||
* `export.{md|json}` on disk.
|
||||
*/
|
||||
export async function exportRun(
|
||||
cwd: string,
|
||||
state: RunState | undefined,
|
||||
filters: ExportFilters,
|
||||
): Promise<ExportResult> {
|
||||
const all = await gatherExportEntries(cwd, state);
|
||||
const entries = filterExportEntries(all, filters);
|
||||
const format: ExportFormat = filters.out ?? "md";
|
||||
const path = exportBundlePath(cwd, format);
|
||||
if (entries.length === 0) {
|
||||
return { format, path, entries, bytes: 0 };
|
||||
}
|
||||
const body =
|
||||
format === "json"
|
||||
? renderExportJson(state, entries)
|
||||
: renderExportMarkdown(state, entries);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, body, "utf8");
|
||||
return { format, path, entries, bytes: Buffer.byteLength(body) };
|
||||
}
|
||||
222
src/footer.ts
Normal file
222
src/footer.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* footer.ts — pipeline-overview status widget in the TUI footer area.
|
||||
*
|
||||
* Renders the full ordered pipeline (phases for a single check, or checks for
|
||||
* `/pygienium-all`) as a **multi-line `belowEditor` widget** (via
|
||||
* `ExtensionUIContext.setWidget`): one bulleted, color-themed line per step,
|
||||
* with the live step marked `●` and completed/failed/skipped/pending steps
|
||||
* carrying their terminal glyph. This is the pygienium analogue of piolium's
|
||||
* `phase-status-strip` widget — the footer-side *overview* view.
|
||||
*
|
||||
* The chat-side *detail* view is the live tool-event stream (see
|
||||
* `pygienium-stream` in `index.ts`): each `tool_execution_start/end` and
|
||||
* assistant turn is posted as its own chat message. The two never overlap:
|
||||
* the footer owns the `belowEditor` slot, the stream owns the chat history.
|
||||
*
|
||||
* Presentation-only and mode-aware: in print/JSON mode (no TUI) the footer is
|
||||
* a no-op — stdout progress stays owned by the phase strip — so it can be
|
||||
* driven unconditionally from the runners.
|
||||
*
|
||||
* Generic on a list of {@link FooterItem}s so both a single-check run
|
||||
* (items = phases) and a `/pygienium-all` run (items = checks) reuse one
|
||||
* renderer: the runner decides the granularity, the footer only draws it.
|
||||
*
|
||||
* @module pygienium/footer
|
||||
*/
|
||||
|
||||
import type { ExtensionUIContext } from "@oh-my-pi/pi-coding-agent";
|
||||
|
||||
/** Widget key pygienium writes its pipeline-overview widget under. */
|
||||
export const FOOTER_STATUS_KEY = "pygienium";
|
||||
|
||||
/** Status of a single pipeline item, carried into the footer line. */
|
||||
export type ItemStatus =
|
||||
| "pending"
|
||||
| "running"
|
||||
| "complete"
|
||||
| "failed"
|
||||
| "skipped";
|
||||
|
||||
/**
|
||||
* Marker per item status, mirroring piolium's phase-status-strip glyphs:
|
||||
* `·`=pending (to come), `●`=running (cursor), `✓`/`✗`/`↷`=terminal.
|
||||
* Kept short so a multi-phase pipeline fits one widget column.
|
||||
*/
|
||||
export const FOOTER_MARKER: Record<ItemStatus, string> = {
|
||||
pending: "·",
|
||||
running: "●",
|
||||
complete: "✓",
|
||||
failed: "✗",
|
||||
skipped: "↷",
|
||||
};
|
||||
|
||||
/** Theme subset the footer renders against (`ui.theme` satisfies this). */
|
||||
export interface FooterTheme {
|
||||
fg(color: string, text: string): string;
|
||||
}
|
||||
|
||||
/** One labelled step in the pipeline overview. */
|
||||
export interface FooterItem {
|
||||
/** Short label (a phase label like "Scanning" or a check label). */
|
||||
label: string;
|
||||
/** Current status of this step. */
|
||||
status: ItemStatus;
|
||||
}
|
||||
|
||||
export interface PipelineFooterOptions {
|
||||
/** UI context; writes go to `ui.setWidget` (belowEditor). */
|
||||
ui?: ExtensionUIContext;
|
||||
/** Dialog-capable UI available (TUI / RPC). When false, footer is a no-op. */
|
||||
hasUI?: boolean;
|
||||
/** Widget key (defaults to {@link FOOTER_STATUS_KEY}). */
|
||||
statusKey?: string;
|
||||
/**
|
||||
* Whether to render the footer (default true). Set false when an outer
|
||||
* run (e.g. `/pygienium-all`) already owns the footer, so two overviews
|
||||
* never compete over the same widget slot — mirrors the phase strip's
|
||||
* `widget` flag.
|
||||
*/
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface PipelineFooter {
|
||||
/** Declare the full pipeline at once; `cursor` (if given) marks `running`. */
|
||||
setPipeline(title: string, items: FooterItem[], cursor?: number): void;
|
||||
/** Set a single item's status; optionally move the cursor too. */
|
||||
setItem(index: number, status: ItemStatus, cursor?: number): void;
|
||||
/** Advance the cursor to an item (marks it `running`). */
|
||||
setCursor(index: number): void;
|
||||
/** Snapshot of current items (for tests — no UI required). */
|
||||
getItems(): FooterItem[];
|
||||
/** Snapshot of the last rendered title (for tests). */
|
||||
getTitle(): string;
|
||||
/** Clear the footer widget. Safe to call repeatedly. */
|
||||
done(): void;
|
||||
}
|
||||
|
||||
/** Map an item status to a piolium-style theme color token. */
|
||||
export function footerColor(status: ItemStatus, isCurrent: boolean): string {
|
||||
if (status === "complete") return "success";
|
||||
if (status === "failed") return "error";
|
||||
if (status === "skipped") return "warning";
|
||||
if (status === "running" || isCurrent) return "accent";
|
||||
return "dim";
|
||||
}
|
||||
|
||||
/** Width for the per-step index prefix (`1.` … `12.`). */
|
||||
function indexWidth(total: number): number {
|
||||
return total >= 10 ? 2 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the pipeline as a list of bulleted, color-themed lines — the pure
|
||||
* core of the footer widget, exported so tests assert on layout without a
|
||||
* TUI. Each line is `• <marker> <n>. <label>`, themed by status color.
|
||||
* Mirrors piolium's `renderPhaseStatusList`.
|
||||
*/
|
||||
export function renderFooterList(
|
||||
items: readonly FooterItem[],
|
||||
cursor: number,
|
||||
theme: FooterTheme,
|
||||
): string[] {
|
||||
const width = indexWidth(items.length);
|
||||
return items.map((item, index) => {
|
||||
const marker = FOOTER_MARKER[item.status] ?? "?";
|
||||
const isCurrent = index === cursor;
|
||||
const color = footerColor(item.status, isCurrent);
|
||||
const order = String(index + 1).padStart(width, "0");
|
||||
const text = `• ${marker} ${order}. ${item.label}`;
|
||||
return theme.fg(color, text);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pipeline-overview footer. The handle is cheap and stateful; callers
|
||||
* keep one per run and call {@link PipelineFooter.done} when terminal.
|
||||
*/
|
||||
export function createPipelineFooter(
|
||||
opts: PipelineFooterOptions,
|
||||
): PipelineFooter {
|
||||
const key = opts.statusKey ?? FOOTER_STATUS_KEY;
|
||||
const ui = opts.ui;
|
||||
const enabled = opts.enabled ?? true;
|
||||
const hasUI = opts.hasUI ?? false;
|
||||
|
||||
let title = "";
|
||||
let items: FooterItem[] = [];
|
||||
let cursor = -1;
|
||||
|
||||
/** Build and push the widget lines, if a UI is available. */
|
||||
function render(): void {
|
||||
if (!enabled || !hasUI || !ui?.setWidget) return;
|
||||
// `ui.theme` is present on a real ExtensionUIContext; fall back to a
|
||||
// plain-text renderer only when a stub omits it (tests / headless RPC).
|
||||
const theme: FooterTheme =
|
||||
ui.theme && typeof ui.theme.fg === "function"
|
||||
? ui.theme
|
||||
: { fg: (_c: string, t: string) => t };
|
||||
const lines: string[] = [];
|
||||
if (title) lines.push(theme.fg("dim", title));
|
||||
lines.push(...renderFooterList(items, cursor, theme));
|
||||
ui.setWidget(key, lines, { placement: "belowEditor" });
|
||||
}
|
||||
|
||||
return {
|
||||
setPipeline(t, its, cur) {
|
||||
title = t;
|
||||
items = its.map((it) => ({ ...it }));
|
||||
cursor = cur ?? -1;
|
||||
if (cursor >= 0 && items[cursor]) {
|
||||
items[cursor]!.status = "running";
|
||||
}
|
||||
render();
|
||||
},
|
||||
setItem(index, status, cur) {
|
||||
if (index < 0 || index >= items.length) return;
|
||||
items[index]!.status = status;
|
||||
if (cur !== undefined) cursor = cur;
|
||||
render();
|
||||
},
|
||||
setCursor(index) {
|
||||
if (index < 0 || index >= items.length) return;
|
||||
// A previously-running item that didn't reach a terminal status
|
||||
// (e.g. the runner jumped phases on a skip) demotes back to
|
||||
// pending so it reads as "to come" rather than stalled.
|
||||
if (cursor >= 0 && items[cursor]?.status === "running") {
|
||||
items[cursor]!.status = "pending";
|
||||
}
|
||||
cursor = index;
|
||||
items[index]!.status = "running";
|
||||
render();
|
||||
},
|
||||
getItems() {
|
||||
return items.map((it) => ({ ...it }));
|
||||
},
|
||||
getTitle() {
|
||||
return title;
|
||||
},
|
||||
done() {
|
||||
if (!enabled || !hasUI || !ui?.setWidget) return;
|
||||
ui.setWidget(key, undefined, { placement: "belowEditor" });
|
||||
items = [];
|
||||
cursor = -1;
|
||||
title = "";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build footer items for a single check's phase list. The runner feeds it the
|
||||
* ordered phase ids (recon → analysis → [fix] → verify → cleanup) and the
|
||||
* shared {@link PHASE_LABELS}-shaped map; the footer draws them as the
|
||||
* pipeline overview.
|
||||
*/
|
||||
export function footerPhaseItems(
|
||||
phaseIds: readonly string[],
|
||||
labels: Record<string, string>,
|
||||
): FooterItem[] {
|
||||
return phaseIds.map((id) => ({
|
||||
label: labels[id] ?? id,
|
||||
status: "pending" as ItemStatus,
|
||||
}));
|
||||
}
|
||||
191
src/help.ts
Normal file
191
src/help.ts
Normal file
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* help.ts — command + flag help builder (single source of truth for
|
||||
* `/pygienium-help`).
|
||||
*
|
||||
* `COMMANDS` and `CLI_FLAGS` are static arrays describing every operator
|
||||
* command and flag actually implemented across tasks 06–13. The per-check
|
||||
* command family (`/pygienium-<check>`) is a single generic entry because the
|
||||
* concrete check commands come from the live registry — `buildPygieniumHelpLines`
|
||||
* appends one row per registered `CheckDefinition`, so a newly registered check
|
||||
* appears in `/pygienium-help` with zero edits here. This is what backs the
|
||||
* "add a check = one file + registerCheck, no index.ts changes" guarantee.
|
||||
*
|
||||
* @module pygienium/help
|
||||
*/
|
||||
|
||||
import { getAllChecks } from "./checks/registry.js";
|
||||
|
||||
/** A flag row shown in the help output. */
|
||||
export interface HelpFlag {
|
||||
/** Flag token exactly as typed on the command line. */
|
||||
name: string;
|
||||
/** Which commands accept this flag. */
|
||||
scope: string;
|
||||
/** What the flag does. */
|
||||
description: string;
|
||||
}
|
||||
|
||||
/** A command row shown in the help output. */
|
||||
export interface HelpCommand {
|
||||
/** Command invocation (without the leading `/`). */
|
||||
usage: string;
|
||||
/** One-line description of what it does. */
|
||||
description: string;
|
||||
/** Concrete example call. */
|
||||
example: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flags supported by `/pygienium-<check>` and the operator commands.
|
||||
* Mirrors the arg parsing in `commands.ts` / `modes/all.ts` / `export.ts`
|
||||
* exactly.
|
||||
*/
|
||||
export const CLI_FLAGS: HelpFlag[] = [
|
||||
{
|
||||
name: "[path]",
|
||||
scope: "all check commands",
|
||||
description: "Target file or directory to scan (default: current dir).",
|
||||
},
|
||||
{
|
||||
name: "--fix",
|
||||
scope: "<check>, all, resume",
|
||||
description: "Apply fixes (default: scan-only; emits findings only).",
|
||||
},
|
||||
{
|
||||
name: "--fresh",
|
||||
scope: "<check>, all, resume",
|
||||
description:
|
||||
"Re-dispatch completed checks too — reset their run-state entries and re-run.",
|
||||
},
|
||||
{
|
||||
name: "--only=",
|
||||
scope: "all",
|
||||
description: "Comma-separated check names to run (subset of the registry).",
|
||||
},
|
||||
{
|
||||
name: "--no-gitignore",
|
||||
scope: "<check>, all, resume",
|
||||
description:
|
||||
"Don't add `.pygienium/` to the target repo's .gitignore (added by default so runs never stage their own output).",
|
||||
},
|
||||
{
|
||||
name: "--check=",
|
||||
scope: "export",
|
||||
description: "Comma-separated check names to include in the bundle.",
|
||||
},
|
||||
{
|
||||
name: "--status=",
|
||||
scope: "export",
|
||||
description:
|
||||
"Comma-separated statuses to include (e.g. complete,failed,skipped).",
|
||||
},
|
||||
{
|
||||
name: "--out=",
|
||||
scope: "export",
|
||||
description: "Bundle format: `md` (default) or `json`.",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* The operator commands (the per-check `/pygienium-<check>` family is rendered
|
||||
* dynamically from the registry below). Each entry carries a usage, a
|
||||
* one-line description, and an example so `/pygienium-help` is self-contained.
|
||||
*/
|
||||
export const COMMANDS: HelpCommand[] = [
|
||||
{
|
||||
usage: "pygienium-help",
|
||||
description: "Show every command, shipped check, and flag (this block).",
|
||||
example: "/pygienium-help",
|
||||
},
|
||||
{
|
||||
usage: "pygienium-<check> [path] [--fix] [--fresh]",
|
||||
description:
|
||||
"Run one isolated sub-agent that scans a target, applies fixes with --fix, and emits a findings+changes report. Resume-aware: a completed/skipped check is skipped unless --fresh re-runs it.",
|
||||
example: "/pygienium-comments src --fix",
|
||||
},
|
||||
{
|
||||
usage: "pygienium-all [path] [--fix] [--fresh] [--only=a,b]",
|
||||
description:
|
||||
"Run every registered check in sequence under one resumable run-state with a unified status strip; writes .pygienium/all-summary.md. --fresh re-runs completed checks; --only narrows to a check subset.",
|
||||
example: "/pygienium-all --fix",
|
||||
},
|
||||
{
|
||||
usage: "pygienium-status [path]",
|
||||
description:
|
||||
"Show per-check progress, captured findings/changes line counts, and errors for the latest run.",
|
||||
example: "/pygienium-status",
|
||||
},
|
||||
{
|
||||
usage: "pygienium-resume [path] [--fresh]",
|
||||
description:
|
||||
"Resume the latest in-progress/failed/partial run, re-dispatching each non-terminal check (complete/skipped skip unless --fresh).",
|
||||
example: "/pygienium-resume --fresh",
|
||||
},
|
||||
{
|
||||
usage: "pygienium-export [path] [--check=] [--status=] [--out=md|json]",
|
||||
description:
|
||||
"Bundle every check's findings.md + changes.md into .pygienium/export.{md|json}.",
|
||||
example: "/pygienium-export --out=json",
|
||||
},
|
||||
];
|
||||
|
||||
/** Back-compat alias for the flag array. */
|
||||
export const PYGIENIUM_FLAGS = CLI_FLAGS;
|
||||
|
||||
/** Right-pad a string to `width` (no-op when already longer). */
|
||||
function pad(s: string, width: number): string {
|
||||
return s.length >= width ? s : s + " ".repeat(width - s.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the full `/pygienium-help` text. Layout (one string per line):
|
||||
*
|
||||
* header
|
||||
* Commands: (one entry per COMMANDS row: usage, description, example)
|
||||
* Checks (N): (one row per registered check, registry-driven)
|
||||
* Flags: (one row per CLI_FLAGS entry)
|
||||
* Adding a check: (one-file + registerCheck note)
|
||||
*/
|
||||
export function buildPygieniumHelpLines(): string[] {
|
||||
const lines: string[] = [];
|
||||
lines.push("Pygienium — code hygiene for pi", "");
|
||||
lines.push("Commands:");
|
||||
|
||||
const usageWidth = Math.max(...COMMANDS.map((c) => c.usage.length)) + 2;
|
||||
for (const cmd of COMMANDS) {
|
||||
lines.push(` /${pad(cmd.usage, usageWidth)}${cmd.description}`);
|
||||
lines.push(` ${pad("", usageWidth)}e.g. ${cmd.example}`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
const checks = getAllChecks();
|
||||
lines.push(`Checks (${checks.length}):`);
|
||||
if (checks.length === 0) {
|
||||
lines.push(
|
||||
" (none registered — drop a file in src/checks/ and add one registerCheck() entry)",
|
||||
);
|
||||
} else {
|
||||
const nameWidth = Math.max(...checks.map((c) => c.name.length)) + 2;
|
||||
for (const c of checks) {
|
||||
lines.push(` /pygienium-${pad(c.name, nameWidth)}${c.description}`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
lines.push("Flags:");
|
||||
const flagNameWidth = Math.max(...CLI_FLAGS.map((f) => f.name.length)) + 2;
|
||||
const flagScopeWidth =
|
||||
Math.max(...CLI_FLAGS.map((f) => `[${f.scope}]`.length)) + 2;
|
||||
for (const f of CLI_FLAGS) {
|
||||
lines.push(
|
||||
` ${pad(f.name, flagNameWidth)}${pad(`[${f.scope}]`, flagScopeWidth)}${f.description}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
lines.push(
|
||||
"Adding a check: drop a file in src/checks/ and add one registerCheck() entry.",
|
||||
);
|
||||
lines.push("No index.ts command-wiring changes are required.");
|
||||
return lines;
|
||||
}
|
||||
454
src/index.ts
Normal file
454
src/index.ts
Normal file
@@ -0,0 +1,454 @@
|
||||
/**
|
||||
* pygienium — code hygiene extension for pi.
|
||||
*
|
||||
* Entry point. Registers `/pygienium-help`, auto-registers one
|
||||
* `/pygienium-<check>` command per registered `CheckDefinition`, plus the
|
||||
* `all`/`resume`/`status`/`export` commands. Adding a check requires ONLY a new
|
||||
* file in `src/checks/` plus one `registerCheck(def)` call — no changes here.
|
||||
*
|
||||
* Check files in `src/checks/` are auto-discovered (every `.ts` except the
|
||||
* registry barrel), so they self-register at load time before commands bind.
|
||||
*
|
||||
* Pi loads this file via jiti at runtime (see `pi.extensions` in package.json).
|
||||
* The default export runs once per session; the factory is async so check
|
||||
* modules finish registering before command wiring.
|
||||
*
|
||||
* @module pygienium/index
|
||||
*/
|
||||
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type {
|
||||
ExtensionAPI,
|
||||
ExtensionCommandContext,
|
||||
ExtensionContext,
|
||||
MessageRenderer,
|
||||
SessionStartEvent,
|
||||
} from "@oh-my-pi/pi-coding-agent";
|
||||
import { Box, Text } from "@oh-my-pi/pi-tui";
|
||||
import { registerCheck, type CheckDefinition } from "./checks/registry.js";
|
||||
import { registerPygieniumCommands, type PygieniumCtx } from "./commands.js";
|
||||
import {
|
||||
type SendChatMessage,
|
||||
type CheckCompletionDetails,
|
||||
PHASE_GLYPH,
|
||||
} from "./phases.js";
|
||||
import type { AgentSessionEvent } from "@oh-my-pi/pi-coding-agent";
|
||||
|
||||
/** Startup hint mirrored after piolium's convention. */
|
||||
export const PYGIENIUM_STARTUP_HINT =
|
||||
"Pygienium loaded. Run /pygienium-help for available checks and flags.";
|
||||
|
||||
/** Custom message type for the live tool-event stream (mirrors piolium-stream). */
|
||||
export const PYGIENIUM_STREAM = "pygienium-stream";
|
||||
|
||||
/** Chat rendering style ("verbose" = per-event stream, "compact" = completion-only). */
|
||||
export type ChatStyle = "verbose" | "compact";
|
||||
|
||||
/**
|
||||
* Read the pygienium chat style from omp's settings.json.
|
||||
* Looks for `pygienium.chatStyle` under `~/.omp/agent/settings.json`.
|
||||
* Defaults to "verbose" (piolium-style per-event stream) when absent or unreadable.
|
||||
*/
|
||||
async function readChatStyle(): Promise<ChatStyle> {
|
||||
try {
|
||||
const raw = await readFile(
|
||||
join(homedir(), ".omp", "agent", "settings.json"),
|
||||
"utf8",
|
||||
);
|
||||
const settings = JSON.parse(raw) as {
|
||||
pygienium?: { chatStyle?: string };
|
||||
};
|
||||
const style = settings.pygienium?.chatStyle;
|
||||
return style === "compact" ? "compact" : "verbose";
|
||||
} catch {
|
||||
return "verbose";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Local structural supertypes for the progress-message renderer params.
|
||||
* These avoid relying on contextual typing from `MessageRenderer` (which
|
||||
* requires resolving pi's internal `Theme`/`CustomMessage` cross-references
|
||||
* via node_modules — not always available in dev environments). Using
|
||||
* `(...args: any[])` for theme methods makes the type bidirectionally
|
||||
* compatible under strict function types, so the cast to `MessageRenderer`
|
||||
* in `registerMessageRenderer` is valid.
|
||||
*/
|
||||
interface ProgressMessage {
|
||||
content: unknown;
|
||||
details?: unknown;
|
||||
}
|
||||
interface ProgressRenderOptions {
|
||||
expanded: boolean;
|
||||
}
|
||||
interface ProgressTheme {
|
||||
fg: (...args: any[]) => string;
|
||||
bg: (...args: any[]) => string;
|
||||
}
|
||||
|
||||
export { buildPygieniumHelpLines } from "./help.js";
|
||||
|
||||
type StreamLineKind = "tool-start" | "tool-end" | "tool-error" | "assistant";
|
||||
|
||||
interface StreamLineDetails {
|
||||
kind: StreamLineKind;
|
||||
phase: string;
|
||||
toolName?: string;
|
||||
body?: string;
|
||||
}
|
||||
|
||||
/** Pick the one useful argument from a tool-call's args (path/command/…). */
|
||||
function summarizeArgs(args: unknown): string {
|
||||
if (!args || typeof args !== "object") return "";
|
||||
const obj = args as Record<string, unknown>;
|
||||
const pickKey = [
|
||||
"file_path",
|
||||
"path",
|
||||
"command",
|
||||
"pattern",
|
||||
"query",
|
||||
"url",
|
||||
].find((k) => typeof obj[k] === "string");
|
||||
if (pickKey) {
|
||||
const value = String(obj[pickKey]);
|
||||
return value.length > 120 ? `${value.slice(0, 117)}…` : value;
|
||||
}
|
||||
const json = JSON.stringify(obj);
|
||||
return json.length > 120 ? `${json.slice(0, 117)}…` : json;
|
||||
}
|
||||
|
||||
/** Extract joined text from an assistant message's content blocks. */
|
||||
function extractAssistantText(content: unknown): string {
|
||||
if (typeof content === "string") return content;
|
||||
if (!Array.isArray(content)) return "";
|
||||
return content
|
||||
.filter(
|
||||
(c) =>
|
||||
c && typeof c === "object" && (c as { type?: string }).type === "text",
|
||||
)
|
||||
.map((c) => (c as { text?: string }).text ?? "")
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Collapse a tool result down to a single short line. */
|
||||
function summarizeToolResult(result: unknown): string {
|
||||
if (result == null) return "";
|
||||
if (typeof result === "string") return result;
|
||||
if (typeof result === "number" || typeof result === "boolean")
|
||||
return String(result);
|
||||
if (Array.isArray(result)) {
|
||||
return result
|
||||
.map((item) => {
|
||||
if (typeof item === "string") return item;
|
||||
if (
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
"text" in (item as Record<string, unknown>)
|
||||
)
|
||||
return String((item as { text?: unknown }).text ?? "");
|
||||
return JSON.stringify(item);
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
if (typeof result !== "object") return "";
|
||||
const obj = result as Record<string, unknown>;
|
||||
// MCP CallToolResult shape: { content: [{ type: "text", text: "..." }, ...] }
|
||||
if (Array.isArray(obj.content)) {
|
||||
const unwrapped = summarizeToolResult(obj.content);
|
||||
if (unwrapped) return unwrapped;
|
||||
}
|
||||
const preferKey = ["stdout", "output", "text", "content", "result"].find(
|
||||
(k) => typeof obj[k] === "string" && (obj[k] as string).length > 0,
|
||||
);
|
||||
if (preferKey) return obj[preferKey] as string;
|
||||
try {
|
||||
return JSON.stringify(obj);
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** Collapse whitespace and cap a line at `max` chars with an ellipsis. */
|
||||
function compactLine(text: string, max: number): string {
|
||||
const collapsed = text.replace(/\s+/g, " ").trim();
|
||||
if (collapsed.length <= max) return collapsed;
|
||||
return `${collapsed.slice(0, max - 1)}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat stream forwarder: turns raw sub-agent events into `pygienium-stream`
|
||||
* messages (one chat line per start/end/assistant turn), the pygienium
|
||||
* analogue of piolium's `makeAgentEventForwarder`. Also exposes
|
||||
* `sendPhaseLine` for synthetic progress lines during non-agent phases
|
||||
* (verify, cleanup, recon) so the chat doesn't go silent.
|
||||
*/
|
||||
interface StreamForwarder {
|
||||
/** Forward a raw sub-agent event tagged with a phase label. */
|
||||
onAgentEvent(phase: string, event: AgentSessionEvent): void;
|
||||
/** Emit a synthetic progress line (e.g. "checking artifacts…"). */
|
||||
sendPhaseLine(phase: string, text: string): void;
|
||||
}
|
||||
|
||||
function makeStreamForwarder(pi: ExtensionAPI): StreamForwarder {
|
||||
const send = (details: StreamLineDetails, fallback: string) => {
|
||||
pi.sendMessage<StreamLineDetails>({
|
||||
customType: PYGIENIUM_STREAM,
|
||||
content: fallback,
|
||||
display: true,
|
||||
details,
|
||||
});
|
||||
};
|
||||
|
||||
const onAgentEvent = (phase: string, event: AgentSessionEvent): void => {
|
||||
switch (event.type) {
|
||||
case "tool_execution_start": {
|
||||
const body = summarizeArgs(event.args);
|
||||
send(
|
||||
{ kind: "tool-start", phase, toolName: event.toolName, body },
|
||||
`[${phase}] → ${event.toolName}${body ? ` ${body}` : ""}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "tool_execution_end": {
|
||||
const body = compactLine(summarizeToolResult(event.result), 200);
|
||||
const kind: StreamLineKind = event.isError ? "tool-error" : "tool-end";
|
||||
const marker = event.isError ? "✗" : "←";
|
||||
send(
|
||||
{ kind, phase, toolName: event.toolName, body },
|
||||
`[${phase}] ${marker} ${event.toolName}${body ? ` ${body}` : ""}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "message_end": {
|
||||
const message = event.message as {
|
||||
role?: string;
|
||||
content?: unknown;
|
||||
};
|
||||
if (message.role !== "assistant") return;
|
||||
const text = extractAssistantText(message.content).trim();
|
||||
if (!text) return;
|
||||
const head = compactLine(text, 240);
|
||||
send({ kind: "assistant", phase, body: head }, `[${phase}] ${head}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const sendPhaseLine = (phase: string, text: string): void => {
|
||||
send({ kind: "assistant", phase, body: text }, `[${phase}] ${text}`);
|
||||
};
|
||||
|
||||
return { onAgentEvent, sendPhaseLine };
|
||||
}
|
||||
|
||||
/**
|
||||
* Import every `checks/*.ts` module (except the registry barrel) and register
|
||||
* each file's `check` export. Check files are pure data modules — they no
|
||||
* longer self-register on import, because omp's extension loader cache-busts
|
||||
* lazily imported graph modules with an `?mtime` suffix, which would split
|
||||
* the registry into two module instances (static entry-graph imports resolve
|
||||
* to the clean file, lazy imports to the `?mtime` copy). Registering here —
|
||||
* from the entry's own registry instance — keeps one registry and still makes
|
||||
* adding a check a drop-a-file operation.
|
||||
*/
|
||||
async function loadCheckModules(): Promise<void> {
|
||||
const dir = join(dirname(fileURLToPath(import.meta.url)), "checks");
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await readdir(dir);
|
||||
} catch {
|
||||
return; // no checks dir (e.g. minimal install)
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.endsWith(".ts")) continue;
|
||||
if (entry === "registry.ts" || entry === "load.ts") continue;
|
||||
const mod = (await import(`./checks/${entry}`)) as {
|
||||
check?: CheckDefinition;
|
||||
};
|
||||
if (mod.check) registerCheck(mod.check);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a callback to send completion messages to the main chat window.
|
||||
*/
|
||||
function makeSendChatMessage(pi: ExtensionAPI): SendChatMessage {
|
||||
return (content: string, meta?: Record<string, unknown>) => {
|
||||
pi.sendMessage({
|
||||
customType: "pygienium-progress",
|
||||
content,
|
||||
display: true,
|
||||
details: {
|
||||
phase: meta?.phase || "info",
|
||||
...meta,
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
export default async function pygieniumExtension(
|
||||
pi: ExtensionAPI,
|
||||
): Promise<void> {
|
||||
// Self-register every shipped check before wiring commands.
|
||||
await loadCheckModules();
|
||||
|
||||
const sendChatMessage = makeSendChatMessage(pi);
|
||||
|
||||
// Register custom message renderer for pygienium progress messages.
|
||||
// Renders an expandable phase tree: collapsed shows the header + a hint,
|
||||
// expanded (Ctrl+O) shows every phase with its status and notes.
|
||||
const progressRenderer = (
|
||||
message: ProgressMessage,
|
||||
{ expanded }: ProgressRenderOptions,
|
||||
theme: ProgressTheme,
|
||||
) => {
|
||||
const details = message.details as
|
||||
| {
|
||||
phase?: string;
|
||||
completion?: CheckCompletionDetails;
|
||||
error?: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(String(message.content));
|
||||
|
||||
const completion = details?.completion;
|
||||
if (completion) {
|
||||
if (expanded) {
|
||||
// Expanded: show every phase with status glyph + branch.
|
||||
const phases = completion.phases;
|
||||
for (let i = 0; i < phases.length; i++) {
|
||||
const entry = phases[i];
|
||||
if (!entry) continue;
|
||||
const isLast = i === phases.length - 1;
|
||||
const branch = isLast ? " └── " : " ├── ";
|
||||
const glyph = PHASE_GLYPH[entry.status] ?? "?";
|
||||
const tag = theme.fg("accent", entry.label);
|
||||
const note = entry.note ? ` · ${entry.note}` : "";
|
||||
lines.push(`${branch}${glyph} ${tag}${note}`);
|
||||
}
|
||||
if (completion.error) {
|
||||
lines.push(theme.fg("error", ` error: ${completion.error}`));
|
||||
}
|
||||
} else {
|
||||
// Collapsed: summary line + hint.
|
||||
const done = completion.phases.filter(
|
||||
(p) => p.status === "complete",
|
||||
).length;
|
||||
const total = completion.phases.length;
|
||||
const hint = completion.error
|
||||
? theme.fg("error", ` ├── ${completion.error}`)
|
||||
: theme.fg(
|
||||
"dim",
|
||||
` ├── ${done}/${total} phases · press Ctrl+O for detail`,
|
||||
);
|
||||
lines.push(hint);
|
||||
}
|
||||
} else if (!expanded) {
|
||||
lines.push(theme.fg("dim", " ├── press Ctrl+O for detail"));
|
||||
}
|
||||
|
||||
const text = lines.join("\n");
|
||||
const box = new Box(1, 1, (t: string) => theme.bg("customMessageBg", t));
|
||||
box.addChild(new Text(text, 0, 0));
|
||||
return box;
|
||||
};
|
||||
pi.registerMessageRenderer(
|
||||
"pygienium-progress",
|
||||
progressRenderer as MessageRenderer,
|
||||
);
|
||||
|
||||
// Live tool-event stream renderer: one chat line per tool start/end and
|
||||
// assistant turn, indented so ends nest under their start. Mirrors
|
||||
// piolium's PIOLIUM_STREAM renderer.
|
||||
pi.registerMessageRenderer<StreamLineDetails>(
|
||||
PYGIENIUM_STREAM,
|
||||
(message, _options, theme) => {
|
||||
const details = message.details;
|
||||
if (!details || typeof details !== "object") {
|
||||
const fallback =
|
||||
typeof message.content === "string" ? message.content : "";
|
||||
return new Text(theme.fg("muted", fallback), 0, 0);
|
||||
}
|
||||
const { kind, phase, toolName, body } = details;
|
||||
// Indent end/error lines so they visually nest under the matching
|
||||
// start line. The pad width matches the "[phase] " prefix.
|
||||
const phaseTag = theme.fg("accent", `[${phase}]`);
|
||||
const indent = " ".repeat(phase.length + 3);
|
||||
let line: string;
|
||||
switch (kind) {
|
||||
case "tool-start": {
|
||||
const arrow = theme.fg("muted", "→");
|
||||
const name = theme.fg("toolTitle", theme.bold(toolName ?? ""));
|
||||
const args = body ? ` ${theme.fg("muted", body)}` : "";
|
||||
line = `${phaseTag} ${arrow} ${name}${args}`;
|
||||
break;
|
||||
}
|
||||
case "tool-end": {
|
||||
const arrow = theme.fg("success", "←");
|
||||
const result = body
|
||||
? ` ${theme.fg("dim", body)}`
|
||||
: ` ${theme.fg("dim", "(ok)")}`;
|
||||
line = `${indent}${arrow}${result}`;
|
||||
break;
|
||||
}
|
||||
case "tool-error": {
|
||||
const marker = theme.fg("error", "✗");
|
||||
const result = body
|
||||
? ` ${theme.fg("error", body)}`
|
||||
: ` ${theme.fg("error", "failed")}`;
|
||||
line = `${indent}${marker}${result}`;
|
||||
break;
|
||||
}
|
||||
case "assistant":
|
||||
line = `${phaseTag} ${theme.fg("muted", body ?? "")}`;
|
||||
break;
|
||||
default:
|
||||
line =
|
||||
typeof message.content === "string"
|
||||
? theme.fg("muted", message.content)
|
||||
: "";
|
||||
}
|
||||
return new Text(line, 0, 0);
|
||||
},
|
||||
);
|
||||
|
||||
const forwarder = makeStreamForwarder(pi);
|
||||
|
||||
// Read chat style from pi's settings.json. When "compact", suppress the
|
||||
// per-event stream + synthetic phase lines so only the completion message
|
||||
// (with its expandable phase tree) shows — the ralpi-style rendering.
|
||||
const chatStyle = await readChatStyle();
|
||||
const verbose = chatStyle === "verbose";
|
||||
const onAgentEvent = verbose ? forwarder.onAgentEvent : undefined;
|
||||
const sendPhaseLine = verbose ? forwarder.sendPhaseLine : undefined;
|
||||
|
||||
registerPygieniumCommands((name, options) => {
|
||||
pi.registerCommand(name, {
|
||||
description: options.description,
|
||||
handler: (args: string, ctx: ExtensionCommandContext) => {
|
||||
// Create PygieniumCtx with chat + stream callbacks.
|
||||
const pygieniumCtx: PygieniumCtx = {
|
||||
cwd: ctx.cwd,
|
||||
hasUI: ctx.hasUI,
|
||||
ui: ctx.ui,
|
||||
sendChatMessage,
|
||||
onAgentEvent,
|
||||
sendPhaseLine,
|
||||
};
|
||||
return options.handler(args, pygieniumCtx);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
pi.on(
|
||||
"session_start",
|
||||
async (_event: SessionStartEvent, ctx: ExtensionContext) => {
|
||||
if (!ctx.hasUI) return;
|
||||
ctx.ui.notify(PYGIENIUM_STARTUP_HINT, "info");
|
||||
},
|
||||
);
|
||||
}
|
||||
0
src/modes/.gitkeep
Normal file
0
src/modes/.gitkeep
Normal file
463
src/modes/all.ts
Normal file
463
src/modes/all.ts
Normal file
@@ -0,0 +1,463 @@
|
||||
/**
|
||||
* modes/all.ts — `/pygienium-all` master orchestrator.
|
||||
*
|
||||
* Runs every registered check in sequence as ordered phases under a unified
|
||||
* status strip, with resumable state and a final summary report. This is the
|
||||
* piolium "balanced"/"deep" mode analogue, but simpler: one run, sequential
|
||||
* phases, shared recon (no scheduler — checks run one after another).
|
||||
*
|
||||
* Pipeline:
|
||||
* init single run (mode "all") → run shared recon once →
|
||||
* for each registered check (in registry order): call `runCheck` with the
|
||||
* SHARED run-state record (not a fresh one per check) → reconcile run
|
||||
* status → write `.pygienium/all-summary.md`.
|
||||
*
|
||||
* Resumability: terminal checks (`complete`/`skipped`) are skipped on resume;
|
||||
* `in_progress`/`failed`/`pending` checks re-run. `--fresh` resets every check
|
||||
* entry and re-runs the lot. `--only=comments,complexity` narrows the candidate
|
||||
* set to a named subset (registration order preserved).
|
||||
*
|
||||
* @module pygienium/modes/all
|
||||
*/
|
||||
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import type { ExtensionUIContext } from "@oh-my-pi/pi-coding-agent";
|
||||
import { getAllChecks, type CheckDefinition } from "../checks/registry.js";
|
||||
import { runCheck } from "./check-runner.js";
|
||||
import type { AgentSessionEvent } from "@oh-my-pi/pi-coding-agent";
|
||||
import { createPhaseStrip, type SendChatMessage } from "../phases.js";
|
||||
import { createPipelineFooter, type ItemStatus } from "../footer.js";
|
||||
import { runRecon } from "../recon.js";
|
||||
import {
|
||||
applyPhaseStatus,
|
||||
ensureRunStateIgnored,
|
||||
initRunState,
|
||||
loadRunState,
|
||||
markRunStatus,
|
||||
PHASE_RECON,
|
||||
reconcileRunStatus,
|
||||
resetCheckEntry,
|
||||
saveRunState,
|
||||
shouldRunOnResume,
|
||||
stateDir,
|
||||
type RunState,
|
||||
} from "../run-state.js";
|
||||
|
||||
/** Artifact directory name (relative to cwd) that holds `all-summary.md`. */
|
||||
export const ALL_ARTIFACT_DIR = ".pygienium";
|
||||
/** Filename for the unified per-check summary report. */
|
||||
export const ALL_SUMMARY_FILENAME = "all-summary.md";
|
||||
|
||||
/** Resolve `<cwd>/.pygienium/all-summary.md`. */
|
||||
export function allSummaryPath(cwd: string): string {
|
||||
return join(cwd, ALL_ARTIFACT_DIR, ALL_SUMMARY_FILENAME);
|
||||
}
|
||||
|
||||
export interface AllRunOptions {
|
||||
/** Working directory (from `ctx.cwd`). */
|
||||
cwd: string;
|
||||
/** Target path to scan (absolute; defaults to `cwd`). */
|
||||
target?: string;
|
||||
/** Whether fixes should be applied (`--fix`). */
|
||||
fix?: boolean;
|
||||
/** Subset of check names to run (`--only=comments,complexity`). */
|
||||
only?: string[];
|
||||
/** Reset and re-run every check, ignoring prior terminal state (`--fresh`). */
|
||||
fresh?: boolean;
|
||||
/**
|
||||
* Ensure `<cwd>/.gitignore` excludes `.pygienium/` before this run writes
|
||||
* state/artifacts (default true). Set false with `--no-gitignore`.
|
||||
*/
|
||||
gitignore?: boolean;
|
||||
/** UI context (optional; null in print mode). */
|
||||
ui?: ExtensionUIContext;
|
||||
/** Whether dialog-capable UI is available. */
|
||||
hasUI?: boolean;
|
||||
/** Optional callback to post completion messages into the chat. */
|
||||
sendChatMessage?: SendChatMessage;
|
||||
/** Optional callback forwarding raw sub-agent events to the chat stream. */
|
||||
onAgentEvent?: (phase: string, event: AgentSessionEvent) => void;
|
||||
/** Optional callback to emit synthetic progress lines during non-agent
|
||||
* phases (verify, cleanup, recon) into the chat stream. */
|
||||
sendPhaseLine?: (phase: string, text: string) => void;
|
||||
}
|
||||
|
||||
/** Outcome of {@link runAllChecks}. */
|
||||
export interface AllRunOutcome {
|
||||
/** Final run status. */
|
||||
status: RunState["status"];
|
||||
/** The updated run state. */
|
||||
state: RunState;
|
||||
/** Absolute path the summary was written to. */
|
||||
summaryPath: string;
|
||||
/** Checks that were actually dispatched (ran `runCheck`). */
|
||||
ran: string[];
|
||||
/** Checks skipped because they were already terminal. */
|
||||
skipped: string[];
|
||||
/** True when this run appended `.pygienium/` to the repo's .gitignore. */
|
||||
gitignoreAppended?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the registry to the `only` subset, preserving insertion order.
|
||||
* Unknown names are silently dropped (a typo shouldn't abort an all-run).
|
||||
*/
|
||||
export function selectChecks(only?: string[]): CheckDefinition[] {
|
||||
const all = getAllChecks();
|
||||
if (!only || only.length === 0) return all;
|
||||
const set = new Set(only);
|
||||
return all.filter((c) => set.has(c.name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `/pygienium-all` args: an optional `[path]` positional plus the
|
||||
* `--fix`, `--fresh`, and `--only=<a>,<b>` flags.
|
||||
*/
|
||||
export function parseAllArgs(
|
||||
args: string,
|
||||
cwd: string,
|
||||
): {
|
||||
target: string;
|
||||
fix: boolean;
|
||||
fresh: boolean;
|
||||
gitignore: boolean;
|
||||
only: string[];
|
||||
} {
|
||||
const tokens = args.trim().length > 0 ? args.trim().split(/\s+/) : [];
|
||||
let fix = false;
|
||||
let fresh = false;
|
||||
let gitignore = true;
|
||||
let target = cwd;
|
||||
const only: string[] = [];
|
||||
for (const tok of tokens) {
|
||||
if (tok === "--fix") {
|
||||
fix = true;
|
||||
} else if (tok === "--fresh") {
|
||||
fresh = true;
|
||||
} else if (tok === "--no-gitignore") {
|
||||
gitignore = false;
|
||||
} else if (tok.startsWith("--only=")) {
|
||||
for (const name of tok.slice("--only=".length).split(",")) {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed) only.push(trimmed);
|
||||
}
|
||||
} else if (!tok.startsWith("--")) {
|
||||
target = tok;
|
||||
}
|
||||
}
|
||||
return { target: resolve(cwd, target), fix, fresh, gitignore, only };
|
||||
}
|
||||
|
||||
/** Count non-empty lines in captured findings/changes text. */
|
||||
function lineCount(text: string | undefined): number {
|
||||
if (!text) return 0;
|
||||
return text.split(/\r?\n/).filter((l) => l.trim().length > 0).length;
|
||||
}
|
||||
|
||||
function toISO(ms: number | undefined): string {
|
||||
return ms == null ? "—" : new Date(ms).toISOString();
|
||||
}
|
||||
|
||||
function short(status: string): string {
|
||||
return status[0]?.toUpperCase() ?? "?";
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the unified summary markdown from run-state. Lists per-check
|
||||
* outcomes: status, artifact paths (when present on disk), findings/changes
|
||||
* line counts, phase breakdown, and errors.
|
||||
*/
|
||||
export function renderAllSummary(
|
||||
state: RunState,
|
||||
selected: CheckDefinition[],
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
lines.push("# Pygienium all-run summary");
|
||||
lines.push("");
|
||||
lines.push(`- status: ${state.status}`);
|
||||
lines.push(`- started: ${toISO(state.startedAt)}`);
|
||||
lines.push(`- updated: ${toISO(state.updatedAt)}`);
|
||||
lines.push(`- cwd: ${state.cwd}`);
|
||||
lines.push(`- recon: ${state.recon.complete ? "complete" : "pending"}`);
|
||||
lines.push(`- checks: ${selected.length}`);
|
||||
lines.push("");
|
||||
|
||||
for (const check of selected) {
|
||||
const entry = state.checks[check.name];
|
||||
const fixTag = entry?.fix ? " (--fix)" : "";
|
||||
lines.push(`## ${check.name} — ${entry?.status ?? "pending"}${fixTag}`);
|
||||
lines.push("");
|
||||
|
||||
// Errors are terminal-run facts: a check that completed via a later
|
||||
// resume/retry must not surface a stale error under a "complete"
|
||||
// status (markCheckStatus clears it on success; this guard covers
|
||||
// hand-edited or legacy state files too).
|
||||
if (entry?.error && entry?.status !== "complete") {
|
||||
lines.push(`- error: ${entry.error}`);
|
||||
}
|
||||
|
||||
// Artifact paths (canonical root: `.pygienium/checks/<name>/`).
|
||||
const findingsPath = `${state.cwd}/.pygienium/checks/${check.name}/findings.md`;
|
||||
const changesPath = `${state.cwd}/.pygienium/checks/${check.name}/changes.md`;
|
||||
const fLines = lineCount(entry?.findings);
|
||||
const cLines = lineCount(entry?.changes);
|
||||
if (fLines > 0) {
|
||||
lines.push(`- findings: ${findingsPath} (${fLines} line(s))`);
|
||||
}
|
||||
if (cLines > 0) {
|
||||
lines.push(`- changes: ${changesPath} (${cLines} line(s))`);
|
||||
}
|
||||
|
||||
// Phase breakdown for transparency.
|
||||
if (entry?.phases?.length) {
|
||||
const phaseSummary = entry.phases
|
||||
.map(
|
||||
(p) =>
|
||||
`${p.id}:${
|
||||
p.status.startsWith("in_progress") ? "…" : short(p.status)
|
||||
}`,
|
||||
)
|
||||
.join(" ");
|
||||
lines.push(`- phases: ${phaseSummary}`);
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
return lines.join("\n") + "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Run every registered check in sequence under a unified status strip.
|
||||
*
|
||||
* Resumable: terminal checks skip on resume unless `fresh` resets them.
|
||||
*/
|
||||
export async function runAllChecks(
|
||||
opts: AllRunOptions,
|
||||
): Promise<AllRunOutcome> {
|
||||
const { cwd } = opts;
|
||||
const target = opts.target ?? cwd;
|
||||
const fix = opts.fix ?? false;
|
||||
const fresh = opts.fresh ?? false;
|
||||
const hasUI = opts.hasUI ?? false;
|
||||
|
||||
// Keep pygienium's own output out of the scanned repo's git index unless
|
||||
// the caller opted out with --no-gitignore.
|
||||
const gitignoreAppended =
|
||||
opts.gitignore === false ? false : await ensureRunStateIgnored(cwd);
|
||||
|
||||
const selected = selectChecks(opts.only);
|
||||
if (selected.length === 0) {
|
||||
// `--only` selected nothing (or no checks registered). Still produce a
|
||||
// summary so the caller has an artifact.
|
||||
const state = (await loadRunState(cwd)) ?? initRunState(cwd, []);
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
const summaryPath = await writeAllSummary(state, []);
|
||||
return {
|
||||
status: state.status,
|
||||
state,
|
||||
summaryPath,
|
||||
ran: [],
|
||||
skipped: [],
|
||||
gitignoreAppended,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Init / resume the single shared run-state --------------------------
|
||||
let state =
|
||||
(await loadRunState(cwd)) ??
|
||||
initRunState(
|
||||
cwd,
|
||||
selected.map((c) => ({ name: c.name, label: c.label, fix })),
|
||||
);
|
||||
|
||||
// Ensure every selected check has an entry (adds any missing on resume).
|
||||
for (const check of selected) {
|
||||
if (!state.checks[check.name]) {
|
||||
state.checks[check.name] = {
|
||||
name: check.name,
|
||||
label: check.label,
|
||||
status: "pending",
|
||||
fix,
|
||||
phases: [
|
||||
{ id: "recon", status: "pending" },
|
||||
{ id: "analysis", status: "pending" },
|
||||
...(fix ? [{ id: "fix", status: "pending" as const }] : []),
|
||||
{ id: "verify", status: "pending" },
|
||||
{ id: "cleanup", status: "pending" },
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
await saveRunState(state);
|
||||
|
||||
// --- Unified phase strip logging all check names -----------------------
|
||||
const strip = createPhaseStrip({
|
||||
ui: opts.ui,
|
||||
hasUI,
|
||||
});
|
||||
setAllPhase(strip, selected, 0, "recon");
|
||||
|
||||
// Pipeline-overview footer: a multi-line widget listing every check with the
|
||||
// cursor on the active one and what's to come. Detail lives in the chat
|
||||
// (per-check completion trees); the footer is the overview. Inner
|
||||
// `runCheck` calls pass `footer: false` so two overviews never compete.
|
||||
const allFooter = createPipelineFooter({
|
||||
ui: opts.ui,
|
||||
hasUI,
|
||||
statusKey: "pygienium-all",
|
||||
});
|
||||
const allItems = selected.map((c) => ({
|
||||
label: c.label,
|
||||
status: "pending" as ItemStatus,
|
||||
}));
|
||||
allFooter.setPipeline("pygienium: all", allItems, 0);
|
||||
const footerSettle = (name: string, status: ItemStatus): void => {
|
||||
const idx = selected.findIndex((c) => c.name === name);
|
||||
if (idx >= 0) allFooter.setItem(idx, status);
|
||||
};
|
||||
|
||||
// --- Shared recon (run once before any check) ---------------------------
|
||||
if (!state.recon.complete) {
|
||||
const snapshot = await runRecon(cwd);
|
||||
state.recon = {
|
||||
complete: true,
|
||||
path: join(stateDir(cwd), "recon.json"),
|
||||
finishedAt: snapshot.createdAt,
|
||||
};
|
||||
// Mark recon complete for every selected check that hasn't run it yet.
|
||||
for (const check of selected) {
|
||||
applyPhaseStatus(state, check.name, PHASE_RECON, "complete");
|
||||
}
|
||||
await saveRunState(state);
|
||||
}
|
||||
|
||||
const ran: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
|
||||
// --- Per-check loop (shared run-state, registry order) ------------------
|
||||
for (let i = 0; i < selected.length; i++) {
|
||||
const check = selected[i]!;
|
||||
setAllPhase(strip, selected, i, "analysis");
|
||||
allFooter.setCursor(i);
|
||||
|
||||
const entry = state.checks[check.name];
|
||||
// Resumability: skip terminal checks unless --fresh.
|
||||
if (entry && !shouldRunOnResume(entry, fresh)) {
|
||||
skipped.push(check.name);
|
||||
footerSettle(
|
||||
check.name,
|
||||
entry.status === "complete" ? "skipped" : "skipped",
|
||||
);
|
||||
strip.log(
|
||||
`pygienium: ${check.label} — already ${entry.status}, skipping`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (fresh && entry) {
|
||||
resetCheckEntry(state, check.name, fix);
|
||||
await saveRunState(state);
|
||||
}
|
||||
|
||||
strip.log(`pygienium: running ${check.label}…`);
|
||||
const outcome = await runCheck({
|
||||
check,
|
||||
cwd,
|
||||
scope: { cwd, target, fix, rest: [] },
|
||||
ui: opts.ui,
|
||||
hasUI,
|
||||
existingState: state,
|
||||
sendChatMessage: opts.sendChatMessage,
|
||||
onAgentEvent: opts.onAgentEvent,
|
||||
sendPhaseLine: opts.sendPhaseLine,
|
||||
// The all-run footer already owns the pipeline-overview widget
|
||||
// slot; suppress the per-check footer so two overviews never
|
||||
// compete over the same `belowEditor` area.
|
||||
footer: false,
|
||||
// Inner runs must not prime the .gitignore twice — the outer all-run
|
||||
// already ensured it. (ensureRunStateIgnored is memoized per cwd,
|
||||
// so this is belt-and-braces.)
|
||||
gitignore: opts.gitignore,
|
||||
});
|
||||
state = outcome.state;
|
||||
ran.push(check.name);
|
||||
footerSettle(
|
||||
check.name,
|
||||
outcome.status === "complete"
|
||||
? "complete"
|
||||
: outcome.status === "skipped"
|
||||
? "skipped"
|
||||
: "failed",
|
||||
);
|
||||
strip.log(`pygienium ${check.label}: ${outcome.status}`);
|
||||
}
|
||||
|
||||
// --- Finalize -----------------------------------------------------------
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
|
||||
setAllPhase(strip, selected, selected.length - 1, "cleanup");
|
||||
// Mark the final check's footer status terminal; the cursor started at 0
|
||||
// and the loop advanced it, so the last selected item is the live one.
|
||||
if (selected.length > 0) {
|
||||
footerSettle(
|
||||
selected[selected.length - 1]!.name,
|
||||
state.checks[selected[selected.length - 1]!.name]?.status === "failed"
|
||||
? "failed"
|
||||
: "complete",
|
||||
);
|
||||
}
|
||||
strip.done();
|
||||
allFooter.done();
|
||||
|
||||
const summaryPath = await writeAllSummary(state, selected);
|
||||
|
||||
return {
|
||||
status: state.status,
|
||||
state,
|
||||
summaryPath,
|
||||
ran,
|
||||
skipped,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the unified strip to reflect which check is active and its phase.
|
||||
* Renders `pygienium: all [i/N] <check-label>: <phase>` so every check name is
|
||||
* surfaced in the strip over the course of the run.
|
||||
*/
|
||||
function setAllPhase(
|
||||
strip: ReturnType<typeof createPhaseStrip>,
|
||||
selected: CheckDefinition[],
|
||||
index: number,
|
||||
phaseId: string,
|
||||
): void {
|
||||
const check = selected[index];
|
||||
const label = check?.label ?? "(none)";
|
||||
const total = selected.length;
|
||||
const pos = String(index + 1);
|
||||
const phaseLabel = PHASE_ALL_LABELS[phaseId] ?? phaseId;
|
||||
strip.setPhase(`all [${pos}/${total}] ${label}: ${phaseLabel}`);
|
||||
}
|
||||
|
||||
const PHASE_ALL_LABELS: Record<string, string> = {
|
||||
recon: "Recon",
|
||||
analysis: "Scanning",
|
||||
fix: "Fixing",
|
||||
verify: "Verifying",
|
||||
cleanup: "Done",
|
||||
};
|
||||
|
||||
/** Write the all-summary.md report, creating the directory as needed. */
|
||||
async function writeAllSummary(
|
||||
state: RunState,
|
||||
selected: CheckDefinition[],
|
||||
): Promise<string> {
|
||||
const path = allSummaryPath(state.cwd);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, renderAllSummary(state, selected), "utf8");
|
||||
return path;
|
||||
}
|
||||
525
src/modes/check-runner.ts
Normal file
525
src/modes/check-runner.ts
Normal file
@@ -0,0 +1,525 @@
|
||||
/**
|
||||
* modes/check-runner.ts — orchestrates a single check run.
|
||||
*
|
||||
* Pipeline:
|
||||
* init/resolve run-state → Q0 recon (shared, once) →
|
||||
* analysis sub-agent (buildScanTask) → fix sub-agent (buildFixTask, only
|
||||
* with --fix) → verify gate → cleanup transient artifacts.
|
||||
*
|
||||
* Every phase is recorded on the persisted run-state via `run-state.ts`, so
|
||||
* `/pygienium-status`, `/pygienium-resume`, and `/pygienium-export` reflect
|
||||
* real progress. The check-runner is check-agnostic: a `CheckDefinition`
|
||||
* supplies the task builders and gate; this module only wires the phases
|
||||
* together.
|
||||
*
|
||||
* @module pygienium/modes/check-runner
|
||||
*/
|
||||
|
||||
import { rm } from "node:fs/promises";
|
||||
import { resolve, join } from "node:path";
|
||||
import type { ExtensionUIContext } from "@oh-my-pi/pi-coding-agent";
|
||||
import type { CheckDefinition, CheckScope } from "../checks/registry.js";
|
||||
import { runAgentTask } from "../agent-runner.js";
|
||||
import { runRecon } from "../recon.js";
|
||||
import {
|
||||
createPhaseStrip,
|
||||
type SendChatMessage,
|
||||
type CheckCompletionDetails,
|
||||
type PhaseLogEntry,
|
||||
type PhaseLogStatus,
|
||||
PHASE_LABELS,
|
||||
} from "../phases.js";
|
||||
import type { AgentSessionEvent } from "@oh-my-pi/pi-coding-agent";
|
||||
import { createPipelineFooter, footerPhaseItems } from "../footer.js";
|
||||
import {
|
||||
applyPhaseStatus,
|
||||
ensureRunStateIgnored,
|
||||
initRunState,
|
||||
loadRunState,
|
||||
markCheckStatus,
|
||||
markRunStatus,
|
||||
PHASE_ANALYSIS,
|
||||
PHASE_CLEANUP,
|
||||
PHASE_FIX,
|
||||
PHASE_RECON,
|
||||
PHASE_VERIFY,
|
||||
phasesForCheck,
|
||||
recordCheckOutput,
|
||||
reconcileRunStatus,
|
||||
saveRunState,
|
||||
stateDir,
|
||||
type RunState,
|
||||
} from "../run-state.js";
|
||||
|
||||
/** Resolve a raw arg string into a check scope (target path + flags). */
|
||||
export function parseCheckArgs(raw: string, cwd: string): CheckScope {
|
||||
const tokens = raw.trim().length > 0 ? raw.trim().split(/\s+/) : [];
|
||||
let fix = false;
|
||||
let target = cwd;
|
||||
const rest: string[] = [];
|
||||
for (const tok of tokens) {
|
||||
if (tok === "--fix") {
|
||||
fix = true;
|
||||
} else if (tok.startsWith("--")) {
|
||||
rest.push(tok);
|
||||
} else {
|
||||
target = tok;
|
||||
}
|
||||
}
|
||||
// Absolute-ize target against cwd.
|
||||
target = resolve(cwd, target);
|
||||
return { cwd, target, fix, rest };
|
||||
}
|
||||
|
||||
export interface RunCheckOptions {
|
||||
/** The check definition to run. */
|
||||
check: CheckDefinition;
|
||||
/** Working directory (from `ctx.cwd`). */
|
||||
cwd: string;
|
||||
/** Parsed scope (target + flags). When omitted, derived from `rawArgs`. */
|
||||
scope?: CheckScope;
|
||||
/** Raw command args, used when `scope` is omitted. */
|
||||
rawArgs?: string;
|
||||
/** UI context (optional; null in print mode). */
|
||||
ui?: ExtensionUIContext;
|
||||
/** Whether dialog-capable UI is available. */
|
||||
hasUI?: boolean;
|
||||
/** Pre-existing run state to update (for `/pygienium-all` and resume). */
|
||||
existingState?: RunState;
|
||||
/** Optional callback to post completion messages into the chat. */
|
||||
sendChatMessage?: SendChatMessage;
|
||||
/**
|
||||
* Render the per-check live widget (default true). Set false when an outer
|
||||
* strip (e.g. `/pygienium-all`) already shows this check's phase, so two
|
||||
* spinners don't fight over the widget area.
|
||||
*/
|
||||
widget?: boolean;
|
||||
/**
|
||||
* Render the pipeline-overview footer status line (default true). Set false
|
||||
* when an outer run (e.g. `/pygienium-all`) already owns the footer, so two
|
||||
* overviews never compete over the same status slot.
|
||||
*/
|
||||
footer?: boolean;
|
||||
/** Optional callback that forwards raw sub-agent events to the chat
|
||||
* stream (see `pygienium-stream` in `index.ts`). */
|
||||
onAgentEvent?: (phase: string, event: AgentSessionEvent) => void;
|
||||
/** Optional callback to emit synthetic progress lines during non-agent
|
||||
* phases (verify, cleanup, recon) into the chat stream. */
|
||||
sendPhaseLine?: (phase: string, text: string) => void;
|
||||
/**
|
||||
* Ensure `<cwd>/.gitignore` excludes `.pygienium/` before this run writes
|
||||
* state/artifacts (default true). Set false with `--no-gitignore`.
|
||||
*/
|
||||
gitignore?: boolean;
|
||||
}
|
||||
|
||||
/** Outcome of a single check run. */
|
||||
export interface CheckRunOutcome {
|
||||
/** Final check status. */
|
||||
status: "complete" | "failed" | "skipped";
|
||||
/** True when this run appended `.pygienium/` to the repo's .gitignore. */
|
||||
gitignoreAppended?: boolean;
|
||||
/** Findings text from the analysis phase. */
|
||||
findings?: string;
|
||||
/** Changes text from the fix phase (when run with --fix). */
|
||||
changes?: string;
|
||||
/** Error message on failure. */
|
||||
error?: string;
|
||||
/** The updated run state. */
|
||||
state: RunState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a single check end-to-end, persisting progress to run-state, and post a
|
||||
* ralpi-style completion message into the chat (header + expandable phase
|
||||
* tree) when a `sendChatMessage` callback is supplied.
|
||||
*
|
||||
* Resumable: if `existingState` already has terminal-ish progress for this
|
||||
* check, the runner resumes the last in-progress phase rather than restarting.
|
||||
*/
|
||||
export async function runCheck(
|
||||
opts: RunCheckOptions,
|
||||
): Promise<CheckRunOutcome> {
|
||||
const startMs = Date.now();
|
||||
const outcome = await runCheckImpl(opts);
|
||||
postCheckCompletion(opts, outcome, Date.now() - startMs);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
async function runCheckImpl(opts: RunCheckOptions): Promise<CheckRunOutcome> {
|
||||
// Keep pygienium's own output out of the scanned repo's git index unless
|
||||
// the caller opted out with --no-gitignore.
|
||||
const gitignoreAppended =
|
||||
opts.gitignore === false ? false : await ensureRunStateIgnored(opts.cwd);
|
||||
const outcome = await runCheckImplInner(opts);
|
||||
return { ...outcome, gitignoreAppended };
|
||||
}
|
||||
|
||||
async function runCheckImplInner(
|
||||
opts: RunCheckOptions,
|
||||
): Promise<CheckRunOutcome> {
|
||||
const { check, cwd } = opts;
|
||||
const scope = opts.scope ?? parseCheckArgs(opts.rawArgs ?? "", cwd);
|
||||
|
||||
// Resolve or init the run state, recording this check on first sight.
|
||||
const state: RunState =
|
||||
opts.existingState ?? (await loadRunState(cwd)) ?? initRunState(cwd, []);
|
||||
if (!state.checks[check.name]) {
|
||||
state.checks[check.name] = {
|
||||
name: check.name,
|
||||
label: check.label,
|
||||
status: "pending",
|
||||
fix: scope.fix,
|
||||
phases: phasesForCheck(scope.fix),
|
||||
};
|
||||
}
|
||||
await saveRunState(state);
|
||||
|
||||
const strip = createPhaseStrip({
|
||||
ui: opts.ui,
|
||||
hasUI: opts.hasUI ?? false,
|
||||
checkLabel: check.label,
|
||||
});
|
||||
|
||||
/** Phase tag combining check label + phase label for stream lines. */
|
||||
const phaseTag = (phaseId: string): string =>
|
||||
`${check.label}: ${PHASE_LABELS[phaseId] ?? phaseId}`;
|
||||
|
||||
/** Forward a raw agent event tagged with the current phase. */
|
||||
const forward = (phaseId: string) => (event: AgentSessionEvent) =>
|
||||
opts.onAgentEvent?.(phaseTag(phaseId), event);
|
||||
|
||||
/** Emit a synthetic stream line for non-agent phases (verify/cleanup/recon). */
|
||||
const phaseLine = (phaseId: string, text: string): void =>
|
||||
opts.sendPhaseLine?.(phaseTag(phaseId), text);
|
||||
|
||||
// Pipeline-overview footer: a static one-line view of the full phase list
|
||||
// with the cursor on the current phase and what's to come. Detail lives in
|
||||
// the chat (phase strip + completion tree); the footer is the overview.
|
||||
// Disabled (no-op) when an outer run owns the footer, e.g. /pygienium-all.
|
||||
const phaseIds = (
|
||||
state.checks[check.name]?.phases ?? phasesForCheck(scope.fix)
|
||||
).map((p) => p.id);
|
||||
const footerIdx = new Map(phaseIds.map((id, i) => [id, i] as const));
|
||||
const footer = createPipelineFooter({
|
||||
ui: opts.ui,
|
||||
hasUI: opts.hasUI ?? false,
|
||||
enabled: opts.footer ?? true,
|
||||
});
|
||||
footer.setPipeline(
|
||||
`pygienium ${check.label}`,
|
||||
footerPhaseItems(phaseIds, PHASE_LABELS),
|
||||
);
|
||||
const footerEnter = (phaseId: string): void => {
|
||||
const i = footerIdx.get(phaseId);
|
||||
if (i !== undefined) footer.setCursor(i);
|
||||
};
|
||||
const footerComplete = (phaseId: string): void => {
|
||||
const i = footerIdx.get(phaseId);
|
||||
if (i !== undefined) footer.setItem(i, "complete");
|
||||
};
|
||||
|
||||
let findings = "";
|
||||
let changes = "";
|
||||
let error: string | undefined;
|
||||
|
||||
try {
|
||||
// --- Phase: gate -----------------------------------------------------
|
||||
const gateResult = await Promise.resolve(check.gate(cwd));
|
||||
if (gateResult) {
|
||||
// Skip this check entirely (no agent work).
|
||||
for (const phase of state.checks[check.name]?.phases ?? []) {
|
||||
if (phase.status === "pending") phase.status = "skipped";
|
||||
}
|
||||
for (let i = 0; i < phaseIds.length; i++) footer.setItem(i, "skipped");
|
||||
markCheckStatus(state, check.name, "skipped", gateResult);
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
strip.setPhase(PHASE_CLEANUP);
|
||||
strip.done();
|
||||
return { status: "skipped", error: gateResult, state };
|
||||
}
|
||||
|
||||
// --- Phase: recon (shared, run once per run) -------------------------
|
||||
if (!state.recon.complete) {
|
||||
strip.setPhase(PHASE_RECON);
|
||||
footerEnter(PHASE_RECON);
|
||||
applyPhaseStatus(state, check.name, PHASE_RECON, "in_progress");
|
||||
await saveRunState(state);
|
||||
phaseLine(PHASE_RECON, "scanning project structure…");
|
||||
const snapshot = await runRecon(cwd);
|
||||
state.recon = {
|
||||
complete: true,
|
||||
path: join(stateDir(cwd), "recon.json"),
|
||||
finishedAt: snapshot.createdAt,
|
||||
};
|
||||
phaseLine(PHASE_RECON, "✓ recon complete");
|
||||
applyPhaseStatus(state, check.name, PHASE_RECON, "complete");
|
||||
await saveRunState(state);
|
||||
footerComplete(PHASE_RECON);
|
||||
} else {
|
||||
// Recon already done this run — mark this check's recon complete.
|
||||
applyPhaseStatus(state, check.name, PHASE_RECON, "complete");
|
||||
footerComplete(PHASE_RECON);
|
||||
}
|
||||
|
||||
// --- Phase: analysis -------------------------------------------------
|
||||
strip.setPhase(PHASE_ANALYSIS);
|
||||
footerEnter(PHASE_ANALYSIS);
|
||||
applyPhaseStatus(state, check.name, PHASE_ANALYSIS, "in_progress");
|
||||
await saveRunState(state);
|
||||
const scanTask = await check.buildScanTask(cwd, scope);
|
||||
const scanResult = await runAgentTask({
|
||||
cwd: scope.target,
|
||||
agentName: check.agentName,
|
||||
task: scanTask,
|
||||
onEvent: forward(PHASE_ANALYSIS),
|
||||
});
|
||||
findings = scanResult.text;
|
||||
recordCheckOutput(state, check.name, { findings });
|
||||
if (!scanResult.ok) {
|
||||
applyPhaseStatus(
|
||||
state,
|
||||
check.name,
|
||||
PHASE_ANALYSIS,
|
||||
"failed",
|
||||
scanResult.error,
|
||||
);
|
||||
markCheckStatus(state, check.name, "failed", scanResult.error);
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
return { status: "failed", error: scanResult.error, findings, state };
|
||||
}
|
||||
applyPhaseStatus(state, check.name, PHASE_ANALYSIS, "complete");
|
||||
await saveRunState(state);
|
||||
footerComplete(PHASE_ANALYSIS);
|
||||
|
||||
// --- Phase: fix (only with --fix) -----------------------------------
|
||||
if (scope.fix) {
|
||||
strip.setPhase(PHASE_FIX);
|
||||
footerEnter(PHASE_FIX);
|
||||
applyPhaseStatus(state, check.name, PHASE_FIX, "in_progress");
|
||||
await saveRunState(state);
|
||||
const fixTask = await check.buildFixTask(cwd, scope, findings);
|
||||
const fixResult = await runAgentTask({
|
||||
cwd: scope.target,
|
||||
agentName: check.fixAgentName ?? "fixer",
|
||||
task: fixTask,
|
||||
onEvent: forward(PHASE_FIX),
|
||||
});
|
||||
changes = fixResult.text;
|
||||
recordCheckOutput(state, check.name, { changes });
|
||||
if (!fixResult.ok) {
|
||||
applyPhaseStatus(
|
||||
state,
|
||||
check.name,
|
||||
PHASE_FIX,
|
||||
"failed",
|
||||
fixResult.error,
|
||||
);
|
||||
markCheckStatus(state, check.name, "failed", fixResult.error);
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
return {
|
||||
status: "failed",
|
||||
error: fixResult.error,
|
||||
findings,
|
||||
changes,
|
||||
state,
|
||||
};
|
||||
}
|
||||
applyPhaseStatus(state, check.name, PHASE_FIX, "complete");
|
||||
await saveRunState(state);
|
||||
footerComplete(PHASE_FIX);
|
||||
}
|
||||
|
||||
// --- Phase: verify ---------------------------------------------------
|
||||
strip.setPhase(PHASE_VERIFY);
|
||||
footerEnter(PHASE_VERIFY);
|
||||
applyPhaseStatus(state, check.name, PHASE_VERIFY, "in_progress");
|
||||
await saveRunState(state);
|
||||
phaseLine(PHASE_VERIFY, "checking artifacts…");
|
||||
// Verify is a lightweight self-check. A check may supply a dedicated
|
||||
// `verify` hook to confirm its artifacts were produced (e.g.
|
||||
// findings.md / changes.md exist). When absent, fall back to re-running
|
||||
// the gate — unchanged from the historical behaviour.
|
||||
const verifyResult = await Promise.resolve(
|
||||
check.verify ? check.verify(scope) : check.gate(cwd),
|
||||
);
|
||||
if (verifyResult) {
|
||||
applyPhaseStatus(state, check.name, PHASE_VERIFY, "failed", verifyResult);
|
||||
markCheckStatus(state, check.name, "failed", verifyResult);
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
return {
|
||||
status: "failed",
|
||||
error: verifyResult,
|
||||
findings,
|
||||
changes,
|
||||
state,
|
||||
};
|
||||
}
|
||||
phaseLine(PHASE_VERIFY, "✓ artifacts confirmed");
|
||||
applyPhaseStatus(state, check.name, PHASE_VERIFY, "complete");
|
||||
await saveRunState(state);
|
||||
footerComplete(PHASE_VERIFY);
|
||||
|
||||
// --- Phase: cleanup --------------------------------------------------
|
||||
strip.setPhase(PHASE_CLEANUP);
|
||||
footerEnter(PHASE_CLEANUP);
|
||||
applyPhaseStatus(state, check.name, PHASE_CLEANUP, "in_progress");
|
||||
await saveRunState(state);
|
||||
phaseLine(PHASE_CLEANUP, "removing transient artifacts…");
|
||||
await cleanupTransientArtifacts(cwd, check.name);
|
||||
phaseLine(PHASE_CLEANUP, "✓ done");
|
||||
applyPhaseStatus(state, check.name, PHASE_CLEANUP, "complete");
|
||||
footerComplete(PHASE_CLEANUP);
|
||||
markCheckStatus(state, check.name, "complete");
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
|
||||
return { status: "complete", findings, changes, state };
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
markCheckStatus(state, check.name, "failed", error);
|
||||
markRunStatus(state, reconcileRunStatus(state));
|
||||
await saveRunState(state);
|
||||
return { status: "failed", error, findings, changes, state };
|
||||
} finally {
|
||||
strip.done();
|
||||
footer.done();
|
||||
}
|
||||
}
|
||||
|
||||
/** Map a run-state `PhaseStatus` to a completion-log status. */
|
||||
function phaseLogStatus(status: string | undefined): PhaseLogStatus {
|
||||
switch (status) {
|
||||
case "complete":
|
||||
return "complete";
|
||||
case "failed":
|
||||
return "failed";
|
||||
case "skipped":
|
||||
return "skipped";
|
||||
default:
|
||||
return "running";
|
||||
}
|
||||
}
|
||||
|
||||
/** Glyph for a check's terminal status. */
|
||||
function statusGlyph(status: CheckRunOutcome["status"]): string {
|
||||
switch (status) {
|
||||
case "complete":
|
||||
return "✓";
|
||||
case "failed":
|
||||
return "✗";
|
||||
default:
|
||||
return "-";
|
||||
}
|
||||
}
|
||||
|
||||
/** Count non-empty lines in captured findings/changes text. */
|
||||
function lineCount(text: string | undefined): number {
|
||||
if (!text) return 0;
|
||||
return text.split(/\r?\n/).filter((l) => l.trim().length > 0).length;
|
||||
}
|
||||
|
||||
/** Format a duration in milliseconds as `1m 2s` / `5s` / `320ms`. */
|
||||
function formatDuration(ms: number): string {
|
||||
const s = Math.floor(ms / 1000);
|
||||
if (s < 1) return `${ms}ms`;
|
||||
if (s < 60) return `${s}s`;
|
||||
const m = Math.floor(s / 60);
|
||||
const rem = s % 60;
|
||||
return rem ? `${m}m ${rem}s` : `${m}m`;
|
||||
}
|
||||
|
||||
/** Build the expandable phase tree carried in the completion message. */
|
||||
function buildPhaseLog(
|
||||
state: RunState,
|
||||
checkName: string,
|
||||
findings?: string,
|
||||
changes?: string,
|
||||
): PhaseLogEntry[] {
|
||||
const phases = state.checks[checkName]?.phases ?? [];
|
||||
return phases.map((p) => {
|
||||
const entry: PhaseLogEntry = {
|
||||
id: p.id,
|
||||
label: PHASE_LABELS[p.id] ?? p.id,
|
||||
status: phaseLogStatus(p.status),
|
||||
};
|
||||
if (p.id === PHASE_ANALYSIS && findings) {
|
||||
entry.note = `findings: ${lineCount(findings)} lines`;
|
||||
} else if (p.id === PHASE_FIX && changes) {
|
||||
entry.note = `changes: ${lineCount(changes)} lines`;
|
||||
} else if (p.error) {
|
||||
entry.note = p.error;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Post a single ralpi-style completion message (header + phase tree) into the
|
||||
* chat via `sendChatMessage`. No-op when no callback is wired (print/json
|
||||
* modes). Mirrors ralpi's per-loop completion message.
|
||||
*/
|
||||
function postCheckCompletion(
|
||||
opts: RunCheckOptions,
|
||||
outcome: CheckRunOutcome,
|
||||
durationMs: number,
|
||||
): void {
|
||||
const send = opts.sendChatMessage;
|
||||
if (!send) return;
|
||||
const check = opts.check;
|
||||
const status = outcome.status;
|
||||
const glyph = statusGlyph(status);
|
||||
const fix = Boolean(
|
||||
(opts.scope ?? parseCheckArgs(opts.rawArgs ?? "", opts.cwd)).fix,
|
||||
);
|
||||
const fixTag = fix ? " --fix" : "";
|
||||
const header = `${glyph} pygienium ${check.label}${fixTag} · ${status} (${formatDuration(durationMs)})`;
|
||||
|
||||
const details: CheckCompletionDetails = {
|
||||
checkLabel: check.label,
|
||||
status,
|
||||
fix,
|
||||
durationMs,
|
||||
phases: buildPhaseLog(
|
||||
outcome.state,
|
||||
check.name,
|
||||
outcome.findings,
|
||||
outcome.changes,
|
||||
),
|
||||
error: outcome.error,
|
||||
};
|
||||
|
||||
send(header, { phase: "complete", completion: details });
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove transient per-check scratch artifacts (e.g. agent-extracted
|
||||
* manifests) written under `<cwd>/.pygienium/<check>-tmp-*`. Findings and
|
||||
* changes are kept in run-state, not these scratch files, so removing them is
|
||||
* safe.
|
||||
*/
|
||||
async function cleanupTransientArtifacts(
|
||||
cwd: string,
|
||||
checkName: string,
|
||||
): Promise<void> {
|
||||
const dir = stateDir(cwd);
|
||||
// Best-effort: remove any `*-tmp-<check>` entries created by agents.
|
||||
const { readdir } = await import("node:fs/promises");
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await readdir(dir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.includes(`-tmp-${checkName}`)) {
|
||||
await rm(join(dir, entry), { recursive: true, force: true }).catch(
|
||||
() => {},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
172
src/phases.ts
Normal file
172
src/phases.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* phases.ts — phase-log accumulator + stdout progress + completion-message
|
||||
* helpers.
|
||||
*
|
||||
* The live *detail* view of a check run is the tool-event stream piped into
|
||||
* the chat (see `pygienium-stream` in `index.ts`): each `tool_execution_start
|
||||
* /end` and assistant turn becomes its own chat message. This module no longer
|
||||
* owns a TUI widget — it only records phase transitions for the completion
|
||||
* message and forwards phase headers to stdout in print/JSON mode.
|
||||
*
|
||||
* The *overview* view is the footer widget (see `footer.ts`): a multi-line
|
||||
* `belowEditor` strip listing the full pipeline with the cursor and what's to
|
||||
* come. The two never overlap: the chat is the per-event detail, the footer
|
||||
* is the static overview.
|
||||
*
|
||||
* The strip accumulates a phase log (`getPhaseLog`) that the check-runner
|
||||
* turns into the expandable completion message rendered by
|
||||
* `registerMessageRenderer("pygienium-progress")` in `index.ts`.
|
||||
*
|
||||
* @module pygienium/phases
|
||||
*/
|
||||
|
||||
import type { ExtensionUIContext } from "@oh-my-pi/pi-coding-agent";
|
||||
|
||||
/** Callback to post a message into the chat history (see `index.ts` renderer). */
|
||||
export type SendChatMessage = (
|
||||
content: string,
|
||||
/** Extra data passed to the message renderer (toolCalls, completion, …). */
|
||||
meta?: {
|
||||
phase?: string;
|
||||
/** Tool calls captured during this agent execution (ralpi-style tree). */
|
||||
toolCalls?: never;
|
||||
[meta: string]: unknown;
|
||||
},
|
||||
) => void;
|
||||
|
||||
/** Phase display metadata for a check run's phases. */
|
||||
export const PHASE_LABELS: Record<string, string> = {
|
||||
recon: "Recon",
|
||||
analysis: "Scanning",
|
||||
fix: "Fixing",
|
||||
verify: "Verifying",
|
||||
cleanup: "Cleaning up",
|
||||
};
|
||||
|
||||
/** Status of a single phase as recorded in the completion log. */
|
||||
export type PhaseLogStatus = "running" | "complete" | "failed" | "skipped";
|
||||
|
||||
/** One phase entry carried into the completion message's `details.phases`. */
|
||||
export interface PhaseLogEntry {
|
||||
/** Phase id (e.g. "analysis"). */
|
||||
id: string;
|
||||
/** Human-readable label (e.g. "Scanning"). */
|
||||
label: string;
|
||||
/** Terminal/running status. */
|
||||
status: PhaseLogStatus;
|
||||
/** Optional note shown on the branch (e.g. "findings: 12 lines"). */
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export interface PhaseStripOptions {
|
||||
/** Check label shown alongside the phase, e.g. "comments". */
|
||||
checkLabel?: string;
|
||||
/** Whether dialog-capable UI is available. */
|
||||
hasUI?: boolean;
|
||||
/** UI context (unused for widget rendering since the stream owns the chat). */
|
||||
ui?: ExtensionUIContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* A handle that records phase transitions for the completion message and
|
||||
* forwards phase headers to stdout when no TUI is present. Created by
|
||||
* {@link createPhaseStrip}; the check-runner drives it.
|
||||
*/
|
||||
export interface PhaseStrip {
|
||||
/** Set the current phase (id or a pre-rendered header string). */
|
||||
setPhase(phaseId: string): void;
|
||||
/** Annotate the most recent phase (e.g. "findings: 12 lines"). */
|
||||
setPhaseNote(note: string): void;
|
||||
/** Append a plain-text progress line (forwarded to stdout in print mode). */
|
||||
log(line: string): void;
|
||||
/** Snapshot of phase transitions for the completion message. */
|
||||
getPhaseLog(): PhaseLogEntry[];
|
||||
/** Mark the strip terminal. Safe to call repeatedly. */
|
||||
done(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple write lock for stdout in print mode to prevent interleaved output
|
||||
* from parallel checks.
|
||||
*/
|
||||
let stdoutLock: Promise<void> = Promise.resolve();
|
||||
|
||||
/** Acquire the stdout write lock and execute the write function. */
|
||||
async function withStdoutLock(fn: () => void): Promise<void> {
|
||||
const prev = stdoutLock;
|
||||
stdoutLock = prev.then(() => {
|
||||
fn();
|
||||
return Promise.resolve();
|
||||
});
|
||||
return stdoutLock;
|
||||
}
|
||||
|
||||
/** Create a phase-strip UI adapter. */
|
||||
export function createPhaseStrip(opts: PhaseStripOptions): PhaseStrip {
|
||||
const checkLabel = opts.checkLabel;
|
||||
const hasUI = opts.hasUI ?? false;
|
||||
const phaseLog: PhaseLogEntry[] = [];
|
||||
let disposed = false;
|
||||
|
||||
let currentHeader = checkLabel
|
||||
? `pygienium ${checkLabel}: starting…`
|
||||
: "pygienium: starting…";
|
||||
|
||||
function phaseLabel(id: string): string {
|
||||
return PHASE_LABELS[id] ?? id;
|
||||
}
|
||||
|
||||
function writeStdout(text: string): void {
|
||||
if (!disposed && !hasUI) {
|
||||
process.stdout.write(`${text}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
setPhase(phaseId) {
|
||||
if (disposed) return;
|
||||
const label = phaseLabel(phaseId);
|
||||
currentHeader = checkLabel
|
||||
? `pygienium ${checkLabel}: ${label}`
|
||||
: `pygienium: ${phaseId}`;
|
||||
phaseLog.push({ id: phaseId, label, status: "running" });
|
||||
if (!hasUI) {
|
||||
withStdoutLock(() => writeStdout(currentHeader)).catch(() => {});
|
||||
}
|
||||
},
|
||||
setPhaseNote(note) {
|
||||
const last = phaseLog[phaseLog.length - 1];
|
||||
if (!last) return;
|
||||
last.note = note;
|
||||
},
|
||||
log(line) {
|
||||
if (disposed || hasUI) return;
|
||||
withStdoutLock(() => writeStdout(line)).catch(() => {});
|
||||
},
|
||||
getPhaseLog() {
|
||||
return phaseLog;
|
||||
},
|
||||
done() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Phase-log detail carried into a completion message's `details`. */
|
||||
export interface CheckCompletionDetails {
|
||||
checkLabel: string;
|
||||
status: "complete" | "failed" | "skipped";
|
||||
fix?: boolean;
|
||||
durationMs?: number;
|
||||
phases: PhaseLogEntry[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** Re-exported for index.ts renderer convenience. */
|
||||
export const PHASE_GLYPH: Record<PhaseLogStatus, string> = {
|
||||
running: "~",
|
||||
complete: "✓",
|
||||
failed: "✗",
|
||||
skipped: "-",
|
||||
};
|
||||
109
src/recon.ts
Normal file
109
src/recon.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* recon.ts — shared Q0 reconnaissance phase.
|
||||
*
|
||||
* Runs once per hygiene run (before any check's analysis phase) and writes a
|
||||
* project snapshot to `<cwd>/.pygienium/recon.json`. Each check can read this
|
||||
* snapshot so the recon work isn't repeated per check. The snapshot is minimal
|
||||
* and dependency-free (git state + source-file inventory) — real checks layer
|
||||
* their own analysis on top via sub-agents.
|
||||
*
|
||||
* @module pygienium/recon
|
||||
*/
|
||||
|
||||
import { exec } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import { join } from "node:path";
|
||||
import { stateDir, RECON_FILENAME } from "./run-state.js";
|
||||
import { SCOPE_EXTENSIONS } from "./checks/scope.js";
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
export interface ReconSnapshot {
|
||||
cwd: string;
|
||||
createdAt: number;
|
||||
gitBranch?: string;
|
||||
gitDirty?: boolean;
|
||||
/** Count of source files by extension. */
|
||||
fileCounts: Record<string, number>;
|
||||
totalSourceFiles: number;
|
||||
}
|
||||
|
||||
/** Run `git ls-files` when possible to get a clean source inventory. */
|
||||
async function listSourceFiles(cwd: string): Promise<string[]> {
|
||||
try {
|
||||
const { stdout } = await execAsync(
|
||||
`git -C ${JSON.stringify(cwd)} ls-files --cached --others --exclude-standard`,
|
||||
{ maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l.length > 0)
|
||||
.filter((l) => {
|
||||
const dot = l.lastIndexOf(".");
|
||||
if (dot === -1) return false;
|
||||
return SCOPE_EXTENSIONS.has(l.slice(dot).toLowerCase());
|
||||
});
|
||||
} catch {
|
||||
/* not a git repo or git unavailable — empty inventory */
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Run the shared recon phase for `cwd`, writing the snapshot if missing. */
|
||||
export async function runRecon(cwd: string): Promise<ReconSnapshot> {
|
||||
const dir = stateDir(cwd);
|
||||
const path = join(dir, RECON_FILENAME);
|
||||
|
||||
// Reuse a fresh-enough snapshot (< 5 min) when present.
|
||||
try {
|
||||
const raw = await readFile(path, "utf8");
|
||||
const existing = JSON.parse(raw) as ReconSnapshot;
|
||||
if (
|
||||
existing.createdAt &&
|
||||
Date.now() - existing.createdAt < 5 * 60 * 1000 &&
|
||||
existing.cwd === cwd
|
||||
) {
|
||||
return existing;
|
||||
}
|
||||
} catch {
|
||||
/* no existing snapshot */
|
||||
}
|
||||
|
||||
const files = await listSourceFiles(cwd);
|
||||
const fileCounts: Record<string, number> = {};
|
||||
for (const f of files) {
|
||||
const dot = f.lastIndexOf(".");
|
||||
const ext = dot === -1 ? "" : f.slice(dot).toLowerCase();
|
||||
fileCounts[ext] = (fileCounts[ext] ?? 0) + 1;
|
||||
}
|
||||
|
||||
let gitBranch: string | undefined;
|
||||
let gitDirty: boolean | undefined;
|
||||
try {
|
||||
const branchOut = await execAsync(
|
||||
`git -C ${JSON.stringify(cwd)} rev-parse --abbrev-ref HEAD`,
|
||||
);
|
||||
gitBranch = branchOut.stdout.trim() || undefined;
|
||||
const statusOut = await execAsync(
|
||||
`git -C ${JSON.stringify(cwd)} status --porcelain`,
|
||||
);
|
||||
gitDirty = statusOut.stdout.trim().length > 0;
|
||||
} catch {
|
||||
/* not a git repo */
|
||||
}
|
||||
|
||||
const snapshot: ReconSnapshot = {
|
||||
cwd,
|
||||
createdAt: Date.now(),
|
||||
gitBranch,
|
||||
gitDirty,
|
||||
fileCounts,
|
||||
totalSourceFiles: files.length,
|
||||
};
|
||||
|
||||
await mkdir(dir, { recursive: true });
|
||||
await writeFile(path, JSON.stringify(snapshot, null, 2) + "\n", "utf8");
|
||||
return snapshot;
|
||||
}
|
||||
326
src/run-state.ts
Normal file
326
src/run-state.ts
Normal file
@@ -0,0 +1,326 @@
|
||||
/**
|
||||
* run-state.ts — persistent hygiene-run state.
|
||||
*
|
||||
* Tracks per-check phase progress so `/pygienium-status`, `/pygienium-resume`,
|
||||
* and `/pygienium-export` work, and so `/pygienium-all` is resumable. State is
|
||||
* a single JSON file at `<cwd>/.pygienium/run-state.json` so it is trivial to
|
||||
* inspect and is naturally session-scoped to the target directory.
|
||||
*
|
||||
* @module pygienium/run-state
|
||||
*/
|
||||
|
||||
import { appendFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const RUN_STATE_DIRNAME = ".pygienium";
|
||||
export const RUN_STATE_FILENAME = "run-state.json";
|
||||
export const RECON_FILENAME = "recon.json";
|
||||
|
||||
/** Resolve the pygienium state directory for a given cwd. */
|
||||
export function stateDir(cwd: string): string {
|
||||
return join(cwd, RUN_STATE_DIRNAME);
|
||||
}
|
||||
|
||||
/** Resolve the run-state file path for a given cwd. */
|
||||
export function runStatePath(cwd: string): string {
|
||||
return join(stateDir(cwd), RUN_STATE_FILENAME);
|
||||
}
|
||||
|
||||
export type PhaseStatus =
|
||||
| "pending"
|
||||
| "in_progress"
|
||||
| "complete"
|
||||
| "failed"
|
||||
| "skipped";
|
||||
|
||||
export type CheckStatus = PhaseStatus;
|
||||
export type RunStatus = "in_progress" | "complete" | "failed" | "partial";
|
||||
|
||||
export interface PhaseEntry {
|
||||
id: string;
|
||||
status: PhaseStatus;
|
||||
startedAt?: number;
|
||||
finishedAt?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface CheckRun {
|
||||
name: string;
|
||||
label: string;
|
||||
status: CheckStatus;
|
||||
fix: boolean;
|
||||
phases: PhaseEntry[];
|
||||
findings?: string;
|
||||
changes?: string;
|
||||
startedAt?: number;
|
||||
finishedAt?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ReconState {
|
||||
complete: boolean;
|
||||
path: string;
|
||||
finishedAt?: number;
|
||||
}
|
||||
|
||||
export interface RunState {
|
||||
version: 1;
|
||||
cwd: string;
|
||||
startedAt: number;
|
||||
updatedAt: number;
|
||||
status: RunStatus;
|
||||
recon: ReconState;
|
||||
checks: Record<string, CheckRun>;
|
||||
}
|
||||
|
||||
/** Phase ids shared by every check run, in execution order. */
|
||||
export const PHASE_RECON = "recon";
|
||||
export const PHASE_ANALYSIS = "analysis";
|
||||
export const PHASE_FIX = "fix";
|
||||
export const PHASE_VERIFY = "verify";
|
||||
export const PHASE_CLEANUP = "cleanup";
|
||||
|
||||
function freshPhase(id: string): PhaseEntry {
|
||||
return { id, status: "pending" };
|
||||
}
|
||||
|
||||
/** Create the phase skeleton for a single check (analysis always runs; fix only when requested). */
|
||||
export function phasesForCheck(fix: boolean): PhaseEntry[] {
|
||||
const phases = [freshPhase(PHASE_RECON), freshPhase(PHASE_ANALYSIS)];
|
||||
if (fix) phases.push(freshPhase(PHASE_FIX));
|
||||
phases.push(freshPhase(PHASE_VERIFY), freshPhase(PHASE_CLEANUP));
|
||||
return phases;
|
||||
}
|
||||
|
||||
/** Initialize a fresh run state for `checkNames` (labels default to the name). */
|
||||
export function initRunState(
|
||||
cwd: string,
|
||||
checks: Array<{ name: string; label: string; fix?: boolean }>,
|
||||
): RunState {
|
||||
const now = Date.now();
|
||||
const state: RunState = {
|
||||
version: 1,
|
||||
cwd,
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
status: "in_progress",
|
||||
recon: { complete: false, path: join(stateDir(cwd), RECON_FILENAME) },
|
||||
checks: {},
|
||||
};
|
||||
for (const c of checks) {
|
||||
state.checks[c.name] = {
|
||||
name: c.name,
|
||||
label: c.label,
|
||||
status: "pending",
|
||||
fix: c.fix ?? false,
|
||||
phases: phasesForCheck(c.fix ?? false),
|
||||
startedAt: undefined,
|
||||
};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Load run state for `cwd`. Returns `undefined` when none exists. */
|
||||
export async function loadRunState(cwd: string): Promise<RunState | undefined> {
|
||||
const path = runStatePath(cwd);
|
||||
try {
|
||||
const raw = await readFile(path, "utf8");
|
||||
return JSON.parse(raw) as RunState;
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist run state, creating the state directory as needed. */
|
||||
export async function saveRunState(state: RunState): Promise<void> {
|
||||
const dir = stateDir(state.cwd);
|
||||
await mkdir(dir, { recursive: true });
|
||||
state.updatedAt = Date.now();
|
||||
await writeFile(
|
||||
runStatePath(state.cwd),
|
||||
JSON.stringify(state, null, 2) + "\n",
|
||||
"utf8",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Memo of cwds whose `.gitignore` was already ensured this process, so the
|
||||
* check runs at most once per target per session.
|
||||
*/
|
||||
const gitIgnoreMemo = new Set<string>();
|
||||
|
||||
/**
|
||||
* Make sure `<cwd>/.gitignore` excludes `.pygienium/` (run-state + artifacts)
|
||||
* so a run never stages its own output into the scanned repo's git index.
|
||||
* Best-effort and idempotent: no-op outside a git work tree or when the entry
|
||||
* already exists. Returns true when it appended the entry (or created the file).
|
||||
*/
|
||||
export async function ensureRunStateIgnored(cwd: string): Promise<boolean> {
|
||||
if (gitIgnoreMemo.has(cwd)) return false;
|
||||
gitIgnoreMemo.add(cwd);
|
||||
try {
|
||||
// Only act inside a git work tree (works for worktrees too: .git is a file).
|
||||
await stat(join(cwd, ".git"));
|
||||
const ignorePath = join(cwd, ".gitignore");
|
||||
const marker = ".pygienium/";
|
||||
let content: string;
|
||||
try {
|
||||
content = await readFile(ignorePath, "utf8");
|
||||
} catch {
|
||||
await writeFile(ignorePath, `${marker}\n`, "utf8");
|
||||
return true;
|
||||
}
|
||||
if (content.split(/\r?\n/).some((l) => l.trim() === marker)) return false;
|
||||
const prefix = content.endsWith("\n") ? "" : "\n";
|
||||
await appendFile(
|
||||
ignorePath,
|
||||
`${prefix}# pygienium run-state and check artifacts\n${marker}\n`,
|
||||
"utf8",
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false; // not a git work tree, or a best-effort write failed
|
||||
}
|
||||
}
|
||||
|
||||
/** Mark a phase's status (and optionally an error message). */
|
||||
export function applyPhaseStatus(
|
||||
state: RunState,
|
||||
checkName: string,
|
||||
phaseId: string,
|
||||
status: PhaseStatus,
|
||||
error?: string,
|
||||
): void {
|
||||
const check = state.checks[checkName];
|
||||
if (!check) return;
|
||||
const phase = check.phases.find((p) => p.id === phaseId);
|
||||
if (!phase) return;
|
||||
phase.status = status;
|
||||
const now = Date.now();
|
||||
if (status === "in_progress") {
|
||||
phase.startedAt = now;
|
||||
if (check.startedAt == null) check.startedAt = now;
|
||||
check.status = "in_progress";
|
||||
} else if (
|
||||
status === "complete" ||
|
||||
status === "failed" ||
|
||||
status === "skipped"
|
||||
) {
|
||||
phase.finishedAt = now;
|
||||
// Always set (or clear) the error: a phase that previously failed
|
||||
// and then succeeds on retry must not carry a stale error forward.
|
||||
phase.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile a check's overall status from its phases and, when terminal,
|
||||
* stamp `finishedAt`. Used after the cleanup phase resolves.
|
||||
*/
|
||||
export function markCheckStatus(
|
||||
state: RunState,
|
||||
checkName: string,
|
||||
status: CheckStatus,
|
||||
error?: string,
|
||||
): void {
|
||||
const check = state.checks[checkName];
|
||||
if (!check) return;
|
||||
check.status = status;
|
||||
// Always set (or clear) the error: a check that previously failed
|
||||
// and then succeeds on retry must not carry a stale error forward.
|
||||
check.error = error;
|
||||
if (status === "complete" || status === "failed" || status === "skipped") {
|
||||
check.finishedAt = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
/** Record findings/changes text on a check. */
|
||||
export function recordCheckOutput(
|
||||
state: RunState,
|
||||
checkName: string,
|
||||
out: { findings?: string; changes?: string },
|
||||
): void {
|
||||
const check = state.checks[checkName];
|
||||
if (!check) return;
|
||||
if (out.findings !== undefined) check.findings = out.findings;
|
||||
if (out.changes !== undefined) check.changes = out.changes;
|
||||
}
|
||||
|
||||
/** Mark the overall run status. */
|
||||
export function markRunStatus(state: RunState, status: RunStatus): void {
|
||||
state.status = status;
|
||||
state.updatedAt = Date.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a check is terminal (shouldn't be re-dispatched unless a
|
||||
* fresh run is forced). `pending`/`in_progress`/`failed` are resumable.
|
||||
*/
|
||||
export function isCheckTerminal(check: CheckRun): boolean {
|
||||
return check.status === "complete" || check.status === "skipped";
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-dispatch predicate for `/pygienium-resume`: a check runs on resume when it
|
||||
* is not terminal, OR when `--fresh` forced a re-dispatch of everything.
|
||||
*/
|
||||
export function shouldRunOnResume(check: CheckRun, fresh: boolean): boolean {
|
||||
return fresh || !isCheckTerminal(check);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset a single check entry back to `pending` with fresh phases. Used by
|
||||
* `/pygienium-resume --fresh` so that previously-complete checks are
|
||||
* re-dispatched from scratch. Preserves `label`/`fix` from the existing entry
|
||||
* unless overridden.
|
||||
*/
|
||||
export function resetCheckEntry(
|
||||
state: RunState,
|
||||
name: string,
|
||||
fixOverride?: boolean,
|
||||
): void {
|
||||
const existing = state.checks[name];
|
||||
const fix = fixOverride ?? existing?.fix ?? false;
|
||||
state.checks[name] = {
|
||||
name,
|
||||
label: existing?.label ?? name,
|
||||
status: "pending",
|
||||
fix,
|
||||
phases: phasesForCheck(fix),
|
||||
startedAt: undefined,
|
||||
finishedAt: undefined,
|
||||
findings: undefined,
|
||||
changes: undefined,
|
||||
error: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the next check to run when resuming: the first `in_progress` check,
|
||||
* else the first pending/failed check. Returns `undefined` when nothing remains.
|
||||
*/
|
||||
/**
|
||||
* Recompute the run-level status from check statuses. A run is `complete` only
|
||||
* when every check is terminal-complete; `failed` when every check failed;
|
||||
* `partial` when some checks failed/skipped but others succeeded.
|
||||
*/
|
||||
export function reconcileRunStatus(state: RunState): RunStatus {
|
||||
const checks = Object.values(state.checks);
|
||||
if (checks.length === 0) return "in_progress";
|
||||
let anyFailed = false;
|
||||
let anySkipped = false;
|
||||
for (const c of checks) {
|
||||
if (c.status === "pending" || c.status === "in_progress")
|
||||
return "in_progress";
|
||||
if (c.status === "failed") anyFailed = true;
|
||||
if (c.status === "skipped") anySkipped = true;
|
||||
}
|
||||
if (anyFailed) {
|
||||
// Every check failed (none succeeded or were skipped) → the run failed;
|
||||
// a mix of failures and successes is only partially complete.
|
||||
return checks.every((c) => c.status === "failed") ? "failed" : "partial";
|
||||
}
|
||||
if (anySkipped) return "partial";
|
||||
return "complete";
|
||||
}
|
||||
108
src/status.ts
Normal file
108
src/status.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* status.ts — readable run-state formatter.
|
||||
*
|
||||
* {@link formatRunStatus} turns a `RunState` into a plain line list covering
|
||||
* the run-level summary and one block per registered check: overall status, the
|
||||
* per-phase breakdown, captured findings/changes artifacts, and any errors.
|
||||
* It is a *pure* function of state — no disk I/O — so it is trivially
|
||||
* unit-testable and deterministic; the in-memory run-state is the single source
|
||||
* of truth for progress (the check-runner records findings/changes text on it).
|
||||
*
|
||||
* `formatRunStatus` is the single helper the `/pygienium-status` command uses;
|
||||
* keeping it here (out of `commands.ts`) lets `commands.ts` stay a thin binder.
|
||||
*
|
||||
* @module pygienium/status
|
||||
*/
|
||||
|
||||
import type { CheckRun, RunState } from "./run-state.js";
|
||||
|
||||
const PHASE_ORDER = ["recon", "analysis", "fix", "verify", "cleanup"] as const;
|
||||
|
||||
function toISO(ms: number | undefined): string {
|
||||
return ms == null ? "—" : new Date(ms).toISOString();
|
||||
}
|
||||
|
||||
function short(status: string): string {
|
||||
return status[0]?.toUpperCase() ?? "?";
|
||||
}
|
||||
|
||||
/** Count non-empty lines in captured findings/changes text. */
|
||||
function lineCount(text: string | undefined): number {
|
||||
if (!text) return 0;
|
||||
const count = text.split(/\r?\n/).filter((l) => l.trim().length > 0).length;
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a single check block (without a trailing separator) — exposed so tests
|
||||
* and the status command share one rendering path.
|
||||
*/
|
||||
export function formatCheckBlock(check: CheckRun, indent = " "): string[] {
|
||||
const lines: string[] = [];
|
||||
const flag = check.fix ? " (--fix)" : "";
|
||||
lines.push(`${indent}${check.name} — ${check.status}${flag}`);
|
||||
|
||||
const phaseSummary = check.phases
|
||||
.map((p) => `${p.id}:${p.status.startsWith("in_progress") ? "…" : short(p.status)}`)
|
||||
.join(" ");
|
||||
if (phaseSummary) lines.push(`${indent} phases: ${phaseSummary}`);
|
||||
|
||||
const findingsLines = lineCount(check.findings);
|
||||
if (findingsLines > 0) {
|
||||
lines.push(`${indent} findings: ${findingsLines} line(s)`);
|
||||
}
|
||||
const changesLines = lineCount(check.changes);
|
||||
if (changesLines > 0) {
|
||||
lines.push(`${indent} changes: ${changesLines} line(s)`);
|
||||
}
|
||||
|
||||
if (check.error) {
|
||||
lines.push(`${indent} error: ${check.error}`);
|
||||
}
|
||||
for (const phase of check.phases) {
|
||||
if (phase.status === "failed" && phase.error && phase.error !== check.error) {
|
||||
lines.push(`${indent} ${phase.id}: ${phase.error}`);
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `/pygienium-status` line list for a run state. Pure: no disk reads.
|
||||
* Layout:
|
||||
*
|
||||
* pygienium run — <status>
|
||||
* started: <iso>
|
||||
* updated: <iso>
|
||||
* cwd: <cwd>
|
||||
* recon: complete|pending
|
||||
*
|
||||
* checks (N):
|
||||
* <name> — <status>
|
||||
* phases: recon:✓ analysis:✓ [fix:✓] verify:✓ cleanup:✓
|
||||
* findings: <N> line(s)
|
||||
* changes: <N> line(s)
|
||||
* error: <msg>
|
||||
*/
|
||||
export function formatRunStatus(state: RunState): string[] {
|
||||
const checks = Object.values(state.checks);
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`pygienium run — ${state.status}`);
|
||||
lines.push(` started: ${toISO(state.startedAt)}`);
|
||||
lines.push(` updated: ${toISO(state.updatedAt)}`);
|
||||
lines.push(` cwd: ${state.cwd}`);
|
||||
const reconLabel = state.recon.complete ? "complete" : "pending";
|
||||
const reconTime = state.recon.finishedAt ? ` (${toISO(state.recon.finishedAt)})` : "";
|
||||
lines.push(` recon: ${reconLabel}${reconTime}`);
|
||||
lines.push("");
|
||||
|
||||
lines.push(` checks (${checks.length}):`);
|
||||
if (checks.length === 0) {
|
||||
lines.push(" (none registered in this run state)");
|
||||
}
|
||||
for (const check of checks) {
|
||||
lines.push(...formatCheckBlock(check));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
Reference in New Issue
Block a user